Java 类org.apache.logging.log4j.util.Strings 实例源码

项目:es-log4j2-appender    文件:ElasticBulkSender.java   
public ElasticBulkSender(String user, String password, HttpHost... hosts) {
    this.user = user;
    this.password = password;
    this.hosts = hosts;
    this.restClient = RestClient.builder(hosts)
            .setHttpClientConfigCallback(new RestClientBuilder.HttpClientConfigCallback() {
                @Override
                public HttpAsyncClientBuilder customizeHttpClient(HttpAsyncClientBuilder httpClientBuilder) {
                    if (!Strings.isBlank(user)) {
                        CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
                        credentialsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(user, password));
                        return httpClientBuilder.setDefaultCredentialsProvider(credentialsProvider);
                    } else {
                        return httpClientBuilder;
                    }
                }
            })
            .build();
}
项目:elasticsearch-indexing-proxy    文件:IndexingProxyService.java   
public void startRequestSender(final String index, final long filePosition, final ActionListener<Map<String, Object>> listener) {
    if (!senderNodes.isEmpty() && !senderNodes.contains(nodeName())) {
        listener.onFailure(new ElasticsearchException(nodeName() + " is not a Sender node."));
        return;
    }

    if (logger.isDebugEnabled()) {
        logger.debug("Starting RequestSender(" + index + ")");
    }
    client.prepareGet(IndexingProxyPlugin.INDEX_NAME, IndexingProxyPlugin.TYPE_NAME, index).setRefresh(true).execute(wrap(res -> {
        if (res.isExists()) {
            final Map<String, Object> source = res.getSourceAsMap();
            final String workingNodeName = (String) source.get(IndexingProxyPlugin.NODE_NAME);
            if (!Strings.isBlank(workingNodeName) && !nodeName().equals(workingNodeName)) {
                listener.onFailure(new ElasticsearchException("RequestSender is working in " + workingNodeName));
            } else {
                final Number pos = (Number) source.get(IndexingProxyPlugin.FILE_POSITION);
                final long value = pos == null ? 1 : pos.longValue();
                launchRequestSender(index, filePosition > 0 ? filePosition : value, res.getVersion(), listener);
            }
        } else {
            launchRequestSender(index, filePosition > 0 ? filePosition : 1, 0, listener);
        }
    }, listener::onFailure));
}
项目:flow-platform    文件:PluginServiceImpl.java   
@Override
public void exec(Plugin plugin) {
    LOGGER.traceMarker("PushProcessor", "Push tags to local");

    if (!Strings.isBlank(plugin.getPluginDetail().getImage()) && !Strings
        .isBlank(plugin.getPluginDetail().getBuild())) {
        return;
    }

    try {
        // put from cache to local git workspace
        Path cachePath = gitCachePath(plugin);
        String latestGitTag = plugin.getTag();
        JGitUtil.push(cachePath, LOCAL_REMOTE, latestGitTag);
        // set currentTag latestTag
        plugin.setCurrentTag(latestGitTag);
        updatePluginStatus(plugin, INSTALLED);
    } catch (GitException e) {
        LOGGER.error("Git Push", e);
        throw new PluginException("Git Push", e);
    }
}
项目:bot4j    文件:ImageRuleImpl.java   
@Override
public void apply(final SendMessage sendMessage) {
    final ImageSendPayload imageSendPayload = sendMessage.getPayloadWithType(ImageSendPayload.class);

    final String title = imageSendPayload.getTitle();
    final String imageUrl = imageSendPayload.getImageUrl();
    final String recipient = sendMessage.getRecipient().getId();

    final SendPhoto sendPhotoTelegram = new SendPhoto(recipient, imageUrl);

    if (!Strings.isBlank(title)) {
        sendPhotoTelegram.caption(title);
    }

    LOG.info("sending image {} to recipient {}", sendPhotoTelegram, recipient);
    final TelegramBot client = provideTelegramBot(sendMessage);
    client.execute(sendPhotoTelegram);
}
项目:bot4j    文件:ListRuleImpl.java   
protected void sendButtonElement(final SendMessage sendMessage, final String recipient,
        final ListSendElement listSendElement) {
    final AbstractSendButton abstractButton = listSendElement.getButton();
    final List<InlineKeyboardButton> buttonList = new ArrayList<InlineKeyboardButton>();

    buttonList.add(telegramSendInlineKeyboardFactory.createInlineKeyboard(abstractButton));
    InlineKeyboardButton[] inlineKeyboardButtons = new InlineKeyboardButton[buttonList.size()];
    inlineKeyboardButtons = buttonList.toArray(inlineKeyboardButtons);
    final InlineKeyboardMarkup inlineKeyboardMarkup = new InlineKeyboardMarkup(inlineKeyboardButtons);

    String title = listSendElement.getTitle();

    if (Strings.isBlank(title)) {
        title = "undefined title of buttonSendPayload";
    }

    final String boldTitle = "*" + title + "*";
    final com.pengrad.telegrambot.request.SendMessage sendMessageTelegram = new com.pengrad.telegrambot.request.SendMessage(
            recipient, boldTitle).replyMarkup(inlineKeyboardMarkup).parseMode(ParseMode.Markdown);
    super.execute(sendMessage, sendMessageTelegram, recipient);
}
项目:bot4j    文件:VideoRuleImpl.java   
@Override
public void apply(final SendMessage sendMessage) {
    final VideoSendPayload videoSendPayload = sendMessage.getPayloadWithType(VideoSendPayload.class);

    final String title = videoSendPayload.getTitle();
    final String videoUrl = videoSendPayload.getVideoUrl();
    final String recipient = sendMessage.getRecipient().getId();

    final SendVideo sendVideoTelegram = new SendVideo(recipient, videoUrl);

    if (!Strings.isBlank(title)) {
        sendVideoTelegram.caption(title);
    }

    LOG.info("sending video {} to recipient {}", sendVideoTelegram, recipient);
    final TelegramBot client = provideTelegramBot(sendMessage);
    client.execute(sendVideoTelegram);
}
项目:bot4j    文件:ButtonsRuleImpl.java   
@Override
public void apply(final SendMessage sendMessage) {
    final ButtonsSendPayload buttonsSendPayload = sendMessage.getPayloadWithType(ButtonsSendPayload.class);
    final List<InlineKeyboardButton> buttonList = new ArrayList<InlineKeyboardButton>();

    for (final AbstractSendButton button : buttonsSendPayload.getButtons()) {
        buttonList.add(telegramSendInlineKeyboardFactory.createInlineKeyboard(button));
    }

    InlineKeyboardButton[] inlineKeyboardButtons = new InlineKeyboardButton[buttonList.size()];
    inlineKeyboardButtons = buttonList.toArray(inlineKeyboardButtons);
    final InlineKeyboardMarkup inlineKeyboardMarkup = new InlineKeyboardMarkup(inlineKeyboardButtons);

    String title = buttonsSendPayload.getTitle();

    if (Strings.isBlank(title)) {
        title = "undefined title of buttonSendPayload";
    }

    final String boldTitle = "*" + title + "*";
    final String recipient = sendMessage.getRecipient().getId();

    final com.pengrad.telegrambot.request.SendMessage sendMessageTelegram = new com.pengrad.telegrambot.request.SendMessage(
            recipient, boldTitle).replyMarkup(inlineKeyboardMarkup).parseMode(ParseMode.Markdown);
    super.execute(sendMessage, sendMessageTelegram, recipient);
}
项目:hmftools    文件:CenterModel.java   
private static void checkAddresseeFields(@NotNull final String sample, @NotNull final CenterData center) {
    final List<String> missingFields = Lists.newArrayList();
    if (getPI(sample, center).isEmpty()) {
        missingFields.add("PI");
    }
    if (center.addressName().isEmpty()) {
        missingFields.add("name");
    }
    if (center.addressZip().isEmpty()) {
        missingFields.add("zip");
    }
    if (center.addressCity().isEmpty()) {
        missingFields.add("city");
    }
    if (!missingFields.isEmpty()) {
        LOGGER.warn("Some address fields (" + Strings.join(missingFields, ',') + ") are missing.");
    }
}
项目:hmftools    文件:VariantAnnotationTest.java   
@Test
public void canGenerateConsequenceString() {
    final VariantAnnotation noConsequences = VariantAnnotationTest.createVariantAnnotationBuilder().build();
    assertEquals(Strings.EMPTY, noConsequences.consequenceString());

    final VariantAnnotation oneConsequence = createVariantAnnotationBuilder(VariantConsequence.MISSENSE_VARIANT).build();
    assertEquals(VariantConsequence.MISSENSE_VARIANT.readableSequenceOntologyTerm(), oneConsequence.consequenceString());

    final VariantAnnotation twoConsequences =
            createVariantAnnotationBuilder(VariantConsequence.MISSENSE_VARIANT, VariantConsequence.INFRAME_DELETION).build();
    assertTrue(twoConsequences.consequenceString().contains(VariantConsequence.MISSENSE_VARIANT.readableSequenceOntologyTerm()));
    assertTrue(twoConsequences.consequenceString().contains(VariantConsequence.INFRAME_DELETION.readableSequenceOntologyTerm()));

    final VariantAnnotation twoConsequencesIgnoreOne =
            createVariantAnnotationBuilder(VariantConsequence.MISSENSE_VARIANT, VariantConsequence.OTHER).build();
    assertEquals(VariantConsequence.MISSENSE_VARIANT.readableSequenceOntologyTerm(), twoConsequencesIgnoreOne.consequenceString());
}
项目:hmftools    文件:VariantAnnotationTest.java   
@NotNull
public static ImmutableVariantAnnotation.Builder createVariantAnnotationBuilder(@NotNull VariantConsequence... consequences) {
    return ImmutableVariantAnnotation.builder()
            .allele(Strings.EMPTY)
            .severity(Strings.EMPTY)
            .gene(Strings.EMPTY)
            .geneID(Strings.EMPTY)
            .featureType(Strings.EMPTY)
            .featureID(Strings.EMPTY)
            .transcriptBioType(Strings.EMPTY)
            .rank(Strings.EMPTY)
            .hgvsCoding(Strings.EMPTY)
            .hgvsProtein(Strings.EMPTY)
            .cDNAPosAndLength(Strings.EMPTY)
            .cdsPosAndLength(Strings.EMPTY)
            .aaPosAndLength(Strings.EMPTY)
            .distance(Strings.EMPTY)
            .addition(Strings.EMPTY)
            .consequences(Lists.newArrayList(consequences));
}
项目:blockchain-benchmarking    文件:JSONRPCHelper.java   
public static String postToSendTransactionEthereum(String url, String sender, String receiver, String amount)
        throws IOException {

    try {
        String params = String.format("{\"jsonrpc\":\"2.0\"," +
                "\"method\":\"eth_sendTransaction\",\"params\":[{\"from\":\"%s\",\"to\":\"%s\"," +
                        "\"value\":\"%s\"}],\"id\":%s}",
                sender, receiver, amount, id);
        String responseString = httpHelper.request(url, params, RequestType.POST);
        ObjectMapper mapper = new ObjectMapper();
        JsonNode responseJson = mapper.readTree(responseString);
        return responseJson.get("result").textValue();
    } catch (Exception e) {
        log.error("Cannot run post method for sending transactions in Ethereum", e);
    }

    return Strings.EMPTY;
}
项目:blockchain-benchmarking    文件:JSONRPCHelper.java   
public static String postToSendMessageEthereum(String url, String sender, String receiver, String message, String amount)
        throws IOException {
    try {
        String params = String.format("{\"jsonrpc\":\"2.0\"," +
                        "\"method\":\"eth_sendTransaction\",\"params\":[{\"from\":\"%s\",\"to\":\"%s\"," +
                        "\"value\":\"%s\", \"data\":\"%s\"}],\"id\":%s}",
                sender, receiver, amount, "0x" + Hex.encodeHexString(message.getBytes()), id);

        String responseString = httpHelper.request(url, params, RequestType.POST);
        ObjectMapper mapper = new ObjectMapper();
        JsonNode responseJson = mapper.readTree(responseString);
        return responseJson.get("result").textValue();
    } catch (Exception e) {
        log.error("Cannot run post method for sending transactions in Ethereum", e);
    }

    return Strings.EMPTY;
}
项目:slack-appender    文件:SlackAppender.java   
public static Client findClientImpl(final String httpClientImpl) {
       Client client = null;
if (Strings.isEmpty(httpClientImpl)) {
    for (String s : Arrays.asList("be.olsson.slackappender.client.OkHttp2Client", "be.olsson.slackappender.client.OkHttp3Client")) {
    client = getClientImpl(s);
    if (client != null) {
        break;
    }
    }
    if (client == null) {
    throw new IllegalArgumentException("Didn't find any working " + Client.class.getName() + " implementation called " + httpClientImpl);
    }
} else {
    client = getClientImpl(httpClientImpl);
    if (client == null) {
    throw new IllegalArgumentException("Didn't find any working " + Client.class.getName() + " implementation called " + httpClientImpl);
    }
}
return client;
   }
项目:LoboEvolution    文件:BaseHistory.java   
/**
 * Gets the recent host entries.
 *
 * @param maxNumItems
 *            the max num items
 * @return the recent host entries
 */
public Collection<HostEntry> getRecentHostEntries(int maxNumItems) {
    synchronized (this) {
        Collection<HostEntry> items = new LinkedList<HostEntry>();
        Iterator<TimedEntry> i = this.historyTimedSet.iterator();
        Set<String> hosts = new HashSet<String>();
        while (i.hasNext()) {
            TimedEntry entry = i.next();
            String host = entry.url.getHost();
            if (Strings.isBlank(host) && !hosts.contains(host)) {

                hosts.add(host);
                if (hosts.size() >= maxNumItems) {
                    break;
                }

                items.add(new HostEntry(host, entry.timestamp));
            }
        }
        return items;
    }
}
项目:vb6parser    文件:VbParseTestRunnerImpl.java   
protected void doCompareParseTree(final File treeFile, final StartRuleContext startRule,
        final VisualBasic6Parser parser) throws IOException {

    final String treeFileData = FileUtils.readFileToString(treeFile);

    if (!Strings.isBlank(treeFileData)) {
        LOG.info("Comparing parse tree with file {}.", treeFile.getName());

        final String inputFileTree = Trees.toStringTree(startRule, parser);
        final String cleanedInputFileTree = io.proleap.vb6.util.StringUtils.cleanFileTree(inputFileTree);
        final String cleanedTreeFileData = io.proleap.vb6.util.StringUtils.cleanFileTree(treeFileData);

        assertEquals(cleanedTreeFileData, cleanedInputFileTree);
    } else {
        LOG.info("Ignoring empty parse tree file {}.", treeFile.getName());
    }
}
项目:logging-log4j2    文件:StructuredDataId.java   
/**
 * A Constructor that helps conformance to RFC 5424.
 *
 * @param name The name portion of the id.
 * @param enterpriseNumber The enterprise number.
 * @param required The list of keys that are required for this id.
 * @param optional The list of keys that are optional for this id.
 * @param maxLength The maximum length of the StructuredData Id key.
 * @since 2.9
 */
public StructuredDataId(final String name, final int enterpriseNumber, final String[] required,
        final String[] optional, final int maxLength) {
    if (name == null) {
        throw new IllegalArgumentException("No structured id name was supplied");
    }
    if (name.contains(AT_SIGN)) {
        throw new IllegalArgumentException("Structured id name cannot contain an " + Strings.quote(AT_SIGN));
    }
    if (enterpriseNumber <= 0) {
        throw new IllegalArgumentException("No enterprise number was supplied");
    }
    this.name = name;
    this.enterpriseNumber = enterpriseNumber;
    final String id = name + AT_SIGN + enterpriseNumber;
    if (maxLength > 0 && id.length() > maxLength) {
        throw new IllegalArgumentException("Length of id exceeds maximum of " + maxLength + " characters: " + id);
    }
    this.required = required;
    this.optional = optional;
}
项目:logging-log4j2    文件:HostNameTest.java   
@Test
public void testHostname() {
    final org.apache.logging.log4j.Logger testLogger = context.getLogger("org.apache.logging.log4j.hosttest");
    testLogger.debug("Hello, {}", "World");
    final List<String> msgs = host.getMessages();
    assertThat(msgs, hasSize(1));
    String expected = NetUtils.getLocalHostname() + Strings.LINE_SEPARATOR;
    assertThat(msgs.get(0), endsWith(expected));
    assertNotNull("No Host FileAppender file name", hostFile.getFileName());
    expected = "target/" + NetUtils.getLocalHostname() + ".log";
    String name = hostFile.getFileName();
    assertEquals("Incorrect HostFile FileAppender file name - expected " + expected + " actual - " + name, name,
        expected);
    name = hostFile.getFilePattern();
    assertNotNull("No file pattern", name);
    expected = "target/" + NetUtils.getLocalHostname() + "-%d{MM-dd-yyyy}-%i.log";
    assertEquals("Incorrect HostFile FileAppender file pattern - expected " + expected + " actual - " + name, name,
        expected);

}
项目:logging-log4j2    文件:AbstractLogger.java   
protected EntryMessage entryMsg(final String format, final Object... params) {
    final int count = params == null ? 0 : params.length;
    if (count == 0) {
        if (Strings.isEmpty(format)) {
            return flowMessageFactory.newEntryMessage(null);
        }
        return flowMessageFactory.newEntryMessage(new SimpleMessage(format));
    }
    if (format != null) {
        return flowMessageFactory.newEntryMessage(new ParameterizedMessage(format, params));
    }
    final StringBuilder sb = new StringBuilder();
    sb.append("params(");
    for (int i = 0; i < count; i++) {
        if (i > 0) {
            sb.append(", ");
        }
        final Object parm = params[i];
        sb.append(parm instanceof Message ? ((Message) parm).getFormattedMessage() : String.valueOf(parm));
    }
    sb.append(')');
    return flowMessageFactory.newEntryMessage(new SimpleMessage(sb));
}
项目:logging-log4j2    文件:DefaultThreadContextStack.java   
@Override
public String pop() {
    if (!useStack) {
        return Strings.EMPTY;
    }
    final MutableThreadContextStack values = STACK.get();
    if (values == null || values.size() == 0) {
        // Like version 1.2
        return Strings.EMPTY;
    }
    final MutableThreadContextStack copy = (MutableThreadContextStack) values.copy();
    final String result = copy.pop();
    copy.freeze();
    STACK.set(copy);
    return result;
}
项目:logging-log4j2    文件:RegexReplacementTest.java   
@Test
public void testReplacement() {
    logger.error(this.getClass().getName());
    List<String> msgs = app.getMessages();
    assertNotNull(msgs);
    assertEquals("Incorrect number of messages. Should be 1 is " + msgs.size(), 1, msgs.size());
    assertTrue("Replacement failed - expected ending " + EXPECTED + " Actual " + msgs.get(0),
        msgs.get(0).endsWith(EXPECTED));
    app.clear();
    ThreadContext.put("MyKey", "Apache");
    logger.error("This is a test for ${ctx:MyKey}");
    msgs = app.getMessages();
    assertNotNull(msgs);
    assertEquals("Incorrect number of messages. Should be 1 is " + msgs.size(), 1, msgs.size());
    assertEquals("LoggerTest This is a test for Apache" + Strings.LINE_SEPARATOR, msgs.get(0));
}
项目:logging-log4j2    文件:CategoryTest.java   
@Test
public void testClassName() {
    final Category category = Category.getInstance("TestCategory");
    final Layout<String> layout = PatternLayout.newBuilder().withPattern("%d %p %C{1.} [%t] %m%n").build();
    final ListAppender appender = new ListAppender("List2", null, layout, false, false);
    appender.start();
    category.setAdditivity(false);
    category.getLogger().addAppender(appender);
    category.error("Test Message");
    final List<String> msgs = appender.getMessages();
    assertTrue("Incorrect number of messages. Expected 1 got " + msgs.size(), msgs.size() == 1);
    final String msg = msgs.get(0);
    appender.clear();
    final String threadName = Thread.currentThread().getName();
    final String expected = "ERROR o.a.l.CategoryTest [" + threadName + "] Test Message" + Strings.LINE_SEPARATOR;
    assertTrue("Incorrect message " + Strings.dquote(msg) + " expected " + Strings.dquote(expected), msg.endsWith(expected));
}
项目:logging-log4j2    文件:RollingRandomAccessFileManagerTest.java   
@Test
public void testFileTimeBasedOnFileModifiedTimeWhenAppendIsTrue() throws IOException {
    final File file = File.createTempFile("log4j2", "test");
    file.deleteOnExit();
    LockSupport.parkNanos(1000000); // 1 millisec

    final boolean isAppend = true;
    assertThat(file, lastModified(beforeNow()));

    final RollingRandomAccessFileManager manager = RollingRandomAccessFileManager.getRollingRandomAccessFileManager(
            //
            file.getAbsolutePath(), Strings.EMPTY, isAppend, true,
            RollingRandomAccessFileManager.DEFAULT_BUFFER_SIZE, new SizeBasedTriggeringPolicy(Long.MAX_VALUE), //
            null, null, null, null, null, null, null);
    assertThat(file, lastModified(equalTo(manager.getFileTime())));
}
项目:logging-log4j2    文件:PatternSelectorTest.java   
@Test
public void testJavaScriptPatternSelector() throws Exception {
    final org.apache.logging.log4j.Logger logger = LogManager.getLogger("TestJavaScriptPatternSelector");
    final org.apache.logging.log4j.Logger logger2 = LogManager.getLogger("JavascriptNoLocation");
    logger.traceEntry();
    logger.info("Hello World");
    logger2.info("No location information");
    logger.traceExit();
    final ListAppender app = (ListAppender) context.getRequiredAppender("List3");
    assertNotNull("No ListAppender", app);
    final List<String> messages = app.getMessages();
    assertNotNull("No Messages", messages);
    assertTrue("Incorrect number of messages. Expected 4, Actual " + messages.size() + ": " + messages, messages.size() == 4);
    String expect = "[TRACE] TestJavaScriptPatternSelector ====== " +
            "o.a.l.l.c.PatternSelectorTest.testJavaScriptPatternSelector:85 Enter ======" + Strings.LINE_SEPARATOR;
    assertEquals(expect, messages.get(0));
    expect = "[INFO ] TestJavaScriptPatternSelector " +
            "o.a.l.l.c.PatternSelectorTest.testJavaScriptPatternSelector.86 Hello World" + Strings.LINE_SEPARATOR;
    assertEquals(expect, messages.get(1));
    assertEquals("[INFO ] JavascriptNoLocation No location information" + Strings.LINE_SEPARATOR, messages.get(2));
    app.clear();
}
项目:logging-log4j2    文件:InMemoryAppenderTest.java   
private void assertMessage(final String string, final InMemoryAppender app, final String header) {
    final LogEvent event = Log4jLogEvent.newBuilder() //
            .setLoggerName("TestLogger") //
            .setLoggerFqcn(InMemoryAppenderTest.class.getName()) //
            .setLevel(Level.INFO) //
            .setMessage(new SimpleMessage("Test")) //
            .build();
    app.start();
    assertTrue("Appender did not start", app.isStarted());
    app.append(event);
    app.append(event);
    final String msg = app.toString();
    assertNotNull("No message", msg);
    final String expectedHeader = header == null ? "" : header;
    final String expected = expectedHeader + "Test" + Strings.LINE_SEPARATOR + "Test" + Strings.LINE_SEPARATOR;
    assertTrue("Incorrect message: " + msg, msg.equals(expected));
    app.stop();
    assertFalse("Appender did not stop", app.isStarted());
}
项目:logging-log4j2    文件:RegexReplacementConverterTest.java   
@Test
public void testReplacement() {
    ThreadContext.put("MyKey", "Apache");
    final LogEvent event = Log4jLogEvent.newBuilder() //
            .setLoggerName(RegexReplacementConverterTest.class.getName()) //
            .setLevel(Level.DEBUG) //
            .setMessage(new SimpleMessage("This is a test")) //
            .build();
    final StringBuilder sb = new StringBuilder();
    final LoggerContext ctx = LoggerContext.getContext();
    final String[] options = new String[] {
        "%logger %msg%n", "\\.", "/"
    };
    final RegexReplacementConverter converter = RegexReplacementConverter.newInstance(ctx.getConfiguration(),
        options);
    converter.format(event, sb);
    assertEquals("org/apache/logging/log4j/core/pattern/RegexReplacementConverterTest This is a test" +
        Strings.LINE_SEPARATOR, sb.toString());
}
项目:logging-log4j2    文件:PatternSelectorTest.java   
@Test
public void testScriptPatternSelector() throws Exception {
    final org.apache.logging.log4j.Logger logger = LogManager.getLogger("TestScriptPatternSelector");
    final org.apache.logging.log4j.Logger logger2 = LogManager.getLogger("NoLocation");
    logger.traceEntry();
    logger.info("Hello World");
    logger2.info("No location information");
    logger.traceExit();
    final ListAppender app = (ListAppender) context.getRequiredAppender("List2");
    assertNotNull("No ListAppender", app);
    final List<String> messages = app.getMessages();
    assertNotNull("No Messages", messages);
    assertTrue("Incorrect number of messages. Expected 4, Actual " + messages.size() + ": " + messages, messages.size() == 4);
    String expect = "[TRACE] TestScriptPatternSelector ====== " +
            "o.a.l.l.c.PatternSelectorTest.testScriptPatternSelector:62 Enter ======" + Strings.LINE_SEPARATOR;
    assertEquals(expect, messages.get(0));
    expect = "[INFO ] TestScriptPatternSelector o.a.l.l.c.PatternSelectorTest.testScriptPatternSelector.63 " +
            "Hello World" + Strings.LINE_SEPARATOR;
    assertEquals(expect, messages.get(1));
    assertEquals("[INFO ] NoLocation No location information" + Strings.LINE_SEPARATOR, messages.get(2));
    app.clear();
}
项目:logging-log4j2    文件:ContextStackJsonAttributeConverter.java   
@Override
public ThreadContext.ContextStack convertToEntityAttribute(final String s) {
    if (Strings.isEmpty(s)) {
        return null;
    }

    List<String> list;
    try {
        list = ContextMapJsonAttributeConverter.OBJECT_MAPPER.readValue(s, new TypeReference<List<String>>() { });
    } catch (final IOException e) {
        throw new PersistenceException("Failed to convert JSON string to list for stack.", e);
    }

    final DefaultThreadContextStack result = new DefaultThreadContextStack(true);
    result.addAll(list);
    return result;
}
项目:logging-log4j2    文件:MongoDbProvider.java   
private static WriteConcern toWriteConcern(final String writeConcernConstant,
        final String writeConcernConstantClassName) {
    WriteConcern writeConcern;
    if (Strings.isNotEmpty(writeConcernConstant)) {
        if (Strings.isNotEmpty(writeConcernConstantClassName)) {
            try {
                final Class<?> writeConcernConstantClass = LoaderUtil.loadClass(writeConcernConstantClassName);
                final Field field = writeConcernConstantClass.getField(writeConcernConstant);
                writeConcern = (WriteConcern) field.get(null);
            } catch (final Exception e) {
                LOGGER.error("Write concern constant [{}.{}] not found, using default.",
                        writeConcernConstantClassName, writeConcernConstant);
                writeConcern = DEFAULT_WRITE_CONCERN;
            }
        } else {
            writeConcern = WriteConcern.valueOf(writeConcernConstant);
            if (writeConcern == null) {
                LOGGER.warn("Write concern constant [{}] not found, using default.", writeConcernConstant);
                writeConcern = DEFAULT_WRITE_CONCERN;
            }
        }
    } else {
        writeConcern = DEFAULT_WRITE_CONCERN;
    }
    return writeConcern;
}
项目:logging-log4j2    文件:SslSocketManager.java   
public static SslSocketManager getSocketManager(final SslConfiguration sslConfig, final String host, int port,
        final int connectTimeoutMillis, int reconnectDelayMillis, final boolean immediateFail,
        final Layout<? extends Serializable> layout, final int bufferSize, final SocketOptions socketOptions) {
    if (Strings.isEmpty(host)) {
        throw new IllegalArgumentException("A host name is required");
    }
    if (port <= 0) {
        port = DEFAULT_PORT;
    }
    if (reconnectDelayMillis == 0) {
        reconnectDelayMillis = DEFAULT_RECONNECTION_DELAY_MILLIS;
    }
    final String name = "TLS:" + host + ':' + port;
    return (SslSocketManager) getManager(name, new SslFactoryData(sslConfig, host, port, connectTimeoutMillis,
            reconnectDelayMillis, immediateFail, layout, bufferSize, socketOptions), FACTORY);
}
项目:logging-log4j2    文件:FileAppenderTest.java   
private void verifyFile(final int count) throws Exception {
    // String expected = "[\\w]* \\[\\s*\\] INFO TestLogger - Test$";
    final String expected = "^\\d{4}-\\d{2}-\\d{2} \\d{2}:\\d{2}:\\d{2},\\d{3} \\[[^\\]]*\\] INFO TestLogger - Test";
    final Pattern pattern = Pattern.compile(expected);
    int lines = 0;
    try (final BufferedReader is = new BufferedReader(new InputStreamReader(new FileInputStream(FILE_NAME)))) {
        String str = Strings.EMPTY;
        while (is.ready()) {
            str = is.readLine();
            // System.out.println(str);
            ++lines;
            final Matcher matcher = pattern.matcher(str);
            assertTrue("Unexpected data: " + str, matcher.matches());
        }
    }
    Assert.assertEquals(count, lines);
}
项目:logging-log4j2    文件:ColumnConfigTest.java   
@Test
public void testPatternColumn03() {
    final ColumnConfig config = ColumnConfig.newBuilder()
        .setName("col3")
        .setPattern("%X{id} %level")
        .setLiteral(Strings.EMPTY)
        .setEventTimestamp(false)
        .setUnicode(true)
        .setClob(false)
        .build();

    assertNotNull("The result should not be null.", config);
    assertEquals("The column name is not correct.", "col3", config.getColumnName());
    assertNotNull("The pattern should not be null.", config.getLayout());
    assertEquals("The pattern is not correct.", "%X{id} %level", config.getLayout().toString());
    assertNull("The literal value should be null.", config.getLiteralValue());
    assertFalse("The timestamp flag should be false.", config.isEventTimestamp());
    assertTrue("The unicode flag should be true.", config.isUnicode());
    assertFalse("The clob flag should be false.", config.isClob());
}
项目:logging-log4j2    文件:PropertiesConfigurationBuilder.java   
private AppenderComponentBuilder createAppender(final String key, final Properties properties) {
    final String name = (String) properties.remove(CONFIG_NAME);
    if (Strings.isEmpty(name)) {
        throw new ConfigurationException("No name attribute provided for Appender " + key);
    }
    final String type = (String) properties.remove(CONFIG_TYPE);
    if (Strings.isEmpty(type)) {
        throw new ConfigurationException("No type attribute provided for Appender " + key);
    }
    final AppenderComponentBuilder appenderBuilder = builder.newAppender(name, type);
    addFiltersToComponent(appenderBuilder, properties);
    final Properties layoutProps = PropertiesUtil.extractSubset(properties, "layout");
    if (layoutProps.size() > 0) {
        appenderBuilder.add(createLayout(name, layoutProps));
    }

    return processRemainingProperties(appenderBuilder, properties);
}
项目:logging-log4j2    文件:ColumnConfigTest.java   
@Test
public void testPatternColumn02() {
    final ColumnConfig config = ColumnConfig.newBuilder()
        .setName("col2")
        .setPattern("%X{id} %level")
        .setLiteral(Strings.EMPTY)
        .setEventTimestamp(false)
        .setUnicode(false)
        .setClob(true)
        .build();

    assertNotNull("The result should not be null.", config);
    assertEquals("The column name is not correct.", "col2", config.getColumnName());
    assertNotNull("The pattern should not be null.", config.getLayout());
    assertEquals("The pattern is not correct.", "%X{id} %level", config.getLayout().toString());
    assertNull("The literal value should be null.", config.getLiteralValue());
    assertFalse("The timestamp flag should be false.", config.isEventTimestamp());
    assertFalse("The unicode flag should be false.", config.isUnicode());
    assertTrue("The clob flag should be true.", config.isClob());
}
项目:logging-log4j2    文件:Configurator.java   
/**
 * Initializes the Logging Context.
 * @param name The Context name.
 * @param loader The ClassLoader for the Context (or null).
 * @param configLocation The configuration for the logging context (or null, or blank).
 * @param externalContext The external context to be attached to the LoggerContext
 * @return The LoggerContext or null if an error occurred (check the status logger).
 */
public static LoggerContext initialize(final String name, final ClassLoader loader, final String configLocation,
        final Object externalContext) {
    if (Strings.isBlank(configLocation)) {
        return initialize(name, loader, (URI) null, externalContext);
    }
    if (configLocation.contains(",")) {
        final String[] parts = configLocation.split(",");
        String scheme = null;
        final List<URI> uris = new ArrayList<>(parts.length);
        for (final String part : parts) {
            final URI uri = NetUtils.toURI(scheme != null ? scheme + ":" + part.trim() : part.trim());
            if (scheme == null && uri.getScheme() != null) {
                scheme = uri.getScheme();
            }
            uris.add(uri);
        }
        return initialize(name, loader, uris, externalContext);
    }
    return initialize(name, loader, NetUtils.toURI(configLocation), externalContext);
}
项目:logging-log4j2    文件:XIncludeTest.java   
@Test
public void testLogToFile() throws Exception {
    final Logger logger = this.ctx.getLogger(FILE_LOGGER_NAME);
    final long random = this.random.nextLong();
    logger.debug("This is test message number {}", random);
    int count = 0;
    String line = Strings.EMPTY;
    try (BufferedReader in = new BufferedReader(new FileReader(this.logFileName))) {
        while (in.ready()) {
            ++count;
            line = in.readLine();
        }
    }
    assertThat(count, is(equalTo(1)));
    assertThat(line, endsWith(Long.toString(random)));
}
项目:log4j2-redis-appender    文件:RedisAppender.java   
private void check() {
    requireNonNull(config, "config");
    requireArgument(Strings.isNotBlank(name), "blank name");
    requireNonNull(charset, "charset");
    requireNonNull(layout, "layout");
    requireArgument(Strings.isNotBlank(key), "blank key");
    requireArgument(Strings.isNotBlank(host), "blank host");
    requireArgument(port > 0, "expecting: port > 0, found: %d", port);
    requireArgument(connectionTimeoutSeconds > 0, "expecting: connectionTimeoutSeconds > 0, found: %d", connectionTimeoutSeconds);
    requireArgument(socketTimeoutSeconds > 0, "expecting: socketTimeoutSeconds > 0, found: %d", socketTimeoutSeconds);
    requireNonNull(poolConfig, "poolConfig");
    requireNonNull(throttlerConfig, "throttlerConfig");
}
项目:spring-boot-boilerplate    文件:MongoDbProvider.java   
private static WriteConcern toWriteConcern(final String writeConcernConstant,
                                           final String writeConcernConstantClassName) {
    WriteConcern writeConcern;
    if (Strings.isNotEmpty(writeConcernConstant)) {
        if (Strings.isNotEmpty(writeConcernConstantClassName)) {
            try {
                final Class<?> writeConcernConstantClass = LoaderUtil.loadClass(writeConcernConstantClassName);
                final Field field = writeConcernConstantClass.getField(writeConcernConstant);
                writeConcern = (WriteConcern) field.get(null);
            } catch (final Exception e) {
                LOGGER.error("Write concern constant [{}.{}] not found, using default.",
                        writeConcernConstantClassName, writeConcernConstant);
                writeConcern = DEFAULT_WRITE_CONCERN;
            }
        } else {
            writeConcern = WriteConcern.valueOf(writeConcernConstant);
            if (writeConcern == null) {
                LOGGER.warn("Write concern constant [{}] not found, using default.", writeConcernConstant);
                writeConcern = DEFAULT_WRITE_CONCERN;
            }
        }
    } else {
        writeConcern = DEFAULT_WRITE_CONCERN;
    }

    return writeConcern;
}
项目:elasticsearch-indexing-proxy    文件:IndexingProxyService.java   
public void stopRequestSender(final String index, final ActionListener<Map<String, Object>> listener) {
    if (logger.isDebugEnabled()) {
        logger.debug("Stopping RequestSender(" + index + ")");
    }
    client.prepareGet(IndexingProxyPlugin.INDEX_NAME, IndexingProxyPlugin.TYPE_NAME, index).setRefresh(true).execute(wrap(res -> {
        final Map<String, Object> params = new HashMap<>();
        if (res.isExists()) {
            final Map<String, Object> source = res.getSourceAsMap();
            final String workingNodeName = (String) source.get(IndexingProxyPlugin.NODE_NAME);
            params.put("node", nodeName());
            params.put("found", true);
            if (Strings.isBlank(workingNodeName)) {
                params.put("stop", false);
                params.put("working", "");
            } else if (nodeName().equals(workingNodeName)) {
                params.put("working", workingNodeName);
                // stop
                final long version = res.getVersion();
                updateRequestSenderInfo(index, "", version, wrap(res2 -> {
                    params.put("stop", true);
                    listener.onResponse(params);
                }, listener::onFailure));
            } else {
                params.put("stop", false);
                params.put("working", workingNodeName);
            }
        } else {
            params.put("found", false);
            params.put("stop", false);
            params.put("working", "");
        }
        if (params.containsKey("stop")) {
            listener.onResponse(params);
        }
    }, listener::onFailure));
}
项目:logging-log4j-boot    文件:Log4jLoggingSystem.java   
@Override
protected void loadDefaults(final LoggingInitializationContext context, final LogFile file) {
    final String configFileName = "classpath:META-INF/log4j/default/log4j2"
        + ((file == null) ? Strings.EMPTY : "-file")
        + ".xml";
    loadConfiguration(context, configFileName, file);
}
项目:flow-platform    文件:StringEncodeUtil.java   
/**
 * Converts a string to MD5 encoding
 *
 * @param origin
 * @param charsetname
 * @return
 */
public static String encodeByMD5(String origin, String charsetname) {
    String resultString = null;
    try {
        resultString = new String(origin);
        MessageDigest md = MessageDigest.getInstance("MD5");
        if (charsetname == null || Strings.EMPTY.equals(charsetname)) {
            resultString = byteArrayToHexString(md.digest(resultString.getBytes()));
        } else {
            resultString = byteArrayToHexString(md.digest(resultString.getBytes(charsetname)));
        }
    } catch (Exception exception) {
    }
    return resultString;
}