private LogEvent createLogEvent(DateTime timestamp) { final MutableLogEvent logEvent = new MutableLogEvent(); logEvent.setMessage(new SimpleMessage("Test")); logEvent.setLevel(Level.TRACE); logEvent.setLoggerName("org.example.Test"); logEvent.setMarker(MarkerManager.getMarker("TestMarker")); logEvent.setTimeMillis(timestamp.getMillis()); logEvent.setNanoTime(42L); logEvent.setContextStack(new MutableThreadContextStack(ImmutableList.of("one", "two"))); final SortedArrayStringMap contextData = new SortedArrayStringMap(1); contextData.putValue("foobar", "quux"); logEvent.setContextData(contextData); logEvent.setThreadId(23L); logEvent.setThreadName("thread-name"); logEvent.setThreadPriority(42); logEvent.setThrown(new Throwable("Test", new Throwable("cause"))); logEvent.setIncludeLocation(true); return logEvent.createMemento(); }
@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); }
@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); } }
@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); }
@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)); }
@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)); }
@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; }
public static StringMap createContextData() { if (DEFAULT_CONSTRUCTOR == null) { return new SortedArrayStringMap(); } try { return (IndexedStringMap) DEFAULT_CONSTRUCTOR.invoke(); } catch (final Throwable ignored) { return new SortedArrayStringMap(); } }
public static StringMap createContextData(final int initialCapacity) { if (INITIAL_CAPACITY_CONSTRUCTOR == null) { return new SortedArrayStringMap(initialCapacity); } try { return (IndexedStringMap) INITIAL_CAPACITY_CONSTRUCTOR.invoke(initialCapacity); } catch (final Throwable ignored) { return new SortedArrayStringMap(initialCapacity); } }
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()); } }
@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)); }
@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"); }
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())); } }
@Test public void test_mdc_key_access() throws IOException { // Create the log event. SimpleMessage message = new SimpleMessage("Hello, World!"); StringMap contextData = new SortedArrayStringMap(); String mdcDirectlyAccessedKey = "mdcKey1"; String mdcDirectlyAccessedValue = "mdcValue1"; contextData.putValue(mdcDirectlyAccessedKey, mdcDirectlyAccessedValue); String mdcPatternMatchedKey = "mdcKey2"; String mdcPatternMatchedValue = "mdcValue2"; contextData.putValue(mdcPatternMatchedKey, mdcPatternMatchedValue); String mdcPatternMismatchedKey = "mdcKey3"; String mdcPatternMismatchedValue = "mdcValue3"; contextData.putValue(mdcPatternMismatchedKey, mdcPatternMismatchedValue); LogEvent logEvent = Log4jLogEvent .newBuilder() .setLoggerName(LogstashLayoutTest.class.getSimpleName()) .setLevel(Level.INFO) .setMessage(message) .setContextData(contextData) .build(); // Create the template. ObjectNode templateRootNode = JSON_NODE_FACTORY.objectNode(); String mdcFieldName = "mdc"; templateRootNode.put(mdcFieldName, "${json:mdc}"); templateRootNode.put(mdcDirectlyAccessedKey, String.format("${json:mdc:%s}", mdcDirectlyAccessedKey)); String template = templateRootNode.toString(); // Create the layout. BuiltConfiguration configuration = ConfigurationBuilderFactory.newConfigurationBuilder().build(); LogstashLayout layout = LogstashLayout .newBuilder() .setConfiguration(configuration) .setStackTraceEnabled(true) .setTemplate(template) .setMdcKeyPattern(mdcPatternMatchedKey) .build(); // Check the serialized event. String serializedLogEvent = layout.toSerializable(logEvent); JsonNode rootNode = OBJECT_MAPPER.readTree(serializedLogEvent); assertThat(point(rootNode, mdcDirectlyAccessedKey).asText()).isEqualTo(mdcDirectlyAccessedValue); assertThat(point(rootNode, mdcFieldName, mdcPatternMatchedKey).asText()).isEqualTo(mdcPatternMatchedValue); assertThat(point(rootNode, mdcFieldName, mdcPatternMismatchedKey).asText()).isNullOrEmpty(); }
@Benchmark public SortedArrayStringMap putAllArrayContextData() { sortedStringArrayMap.clear(); sortedStringArrayMap.putAll(populatedSortedStringArrayMap); return sortedStringArrayMap; }
@Benchmark public SortedArrayStringMap cloneArrayContextData() { return new SortedArrayStringMap(populatedSortedStringArrayMap); }
/** * Constructs a new instance. */ public MapMessage() { this.data = new SortedArrayStringMap(); }
@Test public void testBuilderCorrectlyCopiesAllEventAttributesInclContextData() { final StringMap contextData = new SortedArrayStringMap(); contextData.putValue("A", "B"); final ContextStack contextStack = ThreadContext.getImmutableStack(); final Exception exception = new Exception("test"); final Marker marker = MarkerManager.getMarker("EVENTTEST"); final Message message = new SimpleMessage("foo"); final StackTraceElement stackTraceElement = new StackTraceElement("A", "B", "file", 123); final String fqcn = "qualified"; final String name = "Ceci n'est pas une pipe"; final String threadName = "threadName"; final Log4jLogEvent event = Log4jLogEvent.newBuilder() // .setContextData(contextData) // .setContextStack(contextStack) // .setEndOfBatch(true) // .setIncludeLocation(true) // .setLevel(Level.FATAL) // .setLoggerFqcn(fqcn) // .setLoggerName(name) // .setMarker(marker) // .setMessage(message) // .setNanoTime(1234567890L) // .setSource(stackTraceElement) // .setThreadName(threadName) // .setThrown(exception) // .setTimeMillis(987654321L) .build(); assertSame(contextData, event.getContextData()); assertSame(contextStack, event.getContextStack()); assertEquals(true, event.isEndOfBatch()); assertEquals(true, event.isIncludeLocation()); assertSame(Level.FATAL, event.getLevel()); assertSame(fqcn, event.getLoggerFqcn()); assertSame(name, event.getLoggerName()); assertSame(marker, event.getMarker()); assertSame(message, event.getMessage()); assertEquals(1234567890L, event.getNanoTime()); assertSame(stackTraceElement, event.getSource()); assertSame(threadName, event.getThreadName()); assertSame(exception, event.getThrown()); assertEquals(987654321L, event.getTimeMillis()); final LogEvent event2 = new Log4jLogEvent.Builder(event).build(); assertEquals("copy constructor builder", event2, event); assertEquals("same hashCode", event2.hashCode(), event.hashCode()); }
@Test public void testBuilderCorrectlyCopiesMutableLogEvent() throws Exception { final StringMap contextData = new SortedArrayStringMap(); contextData.putValue("A", "B"); final ContextStack contextStack = ThreadContext.getImmutableStack(); final Exception exception = new Exception("test"); final Marker marker = MarkerManager.getMarker("EVENTTEST"); final Message message = new SimpleMessage("foo"); new StackTraceElement("A", "B", "file", 123); final String fqcn = "qualified"; final String name = "Ceci n'est pas une pipe"; final String threadName = "threadName"; final MutableLogEvent event = new MutableLogEvent(); event.setContextData(contextData); event.setContextStack(contextStack); event.setEndOfBatch(true); event.setIncludeLocation(true); //event.setSource(stackTraceElement); // cannot be explicitly set event.setLevel(Level.FATAL); event.setLoggerFqcn(fqcn); event.setLoggerName(name); event.setMarker(marker); event.setMessage(message); event.setNanoTime(1234567890L); event.setThreadName(threadName); event.setThrown(exception); event.setTimeMillis(987654321L); assertSame(contextData, event.getContextData()); assertSame(contextStack, event.getContextStack()); assertEquals(true, event.isEndOfBatch()); assertEquals(true, event.isIncludeLocation()); assertSame(Level.FATAL, event.getLevel()); assertSame(fqcn, event.getLoggerFqcn()); assertSame(name, event.getLoggerName()); assertSame(marker, event.getMarker()); assertSame(message, event.getMessage()); assertEquals(1234567890L, event.getNanoTime()); //assertSame(stackTraceElement, event.getSource()); // don't invoke assertSame(threadName, event.getThreadName()); assertSame(exception, event.getThrown()); assertEquals(987654321L, event.getTimeMillis()); final LogEvent e2 = new Log4jLogEvent.Builder(event).build(); assertEquals(contextData, e2.getContextData()); assertSame(contextStack, e2.getContextStack()); assertEquals(true, e2.isEndOfBatch()); assertEquals(true, e2.isIncludeLocation()); assertSame(Level.FATAL, e2.getLevel()); assertSame(fqcn, e2.getLoggerFqcn()); assertSame(name, e2.getLoggerName()); assertSame(marker, e2.getMarker()); assertSame(message, e2.getMessage()); assertEquals(1234567890L, e2.getNanoTime()); //assertSame(stackTraceElement, e2.getSource()); // don't invoke assertSame(threadName, e2.getThreadName()); assertSame(exception, e2.getThrown()); assertEquals(987654321L, e2.getTimeMillis()); // use reflection to get value of source field in log event copy: // invoking the getSource() method would initialize the field final Field fieldSource = Log4jLogEvent.class.getDeclaredField("source"); fieldSource.setAccessible(true); final Object value = fieldSource.get(e2); assertNull("source in copy", value); }
@Test public void noArgReturnsSortedArrayStringMapIfNoPropertySpecified() throws Exception { assertTrue(ContextDataFactory.createContextData() instanceof SortedArrayStringMap); }
@Test public void intArgReturnsSortedArrayStringMapIfNoPropertySpecified() throws Exception { assertTrue(ContextDataFactory.createContextData(2) instanceof SortedArrayStringMap); }
private static StringMap createContextData() { final StringMap result = new SortedArrayStringMap(); result.putValue("a", "1"); result.putValue("b", "2"); return result; }
/** * Constructs a new instance. * * @param initialCapacity the initial capacity. */ public MapMessage(final int initialCapacity) { this.data = new SortedArrayStringMap(initialCapacity); }
/** * Constructs a new instance based on an existing {@link Map}. * @param map The Map. */ public MapMessage(final Map<String, V> map) { this.data = new SortedArrayStringMap(map); }
/** * Returns an implementation of the {@code StringMap} used to back this thread context map. * <p> * Subclasses may override. * </p> * @return an implementation of the {@code StringMap} used to back this thread context map */ protected StringMap createStringMap() { return new SortedArrayStringMap(initialCapacity); }
/** * Returns an implementation of the {@code StringMap} used to back this thread context map, pre-populated * with the contents of the specified context data. * <p> * Subclasses may override. * </p> * @param original the key-value pairs to initialize the returned context data with * @return an implementation of the {@code StringMap} used to back this thread context map */ protected StringMap createStringMap(final ReadOnlyStringMap original) { return new SortedArrayStringMap(original); }