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

The following examples show how to use org.apache.logging.log4j.util.BiConsumer. 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   Author: apache   File: JmsManager.java    License: Apache License 2.0 6 votes vote down vote up
private MapMessage map(final org.apache.logging.log4j.message.MapMessage<?, ?> log4jMapMessage,
        final MapMessage jmsMapMessage) {
    // Map without calling org.apache.logging.log4j.message.MapMessage#getData() which makes a copy of the map.
    log4jMapMessage.forEach(new BiConsumer<String, Object>() {
        @Override
        public void accept(final String key, final Object value) {
            try {
                jmsMapMessage.setObject(key, value);
            } catch (final JMSException e) {
                throw new IllegalArgumentException(String.format("%s mapping key '%s' to value '%s': %s",
                        e.getClass(), key, value, e.getLocalizedMessage()), e);
            }
        }
    });
    return jmsMapMessage;
}
 
Example #2
Source Project: logging-log4j2   Author: apache   File: JsonWriter.java    License: Apache License 2.0 6 votes vote down vote up
public <S> void writeString(
        final BiConsumer<StringBuilder, S> emitter,
        final S state) {
    Objects.requireNonNull(emitter, "emitter");
    stringBuilder.append('"');
    formattableBuffer.setLength(0);
    emitter.accept(formattableBuffer, state);
    final int length = formattableBuffer.length();
    // Handle max. string length complying input.
    if (length <= maxStringLength) {
        quoteString(formattableBuffer, 0, length);
    }
    // Handle max. string length violating input.
    else {
        quoteString(formattableBuffer, 0, maxStringLength);
        stringBuilder.append(quotedTruncatedStringSuffix);
    }
    stringBuilder.append('"');
}
 
Example #3
Source Project: logging-log4j2   Author: apache   File: ContextDataJsonAttributeConverter.java    License: Apache License 2.0 6 votes vote down vote up
@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 #4
Source Project: logging-log4j2   Author: apache   File: JdkMapAdapterStringMapTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
    public void testForEachBiConsumer() throws Exception {
        final JdkMapAdapterStringMap original = new JdkMapAdapterStringMap();
        original.putValue("a", "avalue");
        original.putValue("B", "Bvalue");
        original.putValue("3", "3value");

        original.forEach(new BiConsumer<String, String>() {
            int count = 0;
            @Override
            public void accept(final String key, final String value) {
//                assertEquals("key", key, original.getKeyAt(count));
//                assertEquals("val", value, original.getValueAt(count));
                count++;
                assertTrue("count should not exceed size but was " + count, count <= original.size());
            }
        });
    }
 
Example #5
Source Project: logging-log4j2   Author: apache   File: SortedArrayVsHashMapBenchmark.java    License: Apache License 2.0 5 votes vote down vote up
@Benchmark
public int iterateArrayContextDataBiConsumer() {
    final int[] result = {0};

    populatedSortedStringArrayMap.forEach(new BiConsumer<String, Object>() {
        @Override
        public void accept(final String s, final Object o) {
            result[0] += s.hashCode() + o.hashCode();
        }
    });
    return result[0];
}
 
Example #6
Source Project: logging-log4j2   Author: apache   File: SortedArrayVsHashMapBenchmark.java    License: Apache License 2.0 5 votes vote down vote up
@Benchmark
public int iterateHashContextDataBiConsumer() {
    final int[] result = {0};

    populatedOpenHashContextData.forEach(new BiConsumer<String, Object>() {
        @Override
        public void accept(final String s, final Object o) {
            result[0] += s.hashCode() + o.hashCode();
        }
    });
    return result[0];
}
 
Example #7
Source Project: logging-log4j2   Author: apache   File: OpenHashStringMap.java    License: Apache License 2.0 5 votes vote down vote up
@Override
@SuppressWarnings("unchecked")
public <VAL> void forEach(final BiConsumer<String, ? super VAL> action) {
    final int startSize = size;
    final K myKeys[] = this.keys;
    int pos = arraySize;

    iterating = true;
    try {
        if (containsNullKey) {
            action.accept((String) myKeys[pos], (VAL) values[pos]);
            if (size != startSize) {
                throw new ConcurrentModificationException();
            }
        }
        --pos;
        for (; pos >= 0; pos--) {
            if (myKeys[pos] != null) {
                action.accept((String) myKeys[pos], (VAL) values[pos]);
                if (size != startSize) {
                    throw new ConcurrentModificationException();
                }
            }
        }
    } finally {
        iterating = false;
    }
}
 
Example #8
Source Project: logging-log4j2   Author: apache   File: DefaultThreadContextMap.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public <V> void forEach(final BiConsumer<String, ? super V> action) {
    final Map<String, String> map = localMap.get();
    if (map == null) {
        return;
    }
    for (final Map.Entry<String, String> entry : map.entrySet()) {
        //BiConsumer should be able to handle values of any type V. In our case the values are of type String.
        @SuppressWarnings("unchecked")
        V value = (V) entry.getValue();
        action.accept(entry.getKey(), value);
    }
}
 
Example #9
Source Project: logging-log4j2   Author: apache   File: JsonWriterTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void test_writeString_emitter() {
    final String state = "there-is-no-spoon";
    final BiConsumer<StringBuilder, String> emitter = StringBuilder::append;
    final String expectedJson = '"' + state + '"';
    final String actualJson =
            WRITER.use(() -> WRITER.writeString(emitter, state));
    Assertions.assertThat(actualJson).isEqualTo(expectedJson);
}
 
Example #10
Source Project: logging-log4j2   Author: apache   File: JsonWriterTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void test_writeString_emitter_excessive_string() {
    final int maxStringLength = WRITER.getMaxStringLength();
    final String excessiveString = Strings.repeat("x", maxStringLength) + 'y';
    final String expectedJson = '"' +
            excessiveString.substring(0, maxStringLength) +
            WRITER.getTruncatedStringSuffix() +
            '"';
    final BiConsumer<StringBuilder, String> emitter = StringBuilder::append;
    final String actualJson =
            WRITER.use(() -> WRITER.writeString(emitter, excessiveString));
    Assertions.assertThat(actualJson).isEqualTo(expectedJson);
}
 
Example #11
Source Project: logging-log4j2   Author: apache   File: ContextDataAsEntryListSerializer.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 {

    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 #12
Source Project: logging-log4j2   Author: apache   File: JdkMapAdapterStringMap.java    License: Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
@Override
public <V> void forEach(final BiConsumer<String, ? super V> action) {
    final String[] keys = getSortedKeys();
    for (int i = 0; i < keys.length; i++) {
        action.accept(keys[i], (V) map.get(keys[i]));
    }
}
 
Example #13
Source Project: logging-log4j2   Author: apache   File: NoSqlDatabaseManager.java    License: Apache License 2.0 5 votes vote down vote up
private void setFields(final MapMessage<?, ?> mapMessage, final NoSqlObject<W> noSqlObject) {
    // Map without calling org.apache.logging.log4j.message.MapMessage#getData() which makes a copy of the map.
    mapMessage.forEach(new BiConsumer<String, Object>() {
        @Override
        public void accept(final String key, final Object value) {
            noSqlObject.set(key, value);
        }
    });
}
 
Example #14
Source Project: logging-log4j2   Author: apache   File: JdkMapAdapterStringMapTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testNoConcurrentModificationBiConsumerPut() {
    final JdkMapAdapterStringMap original = new JdkMapAdapterStringMap();
    original.putValue("a", "aaa");
    original.putValue("b", "aaa");
    original.putValue("c", "aaa");
    original.putValue("d", "aaa");
    original.putValue("e", "aaa");
    original.forEach(new BiConsumer<String, Object>() {
        @Override
        public void accept(final String s, final Object o) {
            original.putValue("c" + s, "other");
        }
    });
}
 
Example #15
Source Project: logging-log4j2   Author: apache   File: JdkMapAdapterStringMapTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testNoConcurrentModificationBiConsumerPutValue() {
    final JdkMapAdapterStringMap original = new JdkMapAdapterStringMap();
    original.putValue("a", "aaa");
    original.putValue("b", "aaa");
    original.putValue("c", "aaa");
    original.putValue("d", "aaa");
    original.putValue("e", "aaa");
    original.forEach(new BiConsumer<String, Object>() {
        @Override
        public void accept(final String s, final Object o) {
            original.putValue("c" + s, "other");
        }
    });
}
 
Example #16
Source Project: logging-log4j2   Author: apache   File: JdkMapAdapterStringMapTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testNoConcurrentModificationBiConsumerRemove() {
    final JdkMapAdapterStringMap original = new JdkMapAdapterStringMap();
    original.putValue("a", "aaa");
    original.putValue("b", "aaa");
    original.putValue("c", "aaa");
    original.forEach(new BiConsumer<String, Object>() {
        @Override
        public void accept(final String s, final Object o) {
            original.remove("a");
        }
    });
}
 
Example #17
Source Project: logging-log4j2   Author: apache   File: JdkMapAdapterStringMapTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testNoConcurrentModificationBiConsumerClear() {
    final JdkMapAdapterStringMap original = new JdkMapAdapterStringMap();
    original.putValue("a", "aaa");
    original.putValue("b", "aaa");
    original.putValue("c", "aaa");
    original.putValue("d", "aaa");
    original.putValue("e", "aaa");
    original.forEach(new BiConsumer<String, Object>() {
        @Override
        public void accept(final String s, final Object o) {
            original.clear();
        }
    });
}
 
Example #18
Source Project: curiostack   Author: curioswitch   File: RequestLoggingContextInjector.java    License: MIT License 4 votes vote down vote up
@Override
@SuppressWarnings("unchecked")
public <V> void forEach(BiConsumer<String, ? super V> action) {
  map.forEach((key, value) -> action.accept(key, (V) value));
}
 
Example #19
Source Project: Javacord   Author: Javacord   File: Log4jPropertySource.java    License: Apache License 2.0 4 votes vote down vote up
@Override
public void forEach(BiConsumer<String, String> action) {
    action.accept("log4j.isThreadContextMapInheritable", "true");
}
 
Example #20
Source Project: Javacord   Author: Javacord   File: Log4jPropertySource.java    License: Apache License 2.0 4 votes vote down vote up
@Override
public void forEach(BiConsumer<String, String> action) {
    action.accept("log4j.isThreadContextMapInheritable", "true");
}
 
Example #21
Source Project: logging-log4j2   Author: apache   File: LogEventWrapper.java    License: Apache License 2.0 4 votes vote down vote up
@Override
public <V> void forEach(BiConsumer<String, ? super V> action) {
    super.forEach((k,v) -> action.accept(k, (V) v));
}
 
Example #22
Source Project: logging-log4j2   Author: apache   File: Log4j1XmlLayout.java    License: Apache License 2.0 4 votes vote down vote up
private void formatTo(final LogEvent event, final StringBuilder buf) {
      // We yield to the \r\n heresy.

      buf.append("<log4j:event logger=\"");
      buf.append(Transform.escapeHtmlTags(event.getLoggerName()));
      buf.append("\" timestamp=\"");
      buf.append(event.getTimeMillis());
      buf.append("\" level=\"");
      buf.append(Transform.escapeHtmlTags(String.valueOf(event.getLevel())));
      buf.append("\" thread=\"");
      buf.append(Transform.escapeHtmlTags(event.getThreadName()));
      buf.append("\">\r\n");

      buf.append("<log4j:message><![CDATA[");
      // Append the rendered message. Also make sure to escape any existing CDATA sections.
      Transform.appendEscapingCData(buf, event.getMessage().getFormattedMessage());
      buf.append("]]></log4j:message>\r\n");

      final List<String> ndc = event.getContextStack().asList();
      if (!ndc.isEmpty()) {
          buf.append("<log4j:NDC><![CDATA[");
          Transform.appendEscapingCData(buf, Strings.join(ndc, ' '));
          buf.append("]]></log4j:NDC>\r\n");
      }

      @SuppressWarnings("ThrowableResultOfMethodCallIgnored")
final Throwable thrown = event.getThrown();
      if (thrown != null) {
          buf.append("<log4j:throwable><![CDATA[");
          final StringWriter w = new StringWriter();
          thrown.printStackTrace(new PrintWriter(w));
          Transform.appendEscapingCData(buf, w.toString());
          buf.append("]]></log4j:throwable>\r\n");
      }

      if (locationInfo) {
          final StackTraceElement source = event.getSource();
          if (source != null) {
              buf.append("<log4j:locationInfo class=\"");
              buf.append(Transform.escapeHtmlTags(source.getClassName()));
              buf.append("\" method=\"");
              buf.append(Transform.escapeHtmlTags(source.getMethodName()));
              buf.append("\" file=\"");
              buf.append(Transform.escapeHtmlTags(source.getFileName()));
              buf.append("\" line=\"");
              buf.append(source.getLineNumber());
              buf.append("\"/>\r\n");
          }
      }

      if (properties) {
          final ReadOnlyStringMap contextMap = event.getContextData();
          if (!contextMap.isEmpty()) {
              buf.append("<log4j:properties>\r\n");
              contextMap.forEach(new BiConsumer<String, String>() {
                  @Override
                  public void accept(final String key, final String val) {
                      if (val != null) {
                          buf.append("<log4j:data name=\"");
                          buf.append(Transform.escapeHtmlTags(key));
                          buf.append("\" value=\"");
                          buf.append(Transform.escapeHtmlTags(val));
                          buf.append("\"/>\r\n");
                      }
                  }
              });
              buf.append("</log4j:properties>\r\n");
          }
      }

      buf.append("</log4j:event>\r\n\r\n");
  }
 
Example #23
Source Project: logging-log4j2   Author: apache   File: Log4j1XmlLayout.java    License: Apache License 2.0 4 votes vote down vote up
private void formatTo(final LogEvent event, final StringBuilder buf) {
      // We yield to the \r\n heresy.

      buf.append("<log4j:event logger=\"");
      buf.append(Transform.escapeHtmlTags(event.getLoggerName()));
      buf.append("\" timestamp=\"");
      buf.append(event.getTimeMillis());
      buf.append("\" level=\"");
      buf.append(Transform.escapeHtmlTags(String.valueOf(event.getLevel())));
      buf.append("\" thread=\"");
      buf.append(Transform.escapeHtmlTags(event.getThreadName()));
      buf.append("\">\r\n");

      buf.append("<log4j:message><![CDATA[");
      // Append the rendered message. Also make sure to escape any existing CDATA sections.
      Transform.appendEscapingCData(buf, event.getMessage().getFormattedMessage());
      buf.append("]]></log4j:message>\r\n");

      final List<String> ndc = event.getContextStack().asList();
      if (!ndc.isEmpty()) {
          buf.append("<log4j:NDC><![CDATA[");
          Transform.appendEscapingCData(buf, Strings.join(ndc, ' '));
          buf.append("]]></log4j:NDC>\r\n");
      }

      @SuppressWarnings("ThrowableResultOfMethodCallIgnored")
final Throwable thrown = event.getThrown();
      if (thrown != null) {
          buf.append("<log4j:throwable><![CDATA[");
          final StringWriter w = new StringWriter();
          thrown.printStackTrace(new PrintWriter(w));
          Transform.appendEscapingCData(buf, w.toString());
          buf.append("]]></log4j:throwable>\r\n");
      }

      if (locationInfo) {
          final StackTraceElement source = event.getSource();
          if (source != null) {
              buf.append("<log4j:locationInfo class=\"");
              buf.append(Transform.escapeHtmlTags(source.getClassName()));
              buf.append("\" method=\"");
              buf.append(Transform.escapeHtmlTags(source.getMethodName()));
              buf.append("\" file=\"");
              buf.append(Transform.escapeHtmlTags(source.getFileName()));
              buf.append("\" line=\"");
              buf.append(source.getLineNumber());
              buf.append("\"/>\r\n");
          }
      }

      if (properties) {
          final ReadOnlyStringMap contextMap = event.getContextData();
          if (!contextMap.isEmpty()) {
              buf.append("<log4j:properties>\r\n");
              contextMap.forEach(new BiConsumer<String, String>() {
                  @Override
                  public void accept(final String key, final String val) {
                      if (val != null) {
                          buf.append("<log4j:data name=\"");
                          buf.append(Transform.escapeHtmlTags(key));
                          buf.append("\" value=\"");
                          buf.append(Transform.escapeHtmlTags(val));
                          buf.append("\"/>\r\n");
                      }
                  }
              });
              buf.append("</log4j:properties>\r\n");
          }
      }

      buf.append("</log4j:event>\r\n\r\n");
  }
 
Example #24
Source Project: logging-log4j2   Author: apache   File: NoSqlDatabaseManager.java    License: Apache License 2.0 4 votes vote down vote up
private void setFields(final LogEvent event, final NoSqlObject<W> entity) {
    entity.set("level", event.getLevel());
    entity.set("loggerName", event.getLoggerName());
    entity.set("message", event.getMessage() == null ? null : event.getMessage().getFormattedMessage());

    final StackTraceElement source = event.getSource();
    if (source == null) {
        entity.set("source", (Object) null);
    } else {
        entity.set("source", this.convertStackTraceElement(source));
    }

    final Marker marker = event.getMarker();
    if (marker == null) {
        entity.set("marker", (Object) null);
    } else {
        entity.set("marker", buildMarkerEntity(marker));
    }

    entity.set("threadId", event.getThreadId());
    entity.set("threadName", event.getThreadName());
    entity.set("threadPriority", event.getThreadPriority());
    entity.set("millis", event.getTimeMillis());
    entity.set("date", new java.util.Date(event.getTimeMillis()));

    @SuppressWarnings("ThrowableResultOfMethodCallIgnored")
    Throwable thrown = event.getThrown();
    if (thrown == null) {
        entity.set("thrown", (Object) null);
    } else {
        final NoSqlObject<W> originalExceptionEntity = this.connection.createObject();
        NoSqlObject<W> exceptionEntity = originalExceptionEntity;
        exceptionEntity.set("type", thrown.getClass().getName());
        exceptionEntity.set("message", thrown.getMessage());
        exceptionEntity.set("stackTrace", this.convertStackTrace(thrown.getStackTrace()));
        while (thrown.getCause() != null) {
            thrown = thrown.getCause();
            final NoSqlObject<W> causingExceptionEntity = this.connection.createObject();
            causingExceptionEntity.set("type", thrown.getClass().getName());
            causingExceptionEntity.set("message", thrown.getMessage());
            causingExceptionEntity.set("stackTrace", this.convertStackTrace(thrown.getStackTrace()));
            exceptionEntity.set("cause", causingExceptionEntity);
            exceptionEntity = causingExceptionEntity;
        }

        entity.set("thrown", originalExceptionEntity);
    }

    final ReadOnlyStringMap contextMap = event.getContextData();
    if (contextMap == null) {
        entity.set("contextMap", (Object) null);
    } else {
        final NoSqlObject<W> contextMapEntity = this.connection.createObject();
        contextMap.forEach(new BiConsumer<String, String>() {
            @Override
            public void accept(final String key, final String val) {
                contextMapEntity.set(key, val);
            }
        });
        entity.set("contextMap", contextMapEntity);
    }

    final ThreadContext.ContextStack contextStack = event.getContextStack();
    if (contextStack == null) {
        entity.set("contextStack", (Object) null);
    } else {
        entity.set("contextStack", contextStack.asList().toArray());
    }
}
 
Example #25
Source Project: logging-log4j2   Author: apache   File: FactoryTestStringMap.java    License: Apache License 2.0 4 votes vote down vote up
@Override
public <V> void forEach(final BiConsumer<String, ? super V> action) {
    // do nothing
}
 
Example #26
Source Project: logging-log4j2   Author: apache   File: MapMessage.java    License: Apache License 2.0 2 votes vote down vote up
/**
 * Performs the given action for each key-value pair in this data structure
 * until all entries have been processed or the action throws an exception.
 * <p>
 * Some implementations may not support structural modifications (adding new elements or removing elements) while
 * iterating over the contents. In such implementations, attempts to add or remove elements from the
 * {@code BiConsumer}'s {@link BiConsumer#accept(Object, Object)} accept} method may cause a
 * {@code ConcurrentModificationException} to be thrown.
 * </p>
 *
 * @param action The action to be performed for each key-value pair in this collection
 * @param <CV> type of the consumer value
 * @throws java.util.ConcurrentModificationException some implementations may not support structural modifications
 *          to this data structure while iterating over the contents with {@link #forEach(BiConsumer)} or
 *          {@link #forEach(TriConsumer, Object)}.
 * @see ReadOnlyStringMap#forEach(BiConsumer)
 * @since 2.9
 */
public <CV> void forEach(final BiConsumer<String, ? super CV> action) {
    data.forEach(action);
}
 
Example #27
Source Project: logging-log4j2   Author: apache   File: FactoryTestStringMapWithoutIntConstructor.java    License: Apache License 2.0 2 votes vote down vote up
@Override
public <V> void forEach(final BiConsumer<String, ? super V> action) {

}