Java Code Examples for org.apache.logging.log4j.util.Strings#isEmpty()

The following examples show how to use org.apache.logging.log4j.util.Strings#isEmpty() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: PropertiesConfigurationBuilder.java    From logging-log4j2 with Apache License 2.0 6 votes vote down vote up
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);
}
 
Example 2
Source File: TcpSocketManager.java    From logging-log4j2 with Apache License 2.0 6 votes vote down vote up
/**
 * Obtains a TcpSocketManager.
 * 
 * @param host
 *            The host to connect to.
 * @param port
 *            The port on the host.
 * @param connectTimeoutMillis
 *            the connect timeout in milliseconds
 * @param reconnectDelayMillis
 *            The interval to pause between retries.
 * @param bufferSize
 *            The buffer size.
 * @return A TcpSocketManager.
 */
public static TcpSocketManager getSocketManager(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;
    }
    return (TcpSocketManager) getManager("TCP:" + host + ':' + port, new FactoryData(host, port,
            connectTimeoutMillis, reconnectDelayMillis, immediateFail, layout, bufferSize, socketOptions), FACTORY);
}
 
Example 3
Source File: PosixViewAttributeAction.java    From logging-log4j2 with Apache License 2.0 6 votes vote down vote up
@Override
public PosixViewAttributeAction build() {
    if (Strings.isEmpty(basePath)) {
        LOGGER.error("Posix file attribute view action not valid because base path is empty.");
        return null;
    }

    if (filePermissions == null && Strings.isEmpty(filePermissionsString)
                && Strings.isEmpty(fileOwner) && Strings.isEmpty(fileGroup)) {
        LOGGER.error("Posix file attribute view not valid because nor permissions, user or group defined.");
        return null;
    }

    if (!FileUtils.isFilePosixAttributeViewSupported()) {
        LOGGER.warn("Posix file attribute view defined but it is not supported by this files system.");
        return null;
    }

    return new PosixViewAttributeAction(basePath, followLinks, maxDepth, pathConditions,
            subst != null ? subst : configuration.getStrSubstitutor(),
            filePermissions != null ? filePermissions :
                        filePermissionsString != null ? PosixFilePermissions.fromString(filePermissionsString) : null,
            fileOwner,
            fileGroup);
}
 
Example 4
Source File: AbstractLogger.java    From logging-log4j2 with Apache License 2.0 6 votes vote down vote up
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));
}
 
Example 5
Source File: StackTraceElementAttributeConverter.java    From logging-log4j2 with Apache License 2.0 5 votes vote down vote up
@Override
public StackTraceElement convertToEntityAttribute(final String s) {
    if (Strings.isEmpty(s)) {
        return null;
    }

    return StackTraceElementAttributeConverter.convertString(s);
}
 
Example 6
Source File: ThrowableAttributeConverter.java    From logging-log4j2 with Apache License 2.0 5 votes vote down vote up
@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);
}
 
Example 7
Source File: StrMatcher.java    From logging-log4j2 with Apache License 2.0 5 votes vote down vote up
/**
 * 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);
}
 
Example 8
Source File: PropertiesConfigurationBuilder.java    From logging-log4j2 with Apache License 2.0 5 votes vote down vote up
private FilterComponentBuilder createFilter(final String key, final Properties properties) {
    final String type = (String) properties.remove(CONFIG_TYPE);
    if (Strings.isEmpty(type)) {
        throw new ConfigurationException("No type attribute provided for Appender " + key);
    }
    final String onMatch = (String) properties.remove(AbstractFilterBuilder.ATTR_ON_MATCH);
    final String onMismatch = (String) properties.remove(AbstractFilterBuilder.ATTR_ON_MISMATCH);
    final FilterComponentBuilder filterBuilder = builder.newFilter(type, onMatch, onMismatch);
    return processRemainingProperties(filterBuilder, properties);
}
 
Example 9
Source File: AuthenticationInterceptor.java    From moon-api-gateway with MIT License 5 votes vote down vote up
@Override
public boolean preHandler(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

    RequestInfo requestInfo = (RequestInfo) request.getAttribute(Constant.REQUEST_INFO_DATA);

    int appId = -1;
    String apiKey = apiKeyValidation(requestInfo.getQueryStringMap(), requestInfo.getHeaders());
    if (Strings.isNotEmpty(apiKey)) {
        if (apiExposeSpec.getAppDistinctionCache().containsKey(apiKey)) {
            appId = apiExposeSpec.getAppDistinctionCache().get(apiKey);
            requestInfo.setAppId(appId);
        }
    }

    if ( Strings.isEmpty(apiKey)  || appId < 0 ) {
        generateException(ExceptionType.E_1005_APIKEY_IS_INVALID);
        return false;
    }

    if (APIExposeSpecification.isEnabledIpAcl()) {
        if (!aclIpChecker.isAllowedPartnerAndIp(appId, requestInfo.getClientIp())) {
            generateException(ExceptionType.E_1010_IP_ADDRESS_IS_NOT_PERMITTED);
            return false;
        }
    }

    return true;
}
 
Example 10
Source File: NameUtil.java    From logging-log4j2 with Apache License 2.0 5 votes vote down vote up
public static String getSubName(final String name) {
    if (Strings.isEmpty(name)) {
        return null;
    }
    final int i = name.lastIndexOf('.');
    return i > 0 ? name.substring(0, i) : Strings.EMPTY;
}
 
Example 11
Source File: URIMethod.java    From WeCross with Apache License 2.0 5 votes vote down vote up
public boolean isResourceURI() {
    if (Strings.isEmpty(uri)) {
        return false;
    }

    // /network/stub/resource/method
    return uri.startsWith("/") && uri.substring(1).split("/").length == 4;
}
 
Example 12
Source File: ColumnConfig.java    From logging-log4j2 with Apache License 2.0 5 votes vote down vote up
@Override
public ColumnConfig build() {
    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(literal);

    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, literal, false, false, false);
    }

    if (isPattern) {
        final PatternLayout layout =
            PatternLayout.newBuilder()
                .setPattern(pattern)
                .setConfiguration(configuration)
                .setAlwaysWriteExceptions(false)
                .build();
        return new ColumnConfig(name, layout, null, false, isUnicode, isClob);
    }

    LOGGER.error("To configure a column you must specify a pattern or literal or set isEventDate to true.");
    return null;
}
 
Example 13
Source File: Category.java    From logging-log4j2 with Apache License 2.0 5 votes vote down vote up
private static  String getSubName(final String name) {
    if (Strings.isEmpty(name)) {
        return null;
    }
    final int i = name.lastIndexOf('.');
    return i > 0 ? name.substring(0, i) : Strings.EMPTY;
}
 
Example 14
Source File: LogSafeGson.java    From zstack with Apache License 2.0 5 votes vote down vote up
FieldNoLogging(Field field, NoLogging annotation, Class<?> senClz) {
    this.field = field;
    this.annotation = annotation;
    if (!Strings.isEmpty(annotation.classNameField())) {
        this.classNameField = FieldUtils.getField(annotation.classNameField(), senClz);
        if (this.classNameField != null) {
            this.classNameField.setAccessible(true);
        }
    }
}
 
Example 15
Source File: PropertiesConfigurationBuilder.java    From logging-log4j2 with Apache License 2.0 5 votes vote down vote up
private LoggerComponentBuilder createLogger(final String key, final Properties properties) {
    final String name = (String) properties.remove(CONFIG_NAME);
    final String location = (String) properties.remove("includeLocation");
    if (Strings.isEmpty(name)) {
        throw new ConfigurationException("No name attribute provided for Logger " + key);
    }
    final String level = Strings.trimToNull((String) properties.remove("level"));
    final String type = (String) properties.remove(CONFIG_TYPE);
    final LoggerComponentBuilder loggerBuilder;
    boolean includeLocation;
    if (type != null) {
        if (type.equalsIgnoreCase("asyncLogger")) {
            if (location != null) {
                includeLocation = Boolean.parseBoolean(location);
                loggerBuilder = builder.newAsyncLogger(name, level, includeLocation);
            } else {
                loggerBuilder = builder.newAsyncLogger(name, level);
            }
        } else {
            throw new ConfigurationException("Unknown Logger type " + type + " for Logger " + name);
        }
    } else {
        if (location != null) {
            includeLocation = Boolean.parseBoolean(location);
            loggerBuilder = builder.newLogger(name, level, includeLocation);
        } else {
            loggerBuilder = builder.newLogger(name, level);
        }
    }
    addLoggersToComponent(loggerBuilder, properties);
    addFiltersToComponent(loggerBuilder, properties);
    final String additivity = (String) properties.remove("additivity");
    if (!Strings.isEmpty(additivity)) {
        loggerBuilder.addAttribute("additivity", additivity);
    }
    return loggerBuilder;
}
 
Example 16
Source File: MongoDBUtil.java    From sockslib with Apache License 2.0 5 votes vote down vote up
private MongoClient getConnectedClient() {
  if (Strings.isEmpty(username)) {
    return new MongoClient(host, port);
  } else {
    MongoCredential credential =
        MongoCredential.createCredential(username, databaseName, password.toCharArray());
    return new MongoClient(new ServerAddress(host, port), Lists.newArrayList(credential));
  }
}
 
Example 17
Source File: PropertiesConfigurationBuilder.java    From logging-log4j2 with Apache License 2.0 5 votes vote down vote up
private static <B extends ComponentBuilder<B>> ComponentBuilder<B> createComponent(final ComponentBuilder<?> parent,
                                                                                   final String key,
                                                                                   final Properties properties) {
    final String name = (String) properties.remove(CONFIG_NAME);
    final String type = (String) properties.remove(CONFIG_TYPE);
    if (Strings.isEmpty(type)) {
        throw new ConfigurationException("No type attribute provided for component " + key);
    }
    final ComponentBuilder<B> componentBuilder = parent.getBuilder().newComponent(name, type);
    return processRemainingProperties(componentBuilder, properties);
}
 
Example 18
Source File: HtmlLayout.java    From logging-log4j2 with Apache License 2.0 4 votes vote down vote up
/**
 * Formats as a String.
 *
 * @param event The Logging Event.
 * @return A String containing the LogEvent as HTML.
 */
@Override
public String toSerializable(final LogEvent event) {
    final StringBuilder sbuf = getStringBuilder();

    sbuf.append(Strings.LINE_SEPARATOR).append("<tr>").append(Strings.LINE_SEPARATOR);

    sbuf.append("<td>");
    sbuf.append(event.getTimeMillis() - jvmStartTime);
    sbuf.append("</td>").append(Strings.LINE_SEPARATOR);

    final String escapedThread = Transform.escapeHtmlTags(event.getThreadName());
    sbuf.append("<td title=\"").append(escapedThread).append(" thread\">");
    sbuf.append(escapedThread);
    sbuf.append("</td>").append(Strings.LINE_SEPARATOR);

    sbuf.append("<td title=\"Level\">");
    if (event.getLevel().equals(Level.DEBUG)) {
        sbuf.append("<font color=\"#339933\">");
        sbuf.append(Transform.escapeHtmlTags(String.valueOf(event.getLevel())));
        sbuf.append("</font>");
    } else if (event.getLevel().isMoreSpecificThan(Level.WARN)) {
        sbuf.append("<font color=\"#993300\"><strong>");
        sbuf.append(Transform.escapeHtmlTags(String.valueOf(event.getLevel())));
        sbuf.append("</strong></font>");
    } else {
        sbuf.append(Transform.escapeHtmlTags(String.valueOf(event.getLevel())));
    }
    sbuf.append("</td>").append(Strings.LINE_SEPARATOR);

    String escapedLogger = Transform.escapeHtmlTags(event.getLoggerName());
    if (Strings.isEmpty(escapedLogger)) {
        escapedLogger = LoggerConfig.ROOT;
    }
    sbuf.append("<td title=\"").append(escapedLogger).append(" logger\">");
    sbuf.append(escapedLogger);
    sbuf.append("</td>").append(Strings.LINE_SEPARATOR);

    if (locationInfo) {
        final StackTraceElement element = event.getSource();
        sbuf.append("<td>");
        sbuf.append(Transform.escapeHtmlTags(element.getFileName()));
        sbuf.append(':');
        sbuf.append(element.getLineNumber());
        sbuf.append("</td>").append(Strings.LINE_SEPARATOR);
    }

    sbuf.append("<td title=\"Message\">");
    sbuf.append(Transform.escapeHtmlTags(event.getMessage().getFormattedMessage()).replaceAll(REGEXP, "<br />"));
    sbuf.append("</td>").append(Strings.LINE_SEPARATOR);
    sbuf.append("</tr>").append(Strings.LINE_SEPARATOR);

    if (event.getContextStack() != null && !event.getContextStack().isEmpty()) {
        sbuf.append("<tr><td bgcolor=\"#EEEEEE\" style=\"font-size : ").append(fontSize);
        sbuf.append(";\" colspan=\"6\" ");
        sbuf.append("title=\"Nested Diagnostic Context\">");
        sbuf.append("NDC: ").append(Transform.escapeHtmlTags(event.getContextStack().toString()));
        sbuf.append("</td></tr>").append(Strings.LINE_SEPARATOR);
    }

    if (event.getContextData() != null && !event.getContextData().isEmpty()) {
        sbuf.append("<tr><td bgcolor=\"#EEEEEE\" style=\"font-size : ").append(fontSize);
        sbuf.append(";\" colspan=\"6\" ");
        sbuf.append("title=\"Mapped Diagnostic Context\">");
        sbuf.append("MDC: ").append(Transform.escapeHtmlTags(event.getContextData().toMap().toString()));
        sbuf.append("</td></tr>").append(Strings.LINE_SEPARATOR);
    }

    final Throwable throwable = event.getThrown();
    if (throwable != null) {
        sbuf.append("<tr><td bgcolor=\"#993300\" style=\"color:White; font-size : ").append(fontSize);
        sbuf.append(";\" colspan=\"6\">");
        appendThrowableAsHtml(throwable, sbuf);
        sbuf.append("</td></tr>").append(Strings.LINE_SEPARATOR);
    }

    return sbuf.toString();
}
 
Example 19
Source File: LoggerConfig.java    From logging-log4j2 with Apache License 2.0 4 votes vote down vote up
@Override
public String toString() {
    return Strings.isEmpty(name) ? ROOT : name;
}
 
Example 20
Source File: Integers.java    From logging-log4j2 with Apache License 2.0 2 votes vote down vote up
/**
 * Parses the string argument as a signed decimal integer.
 *
 * @param s a {@code String} containing the {@code int} representation to parse, may be {@code null} or {@code ""}
 * @param defaultValue the return value, use {@code defaultValue} if {@code s} is {@code null} or {@code ""}
 * @return the integer value represented by the argument in decimal.
 * @throws NumberFormatException if the string does not contain a parsable integer.
 */
public static int parseInt(final String s, final int defaultValue) {
    return Strings.isEmpty(s) ? defaultValue : Integer.parseInt(s);
}