类org.apache.logging.log4j.util.ReadOnlyStringMap源码实例Demo

下面列出了怎么用org.apache.logging.log4j.util.ReadOnlyStringMap的API类实例代码及写法,或者点击链接到github查看源代码。

源代码1 项目: logging-log4j2   文件: CassandraManager.java
@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);
    }
}
 
@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);
    }
}
 
@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);
    }
}
 
@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);
}
 
源代码5 项目: logging-log4j2   文件: MdcPatternConverter.java
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('}');
}
 
源代码6 项目: logging-log4j2   文件: ColumnMapping.java
@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);
}
 
源代码7 项目: logging-log4j2   文件: ThreadContextMapFilter.java
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;
}
 
源代码8 项目: ambari-logsearch   文件: LogSearchJsonLayout.java
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);
}
 
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();
}
 
源代码10 项目: logging-log4j2   文件: OpenHashStringMap.java
/**
 * 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);
    }
}
 
源代码11 项目: logging-log4j2   文件: OpenHashStringMap.java
@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;
   }
 
源代码12 项目: logging-log4j2   文件: OpenHashStringMap.java
@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);
    }
}
 
@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);
}
 
源代码14 项目: logging-log4j2   文件: ContextDataSerializer.java
@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();
}
 
@Override
public String convertToDatabaseColumn(final ReadOnlyStringMap contextData) {
    if (contextData == null) {
        return null;
    }

    return contextData.toString();
}
 
@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);
}
 
源代码17 项目: logging-log4j2   文件: MdcPatternConverter.java
/**
 * {@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);
            }
        }
    }
}
 
源代码18 项目: logging-log4j2   文件: MdcPatternConverter.java
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('}');
    }
}
 
源代码19 项目: logging-log4j2   文件: ThreadContextDataInjector.java
@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);
}
 
源代码20 项目: logging-log4j2   文件: DynamicThresholdFilter.java
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;

}
 
源代码21 项目: logging-log4j2   文件: MapFilter.java
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;
}
 
源代码22 项目: curiostack   文件: RequestLoggingContextInjector.java
@Override
public ReadOnlyStringMap rawContextData() {
  return new JdkMapAdapaterStringMap(RequestLoggingContext.get());
}
 
源代码23 项目: curiostack   文件: RequestLoggingContextInjector.java
@Override
public void putAll(ReadOnlyStringMap source) {
  throw new UnsupportedOperationException();
}
 
源代码24 项目: log4j2-elasticsearch   文件: TestLogEventMixIn.java
@JsonIgnore
@Override
public abstract ReadOnlyStringMap getContextData();
 
@JsonIgnore
@Override
public abstract ReadOnlyStringMap getContextData();
 
源代码26 项目: log4j2-elasticsearch   文件: TestLogEventMixIn.java
@JsonIgnore
@Override
public abstract ReadOnlyStringMap getContextData();
 
@Override
public ReadOnlyStringMap rawContextData() {
  return ContextDataUtils.getContextAndTracingData();
}
 
@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());
}
 
@Override
protected StringMap createStringMap(final ReadOnlyStringMap original) {
    return new OpenHashStringMap<>(original);
}
 
@Override
protected StringMap createStringMap(final ReadOnlyStringMap original) {
    return new OpenHashStringMap<>(original);
}
 
 类所在包
 同包方法