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

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

源代码1 项目: logging-log4j2   文件: JmsManager.java
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;
}
 
源代码2 项目: logging-log4j2   文件: JsonWriter.java
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];
}
 
源代码7 项目: logging-log4j2   文件: OpenHashStringMap.java
@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;
    }
}
 
源代码8 项目: logging-log4j2   文件: DefaultThreadContextMap.java
@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);
    }
}
 
源代码9 项目: logging-log4j2   文件: JsonWriterTest.java
@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);
}
 
源代码10 项目: logging-log4j2   文件: JsonWriterTest.java
@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);
}
 
源代码12 项目: logging-log4j2   文件: JdkMapAdapterStringMap.java
@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]));
    }
}
 
源代码13 项目: logging-log4j2   文件: NoSqlDatabaseManager.java
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();
        }
    });
}
 
源代码18 项目: curiostack   文件: RequestLoggingContextInjector.java
@Override
@SuppressWarnings("unchecked")
public <V> void forEach(BiConsumer<String, ? super V> action) {
  map.forEach((key, value) -> action.accept(key, (V) value));
}
 
源代码19 项目: Javacord   文件: Log4jPropertySource.java
@Override
public void forEach(BiConsumer<String, String> action) {
    action.accept("log4j.isThreadContextMapInheritable", "true");
}
 
源代码20 项目: Javacord   文件: Log4jPropertySource.java
@Override
public void forEach(BiConsumer<String, String> action) {
    action.accept("log4j.isThreadContextMapInheritable", "true");
}
 
源代码21 项目: logging-log4j2   文件: LogEventWrapper.java
@Override
public <V> void forEach(BiConsumer<String, ? super V> action) {
    super.forEach((k,v) -> action.accept(k, (V) v));
}
 
源代码22 项目: logging-log4j2   文件: Log4j1XmlLayout.java
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");
  }
 
源代码23 项目: logging-log4j2   文件: Log4j1XmlLayout.java
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");
  }
 
源代码24 项目: logging-log4j2   文件: NoSqlDatabaseManager.java
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());
    }
}
 
源代码25 项目: logging-log4j2   文件: FactoryTestStringMap.java
@Override
public <V> void forEach(final BiConsumer<String, ? super V> action) {
    // do nothing
}
 
源代码26 项目: logging-log4j2   文件: MapMessage.java
/**
 * 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) {

}
 
 类所在包
 类方法
 同包方法