    /**
     * Constructs a new {@code T} object using the default constructor of its class. Any exceptions thrown by the
     * constructor will be rethrown by this method, possibly wrapped in an
     * {@link java.lang.reflect.UndeclaredThrowableException}.
     *
     * @param clazz the class to use for instantiation.
     * @param <T>   the type of the object to construct.
     * @return a new instance of T made from its default constructor.
     * @throws IllegalArgumentException if the given class is abstract, an interface, an array class, a primitive type,
     *                                  or void
     * @throws IllegalStateException    if access is denied to the constructor, or there are no default constructors
     */
    public static <T> T instantiate(final Class<T> clazz) {
        Objects.requireNonNull(clazz, "No class provided");
        final Constructor<T> constructor = getDefaultConstructor(clazz);
        try {
            return constructor.newInstance();
        } catch (final NoClassDefFoundError | InstantiationException e) {
            // LOG4J2-1051
            // On platforms like Google App Engine and Android, some JRE classes are not supported: JMX, JNDI, etc.
            throw new IllegalArgumentException(e);
        } catch (final IllegalAccessException e) {
            throw new IllegalStateException(e);
        } catch (final InvocationTargetException e) {
            Throwables.rethrow(e.getCause());
            throw new InternalError("Unreachable");
        }
    }

    /**
     * Constructs a new {@code T} object using the default constructor of its class. Any exceptions thrown by the
     * constructor will be rethrown by this method, possibly wrapped in an
     * {@link java.lang.reflect.UndeclaredThrowableException}.
     *
     * @param clazz the class to use for instantiation.
     * @param <T>   the type of the object to construct.
     * @return a new instance of T made from its default constructor.
     * @throws IllegalArgumentException if the given class is abstract, an interface, an array class, a primitive type,
     *                                  or void
     * @throws IllegalStateException    if access is denied to the constructor, or there are no default constructors
     */
    public static <T> T instantiate(final Class<T> clazz) {
        Objects.requireNonNull(clazz, "No class provided");
        final Constructor<T> constructor = getDefaultConstructor(clazz);
        try {
            return constructor.newInstance();
        } catch (final NoClassDefFoundError e) {
            // LOG4J2-1051
            // On platforms like Google App Engine and Android, some JRE classes are not supported: JMX, JNDI, etc.
            throw new IllegalArgumentException(e);
        } catch (final InstantiationException e) {
            throw new IllegalArgumentException(e);
        } catch (final IllegalAccessException e) {
            throw new IllegalStateException(e);
        } catch (final InvocationTargetException e) {
            Throwables.rethrow(e.getCause());
            throw new InternalError("Unreachable");
        }
    }

Merge Catch [catch(final NoClassDefFoundError e), catch(final InstantiationException e)] to catch(final NoClassDefFoundError|InstantiationException e) in method public instantiate(clazz Class<T>) : T from class org.apache.logging.log4j.core.util.ReflectionUtil


    private static MessageFactory createDefaultMessageFactory() {
        try {
            return DEFAULT_MESSAGE_FACTORY_CLASS.newInstance();
        } catch (final InstantiationException | IllegalAccessException e) {
            throw new IllegalStateException(e);
        }
    }

    private static MessageFactory createDefaultMessageFactory() {
        try {
            return DEFAULT_MESSAGE_FACTORY_CLASS.newInstance();
        } catch (final InstantiationException e) {
            throw new IllegalStateException(e);
        } catch (final IllegalAccessException e) {
            throw new IllegalStateException(e);
        }
    }

Merge Catch [catch(final InstantiationException e), catch(final IllegalAccessException e)] to catch(final InstantiationException|IllegalAccessException e) in method private createDefaultMessageFactory() : MessageFactory from class org.apache.logging.log4j.spi.AbstractLogger


    private static FlowMessageFactory createDefaultFlowMessageFactory() {
        try {
            return DEFAULT_FLOW_MESSAGE_FACTORY_CLASS.newInstance();
        } catch (final InstantiationException | IllegalAccessException e) {
            throw new IllegalStateException(e);
        }
    }

    private static FlowMessageFactory createDefaultFlowMessageFactory() {
        try {
            return DEFAULT_FLOW_MESSAGE_FACTORY_CLASS.newInstance();
        } catch (final InstantiationException e) {
            throw new IllegalStateException(e);
        } catch (final IllegalAccessException e) {
            throw new IllegalStateException(e);
        }
    }

Merge Catch [catch(final InstantiationException e), catch(final IllegalAccessException e)] to catch(final InstantiationException|IllegalAccessException e) in method private createDefaultFlowMessageFactory() : FlowMessageFactory from class org.apache.logging.log4j.spi.AbstractLogger


    /**
     * Constructs a PropertiesUtil for a given properties file name on the classpath. The properties specified in this
     * file are used by default. If a property is not defined in this file, then the equivalent system property is used.
     *
     * @param propertiesFileName the location of properties file to load
     */
    public PropertiesUtil(final String propertiesFileName) {
        final Properties properties = new Properties();
        for (final URL url : LoaderUtil.findResources(propertiesFileName)) {
            try (final InputStream in = url.openStream()) {
                properties.load(in);
            } catch (final IOException ioe) {
                LOGGER.error("Unable to read {}", url.toString(), ioe);
            }
        }
        this.props = properties;
    }

    /**
     * Constructs a PropertiesUtil for a given properties file name on the classpath. The properties specified in this
     * file are used by default. If a property is not defined in this file, then the equivalent system property is used.
     *
     * @param propertiesFileName the location of properties file to load
     */
    public PropertiesUtil(final String propertiesFileName) {
        @SuppressWarnings("IOResourceOpenedButNotSafelyClosed")
        final Properties properties = new Properties();
        for (final URL url : LoaderUtil.findResources(propertiesFileName)) {
            InputStream in = null;
            try {
                in = url.openStream();
                properties.load(in);
            } catch (final IOException ioe) {
                LOGGER.error("Unable to read {}", url.toString(), ioe);
            } finally {
                if (in != null) {
                    try {
                        in.close();
                    } catch (final IOException ioe) {
                        LOGGER.error("Unable to close {}", url.toString(), ioe);
                    }
                }
            }
        }
        this.props = properties;
    }

Try With Resources try(final InputStream in=url.openStream()) in method public PropertiesUtil(propertiesFileName String) from class org.apache.logging.log4j.util.PropertiesUtil


    /**
     * Stores the plugin cache to a given OutputStream.
     *
     * @param os destination to save cache to.
     * @throws IOException
     */
    // NOTE: if this file format is to be changed, the filename should change and this format should still be readable
    public void writeCache(final OutputStream os) throws IOException {
        try (final DataOutputStream out = new DataOutputStream(new BufferedOutputStream(os))) {
            // See PluginManager.readFromCacheFiles for the corresponding decoder. Format may not be changed
            // without breaking existing Log4j2Plugins.dat files.
            out.writeInt(categories.size());
            for (final Map.Entry<String, Map<String, PluginEntry>> category : categories.entrySet()) {
                out.writeUTF(category.getKey());
                final Map<String, PluginEntry> m = category.getValue();
                out.writeInt(m.size());
                for (final Map.Entry<String, PluginEntry> entry : m.entrySet()) {
                    final PluginEntry plugin = entry.getValue();
                    out.writeUTF(plugin.getKey());
                    out.writeUTF(plugin.getClassName());
                    out.writeUTF(plugin.getName());
                    out.writeBoolean(plugin.isPrintable());
                    out.writeBoolean(plugin.isDefer());
                }
            }
        }
    }

    /**
     * Stores the plugin cache to a given OutputStream.
     *
     * @param os destination to save cache to.
     * @throws IOException
     */
    // NOTE: if this file format is to be changed, the filename should change and this format should still be readable
    public void writeCache(final OutputStream os) throws IOException {
        final DataOutputStream out = new DataOutputStream(new BufferedOutputStream(os));
        try {
            // See PluginManager.readFromCacheFiles for the corresponding decoder. Format may not be changed
            // without breaking existing Log4j2Plugins.dat files.
            out.writeInt(categories.size());
            for (final Map.Entry<String, Map<String, PluginEntry>> category : categories.entrySet()) {
                out.writeUTF(category.getKey());
                final Map<String, PluginEntry> m = category.getValue();
                out.writeInt(m.size());
                for (final Map.Entry<String, PluginEntry> entry : m.entrySet()) {
                    final PluginEntry plugin = entry.getValue();
                    out.writeUTF(plugin.getKey());
                    out.writeUTF(plugin.getClassName());
                    out.writeUTF(plugin.getName());
                    out.writeBoolean(plugin.isPrintable());
                    out.writeBoolean(plugin.isDefer());
                }
            }
        } finally {
            Closer.closeSilently(out);
        }
    }

Try With Resources try(final DataOutputStream out=new DataOutputStream(new BufferedOutputStream(os))) in method public writeCache(os OutputStream) : void from class org.apache.logging.log4j.core.config.plugins.processor.PluginCache


    /**
     * Loads and merges all the Log4j plugin cache files specified. Usually, this is obtained via a ClassLoader.
     *
     * @param resources URLs to all the desired plugin cache files to load.
     * @throws IOException
     */
    public void loadCacheFiles(final Enumeration<URL> resources) throws IOException {
        categories.clear();
        while (resources.hasMoreElements()) {
            final URL url = resources.nextElement();
            try (final DataInputStream in = new DataInputStream(new BufferedInputStream(url.openStream()))) {
                final int count = in.readInt();
                for (int i = 0; i < count; i++) {
                    final String category = in.readUTF();
                    final Map<String, PluginEntry> m = getCategory(category);
                    final int entries = in.readInt();
                    for (int j = 0; j < entries; j++) {
                        final PluginEntry entry = new PluginEntry();
                        entry.setKey(in.readUTF());
                        entry.setClassName(in.readUTF());
                        entry.setName(in.readUTF());
                        entry.setPrintable(in.readBoolean());
                        entry.setDefer(in.readBoolean());
                        entry.setCategory(category);
                        if (!m.containsKey(entry.getKey())) {
                            m.put(entry.getKey(), entry);
                        }
                    }
                }
            }
        }
    }

    /**
     * Loads and merges all the Log4j plugin cache files specified. Usually, this is obtained via a ClassLoader.
     *
     * @param resources URLs to all the desired plugin cache files to load.
     * @throws IOException
     */
    public void loadCacheFiles(final Enumeration<URL> resources) throws IOException {
        categories.clear();
        while (resources.hasMoreElements()) {
            final URL url = resources.nextElement();
            final DataInputStream in = new DataInputStream(new BufferedInputStream(url.openStream()));
            try {
                final int count = in.readInt();
                for (int i = 0; i < count; i++) {
                    final String category = in.readUTF();
                    final Map<String, PluginEntry> m = getCategory(category);
                    final int entries = in.readInt();
                    for (int j = 0; j < entries; j++) {
                        final PluginEntry entry = new PluginEntry();
                        entry.setKey(in.readUTF());
                        entry.setClassName(in.readUTF());
                        entry.setName(in.readUTF());
                        entry.setPrintable(in.readBoolean());
                        entry.setDefer(in.readBoolean());
                        entry.setCategory(category);
                        if (!m.containsKey(entry.getKey())) {
                            m.put(entry.getKey(), entry);
                        }
                    }
                }
            } finally {
                Closer.closeSilently(in);
            }
        }
    }

Try With Resources try(final DataInputStream in=new DataInputStream(new BufferedInputStream(url.openStream()))) in method public loadCacheFiles(resources Enumeration<URL>) : void from class org.apache.logging.log4j.core.config.plugins.processor.PluginCache


    /**
     * Constructs a new helper objects and initializes itself.
     */
    public BundleTestInfo() {
        // get a raw POM view, not a fully realized POM object.
        final MavenXpp3Reader reader = new MavenXpp3Reader();
        FileReader fileReader;
        final String fileName = "pom.xml";
        try {
            fileReader = new FileReader(fileName);
        } catch (final FileNotFoundException e) {
            throw new IllegalStateException("Could not find " + fileName, e);
        }
        try {
            final Model model = reader.read(fileReader);
            this.project = new MavenProject(model);
        } catch (final IOException | XmlPullParserException e) {
            throw new IllegalStateException(e);
        } finally {
            try {
                fileReader.close();
            } catch (final IOException e) {
                throw new IllegalStateException(e);
            }
        }
    }

    /**
     * Constructs a new helper objects and initializes itself.
     */
    public BundleTestInfo() {
        // get a raw POM view, not a fully realized POM object.
        final MavenXpp3Reader reader = new MavenXpp3Reader();
        FileReader fileReader;
        final String fileName = "pom.xml";
        try {
            fileReader = new FileReader(fileName);
        } catch (final FileNotFoundException e) {
            throw new IllegalStateException("Could not find " + fileName, e);
        }
        try {
            final Model model = reader.read(fileReader);
            this.project = new MavenProject(model);
        } catch (final FileNotFoundException e) {
            throw new IllegalStateException(e);
        } catch (final IOException e) {
            throw new IllegalStateException(e);
        } catch (final XmlPullParserException e) {
            throw new IllegalStateException(e);
        } finally {
            try {
                fileReader.close();
            } catch (final IOException e) {
                throw new IllegalStateException(e);
            }
        }
    }

Merge Catch [catch(final FileNotFoundException e), catch(final IOException e), catch(final XmlPullParserException e)] to catch(final IOException|XmlPullParserException e) in method public BundleTestInfo() from class org.apache.logging.log4j.osgi.BundleTestInfo


    private List<Appender> getAsyncAppenders(final Appender[] all) {
        final List<Appender> result = new ArrayList<>();
        for (int i = all.length - 1; i >= 0; --i) {
            if (all[i] instanceof AsyncAppender) {
                result.add(all[i]);
            }
        }
        return result;
    }

    private List<Appender> getAsyncAppenders(final Appender[] all) {
        final List<Appender> result = new ArrayList<Appender>();
        for (int i = all.length - 1; i >= 0; --i) {
            if (all[i] instanceof AsyncAppender) {
                result.add(all[i]);
            }
        }
        return result;
    }

Replace Generic With Diamond ArrayList<Appender> with ArrayList<> in method private getAsyncAppenders(all Appender[]) : List<Appender> from class org.apache.logging.log4j.core.config.AbstractConfiguration


    @Test
    public void testSelectFilesToDelete() {
        Configuration config = new DefaultConfiguration();
        config.initialize(); // creates the ScriptManager

        Script script = new Script("test", "javascript", "pathList;"); // script that returns pathList
        ScriptCondition condition = new ScriptCondition(script, config);
        List<PathWithAttributes> pathList = new ArrayList<>();
        Path base = Paths.get("baseDirectory");
        List<PathWithAttributes> result = condition.selectFilesToDelete(base, pathList);
        assertSame(result, pathList);
    }

    @Test
    public void testSelectFilesToDelete() {
        Configuration config = new DefaultConfiguration();
        config.initialize(); // creates the ScriptManager

        Script script = new Script("test", "javascript", "pathList;"); // script that returns pathList
        ScriptCondition condition = new ScriptCondition(script, config);
        List<PathWithAttributes> pathList = new ArrayList<PathWithAttributes>();
        Path base = Paths.get("baseDirectory");
        List<PathWithAttributes> result = condition.selectFilesToDelete(base, pathList);
        assertSame(result, pathList);
    }

Replace Generic With Diamond ArrayList<PathWithAttributes> with ArrayList<> in method public testSelectFilesToDelete() : void from class org.apache.logging.log4j.core.appender.rolling.action.ScriptConditionTest


    @Test
    public void testSelectFilesToDelete2() {
        Configuration config = new DefaultConfiguration();
        config.initialize(); // creates the ScriptManager

        List<PathWithAttributes> pathList = new ArrayList<>();
        pathList.add(new PathWithAttributes(Paths.get("/path/1"), new DummyFileAttributes()));
        pathList.add(new PathWithAttributes(Paths.get("/path/2"), new DummyFileAttributes()));
        pathList.add(new PathWithAttributes(Paths.get("/path/3"), new DummyFileAttributes()));

        String scriptText = "pathList.remove(1);" //
                + "pathList;";
        Script script = new Script("test", "javascript", scriptText);
        ScriptCondition condition = new ScriptCondition(script, config);
        Path base = Paths.get("baseDirectory");
        List<PathWithAttributes> result = condition.selectFilesToDelete(base, pathList);
        assertSame(result, pathList);
        assertEquals(2, result.size());
        assertEquals(Paths.get("/path/1"), result.get(0).getPath());
        assertEquals(Paths.get("/path/3"), result.get(1).getPath());
    }

    @Test
    public void testSelectFilesToDelete2() {
        Configuration config = new DefaultConfiguration();
        config.initialize(); // creates the ScriptManager

        List<PathWithAttributes> pathList = new ArrayList<PathWithAttributes>();
        pathList.add(new PathWithAttributes(Paths.get("/path/1"), new DummyFileAttributes()));
        pathList.add(new PathWithAttributes(Paths.get("/path/2"), new DummyFileAttributes()));
        pathList.add(new PathWithAttributes(Paths.get("/path/3"), new DummyFileAttributes()));

        String scriptText = "pathList.remove(1);" //
                + "pathList;";
        Script script = new Script("test", "javascript", scriptText);
        ScriptCondition condition = new ScriptCondition(script, config);
        Path base = Paths.get("baseDirectory");
        List<PathWithAttributes> result = condition.selectFilesToDelete(base, pathList);
        assertSame(result, pathList);
        assertEquals(2, result.size());
        assertEquals(Paths.get("/path/1"), result.get(0).getPath());
        assertEquals(Paths.get("/path/3"), result.get(1).getPath());
    }

Replace Generic With Diamond ArrayList<PathWithAttributes> with ArrayList<> in method public testSelectFilesToDelete2() : void from class org.apache.logging.log4j.core.appender.rolling.action.ScriptConditionTest


    @Test
    public void testSelectFilesToDelete3() {
        Configuration config = new DefaultConfiguration();
        config.initialize(); // creates the ScriptManager

        List<PathWithAttributes> pathList = new ArrayList<>();
        pathList.add(new PathWithAttributes(Paths.get("/path/1/abc/a.txt"), new DummyFileAttributes()));
        pathList.add(new PathWithAttributes(Paths.get("/path/2/abc/bbb.txt"), new DummyFileAttributes()));
        pathList.add(new PathWithAttributes(Paths.get("/path/3/abc/c.txt"), new DummyFileAttributes()));

        String scriptText = "" //
                + "import java.nio.file.*;" //
                + "def pattern = ~/(\\d*)[\\/\\\\]abc[\\/\\\\].*\\.txt/;" //
                + "assert pattern.getClass() == java.util.regex.Pattern;" //
                + "def copy = pathList.collect{it};"
                + "pathList.each { pathWithAttribs -> \n" //
                + "  def relative = basePath.relativize pathWithAttribs.path;" //
                + "  println 'relative path: ' + relative;" //
                + "  def str = relative.toString();"
                + "  def m = pattern.matcher(str);" //
                + "  if (m.find()) {" //
                + "    def index = m.group(1) as int;" //
                + "    println 'extracted index: ' + index;" //
                + "    def isOdd = (index % 2) == 1;"
                + "    println 'is odd: ' + isOdd;" //
                + "    if (isOdd) { copy.remove pathWithAttribs}"
                + "  }" //
                + "}" //
                + "println copy;"
                + "copy;";
        Script script = new Script("test", "groovy", scriptText);
        ScriptCondition condition = new ScriptCondition(script, config);
        Path base = Paths.get("/path");
        List<PathWithAttributes> result = condition.selectFilesToDelete(base, pathList);
        assertEquals(1, result.size());
        assertEquals(Paths.get("/path/2/abc/bbb.txt"), result.get(0).getPath());
    }

    @Test
    public void testSelectFilesToDelete3() {
        Configuration config = new DefaultConfiguration();
        config.initialize(); // creates the ScriptManager

        List<PathWithAttributes> pathList = new ArrayList<PathWithAttributes>();
        pathList.add(new PathWithAttributes(Paths.get("/path/1/abc/a.txt"), new DummyFileAttributes()));
        pathList.add(new PathWithAttributes(Paths.get("/path/2/abc/bbb.txt"), new DummyFileAttributes()));
        pathList.add(new PathWithAttributes(Paths.get("/path/3/abc/c.txt"), new DummyFileAttributes()));

        String scriptText = "" //
                + "import java.nio.file.*;" //
                + "def pattern = ~/(\\d*)[\\/\\\\]abc[\\/\\\\].*\\.txt/;" //
                + "assert pattern.getClass() == java.util.regex.Pattern;" //
                + "def copy = pathList.collect{it};"
                + "pathList.each { pathWithAttribs -> \n" //
                + "  def relative = basePath.relativize pathWithAttribs.path;" //
                + "  println 'relative path: ' + relative;" //
                + "  def str = relative.toString();"
                + "  def m = pattern.matcher(str);" //
                + "  if (m.find()) {" //
                + "    def index = m.group(1) as int;" //
                + "    println 'extracted index: ' + index;" //
                + "    def isOdd = (index % 2) == 1;"
                + "    println 'is odd: ' + isOdd;" //
                + "    if (isOdd) { copy.remove pathWithAttribs}"
                + "  }" //
                + "}" //
                + "println copy;"
                + "copy;";
        Script script = new Script("test", "groovy", scriptText);
        ScriptCondition condition = new ScriptCondition(script, config);
        Path base = Paths.get("/path");
        List<PathWithAttributes> result = condition.selectFilesToDelete(base, pathList);
        assertEquals(1, result.size());
        assertEquals(Paths.get("/path/2/abc/bbb.txt"), result.get(0).getPath());
    }

Replace Generic With Diamond ArrayList<PathWithAttributes> with ArrayList<> in method public testSelectFilesToDelete3() : void from class org.apache.logging.log4j.core.appender.rolling.action.ScriptConditionTest


    @Test
    public void testBuilderCorrectlyCopiesAllEventAttributes() {
        final Map<String, String> contextMap = new HashMap<>();
        contextMap.put("A", "B");
        final ContextStack contextStack = ThreadContext.getImmutableStack();
        final Exception exception = new Exception("test");
        final Marker marker = MarkerManager.getMarker("EVENTTEST");
        final Message message = new SimpleMessage("foo");
        final StackTraceElement stackTraceElement = new StackTraceElement("A", "B", "file", 123);
        final String fqcn = "qualified";
        final String name = "Ceci n'est pas une pipe";
        final String threadName = "threadName";
        final Log4jLogEvent event = Log4jLogEvent.newBuilder() //
                .setContextMap(contextMap) //
                .setContextStack(contextStack) //
                .setEndOfBatch(true) //
                .setIncludeLocation(true) //
                .setLevel(Level.FATAL) //
                .setLoggerFqcn(fqcn) //
                .setLoggerName(name) //
                .setMarker(marker) //
                .setMessage(message) //
                .setNanoTime(1234567890L) //
                .setSource(stackTraceElement) //
                .setThreadName(threadName) //
                .setThrown(exception) //
                .setTimeMillis(987654321L)
                .build();

        assertSame(contextMap, event.getContextMap());
        assertSame(contextStack, event.getContextStack());
        assertEquals(true, event.isEndOfBatch());
        assertEquals(true, event.isIncludeLocation());
        assertSame(Level.FATAL, event.getLevel());
        assertSame(fqcn, event.getLoggerFqcn());
        assertSame(name, event.getLoggerName());
        assertSame(marker, event.getMarker());
        assertSame(message, event.getMessage());
        assertEquals(1234567890L, event.getNanoTime());
        assertSame(stackTraceElement, event.getSource());
        assertSame(threadName, event.getThreadName());
        assertSame(exception, event.getThrown());
        assertEquals(987654321L, event.getTimeMillis());

        LogEvent event2 = new Log4jLogEvent.Builder(event).build();
        assertEquals("copy constructor builder", event2, event);
        assertEquals("same hashCode", event2.hashCode(), event.hashCode());
    }

    @Test
    public void testBuilderCorrectlyCopiesAllEventAttributes() {
        final Map<String, String> contextMap = new HashMap<String, String>();
        contextMap.put("A", "B");
        final ContextStack contextStack = ThreadContext.getImmutableStack();
        final Exception exception = new Exception("test");
        final Marker marker = MarkerManager.getMarker("EVENTTEST");
        final Message message = new SimpleMessage("foo");
        final StackTraceElement stackTraceElement = new StackTraceElement("A", "B", "file", 123);
        final String fqcn = "qualified";
        final String name = "Ceci n'est pas une pipe";
        final String threadName = "threadName";
        final Log4jLogEvent event = Log4jLogEvent.newBuilder() //
                .setContextMap(contextMap) //
                .setContextStack(contextStack) //
                .setEndOfBatch(true) //
                .setIncludeLocation(true) //
                .setLevel(Level.FATAL) //
                .setLoggerFqcn(fqcn) //
                .setLoggerName(name) //
                .setMarker(marker) //
                .setMessage(message) //
                .setNanoTime(1234567890L) //
                .setSource(stackTraceElement) //
                .setThreadName(threadName) //
                .setThrown(exception) //
                .setTimeMillis(987654321L)
                .build();

        assertSame(contextMap, event.getContextMap());
        assertSame(contextStack, event.getContextStack());
        assertEquals(true, event.isEndOfBatch());
        assertEquals(true, event.isIncludeLocation());
        assertSame(Level.FATAL, event.getLevel());
        assertSame(fqcn, event.getLoggerFqcn());
        assertSame(name, event.getLoggerName());
        assertSame(marker, event.getMarker());
        assertSame(message, event.getMessage());
        assertEquals(1234567890L, event.getNanoTime());
        assertSame(stackTraceElement, event.getSource());
        assertSame(threadName, event.getThreadName());
        assertSame(exception, event.getThrown());
        assertEquals(987654321L, event.getTimeMillis());

        LogEvent event2 = new Log4jLogEvent.Builder(event).build();
        assertEquals("copy constructor builder", event2, event);
        assertEquals("same hashCode", event2.hashCode(), event.hashCode());
    }

Replace Generic With Diamond HashMap<String,String> with HashMap<> in method public testBuilderCorrectlyCopiesAllEventAttributes() : void from class org.apache.logging.log4j.core.impl.Log4jLogEventTest


    @Test
    public void testEquals() {
        final Map<String, String> contextMap = new HashMap<>();
        contextMap.put("A", "B");
        ThreadContext.push("first");
        final ContextStack contextStack = ThreadContext.getImmutableStack();
        final Exception exception = new Exception("test");
        final Marker marker = MarkerManager.getMarker("EVENTTEST");
        final Message message = new SimpleMessage("foo");
        final StackTraceElement stackTraceElement = new StackTraceElement("A", "B", "file", 123);
        final String fqcn = "qualified";
        final String name = "Ceci n'est pas une pipe";
        final String threadName = "threadName";
        final Log4jLogEvent event = Log4jLogEvent.newBuilder() //
                .setContextMap(contextMap) //
                .setContextStack(contextStack) //
                .setEndOfBatch(true) //
                .setIncludeLocation(true) //
                .setLevel(Level.FATAL) //
                .setLoggerFqcn(fqcn) //
                .setLoggerName(name) //
                .setMarker(marker) //
                .setMessage(message) //
                .setNanoTime(1234567890L) //
                .setSource(stackTraceElement) //
                .setThreadName(threadName) //
                .setThrown(exception) //
                .setTimeMillis(987654321L)
                .build();

        assertSame(contextMap, event.getContextMap());
        assertSame(contextStack, event.getContextStack());
        assertEquals(true, event.isEndOfBatch());
        assertEquals(true, event.isIncludeLocation());
        assertSame(Level.FATAL, event.getLevel());
        assertSame(fqcn, event.getLoggerFqcn());
        assertSame(name, event.getLoggerName());
        assertSame(marker, event.getMarker());
        assertSame(message, event.getMessage());
        assertEquals(1234567890L, event.getNanoTime());
        assertSame(stackTraceElement, event.getSource());
        assertSame(threadName, event.getThreadName());
        assertSame(exception, event.getThrown());
        assertEquals(987654321L, event.getTimeMillis());

        final LogEvent event2 = builder(event).build();
        assertEquals("copy constructor builder", event2, event);
        assertEquals("same hashCode", event2.hashCode(), event.hashCode());

        assertSame(contextMap, event2.getContextMap());
        assertSame(contextStack, event2.getContextStack());
        assertEquals(true, event2.isEndOfBatch());
        assertEquals(true, event2.isIncludeLocation());
        assertSame(Level.FATAL, event2.getLevel());
        assertSame(fqcn, event2.getLoggerFqcn());
        assertSame(name, event2.getLoggerName());
        assertSame(marker, event2.getMarker());
        assertSame(message, event2.getMessage());
        assertEquals(1234567890L, event2.getNanoTime());
        assertSame(stackTraceElement, event2.getSource());
        assertSame(threadName, event2.getThreadName());
        assertSame(exception, event2.getThrown());
        assertEquals(987654321L, event2.getTimeMillis());

        final Map<String, String> differentMap = Collections.emptyMap();
        different("different contextMap", builder(event).setContextMap(differentMap), event);
        different("null contextMap", builder(event).setContextMap(null), event);

        ThreadContext.push("abc");
        final ContextStack contextStack2 = ThreadContext.getImmutableStack();
        different("different contextStack", builder(event).setContextStack(contextStack2), event);
        different("null contextStack", builder(event).setContextStack(null), event);

        different("different EndOfBatch", builder(event).setEndOfBatch(false), event);
        different("different IncludeLocation", builder(event).setIncludeLocation(false), event);

        different("different level", builder(event).setLevel(Level.INFO), event);
        different("null level", builder(event).setLevel(null), event);

        different("different fqcn", builder(event).setLoggerFqcn("different"), event);
        different("null fqcn", builder(event).setLoggerFqcn(null), event);

        different("different name", builder(event).setLoggerName("different"), event);
        try { // TODO null logger name throws NPE in equals. Use Objects.requireNonNull in constructor?
            different("null name", builder(event).setLoggerName(null), event);
            fail("Expected NullPointerException");
        } catch (NullPointerException ok) {
        }

        different("different marker", builder(event).setMarker(MarkerManager.getMarker("different")), event);
        different("null marker", builder(event).setMarker(null), event);

        different("different message", builder(event).setMessage(new ObjectMessage("different")), event);
        try { // TODO null message throws NPE in equals(). Use Objects.requireNonNull in constructor?
            different("null message", builder(event).setMessage(null), event);
            fail("Expected NullPointerException");
        } catch (NullPointerException ok) {
        }

        different("different nanoTime", builder(event).setNanoTime(135), event);
        different("different milliTime", builder(event).setTimeMillis(137), event);

        final StackTraceElement stack2 = new StackTraceElement("XXX", "YYY", "file", 123);
        different("different source", builder(event).setSource(stack2), event);
        different("null source", builder(event).setSource(null), event);

        different("different threadname", builder(event).setThreadName("different"), event);
        different("null threadname", builder(event).setThreadName(null), event);

        different("different exception", builder(event).setThrown(new Error("Boo!")), event);
        different("null exception", builder(event).setThrown(null), event);
    }

    @Test
    public void testEquals() {
        final Map<String, String> contextMap = new HashMap<String, String>();
        contextMap.put("A", "B");
        ThreadContext.push("first");
        final ContextStack contextStack = ThreadContext.getImmutableStack();
        final Exception exception = new Exception("test");
        final Marker marker = MarkerManager.getMarker("EVENTTEST");
        final Message message = new SimpleMessage("foo");
        final StackTraceElement stackTraceElement = new StackTraceElement("A", "B", "file", 123);
        final String fqcn = "qualified";
        final String name = "Ceci n'est pas une pipe";
        final String threadName = "threadName";
        final Log4jLogEvent event = Log4jLogEvent.newBuilder() //
                .setContextMap(contextMap) //
                .setContextStack(contextStack) //
                .setEndOfBatch(true) //
                .setIncludeLocation(true) //
                .setLevel(Level.FATAL) //
                .setLoggerFqcn(fqcn) //
                .setLoggerName(name) //
                .setMarker(marker) //
                .setMessage(message) //
                .setNanoTime(1234567890L) //
                .setSource(stackTraceElement) //
                .setThreadName(threadName) //
                .setThrown(exception) //
                .setTimeMillis(987654321L)
                .build();

        assertSame(contextMap, event.getContextMap());
        assertSame(contextStack, event.getContextStack());
        assertEquals(true, event.isEndOfBatch());
        assertEquals(true, event.isIncludeLocation());
        assertSame(Level.FATAL, event.getLevel());
        assertSame(fqcn, event.getLoggerFqcn());
        assertSame(name, event.getLoggerName());
        assertSame(marker, event.getMarker());
        assertSame(message, event.getMessage());
        assertEquals(1234567890L, event.getNanoTime());
        assertSame(stackTraceElement, event.getSource());
        assertSame(threadName, event.getThreadName());
        assertSame(exception, event.getThrown());
        assertEquals(987654321L, event.getTimeMillis());

        final LogEvent event2 = builder(event).build();
        assertEquals("copy constructor builder", event2, event);
        assertEquals("same hashCode", event2.hashCode(), event.hashCode());

        assertSame(contextMap, event2.getContextMap());
        assertSame(contextStack, event2.getContextStack());
        assertEquals(true, event2.isEndOfBatch());
        assertEquals(true, event2.isIncludeLocation());
        assertSame(Level.FATAL, event2.getLevel());
        assertSame(fqcn, event2.getLoggerFqcn());
        assertSame(name, event2.getLoggerName());
        assertSame(marker, event2.getMarker());
        assertSame(message, event2.getMessage());
        assertEquals(1234567890L, event2.getNanoTime());
        assertSame(stackTraceElement, event2.getSource());
        assertSame(threadName, event2.getThreadName());
        assertSame(exception, event2.getThrown());
        assertEquals(987654321L, event2.getTimeMillis());

        final Map<String, String> differentMap = Collections.emptyMap();
        different("different contextMap", builder(event).setContextMap(differentMap), event);
        different("null contextMap", builder(event).setContextMap(null), event);

        ThreadContext.push("abc");
        final ContextStack contextStack2 = ThreadContext.getImmutableStack();
        different("different contextStack", builder(event).setContextStack(contextStack2), event);
        different("null contextStack", builder(event).setContextStack(null), event);

        different("different EndOfBatch", builder(event).setEndOfBatch(false), event);
        different("different IncludeLocation", builder(event).setIncludeLocation(false), event);

        different("different level", builder(event).setLevel(Level.INFO), event);
        different("null level", builder(event).setLevel(null), event);

        different("different fqcn", builder(event).setLoggerFqcn("different"), event);
        different("null fqcn", builder(event).setLoggerFqcn(null), event);

        different("different name", builder(event).setLoggerName("different"), event);
        try { // TODO null logger name throws NPE in equals. Use Objects.requireNonNull in constructor?
            different("null name", builder(event).setLoggerName(null), event);
            fail("Expected NullPointerException");
        } catch (NullPointerException ok) {
        }

        different("different marker", builder(event).setMarker(MarkerManager.getMarker("different")), event);
        different("null marker", builder(event).setMarker(null), event);

        different("different message", builder(event).setMessage(new ObjectMessage("different")), event);
        try { // TODO null message throws NPE in equals(). Use Objects.requireNonNull in constructor?
            different("null message", builder(event).setMessage(null), event);
            fail("Expected NullPointerException");
        } catch (NullPointerException ok) {
        }

        different("different nanoTime", builder(event).setNanoTime(135), event);
        different("different milliTime", builder(event).setTimeMillis(137), event);

        final StackTraceElement stack2 = new StackTraceElement("XXX", "YYY", "file", 123);
        different("different source", builder(event).setSource(stack2), event);
        different("null source", builder(event).setSource(null), event);

        different("different threadname", builder(event).setThreadName("different"), event);
        different("null threadname", builder(event).setThreadName(null), event);

        different("different exception", builder(event).setThrown(new Error("Boo!")), event);
        different("null exception", builder(event).setThrown(null), event);
    }

Replace Generic With Diamond HashMap<String,String> with HashMap<> in method public testEquals() : void from class org.apache.logging.log4j.core.impl.Log4jLogEventTest


        /**
         * Construct a Strategy that parses a Text field
         *
         * @param field The Calendar field
         * @param definingCalendar The Calendar to use
         * @param locale The Locale to use
         */
        CaseInsensitiveTextStrategy(final int field, final Calendar definingCalendar, final Locale locale) {
            this.field = field;
            this.locale = locale;
            final Map<String, Integer> keyValues = getDisplayNames(field, definingCalendar, locale);
            this.lKeyValues = new HashMap<>();

            for (final Map.Entry<String, Integer> entry : keyValues.entrySet()) {
                lKeyValues.put(entry.getKey().toLowerCase(locale), entry.getValue());
            }
        }

        /**
         * Construct a Strategy that parses a Text field
         *
         * @param field The Calendar field
         * @param definingCalendar The Calendar to use
         * @param locale The Locale to use
         */
        CaseInsensitiveTextStrategy(final int field, final Calendar definingCalendar, final Locale locale) {
            this.field = field;
            this.locale = locale;
            final Map<String, Integer> keyValues = getDisplayNames(field, definingCalendar, locale);
            this.lKeyValues = new HashMap<String, Integer>();

            for (final Map.Entry<String, Integer> entry : keyValues.entrySet()) {
                lKeyValues.put(entry.getKey().toLowerCase(locale), entry.getValue());
            }
        }

Replace Generic With Diamond HashMap<String,Integer> with HashMap<> in method package CaseInsensitiveTextStrategy(field int, definingCalendar Calendar, locale Locale) from class org.apache.logging.log4j.core.util.datetime.FastDateParser.CaseInsensitiveTextStrategy


    /**
     * Initialize derived fields from defining fields. This is called from constructor and from readObject
     * (de-serialization)
     *
     * @param definingCalendar the {@link java.util.Calendar} instance used to initialize this FastDateParser
     */
    private void init(final Calendar definingCalendar) {

        final StringBuilder regex = new StringBuilder();
        final List<Strategy> collector = new ArrayList<>();

        final Matcher patternMatcher = formatPattern.matcher(pattern);
        if (!patternMatcher.lookingAt()) {
            throw new IllegalArgumentException("Illegal pattern character '"
                    + pattern.charAt(patternMatcher.regionStart()) + "'");
        }

        currentFormatField = patternMatcher.group();
        Strategy currentStrategy = getStrategy(currentFormatField, definingCalendar);
        for (;;) {
            patternMatcher.region(patternMatcher.end(), patternMatcher.regionEnd());
            if (!patternMatcher.lookingAt()) {
                nextStrategy = null;
                break;
            }
            final String nextFormatField = patternMatcher.group();
            nextStrategy = getStrategy(nextFormatField, definingCalendar);
            if (currentStrategy.addRegex(this, regex)) {
                collector.add(currentStrategy);
            }
            currentFormatField = nextFormatField;
            currentStrategy = nextStrategy;
        }
        if (patternMatcher.regionStart() != patternMatcher.regionEnd()) {
            throw new IllegalArgumentException("Failed to parse \"" + pattern + "\" ; gave up at index "
                    + patternMatcher.regionStart());
        }
        if (currentStrategy.addRegex(this, regex)) {
            collector.add(currentStrategy);
        }
        currentFormatField = null;
        strategies = collector.toArray(new Strategy[collector.size()]);
        parsePattern = Pattern.compile(regex.toString());
    }

    /**
     * Initialize derived fields from defining fields. This is called from constructor and from readObject
     * (de-serialization)
     *
     * @param definingCalendar the {@link java.util.Calendar} instance used to initialize this FastDateParser
     */
    private void init(final Calendar definingCalendar) {

        final StringBuilder regex = new StringBuilder();
        final List<Strategy> collector = new ArrayList<Strategy>();

        final Matcher patternMatcher = formatPattern.matcher(pattern);
        if (!patternMatcher.lookingAt()) {
            throw new IllegalArgumentException("Illegal pattern character '"
                    + pattern.charAt(patternMatcher.regionStart()) + "'");
        }

        currentFormatField = patternMatcher.group();
        Strategy currentStrategy = getStrategy(currentFormatField, definingCalendar);
        for (;;) {
            patternMatcher.region(patternMatcher.end(), patternMatcher.regionEnd());
            if (!patternMatcher.lookingAt()) {
                nextStrategy = null;
                break;
            }
            final String nextFormatField = patternMatcher.group();
            nextStrategy = getStrategy(nextFormatField, definingCalendar);
            if (currentStrategy.addRegex(this, regex)) {
                collector.add(currentStrategy);
            }
            currentFormatField = nextFormatField;
            currentStrategy = nextStrategy;
        }
        if (patternMatcher.regionStart() != patternMatcher.regionEnd()) {
            throw new IllegalArgumentException("Failed to parse \"" + pattern + "\" ; gave up at index "
                    + patternMatcher.regionStart());
        }
        if (currentStrategy.addRegex(this, regex)) {
            collector.add(currentStrategy);
        }
        currentFormatField = null;
        strategies = collector.toArray(new Strategy[collector.size()]);
        parsePattern = Pattern.compile(regex.toString());
    }

Replace Generic With Diamond ArrayList<Strategy> with ArrayList<> in method private init(definingCalendar Calendar) : void from class org.apache.logging.log4j.core.util.datetime.FastDateParser


    /**
     * Get a cache of Strategies for a particular field
     *
     * @param field The Calendar field
     * @return a cache of Locale to Strategy
     */
    private static ConcurrentMap<Locale, Strategy> getCache(final int field) {
        synchronized (caches) {
            if (caches[field] == null) {
                caches[field] = new ConcurrentHashMap<>(3);
            }
            return caches[field];
        }
    }

    /**
     * Get a cache of Strategies for a particular field
     *
     * @param field The Calendar field
     * @return a cache of Locale to Strategy
     */
    private static ConcurrentMap<Locale, Strategy> getCache(final int field) {
        synchronized (caches) {
            if (caches[field] == null) {
                caches[field] = new ConcurrentHashMap<Locale, Strategy>(3);
            }
            return caches[field];
        }
    }

Replace Generic With Diamond ConcurrentHashMap<Locale,Strategy> with ConcurrentHashMap<> in method private getCache(field int) : ConcurrentMap<Locale,Strategy> from class org.apache.logging.log4j.core.util.datetime.FastDateParser


    /**
     * <p>
     * Returns a list of Rules given a pattern.
     * </p>
     *
     * @return a {@code List} of Rule objects
     * @throws IllegalArgumentException if pattern is invalid
     */
    protected List<Rule> parsePattern() {
        final DateFormatSymbols symbols = new DateFormatSymbols(mLocale);
        final List<Rule> rules = new ArrayList<>();

        final String[] ERAs = symbols.getEras();
        final String[] months = symbols.getMonths();
        final String[] shortMonths = symbols.getShortMonths();
        final String[] weekdays = symbols.getWeekdays();
        final String[] shortWeekdays = symbols.getShortWeekdays();
        final String[] AmPmStrings = symbols.getAmPmStrings();

        final int length = mPattern.length();
        final int[] indexRef = new int[1];

        for (int i = 0; i < length; i++) {
            indexRef[0] = i;
            final String token = parseToken(mPattern, indexRef);
            i = indexRef[0];

            final int tokenLen = token.length();
            if (tokenLen == 0) {
                break;
            }

            Rule rule;
            final char c = token.charAt(0);

            switch (c) {
            case 'G': // era designator (text)
                rule = new TextField(Calendar.ERA, ERAs);
                break;
            case 'y': // year (number)
                if (tokenLen == 2) {
                    rule = TwoDigitYearField.INSTANCE;
                } else {
                    rule = selectNumberRule(Calendar.YEAR, tokenLen < 4 ? 4 : tokenLen);
                }
                break;
            case 'M': // month in year (text and number)
                if (tokenLen >= 4) {
                    rule = new TextField(Calendar.MONTH, months);
                } else if (tokenLen == 3) {
                    rule = new TextField(Calendar.MONTH, shortMonths);
                } else if (tokenLen == 2) {
                    rule = TwoDigitMonthField.INSTANCE;
                } else {
                    rule = UnpaddedMonthField.INSTANCE;
                }
                break;
            case 'd': // day in month (number)
                rule = selectNumberRule(Calendar.DAY_OF_MONTH, tokenLen);
                break;
            case 'h': // hour in am/pm (number, 1..12)
                rule = new TwelveHourField(selectNumberRule(Calendar.HOUR, tokenLen));
                break;
            case 'H': // hour in day (number, 0..23)
                rule = selectNumberRule(Calendar.HOUR_OF_DAY, tokenLen);
                break;
            case 'm': // minute in hour (number)
                rule = selectNumberRule(Calendar.MINUTE, tokenLen);
                break;
            case 's': // second in minute (number)
                rule = selectNumberRule(Calendar.SECOND, tokenLen);
                break;
            case 'S': // millisecond (number)
                rule = selectNumberRule(Calendar.MILLISECOND, tokenLen);
                break;
            case 'E': // day in week (text)
                rule = new TextField(Calendar.DAY_OF_WEEK, tokenLen < 4 ? shortWeekdays : weekdays);
                break;
            case 'D': // day in year (number)
                rule = selectNumberRule(Calendar.DAY_OF_YEAR, tokenLen);
                break;
            case 'F': // day of week in month (number)
                rule = selectNumberRule(Calendar.DAY_OF_WEEK_IN_MONTH, tokenLen);
                break;
            case 'w': // week in year (number)
                rule = selectNumberRule(Calendar.WEEK_OF_YEAR, tokenLen);
                break;
            case 'W': // week in month (number)
                rule = selectNumberRule(Calendar.WEEK_OF_MONTH, tokenLen);
                break;
            case 'a': // am/pm marker (text)
                rule = new TextField(Calendar.AM_PM, AmPmStrings);
                break;
            case 'k': // hour in day (1..24)
                rule = new TwentyFourHourField(selectNumberRule(Calendar.HOUR_OF_DAY, tokenLen));
                break;
            case 'K': // hour in am/pm (0..11)
                rule = selectNumberRule(Calendar.HOUR, tokenLen);
                break;
            case 'u': // day of week (1..7)
                rule = selectNumberRule(Calendar.DAY_OF_WEEK, tokenLen);
                break;
            case 'X': // ISO 8601
                rule = Iso8601_Rule.getRule(tokenLen);
                break;
            case 'z': // time zone (text)
                if (tokenLen >= 4) {
                    rule = new TimeZoneNameRule(mTimeZone, mLocale, TimeZone.LONG);
                } else {
                    rule = new TimeZoneNameRule(mTimeZone, mLocale, TimeZone.SHORT);
                }
                break;
            case 'Z': // time zone (value)
                if (tokenLen == 1) {
                    rule = TimeZoneNumberRule.INSTANCE_NO_COLON;
                } else if (tokenLen == 2) {
                    rule = Iso8601_Rule.ISO8601_HOURS_COLON_MINUTES;
                } else {
                    rule = TimeZoneNumberRule.INSTANCE_COLON;
                }
                break;
            case '\'': // literal text
                final String sub = token.substring(1);
                if (sub.length() == 1) {
                    rule = new CharacterLiteral(sub.charAt(0));
                } else {
                    rule = new StringLiteral(sub);
                }
                break;
            default:
                throw new IllegalArgumentException("Illegal pattern component: " + token);
            }

            rules.add(rule);
        }

        return rules;
    }

    /**
     * <p>
     * Returns a list of Rules given a pattern.
     * </p>
     *
     * @return a {@code List} of Rule objects
     * @throws IllegalArgumentException if pattern is invalid
     */
    protected List<Rule> parsePattern() {
        final DateFormatSymbols symbols = new DateFormatSymbols(mLocale);
        final List<Rule> rules = new ArrayList<Rule>();

        final String[] ERAs = symbols.getEras();
        final String[] months = symbols.getMonths();
        final String[] shortMonths = symbols.getShortMonths();
        final String[] weekdays = symbols.getWeekdays();
        final String[] shortWeekdays = symbols.getShortWeekdays();
        final String[] AmPmStrings = symbols.getAmPmStrings();

        final int length = mPattern.length();
        final int[] indexRef = new int[1];

        for (int i = 0; i < length; i++) {
            indexRef[0] = i;
            final String token = parseToken(mPattern, indexRef);
            i = indexRef[0];

            final int tokenLen = token.length();
            if (tokenLen == 0) {
                break;
            }

            Rule rule;
            final char c = token.charAt(0);

            switch (c) {
            case 'G': // era designator (text)
                rule = new TextField(Calendar.ERA, ERAs);
                break;
            case 'y': // year (number)
                if (tokenLen == 2) {
                    rule = TwoDigitYearField.INSTANCE;
                } else {
                    rule = selectNumberRule(Calendar.YEAR, tokenLen < 4 ? 4 : tokenLen);
                }
                break;
            case 'M': // month in year (text and number)
                if (tokenLen >= 4) {
                    rule = new TextField(Calendar.MONTH, months);
                } else if (tokenLen == 3) {
                    rule = new TextField(Calendar.MONTH, shortMonths);
                } else if (tokenLen == 2) {
                    rule = TwoDigitMonthField.INSTANCE;
                } else {
                    rule = UnpaddedMonthField.INSTANCE;
                }
                break;
            case 'd': // day in month (number)
                rule = selectNumberRule(Calendar.DAY_OF_MONTH, tokenLen);
                break;
            case 'h': // hour in am/pm (number, 1..12)
                rule = new TwelveHourField(selectNumberRule(Calendar.HOUR, tokenLen));
                break;
            case 'H': // hour in day (number, 0..23)
                rule = selectNumberRule(Calendar.HOUR_OF_DAY, tokenLen);
                break;
            case 'm': // minute in hour (number)
                rule = selectNumberRule(Calendar.MINUTE, tokenLen);
                break;
            case 's': // second in minute (number)
                rule = selectNumberRule(Calendar.SECOND, tokenLen);
                break;
            case 'S': // millisecond (number)
                rule = selectNumberRule(Calendar.MILLISECOND, tokenLen);
                break;
            case 'E': // day in week (text)
                rule = new TextField(Calendar.DAY_OF_WEEK, tokenLen < 4 ? shortWeekdays : weekdays);
                break;
            case 'D': // day in year (number)
                rule = selectNumberRule(Calendar.DAY_OF_YEAR, tokenLen);
                break;
            case 'F': // day of week in month (number)
                rule = selectNumberRule(Calendar.DAY_OF_WEEK_IN_MONTH, tokenLen);
                break;
            case 'w': // week in year (number)
                rule = selectNumberRule(Calendar.WEEK_OF_YEAR, tokenLen);
                break;
            case 'W': // week in month (number)
                rule = selectNumberRule(Calendar.WEEK_OF_MONTH, tokenLen);
                break;
            case 'a': // am/pm marker (text)
                rule = new TextField(Calendar.AM_PM, AmPmStrings);
                break;
            case 'k': // hour in day (1..24)
                rule = new TwentyFourHourField(selectNumberRule(Calendar.HOUR_OF_DAY, tokenLen));
                break;
            case 'K': // hour in am/pm (0..11)
                rule = selectNumberRule(Calendar.HOUR, tokenLen);
                break;
            case 'u': // day of week (1..7)
                rule = selectNumberRule(Calendar.DAY_OF_WEEK, tokenLen);
                break;
            case 'X': // ISO 8601
                rule = Iso8601_Rule.getRule(tokenLen);
                break;
            case 'z': // time zone (text)
                if (tokenLen >= 4) {
                    rule = new TimeZoneNameRule(mTimeZone, mLocale, TimeZone.LONG);
                } else {
                    rule = new TimeZoneNameRule(mTimeZone, mLocale, TimeZone.SHORT);
                }
                break;
            case 'Z': // time zone (value)
                if (tokenLen == 1) {
                    rule = TimeZoneNumberRule.INSTANCE_NO_COLON;
                } else if (tokenLen == 2) {
                    rule = Iso8601_Rule.ISO8601_HOURS_COLON_MINUTES;
                } else {
                    rule = TimeZoneNumberRule.INSTANCE_COLON;
                }
                break;
            case '\'': // literal text
                final String sub = token.substring(1);
                if (sub.length() == 1) {
                    rule = new CharacterLiteral(sub.charAt(0));
                } else {
                    rule = new StringLiteral(sub);
                }
                break;
            default:
                throw new IllegalArgumentException("Illegal pattern component: " + token);
            }

            rules.add(rule);
        }

        return rules;
    }

Replace Generic With Diamond ArrayList<Rule> with ArrayList<> in method protected parsePattern() : List<Rule> from class org.apache.logging.log4j.core.util.datetime.FastDatePrinter


    public Provider(final Properties props, final URL url, final ClassLoader classLoader) {
        this.url = url;
        this.classLoader = new WeakReference<>(classLoader);
        final String weight = props.getProperty(FACTORY_PRIORITY);
        priority = weight == null ? DEFAULT_PRIORITY : Integer.valueOf(weight);
        className = props.getProperty(LOGGER_CONTEXT_FACTORY);
        threadContextMap = props.getProperty(THREAD_CONTEXT_MAP);
    }

    public Provider(final Properties props, final URL url, final ClassLoader classLoader) {
        this.url = url;
        this.classLoader = new WeakReference<ClassLoader>(classLoader);
        final String weight = props.getProperty(FACTORY_PRIORITY);
        priority = weight == null ? DEFAULT_PRIORITY : Integer.valueOf(weight);
        className = props.getProperty(LOGGER_CONTEXT_FACTORY);
        threadContextMap = props.getProperty(THREAD_CONTEXT_MAP);
    }

Replace Generic With Diamond WeakReference<ClassLoader> with WeakReference<> in method public Provider(props Properties, url URL, classLoader ClassLoader) from class org.apache.logging.log4j.spi.Provider


    /**
     * Scans for classes starting at the package provided and descending into subpackages. Each class is offered up to
     * the Test as it is discovered, and if the Test returns true the class is retained. Accumulated classes can be
     * fetched by calling {@link #getClasses()}.
     *
     * @param test
     *        an instance of {@link Test} that will be used to filter classes
     * @param packageName
     *        the name of the package from which to start scanning for classes, e.g. {@code net.sourceforge.stripes}
     */
    public void findInPackage(final Test test, String packageName) {
        packageName = packageName.replace('.', '/');
        final ClassLoader loader = getClassLoader();
        Enumeration<URL> urls;

        try {
            urls = loader.getResources(packageName);
        } catch (final IOException ioe) {
            LOGGER.warn("Could not read package: " + packageName, ioe);
            return;
        }

        while (urls.hasMoreElements()) {
            try {
                final URL url = urls.nextElement();
                final String urlPath = extractPath(url);

                LOGGER.info("Scanning for classes in [" + urlPath + "] matching criteria: " + test);
                // Check for a jar in a war in JBoss
                if (VFSZIP.equals(url.getProtocol())) {
                    final String path = urlPath.substring(0, urlPath.length() - packageName.length() - 2);
                    final URL newURL = new URL(url.getProtocol(), url.getHost(), path);
                    @SuppressWarnings("resource")
                    final JarInputStream stream = new JarInputStream(newURL.openStream());
                    try {
                        loadImplementationsInJar(test, packageName, path, stream);
                    } finally {
                        close(stream, newURL);
                    }
                } else if (BUNDLE_RESOURCE.equals(url.getProtocol())) {
                    loadImplementationsInBundle(test, packageName);
                } else {
                    final File file = new File(urlPath);
                    if (file.isDirectory()) {
                        loadImplementationsInDirectory(test, packageName, file);
                    } else {
                        loadImplementationsInJar(test, packageName, file);
                    }
                }
            } catch (final IOException | URISyntaxException ioe) {
                LOGGER.warn("could not read entries", ioe);
            }
        }
    }

    /**
     * Scans for classes starting at the package provided and descending into subpackages. Each class is offered up to
     * the Test as it is discovered, and if the Test returns true the class is retained. Accumulated classes can be
     * fetched by calling {@link #getClasses()}.
     *
     * @param test
     *        an instance of {@link Test} that will be used to filter classes
     * @param packageName
     *        the name of the package from which to start scanning for classes, e.g. {@code net.sourceforge.stripes}
     */
    public void findInPackage(final Test test, String packageName) {
        packageName = packageName.replace('.', '/');
        final ClassLoader loader = getClassLoader();
        Enumeration<URL> urls;

        try {
            urls = loader.getResources(packageName);
        } catch (final IOException ioe) {
            LOGGER.warn("Could not read package: " + packageName, ioe);
            return;
        }

        while (urls.hasMoreElements()) {
            try {
                final URL url = urls.nextElement();
                final String urlPath = extractPath(url);

                LOGGER.info("Scanning for classes in [" + urlPath + "] matching criteria: " + test);
                // Check for a jar in a war in JBoss
                if (VFSZIP.equals(url.getProtocol())) {
                    final String path = urlPath.substring(0, urlPath.length() - packageName.length() - 2);
                    final URL newURL = new URL(url.getProtocol(), url.getHost(), path);
                    @SuppressWarnings("resource")
                    final JarInputStream stream = new JarInputStream(newURL.openStream());
                    try {
                        loadImplementationsInJar(test, packageName, path, stream);
                    } finally {
                        close(stream, newURL);
                    }
                } else if (BUNDLE_RESOURCE.equals(url.getProtocol())) {
                    loadImplementationsInBundle(test, packageName);
                } else {
                    final File file = new File(urlPath);
                    if (file.isDirectory()) {
                        loadImplementationsInDirectory(test, packageName, file);
                    } else {
                        loadImplementationsInJar(test, packageName, file);
                    }
                }
            } catch (final IOException ioe) {
                LOGGER.warn("could not read entries", ioe);
            } catch (final URISyntaxException e) {
                LOGGER.warn("could not read entries", e);
            }
        }
    }

Merge Catch [catch(final IOException ioe), catch(final URISyntaxException e)] to catch(final IOException|URISyntaxException ioe) in method public findInPackage(test Test, packageName String) : void from class org.apache.logging.log4j.core.config.plugins.util.ResolverUtil


    @Test
    public void testFlushAtEndOfBatch() throws Exception {
        final Logger log = this.init.getLogger("com.foo.Bar");
        final String logMsg = "Message flushed with immediate flush=true";
        log.info(logMsg);
        log.error(logMsg, new IllegalArgumentException("badarg"));
        this.init.getContext().stop(); // stops async thread
        String line1;
        String line2;
        String line3;
        String line4;
        String line5;
        String line6;
        try (final BufferedReader reader = new BufferedReader(new FileReader(this.logFile))) {
            line1 = reader.readLine();
            line2 = reader.readLine();
            line3 = reader.readLine();
            line4 = reader.readLine();
            line5 = reader.readLine();
            line6 = reader.readLine();
        }
        assertNotNull("line1", line1);
        final String msg1 = "[";
        assertTrue("line1 incorrect: [" + line1 + "], does not contain: [" + msg1 + ']', line1.equals(msg1));

        assertNotNull("line2", line2);
        final String msg2 = "{";
        assertTrue("line2 incorrect: [" + line2 + "], does not contain: [" + msg2 + ']', line2.equals(msg2));

        assertNotNull("line3", line3);
        final String msg3 = "  \"timeMillis\" : ";
        assertTrue("line3 incorrect: [" + line3 + "], does not contain: [" + msg3 + ']', line3.contains(msg3));

        assertNotNull("line4", line4);
        final String msg4 = "  \"thread\" : \"main\",";
        assertTrue("line4 incorrect: [" + line4 + "], does not contain: [" + msg4 + ']', line4.contains(msg4));

        assertNotNull("line5", line5);
        final String msg5 = "  \"level\" : \"INFO\",";
        assertTrue("line5 incorrect: [" + line5 + "], does not contain: [" + msg5 + ']', line5.contains(msg5));

        assertNotNull("line6", line6);
        final String msg6 = "  \"loggerName\" : \"com.foo.Bar\",";
        assertTrue("line5 incorrect: [" + line6 + "], does not contain: [" + msg6 + ']', line6.contains(msg6));

        final String location = "testFlushAtEndOfBatch";
        assertTrue("no location", !line1.contains(location));
    }

    @Test
    public void testFlushAtEndOfBatch() throws Exception {
        final Logger log = this.init.getLogger("com.foo.Bar");
        final String logMsg = "Message flushed with immediate flush=true";
        log.info(logMsg);
        log.error(logMsg, new IllegalArgumentException("badarg"));
        this.init.getContext().stop(); // stops async thread
        String line1;
        String line2;
        String line3;
        String line4;
        String line5;
        String line6;
        final BufferedReader reader = new BufferedReader(new FileReader(this.logFile));
        try {
            line1 = reader.readLine();
            line2 = reader.readLine();
            line3 = reader.readLine();
            line4 = reader.readLine();
            line5 = reader.readLine();
            line6 = reader.readLine();
        } finally {
            reader.close();
        }
        assertNotNull("line1", line1);
        final String msg1 = "[";
        assertTrue("line1 incorrect: [" + line1 + "], does not contain: [" + msg1 + ']', line1.equals(msg1));

        assertNotNull("line2", line2);
        final String msg2 = "{";
        assertTrue("line2 incorrect: [" + line2 + "], does not contain: [" + msg2 + ']', line2.equals(msg2));

        assertNotNull("line3", line3);
        final String msg3 = "  \"timeMillis\" : ";
        assertTrue("line3 incorrect: [" + line3 + "], does not contain: [" + msg3 + ']', line3.contains(msg3));

        assertNotNull("line4", line4);
        final String msg4 = "  \"thread\" : \"main\",";
        assertTrue("line4 incorrect: [" + line4 + "], does not contain: [" + msg4 + ']', line4.contains(msg4));

        assertNotNull("line5", line5);
        final String msg5 = "  \"level\" : \"INFO\",";
        assertTrue("line5 incorrect: [" + line5 + "], does not contain: [" + msg5 + ']', line5.contains(msg5));

        assertNotNull("line6", line6);
        final String msg6 = "  \"loggerName\" : \"com.foo.Bar\",";
        assertTrue("line5 incorrect: [" + line6 + "], does not contain: [" + msg6 + ']', line6.contains(msg6));

        final String location = "testFlushAtEndOfBatch";
        assertTrue("no location", !line1.contains(location));
    }

Try With Resources try(final BufferedReader reader=new BufferedReader(new FileReader(this.logFile))) in method public testFlushAtEndOfBatch() : void from class org.apache.logging.log4j.core.appender.JsonCompleteFileAppenderTest


    @Test
    public void testMemMapLocation() throws Exception {
        final File f = new File(LOGFILE);
        if (f.exists()) {
            assertTrue(f.delete());
        }
        assertTrue(!f.exists());

        final int expectedFileLength = Integers.ceilingNextPowerOfTwo(32000);
        assertEquals(32768, expectedFileLength);

        final Logger log = LogManager.getLogger();
        try {
            log.warn("Test log1");
            assertTrue(f.exists());
            assertEquals("initial length", expectedFileLength, f.length());

            log.warn("Test log2");
            assertEquals("not grown", expectedFileLength, f.length());
        } finally {
            (LoggerContext.getContext(false)).stop();
        }
        final int LINESEP = System.getProperty("line.separator").length();
        assertEquals("Shrunk to actual used size", 474 + 2 * LINESEP, f.length());

        String line1, line2, line3;
        try (final BufferedReader reader = new BufferedReader(new FileReader(LOGFILE))) {
            line1 = reader.readLine();
            line2 = reader.readLine();
            line3 = reader.readLine();
        }
        assertNotNull(line1);
        assertThat(line1, containsString("Test log1"));
        final String location1 = "org.apache.logging.log4j.core.appender.MemoryMappedFileAppenderLocationTest.testMemMapLocation(MemoryMappedFileAppenderLocationTest.java:65)";
        assertThat(line1, containsString(location1));

        assertNotNull(line2);
        assertThat(line2, containsString("Test log2"));
        final String location2 = "org.apache.logging.log4j.core.appender.MemoryMappedFileAppenderLocationTest.testMemMapLocation(MemoryMappedFileAppenderLocationTest.java:69)";
        assertThat(line2, containsString(location2));

        assertNull("only two lines were logged", line3);
    }

    @Test
    public void testMemMapLocation() throws Exception {
        final File f = new File(LOGFILE);
        if (f.exists()) {
            assertTrue(f.delete());
        }
        assertTrue(!f.exists());

        final int expectedFileLength = Integers.ceilingNextPowerOfTwo(32000);
        assertEquals(32768, expectedFileLength);

        final Logger log = LogManager.getLogger();
        try {
            log.warn("Test log1");
            assertTrue(f.exists());
            assertEquals("initial length", expectedFileLength, f.length());

            log.warn("Test log2");
            assertEquals("not grown", expectedFileLength, f.length());
        } finally {
            (LoggerContext.getContext(false)).stop();
        }
        final int LINESEP = System.getProperty("line.separator").length();
        assertEquals("Shrunk to actual used size", 474 + 2 * LINESEP, f.length());

        String line1, line2, line3;
        final BufferedReader reader = new BufferedReader(new FileReader(LOGFILE));
        try {
            line1 = reader.readLine();
            line2 = reader.readLine();
            line3 = reader.readLine();
        } finally {
            reader.close();
        }
        assertNotNull(line1);
        assertThat(line1, containsString("Test log1"));
        final String location1 = "org.apache.logging.log4j.core.appender.MemoryMappedFileAppenderLocationTest.testMemMapLocation(MemoryMappedFileAppenderLocationTest.java:65)";
        assertThat(line1, containsString(location1));

        assertNotNull(line2);
        assertThat(line2, containsString("Test log2"));
        final String location2 = "org.apache.logging.log4j.core.appender.MemoryMappedFileAppenderLocationTest.testMemMapLocation(MemoryMappedFileAppenderLocationTest.java:69)";
        assertThat(line2, containsString(location2));

        assertNull("only two lines were logged", line3);
    }

Try With Resources try(final BufferedReader reader=new BufferedReader(new FileReader(LOGFILE))) in method public testMemMapLocation() : void from class org.apache.logging.log4j.core.appender.MemoryMappedFileAppenderLocationTest


    @Test
    public void testMemMapExtendsIfNeeded() throws Exception {
        final File f = new File(LOGFILE);
        if (f.exists()) {
            assertTrue(f.delete());
        }
        assertTrue(!f.exists());

        final Logger log = LogManager.getLogger();
        final char[] text = new char[200];
        Arrays.fill(text, 'A');
        try {
            log.warn("Test log1");
            assertTrue(f.exists());
            assertEquals("initial length", 256, f.length());

            log.warn(new String(text));
            assertEquals("grown", 256 * 2, f.length());

            log.warn(new String(text));
            assertEquals("grown again", 256 * 3, f.length());
        } finally {
            (LoggerContext.getContext(false)).stop();
        }
        final int LINESEP = System.getProperty("line.separator").length();
        assertEquals("Shrunk to actual used size", 658 + 3 * LINESEP, f.length());

        String line1, line2, line3, line4;
        try (final BufferedReader reader = new BufferedReader(new FileReader(LOGFILE))) {
            line1 = reader.readLine();
            line2 = reader.readLine();
            line3 = reader.readLine();
            line4 = reader.readLine();
        }
        assertNotNull(line1);
        assertThat(line1, containsString("Test log1"));

        assertNotNull(line2);
        assertThat(line2, containsString(new String(text)));

        assertNotNull(line3);
        assertThat(line3, containsString(new String(text)));

        assertNull("only three lines were logged", line4);
    }

    @Test
    public void testMemMapExtendsIfNeeded() throws Exception {
        final File f = new File(LOGFILE);
        if (f.exists()) {
            assertTrue(f.delete());
        }
        assertTrue(!f.exists());

        final Logger log = LogManager.getLogger();
        final char[] text = new char[200];
        Arrays.fill(text, 'A');
        try {
            log.warn("Test log1");
            assertTrue(f.exists());
            assertEquals("initial length", 256, f.length());

            log.warn(new String(text));
            assertEquals("grown", 256 * 2, f.length());

            log.warn(new String(text));
            assertEquals("grown again", 256 * 3, f.length());
        } finally {
            (LoggerContext.getContext(false)).stop();
        }
        final int LINESEP = System.getProperty("line.separator").length();
        assertEquals("Shrunk to actual used size", 658 + 3 * LINESEP, f.length());

        String line1, line2, line3, line4;
        final BufferedReader reader = new BufferedReader(new FileReader(LOGFILE));
        try {
            line1 = reader.readLine();
            line2 = reader.readLine();
            line3 = reader.readLine();
            line4 = reader.readLine();
        } finally {
            reader.close();
        }
        assertNotNull(line1);
        assertThat(line1, containsString("Test log1"));

        assertNotNull(line2);
        assertThat(line2, containsString(new String(text)));

        assertNotNull(line3);
        assertThat(line3, containsString(new String(text)));

        assertNull("only three lines were logged", line4);
    }

Try With Resources try(final BufferedReader reader=new BufferedReader(new FileReader(LOGFILE))) in method public testMemMapExtendsIfNeeded() : void from class org.apache.logging.log4j.core.appender.MemoryMappedFileAppenderRemapTest


    @Test
    public void testMemMapBasics() throws Exception {
        final File f = new File(LOGFILE);
        if (f.exists()) {
            assertTrue(f.delete());
        }
        assertTrue(!f.exists());

        final Logger log = LogManager.getLogger();
        try {
            log.warn("Test log1");
            assertTrue(f.exists());
            assertEquals("initial length", MemoryMappedFileManager.DEFAULT_REGION_LENGTH, f.length());

            log.warn("Test log2");
            assertEquals("not grown", MemoryMappedFileManager.DEFAULT_REGION_LENGTH, f.length());
        } finally {
            (LoggerContext.getContext(false)).stop();
        }
        final int LINESEP = System.getProperty("line.separator").length();
        assertEquals("Shrunk to actual used size", 186 + 2 * LINESEP, f.length());

        String line1, line2, line3;
        try (final BufferedReader reader = new BufferedReader(new FileReader(LOGFILE))) {
            line1 = reader.readLine();
            line2 = reader.readLine();
            line3 = reader.readLine();
        }
        assertNotNull(line1);
        assertThat(line1, containsString("Test log1"));

        assertNotNull(line2);
        assertThat(line2, containsString("Test log2"));

        assertNull("only two lines were logged", line3);
    }

    @Test
    public void testMemMapBasics() throws Exception {
        final File f = new File(LOGFILE);
        if (f.exists()) {
            assertTrue(f.delete());
        }
        assertTrue(!f.exists());

        final Logger log = LogManager.getLogger();
        try {
            log.warn("Test log1");
            assertTrue(f.exists());
            assertEquals("initial length", MemoryMappedFileManager.DEFAULT_REGION_LENGTH, f.length());

            log.warn("Test log2");
            assertEquals("not grown", MemoryMappedFileManager.DEFAULT_REGION_LENGTH, f.length());
        } finally {
            (LoggerContext.getContext(false)).stop();
        }
        final int LINESEP = System.getProperty("line.separator").length();
        assertEquals("Shrunk to actual used size", 186 + 2 * LINESEP, f.length());

        String line1, line2, line3;
        final BufferedReader reader = new BufferedReader(new FileReader(LOGFILE));
        try {
            line1 = reader.readLine();
            line2 = reader.readLine();
            line3 = reader.readLine();
        } finally {
            reader.close();
        }
        assertNotNull(line1);
        assertThat(line1, containsString("Test log1"));

        assertNotNull(line2);
        assertThat(line2, containsString("Test log2"));

        assertNull("only two lines were logged", line3);
    }

Try With Resources try(final BufferedReader reader=new BufferedReader(new FileReader(LOGFILE))) in method public testMemMapBasics() : void from class org.apache.logging.log4j.core.appender.MemoryMappedFileAppenderSimpleTest


    @Test
    public void testRandomAccessConfiguration() throws Exception {
        final Logger logger = this.init.getLogger("com.foo.Bar");
        final String message = "This is a test log message brought to you by Slurm.";
        logger.info(message);
        this.init.getContext().stop(); // stop async thread

        String line;
        try (final BufferedReader reader = new BufferedReader(new FileReader(this.logFile))) {
            line = reader.readLine();
        }
        assertNotNull(line);
        assertThat(line, containsString(message));
        final Matcher<String> containsLocationInformation = containsString("testRandomAccessConfiguration");
        final Matcher<String> containsLocationInformationIfEnabled = this.locationEnabled ?
                containsLocationInformation : not(containsLocationInformation);
        assertThat(line, containsLocationInformationIfEnabled);
    }

    @Test
    public void testRandomAccessConfiguration() throws Exception {
        final Logger logger = this.init.getLogger("com.foo.Bar");
        final String message = "This is a test log message brought to you by Slurm.";
        logger.info(message);
        this.init.getContext().stop(); // stop async thread

        String line;
        final BufferedReader reader = new BufferedReader(new FileReader(this.logFile));
        try {
            line = reader.readLine();
        } finally {
            reader.close();
        }
        assertNotNull(line);
        assertThat(line, containsString(message));
        final Matcher<String> containsLocationInformation = containsString("testRandomAccessConfiguration");
        final Matcher<String> containsLocationInformationIfEnabled = this.locationEnabled ?
                containsLocationInformation : not(containsLocationInformation);
        assertThat(line, containsLocationInformationIfEnabled);
    }

Try With Resources try(final BufferedReader reader=new BufferedReader(new FileReader(this.logFile))) in method public testRandomAccessConfiguration() : void from class org.apache.logging.log4j.core.appender.RandomAccessFileAppenderTests


    @Test
    public void testFlushAtEndOfBatch() throws Exception {
        final File file = new File("target", "XmlCompactFileAppenderTest.log");
        file.delete();
        final Logger log = LogManager.getLogger("com.foo.Bar");
        final String logMsg = "Message flushed with immediate flush=false";
        log.info(logMsg);
        CoreLoggerContexts.stopLoggerContext(false, file); // stop async thread

        String line1;
        try (final BufferedReader reader = new BufferedReader(new FileReader(file))) {
            line1 = reader.readLine();
        } finally {
            file.delete();
        }
        assertNotNull("line1", line1);
        final String msg1 = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>";
        assertTrue("line1 incorrect: [" + line1 + "], does not contain: [" + msg1 + ']', line1.contains(msg1));

        final String msg2 = "<Events xmlns=\"http://logging.apache.org/log4j/2.0/events\">";
        assertTrue("line1 incorrect: [" + line1 + "], does not contain: [" + msg2 + ']', line1.contains(msg2));

        final String msg3 = "<Event ";
        assertTrue("line1 incorrect: [" + line1 + "], does not contain: [" + msg3 + ']', line1.contains(msg3));

        final String msg4 = logMsg;
        assertTrue("line1 incorrect: [" + line1 + "], does not contain: [" + msg4 + ']', line1.contains(msg4));

        final String location = "testFlushAtEndOfBatch";
        assertTrue("no location", !line1.contains(location));

        assertTrue(line1.indexOf('\r') == -1);
        assertTrue(line1.indexOf('\n') == -1);
    }

    @Test
    public void testFlushAtEndOfBatch() throws Exception {
        final File file = new File("target", "XmlCompactFileAppenderTest.log");
        file.delete();
        final Logger log = LogManager.getLogger("com.foo.Bar");
        final String logMsg = "Message flushed with immediate flush=false";
        log.info(logMsg);
        CoreLoggerContexts.stopLoggerContext(false, file); // stop async thread

        final BufferedReader reader = new BufferedReader(new FileReader(file));
        String line1;
        try {
            line1 = reader.readLine();
        } finally {
            reader.close();
            file.delete();
        }
        assertNotNull("line1", line1);
        final String msg1 = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>";
        assertTrue("line1 incorrect: [" + line1 + "], does not contain: [" + msg1 + ']', line1.contains(msg1));

        final String msg2 = "<Events xmlns=\"http://logging.apache.org/log4j/2.0/events\">";
        assertTrue("line1 incorrect: [" + line1 + "], does not contain: [" + msg2 + ']', line1.contains(msg2));

        final String msg3 = "<Event ";
        assertTrue("line1 incorrect: [" + line1 + "], does not contain: [" + msg3 + ']', line1.contains(msg3));

        final String msg4 = logMsg;
        assertTrue("line1 incorrect: [" + line1 + "], does not contain: [" + msg4 + ']', line1.contains(msg4));

        final String location = "testFlushAtEndOfBatch";
        assertTrue("no location", !line1.contains(location));

        assertTrue(line1.indexOf('\r') == -1);
        assertTrue(line1.indexOf('\n') == -1);
    }

Try With Resources try(final BufferedReader reader=new BufferedReader(new FileReader(file))) in method public testFlushAtEndOfBatch() : void from class org.apache.logging.log4j.core.appender.XmlCompactFileAppenderTest


    @Test
    public void testFlushAtEndOfBatch() throws Exception {
        final File file = new File("target", "XmlCompleteFileAppenderTest.log");
        // System.out.println(f.getAbsolutePath());
        file.delete();
        final Logger log = LogManager.getLogger("com.foo.Bar");
        final String logMsg = "Message flushed with immediate flush=false";
        log.info(logMsg);
        CoreLoggerContexts.stopLoggerContext(false, file); // stop async thread

        String line1;
        String line2;
        String line3;
        String line4;
        try (final BufferedReader reader = new BufferedReader(new FileReader(file))) {
            line1 = reader.readLine();
            line2 = reader.readLine();
            line3 = reader.readLine();
            line4 = reader.readLine();
        } finally {
            file.delete();
        }
        assertNotNull("line1", line1);
        final String msg1 = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>";
        assertTrue("line1 incorrect: [" + line1 + "], does not contain: [" + msg1 + ']', line1.equals(msg1));

        assertNotNull("line2", line2);
        final String msg2 = "<Events xmlns=\"http://logging.apache.org/log4j/2.0/events\">";
        assertTrue("line2 incorrect: [" + line2 + "], does not contain: [" + msg2 + ']', line2.equals(msg2));

        assertNotNull("line3", line3);
        final String msg3 = "<Event ";
        assertTrue("line3 incorrect: [" + line3 + "], does not contain: [" + msg3 + ']', line3.contains(msg3));

        assertNotNull("line4", line4);
        final String msg4 = logMsg;
        assertTrue("line4 incorrect: [" + line4 + "], does not contain: [" + msg4 + ']', line4.contains(msg4));

        final String location = "testFlushAtEndOfBatch";
        assertTrue("no location", !line1.contains(location));
    }

    @Test
    public void testFlushAtEndOfBatch() throws Exception {
        final File file = new File("target", "XmlCompleteFileAppenderTest.log");
        // System.out.println(f.getAbsolutePath());
        file.delete();
        final Logger log = LogManager.getLogger("com.foo.Bar");
        final String logMsg = "Message flushed with immediate flush=false";
        log.info(logMsg);
        CoreLoggerContexts.stopLoggerContext(false, file); // stop async thread

        final BufferedReader reader = new BufferedReader(new FileReader(file));
        String line1;
        String line2;
        String line3;
        String line4;
        try {
            line1 = reader.readLine();
            line2 = reader.readLine();
            line3 = reader.readLine();
            line4 = reader.readLine();
        } finally {
            reader.close();
            file.delete();
        }
        assertNotNull("line1", line1);
        final String msg1 = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>";
        assertTrue("line1 incorrect: [" + line1 + "], does not contain: [" + msg1 + ']', line1.equals(msg1));

        assertNotNull("line2", line2);
        final String msg2 = "<Events xmlns=\"http://logging.apache.org/log4j/2.0/events\">";
        assertTrue("line2 incorrect: [" + line2 + "], does not contain: [" + msg2 + ']', line2.equals(msg2));

        assertNotNull("line3", line3);
        final String msg3 = "<Event ";
        assertTrue("line3 incorrect: [" + line3 + "], does not contain: [" + msg3 + ']', line3.contains(msg3));

        assertNotNull("line4", line4);
        final String msg4 = logMsg;
        assertTrue("line4 incorrect: [" + line4 + "], does not contain: [" + msg4 + ']', line4.contains(msg4));

        final String location = "testFlushAtEndOfBatch";
        assertTrue("no location", !line1.contains(location));
    }

Try With Resources try(final BufferedReader reader=new BufferedReader(new FileReader(file))) in method public testFlushAtEndOfBatch() : void from class org.apache.logging.log4j.core.appender.XmlCompleteFileAppenderTest


    @Test
    public void testFlushAtEndOfBatch() throws Exception {
        final File file = new File("target", "XmlFileAppenderTest.log");
        // System.out.println(f.getAbsolutePath());
        file.delete();
        final Logger log = LogManager.getLogger("com.foo.Bar");
        final String logMsg = "Message flushed with immediate flush=false";
        log.info(logMsg);
        CoreLoggerContexts.stopLoggerContext(false, file); // stop async thread

        String line1;
        String line2;
        String line3;
        try (final BufferedReader reader = new BufferedReader(new FileReader(file))) {
            line1 = reader.readLine();
            line2 = reader.readLine();
            line3 = reader.readLine();
        } finally {
            file.delete();
        }
        assertNotNull("line1", line1);

        assertNotNull("line1", line1);
        final String msg1 = "<Event ";
        assertTrue("line1 incorrect: [" + line1 + "], does not contain: [" + msg1 + ']', line1.contains(msg1));

        assertNotNull("line2", line2);
        final String msg2 = logMsg;
        assertTrue("line2 incorrect: [" + line2 + "], does not contain: [" + msg2 + ']', line2.contains(msg2));

        assertNotNull("line3", line3);
        final String msg3 = "</Event>";
        assertTrue("line3 incorrect: [" + line3 + "], does not contain: [" + msg3 + ']', line3.contains(msg3));

        final String location = "testFlushAtEndOfBatch";
        assertTrue("no location", !line1.contains(location));
    }

    @Test
    public void testFlushAtEndOfBatch() throws Exception {
        final File file = new File("target", "XmlFileAppenderTest.log");
        // System.out.println(f.getAbsolutePath());
        file.delete();
        final Logger log = LogManager.getLogger("com.foo.Bar");
        final String logMsg = "Message flushed with immediate flush=false";
        log.info(logMsg);
        CoreLoggerContexts.stopLoggerContext(false, file); // stop async thread

        final BufferedReader reader = new BufferedReader(new FileReader(file));
        String line1;
        String line2;
        String line3;
        try {
            line1 = reader.readLine();
            line2 = reader.readLine();
            line3 = reader.readLine();
        } finally {
            reader.close();
            file.delete();
        }
        assertNotNull("line1", line1);

        assertNotNull("line1", line1);
        final String msg1 = "<Event ";
        assertTrue("line1 incorrect: [" + line1 + "], does not contain: [" + msg1 + ']', line1.contains(msg1));

        assertNotNull("line2", line2);
        final String msg2 = logMsg;
        assertTrue("line2 incorrect: [" + line2 + "], does not contain: [" + msg2 + ']', line2.contains(msg2));

        assertNotNull("line3", line3);
        final String msg3 = "</Event>";
        assertTrue("line3 incorrect: [" + line3 + "], does not contain: [" + msg3 + ']', line3.contains(msg3));

        final String location = "testFlushAtEndOfBatch";
        assertTrue("no location", !line1.contains(location));
    }

Try With Resources try(final BufferedReader reader=new BufferedReader(new FileReader(file))) in method public testFlushAtEndOfBatch() : void from class org.apache.logging.log4j.core.appender.XmlFileAppenderTest


    @Test
    @Ignore
    public void testFlushAtEndOfBatch() throws Exception {
        final File file = new File("target", "XmlRandomAccessFileAppenderTest.log");
        // System.out.println(f.getAbsolutePath());
        file.delete();
        final Logger log = LogManager.getLogger("com.foo.Bar");
        final String logMsg = "Message flushed with immediate flush=false";
        log.info(logMsg);
        CoreLoggerContexts.stopLoggerContext(false, file); // stop async thread

        String line1;
        String line2;
        String line3;
        String line4;
        try (final BufferedReader reader = new BufferedReader(new FileReader(file))) {
            line1 = reader.readLine();
            line2 = reader.readLine();
            line3 = reader.readLine();
            line4 = reader.readLine();
        } finally {
            file.delete();
        }
        assertNotNull("line1", line1);
        final String msg1 = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>";
        assertTrue("line1 incorrect: [" + line1 + "], does not contain: [" + msg1 + ']', line1.equals(msg1));

        assertNotNull("line2", line2);
        final String msg2 = "<log4j:events xmlns:log4j=\"http://logging.apache.org/log4j/\">";
        assertTrue("line2 incorrect: [" + line2 + "], does not contain: [" + msg2 + ']', line2.equals(msg2));

        assertNotNull("line3", line3);
        final String msg3 = "<log4j:event ";
        assertTrue("line3 incorrect: [" + line3 + "], does not contain: [" + msg3 + ']', line3.contains(msg3));

        assertNotNull("line4", line4);
        final String msg4 = logMsg;
        assertTrue("line4 incorrect: [" + line4 + "], does not contain: [" + msg4 + ']', line4.contains(msg4));

        final String location = "testFlushAtEndOfBatch";
        assertTrue("no location", !line1.contains(location));
    }

    @Test
    @Ignore
    public void testFlushAtEndOfBatch() throws Exception {
        final File file = new File("target", "XmlRandomAccessFileAppenderTest.log");
        // System.out.println(f.getAbsolutePath());
        file.delete();
        final Logger log = LogManager.getLogger("com.foo.Bar");
        final String logMsg = "Message flushed with immediate flush=false";
        log.info(logMsg);
        CoreLoggerContexts.stopLoggerContext(false, file); // stop async thread

        final BufferedReader reader = new BufferedReader(new FileReader(file));
        String line1;
        String line2;
        String line3;
        String line4;
        try {
            line1 = reader.readLine();
            line2 = reader.readLine();
            line3 = reader.readLine();
            line4 = reader.readLine();
        } finally {
            reader.close();
            file.delete();
        }
        assertNotNull("line1", line1);
        final String msg1 = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>";
        assertTrue("line1 incorrect: [" + line1 + "], does not contain: [" + msg1 + ']', line1.equals(msg1));

        assertNotNull("line2", line2);
        final String msg2 = "<log4j:events xmlns:log4j=\"http://logging.apache.org/log4j/\">";
        assertTrue("line2 incorrect: [" + line2 + "], does not contain: [" + msg2 + ']', line2.equals(msg2));

        assertNotNull("line3", line3);
        final String msg3 = "<log4j:event ";
        assertTrue("line3 incorrect: [" + line3 + "], does not contain: [" + msg3 + ']', line3.contains(msg3));

        assertNotNull("line4", line4);
        final String msg4 = logMsg;
        assertTrue("line4 incorrect: [" + line4 + "], does not contain: [" + msg4 + ']', line4.contains(msg4));

        final String location = "testFlushAtEndOfBatch";
        assertTrue("no location", !line1.contains(location));
    }

Try With Resources try(final BufferedReader reader=new BufferedReader(new FileReader(file))) in method public testFlushAtEndOfBatch() : void from class org.apache.logging.log4j.core.appender.XmlRandomAccessFileAppenderTest