Java Code Examples for org.apache.logging.log4j.util.ReadOnlyStringMap

The following examples show how to use org.apache.logging.log4j.util.ReadOnlyStringMap. These examples are extracted from open source projects. 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 Project: logging-log4j2   Source File: CassandraManager.java    License: Apache License 2.0 6 votes vote down vote up
@Override
protected void writeInternal(final LogEvent event, final Serializable serializable) {
    for (int i = 0; i < columnMappings.size(); i++) {
        final ColumnMapping columnMapping = columnMappings.get(i);
        if (ThreadContextMap.class.isAssignableFrom(columnMapping.getType())
            || ReadOnlyStringMap.class.isAssignableFrom(columnMapping.getType())) {
            values[i] = event.getContextData().toMap();
        } else if (ThreadContextStack.class.isAssignableFrom(columnMapping.getType())) {
            values[i] = event.getContextStack().asList();
        } else if (Date.class.isAssignableFrom(columnMapping.getType())) {
            values[i] = DateTypeConverter.fromMillis(event.getTimeMillis(), columnMapping.getType().asSubclass(Date.class));
        } else {
            values[i] = TypeConverters.convert(columnMapping.getLayout().toSerializable(event),
                columnMapping.getType(), null);
        }
    }
    final BoundStatement boundStatement = preparedStatement.bind(values);
    if (batchStatement == null) {
        session.execute(boundStatement);
    } else {
        batchStatement.add(boundStatement);
    }
}
 
Example 2
@Override
public String convertToDatabaseColumn(final ReadOnlyStringMap contextData) {
    if (contextData == null) {
        return null;
    }

    try {
        final JsonNodeFactory factory = OBJECT_MAPPER.getNodeFactory();
        final ObjectNode root = factory.objectNode();
        contextData.forEach(new BiConsumer<String, Object>() {
            @Override
            public void accept(final String key, final Object value) {
                // we will cheat here and write the toString of the Object... meh, but ok.
                root.put(key, String.valueOf(value));
            }
        });
        return OBJECT_MAPPER.writeValueAsString(root);
    } catch (final Exception e) {
        throw new PersistenceException("Failed to convert contextData to JSON string.", e);
    }
}
 
Example 3
@Override
public ReadOnlyStringMap convertToEntityAttribute(final String s) {
    if (Strings.isEmpty(s)) {
        return null;
    }
    try {
        final StringMap result = ContextDataFactory.createContextData();
        final ObjectNode root = (ObjectNode) OBJECT_MAPPER.readTree(s);
        final Iterator<Map.Entry<String, JsonNode>> entries = root.fields();
        while (entries.hasNext()) {
            final Map.Entry<String, JsonNode> entry = entries.next();

            // Don't know what to do with non-text values.
            // Maybe users who need this need to provide custom converter?
            final Object value = entry.getValue().textValue();
            result.putValue(entry.getKey(), value);
        }
        return result;
    } catch (final IOException e) {
        throw new PersistenceException("Failed to convert JSON string to map.", e);
    }
}
 
Example 4
@Test
public void testConvert02() {
    final StringMap map = new SortedArrayStringMap();
    map.putValue("someKey", "coolValue");
    map.putValue("anotherKey", "testValue");
    map.putValue("myKey", "yourValue");

    final String converted = this.converter.convertToDatabaseColumn(map);

    assertNotNull("The converted value should not be null.", converted);

    final ReadOnlyStringMap reversed = this.converter.convertToEntityAttribute(converted);

    assertNotNull("The reversed value should not be null.", reversed);
    assertEquals("The reversed value is not correct.", map, reversed);
}
 
Example 5
Source Project: logging-log4j2   Source File: MdcPatternConverter.java    License: Apache License 2.0 6 votes vote down vote up
private static void appendSelectedKeys(final String[] keys, final ReadOnlyStringMap contextData, final StringBuilder sb) {
    // Print all the keys in the array that have a value.
    final int start = sb.length();
    sb.append('{');
    for (int i = 0; i < keys.length; i++) {
        final String theKey = keys[i];
        final Object value = contextData.getValue(theKey);
        if (value != null) { // !contextData.containskey(theKey)
            if (sb.length() - start > 1) {
                sb.append(", ");
            }
            sb.append(theKey).append('=');
            StringBuilders.appendValue(sb, value);
        }
    }
    sb.append('}');
}
 
Example 6
Source Project: logging-log4j2   Source File: ColumnMapping.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public ColumnMapping build() {
    if (pattern != null) {
        layout = PatternLayout.newBuilder()
            .setPattern(pattern)
            .setConfiguration(configuration)
            .setAlwaysWriteExceptions(false)
            .build();
    }
    if (!(layout == null
        || literal == null
        || Date.class.isAssignableFrom(type)
        || ReadOnlyStringMap.class.isAssignableFrom(type)
        || ThreadContextMap.class.isAssignableFrom(type)
        || ThreadContextStack.class.isAssignableFrom(type))) {
        LOGGER.error("No 'layout' or 'literal' value specified and type ({}) is not compatible with ThreadContextMap, ThreadContextStack, or java.util.Date for the mapping", type, this);
        return null;
    }
    if (literal != null && parameter != null) {
        LOGGER.error("Only one of 'literal' or 'parameter' can be set on the column mapping {}", this);
        return null;
    }
    return new ColumnMapping(name, source, layout, literal, parameter, type);
}
 
Example 7
Source Project: logging-log4j2   Source File: ThreadContextMapFilter.java    License: Apache License 2.0 6 votes vote down vote up
private Result filter() {
    boolean match = false;
    if (useMap) {
        ReadOnlyStringMap currentContextData = null;
        final IndexedReadOnlyStringMap map = getStringMap();
        for (int i = 0; i < map.size(); i++) {
            if (currentContextData == null) {
                currentContextData = currentContextData();
            }
            final String toMatch = currentContextData.getValue(map.getKeyAt(i));
            match = toMatch != null && ((List<String>) map.getValueAt(i)).contains(toMatch);
            if ((!isAnd() && match) || (isAnd() && !match)) {
                break;
            }
        }
    } else {
        match = value.equals(currentContextData().getValue(key));
    }
    return match ? onMatch : onMismatch;
}
 
Example 8
Source Project: ambari-logsearch   Source File: LogSearchJsonLayout.java    License: Apache License 2.0 5 votes vote down vote up
public LogSearchJsonLayout(Charset charset) {
  super(charset);
  SimpleModule module = new SimpleModule();
  module.addSerializer(LogEvent.class, new LogEventSerializer());
  module.addSerializer(ReadOnlyStringMap.class, new ContextDataSerializer() {
  });
  objectMapper = new ObjectMapper();
  objectMapper.registerModule(module);
  objectMapper.setSerializationInclusion(JsonInclude.Include.NON_EMPTY);
}
 
Example 9
private Map<String, String> getCustomFieldsFromMdc(LogEvent event) {
	ReadOnlyStringMap contextData = event.getContextData();
	if (contextData == null || contextData.isEmpty()) {
		return Collections.emptyMap();
	}
	CustomFieldsMdcCollector mdcCollector = new CustomFieldsMdcCollector();
	contextData.forEach(mdcCollector);
	return mdcCollector.getCustomFields();
}
 
Example 10
Source Project: logging-log4j2   Source File: OpenHashStringMap.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Creates a new hash map copying a given type-specific one.
 *
 * @param contextData
 *            a type-specific map to be copied into the new hash map.
 * @param f
 *            the load factor.
 */
public OpenHashStringMap(final ReadOnlyStringMap contextData, final float f) {
    this(contextData.size(), f);
    if (contextData instanceof OpenHashStringMap) {
        initFrom0((OpenHashStringMap) contextData);
    } else {
        contextData.forEach(PUT_ALL, this);
    }
}
 
Example 11
Source Project: logging-log4j2   Source File: OpenHashStringMap.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public boolean equals(final Object obj) {
       if (obj == this) {
           return true;
       }
       if (!(obj instanceof ReadOnlyStringMap)) {
           return false;
       }
       final ReadOnlyStringMap other = (ReadOnlyStringMap) obj;
       if (other.size() != size()) {
           return false;
       }
       int pos = arraySize;
       if (containsNullKey) {
           if (!Objects.equals(getObjectValue(null), other.getValue(null))) {
               return false;
           }
       }
       --pos;
       final K myKeys[] = this.keys;
       for (; pos >= 0; pos--) {
           K k;
           if ((k = myKeys[pos]) != null) {
               if (!Objects.equals(values[pos], other.getValue((String) k))) {
                   return false;
               }
           }
       }
       return true;
   }
 
Example 12
Source Project: logging-log4j2   Source File: OpenHashStringMap.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void putAll(final ReadOnlyStringMap source) {
    assertNotFrozen();
    assertNoConcurrentModification();

    if (size() == 0 && source instanceof OpenHashStringMap) {
        initFrom0((OpenHashStringMap) source);
    } else if (source != null) {
        source.forEach(PUT_ALL, this);
    }
}
 
Example 13
@Override
public void serialize(final ReadOnlyStringMap contextData, final JsonGenerator jgen,
        final SerializerProvider provider) throws IOException, JsonGenerationException {

    final MapEntry[] pairs = createMapEntryArray(contextData.size());
    contextData.forEach(new BiConsumer<String, Object>() {
        int i = 0;

        @Override
        public void accept(final String key, final Object value) {
            pairs[i++] = createMapEntry(key, String.valueOf(value));
        }
    });
    jgen.writeObject(pairs);
}
 
Example 14
Source Project: logging-log4j2   Source File: ContextDataSerializer.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void serialize(final ReadOnlyStringMap contextData, final JsonGenerator jgen,
        final SerializerProvider provider) throws IOException, JsonGenerationException {

    jgen.writeStartObject();
    contextData.forEach(WRITE_STRING_FIELD_INTO, jgen);
    jgen.writeEndObject();
}
 
Example 15
@Override
public String convertToDatabaseColumn(final ReadOnlyStringMap contextData) {
    if (contextData == null) {
        return null;
    }

    return contextData.toString();
}
 
Example 16
@Test
public void testConvert01() {
    final StringMap map = new SortedArrayStringMap();
    map.putValue("test1", "another1");
    map.putValue("key2", "value2");

    final String converted = this.converter.convertToDatabaseColumn(map);

    assertNotNull("The converted value should not be null.", converted);

    final ReadOnlyStringMap reversed = this.converter.convertToEntityAttribute(converted);

    assertNotNull("The reversed value should not be null.", reversed);
    assertEquals("The reversed value is not correct.", map, reversed);
}
 
Example 17
Source Project: logging-log4j2   Source File: MdcPatternConverter.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
public void format(final LogEvent event, final StringBuilder toAppendTo) {
    final ReadOnlyStringMap contextData = event.getContextData();
    // if there is no additional options, we output every single
    // Key/Value pair for the MDC in a similar format to Hashtable.toString()
    if (full) {
        if (contextData == null || contextData.size() == 0) {
            toAppendTo.append("{}");
            return;
        }
        appendFully(contextData, toAppendTo);
    } else {
        if (keys != null) {
            if (contextData == null || contextData.size() == 0) {
                toAppendTo.append("{}");
                return;
            }
            appendSelectedKeys(keys, contextData, toAppendTo);
        } else if (contextData != null){
            // otherwise they just want a single key output
            final Object value = contextData.getValue(key);
            if (value != null) {
                StringBuilders.appendValue(toAppendTo, value);
            }
        }
    }
}
 
Example 18
Source Project: logging-log4j2   Source File: MdcPatternConverter.java    License: Apache License 2.0 5 votes vote down vote up
private static void appendFully(final ReadOnlyStringMap contextData, final StringBuilder toAppendTo) {
    toAppendTo.append("{");
    final int start = toAppendTo.length();
    contextData.forEach(WRITE_KEY_VALUES_INTO, toAppendTo);
    final int end = toAppendTo.length();
    if (end > start) {
        toAppendTo.setCharAt(end - 2, '}');
        toAppendTo.deleteCharAt(end - 1);
    } else {
        toAppendTo.append('}');
    }
}
 
Example 19
Source Project: logging-log4j2   Source File: ThreadContextDataInjector.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public ReadOnlyStringMap rawContextData() {
    final ReadOnlyThreadContextMap map = ThreadContext.getThreadContextMap();
    if (map instanceof ReadOnlyStringMap) {
        return (ReadOnlyStringMap) map;
    }
    // note: default ThreadContextMap is null
    final Map<String, String> copy = ThreadContext.getImmutableContext();
    return copy.isEmpty() ? ContextDataFactory.emptyFrozenContextData() : new JdkMapAdapterStringMap(copy);
}
 
Example 20
Source Project: logging-log4j2   Source File: DynamicThresholdFilter.java    License: Apache License 2.0 5 votes vote down vote up
private Result filter(final Level level, final ReadOnlyStringMap contextMap) {
    final String value = contextMap.getValue(key);
    if (value != null) {
        Level ctxLevel = levelMap.get(value);
        if (ctxLevel == null) {
            ctxLevel = defaultThreshold;
        }
        return level.isMoreSpecificThan(ctxLevel) ? onMatch : onMismatch;
    }
    return Result.NEUTRAL;

}
 
Example 21
Source Project: logging-log4j2   Source File: MapFilter.java    License: Apache License 2.0 5 votes vote down vote up
protected boolean filter(final ReadOnlyStringMap data) {
    boolean match = false;
    for (int i = 0; i < map.size(); i++) {
        final String toMatch = data.getValue(map.getKeyAt(i));
        match = toMatch != null && ((List<String>) map.getValueAt(i)).contains(toMatch);

        if ((!isAnd && match) || (isAnd && !match)) {
            break;
        }
    }
    return match;
}
 
Example 22
Source Project: curiostack   Source File: RequestLoggingContextInjector.java    License: MIT License 4 votes vote down vote up
@Override
public ReadOnlyStringMap rawContextData() {
  return new JdkMapAdapaterStringMap(RequestLoggingContext.get());
}
 
Example 23
Source Project: curiostack   Source File: RequestLoggingContextInjector.java    License: MIT License 4 votes vote down vote up
@Override
public void putAll(ReadOnlyStringMap source) {
  throw new UnsupportedOperationException();
}
 
Example 24
Source Project: log4j2-elasticsearch   Source File: TestLogEventMixIn.java    License: Apache License 2.0 4 votes vote down vote up
@JsonIgnore
@Override
public abstract ReadOnlyStringMap getContextData();
 
Example 25
@JsonIgnore
@Override
public abstract ReadOnlyStringMap getContextData();
 
Example 26
Source Project: log4j2-elasticsearch   Source File: TestLogEventMixIn.java    License: Apache License 2.0 4 votes vote down vote up
@JsonIgnore
@Override
public abstract ReadOnlyStringMap getContextData();
 
Example 27
@Override
public ReadOnlyStringMap rawContextData() {
  return ContextDataUtils.getContextAndTracingData();
}
 
Example 28
@Override
public void append(LogEvent event) {
    List<Object> args = new ArrayList<>();

    args.add(buildFormattedMessage(event));

    args.add("PRIORITY=%d");
    args.add(Integer.valueOf(log4jLevelToJournalPriority(event.getLevel())));

    if (logThreadName) {
        args.add("THREAD_NAME=%s");
        args.add(event.getThreadName());
    }

    if (logLoggerName) {
        args.add("LOG4J_LOGGER=%s");
        args.add(event.getLoggerName());
    }

    if (logAppenderName) {
        args.add("LOG4J_APPENDER=%s");
        args.add(getName());
    }

    if (logStacktrace && event.getThrown() != null) {
        StringWriter stacktrace = new StringWriter();
        event.getThrown().printStackTrace(new PrintWriter(stacktrace));
        args.add("STACKTRACE=%s");
        args.add(stacktrace.toString());
    }

    if (logSource && event.getSource() != null) {
        String fileName = event.getSource().getFileName();
        args.add("CODE_FILE=%s");
        args.add(fileName);

        String methodName = event.getSource().getMethodName();
        args.add("CODE_FUNC=%s");
        args.add(methodName);

        int lineNumber = event.getSource().getLineNumber();
        args.add("CODE_LINE=%d");
        args.add(Integer.valueOf(lineNumber));
    }

    if (logThreadContext) {
        ReadOnlyStringMap context = event.getContextData();
        if (context != null) {
            for (Entry<String, String> entry : context.toMap().entrySet()) {
                String key = entry.getKey();
                args.add(threadContextPrefix + normalizeKey(key) + "=%s");
                args.add(entry.getValue());
            }
        }
    }

    if (syslogIdentifier != null && !syslogIdentifier.isEmpty()) {
        args.add("SYSLOG_IDENTIFIER=%s");
        args.add(syslogIdentifier);
    }

    if (syslogFacility != null && !syslogFacility.isEmpty()) {
        args.add("SYSLOG_FACILITY=%d");
        args.add(Integer.valueOf(syslogFacility));
    }

    args.add(null); // null terminated

    journalLibrary.sd_journal_send("MESSAGE=%s", args.toArray());
}
 
Example 29
@Override
protected StringMap createStringMap(final ReadOnlyStringMap original) {
    return new OpenHashStringMap<>(original);
}
 
Example 30
@Override
protected StringMap createStringMap(final ReadOnlyStringMap original) {
    return new OpenHashStringMap<>(original);
}