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

项目: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;
}
项目:log4j2    文件:DataSourceConnectionSource.java   
/**
 * Factory method for creating a connection source within the plugin manager.
 *
 * @param jndiName The full JNDI path where the data source is bound. Should start with java:/comp/env or
 *                 environment-equivalent.
 * @return the created connection source.
 */
@PluginFactory
public static DataSourceConnectionSource createConnectionSource(@PluginAttribute("jndiName") final String jndiName) {
    if (Strings.isEmpty(jndiName)) {
        LOGGER.error("No JNDI name provided.");
        return null;
    }

    try {
        final InitialContext context = new InitialContext();
        final DataSource dataSource = (DataSource) context.lookup(jndiName);
        if (dataSource == null) {
            LOGGER.error("No data source found with JNDI name [" + jndiName + "].");
            return null;
        }

        return new DataSourceConnectionSource(jndiName, dataSource);
    } catch (final NamingException e) {
        LOGGER.error(e.getMessage(), e);
        return null;
    }
}
项目:CrystalMod    文件:PlayerCubeChunkLoaderManager.java   
@Override
public void ticketsLoaded(final List<ForgeChunkManager.Ticket> tickets, final World world) {
    if(world.provider.getDimension() != ModDimensions.CUBE_ID)return;
       PlayerCubeChunkLoaderManager.dirty = true;
       final HashMap<GameProfile, ForgeChunkManager.Ticket> cache = new HashMap<GameProfile, ForgeChunkManager.Ticket>();
       PlayerCubeChunkLoaderManager.playerTickets = cache;
       for (final ForgeChunkManager.Ticket ticket : tickets) {
           final NBTTagCompound modData = ticket.getModData();
           GameProfile profile = null;
        final String name = modData.getString("Name");
           UUID uuid = null;
           if (modData.hasKey("UUIDL")) {
               uuid = new UUID(modData.getLong("UUIDU"), modData.getLong("UUIDL"));
           }
           if (Strings.isEmpty(name)) {
               profile = null;
           }
           else profile = new GameProfile(uuid, name);

           cache.put(profile, ticket);
           final int[] x = modData.getIntArray("x");
           final int[] z = modData.getIntArray("z");
           if (x.length == z.length) {
               for (int i = 0; i < x.length; ++i) {
                   ForgeChunkManager.forceChunk(ticket, new ChunkPos(x[i], z[i]));
               }
           }
       }
   }
项目:log4j2    文件:FlumePersistentManager.java   
/**
 * Returns a FlumeAvroManager.
 * @param name The name of the manager.
 * @param agents The agents to use.
 * @param properties Properties to pass to the Manager.
 * @param batchSize The number of events to include in a batch.
 * @param retries The number of times to retry connecting before giving up.
 * @param connectionTimeout The amount of time to wait to establish a connection.
 * @param requestTimeout The amount of time to wait for a response to a request.
 * @param delay Amount of time to delay before delivering a batch.
 * @param dataDir The location of the Berkeley database.
 * @return A FlumeAvroManager.
 */
public static FlumePersistentManager getManager(final String name, final Agent[] agents,
                                                final Property[] properties, int batchSize, final int retries,
                                                final int connectionTimeout, final int requestTimeout,
                                                final int delay, final int lockTimeoutRetryCount,
                                                final String dataDir) {
    if (agents == null || agents.length == 0) {
        throw new IllegalArgumentException("At least one agent is required");
    }

    if (batchSize <= 0) {
        batchSize = 1;
    }
    final String dataDirectory = Strings.isEmpty(dataDir) ? DEFAULT_DATA_DIR : dataDir;

    final StringBuilder sb = new StringBuilder("FlumePersistent[");
    boolean first = true;
    for (final Agent agent : agents) {
        if (!first) {
            sb.append(",");
        }
        sb.append(agent.getHost()).append(":").append(agent.getPort());
        first = false;
    }
    sb.append("]");
    sb.append(" ").append(dataDirectory);
    return getManager(sb.toString(), factory, new FactoryData(name, agents, batchSize, retries,
        connectionTimeout, requestTimeout, delay, lockTimeoutRetryCount, dataDir, properties));
}
项目:log4j2    文件:StrMatcher.java   
/**
 * Constructor that creates a matcher from a string representing a set of characters.
 *
 * @param chars  the characters to match, null or empty matches nothing
 * @return a new Matcher for the given characters
 */
public static StrMatcher charSetMatcher(final String chars) {
    if (Strings.isEmpty(chars)) {
        return NONE_MATCHER;
    }
    if (chars.length() == 1) {
        return new CharMatcher(chars.charAt(0));
    }
    return new CharSetMatcher(chars.toCharArray());
}
项目:log4j2    文件:StrMatcher.java   
/**
 * Constructor that creates a matcher from a string.
 *
 * @param str  the string to match, null or empty matches nothing
 * @return a new Matcher for the given String
 */
public static StrMatcher stringMatcher(final String str) {
    if (Strings.isEmpty(str)) {
        return NONE_MATCHER;
    }
    return new StringMatcher(str);
}
项目:log4j2    文件:TLSSocketManager.java   
public static TLSSocketManager getSocketManager(final SSLConfiguration sslConfig, final String host, int port,
                                                int delay, final boolean immediateFail, final Layout layout ) {
    if (Strings.isEmpty(host)) {
        throw new IllegalArgumentException("A host name is required");
    }
    if (port <= 0) {
        port = DEFAULT_PORT;
    }
    if (delay == 0) {
        delay = DEFAULT_RECONNECTION_DELAY;
    }
    return (TLSSocketManager) getManager("TLS:" + host + ":" + port,
            new TLSFactoryData(sslConfig, host, port, delay, immediateFail, layout), FACTORY);
}
项目:log4j2    文件:TCPSocketManager.java   
/**
 * Obtain a TCPSocketManager.
 * @param host The host to connect to.
 * @param port The port on the host.
 * @param delay The interval to pause between retries.
 * @return A TCPSocketManager.
 */
public static TCPSocketManager getSocketManager(final String host, int port, int delay,
                                                final boolean immediateFail, final Layout<? extends Serializable> layout ) {
    if (Strings.isEmpty(host)) {
        throw new IllegalArgumentException("A host name is required");
    }
    if (port <= 0) {
        port = DEFAULT_PORT;
    }
    if (delay == 0) {
        delay = DEFAULT_RECONNECTION_DELAY;
    }
    return (TCPSocketManager) getManager("TCP:" + host + ":" + port,
        new FactoryData(host, port, delay, immediateFail, layout), FACTORY);
}
项目:log4j2    文件:DatagramSocketManager.java   
/**
 * Obtain a SocketManager.
 * @param host The host to connect to.
 * @param port The port on the host.
 * @param layout The layout.
 * @return A DatagramSocketManager.
 */
public static DatagramSocketManager getSocketManager(final String host, final int port, final Layout<? extends Serializable> layout) {
    if (Strings.isEmpty(host)) {
        throw new IllegalArgumentException("A host name is required");
    }
    if (port <= 0) {
        throw new IllegalArgumentException("A port value is required");
    }
    return (DatagramSocketManager) getManager("UDP:" + host + ":" + port, new FactoryData(host, port, layout),
        FACTORY);
}
项目:log4j2    文件:StackTraceElementAttributeConverter.java   
@Override
public StackTraceElement convertToEntityAttribute(final String s) {
    if (Strings.isEmpty(s)) {
        return null;
    }

    return StackTraceElementAttributeConverter.convertString(s);
}
项目:log4j2    文件:MessageAttributeConverter.java   
@Override
public Message convertToEntityAttribute(final String s) {
    if (Strings.isEmpty(s)) {
        return null;
    }

    return LOGGER.getMessageFactory().newMessage(s);
}
项目:log4j2    文件:MarkerAttributeConverter.java   
@Override
public Marker convertToEntityAttribute(final String s) {
    if (Strings.isEmpty(s)) {
        return null;
    }

    final int bracket = s.indexOf("[");

    return bracket < 1 ? MarkerManager.getMarker(s) : MarkerManager.getMarker(s.substring(0, bracket));
}
项目:log4j2    文件:ThrowableAttributeConverter.java   
@Override
public Throwable convertToEntityAttribute(final String s) {
    if (Strings.isEmpty(s)) {
        return null;
    }

    final List<String> lines = Arrays.asList(s.split("(\n|\r\n)"));
    return this.convertString(lines.listIterator(), false);
}
项目:log4j2    文件:ContextMapJsonAttributeConverter.java   
@Override
public Map<String, String> convertToEntityAttribute(final String s) {
    if (Strings.isEmpty(s)) {
        return null;
    }
    try {
        return OBJECT_MAPPER.readValue(s, new TypeReference<Map<String, String>>() { });
    } catch (final IOException e) {
        throw new PersistenceException("Failed to convert JSON string to map.", e);
    }
}
项目:log4j2    文件:DriverManagerConnectionSource.java   
/**
 * Factory method for creating a connection source within the plugin manager.
 *
 * @param url The JDBC URL to use to connect to the logging database. A driver that can accept this URL must be on
 *            the classpath.
 * @param username The username with which to log in to the database, if applicable.
 * @param password The password with which to log in to the database, if applicable.
 * @return the created connection source.
 */
@PluginFactory
public static DriverManagerConnectionSource createConnectionSource(
        @PluginAttribute("url") final String url,
        @PluginAttribute("username") String username,
        @PluginAttribute("password") String password) {
    if (Strings.isEmpty(url)) {
        LOGGER.error("No JDBC URL specified for the database.");
        return null;
    }

    Driver driver;
    try {
        driver = DriverManager.getDriver(url);
    } catch (final SQLException e) {
        LOGGER.error("No matching driver found for database URL [" + url + "].", e);
        return null;
    }

    if (driver == null) {
        LOGGER.error("No matching driver found for database URL [" + url + "].");
        return null;
    }

    if (username == null || username.trim().isEmpty()) {
        username = null;
        password = null;
    }

    return new DriverManagerConnectionSource(url, username, password);
}
项目:log4j2    文件:XMLLayout.java   
protected XMLLayout(final boolean locationInfo, final boolean properties, final boolean complete,
                    boolean compact, final String nsPrefix, final Charset charset) {
    super(charset);
    this.locationInfo = locationInfo;
    this.properties = properties;
    this.complete = complete;
    this.eol = compact ? COMPACT_EOL : DEFAULT_EOL;
    this.indent1 = compact ? COMPACT_INDENT : DEFAULT_INDENT;
    this.indent2 = this.indent1 + this.indent1;
    this.indent3 = this.indent2 + this.indent1;
    this.namespacePrefix = (Strings.isEmpty(nsPrefix) ? DEFAULT_NS_PREFIX : nsPrefix) + ":";
}
项目:log4j2    文件:RFC5424Layout.java   
boolean discard() {
    if (discardIfEmpty == false) {
        return false;
    }
    boolean foundNotEmptyValue = false;
    for (final Map.Entry<String, String> entry : fields.entrySet()) {
        if (Strings.isNotEmpty(entry.getValue())) {
            foundNotEmptyValue = true;
            break;
        }
    }
    return !foundNotEmptyValue;
}
项目:Cauldron    文件:TwitchStream.java   
public TwitchStream(Minecraft p_i1012_1_, final String p_i1012_2_)
{
    this.field_152964_p = IStream.AuthFailureReason.ERROR;
    this.field_152953_e = p_i1012_1_;
    this.field_152951_c = new BroadcastController();
    this.field_152952_d = new ChatController();
    this.field_152951_c.func_152841_a(this);
    this.field_152952_d.func_152990_a(this);
    this.field_152951_c.func_152842_a("nmt37qblda36pvonovdkbopzfzw3wlq");
    this.field_152952_d.func_152984_a("nmt37qblda36pvonovdkbopzfzw3wlq");
    this.field_152954_f.getChatStyle().setColor(EnumChatFormatting.DARK_PURPLE);

    if (Strings.isNotEmpty(p_i1012_2_) && OpenGlHelper.framebufferSupported)
    {
        Thread thread = new Thread("Twitch authenticator")
        {
            private static final String __OBFID = "CL_00001811";
            public void run()
            {
                try
                {
                    URL url = new URL("https://api.twitch.tv/kraken?oauth_token=" + URLEncoder.encode(p_i1012_2_, "UTF-8"));
                    String s = HttpUtil.func_152755_a(url);
                    JsonObject jsonobject = JsonUtils.getJsonElementAsJsonObject((new JsonParser()).parse(s), "Response");
                    JsonObject jsonobject1 = JsonUtils.func_152754_s(jsonobject, "token");

                    if (JsonUtils.getJsonObjectBooleanFieldValue(jsonobject1, "valid"))
                    {
                        String s1 = JsonUtils.getJsonObjectStringFieldValue(jsonobject1, "user_name");
                        TwitchStream.field_152950_b.debug(TwitchStream.field_152949_a, "Authenticated with twitch; username is {}", new Object[] {s1});
                        AuthToken authtoken = new AuthToken();
                        authtoken.data = p_i1012_2_;
                        TwitchStream.this.field_152951_c.func_152818_a(s1, authtoken);
                        TwitchStream.this.field_152952_d.func_152998_c(s1);
                        TwitchStream.this.field_152952_d.func_152994_a(authtoken);
                        Runtime.getRuntime().addShutdownHook(new Thread("Twitch shutdown hook")
                        {
                            private static final String __OBFID = "CL_00001810";
                            public void run()
                            {
                                TwitchStream.this.func_152923_i();
                            }
                        });
                        TwitchStream.this.field_152951_c.func_152817_A();
                    }
                    else
                    {
                        TwitchStream.this.field_152964_p = IStream.AuthFailureReason.INVALID_TOKEN;
                        TwitchStream.field_152950_b.error(TwitchStream.field_152949_a, "Given twitch access token is invalid");
                    }
                }
                catch (IOException ioexception)
                {
                    TwitchStream.this.field_152964_p = IStream.AuthFailureReason.ERROR;
                    TwitchStream.field_152950_b.error(TwitchStream.field_152949_a, "Could not authenticate with twitch", ioexception);
                }
            }
        };
        thread.setDaemon(true);
        thread.start();
    }
}
项目:Cauldron    文件:TwitchStream.java   
public TwitchStream(Minecraft p_i1012_1_, final String p_i1012_2_)
{
    this.field_152964_p = IStream.AuthFailureReason.ERROR;
    this.field_152953_e = p_i1012_1_;
    this.field_152951_c = new BroadcastController();
    this.field_152952_d = new ChatController();
    this.field_152951_c.func_152841_a(this);
    this.field_152952_d.func_152990_a(this);
    this.field_152951_c.func_152842_a("nmt37qblda36pvonovdkbopzfzw3wlq");
    this.field_152952_d.func_152984_a("nmt37qblda36pvonovdkbopzfzw3wlq");
    this.field_152954_f.getChatStyle().setColor(EnumChatFormatting.DARK_PURPLE);

    if (Strings.isNotEmpty(p_i1012_2_) && OpenGlHelper.framebufferSupported)
    {
        Thread thread = new Thread("Twitch authenticator")
        {
            private static final String __OBFID = "CL_00001811";
            public void run()
            {
                try
                {
                    URL url = new URL("https://api.twitch.tv/kraken?oauth_token=" + URLEncoder.encode(p_i1012_2_, "UTF-8"));
                    String s = HttpUtil.func_152755_a(url);
                    JsonObject jsonobject = JsonUtils.getJsonElementAsJsonObject((new JsonParser()).parse(s), "Response");
                    JsonObject jsonobject1 = JsonUtils.func_152754_s(jsonobject, "token");

                    if (JsonUtils.getJsonObjectBooleanFieldValue(jsonobject1, "valid"))
                    {
                        String s1 = JsonUtils.getJsonObjectStringFieldValue(jsonobject1, "user_name");
                        TwitchStream.field_152950_b.debug(TwitchStream.field_152949_a, "Authenticated with twitch; username is {}", new Object[] {s1});
                        AuthToken authtoken = new AuthToken();
                        authtoken.data = p_i1012_2_;
                        TwitchStream.this.field_152951_c.func_152818_a(s1, authtoken);
                        TwitchStream.this.field_152952_d.func_152998_c(s1);
                        TwitchStream.this.field_152952_d.func_152994_a(authtoken);
                        Runtime.getRuntime().addShutdownHook(new Thread("Twitch shutdown hook")
                        {
                            private static final String __OBFID = "CL_00001810";
                            public void run()
                            {
                                TwitchStream.this.func_152923_i();
                            }
                        });
                        TwitchStream.this.field_152951_c.func_152817_A();
                    }
                    else
                    {
                        TwitchStream.this.field_152964_p = IStream.AuthFailureReason.INVALID_TOKEN;
                        TwitchStream.field_152950_b.error(TwitchStream.field_152949_a, "Given twitch access token is invalid");
                    }
                }
                catch (IOException ioexception)
                {
                    TwitchStream.this.field_152964_p = IStream.AuthFailureReason.ERROR;
                    TwitchStream.field_152950_b.error(TwitchStream.field_152949_a, "Could not authenticate with twitch", ioexception);
                }
            }
        };
        thread.setDaemon(true);
        thread.start();
    }
}
项目:log4j2    文件:PatternParser.java   
/**
 * Processes a format specifier sequence.
 *
 * @param c                 initial character of format specifier.
 * @param pattern           conversion pattern
 * @param i                 current position in conversion pattern.
 * @param currentLiteral    current literal.
 * @param formattingInfo    current field specifier.
 * @param rules             map of stock pattern converters keyed by format specifier.
 * @param patternConverters list to receive parsed pattern converter.
 * @param formattingInfos   list to receive corresponding field specifier.
 * @return position after format specifier sequence.
 */
private int finalizeConverter(final char c, final String pattern, int i,
        final StringBuilder currentLiteral, final FormattingInfo formattingInfo,
        final Map<String, Class<PatternConverter>> rules,
        final List<PatternConverter> patternConverters, final List<FormattingInfo> formattingInfos) {
    final StringBuilder convBuf = new StringBuilder();
    i = extractConverter(c, pattern, i, convBuf, currentLiteral);

    final String converterId = convBuf.toString();

    final List<String> options = new ArrayList<String>();
    i = extractOptions(pattern, i, options);

    final PatternConverter pc = createConverter(converterId, currentLiteral, rules, options);

    if (pc == null) {
        StringBuilder msg;

        if (Strings.isEmpty(converterId)) {
            msg = new StringBuilder("Empty conversion specifier starting at position ");
        } else {
            msg = new StringBuilder("Unrecognized conversion specifier [");
            msg.append(converterId);
            msg.append("] starting at position ");
        }

        msg.append(Integer.toString(i));
        msg.append(" in conversion pattern.");

        LOGGER.error(msg.toString());

        patternConverters.add(new LiteralPatternConverter(config, currentLiteral.toString()));
        formattingInfos.add(FormattingInfo.getDefault());
    } else {
        patternConverters.add(pc);
        formattingInfos.add(formattingInfo);

        if (currentLiteral.length() > 0) {
            patternConverters.add(new LiteralPatternConverter(config, currentLiteral.toString()));
            formattingInfos.add(FormattingInfo.getDefault());
        }
    }

    currentLiteral.setLength(0);

    return i;
}
项目:log4j2    文件:LoggerConfig.java   
@Override
public String toString() {
    return Strings.isEmpty(name) ? "root" : name;
}
项目:log4j2    文件:SMTPManager.java   
public static SMTPManager getSMTPManager(final String to, final String cc, final String bcc,
                                         final String from, final String replyTo,
                                         final String subject, String protocol, final String host,
                                         final int port, final String username, final String password,
                                         final boolean isDebug, final String filterName, final int numElements) {
    if (Strings.isEmpty(protocol)) {
        protocol = "smtp";
    }

    final StringBuilder sb = new StringBuilder();
    if (to != null) {
        sb.append(to);
    }
    sb.append(":");
    if (cc != null) {
        sb.append(cc);
    }
    sb.append(":");
    if (bcc != null) {
        sb.append(bcc);
    }
    sb.append(":");
    if (from != null) {
        sb.append(from);
    }
    sb.append(":");
    if (replyTo != null) {
        sb.append(replyTo);
    }
    sb.append(":");
    if (subject != null) {
        sb.append(subject);
    }
    sb.append(":");
    sb.append(protocol).append(":").append(host).append(":").append("port").append(":");
    if (username != null) {
        sb.append(username);
    }
    sb.append(":");
    if (password != null) {
        sb.append(password);
    }
    sb.append(isDebug ? ":debug:" : "::");
    sb.append(filterName);

    final String name = "SMTP:" + NameUtil.md5(sb.toString());

    return getManager(name, FACTORY, new FactoryData(to, cc, bcc, from, replyTo, subject,
        protocol, host, port, username, password, isDebug, numElements));
}
项目:log4j2    文件:ColumnConfig.java   
/**
 * Factory method for creating a column config within the plugin manager.
 *
 * @param config The configuration object
 * @param name The name of the database column as it exists within the database table.
 * @param pattern The {@link PatternLayout} pattern to insert in this column. Mutually exclusive with
 *                {@code literalValue!=null} and {@code eventTimestamp=true}
 * @param literalValue The literal value to insert into the column as-is without any quoting or escaping. Mutually
 *                     exclusive with {@code pattern!=null} and {@code eventTimestamp=true}.
 * @param eventTimestamp If {@code "true"}, indicates that this column is a date-time column in which the event
 *                       timestamp should be inserted. Mutually exclusive with {@code pattern!=null} and
 *                       {@code literalValue!=null}.
 * @param unicode If {@code "true"}, indicates that the column is a unicode String.
 * @param clob If {@code "true"}, indicates that the column is a character LOB (CLOB).
 * @return the created column config.
 */
@PluginFactory
public static ColumnConfig createColumnConfig(
        @PluginConfiguration final Configuration config,
        @PluginAttribute("name") final String name,
        @PluginAttribute("pattern") final String pattern,
        @PluginAttribute("literal") final String literalValue,
        @PluginAttribute("isEventTimestamp") final String eventTimestamp,
        @PluginAttribute("isUnicode") final String unicode,
        @PluginAttribute("isClob") final String clob) {
    if (Strings.isEmpty(name)) {
        LOGGER.error("The column config is not valid because it does not contain a column name.");
        return null;
    }

    final boolean isPattern = Strings.isNotEmpty(pattern);
    final boolean isLiteralValue = Strings.isNotEmpty(literalValue);
    final boolean isEventTimestamp = Boolean.parseBoolean(eventTimestamp);
    final boolean isUnicode = Booleans.parseBoolean(unicode, true);
    final boolean isClob = Boolean.parseBoolean(clob);

    if ((isPattern && isLiteralValue) || (isPattern && isEventTimestamp) || (isLiteralValue && isEventTimestamp)) {
        LOGGER.error("The pattern, literal, and isEventTimestamp attributes are mutually exclusive.");
        return null;
    }

    if (isEventTimestamp) {
        return new ColumnConfig(name, null, null, true, false, false);
    }
    if (isLiteralValue) {
        return new ColumnConfig(name, null, literalValue, false, false, false);
    }
    if (isPattern) {
        return new ColumnConfig(
                name, PatternLayout.createLayout(pattern, config, null, null, "false"), null, false, isUnicode,
                isClob
        );
    }

    LOGGER.error("To configure a column you must specify a pattern or literal or set isEventDate to true.");
    return null;
}