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

The following examples show how to use org.apache.logging.log4j.util.SortedArrayStringMap. 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
@Test
public void insertConfigurationProperties() {
  assertThat(
          new OpenCensusTraceContextDataInjector()
              .injectContextData(
                  Lists.newArrayList(
                      Property.createProperty("property1", "value1"),
                      Property.createProperty("property2", "value2")),
                  new SortedArrayStringMap())
              .toMap())
      .containsExactly(
          "property1",
          "value1",
          "property2",
          "value2",
          "traceId",
          "00000000000000000000000000000000",
          "spanId",
          "0000000000000000",
          "traceSampled",
          "false");
}
 
Example 2
@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 3
@Test
public void emptyMdcAndArguments() throws Exception {
	StringBuilder sb = new StringBuilder();
	when(event.getContextData()).thenReturn(new SortedArrayStringMap());
	when(event.getMessage().getParameters()).thenReturn(NO_PARAMETERS);

	converter.format(event, sb);

	verifyConverterCall(emptyMap());
}
 
Example 4
@Test
public void standardArgument() throws Exception {
	StringBuilder sb = new StringBuilder();
	when(event.getContextData()).thenReturn(new SortedArrayStringMap());
	when(event.getMessage().getParameters()).thenReturn(new Object[] { "standard argument" });

	converter.format(event, sb);

	verifyConverterCall(emptyMap(), is("standard argument"));
}
 
Example 5
@Test
public void singleCustomFieldArgument() throws Exception {
	StringBuilder sb = new StringBuilder();
	when(event.getContextData()).thenReturn(new SortedArrayStringMap());
	CustomField customField = customField("some key", "some value");
	when(event.getMessage().getParameters()).thenReturn(new Object[] { customField });

	converter.format(event, sb);

	verifyConverterCall(emptyMap(), is(sameInstance(customField)));
}
 
Example 6
@Test
public void mdcFields() throws Exception {
	StringBuilder sb = new StringBuilder();
	when(event.getContextData()).thenReturn(new SortedArrayStringMap(MDC_PROPERTIES));
	when(event.getMessage().getParameters()).thenReturn(NO_PARAMETERS);

	converter.format(event, sb);

	verifyConverterCall(allOf(hasEntry("this key", "this value"), hasEntry("that key", "that value"),
			not(hasEntry("other key", "other value"))));
}
 
Example 7
@Test
public void mergesMdcFieldsAndArguments() throws Exception {
	StringBuilder sb = new StringBuilder();
	when(event.getContextData()).thenReturn(new SortedArrayStringMap(MDC_PROPERTIES));
	CustomField customField = customField("some key", "some value");
	when(event.getMessage().getParameters()).thenReturn(new Object[] { customField });

	converter.format(event, sb);

	verifyConverterCall(allOf(hasEntry("this key", "this value"), hasEntry("that key", "that value"),
			not(hasEntry("other key", "other value"))), is(sameInstance(customField)));

}
 
Example 8
@Setup
public void setup() {
    openHashMapContextData = new OpenHashStringMap<>();
    sortedStringArrayMap = new SortedArrayStringMap();
    map = new HashMap<>();

    keys = new String[count];
    final Random r = new Random();
    for (int j = 0; j < keys.length; j++) {
        final char[] str = new char[length];
        for (int i = 0; i < str.length; i++) {
            str[i] = (char) r.nextInt();
        }
        keys[j] = new String(str);
    }

    populatedMap = new HashMap<>();
    for (int i = 0; i < count; i++) {
        populatedMap.put(keys[i], value);
    }
    populatedSortedStringArrayMap = new SortedArrayStringMap();
    for (int i = 0; i < count; i++) {
        populatedSortedStringArrayMap.putValue(keys[i], value);
    }
    populatedOpenHashContextData = new OpenHashStringMap<>();
    for (int i = 0; i < count; i++) {
        populatedOpenHashContextData.putValue(keys[i], value);
    }
}
 
Example 9
Source Project: logging-log4j2   Source File: JsonWriterTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void test_writeObject_IndexedReadOnlyStringMap() {
    final IndexedReadOnlyStringMap map =
            new SortedArrayStringMap(new LinkedHashMap<String, Object>() {{
                put("buzz", 1.2D);
                put("foo", "bar");
            }});
    final String expectedJson = "{'buzz':1.2,'foo':'bar'}".replace('\'', '"');
    final String actualJson = WRITER.use(() -> WRITER.writeObject(map));
    Assertions.assertThat(actualJson).isEqualTo(expectedJson);
}
 
Example 10
@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 11
@Test
public void testConvertToDatabaseColumn01() {
    final StringMap map = new SortedArrayStringMap();
    map.putValue("test1", "another1");
    map.putValue("key2", "value2");

    assertEquals("The converted value is not correct.", map.toString(),
            this.converter.convertToDatabaseColumn(map));
}
 
Example 12
@Test
public void testConvertToDatabaseColumn02() {
    final StringMap map = new SortedArrayStringMap();
    map.putValue("someKey", "coolValue");
    map.putValue("anotherKey", "testValue");
    map.putValue("myKey", "yourValue");

    assertEquals("The converted value is not correct.", map.toString(),
            this.converter.convertToDatabaseColumn(map));
}
 
Example 13
Source Project: logging-log4j2   Source File: MDCContextMap.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public StringMap getReadOnlyContextData() {
    final Map<String, String> copy = getCopy();
    if (copy.isEmpty()) {
        return EMPTY_CONTEXT_DATA;
    }
    final StringMap result = new SortedArrayStringMap();
    for (final Entry<String, String> entry : copy.entrySet()) {
        result.putValue(entry.getKey(), entry.getValue());
    }
    return result;
}
 
Example 14
Source Project: logging-log4j2   Source File: ContextDataFactory.java    License: Apache License 2.0 5 votes vote down vote up
public static StringMap createContextData() {
    if (DEFAULT_CONSTRUCTOR == null) {
        return new SortedArrayStringMap();
    }
    try {
        return (IndexedStringMap) DEFAULT_CONSTRUCTOR.newInstance();
    } catch (final Throwable ignored) {
        return new SortedArrayStringMap();
    }
}
 
Example 15
Source Project: logging-log4j2   Source File: ContextDataFactory.java    License: Apache License 2.0 5 votes vote down vote up
public static StringMap createContextData(final int initialCapacity) {
    if (INITIAL_CAPACITY_CONSTRUCTOR == null) {
        return new SortedArrayStringMap(initialCapacity);
    }
    try {
        return (IndexedStringMap) INITIAL_CAPACITY_CONSTRUCTOR.newInstance(initialCapacity);
    } catch (final Throwable ignored) {
        return new SortedArrayStringMap(initialCapacity);
    }
}
 
Example 16
Source Project: logging-log4j2   Source File: MapFilter.java    License: Apache License 2.0 5 votes vote down vote up
protected MapFilter(final Map<String, List<String>> map, final boolean oper, final Result onMatch, final Result onMismatch) {
    super(onMatch, onMismatch);
    this.isAnd = oper;
    Objects.requireNonNull(map, "map cannot be null");

    this.map = new SortedArrayStringMap(map.size());
    for (final Map.Entry<String, List<String>> entry : map.entrySet()) {
        this.map.putValue(entry.getKey(), entry.getValue());
    }
}
 
Example 17
Source Project: logging-log4j2   Source File: ContextDataFactoryTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void intArgSetsCapacityIfNoPropertySpecified() throws Exception {
    final SortedArrayStringMap actual = (SortedArrayStringMap) ContextDataFactory.createContextData(2);
    final Field thresholdField = SortedArrayStringMap.class.getDeclaredField("threshold");
    thresholdField.setAccessible(true);
    assertEquals(2, thresholdField.getInt(actual));
}
 
Example 18
@Test
public void intArgReturnsSortedArrayStringMapIfPropertySpecifiedButMissingIntConstructor() throws Exception {
    System.setProperty("log4j2.ContextData", FactoryTestStringMapWithoutIntConstructor.class.getName());
    assertTrue(ContextDataFactory.createContextData(2) instanceof SortedArrayStringMap);
    final SortedArrayStringMap actual = (SortedArrayStringMap) ContextDataFactory.createContextData(2);
    final Field thresholdField = SortedArrayStringMap.class.getDeclaredField("threshold");
    thresholdField.setAccessible(true);
    assertEquals(2, thresholdField.getInt(actual));
    System.clearProperty("log4j2.ContextData");
}
 
Example 19
private void testContextDataInjector() {
    ReadOnlyThreadContextMap readOnlythreadContextMap = getThreadContextMap();
    assertThat("thread context map class name",
               (readOnlythreadContextMap == null) ? null : readOnlythreadContextMap.getClass().getName(),
               is(equalTo(readOnlythreadContextMapClassName)));

    ContextDataInjector contextDataInjector = createInjector();
    StringMap stringMap = contextDataInjector.injectContextData(null, new SortedArrayStringMap());

    assertThat("thread context map", ThreadContext.getContext(), allOf(hasEntry("foo", "bar"), not(hasKey("baz"))));
    assertThat("context map", stringMap.toMap(), allOf(hasEntry("foo", "bar"), not(hasKey("baz"))));

    if (!stringMap.isFrozen()) {
        stringMap.clear();
        assertThat("thread context map", ThreadContext.getContext(), allOf(hasEntry("foo", "bar"), not(hasKey("baz"))));
        assertThat("context map", stringMap.toMap().entrySet(), is(empty()));
    }

    ThreadContext.put("foo", "bum");
    ThreadContext.put("baz", "bam");

    assertThat("thread context map", ThreadContext.getContext(), allOf(hasEntry("foo", "bum"), hasEntry("baz", "bam")));
    if (stringMap.isFrozen()) {
        assertThat("context map", stringMap.toMap(), allOf(hasEntry("foo", "bar"), not(hasKey("baz"))));
    } else {
        assertThat("context map", stringMap.toMap().entrySet(), is(empty()));
    }
}
 
Example 20
Source Project: logging-log4j2   Source File: JsonLayoutTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testLayoutRingBufferEventReusableMessageWithCurlyBraces() throws Exception {
    final boolean propertiesAsList = false;
    final AbstractJacksonLayout layout = JsonLayout.newBuilder()
            .setLocationInfo(false)
            .setProperties(false)
            .setPropertiesAsList(propertiesAsList)
            .setComplete(false)
            .setCompact(true)
            .setEventEol(false)
            .setCharset(StandardCharsets.UTF_8)
            .setIncludeStacktrace(true)
            .build();
    Message message = ReusableMessageFactory.INSTANCE.newMessage("Testing {}", new TestObj());
    try {
        RingBufferLogEvent ringBufferEvent = new RingBufferLogEvent();
        ringBufferEvent.setValues(
                null, "a.B", null, "f.q.c.n", Level.DEBUG, message,
                null, new SortedArrayStringMap(), ThreadContext.EMPTY_STACK, 1L,
                "threadName", 1, null, new SystemClock(), new DummyNanoClock());
        final String str = layout.toSerializable(ringBufferEvent);
        final String expectedMessage = "Testing " + TestObj.TO_STRING_VALUE;
        assertThat(str, containsString("\"message\":\"" + expectedMessage + '"'));
        final Log4jLogEvent actual = new Log4jJsonObjectMapper(propertiesAsList, true, false, false).readValue(str, Log4jLogEvent.class);
        assertEquals(expectedMessage, actual.getMessage().getFormattedMessage());
    } finally {
        ReusableMessageFactory.release(message);
    }
}
 
Example 21
@Test
public void handleEmptyConfigurationProperties() {
  assertContainsOnlyDefaultTracingEntries(
      new OpenCensusTraceContextDataInjector()
          .injectContextData(Collections.<Property>emptyList(), new SortedArrayStringMap()));
}
 
Example 22
@Test
public void handleNullConfigurationProperties() {
  assertContainsOnlyDefaultTracingEntries(
      new OpenCensusTraceContextDataInjector()
          .injectContextData(null, new SortedArrayStringMap()));
}
 
Example 23
@Benchmark
public SortedArrayStringMap putAllArrayContextData() {
    sortedStringArrayMap.clear();
    sortedStringArrayMap.putAll(populatedSortedStringArrayMap);
    return sortedStringArrayMap;
}
 
Example 24
@Benchmark
public SortedArrayStringMap cloneArrayContextData() {
    return new SortedArrayStringMap(populatedSortedStringArrayMap);
}
 
Example 25
Source Project: logging-log4j2   Source File: MapMessage.java    License: Apache License 2.0 4 votes vote down vote up
/**
 * Constructs a new instance.
 */
public MapMessage() {
    this.data = new SortedArrayStringMap();
}
 
Example 26
Source Project: logging-log4j2   Source File: PropertyRewritePolicy.java    License: Apache License 2.0 4 votes vote down vote up
/**
 * {@inheritDoc}
 */
public LoggingEvent rewrite(final LoggingEvent source) {
    if (!properties.isEmpty()) {
        Map<String, String> rewriteProps = source.getProperties() != null ? new HashMap<>(source.getProperties())
                : new HashMap<>();
        for (Map.Entry<String, String> entry : properties.entrySet()) {
            if (!rewriteProps.containsKey(entry.getKey())) {
                rewriteProps.put(entry.getKey(), entry.getValue());
            }
        }
        LogEvent event;
        if (source instanceof LogEventAdapter) {
            event = new Log4jLogEvent.Builder(((LogEventAdapter) source).getEvent())
                    .setContextData(new SortedArrayStringMap(rewriteProps))
                    .build();
        } else {
            LocationInfo info = source.getLocationInformation();
            StackTraceElement element = new StackTraceElement(info.getClassName(), info.getMethodName(),
                    info.getFileName(), Integer.parseInt(info.getLineNumber()));
            Thread thread = getThread(source.getThreadName());
            long threadId = thread != null ? thread.getId() : 0;
            int threadPriority = thread != null ? thread.getPriority() : 0;
            event = Log4jLogEvent.newBuilder()
                    .setContextData(new SortedArrayStringMap(rewriteProps))
                    .setLevel(OptionConverter.convertLevel(source.getLevel()))
                    .setLoggerFqcn(source.getFQNOfLoggerClass())
                    .setMarker(null)
                    .setMessage(new SimpleMessage(source.getRenderedMessage()))
                    .setSource(element)
                    .setLoggerName(source.getLoggerName())
                    .setThreadName(source.getThreadName())
                    .setThreadId(threadId)
                    .setThreadPriority(threadPriority)
                    .setThrown(source.getThrowableInformation().getThrowable())
                    .setTimeMillis(source.getTimeStamp())
                    .setNanoTime(0)
                    .setThrownProxy(null)
                    .build();
        }
        return new LogEventAdapter(event);
    }
    return source;
}
 
Example 27
Source Project: logging-log4j2   Source File: JsonTemplateLayoutTest.java    License: Apache License 2.0 4 votes vote down vote up
@Test
public void test_mdc_key_access() {

    // Create the log event.
    final SimpleMessage message = new SimpleMessage("Hello, World!");
    final StringMap contextData = new SortedArrayStringMap();
    final String mdcDirectlyAccessedKey = "mdcKey1";
    final String mdcDirectlyAccessedValue = "mdcValue1";
    contextData.putValue(mdcDirectlyAccessedKey, mdcDirectlyAccessedValue);
    final String mdcDirectlyAccessedNullPropertyKey = "mdcKey2";
    final String mdcDirectlyAccessedNullPropertyValue = null;
    // noinspection ConstantConditions
    contextData.putValue(mdcDirectlyAccessedNullPropertyKey, mdcDirectlyAccessedNullPropertyValue);
    final LogEvent logEvent = Log4jLogEvent
            .newBuilder()
            .setLoggerName(LOGGER_NAME)
            .setLevel(Level.INFO)
            .setMessage(message)
            .setContextData(contextData)
            .build();

    // Create the event template.
    String eventTemplate = writeJson(Map(
            mdcDirectlyAccessedKey, Map(
                    "$resolver", "mdc",
                    "key", mdcDirectlyAccessedKey),
            mdcDirectlyAccessedNullPropertyKey, Map(
                    "$resolver", "mdc",
                    "key", mdcDirectlyAccessedNullPropertyKey)));

    // Create the layout.
    final JsonTemplateLayout layout = JsonTemplateLayout
            .newBuilder()
            .setConfiguration(CONFIGURATION)
            .setStackTraceEnabled(true)
            .setEventTemplate(eventTemplate)
            .build();

    // Check the serialized event.
    usingSerializedLogEventAccessor(layout, logEvent, accessor -> {
        assertThat(accessor.getString(mdcDirectlyAccessedKey)).isEqualTo(mdcDirectlyAccessedValue);
        assertThat(accessor.getString(mdcDirectlyAccessedNullPropertyKey)).isNull();
    });

}
 
Example 28
Source Project: logging-log4j2   Source File: JsonTemplateLayoutTest.java    License: Apache License 2.0 4 votes vote down vote up
@Test
public void test_mdc_pattern() {

    // Create the log event.
    final SimpleMessage message = new SimpleMessage("Hello, World!");
    final StringMap contextData = new SortedArrayStringMap();
    final String mdcPatternMatchedKey = "mdcKey1";
    final String mdcPatternMatchedValue = "mdcValue1";
    contextData.putValue(mdcPatternMatchedKey, mdcPatternMatchedValue);
    final String mdcPatternMismatchedKey = "mdcKey2";
    final String mdcPatternMismatchedValue = "mdcValue2";
    contextData.putValue(mdcPatternMismatchedKey, mdcPatternMismatchedValue);
    final LogEvent logEvent = Log4jLogEvent
            .newBuilder()
            .setLoggerName(LOGGER_NAME)
            .setLevel(Level.INFO)
            .setMessage(message)
            .setContextData(contextData)
            .build();

    // Create the event template.
    final String mdcFieldName = "mdc";
    final String eventTemplate = writeJson(Map(
            mdcFieldName, Map(
                    "$resolver", "mdc",
                    "pattern", mdcPatternMatchedKey)));

    // Create the layout.
    final JsonTemplateLayout layout = JsonTemplateLayout
            .newBuilder()
            .setConfiguration(CONFIGURATION)
            .setStackTraceEnabled(true)
            .setEventTemplate(eventTemplate)
            .build();

    // Check the serialized event.
    usingSerializedLogEventAccessor(layout, logEvent, accessor -> {
        assertThat(accessor.getString(new String[]{mdcFieldName, mdcPatternMatchedKey})).isEqualTo(mdcPatternMatchedValue);
        assertThat(accessor.exists(new String[]{mdcFieldName, mdcPatternMismatchedKey})).isFalse();
    });

}
 
Example 29
Source Project: logging-log4j2   Source File: JsonTemplateLayoutTest.java    License: Apache License 2.0 4 votes vote down vote up
@Test
public void test_mdc_flatten() {

    // Create the log event.
    final SimpleMessage message = new SimpleMessage("Hello, World!");
    final StringMap contextData = new SortedArrayStringMap();
    final String mdcPatternMatchedKey = "mdcKey1";
    final String mdcPatternMatchedValue = "mdcValue1";
    contextData.putValue(mdcPatternMatchedKey, mdcPatternMatchedValue);
    final String mdcPatternMismatchedKey = "mdcKey2";
    final String mdcPatternMismatchedValue = "mdcValue2";
    contextData.putValue(mdcPatternMismatchedKey, mdcPatternMismatchedValue);
    final LogEvent logEvent = Log4jLogEvent
            .newBuilder()
            .setLoggerName(LOGGER_NAME)
            .setLevel(Level.INFO)
            .setMessage(message)
            .setContextData(contextData)
            .build();

    // Create the event template.
    final String mdcPrefix = "_mdc.";
    final String eventTemplate = writeJson(Map(
            "ignoredFieldName", Map(
                    "$resolver", "mdc",
                    "pattern", mdcPatternMatchedKey,
                    "flatten", Map("prefix", mdcPrefix))));

    // Create the layout.
    final JsonTemplateLayout layout = JsonTemplateLayout
            .newBuilder()
            .setConfiguration(CONFIGURATION)
            .setStackTraceEnabled(true)
            .setEventTemplate(eventTemplate)
            .build();

    // Check the serialized event.
    usingSerializedLogEventAccessor(layout, logEvent, accessor -> {
        assertThat(accessor.getString(mdcPrefix + mdcPatternMatchedKey)).isEqualTo(mdcPatternMatchedValue);
        assertThat(accessor.exists(mdcPrefix + mdcPatternMismatchedKey)).isFalse();
    });

}
 
Example 30
Source Project: logging-log4j2   Source File: JsonWriterTest.java    License: Apache License 2.0 4 votes vote down vote up
@Test
public void test_writeObject_Map() {
    final Map<String, Object> map = new LinkedHashMap<String, Object>() {{
        put("key1", "val1");
        put("key2", Collections.singletonMap("key2.1", "val2.1"));
        put("key3", Arrays.asList(
                3,
                (byte) 127,
                4.5D,
                4.6F,
                Arrays.asList(true, false),
                new BigDecimal("30.12345678901234567890123456789"),
                new BigInteger("12345678901234567890123456789"),
                Collections.singleton('a'),
                Collections.singletonMap("key3.3", "val3.3")));
        put("key4", new LinkedHashMap<String, Object>() {{
            put("chars", new char[]{'a', 'b', 'c'});
            put("booleans", new boolean[]{true, false});
            put("bytes", new byte[]{1, 2});
            put("shorts", new short[]{3, 4});
            put("ints", new int[]{256, 257});
            put("longs", new long[]{2147483648L, 2147483649L});
            put("floats", new float[]{1.0F, 1.1F});
            put("doubles", new double[]{2.0D, 2.1D});
            put("objects", new Object[]{"foo", "bar"});
        }});
        put("key5\t", new Object() {
            @Override
            public String toString() {
                return "custom-object\r";
            }
        });
        put("key6", Arrays.asList(
                new SortedArrayStringMap(new LinkedHashMap<String, Object>() {{
                    put("buzz", 1.2D);
                    put("foo", "bar");
                }}),
                new JdkMapAdapterStringMap(Collections.singletonMap("a", "b"))));
        put("key7", (StringBuilderFormattable) buffer ->
                buffer.append(7.7777777777777D));
    }};
    final String expectedJson = ("{" +
            "'key1':'val1'," +
            "'key2':{'key2.1':'val2.1'}," +
            "'key3':[" +
            "3," +
            "127," +
            "4.5," +
            "4.6," +
            "[true,false]," +
            "30.12345678901234567890123456789," +
            "12345678901234567890123456789," +
            "['a']," +
            "{'key3.3':'val3.3'}" +
            "]," +
            "'key4':{" +
            "'chars':['a','b','c']," +
            "'booleans':[true,false]," +
            "'bytes':[1,2]," +
            "'shorts':[3,4]," +
            "'ints':[256,257]," +
            "'longs':[2147483648,2147483649]," +
            "'floats':[1.0,1.1]," +
            "'doubles':[2.0,2.1]," +
            "'objects':['foo','bar']" +
            "}," +
            "'key5\\t':'custom-object\\r'," +
            "'key6':[{'buzz':1.2,'foo':'bar'},{'a':'b'}]," +
            "'key7':'7.7777777777777'" +
            "}").replace('\'', '"');
    final String actualJson = WRITER.use(() -> WRITER.writeObject(map));
    Assertions.assertThat(actualJson).isEqualTo(expectedJson);
}