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

The following examples show how to use org.apache.logging.log4j.util.Strings#isNotEmpty() . 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: PluginValueInjector.java    From logging-log4j2 with Apache License 2.0 6 votes vote down vote up
@Override
public void inject(final Object factory) {
    final String elementValue = node.getValue();
    final String attributeValue = node.getAttributes().get(name);
    String rawValue = null; // if neither is specified, return null (LOG4J2-1313)
    if (Strings.isNotEmpty(elementValue)) {
        if (Strings.isNotEmpty(attributeValue)) {
            LOGGER.error("Configuration contains {} with both attribute value ({}) AND element" +
                            " value ({}). Please specify only one value. Using the element value.",
                    node.getName(), attributeValue, elementValue);
        }
        rawValue = elementValue;
    } else {
        rawValue = findAndRemoveNodeAttribute().orElse(null);
    }
    final String value = stringSubstitutionStrategy.apply(rawValue);
    StringBuilders.appendKeyDqValue(debugLog, name, value);
    configurationBinder.bindString(factory, value);
}
 
Example 2
Source File: KVMHost.java    From zstack with Apache License 2.0 6 votes vote down vote up
private void handle(GetKVMHostDownloadCredentialMsg msg) {
    final GetKVMHostDownloadCredentialReply reply = new GetKVMHostDownloadCredentialReply();

    String key = asf.getPrivateKey();

    String hostname = null;
    if (Strings.isNotEmpty(msg.getDataNetworkCidr())) {
        String dataNetworkAddress = getDataNetworkAddress(self.getUuid(), msg.getDataNetworkCidr());

        if (dataNetworkAddress != null) {
            hostname = dataNetworkAddress;
        }
    }

    reply.setHostname(hostname == null ? getSelf().getManagementIp() : hostname);
    reply.setUsername(getSelf().getUsername());
    reply.setSshPort(getSelf().getPort());
    reply.setSshKey(key);
    bus.reply(msg, reply);
}
 
Example 3
Source File: Rfc5424Layout.java    From logging-log4j2 with Apache License 2.0 5 votes vote down vote up
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;
}
 
Example 4
Source File: GelfLogField.java    From xian with Apache License 2.0 5 votes vote down vote up
@PluginFactory
public static GelfLogField createField(@PluginConfiguration final Configuration config,
        @PluginAttribute("name") String name, @PluginAttribute("literal") String literalValue,
        @PluginAttribute("mdc") String mdc, @PluginAttribute("pattern") String pattern) {

    final boolean isPattern = Strings.isNotEmpty(pattern);
    final boolean isLiteralValue = Strings.isNotEmpty(literalValue);
    final boolean isMDC = Strings.isNotEmpty(mdc);

    if (Strings.isEmpty(name)) {
        LOGGER.error("The name is empty");
        return null;
    }

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

    if (isPattern) {

        PatternLayout patternLayout = newBuilder().withPattern(pattern).withConfiguration(config)
                .withNoConsoleNoAnsi(false).withAlwaysWriteExceptions(false).build();

        return new GelfLogField(name, null, null, patternLayout);
    }

    return new GelfLogField(name, literalValue, mdc, null);
}
 
Example 5
Source File: GelfLogAppender.java    From xian with Apache License 2.0 5 votes vote down vote up
/**
 * Configure fields (literals, MDC, layout).
 *
 * @param mdcGelfMessageAssembler the assembler
 * @param knownFields             static field array
 * @param dynamicFieldArray       dynamic field array
 */
private static void configureFields(MdcGelfMessageAssembler mdcGelfMessageAssembler,
                                    GelfLogField[] knownFields,
                                    GelfDynamicMdcLogFields[] dynamicFieldArray) {

    if (knownFields == null || knownFields.length == 0) {
        mdcGelfMessageAssembler.addFields(LogMessageField.getDefaultMapping(Time, Severity, ThreadName, SourceClassName,
                SourceMethodName, SourceLineNumber, SourceSimpleClassName, LoggerName, Marker));
        return;
    }

    for (GelfLogField field : knownFields) {

        if (Strings.isNotEmpty(field.getMdc())) {
            mdcGelfMessageAssembler.addField(new MdcMessageField(field.getName(), field.getMdc()));
        }

        if (Strings.isNotEmpty(field.getLiteral())) {
            mdcGelfMessageAssembler.addField(new StaticMessageField(field.getName(), field.getLiteral()));
        }

        if (field.getPatternLayout() != null) {
            mdcGelfMessageAssembler.addField(new PatternLogMessageField(field.getName(), null, field.getPatternLayout()));
        }
    }

    if (dynamicFieldArray != null) {
        for (GelfDynamicMdcLogFields gelfDynamicMdcLogFields : dynamicFieldArray) {
            mdcGelfMessageAssembler.addField(new DynamicMdcMessageField(gelfDynamicMdcLogFields.getRegex()));
        }
    }
}
 
Example 6
Source File: DynamicEntityMeta.java    From we-cmdb with Apache License 2.0 5 votes vote down vote up
public String getName() {
    if(Strings.isNotEmpty(name)){
        return name;
    }else{
        return tableName;
    }
}
 
Example 7
Source File: ExceptionAdvice.java    From moon-api-gateway with MIT License 5 votes vote down vote up
@ExceptionHandler(GeneralException.class)
public ResponseEntity generalException(GeneralException e, HttpServletRequest request) {
    log.error("{}", getStackTrace(e));
    ExceptionType exceptionType = e.getExceptionType();
    setHttpResponseErrorCode(request, exceptionType.getCode());
    String message = messageManager.getProperty(exceptionType.getCode());
    if (Strings.isNotEmpty(e.getMessage())) message = String.format("%s %s", message, e.getMessage());
    CommonResponseEntity response = CommonResponseEntity.generateException(e.getExceptionType().getCode(), message);
    return HttpHelper.newResponseEntityWithId(e.getExceptionType().getHttpStatus(), response);
}
 
Example 8
Source File: ConfigurationFactory.java    From logging-log4j2 with Apache License 2.0 5 votes vote down vote up
private Configuration getConfiguration(final LoggerContext loggerContext, final boolean isTest, final String name) {
    final boolean named = Strings.isNotEmpty(name);
    final ClassLoader loader = LoaderUtil.getThreadContextClassLoader();
    for (final ConfigurationFactory factory : getFactories()) {
        String configName;
        final String prefix = isTest ? factory.getTestPrefix() : factory.getDefaultPrefix();
        final String [] types = factory.getSupportedTypes();
        if (types == null) {
            continue;
        }

        for (final String suffix : types) {
            if (suffix.equals(ALL_TYPES)) {
                continue;
            }
            configName = named ? prefix + name + suffix : prefix + suffix;

            final ConfigurationSource source = ConfigurationSource.fromResource(configName, loader);
            if (source != null) {
                if (!factory.isActive()) {
                    LOGGER.warn("Found configuration file {} for inactive ConfigurationFactory {}", configName, factory.getClass().getName());
                }
                return factory.getConfiguration(loggerContext, source);
            }
        }
    }
    return null;
}
 
Example 9
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 10
Source File: SdxRepairSettings.java    From cloudbreak with Apache License 2.0 5 votes vote down vote up
public static SdxRepairSettings from(SdxRepairRequest request) {
    if (StringUtils.isNotBlank(request.getHostGroupName()) && CollectionUtils.isNotEmpty(request.getHostGroupNames())) {
        throw new BadRequestException("Please send only one hostGroupName in the 'hostGroupName' field " +
                "or multiple hostGroups in the 'hostGroupNames' fields");
    }
    SdxRepairSettings settings = new SdxRepairSettings();
    if (Strings.isNotEmpty(request.getHostGroupName())) {
        settings.hostGroupNames = List.of(request.getHostGroupName());
    } else {
        settings.hostGroupNames = request.getHostGroupNames();
    }
    return settings;
}
 
Example 11
Source File: DatabasePauseSupportService.java    From cloudbreak with Apache License 2.0 5 votes vote down vote up
public boolean isDatabasePauseSupported(SdxCluster sdxCluster) {
    if (sdxCluster.hasExternalDatabase() && Strings.isNotEmpty(sdxCluster.getDatabaseCrn())) {
        DetailedEnvironmentResponse environment = environmentClientService.getByCrn(sdxCluster.getEnvCrn());

        return platformConfig.isExternalDatabasePauseSupportedFor(CloudPlatform.valueOf(environment.getCloudPlatform()));
    }
    return false;
}
 
Example 12
Source File: JeroMqAppender.java    From logging-log4j2 with Apache License 2.0 4 votes vote down vote up
@PluginFactory
public static JeroMqAppender createAppender(
        // @formatter:off
        @Required(message = "No name provided for JeroMqAppender") @PluginAttribute final String name,
        @PluginElement Layout<?> layout,
        @PluginElement final Filter filter,
        @PluginElement final Property[] properties,
        // Super attributes
        @PluginAttribute final boolean ignoreExceptions,
        // ZMQ attributes; defaults picked from zmq.Options.
        @PluginAttribute(defaultLong = 0) final long affinity,
        @PluginAttribute(defaultLong = DEFAULT_BACKLOG) final long backlog,
        @PluginAttribute final boolean delayAttachOnConnect,
        @PluginAttribute final byte[] identity,
        @PluginAttribute(defaultBoolean = true) final boolean ipv4Only,
        @PluginAttribute(defaultLong = -1) final long linger,
        @PluginAttribute(defaultLong = -1) final long maxMsgSize,
        @PluginAttribute(defaultLong = DEFAULT_RCV_HWM) final long rcvHwm,
        @PluginAttribute(defaultLong = 0) final long receiveBufferSize,
        @PluginAttribute(defaultLong = -1) final int receiveTimeOut,
        @PluginAttribute(defaultLong = DEFAULT_IVL) final long reconnectIVL,
        @PluginAttribute(defaultLong = 0) final long reconnectIVLMax,
        @PluginAttribute(defaultLong = 0) final long sendBufferSize,
        @PluginAttribute(defaultLong = -1) final int sendTimeOut,
        @PluginAttribute(defaultLong = DEFAULT_SND_HWM) final long sndHwm,
        @PluginAttribute(defaultInt = -1) final int tcpKeepAlive,
        @PluginAttribute(defaultLong = -1) final long tcpKeepAliveCount,
        @PluginAttribute(defaultLong = -1) final long tcpKeepAliveIdle,
        @PluginAttribute(defaultLong = -1) final long tcpKeepAliveInterval,
        @PluginAttribute final boolean xpubVerbose
        // @formatter:on
) {
    if (layout == null) {
        layout = PatternLayout.createDefaultLayout();
    }
    List<String> endpoints;
    if (properties == null) {
        endpoints = new ArrayList<>(0);
    } else {
        endpoints = new ArrayList<>(properties.length);
        for (final Property property : properties) {
            if ("endpoint".equalsIgnoreCase(property.getName())) {
                final String value = property.getValue();
                if (Strings.isNotEmpty(value)) {
                    endpoints.add(value);
                }
            }
        }
    }
    LOGGER.debug("Creating JeroMqAppender with name={}, filter={}, layout={}, ignoreExceptions={}, endpoints={}",
            name, filter, layout, ignoreExceptions, endpoints);
    return new JeroMqAppender(name, filter, layout, ignoreExceptions, endpoints, affinity, backlog,
            delayAttachOnConnect, identity, ipv4Only, linger, maxMsgSize, rcvHwm, receiveBufferSize,
            receiveTimeOut, reconnectIVL, reconnectIVLMax, sendBufferSize, sendTimeOut, sndHwm, tcpKeepAlive,
            tcpKeepAliveCount, tcpKeepAliveIdle, tcpKeepAliveInterval, xpubVerbose, Property.EMPTY_ARRAY);
}
 
Example 13
Source File: SimpleLogger.java    From logging-log4j2 with Apache License 2.0 4 votes vote down vote up
@Override
public void logMessage(final String fqcn, final Level mgsLevel, final Marker marker, final Message msg,
        final Throwable throwable) {
    final StringBuilder sb = new StringBuilder();
    // Append date-time if so configured
    if (showDateTime) {
        final Date now = new Date();
        String dateText;
        synchronized (dateFormatter) {
            dateText = dateFormatter.format(now);
        }
        sb.append(dateText);
        sb.append(SPACE);
    }

    sb.append(mgsLevel.toString());
    sb.append(SPACE);
    if (Strings.isNotEmpty(logName)) {
        sb.append(logName);
        sb.append(SPACE);
    }
    sb.append(msg.getFormattedMessage());
    if (showContextMap) {
        final Map<String, String> mdc = ThreadContext.getImmutableContext();
        if (mdc.size() > 0) {
            sb.append(SPACE);
            sb.append(mdc.toString());
            sb.append(SPACE);
        }
    }
    final Object[] params = msg.getParameters();
    Throwable t;
    if (throwable == null && params != null && params.length > 0
            && params[params.length - 1] instanceof Throwable) {
        t = (Throwable) params[params.length - 1];
    } else {
        t = throwable;
    }
    stream.println(sb.toString());
    if (t != null) {
        stream.print(SPACE);
        t.printStackTrace(stream);
    }
}
 
Example 14
Source File: DatabaseService.java    From cloudbreak with Apache License 2.0 4 votes vote down vote up
private boolean dbHasBeenCreatedPreviously(SdxCluster sdxCluster) {
    return Strings.isNotEmpty(sdxCluster.getDatabaseCrn());
}
 
Example 15
Source File: ElasticsearchResource.java    From vertexium with Apache License 2.0 4 votes vote down vote up
private boolean shouldUseRemoteElasticsearch() {
    return Strings.isNotEmpty(getRemoteEsAddresses());
}
 
Example 16
Source File: ElasticsearchResource.java    From vertexium with Apache License 2.0 4 votes vote down vote up
private boolean shouldUseRemoteElasticsearch() {
    return Strings.isNotEmpty(getRemoteEsAddresses());
}
 
Example 17
Source File: ProxyServiceImpl.java    From moon-api-gateway with MIT License 4 votes vote down vote up
/**
 * Create a new request object based on the variables created in prepareProxyInterceptor.
 *
 * Determine the request Method.
 * Inject the header and query param into the new request object.
 * It also injects the body sent by the client into a byte array.
 *
 * @param request This is a client request.
 * @param responseInfo It is an object created by prepareProxyInterceptor. Contains the header, query, and body required for the proxy.
 * @return a new request object that is completely different from client request. This will request an api for the outbound service.
 */

private static Request setHeaderAndQueryInfo(Request request, ResponseInfo responseInfo) {
    Map<String, String> requestHeaders = responseInfo.getHeaders();

    requestHeaders.forEach(request::header);

    request.method(responseInfo.getRequestMethod());
    request.accept(responseInfo.getRequestAccept());

    if (Strings.isNotEmpty(responseInfo.getRequestContentType()) && Objects.nonNull(responseInfo.getRequestBody())) {
        request.content(new BytesContentProvider(responseInfo.getRequestBody()), responseInfo.getRequestContentType());
    }

    Map<String, String> requestQueryParams = responseInfo.getQueryStringMap();
    requestQueryParams.forEach(request::param);

    return request;
}
 
Example 18
Source File: RedisClusterRepository.java    From moon-api-gateway with MIT License 4 votes vote down vote up
@Override
public ServiceInfo getServiceInfo(int serviceId) {
    String serviceInfoInString = hget(Constant.REDIS_KEY_INTERNAL_SERVICE_INFO, String.valueOf(serviceId));
    if (Strings.isNotEmpty(serviceInfoInString)) return JsonUtil.fromJson(serviceInfoInString, ServiceInfo.class);
    else throw new GeneralException(ExceptionType.E_1004_RESOURCE_NOT_FOUND);
}
 
Example 19
Source File: RedisClusterRepository.java    From moon-api-gateway with MIT License 4 votes vote down vote up
@Override
public AppInfo getAppInfo(int appId) {
    String appInfoInString = hget(Constant.REDIS_KEY_INTERNAL_APP_INFO, String.valueOf(appId));
    if (Strings.isNotEmpty(appInfoInString)) return JsonUtil.fromJson(appInfoInString, AppInfo.class);
    else throw new GeneralException(ExceptionType.E_1004_RESOURCE_NOT_FOUND);
}
 
Example 20
Source File: ThrowableFormatOptions.java    From logging-log4j2 with Apache License 2.0 4 votes vote down vote up
/**
 * Creates a new instance based on the array of options.
 *
 * @param options
 *            The array of options.
 * @return A new initialized instance.
 */
public static ThrowableFormatOptions newInstance(String[] options) {
    if (options == null || options.length == 0) {
        return DEFAULT;
    }
    // NOTE: The following code is present for backward compatibility
    // and was copied from Extended/RootThrowablePatternConverter.
    // This supports a single option with the format:
    // %xEx{["none"|"short"|"full"|depth],[filters(packages)}
    // However, the convention for multiple options should be:
    // %xEx{["none"|"short"|"full"|depth]}[{filters(packages)}]
    if (options.length == 1 && Strings.isNotEmpty(options[0])) {
        final String[] opts = options[0].split(Patterns.COMMA_SEPARATOR, 2);
        final String first = opts[0].trim();
        try (final Scanner scanner = new Scanner(first)) {
            if (opts.length > 1 && (first.equalsIgnoreCase(FULL) || first.equalsIgnoreCase(SHORT)
                    || first.equalsIgnoreCase(NONE) || scanner.hasNextInt())) {
                options = new String[] { first, opts[1].trim() };
            }
        }
    }

    int lines = DEFAULT.lines;
    String separator = DEFAULT.separator;
    List<String> packages = DEFAULT.ignorePackages;
    TextRenderer ansiRenderer = DEFAULT.textRenderer;
    String suffix = DEFAULT.getSuffix();
    for (final String rawOption : options) {
        if (rawOption != null) {
            final String option = rawOption.trim();
            if (option.isEmpty()) {
                // continue;
            } else if (option.startsWith("separator(") && option.endsWith(")")) {
                separator = option.substring("separator(".length(), option.length() - 1);
            } else if (option.startsWith("filters(") && option.endsWith(")")) {
                final String filterStr = option.substring("filters(".length(), option.length() - 1);
                if (filterStr.length() > 0) {
                    final String[] array = filterStr.split(Patterns.COMMA_SEPARATOR);
                    if (array.length > 0) {
                        packages = new ArrayList<>(array.length);
                        for (String token : array) {
                            token = token.trim();
                            if (token.length() > 0) {
                                packages.add(token);
                            }
                        }
                    }
                }
            } else if (option.equalsIgnoreCase(NONE)) {
                lines = 0;
            } else if (option.equalsIgnoreCase(SHORT) || option.equalsIgnoreCase(CLASS_NAME)
                    || option.equalsIgnoreCase(METHOD_NAME) || option.equalsIgnoreCase(LINE_NUMBER)
                    || option.equalsIgnoreCase(FILE_NAME) || option.equalsIgnoreCase(MESSAGE)
                    || option.equalsIgnoreCase(LOCALIZED_MESSAGE)) {
                lines = 2;
            } else if (option.startsWith("ansi(") && option.endsWith(")") || option.equals("ansi")) {
                if (Loader.isJansiAvailable()) {
                    final String styleMapStr = option.equals("ansi") ? Strings.EMPTY
                            : option.substring("ansi(".length(), option.length() - 1);
                    ansiRenderer = new JAnsiTextRenderer(new String[] { null, styleMapStr },
                            JAnsiTextRenderer.DefaultExceptionStyleMap);
                } else {
                    StatusLogger.getLogger().warn(
                            "You requested ANSI exception rendering but JANSI is not on the classpath. Please see https://logging.apache.org/log4j/2.x/runtime-dependencies.html");
                }
            } else if (option.startsWith("S(") && option.endsWith(")")){
                suffix = option.substring("S(".length(), option.length() - 1);
            } else if (option.startsWith("suffix(") && option.endsWith(")")){
                suffix = option.substring("suffix(".length(), option.length() - 1);
            } else if (!option.equalsIgnoreCase(FULL)) {
                lines = Integer.parseInt(option);
            }
        }
    }
    return new ThrowableFormatOptions(lines, separator, packages, ansiRenderer, suffix);
}