    @Test
    public void testWriteInternal03() {
        given(connection.isClosed()).willReturn(false);
        given(message.getFormattedMessage()).willReturn("Another cool message 02.");

        try (final NoSqlDatabaseManager<?> manager = NoSqlDatabaseManager.getNoSqlDatabaseManager("name", 0,
            provider)) {
            manager.startup();

            manager.connectAndStart();
            then(provider).should().getConnection();

            final IOException exception1 = new IOException("This is the cause.");
            final SQLException exception2 = new SQLException("This is the result.", exception1);
            final Map<String, String> context = new HashMap<>();
            context.put("hello", "world");
            context.put("user", "pass");

            ThreadContext.push("message1");
            ThreadContext.push("stack2");
            final ThreadContext.ContextStack stack = ThreadContext.getImmutableStack();
            ThreadContext.clearStack();

            final LogEvent event = Log4jLogEvent.newBuilder()
                .setLevel(Level.DEBUG)
                .setLoggerName("com.foo.NoSQLDbTest.testWriteInternal02")
                .setMessage(message)
                .setSource(new StackTraceElement("com.bar.Foo", "anotherMethod03", "Foo.java", 9))
                .setMarker(MarkerManager.getMarker("AnotherMarker").addParents(
                    MarkerManager.getMarker("Parent1").addParents(MarkerManager.getMarker("GrandParent1")),
                    MarkerManager.getMarker("Parent2")))
                .setThreadId(1L)
                .setThreadName("AnotherThread-B")
                .setThreadPriority(1)
                .setTimeMillis(987654321564L)
                .setThrown(exception2)
                .setContextMap(context)
                .setContextStack(stack)
                .build();

            manager.writeInternal(event);
            then(connection).should().insertObject(captor.capture());

            final NoSqlObject<Map<String, Object>> inserted = captor.getValue();
            assertNotNull("The inserted value should not be null.", inserted);
            final Map<String, Object> object = inserted.unwrap();
            assertNotNull("The unwrapped object should not be null.", object);

            assertEquals("The level is not correct.", Level.DEBUG, object.get("level"));
            assertEquals("The logger is not correct.", "com.foo.NoSQLDbTest.testWriteInternal02",
                object.get("loggerName"));
            assertEquals("The message is not correct.", "Another cool message 02.", object.get("message"));
            assertEquals("The thread is not correct.", "AnotherThread-B", object.get("threadName"));
            assertEquals("The millis is not correct.", 987654321564L, object.get("millis"));
            assertEquals("The date is not correct.", 987654321564L, ((Date) object.get("date")).getTime());

            assertTrue("The source should be a map.", object.get("source") instanceof Map);
            @SuppressWarnings("unchecked")
            final Map<String, Object> source = (Map<String, Object>) object.get("source");
            assertEquals("The class is not correct.", "com.bar.Foo", source.get("className"));
            assertEquals("The method is not correct.", "anotherMethod03", source.get("methodName"));
            assertEquals("The file name is not correct.", "Foo.java", source.get("fileName"));
            assertEquals("The line number is not correct.", 9, source.get("lineNumber"));

            assertTrue("The marker should be a map.", object.get("marker") instanceof Map);
            @SuppressWarnings("unchecked")
            final Map<String, Object> marker = (Map<String, Object>) object.get("marker");
            assertEquals("The marker name is not correct.", "AnotherMarker", marker.get("name"));

            assertTrue("The marker parents should be a list.", marker.get("parents") instanceof List);
            @SuppressWarnings("unchecked")
            final List<Object> markerParents = (List<Object>) marker.get("parents");
            assertEquals("The marker parents should contain two parents", 2, markerParents.size());

            assertTrue("The marker parents[0] should be a map.", markerParents.get(0) instanceof Map);
            @SuppressWarnings("unchecked")
            final Map<String, Object> parent1 = (Map<String, Object>) markerParents.get(0);
            assertEquals("The first marker parent name is not correct.", "Parent1", parent1.get("name"));

            assertTrue("The marker parents[1] should be a map.", markerParents.get(1) instanceof Map);
            @SuppressWarnings("unchecked")
            final Map<String, Object> parent2 = (Map<String, Object>) markerParents.get(1);
            assertEquals("The second marker parent name is not correct.", "Parent2", parent2.get("name"));
            assertNull("The second marker should have no parent.", parent2.get("parent"));

            assertTrue("The parent1 parents should be a list.", parent1.get("parents") instanceof List);
            @SuppressWarnings("unchecked")
            final List<Object> parent1Parents = (List<Object>) parent1.get("parents");
            assertEquals("The parent1 parents should have only one parent", 1, parent1Parents.size());

            assertTrue("The parent1Parents[0] should be a map.", parent1Parents.get(0) instanceof Map);
            @SuppressWarnings("unchecked")
            final Map<String, Object> parent1parent = (Map<String, Object>) parent1Parents.get(0);
            assertEquals("The first parent1 parent name is not correct.", "GrandParent1", parent1parent.get("name"));
            assertNull("The parent1parent marker should have no parent.", parent1parent.get("parent"));

            assertTrue("The thrown should be a map.", object.get("thrown") instanceof Map);
            @SuppressWarnings("unchecked")
            final Map<String, Object> thrown = (Map<String, Object>) object.get("thrown");
            assertEquals("The thrown type is not correct.", "java.sql.SQLException", thrown.get("type"));
            assertEquals("The thrown message is not correct.", "This is the result.", thrown.get("message"));
            assertTrue("The thrown stack trace should be a list.", thrown.get("stackTrace") instanceof List);
            @SuppressWarnings("unchecked")
            final List<Map<String, Object>> stackTrace = (List<Map<String, Object>>) thrown.get("stackTrace");
            assertEquals("The thrown stack trace length is not correct.", exception2.getStackTrace().length,
                stackTrace.size());
            for (int i = 0; i < exception2.getStackTrace().length; i++) {
                final StackTraceElement e1 = exception2.getStackTrace()[i];
                final Map<String, Object> e2 = stackTrace.get(i);

                assertEquals("Element class name [" + i + "] is not correct.", e1.getClassName(), e2.get("className"));
                assertEquals("Element method name [" + i + "] is not correct.", e1.getMethodName(),
                    e2.get("methodName"));
                assertEquals("Element file name [" + i + "] is not correct.", e1.getFileName(), e2.get("fileName"));
                assertEquals("Element line number [" + i + "] is not correct.", e1.getLineNumber(),
                    e2.get("lineNumber"));
            }
            assertTrue("The thrown cause should be a map.", thrown.get("cause") instanceof Map);
            @SuppressWarnings("unchecked")
            final Map<String, Object> cause = (Map<String, Object>) thrown.get("cause");
            assertEquals("The cause type is not correct.", "java.io.IOException", cause.get("type"));
            assertEquals("The cause message is not correct.", "This is the cause.", cause.get("message"));
            assertTrue("The cause stack trace should be a list.", cause.get("stackTrace") instanceof List);
            @SuppressWarnings("unchecked")
            final List<Map<String, Object>> causeStackTrace = (List<Map<String, Object>>) cause.get("stackTrace");
            assertEquals("The cause stack trace length is not correct.", exception1.getStackTrace().length,
                causeStackTrace.size());
            for (int i = 0; i < exception1.getStackTrace().length; i++) {
                final StackTraceElement e1 = exception1.getStackTrace()[i];
                final Map<String, Object> e2 = causeStackTrace.get(i);

                assertEquals("Element class name [" + i + "] is not correct.", e1.getClassName(), e2.get("className"));
                assertEquals("Element method name [" + i + "] is not correct.", e1.getMethodName(),
                    e2.get("methodName"));
                assertEquals("Element file name [" + i + "] is not correct.", e1.getFileName(), e2.get("fileName"));
                assertEquals("Element line number [" + i + "] is not correct.", e1.getLineNumber(),
                    e2.get("lineNumber"));
            }
            assertNull("The cause should have no cause.", cause.get("cause"));

            assertTrue("The context map should be a map.", object.get("contextMap") instanceof Map);
            assertEquals("The context map is not correct.", context, object.get("contextMap"));

            assertTrue("The context stack should be list.", object.get("contextStack") instanceof List);
            assertEquals("The context stack is not correct.", stack.asList(), object.get("contextStack"));
        }
    }

    @Test
    public void testWriteInternal03() {
        final NoSqlDatabaseManager<?> manager = NoSqlDatabaseManager.getNoSqlDatabaseManager("name", 0, this.provider);

        try {
            replay(this.provider, this.connection);

            manager.startup();

            verify(this.provider, this.connection);
            reset(this.provider, this.connection);
            expect(this.provider.getConnection()).andReturn(this.connection);
            replay(this.provider, this.connection);

            manager.connectAndStart();

            verify(this.provider, this.connection);
            reset(this.provider, this.connection);

            final Capture<NoSqlObject<Map<String, Object>>> capture = EasyMock.newCapture();

            final IOException exception1 = new IOException("This is the cause.");
            final SQLException exception2 = new SQLException("This is the result.", exception1);
            final Map<String, String> context = new HashMap<>();
            context.put("hello", "world");
            context.put("user", "pass");

            final LogEvent event = createStrictMock(LogEvent.class);
            final Message message = createStrictMock(Message.class);
            ThreadContext.push("message1");
            ThreadContext.push("stack2");
            final ThreadContext.ContextStack stack = ThreadContext.getImmutableStack();
            ThreadContext.clearStack();

            expect(this.connection.isClosed()).andReturn(false);
            expect(this.connection.createObject()).andAnswer(new IAnswer<DefaultNoSqlObject>() {
                @Override
                public DefaultNoSqlObject answer() throws Throwable {
                    return new DefaultNoSqlObject();
                }
            }).atLeastOnce();
            expect(this.connection.createList(anyInt())).andAnswer(new IAnswer<DefaultNoSqlObject[]>() {
                @Override
                public DefaultNoSqlObject[] answer() throws Throwable {
                    return new DefaultNoSqlObject[(Integer) getCurrentArguments()[0]];
                }
            });
            expect(this.connection.createObject()).andAnswer(new IAnswer<DefaultNoSqlObject>() {
                @Override
                public DefaultNoSqlObject answer() throws Throwable {
                    return new DefaultNoSqlObject();
                }
            }).atLeastOnce();
            expect(this.connection.createList(anyInt())).andAnswer(new IAnswer<DefaultNoSqlObject[]>() {
                @Override
                public DefaultNoSqlObject[] answer() throws Throwable {
                    return new DefaultNoSqlObject[(Integer) getCurrentArguments()[0]];
                }
            });
            expect(this.connection.createObject()).andAnswer(new IAnswer<DefaultNoSqlObject>() {
                @Override
                public DefaultNoSqlObject answer() throws Throwable {
                    return new DefaultNoSqlObject();
                }
            }).atLeastOnce();
            expect(event.getLevel()).andReturn(Level.DEBUG);
            expect(event.getLoggerName()).andReturn("com.foo.NoSQLDbTest.testWriteInternal02");
            expect(event.getMessage()).andReturn(message).times(2);
            expect(message.getFormattedMessage()).andReturn("Another cool message 02.");
            expect(event.getSource()).andReturn(new StackTraceElement("com.bar.Foo", "anotherMethod03", "Foo.java", 9));
            expect(event.getMarker()).andReturn(
                    MarkerManager.getMarker("AnotherMarker").addParents(MarkerManager.getMarker("Parent1").addParents(MarkerManager.getMarker("GrandParent1")),
                            MarkerManager.getMarker("Parent2")));
            expect(event.getThreadId()).andReturn(1L);
            expect(event.getThreadName()).andReturn("AnotherThread-B");
            expect(event.getThreadPriority()).andReturn(1);
            expect(event.getTimeMillis()).andReturn(987654321564L).times(2);
            expect(event.getThrown()).andReturn(exception2);
            expect(event.getContextMap()).andReturn(context);
            expect(event.getContextStack()).andReturn(stack);
            this.connection.insertObject(capture(capture));
            expectLastCall();
            replay(this.provider, this.connection, event, message);

            manager.writeInternal(event);

            final NoSqlObject<Map<String, Object>> inserted = capture.getValue();
            assertNotNull("The inserted value should not be null.", inserted);
            final Map<String, Object> object = inserted.unwrap();
            assertNotNull("The unwrapped object should not be null.", object);

            assertEquals("The level is not correct.", Level.DEBUG, object.get("level"));
            assertEquals("The logger is not correct.", "com.foo.NoSQLDbTest.testWriteInternal02",
                    object.get("loggerName"));
            assertEquals("The message is not correct.", "Another cool message 02.", object.get("message"));
            assertEquals("The thread is not correct.", "AnotherThread-B", object.get("threadName"));
            assertEquals("The millis is not correct.", 987654321564L, object.get("millis"));
            assertEquals("The date is not correct.", 987654321564L, ((Date) object.get("date")).getTime());

            assertTrue("The source should be a map.", object.get("source") instanceof Map);
            @SuppressWarnings("unchecked")
            final Map<String, Object> source = (Map<String, Object>) object.get("source");
            assertEquals("The class is not correct.", "com.bar.Foo", source.get("className"));
            assertEquals("The method is not correct.", "anotherMethod03", source.get("methodName"));
            assertEquals("The file name is not correct.", "Foo.java", source.get("fileName"));
            assertEquals("The line number is not correct.", 9, source.get("lineNumber"));

            assertTrue("The marker should be a map.", object.get("marker") instanceof Map);
            @SuppressWarnings("unchecked")
            final Map<String, Object> marker = (Map<String, Object>) object.get("marker");
            assertEquals("The marker name is not correct.", "AnotherMarker", marker.get("name"));

            assertTrue("The marker parents should be a list.", marker.get("parents") instanceof List);
            @SuppressWarnings("unchecked")
            final List<Object> markerParents = (List<Object>) marker.get("parents");
            assertEquals("The marker parents should contain two parents", 2, markerParents.size());

            assertTrue("The marker parents[0] should be a map.", markerParents.get(0) instanceof Map);
            @SuppressWarnings("unchecked")
            final Map<String, Object> parent1 = (Map<String, Object>) markerParents.get(0);
            assertEquals("The first marker parent name is not correct.", "Parent1", parent1.get("name"));

            assertTrue("The marker parents[1] should be a map.", markerParents.get(1) instanceof Map);
            @SuppressWarnings("unchecked")
            final Map<String, Object> parent2 = (Map<String, Object>) markerParents.get(1);
            assertEquals("The second marker parent name is not correct.", "Parent2", parent2.get("name"));
            assertNull("The second marker should have no parent.", parent2.get("parent"));

            assertTrue("The parent1 parents should be a list.", parent1.get("parents") instanceof List);
            @SuppressWarnings("unchecked")
            final List<Object> parent1Parents = (List<Object>) parent1.get("parents");
            assertEquals("The parent1 parents should have only one parent", 1, parent1Parents.size());

            assertTrue("The parent1Parents[0] should be a map.", parent1Parents.get(0) instanceof Map);
            @SuppressWarnings("unchecked")
            final Map<String, Object> parent1parent = (Map<String, Object>) parent1Parents.get(0);
            assertEquals("The first parent1 parent name is not correct.", "GrandParent1", parent1parent.get("name"));
            assertNull("The parent1parent marker should have no parent.", parent1parent.get("parent"));

            assertTrue("The thrown should be a map.", object.get("thrown") instanceof Map);
            @SuppressWarnings("unchecked")
            final Map<String, Object> thrown = (Map<String, Object>) object.get("thrown");
            assertEquals("The thrown type is not correct.", "java.sql.SQLException", thrown.get("type"));
            assertEquals("The thrown message is not correct.", "This is the result.", thrown.get("message"));
            assertTrue("The thrown stack trace should be a list.", thrown.get("stackTrace") instanceof List);
            @SuppressWarnings("unchecked")
            final List<Map<String, Object>> stackTrace = (List<Map<String, Object>>) thrown.get("stackTrace");
            assertEquals("The thrown stack trace length is not correct.", exception2.getStackTrace().length,
                    stackTrace.size());
            for (int i = 0; i < exception2.getStackTrace().length; i++) {
                final StackTraceElement e1 = exception2.getStackTrace()[i];
                final Map<String, Object> e2 = stackTrace.get(i);

                assertEquals("Element class name [" + i + "] is not correct.", e1.getClassName(), e2.get("className"));
                assertEquals("Element method name [" + i + "] is not correct.", e1.getMethodName(),
                        e2.get("methodName"));
                assertEquals("Element file name [" + i + "] is not correct.", e1.getFileName(), e2.get("fileName"));
                assertEquals("Element line number [" + i + "] is not correct.", e1.getLineNumber(),
                        e2.get("lineNumber"));
            }
            assertTrue("The thrown cause should be a map.", thrown.get("cause") instanceof Map);
            @SuppressWarnings("unchecked")
            final Map<String, Object> cause = (Map<String, Object>) thrown.get("cause");
            assertEquals("The cause type is not correct.", "java.io.IOException", cause.get("type"));
            assertEquals("The cause message is not correct.", "This is the cause.", cause.get("message"));
            assertTrue("The cause stack trace should be a list.", cause.get("stackTrace") instanceof List);
            @SuppressWarnings("unchecked")
            final List<Map<String, Object>> causeStackTrace = (List<Map<String, Object>>) cause.get("stackTrace");
            assertEquals("The cause stack trace length is not correct.", exception1.getStackTrace().length,
                    causeStackTrace.size());
            for (int i = 0; i < exception1.getStackTrace().length; i++) {
                final StackTraceElement e1 = exception1.getStackTrace()[i];
                final Map<String, Object> e2 = causeStackTrace.get(i);

                assertEquals("Element class name [" + i + "] is not correct.", e1.getClassName(), e2.get("className"));
                assertEquals("Element method name [" + i + "] is not correct.", e1.getMethodName(),
                        e2.get("methodName"));
                assertEquals("Element file name [" + i + "] is not correct.", e1.getFileName(), e2.get("fileName"));
                assertEquals("Element line number [" + i + "] is not correct.", e1.getLineNumber(),
                        e2.get("lineNumber"));
            }
            assertNull("The cause should have no cause.", cause.get("cause"));

            assertTrue("The context map should be a map.", object.get("contextMap") instanceof Map);
            assertEquals("The context map is not correct.", context, object.get("contextMap"));

            assertTrue("The context stack should be list.", object.get("contextStack") instanceof List);
            assertEquals("The context stack is not correct.", stack.asList(), object.get("contextStack"));

            verify(this.provider, this.connection, event, message);
        } finally {
            try {
                manager.close();
            } catch (final Throwable ignore) {
                /* */
            }
        }
    }

Try With Resources try(final NoSqlDatabaseManager<?> manager=NoSqlDatabaseManager.getNoSqlDatabaseManager("name",0,provider)) in method public testWriteInternal03() : void from class org.apache.logging.log4j.nosql.appender.NoSqlDatabaseManagerTest


    /**
     * Looks up the value of the JNDI resource.
     * @param event The current LogEvent (is ignored by this StrLookup).
     * @param key  the JNDI resource name to be looked up, may be null
     * @return The String value of the JNDI resource.
     */
    @Override
    public String lookup(final LogEvent event, final String key) {
        if (key == null) {
            return null;
        }
        final String jndiName = convertJndiName(key);
        try (final JndiManager jndiManager = JndiManager.getDefaultManager()) {
            final Object value = jndiManager.lookup(jndiName);
            return value == null ? null : String.valueOf(value);
        } catch (final NamingException e) {
            LOGGER.warn(LOOKUP, "Error looking up JNDI resource [{}].", jndiName, e);
            return null;
        }
    }

    /**
     * Looks up the value of the JNDI resource.
     * @param event The current LogEvent (is ignored by this StrLookup).
     * @param key  the JNDI resource name to be looked up, may be null
     * @return The String value of the JNDI resource.
     */
    @Override
    public String lookup(final LogEvent event, final String key) {
        if (key == null) {
            return null;
        }
        final String jndiName = convertJndiName(key);
        final JndiManager jndiManager = JndiManager.getDefaultManager();
        try {
            final Object value = jndiManager.lookup(jndiName);
            return value == null ? null : String.valueOf(value);
        } catch (final NamingException e) {
            LOGGER.warn(LOOKUP, "Error looking up JNDI resource [{}].", jndiName, e);
            return null;
        } finally {
            jndiManager.close();
        }
    }

Try With Resources try(final JndiManager jndiManager=JndiManager.getDefaultManager()) in method public lookup(event LogEvent, key String) : String from class org.apache.logging.log4j.core.lookup.JndiLookup


    @Override
    public Map<String, String> getCopy() {
        return new HashMap<>();
    }

    @Override
    public Map<String, String> getCopy() {
        return new HashMap<String, String>();
    }

Replace Generic With Diamond HashMap<String,String> with HashMap<> in method public getCopy() : Map<String,String> from class org.apache.logging.log4j.spi.NoOpThreadContextMap


        @Override
        public void run() {
            try {
                try (final Socket socket = sock.accept()) {
                    if (socket != null) {
                        final ObjectInputStream ois = new ObjectInputStream(socket.getInputStream());
                        while (!shutdown) {
                            queue.add((LogEvent) ois.readObject());
                            ++count;
                        }
                    }
                }
            } catch (final EOFException eof) {
                // Socket is closed.
            } catch (final Exception e) {
                if (!shutdown) {
                    Throwables.rethrow(e);
                }
            }
        }

        @Override
        public void run() {
            try {
                final Socket socket = sock.accept();
                if (socket != null) {
                    final ObjectInputStream ois = new ObjectInputStream(socket.getInputStream());
                    while (!shutdown) {
                        list.add((LogEvent) ois.readObject());
                        ++tcpCount;
                    }
                }
            } catch (final EOFException eof) {
                // Socket is closed.
            } catch (final Exception e) {
                if (!shutdown) {
                    Throwables.rethrow(e);
                }
            }
        }

Try With Resources try(final Socket socket=sock.accept()) in method public run() : void from class org.apache.logging.log4j.core.appender.SocketAppenderTest.TCPSocketServer


    @Test
	public void testWriteInternalNotConnected01() {
		replay(this.provider, this.connection);

		try (final NoSqlDatabaseManager<?> manager = NoSqlDatabaseManager.getNoSqlDatabaseManager("name", 0,
				this.provider)) {

			verify(this.provider, this.connection);
			reset(this.provider, this.connection);

			final LogEvent event = createStrictMock(LogEvent.class);
			replay(this.provider, this.connection, event);

			try {
				manager.writeInternal(event);
				fail("Expected AppenderLoggingException.");
			} catch (final AppenderLoggingException ignore) {
				/* */
			}

			verify(event);
		}
	}

    @Test
    public void testWriteInternalNotConnected01() {
        replay(this.provider, this.connection);

        final NoSqlDatabaseManager<?> manager = NoSqlDatabaseManager.getNoSqlDatabaseManager("name", 0, this.provider);

        try {
            verify(this.provider, this.connection);
            reset(this.provider, this.connection);

            final LogEvent event = createStrictMock(LogEvent.class);
            replay(this.provider, this.connection, event);

            try {
                manager.writeInternal(event);
                fail("Expected AppenderLoggingException.");
            } catch (final AppenderLoggingException ignore) {
                /* */
            }

            verify(event);
        } finally {
            try {
                manager.close();
            } catch (final Throwable ignore) {
                /* */
            }
        }
    }

Try With Resources try(final NoSqlDatabaseManager<?> manager=NoSqlDatabaseManager.getNoSqlDatabaseManager("name",0,this.provider)) in method public testWriteInternalNotConnected01() : void from class org.apache.logging.log4j.nosql.appender.NoSqlDatabaseManagerTest


    @Test
	public void testConnection() {
		replay(this.provider, this.connection);

		try (final NoSqlDatabaseManager<?> manager = NoSqlDatabaseManager.getNoSqlDatabaseManager("name", 0,
				this.provider)) {

			assertNotNull("The manager should not be null.", manager);

			verify(this.provider, this.connection);
			reset(this.provider, this.connection);
			expect(this.provider.getConnection()).andReturn(this.connection);
			replay(this.provider, this.connection);

			manager.connectAndStart();
			manager.commitAndClose();
		}
	}

    @Test
    public void testConnection() {
        replay(this.provider, this.connection);

        final NoSqlDatabaseManager<?> manager = NoSqlDatabaseManager.getNoSqlDatabaseManager("name", 0, this.provider);

        assertNotNull("The manager should not be null.", manager);

        try {
            verify(this.provider, this.connection);
            reset(this.provider, this.connection);
            expect(this.provider.getConnection()).andReturn(this.connection);
            replay(this.provider, this.connection);

            manager.connectAndStart();
            manager.commitAndClose();
        } finally {
            try {
                manager.close();
            } catch (final Throwable ignore) {
                /* */
            }
        }
    }

Try With Resources try(final NoSqlDatabaseManager<?> manager=NoSqlDatabaseManager.getNoSqlDatabaseManager("name",0,this.provider)) in method public testConnection() : void from class org.apache.logging.log4j.nosql.appender.NoSqlDatabaseManagerTest


    public void tearDown() throws SQLException {
        final LoggerContext context = LoggerContext.getContext(false);
        try {
            final Appender appender = context.getConfiguration().getAppender("databaseAppender");
            assertNotNull("The appender should not be null.", appender);
            assertTrue("The appender should be a JpaAppender.", appender instanceof JpaAppender);
            ((JpaAppender) appender).getManager().release();
        } finally {
            System.clearProperty(ConfigurationFactory.CONFIGURATION_FILE_PROPERTY);
            context.reconfigure();
            StatusLogger.getLogger().reset();

            try (Statement statement = this.connection.createStatement();) {
                statement.execute("SHUTDOWN");
            }

            this.connection.close();
        }
    }

    public void tearDown() throws SQLException {
        final LoggerContext context = LoggerContext.getContext(false);
        try {
            final Appender appender = context.getConfiguration().getAppender("databaseAppender");
            assertNotNull("The appender should not be null.", appender);
            assertTrue("The appender should be a JpaAppender.", appender instanceof JpaAppender);
            ((JpaAppender) appender).getManager().release();
        } finally {
            System.clearProperty(ConfigurationFactory.CONFIGURATION_FILE_PROPERTY);
            context.reconfigure();
            StatusLogger.getLogger().reset();

            Statement statement = null;
            try {
                statement = this.connection.createStatement();
                statement.execute("SHUTDOWN");
            } finally {
                try {
                    if (statement != null) {
                        statement.close();
                    }
                } catch (final SQLException ignore) {
                    /* */
                }
            }

            this.connection.close();
        }
    }

Try With Resources try(Statement statement=this.connection.createStatement()) in method public tearDown() : void from class org.apache.logging.log4j.core.appender.db.jpa.AbstractJpaAppenderTest


    @After
    public void tearDown() throws SQLException {
        final LoggerContext context = LoggerContext.getContext(false);
        try {
            final Appender appender = context.getConfiguration().getAppender("databaseAppender");
            assertNotNull("The appender should not be null.", appender);
            assertTrue("The appender should be a JdbcAppender.", appender instanceof JdbcAppender);
            ((JdbcAppender) appender).getManager().release();
        } finally {
            System.clearProperty(ConfigurationFactory.CONFIGURATION_FILE_PROPERTY);
            context.reconfigure();
            StatusLogger.getLogger().reset();

            try (Statement statement = this.connection.createStatement()) {
                statement.execute("SHUTDOWN");
            }

            this.connection.close();
        }
    }

    @After
    public void tearDown() throws SQLException {
        final LoggerContext context = LoggerContext.getContext(false);
        try {
            final Appender appender = context.getConfiguration().getAppender("databaseAppender");
            assertNotNull("The appender should not be null.", appender);
            assertTrue("The appender should be a JdbcAppender.", appender instanceof JdbcAppender);
            ((JdbcAppender) appender).getManager().release();
        } finally {
            System.clearProperty(ConfigurationFactory.CONFIGURATION_FILE_PROPERTY);
            context.reconfigure();
            StatusLogger.getLogger().reset();

            Statement statement = null;
            try {
                statement = this.connection.createStatement();
                statement.execute("SHUTDOWN");
            } finally {
                try {
                    if (statement != null) {
                        statement.close();
                    }
                } catch (final SQLException ignore) {
                    /* */
                }
            }

            this.connection.close();
        }
    }

Try With Resources try(Statement statement=this.connection.createStatement()) in method public tearDown() : void from class org.apache.logging.log4j.core.appender.db.jdbc.AbstractJdbcAppenderTest


    @Test
    public void testPolicy() throws Exception {
        final Configuration configuration = new DefaultConfiguration();
        final Path target = Paths.get(TARGET_FILE);
        target.toFile().getParentFile().mkdirs();
        final long timeStamp = System.currentTimeMillis() - (1000 * 60 * 60 * 24);
        final String expectedDate = formatter.format(timeStamp);
        final String rolledFileName = ROLLED_FILE_PREFIX + expectedDate + ROLLED_FILE_SUFFIX;
        final Path rolled = Paths.get(rolledFileName);
        final long copied;
        try (final InputStream is = new ByteArrayInputStream(TEST_DATA.getBytes("UTF-8"))) {
            copied = Files.copy(is, target, StandardCopyOption.REPLACE_EXISTING);
        }
        final long size = Files.size(target);
        assertTrue(size > 0);
        assertEquals(copied, size);

        Assert.assertTrue(target.toFile().setLastModified(timeStamp));
        final PatternLayout layout = PatternLayout.newBuilder().withPattern("%msg").withConfiguration(configuration)
                .build();
        final RolloverStrategy strategy = DefaultRolloverStrategy.createStrategy(null, null, null, "0", null, true,
                configuration);
        final OnStartupTriggeringPolicy policy = OnStartupTriggeringPolicy.createPolicy(1);
        try (final RollingFileManager manager = RollingFileManager.getFileManager(TARGET_FILE, TARGET_PATTERN, true, false,
                policy, strategy, null, layout, 8192, true, false, configuration)) {
            manager.initialize();
            String files = Arrays.toString(new File(TARGET_FOLDER).listFiles());
            assertTrue(target.toString() + ", files = " + files, Files.exists(target));
            assertEquals(target.toString(), 0, Files.size(target));
            assertTrue("Missing: " + rolled.toString() + ", files on disk = " + files, Files.exists(rolled));
            assertEquals(rolled.toString(), size, Files.size(rolled));
        }
    }

    @Test
    public void testPolicy() throws Exception {
        final Configuration configuration = new DefaultConfiguration();
        final Path target = Paths.get(TARGET_FILE);
        target.toFile().getParentFile().mkdirs();
        final long timeStamp = System.currentTimeMillis() - (1000 * 60 * 60 * 24);
        final String expectedDate = formatter.format(timeStamp);
        final String rolledFileName = ROLLED_FILE_PREFIX + expectedDate + ROLLED_FILE_SUFFIX;
        final Path rolled = Paths.get(rolledFileName);
        final long copied;
        try (final InputStream is = new ByteArrayInputStream(TEST_DATA.getBytes("UTF-8"))) {
            copied = Files.copy(is, target, StandardCopyOption.REPLACE_EXISTING);
        }
        final long size = Files.size(target);
        assertTrue(size > 0);
        assertEquals(copied, size);

        Assert.assertTrue(target.toFile().setLastModified(timeStamp));
        final PatternLayout layout = PatternLayout.newBuilder().withPattern("%msg").withConfiguration(configuration)
                .build();
        final RolloverStrategy strategy = DefaultRolloverStrategy.createStrategy(null, null, null, "0", null, true,
                configuration);
        final OnStartupTriggeringPolicy policy = OnStartupTriggeringPolicy.createPolicy(1);
        final RollingFileManager manager = RollingFileManager.getFileManager(TARGET_FILE, TARGET_PATTERN, true, false,
                policy, strategy, null, layout, 8192, true, false, configuration);
        try {
            manager.initialize();
            String files = Arrays.toString(new File(TARGET_FOLDER).listFiles());
            assertTrue(target.toString() + ", files = " + files, Files.exists(target));
            assertEquals(target.toString(), 0, Files.size(target));
            assertTrue("Missing: " + rolled.toString() + ", files on disk = " + files, Files.exists(rolled));
            assertEquals(rolled.toString(), size, Files.size(rolled));
        } finally {
            manager.close();
        }
    }

Try With Resources try(final RollingFileManager manager=RollingFileManager.getFileManager(TARGET_FILE,TARGET_PATTERN,true,false,policy,strategy,null,layout,8192,true,false,configuration)) in method public testPolicy() : void from class org.apache.logging.log4j.core.appender.rolling.OnStartupTriggeringPolicyTest


    @Override
    public PropertiesConfiguration getConfiguration(final ConfigurationSource source) {
        final Properties properties = new Properties();
        try (final InputStream configStream = source.getInputStream()) {
            properties.load(configStream);
        } catch (final IOException ioe) {
            throw new ConfigurationException("Unable to load " + source.toString(), ioe);
        }
        return new PropertiesConfigurationBuilder().setConfigurationSource(source)
                .setRootProperties(properties).build();
    }

    @Override
    public PropertiesConfiguration getConfiguration(final ConfigurationSource source) {
        final InputStream configStream = source.getInputStream();
        final Properties properties = new Properties();
        try {
            properties.load(configStream);
        } catch (final IOException ioe) {
            throw new ConfigurationException("Unable to load " + source.toString(), ioe);
        }
        return new PropertiesConfigurationBuilder().setConfigurationSource(source)
                .setRootProperties(properties).build();
    }

Try With Resources try(final InputStream configStream=source.getInputStream()) in method public getConfiguration(source ConfigurationSource) : PropertiesConfiguration from class org.apache.logging.log4j.core.config.properties.PropertiesConfigurationFactory


    @Override
    public Configuration getConfiguration(final ConfigurationSource source) {
        final ConfigurationBuilder<BuiltConfiguration> builder;
        try (final InputStream configStream = source.getInputStream()) {
            builder = new Log4j1ConfigurationParser().buildConfigurationBuilder(configStream);
        } catch (IOException e) {
            throw new ConfigurationException("Unable to load " + source.toString(), e);
        }
        if (builder == null) return null;
        return builder.build();
    }

    @Override
    public Configuration getConfiguration(final ConfigurationSource source) {
        final ConfigurationBuilder<BuiltConfiguration> builder;
        try {
            builder = new Log4j1ConfigurationParser().buildConfigurationBuilder(source.getInputStream());
        } catch (IOException e) {
            throw new ConfigurationException("Unable to load " + source.toString(), e);
        }
        if (builder == null) return null;
        return builder.build();
    }

Try With Resources try(final InputStream configStream=source.getInputStream()) in method public getConfiguration(source ConfigurationSource) : Configuration from class org.apache.log4j.config.Log4j1ConfigurationFactory


    @Override
    protected synchronized void write(final byte[] bytes, final int offset, final int length, final boolean immediateFlush)  {

        if (isLocking) {
            final FileChannel channel = ((FileOutputStream) getOutputStream()).getChannel();
            try {
                /* Lock the whole file. This could be optimized to only lock from the current file
                   position. Note that locking may be advisory on some systems and mandatory on others,
                   so locking just from the current position would allow reading on systems where
                   locking is mandatory.  Also, Java 6 will throw an exception if the region of the
                   file is already locked by another FileChannel in the same JVM. Hopefully, that will
                   be avoided since every file should have a single file manager - unless two different
                   files strings are configured that somehow map to the same file.*/
                try (final FileLock lock = channel.lock(0, Long.MAX_VALUE, false)) {
                    super.write(bytes, offset, length, immediateFlush);
                }
            } catch (final IOException ex) {
                throw new AppenderLoggingException("Unable to obtain lock on " + getName(), ex);
            }

        } else {
            super.write(bytes, offset, length, immediateFlush);
        }
    }

    @Override
    protected synchronized void write(final byte[] bytes, final int offset, final int length, final boolean immediateFlush)  {

        if (isLocking) {
            final FileChannel channel = ((FileOutputStream) getOutputStream()).getChannel();
            try {
                /* Lock the whole file. This could be optimized to only lock from the current file
                   position. Note that locking may be advisory on some systems and mandatory on others,
                   so locking just from the current position would allow reading on systems where
                   locking is mandatory.  Also, Java 6 will throw an exception if the region of the
                   file is already locked by another FileChannel in the same JVM. Hopefully, that will
                   be avoided since every file should have a single file manager - unless two different
                   files strings are configured that somehow map to the same file.*/
                final FileLock lock = channel.lock(0, Long.MAX_VALUE, false);
                try {
                    super.write(bytes, offset, length, immediateFlush);
                } finally {
                    lock.release();
                }
            } catch (final IOException ex) {
                throw new AppenderLoggingException("Unable to obtain lock on " + getName(), ex);
            }

        } else {
            super.write(bytes, offset, length, immediateFlush);
        }
    }

Try With Resources try(final FileLock lock=channel.lock(0,Long.MAX_VALUE,false)) in method protected write(bytes byte[], offset int, length int, immediateFlush boolean) : void from class org.apache.logging.log4j.core.appender.FileManager


    /**
     * @param args
     */
    public static void main(final String[] args) {
        try (final LoggerContext ctx = Configurator.initialize(FormatterLoggerManualExample.class.getName(),
                "target/test-classes/log4j2-console.xml");) {
            final User user = new User();
            logger.debug("User %s with birthday %s", user.getName(), user.getBirthdayCalendar());
            logger.debug("User %1$s with birthday %2$tm %2$te, %2$tY", user.getName(), user.getBirthdayCalendar());
            logger.debug("Integer.MAX_VALUE = %,d", Integer.MAX_VALUE);
            logger.debug("Long.MAX_VALUE = %,d", Long.MAX_VALUE);
        }

    }

    /**
     * @param args
     */
    public static void main(final String[] args) {
        final LoggerContext ctx = Configurator.initialize(FormatterLoggerManualExample.class.getName(),
                "target/test-classes/log4j2-console.xml");
        try {
            final User user = new User();
            logger.debug("User %s with birthday %s", user.getName(), user.getBirthdayCalendar());
            logger.debug("User %1$s with birthday %2$tm %2$te, %2$tY", user.getName(), user.getBirthdayCalendar());
            logger.debug("Integer.MAX_VALUE = %,d", Integer.MAX_VALUE);
            logger.debug("Long.MAX_VALUE = %,d", Long.MAX_VALUE);
        } finally {
            Configurator.shutdown(ctx);
        }

    }

Try With Resources try(final LoggerContext ctx=Configurator.initialize(FormatterLoggerManualExample.class.getName(),"target/test-classes/log4j2-console.xml")) in method public main(args String[]) : void from class org.apache.logging.log4j.FormatterLoggerManualExample


    public static void main(final String[] args) {
        try (final LoggerContext ctx = Configurator.initialize(ConsoleAppenderAnsiMessagesMain.class.getName(),
                "target/test-classes/log4j2-console.xml")) {
            LOG.fatal("\u001b[1;35mFatal message.\u001b[0m");
            LOG.error("\u001b[1;31mError message.\u001b[0m");
            LOG.warn("\u001b[0;33mWarning message.\u001b[0m");
            LOG.info("\u001b[0;32mInformation message.\u001b[0m");
            LOG.debug("\u001b[0;36mDebug message.\u001b[0m");
            LOG.trace("\u001b[0;30mTrace message.\u001b[0m");
            LOG.error("\u001b[1;31mError message.\u001b[0m", new IOException("test"));
        }
    }

    public static void main(final String[] args) {
        final LoggerContext ctx = Configurator.initialize(ConsoleAppenderAnsiMessagesMain.class.getName(),
                "target/test-classes/log4j2-console.xml");
        try {
            LOG.fatal("\u001b[1;35mFatal message.\u001b[0m");
            LOG.error("\u001b[1;31mError message.\u001b[0m");
            LOG.warn("\u001b[0;33mWarning message.\u001b[0m");
            LOG.info("\u001b[0;32mInformation message.\u001b[0m");
            LOG.debug("\u001b[0;36mDebug message.\u001b[0m");
            LOG.trace("\u001b[0;30mTrace message.\u001b[0m");
            LOG.error("\u001b[1;31mError message.\u001b[0m", new IOException("test"));
        } finally {
            Configurator.shutdown(ctx);
        }
    }

Try With Resources try(final LoggerContext ctx=Configurator.initialize(ConsoleAppenderAnsiMessagesMain.class.getName(),"target/test-classes/log4j2-console.xml")) in method public main(args String[]) : void from class org.apache.logging.log4j.core.appender.ConsoleAppenderAnsiMessagesMain


    public static void main(final String[] args) {
        // System.out.println(System.getProperty("java.class.path"));
        final String config = args.length == 0 ? "target/test-classes/log4j2-180.xml" : args[0];
        try (final LoggerContext ctx = Configurator.initialize(ConsoleAppenderAnsiMessagesMain.class.getName(),
                config)) {
            LOG.fatal("Fatal message.");
            LOG.error("Error message.");
            LOG.warn("Warning message.");
            LOG.info("Information message.");
            LOG.debug("Debug message.");
            LOG.trace("Trace message.");
            try {
                throw new NullPointerException();
            } catch (final Exception e) {
                LOG.error("Error message.", e);
                LOG.catching(Level.ERROR, e);
            }
        }
    }

    public static void main(final String[] args) {
        // System.out.println(System.getProperty("java.class.path"));
        final String config = args.length == 0 ? "target/test-classes/log4j2-180.xml" : args[0];
        final LoggerContext ctx = Configurator.initialize(ConsoleAppenderAnsiMessagesMain.class.getName(), config);
        try {
            LOG.fatal("Fatal message.");
            LOG.error("Error message.");
            LOG.warn("Warning message.");
            LOG.info("Information message.");
            LOG.debug("Debug message.");
            LOG.trace("Trace message.");
            try {
                throw new NullPointerException();
            } catch (final Exception e) {
                LOG.error("Error message.", e);
                LOG.catching(Level.ERROR, e);
            }
        } finally {
            Configurator.shutdown(ctx);
        }
    }

Try With Resources try(final LoggerContext ctx=Configurator.initialize(ConsoleAppenderAnsiMessagesMain.class.getName(),config)) in method public main(args String[]) : void from class org.apache.logging.log4j.core.appender.ConsoleAppenderAnsiStyleJira180Main


    public static void main(final String[] args) {
        // System.out.println(System.getProperty("java.class.path"));
        final String config = args.length == 0 ? "target/test-classes/log4j2-272.xml" : args[0];
        try (final LoggerContext ctx = Configurator.initialize(ConsoleAppenderAnsiMessagesMain.class.getName(), config)) {
            LOG.fatal("Fatal message.");
            LOG.error("Error message.");
            LOG.warn("Warning message.");
            LOG.info("Information message.");
            LOG.debug("Debug message.");
            LOG.trace("Trace message.");
            try {
                throw new NullPointerException();
            } catch (final Exception e) {
                LOG.error("Error message.", e);
                LOG.catching(Level.ERROR, e);
            }
            LOG.warn("this is ok \n And all \n this have only\t\tblack colour \n and here is colour again?");
            LOG.info("Information message.");
        }
    }

    public static void main(final String[] args) {
        // System.out.println(System.getProperty("java.class.path"));
        final String config = args.length == 0 ? "target/test-classes/log4j2-272.xml" : args[0];
        final LoggerContext ctx = Configurator.initialize(ConsoleAppenderAnsiMessagesMain.class.getName(), config);
        try {
            LOG.fatal("Fatal message.");
            LOG.error("Error message.");
            LOG.warn("Warning message.");
            LOG.info("Information message.");
            LOG.debug("Debug message.");
            LOG.trace("Trace message.");
            try {
                throw new NullPointerException();
            } catch (final Exception e) {
                LOG.error("Error message.", e);
                LOG.catching(Level.ERROR, e);
            }
            LOG.warn("this is ok \n And all \n this have only\t\tblack colour \n and here is colour again?");
            LOG.info("Information message.");
        } finally {
            Configurator.shutdown(ctx);
        }
    }

Try With Resources try(final LoggerContext ctx=Configurator.initialize(ConsoleAppenderAnsiMessagesMain.class.getName(),config)) in method public main(args String[]) : void from class org.apache.logging.log4j.core.appender.ConsoleAppenderAnsiStyleJira272Main


    public static void main(final String[] args) {
        // System.out.println(System.getProperty("java.class.path"));
        final String config = args.length == 0 ? "target/test-classes/log4j2-319.xml" : args[0];
        try (final LoggerContext ctx = Configurator.initialize(ConsoleAppenderAnsiMessagesMain.class.getName(),
                config)) {
            LOG.fatal("Fatal message.");
            LOG.error("Error message.");
            LOG.warn("Warning message.");
            LOG.info("Information message.");
            LOG.debug("Debug message.");
            LOG.trace("Trace message.");
            try {
                throw new NullPointerException();
            } catch (final Exception e) {
                LOG.error("Error message.", e);
                LOG.catching(Level.ERROR, e);
            }
            LOG.warn("this is ok \n And all \n this have only\t\tblack colour \n and here is colour again?");
            LOG.info("Information message.");
        }
    }

    public static void main(final String[] args) {
        // System.out.println(System.getProperty("java.class.path"));
        final String config = args.length == 0 ? "target/test-classes/log4j2-319.xml" : args[0];
        final LoggerContext ctx = Configurator.initialize(ConsoleAppenderAnsiMessagesMain.class.getName(), config);
        try {
            LOG.fatal("Fatal message.");
            LOG.error("Error message.");
            LOG.warn("Warning message.");
            LOG.info("Information message.");
            LOG.debug("Debug message.");
            LOG.trace("Trace message.");
            try {
                throw new NullPointerException();
            } catch (final Exception e) {
                LOG.error("Error message.", e);
                LOG.catching(Level.ERROR, e);
            }
            LOG.warn("this is ok \n And all \n this have only\t\tblack colour \n and here is colour again?");
            LOG.info("Information message.");
        } finally {
            Configurator.shutdown(ctx);
        }
    }

Try With Resources try(final LoggerContext ctx=Configurator.initialize(ConsoleAppenderAnsiMessagesMain.class.getName(),config)) in method public main(args String[]) : void from class org.apache.logging.log4j.core.appender.ConsoleAppenderAnsiStyleJira319Main


    public void test(final String[] args) {
        // System.out.println(System.getProperty("java.class.path"));
        final String config = args == null || args.length == 0 ? "target/test-classes/log4j2-console-style-ansi.xml"
                : args[0];
        try (final LoggerContext ctx = Configurator.initialize(ConsoleAppenderAnsiMessagesMain.class.getName(), config)) {
            final Logger logger = LogManager.getLogger(ConsoleAppenderAnsiStyleLayoutMain.class);
            logger.fatal("Fatal message.");
            logger.error("Error message.");
            logger.warn("Warning message.");
            logger.info("Information message.");
            logger.debug("Debug message.");
            logger.trace("Trace message.");
            logger.error("Error message.", new IOException("test"));
        }
    }

    public void test(final String[] args) {
        // System.out.println(System.getProperty("java.class.path"));
        final String config = args == null || args.length == 0 ? "target/test-classes/log4j2-console-style-ansi.xml"
                : args[0];
        final LoggerContext ctx = Configurator.initialize(ConsoleAppenderAnsiMessagesMain.class.getName(), config);
        final Logger logger = LogManager.getLogger(ConsoleAppenderAnsiStyleLayoutMain.class);
        try {
            logger.fatal("Fatal message.");
            logger.error("Error message.");
            logger.warn("Warning message.");
            logger.info("Information message.");
            logger.debug("Debug message.");
            logger.trace("Trace message.");
            logger.error("Error message.", new IOException("test"));
        } finally {
            Configurator.shutdown(ctx);
        }
    }

Try With Resources try(final LoggerContext ctx=Configurator.initialize(ConsoleAppenderAnsiMessagesMain.class.getName(),config)) in method public test(args String[]) : void from class org.apache.logging.log4j.core.appender.ConsoleAppenderAnsiStyleLayoutMain


    public static void main(final String[] args) {
        try (final LoggerContext ctx = Configurator.initialize(ConsoleAppenderAnsiMessagesMain.class.getName(),
                "target/test-classes/log4j2-console-style-name-ansi.xml")) {
            LOG.fatal("Fatal message.");
            LOG.error("Error message.");
            LOG.warn("Warning message.");
            LOG.info("Information message.");
            LOG.debug("Debug message.");
            LOG.trace("Trace message.");
            LOG.error("Error message.", new IOException("test"));
        }
    }

    public static void main(final String[] args) {
        final LoggerContext ctx = Configurator.initialize(ConsoleAppenderAnsiMessagesMain.class.getName(),
                "target/test-classes/log4j2-console-style-name-ansi.xml");
        try {
            LOG.fatal("Fatal message.");
            LOG.error("Error message.");
            LOG.warn("Warning message.");
            LOG.info("Information message.");
            LOG.debug("Debug message.");
            LOG.trace("Trace message.");
            LOG.error("Error message.", new IOException("test"));
        } finally {
            Configurator.shutdown(ctx);
        }
    }

Try With Resources try(final LoggerContext ctx=Configurator.initialize(ConsoleAppenderAnsiMessagesMain.class.getName(),"target/test-classes/log4j2-console-style-name-ansi.xml")) in method public main(args String[]) : void from class org.apache.logging.log4j.core.appender.ConsoleAppenderAnsiStyleNameLayoutMain


    static void test(final String[] args, final String config) {
        // System.out.println(System.getProperty("java.class.path"));
        try (final LoggerContext ctx = Configurator
                .initialize(ConsoleAppenderDefaultSuppressedThrowable.class.getName(), config)) {
            final IOException ioEx = new IOException("test suppressed");
            ioEx.addSuppressed(new IOException("test suppressed 1", new IOException("test 1")));
            final IOException ioEx2 = new IOException("test 2");
            ioEx2.addSuppressed(new IOException("test 3"));
            ioEx.addSuppressed(new IOException("test suppressed 2", ioEx2));
            final IOException e = new IOException("test", ioEx);
            LOG.error("Error message {}, suppressed?", "Hi", e);
            System.out.println("printStackTrace");
            e.printStackTrace();
        }
    }

	static void test(final String[] args, final String config) {
		// System.out.println(System.getProperty("java.class.path"));
		final LoggerContext ctx = Configurator.initialize(ConsoleAppenderDefaultSuppressedThrowable.class.getName(),
				config);
		try {
			final IOException ioEx = new IOException("test suppressed");
			ioEx.addSuppressed(new IOException("test suppressed 1", new IOException("test 1")));
			final IOException ioEx2 = new IOException("test 2");
			ioEx2.addSuppressed(new IOException("test 3"));
			ioEx.addSuppressed(new IOException("test suppressed 2", ioEx2));
			final IOException e = new IOException("test", ioEx);
			LOG.error("Error message {}, suppressed?", "Hi", e);
			System.out.println("printStackTrace");
			e.printStackTrace();
		} finally {
			Configurator.shutdown(ctx);
		}
	}

Try With Resources try(final LoggerContext ctx=Configurator.initialize(ConsoleAppenderDefaultSuppressedThrowable.class.getName(),config)) in method package test(args String[], config String) : void from class org.apache.logging.log4j.core.appender.ConsoleAppenderDefaultSuppressedThrowable


    public static void main(final String[] args) {
        try (final LoggerContext ctx = Configurator.initialize(ConsoleAppenderAnsiMessagesMain.class.getName(),
                "target/test-classes/log4j2-console-highlight-default.xml")) {
            LOG.fatal("Fatal message.");
            LOG.error("Error message.");
            LOG.warn("Warning message.");
            LOG.info("Information message.");
            LOG.debug("Debug message.");
            LOG.trace("Trace message.");
            LOG.error("Error message.", new IOException("test"));
        }
    }

    public static void main(final String[] args) {
        final LoggerContext ctx = Configurator.initialize(ConsoleAppenderAnsiMessagesMain.class.getName(),
                "target/test-classes/log4j2-console-highlight-default.xml");
        try {
            LOG.fatal("Fatal message.");
            LOG.error("Error message.");
            LOG.warn("Warning message.");
            LOG.info("Information message.");
            LOG.debug("Debug message.");
            LOG.trace("Trace message.");
            LOG.error("Error message.", new IOException("test"));
        } finally {
            Configurator.shutdown(ctx);
        }
    }

Try With Resources try(final LoggerContext ctx=Configurator.initialize(ConsoleAppenderAnsiMessagesMain.class.getName(),"target/test-classes/log4j2-console-highlight-default.xml")) in method public main(args String[]) : void from class org.apache.logging.log4j.core.appender.ConsoleAppenderHighlightLayoutDefaultMain


    public static void main(final String[] args) {
        try (final LoggerContext ctx = Configurator.initialize(ConsoleAppenderAnsiMessagesMain.class.getName(),
                "target/test-classes/log4j2-console-highlight-logback.xml")) {
            LOG.fatal("Fatal message.");
            LOG.error("Error message.");
            LOG.warn("Warning message.");
            LOG.info("Information message.");
            LOG.debug("Debug message.");
            LOG.trace("Trace message.");
            LOG.error("Error message.", new IOException("test"));
        }
    }

    public static void main(final String[] args) {
        final LoggerContext ctx = Configurator.initialize(ConsoleAppenderAnsiMessagesMain.class.getName(),
                "target/test-classes/log4j2-console-highlight-logback.xml");
        try {
            LOG.fatal("Fatal message.");
            LOG.error("Error message.");
            LOG.warn("Warning message.");
            LOG.info("Information message.");
            LOG.debug("Debug message.");
            LOG.trace("Trace message.");
            LOG.error("Error message.", new IOException("test"));
        } finally {
            Configurator.shutdown(ctx);
        }
    }

Try With Resources try(final LoggerContext ctx=Configurator.initialize(ConsoleAppenderAnsiMessagesMain.class.getName(),"target/test-classes/log4j2-console-highlight-logback.xml")) in method public main(args String[]) : void from class org.apache.logging.log4j.core.appender.ConsoleAppenderHighlightLayoutLogbackMain


    public static void main(final String[] args) {
        try (final LoggerContext ctx = Configurator.initialize(ConsoleAppenderAnsiMessagesMain.class.getName(),
                "target/test-classes/log4j2-console-highlight.xml")) {
            LOG.fatal("Fatal message.");
            LOG.error("Error message.");
            LOG.warn("Warning message.");
            LOG.info("Information message.");
            LOG.debug("Debug message.");
            LOG.trace("Trace message.");
            LOG.error("Error message.", new IOException("test"));
        }
    }

    public static void main(final String[] args) {
        final LoggerContext ctx = Configurator.initialize(ConsoleAppenderAnsiMessagesMain.class.getName(),
                "target/test-classes/log4j2-console-highlight.xml");
        try {
            LOG.fatal("Fatal message.");
            LOG.error("Error message.");
            LOG.warn("Warning message.");
            LOG.info("Information message.");
            LOG.debug("Debug message.");
            LOG.trace("Trace message.");
            LOG.error("Error message.", new IOException("test"));
        } finally {
            Configurator.shutdown(ctx);
        }
    }

Try With Resources try(final LoggerContext ctx=Configurator.initialize(ConsoleAppenderAnsiMessagesMain.class.getName(),"target/test-classes/log4j2-console-highlight.xml")) in method public main(args String[]) : void from class org.apache.logging.log4j.core.appender.ConsoleAppenderHighlightLayoutMain


    public void test(final String[] args) {
        // System.out.println(System.getProperty("java.class.path"));
        final String config = args == null || args.length == 0 ? "target/test-classes/log4j2-console-msg-ansi.xml"
                : args[0];
        try (final LoggerContext ctx = Configurator.initialize(ConsoleAppenderAnsiMessagesMain.class.getName(),
                config)) {
            final Logger logger = LogManager.getLogger(ConsoleAppenderJAnsiMessageMain.class);
            logger.info(ansi().fg(RED).a("Hello").fg(CYAN).a(" World").reset());
            // JAnsi format:
            // logger.info("@|red Hello|@ @|cyan World|@");
            for (Entry<Object, Object> entry : System.getProperties().entrySet()) {
                logger.info("@|KeyStyle {}|@ = @|ValueStyle {}|@", entry.getKey(), entry.getValue());
            }
        }
    }

    public void test(final String[] args) {
        // System.out.println(System.getProperty("java.class.path"));
        final String config = args == null || args.length == 0 ? "target/test-classes/log4j2-console-msg-ansi.xml"
                : args[0];
        final LoggerContext ctx = Configurator.initialize(ConsoleAppenderAnsiMessagesMain.class.getName(), config);
        final Logger logger = LogManager.getLogger(ConsoleAppenderJAnsiMessageMain.class);
        try {
            logger.info(ansi().fg(RED).a("Hello").fg(CYAN).a(" World").reset());
            // JAnsi format:
            // logger.info("@|red Hello|@ @|cyan World|@");
            for (Entry<Object, Object> entry : System.getProperties().entrySet()) {
                logger.info("@|KeyStyle {}|@ = @|ValueStyle {}|@", entry.getKey(), entry.getValue());
            }
        } finally {
            Configurator.shutdown(ctx);
        }
    }

Try With Resources try(final LoggerContext ctx=Configurator.initialize(ConsoleAppenderAnsiMessagesMain.class.getName(),config)) in method public test(args String[]) : void from class org.apache.logging.log4j.core.appender.ConsoleAppenderJAnsiMessageMain


    static void test(final String[] args, final String config) {
        // System.out.println(System.getProperty("java.class.path"));
        try (final LoggerContext ctx = Configurator.initialize(ConsoleAppenderNoAnsiStyleLayoutMain.class.getName(),
                config)) {
            LOG.fatal("Fatal message.");
            LOG.error("Error message.");
            LOG.warn("Warning message.");
            LOG.info("Information message.");
            LOG.debug("Debug message.");
            LOG.trace("Trace message.");
            logThrowableFromMethod();
            // This will log the stack trace as well:
            final IOException ioException = new IOException("test");
            LOG.error("Error message {}", "Hi", ioException);
            final Throwable t = new IOException("test suppressed");
            t.addSuppressed(new IOException("test suppressed 2", ioException));
            LOG.error("Error message {}, suppressed?", "Hi", t);
            LOG.error("Error message {}, suppressed?", "Hi", new IOException("test", t));
        }
    }

	static void test(final String[] args, final String config) {
		// System.out.println(System.getProperty("java.class.path"));
		final LoggerContext ctx = Configurator.initialize(ConsoleAppenderNoAnsiStyleLayoutMain.class.getName(), config);
		try {
			LOG.fatal("Fatal message.");
			LOG.error("Error message.");
			LOG.warn("Warning message.");
			LOG.info("Information message.");
			LOG.debug("Debug message.");
			LOG.trace("Trace message.");
			logThrowableFromMethod();
			// This will log the stack trace as well:
			final IOException ioException = new IOException("test");
			LOG.error("Error message {}", "Hi", ioException);
			final Throwable t = new IOException("test suppressed");
			t.addSuppressed(new IOException("test suppressed 2", ioException));
			LOG.error("Error message {}, suppressed?", "Hi", t);
			LOG.error("Error message {}, suppressed?", "Hi", new IOException("test", t));
		} finally {
			Configurator.shutdown(ctx);
		}
	}

Try With Resources try(final LoggerContext ctx=Configurator.initialize(ConsoleAppenderNoAnsiStyleLayoutMain.class.getName(),config)) in method package test(args String[], config String) : void from class org.apache.logging.log4j.core.appender.ConsoleAppenderNoAnsiStyleLayoutMain


    public static void main(final String[] args) {
        try (final LoggerContext ctx = Configurator.initialize(Jira739Test.class.getName(),
                "target/test-classes/LOG4J2-739.xml")) {
            for (int i = 0; i < 10; i++) {
                LOG.trace("Entering Log4j Example " + i + " times");
                LOG.error("Ohh!Failed!");
                LOG.trace("Exiting Log4j Example." + i + " times");
            }
        }
    }

    public static void main(final String[] args) {
        final LoggerContext ctx = Configurator.initialize(Jira739Test.class.getName(),
                "target/test-classes/LOG4J2-739.xml");
        try {
            for (int i = 0; i < 10; i++) {
                LOG.trace("Entering Log4j Example " + i + " times");
                LOG.error("Ohh!Failed!");
                LOG.trace("Exiting Log4j Example." + i + " times");
            }
        } finally {
            Configurator.shutdown(ctx);
        }
    }

Try With Resources try(final LoggerContext ctx=Configurator.initialize(Jira739Test.class.getName(),"target/test-classes/LOG4J2-739.xml")) in method public main(args String[]) : void from class org.apache.logging.log4j.core.appender.Jira739Test


    public static void main(final String[] args) {
        // src/test/resources/log4j2-console-progress.xml
        // target/test-classes/log4j2-progress-console.xml
        try (final LoggerContext ctx = Configurator.initialize(ProgressConsoleTest.class.getName(),
                "target/test-classes/log4j2-progress-console.xml")) {
            for (double i = 0; i <= 1; i = i + 0.05) {
                updateProgress(i);
                try {
                    Thread.sleep(100);
                } catch (final InterruptedException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        }
    }

    public static void main(final String[] args) {
        final LoggerContext ctx = Configurator.initialize(ProgressConsoleTest.class.getName(),
                "target/test-classes/log4j2-progress-console.xml");
        // src/test/resources/log4j2-console-progress.xml
        // target/test-classes/log4j2-progress-console.xml
        try {
            for (double i = 0; i <= 1; i = i + 0.05) {
                updateProgress(i);
                try {
                    Thread.sleep(100);
                } catch (final InterruptedException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        } finally {
            Configurator.shutdown(ctx);
        }
    }

Try With Resources try(final LoggerContext ctx=Configurator.initialize(ProgressConsoleTest.class.getName(),"target/test-classes/log4j2-progress-console.xml")) in method public main(args String[]) : void from class org.apache.logging.log4j.core.appender.ProgressConsoleTest


    private void testInitializeFromFilePath(final String path) {
        try (final LoggerContext loggerContext = Configurator.initialize(getClass().getName(), null, path)) {
            Assert.assertNotNull(loggerContext.getConfiguration().getAppender("List"));
        }
    }

    private void testInitializeFromFilePath(final String path) {
        final LoggerContext loggerContext = Configurator.initialize(getClass().getName(), null, path);
        try {
            Assert.assertNotNull(loggerContext.getConfiguration().getAppender("List"));
        } finally {
            loggerContext.stop();
        }
    }

Try With Resources try(final LoggerContext loggerContext=Configurator.initialize(getClass().getName(),null,path)) in method private testInitializeFromFilePath(path String) : void from class org.apache.logging.log4j.core.config.ConfiguratorTest


    @Override
    public BlockingQueue<E> create(int capacity) {
        return new DisruptorBlockingQueue<>(capacity);
    }

    @Override
    public BlockingQueue<E> create(int capacity) {
        return new DisruptorBlockingQueue<E>(capacity);
    }

Replace Generic With Diamond DisruptorBlockingQueue<E> with DisruptorBlockingQueue<> in method public create(capacity int) : BlockingQueue<E> from class org.apache.logging.log4j.core.async.DisruptorBlockingQueueFactory


    /**
     * Send the contents of the cyclic buffer as an e-mail message.
     * @param layout The layout for formatting the events.
     * @param appendEvent The event that triggered the send.
     */
    public void sendEvents(final Layout<?> layout, final LogEvent appendEvent) {
        if (message == null) {
            connect(appendEvent);
        }
        try {
            final LogEvent[] priorEvents = buffer.removeAll();
            // LOG4J-310: log appendEvent even if priorEvents is empty

            final byte[] rawBytes = formatContentToBytes(priorEvents, appendEvent, layout);

            final String contentType = layout.getContentType();
            final String encoding = getEncoding(rawBytes, contentType);
            final byte[] encodedBytes = encodeContentToBytes(rawBytes, encoding);

            final InternetHeaders headers = getHeaders(contentType, encoding);
            final MimeMultipart mp = getMimeMultipart(encodedBytes, headers);

            sendMultipartMessage(message, mp);
        } catch (final MessagingException | IOException | RuntimeException e) {
            logError("caught exception while sending e-mail notification.", e);
            throw new LoggingException("Error occurred while sending email", e);
        }
    }

    /**
     * Send the contents of the cyclic buffer as an e-mail message.
     * @param layout The layout for formatting the events.
     * @param appendEvent The event that triggered the send.
     */
    public void sendEvents(final Layout<?> layout, final LogEvent appendEvent) {
        if (message == null) {
            connect(appendEvent);
        }
        try {
            final LogEvent[] priorEvents = buffer.removeAll();
            // LOG4J-310: log appendEvent even if priorEvents is empty

            final byte[] rawBytes = formatContentToBytes(priorEvents, appendEvent, layout);

            final String contentType = layout.getContentType();
            final String encoding = getEncoding(rawBytes, contentType);
            final byte[] encodedBytes = encodeContentToBytes(rawBytes, encoding);

            final InternetHeaders headers = getHeaders(contentType, encoding);
            final MimeMultipart mp = getMimeMultipart(encodedBytes, headers);

            sendMultipartMessage(message, mp);
        } catch (final MessagingException e) {
            logError("caught exception while sending e-mail notification.", e);
            throw new LoggingException("Error occurred while sending email", e);
        } catch (final IOException e) {
            logError("caught exception while sending e-mail notification.", e);
            throw new LoggingException("Error occurred while sending email", e);
        } catch (final RuntimeException e) {
            logError("caught exception while sending e-mail notification.", e);
            throw new LoggingException("Error occurred while sending email", e);
        }
    }

Merge Catch [catch(final MessagingException e), catch(final IOException e), catch(final RuntimeException e)] to catch(final MessagingException|IOException|RuntimeException e) in method public sendEvents(layout Layout<?>, appendEvent LogEvent) : void from class org.apache.logging.log4j.core.net.SmtpManager


    /**
     * Enables XInclude for the given DocumentBuilderFactory
     *
     * @param factory a DocumentBuilderFactory
     */
    private static void enableXInclude(final DocumentBuilderFactory factory) {
        try {
            // Alternative: We set if a system property on the command line is set, for example:
            // -DLog4j.XInclude=true
            factory.setXIncludeAware(true);
        } catch (final UnsupportedOperationException e) {
            LOGGER.warn("The DocumentBuilderFactory [{}] does not support XInclude: {}", factory, e);
        } catch (@SuppressWarnings("ErrorNotRethrown") final AbstractMethodError | NoSuchMethodError err) {
            LOGGER.warn("The DocumentBuilderFactory [{}] is out of date and does not support XInclude: {}", factory,
                    err);
        }
        try {
            // Alternative: We could specify all features and values with system properties like:
            // -DLog4j.DocumentBuilderFactory.Feature="http://apache.org/xml/features/xinclude/fixup-base-uris true"
            factory.setFeature(XINCLUDE_FIXUP_BASE_URIS, true);
        } catch (final ParserConfigurationException e) {
            LOGGER.warn("The DocumentBuilderFactory [{}] does not support the feature [{}]: {}", factory,
                    XINCLUDE_FIXUP_BASE_URIS, e);
        } catch (@SuppressWarnings("ErrorNotRethrown") final AbstractMethodError err) {
            LOGGER.warn("The DocumentBuilderFactory [{}] is out of date and does not support setFeature: {}", factory,
                    err);
        }
        try {
            factory.setFeature(XINCLUDE_FIXUP_LANGUAGE, true);
        } catch (final ParserConfigurationException e) {
            LOGGER.warn("The DocumentBuilderFactory [{}] does not support the feature [{}]: {}", factory,
                    XINCLUDE_FIXUP_LANGUAGE, e);
        } catch (@SuppressWarnings("ErrorNotRethrown") final AbstractMethodError err) {
            LOGGER.warn("The DocumentBuilderFactory [{}] is out of date and does not support setFeature: {}", factory,
                    err);
        }
    }

    /**
     * Enables XInclude for the given DocumentBuilderFactory
     *
     * @param factory a DocumentBuilderFactory
     */
    private static void enableXInclude(final DocumentBuilderFactory factory) {
        try {
            // Alternative: We set if a system property on the command line is set, for example:
            // -DLog4j.XInclude=true
            factory.setXIncludeAware(true);
        } catch (final UnsupportedOperationException e) {
            LOGGER.warn("The DocumentBuilderFactory [{}] does not support XInclude: {}", factory, e);
        } catch (@SuppressWarnings("ErrorNotRethrown") final AbstractMethodError err) {
            LOGGER.warn("The DocumentBuilderFactory [{}] is out of date and does not support XInclude: {}", factory,
                    err);
        } catch (final NoSuchMethodError err) {
            // LOG4J2-919
            LOGGER.warn("The DocumentBuilderFactory [{}] is out of date and does not support XInclude: {}", factory,
                    err);
        }
        try {
            // Alternative: We could specify all features and values with system properties like:
            // -DLog4j.DocumentBuilderFactory.Feature="http://apache.org/xml/features/xinclude/fixup-base-uris true"
            factory.setFeature(XINCLUDE_FIXUP_BASE_URIS, true);
        } catch (final ParserConfigurationException e) {
            LOGGER.warn("The DocumentBuilderFactory [{}] does not support the feature [{}]: {}", factory,
                    XINCLUDE_FIXUP_BASE_URIS, e);
        } catch (@SuppressWarnings("ErrorNotRethrown") final AbstractMethodError err) {
            LOGGER.warn("The DocumentBuilderFactory [{}] is out of date and does not support setFeature: {}", factory,
                    err);
        }
        try {
            factory.setFeature(XINCLUDE_FIXUP_LANGUAGE, true);
        } catch (final ParserConfigurationException e) {
            LOGGER.warn("The DocumentBuilderFactory [{}] does not support the feature [{}]: {}", factory,
                    XINCLUDE_FIXUP_LANGUAGE, e);
        } catch (@SuppressWarnings("ErrorNotRethrown") final AbstractMethodError err) {
            LOGGER.warn("The DocumentBuilderFactory [{}] is out of date and does not support setFeature: {}", factory,
                    err);
        }
    }

Merge Catch [catch(final AbstractMethodError err), catch(final NoSuchMethodError err)] to catch(final AbstractMethodError|NoSuchMethodError err) in method private enableXInclude(factory DocumentBuilderFactory) : void from class org.apache.logging.log4j.core.config.xml.XmlConfiguration


    /**
     * Advertise the provided entity.
     *
     * Properties map provided in advertise method must include a "name" entry but may also provide "protocol" (tcp/udp)
     * as well as a "port" entry
     *
     * The length of property names and values must be 255 bytes or less. Entries with names or values larger than 255
     * bytes will be removed prior to advertisement.
     *
     * @param properties the properties representing the entity to advertise
     * @return the object which can be used to unadvertise, or null if advertisement was unsuccessful
     */
    @Override
    public Object advertise(final Map<String, String> properties) {
        // default to tcp if "protocol" was not set
        final Map<String, String> truncatedProperties = new HashMap<>();
        for (final Map.Entry<String, String> entry : properties.entrySet()) {
            if (entry.getKey().length() <= MAX_LENGTH && entry.getValue().length() <= MAX_LENGTH) {
                truncatedProperties.put(entry.getKey(), entry.getValue());
            }
        }
        final String protocol = truncatedProperties.get("protocol");
        final String zone = "._log4j._" + (protocol != null ? protocol : "tcp") + ".local.";
        // default to 4555 if "port" was not set
        final String portString = truncatedProperties.get("port");
        final int port = Integers.parseInt(portString, DEFAULT_PORT);

        final String name = truncatedProperties.get("name");

        // if version 3 is available, use it to construct a serviceInfo instance, otherwise support the version1 API
        if (jmDNS != null) {
            boolean isVersion3 = false;
            try {
                // create method is in version 3, not version 1
                jmDNSClass.getMethod("create");
                isVersion3 = true;
            } catch (final NoSuchMethodException e) {
                // no-op
            }
            Object serviceInfo;
            if (isVersion3) {
                serviceInfo = buildServiceInfoVersion3(zone, port, name, truncatedProperties);
            } else {
                serviceInfo = buildServiceInfoVersion1(zone, port, name, truncatedProperties);
            }

            try {
                final Method method = jmDNSClass.getMethod("registerService", serviceInfoClass);
                method.invoke(jmDNS, serviceInfo);
            } catch (final IllegalAccessException | InvocationTargetException e) {
                LOGGER.warn("Unable to invoke registerService method", e);
            } catch (final NoSuchMethodException e) {
                LOGGER.warn("No registerService method", e);
            }
            return serviceInfo;
        }
        LOGGER.warn("JMDNS not available - will not advertise ZeroConf support");
        return null;
    }

    /**
     * Advertise the provided entity.
     *
     * Properties map provided in advertise method must include a "name" entry but may also provide "protocol" (tcp/udp)
     * as well as a "port" entry
     *
     * The length of property names and values must be 255 bytes or less. Entries with names or values larger than 255
     * bytes will be removed prior to advertisement.
     *
     * @param properties the properties representing the entity to advertise
     * @return the object which can be used to unadvertise, or null if advertisement was unsuccessful
     */
    @Override
    public Object advertise(final Map<String, String> properties) {
        // default to tcp if "protocol" was not set
        final Map<String, String> truncatedProperties = new HashMap<>();
        for (final Map.Entry<String, String> entry : properties.entrySet()) {
            if (entry.getKey().length() <= MAX_LENGTH && entry.getValue().length() <= MAX_LENGTH) {
                truncatedProperties.put(entry.getKey(), entry.getValue());
            }
        }
        final String protocol = truncatedProperties.get("protocol");
        final String zone = "._log4j._" + (protocol != null ? protocol : "tcp") + ".local.";
        // default to 4555 if "port" was not set
        final String portString = truncatedProperties.get("port");
        final int port = Integers.parseInt(portString, DEFAULT_PORT);

        final String name = truncatedProperties.get("name");

        // if version 3 is available, use it to construct a serviceInfo instance, otherwise support the version1 API
        if (jmDNS != null) {
            boolean isVersion3 = false;
            try {
                // create method is in version 3, not version 1
                jmDNSClass.getMethod("create");
                isVersion3 = true;
            } catch (final NoSuchMethodException e) {
                // no-op
            }
            Object serviceInfo;
            if (isVersion3) {
                serviceInfo = buildServiceInfoVersion3(zone, port, name, truncatedProperties);
            } else {
                serviceInfo = buildServiceInfoVersion1(zone, port, name, truncatedProperties);
            }

            try {
                final Method method = jmDNSClass.getMethod("registerService", serviceInfoClass);
                method.invoke(jmDNS, serviceInfo);
            } catch (final IllegalAccessException e) {
                LOGGER.warn("Unable to invoke registerService method", e);
            } catch (final NoSuchMethodException e) {
                LOGGER.warn("No registerService method", e);
            } catch (final InvocationTargetException e) {
                LOGGER.warn("Unable to invoke registerService method", e);
            }
            return serviceInfo;
        }
        LOGGER.warn("JMDNS not available - will not advertise ZeroConf support");
        return null;
    }

Merge Catch [catch(final IllegalAccessException e), catch(final InvocationTargetException e)] to catch(final IllegalAccessException|InvocationTargetException e) in method public advertise(properties Map<String,String>) : Object from class org.apache.logging.log4j.core.net.MulticastDnsAdvertiser


    /**
     * Unadvertise the previously advertised entity.
     *
     * @param serviceInfo
     */
    @Override
    public void unadvertise(final Object serviceInfo) {
        if (jmDNS != null) {
            try {
                final Method method = jmDNSClass.getMethod("unregisterService", serviceInfoClass);
                method.invoke(jmDNS, serviceInfo);
            } catch (final IllegalAccessException | InvocationTargetException e) {
                LOGGER.warn("Unable to invoke unregisterService method", e);
            } catch (final NoSuchMethodException e) {
                LOGGER.warn("No unregisterService method", e);
            }
        }
    }

    /**
     * Unadvertise the previously advertised entity.
     *
     * @param serviceInfo
     */
    @Override
    public void unadvertise(final Object serviceInfo) {
        if (jmDNS != null) {
            try {
                final Method method = jmDNSClass.getMethod("unregisterService", serviceInfoClass);
                method.invoke(jmDNS, serviceInfo);
            } catch (final IllegalAccessException e) {
                LOGGER.warn("Unable to invoke unregisterService method", e);
            } catch (final NoSuchMethodException e) {
                LOGGER.warn("No unregisterService method", e);
            } catch (final InvocationTargetException e) {
                LOGGER.warn("Unable to invoke unregisterService method", e);
            }
        }
    }

Merge Catch [catch(final IllegalAccessException e), catch(final InvocationTargetException e)] to catch(final IllegalAccessException|InvocationTargetException e) in method public unadvertise(serviceInfo Object) : void from class org.apache.logging.log4j.core.net.MulticastDnsAdvertiser


    private static Object createJmDnsVersion1() {
        try {
            return jmDNSClass.getConstructor().newInstance();
        } catch (final InstantiationException | IllegalAccessException | NoSuchMethodException | InvocationTargetException e) {
            LOGGER.warn("Unable to instantiate JMDNS", e);
        }
        return null;
    }

    private static Object createJmDnsVersion1() {
        try {
            return jmDNSClass.getConstructor().newInstance();
        } catch (final InstantiationException e) {
            LOGGER.warn("Unable to instantiate JMDNS", e);
        } catch (final IllegalAccessException e) {
            LOGGER.warn("Unable to instantiate JMDNS", e);
        } catch (final NoSuchMethodException e) {
            LOGGER.warn("Unable to instantiate JMDNS", e);
        } catch (final InvocationTargetException e) {
            LOGGER.warn("Unable to instantiate JMDNS", e);
        }
        return null;
    }

Merge Catch [catch(final InstantiationException e), catch(final IllegalAccessException e), catch(final NoSuchMethodException e), catch(final InvocationTargetException e)] to catch(final InstantiationException|IllegalAccessException|NoSuchMethodException|InvocationTargetException e) in method private createJmDnsVersion1() : Object from class org.apache.logging.log4j.core.net.MulticastDnsAdvertiser


    private static Object createJmDnsVersion3() {
        try {
            final Method jmDNSCreateMethod = jmDNSClass.getMethod("create");
            return jmDNSCreateMethod.invoke(null, (Object[]) null);
        } catch (final IllegalAccessException | InvocationTargetException e) {
            LOGGER.warn("Unable to invoke create method", e);
        } catch (final NoSuchMethodException e) {
            LOGGER.warn("Unable to get create method", e);
        }
        return null;
    }

    private static Object createJmDnsVersion3() {
        try {
            final Method jmDNSCreateMethod = jmDNSClass.getMethod("create");
            return jmDNSCreateMethod.invoke(null, (Object[]) null);
        } catch (final IllegalAccessException e) {
            LOGGER.warn("Unable to invoke create method", e);
        } catch (final NoSuchMethodException e) {
            LOGGER.warn("Unable to get create method", e);
        } catch (final InvocationTargetException e) {
            LOGGER.warn("Unable to invoke create method", e);
        }
        return null;
    }

Merge Catch [catch(final IllegalAccessException e), catch(final InvocationTargetException e)] to catch(final IllegalAccessException|InvocationTargetException e) in method private createJmDnsVersion3() : Object from class org.apache.logging.log4j.core.net.MulticastDnsAdvertiser


    private static Object buildServiceInfoVersion1(final String zone, final int port, final String name,
            final Map<String, String> properties) {
        // version 1 uses a hashtable
        @SuppressWarnings("UseOfObsoleteCollectionType")
        final Hashtable<String, String> hashtableProperties = new Hashtable<>(properties);
        try {
            return serviceInfoClass.getConstructor(String.class, String.class, int.class, int.class, int.class,
                    Hashtable.class).newInstance(zone, name, port, 0, 0, hashtableProperties);
        } catch (final IllegalAccessException | InstantiationException | InvocationTargetException e) {
            LOGGER.warn("Unable to construct ServiceInfo instance", e);
        } catch (final NoSuchMethodException e) {
            LOGGER.warn("Unable to get ServiceInfo constructor", e);
        }
        return null;
    }

    private static Object buildServiceInfoVersion1(final String zone, final int port, final String name,
            final Map<String, String> properties) {
        // version 1 uses a hashtable
        @SuppressWarnings("UseOfObsoleteCollectionType")
        final Hashtable<String, String> hashtableProperties = new Hashtable<>(properties);
        try {
            return serviceInfoClass.getConstructor(String.class, String.class, int.class, int.class, int.class,
                    Hashtable.class).newInstance(zone, name, port, 0, 0, hashtableProperties);
        } catch (final IllegalAccessException e) {
            LOGGER.warn("Unable to construct ServiceInfo instance", e);
        } catch (final NoSuchMethodException e) {
            LOGGER.warn("Unable to get ServiceInfo constructor", e);
        } catch (final InstantiationException e) {
            LOGGER.warn("Unable to construct ServiceInfo instance", e);
        } catch (final InvocationTargetException e) {
            LOGGER.warn("Unable to construct ServiceInfo instance", e);
        }
        return null;
    }

Merge Catch [catch(final IllegalAccessException e), catch(final InstantiationException e), catch(final InvocationTargetException e)] to catch(final IllegalAccessException|InstantiationException|InvocationTargetException e) in method private buildServiceInfoVersion1(zone String, port int, name String, properties Map<String,String>) : Object from class org.apache.logging.log4j.core.net.MulticastDnsAdvertiser


    private static Object buildServiceInfoVersion3(final String zone, final int port, final String name,
            final Map<String, String> properties) {
        try {
            return serviceInfoClass
                    // zone/type display name port weight priority properties
                    .getMethod("create", String.class, String.class, int.class, int.class, int.class, Map.class)
                    .invoke(null, zone, name, port, 0, 0, properties);
        } catch (final IllegalAccessException | InvocationTargetException e) {
            LOGGER.warn("Unable to invoke create method", e);
        } catch (final NoSuchMethodException e) {
            LOGGER.warn("Unable to find create method", e);
        }
        return null;
    }

    private static Object buildServiceInfoVersion3(final String zone, final int port, final String name,
            final Map<String, String> properties) {
        try {
            return serviceInfoClass
                    // zone/type display name port weight priority properties
                    .getMethod("create", String.class, String.class, int.class, int.class, int.class, Map.class)
                    .invoke(null, zone, name, port, 0, 0, properties);
        } catch (final IllegalAccessException e) {
            LOGGER.warn("Unable to invoke create method", e);
        } catch (final NoSuchMethodException e) {
            LOGGER.warn("Unable to find create method", e);
        } catch (final InvocationTargetException e) {
            LOGGER.warn("Unable to invoke create method", e);
        }
        return null;
    }

Merge Catch [catch(final IllegalAccessException e), catch(final InvocationTargetException e)] to catch(final IllegalAccessException|InvocationTargetException e) in method private buildServiceInfoVersion3(zone String, port int, name String, properties Map<String,String>) : Object from class org.apache.logging.log4j.core.net.MulticastDnsAdvertiser


    private static Object initializeJmDns() {
        try {
            jmDNSClass = Loader.loadClass("javax.jmdns.JmDNS");
            serviceInfoClass = Loader.loadClass("javax.jmdns.ServiceInfo");
            // if version 3 is available, use it to constuct a serviceInfo instance, otherwise support the version1 API
            boolean isVersion3 = false;
            try {
                // create method is in version 3, not version 1
                jmDNSClass.getMethod("create");
                isVersion3 = true;
            } catch (final NoSuchMethodException e) {
                // no-op
            }

            if (isVersion3) {
                return createJmDnsVersion3();
            }
            return createJmDnsVersion1();
        } catch (final ClassNotFoundException | ExceptionInInitializerError e) {
            LOGGER.warn("JmDNS or serviceInfo class not found", e);
        }
        return null;
    }

    private static Object initializeJmDns() {
        try {
            jmDNSClass = Loader.loadClass("javax.jmdns.JmDNS");
            serviceInfoClass = Loader.loadClass("javax.jmdns.ServiceInfo");
            // if version 3 is available, use it to constuct a serviceInfo instance, otherwise support the version1 API
            boolean isVersion3 = false;
            try {
                // create method is in version 3, not version 1
                jmDNSClass.getMethod("create");
                isVersion3 = true;
            } catch (final NoSuchMethodException e) {
                // no-op
            }

            if (isVersion3) {
                return createJmDnsVersion3();
            }
            return createJmDnsVersion1();
        } catch (final ClassNotFoundException e) {
            LOGGER.warn("JmDNS or serviceInfo class not found", e);
        } catch (final ExceptionInInitializerError e2) {
            LOGGER.warn("JmDNS or serviceInfo class not found", e2);
        }
        return null;
    }

Merge Catch [catch(final ClassNotFoundException e), catch(final ExceptionInInitializerError e2)] to catch(final ClassNotFoundException|ExceptionInInitializerError e) in method private initializeJmDns() : Object from class org.apache.logging.log4j.core.net.MulticastDnsAdvertiser