下面列出了怎么用org.apache.logging.log4j.util.BiConsumer的API类实例代码及写法,或者点击链接到github查看源代码。
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;
}
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('"');
}
@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);
}
}
@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());
}
});
}
@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];
}
@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];
}
@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;
}
}
@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);
}
}
@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);
}
@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);
}
@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);
}
@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]));
}
}
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);
}
});
}
@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");
}
});
}
@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");
}
});
}
@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");
}
});
}
@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();
}
});
}
@Override
@SuppressWarnings("unchecked")
public <V> void forEach(BiConsumer<String, ? super V> action) {
map.forEach((key, value) -> action.accept(key, (V) value));
}
@Override
public void forEach(BiConsumer<String, String> action) {
action.accept("log4j.isThreadContextMapInheritable", "true");
}
@Override
public void forEach(BiConsumer<String, String> action) {
action.accept("log4j.isThreadContextMapInheritable", "true");
}
@Override
public <V> void forEach(BiConsumer<String, ? super V> action) {
super.forEach((k,v) -> action.accept(k, (V) v));
}
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");
}
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");
}
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());
}
}
@Override
public <V> void forEach(final BiConsumer<String, ? super V> action) {
// do nothing
}
/**
* 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);
}
@Override
public <V> void forEach(final BiConsumer<String, ? super V> action) {
}