	private PluginModel parseConfigFile(URL location) {

		PluginModel pluginModel = null;
		File pluginFile = new File(location.getFile());

		try (JarFile jarFile = new JarFile(pluginFile); InputStream inputStream = jarFile.getInputStream(jarFile.getEntry(PLUGINXML))){
			Log.debug("Creating jarfile path: [" + pluginFile + "]");

			InputSource inputSource = new InputSource(inputStream);
			Log.debug("Creating plugin for: " + pluginFile);
			pluginModel = new PluginParser().parsePlugin(inputSource);
		} catch (SAXException | ParserConfigurationException se) {
			Log.error("Error while parsing plugin config file: ", se);
		} catch (IOException ioe) {
			Log.error("No such plugin config file: 	", ioe);
		}
		return pluginModel;
	}

	private PluginModel parseConfigFile(URL location) {

		PluginModel pluginModel = null;
		try {
			File pluginFile = new File(location.toURI());
			Log.debug("Creating jarfile path: [" + pluginFile + "]");
			JarFile jarFile = new JarFile(pluginFile);

			InputStream inputStream = jarFile.getInputStream(jarFile
					.getEntry(PLUGINXML));
			try {
				InputSource inputSource = new InputSource(inputStream);
				Log.debug("Creating plugin for: " + pluginFile);
				pluginModel = new PluginParser().parsePlugin(inputSource);
			} finally {
				Log.debug("Closing stream in any case.");
				inputStream.close();
				jarFile.close();
			}
		} catch (MalformedURLException mfue) {
			Log.error("Error creating config file location URL: ", mfue);
		} catch (SAXParseException se) {
			Log.error("Error while parsing plugin config file: ", se);
		} catch (IOException ioe) {
			Log.error("No such plugin config file: 	", ioe);
		} catch (Exception e) {
			Log.error("An unexpected error accured: ", e);
		}
		return pluginModel;
	}

Try With Resources try(JarFile jarFile=new JarFile(pluginFile); InputStream inputStream=jarFile.getInputStream(jarFile.getEntry(PLUGINXML))) in method private parseConfigFile(location URL) : PluginModel from class org.tzi.use.runtime.util.PluginRegistry


    private void failCompileSpecFailedFailFileDiffers(String specFileName, StringOutputStream errStr, File failFile) {
        System.err.println("Expected: #############");

        try (BufferedReader failReader = new BufferedReader(new FileReader(failFile))){
            while (true) {
                String line = failReader.readLine();
                if (line == null) {
                    break;
                }
                System.err.println(line);
            }
        } catch (IOException ex) {
            System.err.println(ex.getMessage());
        }
        System.err.println("Got: ##################");
        System.err.print(errStr.toString());
        System.err.println("#######################");
        fail(
             "compilation of "
             + specFileName
             + " had errors, "
             + "but the expected error output differs.");
    }

    private void failCompileSpecFailedFailFileDiffers(String specFileName, StringOutputStream errStr, File failFile) {
        System.err.println("Expected: #############");
        BufferedReader failReader = null;

        try {
            failReader = new BufferedReader(new FileReader(failFile));
            while (true) {
                String line = failReader.readLine();
                if (line == null) {
                    break;
                }
                System.err.println(line);
            }
        } catch (IOException ex) {
            System.err.println(ex.getMessage());
        } finally {
        	if (failReader != null) {
				try {
					failReader.close();
				} catch (IOException e) {}
        	}
        }
        System.err.println("Got: ##################");
        System.err.print(errStr.toString());
        System.err.println("#######################");
        fail(
             "compilation of "
             + specFileName
             + " had errors, "
             + "but the expected error output differs.");
    }

Try With Resources try(BufferedReader failReader=new BufferedReader(new FileReader(failFile))) in method private failCompileSpecFailedFailFileDiffers(specFileName String, errStr StringOutputStream, failFile File) : void from class org.tzi.use.parser.USECompilerTest


    private boolean isErrorMessageAsExpected(File failFile, StringOutputStream errStr) throws FileNotFoundException {
        // check whether error output equals expected output
        String[] expect = errStr.toString().split("\n|(\r\n)");
        //                        for (int i = 0; i < expect.length; i++) {
        //                            System.out.println("[" + expect[i] + "]");
        //                        }
        int j = 0;
        boolean ok = true;
        try (BufferedReader failReader = new BufferedReader(new FileReader(failFile))){
            while (ok) {
                String line = failReader.readLine();
                if (line == null) {
                    ok = j == expect.length;
                    break;
                }
                ok = line.equals(expect[j]);
                j++;
            }
        } catch (IOException ex) {
            ok = false;
        } catch (IndexOutOfBoundsException ex) {
        	ok = false;
        }
        return ok;
    }

    private boolean isErrorMessageAsExpected(File failFile, StringOutputStream errStr) throws FileNotFoundException {
        // check whether error output equals expected output
        BufferedReader failReader =
            new BufferedReader(new FileReader(failFile));
        String[] expect = errStr.toString().split("\n|(\r\n)");
        //                        for (int i = 0; i < expect.length; i++) {
        //                            System.out.println("[" + expect[i] + "]");
        //                        }
        int j = 0;
        boolean ok = true;
        try {
            while (ok) {
                String line = failReader.readLine();
                if (line == null) {
                    ok = j == expect.length;
                    break;
                }
                ok = line.equals(expect[j]);
                j++;
            }
        } catch (IOException ex) {
            ok = false;
        } catch (IndexOutOfBoundsException ex) {
        	ok = false;
        } finally {
			try {
				failReader.close();
			} catch (IOException e) {}
        }
        return ok;
    }

Try With Resources try(BufferedReader failReader=new BufferedReader(new FileReader(failFile))) in method private isErrorMessageAsExpected(failFile File, errStr StringOutputStream) : boolean from class org.tzi.use.parser.USECompilerTest


    private MModel compileSpecification(File specFile, PrintWriter newErr) throws FileNotFoundException {
        MModel result = null;

        try (FileInputStream specStream = new FileInputStream(specFile)){
			result = USECompiler.compileSpecification(specStream,
					specFile.getName(), newErr, new ModelFactory());
			specStream.close();
		} catch (IOException e) {
			// This can be ignored
			e.printStackTrace();
		}

        return result;
    }

    private MModel compileSpecification(File specFile, PrintWriter newErr) throws FileNotFoundException {
        FileInputStream specStream = new FileInputStream(specFile);
        MModel result;

        result = USECompiler.compileSpecification(specStream, specFile.getName(),
                                                newErr, new ModelFactory());
        try {
			specStream.close();
		} catch (IOException e) {
			// This can be ignored
			e.printStackTrace();
		}

        return result;
    }

Try With Resources try(FileInputStream specStream=new FileInputStream(specFile)) in method private compileSpecification(specFile File, newErr PrintWriter) : MModel from class org.tzi.use.parser.USECompilerTest


        @Override
		public void actionPerformed(ActionEvent e) {
            String path;
            // reuse chooser if possible
            if (fChooser == null) {
                fChooser = new JFileChooser(Options.getLastDirectory().toFile());
                ExtFileFilter filter = new ExtFileFilter("soil", "soil scripts");
                fChooser.setFileFilter(filter);
                fChooser.setDialogTitle("Save script");
            }
            int returnVal = fChooser.showSaveDialog(MainWindow.this);
            if (returnVal != JFileChooser.APPROVE_OPTION)
                return;

            path = fChooser.getCurrentDirectory().toString();
            String filename = fChooser.getSelectedFile().getName();
			if (!filename.endsWith(".soil"))
				filename += ".soil";
            File f = new File(path, filename);
            Log.verbose("File " + f);

            if (f.exists()) {
                int n = JOptionPane.showConfirmDialog(MainWindow.this,
                        "Overwrite existing file " + f + "?", "Please confirm",
                        JOptionPane.YES_NO_CANCEL_OPTION);
                if (n != JOptionPane.YES_OPTION)
                    return;
            }

            // write script file
            try (PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter(f)))){
                out.println("-- Script generated by USE "
                        + Options.RELEASE_VERSION);
                out.println();
                fSession.system().writeSoilStatements(out);
                fLogWriter.println("Wrote script " + f);
            } catch (IOException ex) {
                JOptionPane.showMessageDialog(MainWindow.this, ex.getMessage(),
                        "Error", JOptionPane.ERROR_MESSAGE);
            }
        }

        @Override
		public void actionPerformed(ActionEvent e) {
            String path;
            // reuse chooser if possible
            if (fChooser == null) {
                fChooser = new JFileChooser(Options.getLastDirectory().toFile());
                ExtFileFilter filter = new ExtFileFilter("soil", "soil scripts");
                fChooser.setFileFilter(filter);
                fChooser.setDialogTitle("Save script");
            }
            int returnVal = fChooser.showSaveDialog(MainWindow.this);
            if (returnVal != JFileChooser.APPROVE_OPTION)
                return;

            path = fChooser.getCurrentDirectory().toString();
            String filename = fChooser.getSelectedFile().getName();
			if (!filename.endsWith(".soil"))
				filename += ".soil";
            File f = new File(path, filename);
            Log.verbose("File " + f);

            if (f.exists()) {
                int n = JOptionPane.showConfirmDialog(MainWindow.this,
                        "Overwrite existing file " + f + "?", "Please confirm",
                        JOptionPane.YES_NO_CANCEL_OPTION);
                if (n != JOptionPane.YES_OPTION)
                    return;
            }

            // write script file
            PrintWriter out = null;
            try {
                out = new PrintWriter(new BufferedWriter(new FileWriter(f)));
                out.println("-- Script generated by USE "
                        + Options.RELEASE_VERSION);
                out.println();
                //fSession.system().writeUSEcmds(out);
                fSession.system().writeSoilStatements(out);
                fLogWriter.println("Wrote script " + f);
            } catch (IOException ex) {
                JOptionPane.showMessageDialog(MainWindow.this, ex.getMessage(),
                        "Error", JOptionPane.ERROR_MESSAGE);
            } finally {
                if (out != null)
                    out.close();
            }
        }

Try With Resources try(PrintWriter out=new PrintWriter(new BufferedWriter(new FileWriter(f)))) in method public actionPerformed(e ActionEvent) : void from class org.tzi.use.gui.main.MainWindow.ActionFileSaveScript


        @Override
		public void actionPerformed(ActionEvent e) {
            String path;
            // reuse chooser if possible
            if (fChooser == null) {
                fChooser = new JFileChooser(Options.getLastDirectory().toFile());
                ExtFileFilter filter = new ExtFileFilter("txt",
                        "Textfiles");
                fChooser.setFileFilter(filter);
                fChooser.setDialogTitle("Save protocol");
            }
            int returnVal = fChooser.showSaveDialog(MainWindow.this);
            if (returnVal != JFileChooser.APPROVE_OPTION)
                return;

            path = fChooser.getCurrentDirectory().toString();
            String filename = fChooser.getSelectedFile().getName();

			if (!(filename.lastIndexOf(".") > filename.lastIndexOf("\\")))
				filename += ".txt";

            File f = new File(path, filename);

            if (f.exists()) {
                int n = JOptionPane.showConfirmDialog(MainWindow.this,
                        "Overwrite existing file " + f + "?", "Please confirm",
                        JOptionPane.YES_NO_CANCEL_OPTION);
                if (n != JOptionPane.YES_OPTION)
                    return;
            }

            try (FileOutputStream fOut = new FileOutputStream(f)){
                USEWriter.getInstance().writeProtocolFile(fOut);
                fOut.flush();
                fOut.close();
            } catch (IOException e1) {
                e1.printStackTrace();
            }
        }

        @Override
		public void actionPerformed(ActionEvent e) {
            String path;
            // reuse chooser if possible
            if (fChooser == null) {
                fChooser = new JFileChooser(Options.getLastDirectory().toFile());
                ExtFileFilter filter = new ExtFileFilter("txt",
                        "Textfiles");
                fChooser.setFileFilter(filter);
                fChooser.setDialogTitle("Save protocol");
            }
            int returnVal = fChooser.showSaveDialog(MainWindow.this);
            if (returnVal != JFileChooser.APPROVE_OPTION)
                return;

            path = fChooser.getCurrentDirectory().toString();
            String filename = fChooser.getSelectedFile().getName();

			if (!(filename.lastIndexOf(".") > filename.lastIndexOf("\\")))
				filename += ".txt";

            File f = new File(path, filename);

            if (f.exists()) {
                int n = JOptionPane.showConfirmDialog(MainWindow.this,
                        "Overwrite existing file " + f + "?", "Please confirm",
                        JOptionPane.YES_NO_CANCEL_OPTION);
                if (n != JOptionPane.YES_OPTION)
                    return;
            }

            try {
                FileOutputStream fOut = new FileOutputStream(f);
                USEWriter.getInstance().writeProtocolFile(fOut);
                fOut.flush();
                fOut.close();
            } catch (IOException e1) {
                e1.printStackTrace();
            }
        }

Try With Resources try(FileOutputStream fOut=new FileOutputStream(f)) in method public actionPerformed(e ActionEvent) : void from class org.tzi.use.gui.main.MainWindow.ActionFileSaveProtocol


	public static void main(String args[]) {
		// set System.out to the OldUSEWriter to protocol the output.
		System.setOut(USEWriter.getInstance().getOut());
		// set System.err to the OldUSEWriter to protocol the output.
		System.setErr(USEWriter.getInstance().getErr());

		// read and set global options, setup application properties
		Options.processArgs(args);
		if (Options.doGUI) {
			initGUIdefaults();
		}

		Session session = new Session();
		IRuntime pluginRuntime = null;
		MModel model = null;
		MSystem system = null;

		if (!Options.disableExtensions) {
			ExtensionManager.EXTENSIONS_FOLDER = Options.homeDir + "/oclextensions";
			ExtensionManager.getInstance().loadExtensions();
		}

		// Plugin Framework
		if (Options.doPLUGIN) {
			// create URL from plugin directory
			Path pluginDirURL = Options.pluginDir;
			Log.verbose("Plugin path: [" + pluginDirURL + "]");
			Class<?> mainPluginRuntimeClass = null;
			try {
				mainPluginRuntimeClass = Class
						.forName("org.tzi.use.runtime.MainPluginRuntime");
			} catch (ClassNotFoundException e) {
				Log
						.error("Could not load PluginRuntime. Probably use-runtime-...jar is missing.\n"
								+ "Try starting use with -noplugins switch.\n"
								+ e.getMessage());
				System.exit(1);
			}
			try {
				Method run = mainPluginRuntimeClass.getMethod("run",
						new Class[] { Path.class });
				pluginRuntime = (IRuntime) run.invoke(null,
						new Object[] { pluginDirURL });
				Log.debug("Starting plugin runtime, got class ["
						+ pluginRuntime.getClass() + "]");
			} catch (Exception e) {
				e.printStackTrace();
				Log.error("FATAL ERROR.");
				System.exit(1);
			}
		}

		// compile spec if filename given as argument
		if (Options.specFilename != null) {
			try (FileInputStream specStream = new FileInputStream(Options.specFilename)){
				Log.verbose("compiling specification...");
				model = USECompiler.compileSpecification(specStream,
						Options.specFilename, new PrintWriter(System.err),
						new ModelFactory());
			} catch (FileNotFoundException e) {
				Log.error("File `" + Options.specFilename + "' not found.");
				System.exit(1);
			} catch (IOException e1) {
				// close failed
			}

			// compile errors?
			if (model == null) {
				System.exit(1);
			}

			Options.setLastDirectory(new java.io.File(Options.specFilename).getAbsoluteFile().toPath().getParent());
			if (!Options.testMode)
				Options.getRecentFiles().push(Options.specFilename);

			if (Options.compileOnly) {
				Log.verbose("no errors.");
				if (Options.compileAndPrint) {
					MMVisitor v = new MMPrintVisitor(new PrintWriter(
							System.out, true));
					model.processWithVisitor(v);
				}
				System.exit(0);
			}

			// print some info about model
			Log.verbose(model.getStats());

			// create system
			system = new MSystem(model);
		}
		session.setSystem(system);

		if (Options.doGUI) {
			Class<?> mainWindowClass = null;
			try {
				mainWindowClass = Class
						.forName("org.tzi.use.gui.main.MainWindow");
				Log.debug("Initializing [" + mainWindowClass.toString() + "]");
			} catch (ClassNotFoundException e) {
				Log
						.error("Could not load GUI. Probably use-gui-...jar is missing.\n"
								+ "Try starting use with -nogui switch.\n" + e);
				System.exit(1);
			}
			if (mainWindowClass == null) {
				Log.error("MainWindow could not be initialized! Exiting!");
				System.exit(1);
			}
			try {
				if (pluginRuntime == null) {
					Log.debug("Starting gui without plugin runtime!");
					Method create = mainWindowClass.getMethod("create",
							new Class[] { Session.class });
					Log.debug("Invoking method create with ["
							+ session.toString() + "]");
					create.invoke(null, new Object[] { session });
				} else {
					Log.debug("Starting gui with plugin runtime.");
					Method create = mainWindowClass.getMethod("create",
							new Class[] { Session.class, IRuntime.class });
					Log.debug("Invoking method create with ["
							+ session.toString() + "] ["
							+ pluginRuntime.toString() + "]");
					create
							.invoke(null,
									new Object[] { session, pluginRuntime });
				}
			} catch (Exception e) {
				Log.error("FATAL ERROR.", e);
				System.exit(1);
			}
		}

		// create thread for shell
		Shell.createInstance(session, pluginRuntime);
		Shell sh = Shell.getInstance();
		Thread t = new Thread(sh);
		t.start();

		// wait on exit from shell (this thread never returns)
		try {
			t.join();
		} catch (InterruptedException ex) {
			// ignored
		}
	}

	public static void main(String args[]) {
		// set System.out to the OldUSEWriter to protocol the output.
		System.setOut(USEWriter.getInstance().getOut());
		// set System.err to the OldUSEWriter to protocol the output.
		System.setErr(USEWriter.getInstance().getErr());

		// read and set global options, setup application properties
		Options.processArgs(args);
		if (Options.doGUI) {
			initGUIdefaults();
		}

		Session session = new Session();
		IRuntime pluginRuntime = null;
		MModel model = null;
		MSystem system = null;

		if (!Options.disableExtensions) {
			ExtensionManager.EXTENSIONS_FOLDER = Options.homeDir + "/oclextensions";
			ExtensionManager.getInstance().loadExtensions();
		}

		// Plugin Framework
		if (Options.doPLUGIN) {
			// create URL from plugin directory
			Path pluginDirURL = Options.pluginDir;
			Log.verbose("Plugin path: [" + pluginDirURL + "]");
			Class<?> mainPluginRuntimeClass = null;
			try {
				mainPluginRuntimeClass = Class
						.forName("org.tzi.use.runtime.MainPluginRuntime");
			} catch (ClassNotFoundException e) {
				Log
						.error("Could not load PluginRuntime. Probably use-runtime-...jar is missing.\n"
								+ "Try starting use with -noplugins switch.\n"
								+ e.getMessage());
				System.exit(1);
			}
			try {
				Method run = mainPluginRuntimeClass.getMethod("run",
						new Class[] { Path.class });
				pluginRuntime = (IRuntime) run.invoke(null,
						new Object[] { pluginDirURL });
				Log.debug("Starting plugin runtime, got class ["
						+ pluginRuntime.getClass() + "]");
			} catch (Exception e) {
				e.printStackTrace();
				Log.error("FATAL ERROR.");
				System.exit(1);
			}
		}

		// compile spec if filename given as argument
		if (Options.specFilename != null) {
			FileInputStream specStream = null;
			try {
				Log.verbose("compiling specification...");
				specStream = new FileInputStream(Options.specFilename);
				model = USECompiler.compileSpecification(specStream,
						Options.specFilename, new PrintWriter(System.err),
						new ModelFactory());
			} catch (FileNotFoundException e) {
				Log.error("File `" + Options.specFilename + "' not found.");
				System.exit(1);
			} finally {
				if (specStream != null)
					try {
						specStream.close();
					} catch (IOException ex) {
						// ignored
					}
			}

			// compile errors?
			if (model == null) {
				System.exit(1);
			}

			Options.setLastDirectory(new java.io.File(Options.specFilename).toPath().getParent());
			if (!Options.testMode)
				Options.getRecentFiles().push(Options.specFilename);

			if (Options.compileOnly) {
				Log.verbose("no errors.");
				if (Options.compileAndPrint) {
					MMVisitor v = new MMPrintVisitor(new PrintWriter(
							System.out, true));
					model.processWithVisitor(v);
				}
				System.exit(0);
			}

			// print some info about model
			Log.verbose(model.getStats());

			// create system
			system = new MSystem(model);
		}
		session.setSystem(system);

		if (Options.doGUI) {
			Class<?> mainWindowClass = null;
			try {
				mainWindowClass = Class
						.forName("org.tzi.use.gui.main.MainWindow");
				Log.debug("Initializing [" + mainWindowClass.toString() + "]");
			} catch (ClassNotFoundException e) {
				Log
						.error("Could not load GUI. Probably use-gui-...jar is missing.\n"
								+ "Try starting use with -nogui switch.\n" + e);
				System.exit(1);
			}
			if (mainWindowClass == null) {
				Log.error("MainWindow could not be initialized! Exiting!");
				System.exit(1);
			}
			try {
				if (pluginRuntime == null) {
					Log.debug("Starting gui without plugin runtime!");
					Method create = mainWindowClass.getMethod("create",
							new Class[] { Session.class });
					Log.debug("Invoking method create with ["
							+ session.toString() + "]");
					create.invoke(null, new Object[] { session });
				} else {
					Log.debug("Starting gui with plugin runtime.");
					Method create = mainWindowClass.getMethod("create",
							new Class[] { Session.class, IRuntime.class });
					Log.debug("Invoking method create with ["
							+ session.toString() + "] ["
							+ pluginRuntime.toString() + "]");
					create
							.invoke(null,
									new Object[] { session, pluginRuntime });
				}
			} catch (Exception e) {
				Log.error("FATAL ERROR.", e);
				System.exit(1);
			}
		}

		// create thread for shell
		Shell.createInstance(session, pluginRuntime);
		Shell sh = Shell.getInstance();
		Thread t = new Thread(sh);
		t.start();

		// wait on exit from shell (this thread never returns)
		try {
			t.join();
		} catch (InterruptedException ex) {
			// ignored
		}
	}

Try With Resources try(FileInputStream specStream=new FileInputStream(Options.specFilename)) in method public main(args String[]) : void from class org.tzi.use.main.Main


    public void write() {

        try (BufferedReader in = Files.newBufferedReader(Options.MONITOR_ASPECT_TEMPLATE, Charset.defaultCharset())) {
            while (true) {
                String line = in.readLine();
                if (line == null )
                    break;
                String s = line.trim();
                if (s.startsWith("@") && s.endsWith("@") )
                    replaceLine(s);
                else // copy
                    fOut.println(line);
            }
        } catch (IOException ex) {
            System.err.println(ex.getMessage());
        }
    }

    public void write() {
        BufferedReader in = null;
        try {
            in = new BufferedReader(new FileReader(Options.MONITOR_ASPECT_TEMPLATE));
            while (true ) {
                String line = in.readLine();
                if (line == null )
                    break;
                String s = line.trim();
                if (s.startsWith("@") && s.endsWith("@") )
                    replaceLine(s);
                else // copy
                    fOut.println(line);
            }
        } catch (IOException ex) {
            System.err.println(ex.getMessage());
        } finally {
            fOut.close();
            if (in != null )
                try { in.close(); } catch (IOException ex) {
                    // ignored
                }
        }
    }

Try With Resources try(BufferedReader in=Files.newBufferedReader(Options.MONITOR_ASPECT_TEMPLATE,Charset.defaultCharset())) in method public write() : void from class org.tzi.use.main.MonitorAspectGenerator


    private HelpForCmd() {
    	Path path = Options.homeDir.resolve("etc").resolve(HELP_PROPERTY_FILE);
        try (InputStream fis = Files.newInputStream(path)) {
            resource = new PropertyResourceBundle(fis);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private HelpForCmd() {
        try {
            FileInputStream fis = new FileInputStream(Options.homeDir
                    + Options.FILE_SEPARATOR + "etc" + Options.FILE_SEPARATOR
                    + HELP_PROPERTY_FILE);
            resource = new PropertyResourceBundle(fis);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

Try With Resources try(InputStream fis=Files.newInputStream(path)) in method private HelpForCmd() from class org.tzi.use.main.shell.HelpForCmd


    /**
     * Reads commands from a socket.
     */
    private void cmdNet() {
        int port = 1777;
        Log.verbose("waiting for connection on port " + port + "...");

        try (ServerSocket socket = new ServerSocket(port)) {
            Socket client = socket.accept();
            InetAddress clientAddr = client.getInetAddress();

            Log.verbose("connected to " + clientAddr.getHostName() + ":" + client.getPort());

            Readline readline = new SocketReadline(client, true, "net>");
            fReadlineStack.push(readline);
        } catch (IOException ex) {
            Log.error("Can't bind or listen on port " + port + ".");
        }
    }

    /**
     * Reads commands from a socket.
     */
    private void cmdNet() {
        int port = 1777;
        try {
            Log.verbose("waiting for connection on port " + port + "...");
            ServerSocket socket = new ServerSocket(port);
            Socket client = socket.accept();
            InetAddress clientAddr = client.getInetAddress();
            Log.verbose("connected to " + clientAddr.getHostName() + "/"
                    + client.getPort());
            Readline readline = new SocketReadline(client, true, "net>");
            fReadlineStack.push(readline);
        } catch (IOException ex) {
            Log.error("Can't bind or listen on port " + port + ".");
        }
    }

Try With Resources try(ServerSocket socket=new ServerSocket(port)) in method private cmdNet() : void from class org.tzi.use.main.shell.Shell


    /**
     * The scope of this test function is to test that loadCards properly loads the json into Cards
     */
    @Test void loadCards() {
        simpleGameSetupWith3PlayersOneInActionStateOthersInIdle();

        ArrayList<Position> expectedList = new ArrayList<>() {{
            add(new Position(0,0));
            add(new Position(0,1));
            add(new Position(0,2));
            add(new Position(0,3));
            add(new Position(0,4));
            add(new Position(1,0));
            add(new Position(1,4));
            add(new Position(2,0));
            add(new Position(2,4));
            add(new Position(3,0));
            add(new Position(3,4));
            add(new Position(4,0));
            add(new Position(4,1));
            add(new Position(4,2));
            add(new Position(4,3));
            add(new Position(4,4));
        }};
        assertEquals("Apollo", game.getLoadedCards().get(0).getName());
        assertTrue(game.getLoadedCards().get(1).getDefaultActionListCopy().get(1) instanceof MoveAction);
        //checks whether the list of notAvailableCells loaded from the json is properly set to the action attribute
        assertTrue(game.getLoadedCards().get(10).getDefaultActionListCopy().get(2).getNotAvailableCell().containsAll(expectedList) && expectedList.containsAll(game.getLoadedCards().get(10).getDefaultActionListCopy().get(2).getNotAvailableCell()));
    }

    /**
     * The scope of this test function is to test that loadCards properly loads the json into Cards
     */
    @Test void loadCards() {
        simpleGameSetupWith3PlayersOneInActionStateOthersInIdle();

        ArrayList<Position> expectedList = new ArrayList<Position>() {{
            add(new Position(0,0));
            add(new Position(0,1));
            add(new Position(0,2));
            add(new Position(0,3));
            add(new Position(0,4));
            add(new Position(1,0));
            add(new Position(1,4));
            add(new Position(2,0));
            add(new Position(2,4));
            add(new Position(3,0));
            add(new Position(3,4));
            add(new Position(4,0));
            add(new Position(4,1));
            add(new Position(4,2));
            add(new Position(4,3));
            add(new Position(4,4));
        }};
        assertEquals("Apollo", game.getLoadedCards().get(0).getName());
        assertTrue(game.getLoadedCards().get(1).getDefaultActionListCopy().get(1) instanceof MoveAction);
        //checks whether the list of notAvailableCells loaded from the json is properly set to the action attribute
        assertTrue(game.getLoadedCards().get(10).getDefaultActionListCopy().get(2).getNotAvailableCell().containsAll(expectedList) && expectedList.containsAll(game.getLoadedCards().get(10).getDefaultActionListCopy().get(2).getNotAvailableCell()));
    }

Replace Generic With Diamond ArrayList<Position> with ArrayList<> in method package loadCards() : void from class it.polimi.ingsw.model.GameLogicExecutorTest


    /**
     * @param message
     * This function sends the provided message over the network in a new thread
     */
    public void asyncSend(final Object message) {
        new Thread(() -> send(message)).start();
    }

    /**
     * @param message
     * This function sends the provided message over the network in a new thread
     */
    public void asyncSend(final Object message) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                send(message);
            }
        }).start();
    }

Replace Anonymous With Lambda it.polimi.ingsw.client.SocketServerConnection.asyncSend.start.new Thread.new Runnable with () -> send(message) in method public asyncSend(message Object) : void from class it.polimi.ingsw.client.SocketServerConnection


    /**
     * @param inputObject
     * Private utility function to recognise a RequestAndUpdateMessage from a PingMessage
     * To distinguish between RequestAndUpdateMessage types a visitor pattern has been implemented
     */
    private void handleMessage(Object inputObject) {
        if (inputObject instanceof RequestAndUpdateMessage) {
            RequestAndUpdateMessage message = (RequestAndUpdateMessage) inputObject;
            RequestAndUpdateObservable visitor = this;
            new Thread(() -> message.accept(visitor)).start();
        } else if (inputObject instanceof PingMessage) {
            lastPing = new Timestamp(System.currentTimeMillis());
            asyncSend(new PongMessage());
        } else {
            throw new IllegalArgumentException();
        }
    }

    /**
     * @param inputObject
     * Private utility function to recognise a RequestAndUpdateMessage from a PingMessage
     * To distinguish between RequestAndUpdateMessage types a visitor pattern has been implemented
     */
    private void handleMessage(Object inputObject) {
        if (inputObject instanceof RequestAndUpdateMessage) {
            RequestAndUpdateMessage message = (RequestAndUpdateMessage) inputObject;
            RequestAndUpdateObservable visitor = this;
            new Thread(new Runnable() {
                @Override
                public void run() {
                    message.accept(visitor);
                }
            }).start();
        } else if (inputObject instanceof PingMessage) {
            lastPing = new Timestamp(System.currentTimeMillis());
            asyncSend(new PongMessage());
        } else {
            throw new IllegalArgumentException();
        }
    }

Replace Anonymous With Lambda it.polimi.ingsw.client.SocketServerConnection.handleMessage.start.new Thread.new Runnable with () -> message.accept(visitor) in method private handleMessage(inputObject Object) : void from class it.polimi.ingsw.client.SocketServerConnection


    /**
     * Main connection function
     * It handles the socket connection and the timer initialization, it then listens the socket connection for new messages
     * Finally it closes the network socket
     */
    public boolean run(ClientView clientView) {
        ObjectInputStream socketIn;
        try {
            socket = new Socket(ip, port);
            System.out.println("Connection established"); //TODO: logging
            socketIn = new ObjectInputStream(socket.getInputStream());
            socketOut = new ObjectOutputStream(socket.getOutputStream());
        } catch (IOException e) {
            return false;
        }

        new Thread(() -> {
            try {
                Timer timer = new Timer();
                timer.schedule(new TimerTask() {
                    @Override
                    public void run() {
                        if (System.currentTimeMillis() - lastPing.getTime() > timerFrequency * 1.5 * 1000) {
                            System.out.println("No ping received!"); //TODO: logging
                            closeConnection();
                            timer.cancel();
                        }
                    }
                }, 1000, timerFrequency * 1000);

                addListener(clientView);
                while (isActive()) {
                    Object inputObject = socketIn.readObject();
                    handleMessage(inputObject);
                }
            }
            catch (Exception e){
                setActiveToFalse();
            }
            finally {
                try {
                    socketIn.close();
                    socketOut.close();
                    socket.close();
                } catch (IOException ignored) {
                }
            }
        }).start();
        return true;
    }

    /**
     * Main connection function
     * It handles the socket connection and the timer initialization
     * Finally it closes the network socket
     */
    public boolean run(ClientView clientView) {
        ObjectInputStream socketIn;
        try {
            socket = new Socket(ip, port);
            System.out.println("Connection established"); //TODO: logging
            socketIn = new ObjectInputStream(socket.getInputStream());
            socketOut = new ObjectOutputStream(socket.getOutputStream());
        } catch (IOException e) {
            return false;
        }

        new Thread(new Runnable() {
            @Override
            public void run() {
                try{
                    Timer timer = new Timer();
                    timer.schedule(new TimerTask() {
                        @Override
                        public void run() {
                            if (System.currentTimeMillis() - lastPing.getTime() > timerFrequency * 1.5 * 1000) {
                                //System.out.println("No ping received!");
                                closeConnection();
                                timer.cancel();
                            }
                        }
                    }, 1000, timerFrequency * 1000);

                    addListener(clientView);
                    Thread t0 = asyncReadFromSocket(socketIn);
                    t0.join();
                } catch(InterruptedException e){
                    System.out.println("Connection closed"); //TODO: logging
                } finally {
                    try {
                        socketIn.close();
                        socketOut.close();
                        socket.close();
                    } catch (IOException ignored) {
                    }
                }
            }
        }).start();

        return true;
    }

Replace Anonymous With Lambda it.polimi.ingsw.client.SocketServerConnection.run.start.new Thread.new Runnable with () -> {tryTimer timer=new Timer(); in method public run(clientView ClientView) : boolean from class it.polimi.ingsw.client.SocketServerConnection


    /**
     * Constructor of this class
     * @param name defines the name of the player
     */
    Player(String name) {
        this.name = name;
        this.isLoser=false;
        this.isWinner=false;
        //this.state = state;
        pawnList = new ArrayList<>();
    }

    /**
     * Constructor of this class
     * @param name defines the name of the player
     */
    Player(String name) {
        this.name = name;
        this.isLoser=false;
        this.isWinner=false;
        //this.state = state;
        pawnList = new ArrayList<Pawn>();
    }

Replace Generic With Diamond ArrayList<Pawn> with ArrayList<> in method package Player(name String) from class it.polimi.ingsw.model.Player


    @Override
    public void asyncSend(final Object message) {
        new Thread(() -> send(message)).start();
    }

    @Override
    public void asyncSend(final Object message) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                send(message);
            }
        }).start();
    }

Replace Anonymous With Lambda it.polimi.ingsw.server.SocketClientConnection.asyncSend.start.new Thread.new Runnable with () -> send(message) in method public asyncSend(message Object) : void from class it.polimi.ingsw.server.SocketClientConnection


    /**
     * getNextCurrentPlayer method to get the Players in the provided playerState. If there are no
     * players in the provided playerStateType returns an empty arrayList. If more than one player
     * is found in actionState throws an exception
     */
    ArrayList<Player> getPlayersIn(PlayerStateType playerState) {
        ArrayList<Player> tempPlayerList = new ArrayList<>();
        for (Player player : inGamePlayers) {
            if (player.getState().getType() == playerState) {
                tempPlayerList.add(player);
            }
        }
        if (playerState == PlayerStateType.ActionState && tempPlayerList.size() != 1) {
            throw new InvalidGameException("No player/more than one player in ActionState found");
        }
        return tempPlayerList;
    }

    /**
     * getNextCurrentPlayer method to get the Players in the provided playerState. If there are no
     * players in the provided playerStateType returns an empty arrayList. If more than one player
     * is found in actionState throws an exception
     */
    ArrayList<Player> getPlayersIn(PlayerStateType playerState) {
        ArrayList<Player> tempPlayerList = new ArrayList<Player>();
        for (Player player : inGamePlayers) {
            if (player.getState().getType() == playerState) {
                tempPlayerList.add(player);
            }
        }
        if (playerState == PlayerStateType.ActionState && tempPlayerList.size() != 1) {
            throw new InvalidGameException("No player/more than one player in ActionState found");
        }
        return tempPlayerList;
    }

Replace Generic With Diamond ArrayList<Player> with ArrayList<> in method package getPlayersIn(playerState PlayerStateType) : ArrayList<Player> from class it.polimi.ingsw.model.Game


    public ArrayList<Position> availableCells(Cell[][] matrixCopy) {
        return new ArrayList<>();
    }

    public ArrayList<Position> availableCells(Cell[][] matrixCopy) {
        return new ArrayList<Position>();
    }

Replace Generic With Diamond ArrayList<Position> with ArrayList<> in method public availableCells(matrixCopy Cell[][]) : ArrayList<Position> from class it.polimi.ingsw.model.action.ConstructAction


	public void updateNetworthLabel(double currentNetWorth) {
		Platform.runLater(() -> {
			netWorthLabel.setText(CapCoinFormatter.getCapCoins(currentNetWorth));
		});
	}

	public void updateNetworthLabel(double currentNetWorth) {
		Platform.runLater(new Runnable() {
			public void run() {
				netWorthLabel.setText(CapCoinFormatter.getCapCoins(currentNetWorth));
			}
		});
	}

Replace Anonymous With Lambda de.uni.mannheim.capitalismx.ui.controller.GameHudController.updateNetworthLabel.runLater.new Runnable with () -> {netWorthLabel.setText(CapCoinFormatter.getCapCoins(currentNetWorth)); in method public updateNetworthLabel(currentNetWorth double) : void from class de.uni.mannheim.capitalismx.ui.controller.GameHudController


	public void updateNetworthChangeLabel(Double diff) {
		Platform.runLater(() -> {
			if (diff != null) {
				colorHudLabel(diff, netWorthChangeLabel);
				netWorthChangeLabel.setText(((diff >= 0) ? "+" : "") + CapCoinFormatter.getCapCoins(diff));
			}
		});
	}

	public void updateNetworthChangeLabel(Double diff) {
		Platform.runLater(new Runnable() {
			public void run() {
				if (diff != null) {
					colorHudLabel(diff, netWorthChangeLabel);
					netWorthChangeLabel.setText(((diff >= 0) ? "+" : "") + CapCoinFormatter.getCapCoins(diff));
				}
			}
		});
	}

Replace Anonymous With Lambda de.uni.mannheim.capitalismx.ui.controller.GameHudController.updateNetworthChangeLabel.runLater.new Runnable with () -> {if(diff != null){colorHudLabel(diff,netWorthChangeLabel); in method public updateNetworthChangeLabel(diff Double) : void from class de.uni.mannheim.capitalismx.ui.controller.GameHudController


	public void updateNumOfEmployees() {
		Platform.runLater(() -> {
			int numOfEmployees = GameState.getInstance().getHrDepartment().getTotalNumberOfEmployees();
			int capacity = GameState.getInstance().getHrDepartment().getTotalEmployeeCapacity();
			employeeLabel.setText(numOfEmployees + "/" + capacity);
		});
	}

	public void updateNumOfEmployees() {
		Platform.runLater(new Runnable() {
			public void run() {
				int numOfEmployees = GameState.getInstance().getHrDepartment().getTotalNumberOfEmployees();
				int capacity = GameState.getInstance().getHrDepartment().getTotalEmployeeCapacity();
				employeeLabel.setText(numOfEmployees + "/" + capacity);
			}
		});
	}

Replace Anonymous With Lambda de.uni.mannheim.capitalismx.ui.controller.GameHudController.updateNumOfEmployees.runLater.new Runnable with () -> {int numOfEmployees=GameState.getInstance().getHrDepartment().getTotalNumberOfEmployees(); in method public updateNumOfEmployees() : void from class de.uni.mannheim.capitalismx.ui.controller.GameHudController


    private void init() {
        this.initProperties();
        this.initSkills();

        // initialize map
        issuedActions = new HashMap<>();
        for (String c : CAMPAIGN_NAMES) {
        	issuedActions.put(c, new ArrayList<>());
        }

        campaignsWithDates = new ArrayList<>();
        pressReleases = new ArrayList<>();
        consultancies = new ArrayList<>();
        marketResearches = new ArrayList<>();
    }

    private void init() {
        this.initProperties();
        this.initSkills();

        // initialize map
        issuedActions = new HashMap<>();
        for (String c : CAMPAIGN_NAMES) {
        	issuedActions.put(c, new ArrayList<>());
        }

        campaignsWithDates = new ArrayList<Campaign>();
        pressReleases = new ArrayList<>();
        consultancies = new ArrayList<>();
        marketResearches = new ArrayList<>();
    }

Replace Generic With Diamond ArrayList<Campaign> with ArrayList<> in method private init() : void from class de.uni.mannheim.capitalismx.marketing.department.MarketingDepartment


    /**
     *  Save the GameState instance in a file. The GameState and every Object that the GameState instance contains
     *  must implement the Serializable interface.
     * @param state A {@link GameState} instance that should be saved.
     */
    public void saveGameState(GameState state) {
        File file = new File(filePath);

        try (FileOutputStream fileOutputStream = new FileOutputStream(file)) {

            ObjectOutputStream objectOutputStream = new ObjectOutputStream(fileOutputStream);
            objectOutputStream.writeObject(state);

            objectOutputStream.close();
        } catch (IOException e) {
            logger.error(e.getMessage());
        }

    }

    /**
     *  Save the GameState instance in a file. The GameState and every Object that the GameState instance contains
     *  must implement the Serializable interface.
     * @param state A {@link GameState} instance that should be saved.
     */
    public void saveGameState(GameState state) {
        File file = new File(dir + File.separator + SAVE_GAME_FILE);

        try {
            FileOutputStream fileOutputStream = new FileOutputStream(file);
            ObjectOutputStream objectOutputStream = new ObjectOutputStream(fileOutputStream);

            objectOutputStream.writeObject(state);

            objectOutputStream.close();
            fileOutputStream.close();

        } catch (IOException e) {
            logger.error(e.getMessage());
        }

    }

Try With Resources try(FileOutputStream fileOutputStream=new FileOutputStream(file)) in method public saveGameState(state GameState) : void from class de.uni.mannheim.capitalismx.gamesave.SaveGameHandler


    /**
     *
     * @return Returns the GameState instance saved in the defined file.
     */
    public GameState loadGameState() throws ClassNotFoundException {
        GameState gameState = null;

        try (ObjectInputStream objectInputStream = new ObjectInputStream(new FileInputStream(new File(filePath)))) {
            gameState = (GameState) objectInputStream.readObject();
        } catch (IOException e) {
            logger.error(e.getMessage());
        }

        return gameState;
    }

    /**
     *
     * @return Returns the GameState instance saved in the defined file.
     */
    public GameState loadGameState() throws ClassNotFoundException{
        GameState gameState = null;

        try {
            FileInputStream fileInputStream = new FileInputStream(new File(dir + File.separator + SAVE_GAME_FILE));
            ObjectInputStream objectInputStream = new ObjectInputStream(fileInputStream);

            gameState = (GameState) objectInputStream.readObject();
        } catch (IOException e) {
            logger.error(e.getMessage());
        }

        return gameState;
    }

Try With Resources try(ObjectInputStream objectInputStream=new ObjectInputStream(new FileInputStream(new File(filePath)))) in method public loadGameState() : GameState from class de.uni.mannheim.capitalismx.gamesave.SaveGameHandler


    public void handleTimeouts() {
        Bukkit.getScheduler().runTaskTimer(NFTWorlds.getInstance(), () -> {
            PaymentRequest.getPaymentRequests().removeIf(paymentRequest -> paymentRequest.getTimeout() < System.currentTimeMillis());
            PeerToPeerPayment.getPeerToPeerPayments().removeIf(peerToPeerPayment -> peerToPeerPayment.getTimeout() < System.currentTimeMillis());
        }, 20L, 20L);
    }

    public void handleTimeouts() {
        Bukkit.getScheduler().runTaskTimer(NFTWorlds.getInstance(), new Runnable() {
            @Override
            public void run() {
                PaymentRequest.getPaymentRequests().removeIf(paymentRequest -> paymentRequest.getTimeout() < System.currentTimeMillis());
                PeerToPeerPayment.getPeerToPeerPayments().removeIf(peerToPeerPayment -> peerToPeerPayment.getTimeout() < System.currentTimeMillis());
            }
        }, 20L, 20L);
    }

Replace Anonymous With Lambda com.nftworlds.wallet.handlers.TimeoutHandler.handleTimeouts.runTaskTimer.new Runnable with () -> {PaymentRequest.getPaymentRequests().removeIf(paymentRequest -> paymentRequest.getTimeout() < System.currentTimeMillis()); in method public handleTimeouts() : void from class com.nftworlds.wallet.handlers.TimeoutHandler


    private void setRanking() {
        ResponseEntity<List<RankingRegistryDTO>> rankingResponse = localSessionSingleton.exchange(
                HOST + RANKING_PATH, HttpMethod.GET, null,
                new ParameterizedTypeReference<>() {
                });
        List<RankingRegistryDTO> rankingList = rankingResponse.getBody();

        IntStream.range(0, rankingList.size()).forEach(i -> rankingText.setText(getRankingText(i, rankingList.get(i))));

        rankingText.setEditable(false);
        rankingText.setVisible(false);
    }

    private void setRanking() {
        ResponseEntity<List<RankingRegistryDTO>> rankingResponse = localSessionSingleton.exchange(
                LoginController.HOST + RANKING_PATH, HttpMethod.GET, null,
                new ParameterizedTypeReference<List<RankingRegistryDTO>>() {
                });
        List<RankingRegistryDTO> rankingList = rankingResponse.getBody();

        IntStream.range(0, rankingList.size()).forEach(i -> rankingText.setText(getRankingText(i, rankingList.get(i))));

        rankingText.setEditable(false);
        rankingText.setVisible(false);
    }

Replace Generic With Diamond ParameterizedTypeReference<List<RankingRegistryDTO>> with ParameterizedTypeReference<> in method private setRanking() : void from class com.killerchess.view.mainpanel.MainPanelController


    private void initializeRoomsVBox() {
        Text title = new Text(" Rooms:");
        title.setFont(Font.font("Arial", FontWeight.BOLD, 14));
        getRoomsVBoxChildren().add(title);

        ResponseEntity<List<GameDTO>> roomsResponse = localSessionSingleton.exchange(
                HOST + AVAILABLE_GAMES_PATH, HttpMethod.GET, null,
                new ParameterizedTypeReference<>() {
                });

        List<GameDTO> gamesList = roomsResponse.getBody();
        List<TextArea> gamesOptions = new ArrayList<>();

        for (GameDTO gameDTO : gamesList) {
            TextArea gameOption = new TextArea();
            gameOption.setEditable(false);
            gameOption.setText("Room: " + gameDTO.getGameName() + "\n" + "host: " + gameDTO.getHost() + "\n");
            gameOption.setId(gameDTO.getGameId());
            gamesOptions.add(gameOption);
        }

        for (TextArea gameOption : gamesOptions) {
            VBox.setMargin(gameOption, new Insets(0, 0, 0, 8));
            getRoomsVBoxChildren().add(gameOption);
            createEventsForGames(gamesList, gameOption);
        }

        roomsVBox.setOnMouseClicked((e) -> roomsVBox.requestFocus());
    }

    private void initializeRoomsVBox() {
        Text title = new Text(" Rooms:");
        title.setFont(Font.font("Arial", FontWeight.BOLD, 14));
        getRoomsVBoxChildren().add(title);

        ResponseEntity<List<GameDTO>> roomsResponse = localSessionSingleton.exchange(
                LoginController.HOST + AVAILABLE_GAMES_PATH, HttpMethod.GET, null,
                new ParameterizedTypeReference<List<GameDTO>>() {
                });

        List<GameDTO> gamesList = roomsResponse.getBody();
        List<TextArea> gamesOptions = new ArrayList<>();

        for (GameDTO gameDTO : gamesList) {
            TextArea gameOption = new TextArea();
            gameOption.setEditable(false);
            gameOption.setText("Room: " + gameDTO.getGameName() + "\n" + "host: " + gameDTO.getHost() + "\n");
            gameOption.setId(gameDTO.getGameId());
            gamesOptions.add(gameOption);
        }

        for (TextArea gameOption : gamesOptions) {
            VBox.setMargin(gameOption, new Insets(0, 0, 0, 8));
            getRoomsVBoxChildren().add(gameOption);
            createEventsForGames(gamesList, gameOption);
        }

        roomsVBox.setOnMouseClicked((e) -> roomsVBox.requestFocus());
    }

Replace Generic With Diamond ParameterizedTypeReference<List<GameDTO>> with ParameterizedTypeReference<> in method private initializeRoomsVBox() : void from class com.killerchess.view.mainpanel.MainPanelController


    /**
     * Это метод должен добавить пользователя в систему.
     * По умолчанию добавляем пустой список банковских счетов.
     *
     * @param user Клиент банка.
     */
    public void addUser(User user) {
        this.users.putIfAbsent(user, new ArrayList<>());
    }

    /**
     * Это метод должен добавить пользователя в систему.
     * По умолчанию добавляем пустой список банковских счетов.
     *
     * @param user Клиент банка.
     */
    public void addUser(User user) {
        this.users.putIfAbsent(user, new ArrayList<Account>());
    }

Replace Generic With Diamond ArrayList<Account> with ArrayList<> in method public addUser(user User) : void from class ru.job4j.bank.BankService


    public static void saveKeyBindings() {
        try (BufferedWriter writer = new BufferedWriter(new FileWriter(ASSETS_PATH + "/" + SETTINGS_FILE, false))) {
            for (Key option : Key.KEYS) {
                writer.write(option.getName() + "=" + option.getKeyInput().formatKeyInput());
                writer.newLine();
            }

            writer.write("layout=" + KeyboardLayout.getCurrentKeyboardLayout().name());
        } catch (IOException e) {
            e.printStackTrace();
            resetKeyBindings();
        }
    }

    public static void saveKeyBindings() {
        FileWriter fileWriter;
        BufferedWriter bufferedWriter = null;
        try {
            fileWriter = new FileWriter(SETTINGS_FILE, false);
            bufferedWriter = new BufferedWriter(fileWriter);

            for (Key option : Key.KEYS) {
                bufferedWriter.write(option.getName() + "=" + option.getKeyInput().formatKeyInput());
                bufferedWriter.newLine();
            }

            bufferedWriter.write("layout=" + KeyboardLayout.getCurrentKeyboardLayout().name());
        } catch (IOException e) {
            e.printStackTrace();
            resetKeyBindings();
        } finally {
            try {
                if (bufferedWriter != null)
                    bufferedWriter.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

Try With Resources try(BufferedWriter writer=new BufferedWriter(new FileWriter(ASSETS_PATH + "/" + SETTINGS_FILE,false))) in method public saveKeyBindings() : void from class util.KeybindingsManager


    public static void resetKeyBindings() {
        try (BufferedWriter writer = new BufferedWriter(new FileWriter(ASSETS_PATH + "/" + SETTINGS_FILE, false))) {
            for (Key key : Key.KEYS) {
                key.reset();

                writer.write(key.getName() + "=" + key.getDefaultKeyInput().formatKeyInput());
                writer.newLine();
            }

            writer.write("layout=" + KeyboardLayout.getDefaultKeyboardLayout().name());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void resetKeyBindings() {
        FileWriter fileWriter;
        BufferedWriter bufferedWriter = null;
        try {
            fileWriter = new FileWriter(SETTINGS_FILE, false);
            bufferedWriter = new BufferedWriter(fileWriter);

            for (Key key : Key.KEYS) {
                key.reset();

                bufferedWriter.write(key.getName() + "=" + key.getDefaultKeyInput().formatKeyInput());
                bufferedWriter.newLine();
            }

            bufferedWriter.write("layout=" + KeyboardLayout.getDefaultKeyboardLayout().name());
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (bufferedWriter != null)
                    bufferedWriter.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

Try With Resources try(BufferedWriter writer=new BufferedWriter(new FileWriter(ASSETS_PATH + "/" + SETTINGS_FILE,false))) in method public resetKeyBindings() : void from class util.KeybindingsManager


    public static void loadSettings() {
        try (BufferedReader reader = new BufferedReader(new FileReader(ASSETS_PATH + "/" + SETTINGS_FILE))) {
            String line = reader.readLine();
            do {
                String[] parameters = line.split("=");
                String name = parameters[0];
                String value = parameters[1];

                Option<?> option = Option.getOption(name);
                if (option == null)
                    continue;

                option.setValue(value);
            } while ((line = reader.readLine()) != null);
        } catch (IOException | IndexOutOfBoundsException e) {
            e.printStackTrace();
            resetSettings();
        } finally {
            DisplayManager.showWindow();
        }
    }

    public static void loadSettings() {
        FileReader fileReader;
        BufferedReader bufferedReader = null;
        try {
            fileReader = new FileReader(SETTINGS_FILE);
            bufferedReader = new BufferedReader(fileReader);

            String line = bufferedReader.readLine();
            do {
                String[] parameters = line.split("=");
                String name = parameters[0];
                String value = parameters[1];

                Option<?> option = Option.getOption(name);
                if (option == null)
                    continue;

                option.setValue(value);
            } while ((line = bufferedReader.readLine()) != null);
        } catch (IOException | IndexOutOfBoundsException e) {
            e.printStackTrace();
            resetSettings();
        } finally {
            try {
                if (bufferedReader != null)
                    bufferedReader.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            DisplayManager.showWindow();
        }
    }

Try With Resources try(BufferedReader reader=new BufferedReader(new FileReader(ASSETS_PATH + "/" + SETTINGS_FILE))) in method public loadSettings() : void from class util.SettingsManager


    public static void saveSettings() {
        try (BufferedWriter writer = new BufferedWriter(new FileWriter(ASSETS_PATH + "/" + SETTINGS_FILE, false))) {
            for (Option<?> option : Option.OPTIONS) {
                if (!option.equals(Option.OPTIONS.get(0)))
                    writer.newLine();
                writer.write(option.name + "=" + option.getCallback.onOptionGet().toString());
            }
        } catch (IOException e) {
            e.printStackTrace();
            resetSettings();
        }
    }

    public static void saveSettings() {
        FileWriter fileWriter;
        BufferedWriter bufferedWriter = null;
        try {
            fileWriter = new FileWriter(SETTINGS_FILE, false);
            bufferedWriter = new BufferedWriter(fileWriter);

            for (Option<?> option : Option.OPTIONS) {
                if (!option.equals(Option.OPTIONS.get(0)))
                    bufferedWriter.newLine();
                bufferedWriter.write(option.name + "=" + option.getCallback.onOptionGet().toString());
            }
        } catch (IOException e) {
            e.printStackTrace();
            resetSettings();
        } finally {
            try {
                if (bufferedWriter != null)
                    bufferedWriter.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

Try With Resources try(BufferedWriter writer=new BufferedWriter(new FileWriter(ASSETS_PATH + "/" + SETTINGS_FILE,false))) in method public saveSettings() : void from class util.SettingsManager


    public static void resetSettings() {
        try (BufferedWriter writer = new BufferedWriter(new FileWriter(ASSETS_PATH + "/" + SETTINGS_FILE, false))) {
            for (Option<?> option : Option.OPTIONS) {
                option.reset();

                if (!option.equals(Option.OPTIONS.get(0)))
                    writer.newLine();
                writer.write(option.name + "=" + option.defaultValue);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void resetSettings() {
        FileWriter fileWriter;
        BufferedWriter bufferedWriter = null;
        try {
            fileWriter = new FileWriter(SETTINGS_FILE, false);
            bufferedWriter = new BufferedWriter(fileWriter);

            for (Option<?> option : Option.OPTIONS) {
                option.reset();

                if (!option.equals(Option.OPTIONS.get(0)))
                    bufferedWriter.newLine();
                bufferedWriter.write(option.name + "=" + option.defaultValue);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (bufferedWriter != null)
                    bufferedWriter.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

Try With Resources try(BufferedWriter writer=new BufferedWriter(new FileWriter(ASSETS_PATH + "/" + SETTINGS_FILE,false))) in method public resetSettings() : void from class util.SettingsManager


    public static void cleanOBJFile(File file) {
        if (!file.exists())
            throw new MissingFileException(file);

        List<String> lines = new ArrayList<>();

        State state = State.DEFAULT;
        int nbVertices = 0;
        int nbVerticesBoundingBox = 0;
        int nbVerticesSelectionBox = 0;
        try (BufferedReader reader = new BufferedReader(new FileReader(file))) {

            String line;
            boolean firstLine = false;
            while ((line = reader.readLine()) != null) {
                if (!firstLine) {
                    if (!line.startsWith("#")) {
                        System.err.println("File '" + file.getName() + "' already cleaned!");

                        return;
                    }
                    firstLine = true;
                }

                // Comments
                if (line.startsWith("#") || line.startsWith("s"))
                    continue;

                String[] parts = line.split(" ");
                if (parts.length == 0)
                    continue;

                // Object name
                if (line.startsWith("o")) {
                    lines.add(line);

                    if (line.contains("SelectionBox")) {
                        state = State.SELECTION_BOX;
                        nbVertices += nbVerticesBoundingBox;
                    } else if (line.contains("BoundingBox")) {
                        state = State.BOUNDING_BOX;
                        nbVertices += nbVerticesSelectionBox;
                    }
                    continue;
                }

                // vertices
                if (line.startsWith("v ")) {
                    switch (state) {
                        case DEFAULT:
                            nbVertices++;
                            break;
                        case BOUNDING_BOX:
                            nbVerticesBoundingBox++;
                            break;
                        case SELECTION_BOX:
                            nbVerticesSelectionBox++;
                            break;
                    }
                }

                if ((state == State.SELECTION_BOX || state == State.BOUNDING_BOX) && !line.startsWith("v ")) {
                    if (line.startsWith("vt") || line.startsWith("vn"))
                        continue;

                    if (line.startsWith("f")) {
                        StringBuilder newLineBuilder = new StringBuilder();
                        for (String part : parts) {
                            if (part.equals("f"))
                                newLineBuilder.append(part).append(" ");
                            else {
                                String[] p = part.split("/");
                                newLineBuilder.append(Integer.parseInt(p[0])).append(" ");
                            }
                        }
                        String newLine = newLineBuilder.toString().trim();
                        lines.add(newLine);
                    }
                    continue;
                }

                StringBuilder newLineBuilder = new StringBuilder();
                for (String part : parts) {
                    part = part.trim();
                    if (part.matches("^-?[0-9]+\\.[0-9]+$"))
                        part = String.format(Locale.ROOT, "%.4f", Float.parseFloat(part));

                    newLineBuilder.append(part).append(" ");
                }
                String newLine = newLineBuilder.toString().trim();
                lines.add(newLine);
            }

        } catch (IOException e) {
            e.printStackTrace();
        }
        try (BufferedWriter writer = new BufferedWriter(new FileWriter(file))) {
            for (String l : lines) {
                writer.write(l);
                writer.newLine();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void cleanOBJFile(String fileName) {
        List<String> lines = new ArrayList<>();

        FileReader fileReader = null;
        BufferedReader bufferedReader = null;
        FileWriter fileWriter = null;
        BufferedWriter bufferedWriter = null;

        State state = State.DEFAULT;
        int nbVertices = 0;
        int nbVerticesBoundingBox = 0;
        int nbVerticesSelectionBox = 0;
        try {
            fileReader = new FileReader("res/" + fileName);
            bufferedReader = new BufferedReader(fileReader);

            String line;
            boolean firstLine = false;
            while ((line = bufferedReader.readLine()) != null) {
                if (!firstLine) {
                    if (!line.startsWith("#")) {
                        System.err.println("File '" + fileName + "' already cleaned!");

                        return;
                    }
                    firstLine = true;
                }

                // Comments
                if (line.startsWith("#") || line.startsWith("s"))
                    continue;

                String[] parts = line.split(" ");
                if (parts.length == 0)
                    continue;

                // Object name
                if (line.startsWith("o")) {
                    lines.add(line);

                    if (line.contains("SelectionBox")) {
                        state = State.SELECTION_BOX;
                        nbVertices += nbVerticesBoundingBox;
                    } else if (line.contains("BoundingBox")) {
                        state = State.BOUNDING_BOX;
                        nbVertices += nbVerticesSelectionBox;
                    }
                    continue;
                }

                // vertices
                if (line.startsWith("v ")) {
                    switch (state) {
                        case DEFAULT:
                            nbVertices++;
                            break;
                        case BOUNDING_BOX:
                            nbVerticesBoundingBox++;
                            break;
                        case SELECTION_BOX:
                            nbVerticesSelectionBox++;
                            break;
                    }
                }

                if ((state == State.SELECTION_BOX || state == State.BOUNDING_BOX) && !line.startsWith("v ")) {
                    if (line.startsWith("vt") || line.startsWith("vn"))
                        continue;

                    if (line.startsWith("f")) {
                        StringBuilder newLineBuilder = new StringBuilder();
                        for (String part : parts) {
                            if (part.equals("f"))
                                newLineBuilder.append(part).append(" ");
                            else {
                                String[] p = part.split("/");
                                newLineBuilder.append(Integer.parseInt(p[0])).append(" ");
                            }
                        }
                        String newLine = newLineBuilder.toString().trim();
                        lines.add(newLine);
                    }
                    continue;
                }

                StringBuilder newLineBuilder = new StringBuilder();
                for (String part : parts) {
                    part = part.trim();
                    if (part.matches("^-?[0-9]+\\.[0-9]+$"))
                        part = String.format(Locale.ROOT, "%.4f", Float.parseFloat(part));

                    newLineBuilder.append(part).append(" ");
                }
                String newLine = newLineBuilder.toString().trim();
                lines.add(newLine);
            }

            bufferedReader.close();
            fileReader.close();

            fileWriter = new FileWriter("res/" + fileName);
            bufferedWriter = new BufferedWriter(fileWriter);
            for (String l : lines) {
                bufferedWriter.write(l);
                bufferedWriter.newLine();
            }

        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (bufferedReader != null)
                    bufferedReader.close();
                if (fileReader != null)
                    fileReader.close();
                if (bufferedWriter != null)
                    bufferedWriter.close();
                if (fileWriter != null)
                    fileWriter.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

Try With Resources try(BufferedReader reader=new BufferedReader(new FileReader(file))) in method public cleanOBJFile(file File) : void from class util.Utils


    public void focus() {
        if (this.clickType == ClickType.NONE) { // Start blinking effect
            this.lastBlinkTime = System.currentTimeMillis();
            this.clickType = ClickType.M1;

            this.cursor.setDisplayed(true);
            this.service.schedule(this::createRequests, 100, TimeUnit.MILLISECONDS);
        }

        if (this.textSelected)
            unselectText();

        float xCursor = MouseUtils.getCursorPos().x;
        if (xCursor > this.minCursorXPosition) {
            Text text = this.guiText.getText();
            if (xCursor > getCursorMaxPosition()) {
                this.cursor.setX(getCursorMaxPosition());
                this.cursorPosition = text.getTextString().length();
            } else {
                String textString = text.getTextString();
                List<Double> characterWidths = textString.chars().mapToDouble(text::getCharacterWidth)
                        .boxed().collect(Collectors.toList());
                float total = this.minCursorXPosition;
                int index = 0;
                for (double val : characterWidths) {
                    float floatVal = (float) val;
                    float tempTotal = total + floatVal;
                    if (floatVal + total > xCursor) {
                        float previousChar = xCursor - total;
                        float min = Math.min(tempTotal - xCursor, previousChar);
                        this.cursor.setX(min == previousChar ? total : tempTotal);
                        this.cursorPosition = index;
                        return;
                    }
                    total = tempTotal;
                    index++;
                }
            }
        }
    }

    public void focus() {
        if (this.clickType == ClickType.NONE) { // Start blinking effect
            this.lastBlinkTime = System.currentTimeMillis();
            this.clickType = ClickType.M1;

            this.cursor.setDisplayed(true);
            new Timer().schedule(new TimerTask() {
                @Override
                public void run() {
                    createRequests();
                }
            }, 100);
        }

        if (this.textSelected)
            unselectText();

        float xCursor = MouseUtils.getCursorPos().x;
        if (xCursor > this.minCursorXPosition) {
            Text text = this.guiText.getText();
            if (xCursor > getCursorMaxPosition()) {
                this.cursor.setX(getCursorMaxPosition());
                this.cursorPosition = text.getTextString().length();
            } else {
                String textString = text.getTextString();
                List<Double> characterWidths = textString.chars().mapToDouble(text::getCharacterWidth)
                        .boxed().collect(Collectors.toList());
                float total = this.minCursorXPosition;
                int index = 0;
                for (double val : characterWidths) {
                    float floatVal = (float) val;
                    float tempTotal = total + floatVal;
                    if (floatVal + total > xCursor) {
                        float previousChar = xCursor - total;
                        float min = Math.min(tempTotal - xCursor, previousChar);
                        this.cursor.setX(min == previousChar ? total : tempTotal);
                        this.cursorPosition = index;
                        return;
                    }
                    total = tempTotal;
                    index++;
                }
            }
        }
    }

Replace Anonymous With Lambda guis.presets.GuiTextInput.focus.schedule.new TimerTask with this::createRequests in method public focus() : void from class guis.presets.GuiTextInput


	@FXML
	protected void handleLoadTDURI(ActionEvent event) {
		try {
			URI uri = new URI(textFieldURI.getText());
			// TODO coap scheme use californium

			URL url = uri.toURL(); // get URL from your uri object
			try(InputStream istream = url.openStream()) {
				JsonObject jobj = JSONLD.parseJSON(istream);
				loadTD(jobj);
			}
		} catch (Exception e) {
			LOGGER.severe(e.getMessage());
			showAlertDialog(e);
		}
	}

	@FXML
	protected void handleLoadTDURI(ActionEvent event) {
		try {
			URI uri = new URI(textFieldURI.getText());
			// TODO coap scheme use californium

			URL url = uri.toURL(); // get URL from your uri object
			InputStream istream = url.openStream();

			JsonObject jobj = JSONLD.parseJSON(istream);
			loadTD(jobj);
		} catch (Exception e) {
			LOGGER.severe(e.getMessage());
			showAlertDialog(e);
		}
	}

Try With Resources try(InputStream istream=url.openStream()) in method protected handleLoadTDURI(event ActionEvent) : void from class io.thingweb.wot.fxui.MainLayoutController


		public void run() {
			try {
				URL url = uri.toURL();
				HttpURLConnection httpCon = (HttpURLConnection) url.openConnection();
				httpCon.setRequestMethod("GET");
				if(securityAsToken != null) {
					httpCon.setRequestProperty("Authorization", "Bearer " + securityAsToken);
				}

				try(InputStream is = httpCon.getInputStream()) {
					ByteArrayOutputStream baos = new ByteArrayOutputStream();
					int b;
					while ((b = is.read()) != -1) {
						baos.write(b);
					}

					String contentType = httpCon.getHeaderField("content-type");
					MediaType mediaType = MediaType.getMediaType(contentType);

					int responseCode = httpCon.getResponseCode();

					httpCon.disconnect();

					Content c = new Content(baos.toByteArray(), mediaType);

					if (responseCode == 200) {
						callback.onGet(propertyName, c);
					} else {
						// error
						error(new RuntimeException("ResponseCode==" + responseCode));
					}
				}
			} catch (Exception e) {
				error(e);
			}
		}

		public void run() {
			try {
				URL url = uri.toURL();
				HttpURLConnection httpCon = (HttpURLConnection) url.openConnection();
				httpCon.setRequestMethod("GET");
				if(securityAsToken != null) {
					httpCon.setRequestProperty("Authorization", "Bearer " + securityAsToken);
				}

				InputStream is = httpCon.getInputStream();
				ByteArrayOutputStream baos = new ByteArrayOutputStream();
				int b;
				while ((b = is.read()) != -1) {
					baos.write(b);
				}

				String contentType = httpCon.getHeaderField("content-type");
				MediaType mediaType = MediaType.getMediaType(contentType);

				int responseCode = httpCon.getResponseCode();

				httpCon.disconnect();

				Content c = new Content(baos.toByteArray(), mediaType);

				if (responseCode == 200) {
					callback.onGet(propertyName, c);
				} else {
					// error
					error(new RuntimeException("ResponseCode==" + responseCode));
				}

			} catch (Exception e) {
				error(e);
			}
		}

Try With Resources try(InputStream is=httpCon.getInputStream()) in method public run() : void from class io.thingweb.wot.fxui.client.impl.HttpClientImpl.CallbackGetTask


		public void run() {
			try {
				URL url = uri.toURL();
				HttpURLConnection httpCon = (HttpURLConnection) url.openConnection();
				httpCon.setDoOutput(true);
				httpCon.setRequestProperty("content-type", propertyValue.getMediaType().mediaType);
				httpCon.setRequestMethod(isAction ? "POST" : "PUT");
				if(securityAsToken != null) {
					httpCon.setRequestProperty("Authorization", "Bearer " + securityAsToken);
				}

				OutputStream out = httpCon.getOutputStream();
				out.write(propertyValue.getContent());
				out.close();

				try(InputStream is = httpCon.getInputStream()) {
					ByteArrayOutputStream baos = new ByteArrayOutputStream();
					int b;
					while ((b = is.read()) != -1) {
						baos.write(b);
					}

					String contentType = httpCon.getHeaderField("content-type");
					MediaType mediaType = MediaType.getMediaType(contentType);

					int responseCode = httpCon.getResponseCode();

					httpCon.disconnect();

					Content c = new Content(baos.toByteArray(), mediaType);

					// TODO generally all 2xx are success?
					// 204 No Content
					if (responseCode == 200 || responseCode == 204) {
						if(!isAction) {
							callback.onPut(name,  c);
						} else {
							callback.onAction(name, c);
						}
					} else {
						// error
						error(new RuntimeException("ResponseCode==" + responseCode));
					}
				}
			} catch (Exception e) {
				error(e);
			}
		}

		public void run() {
			try {
				URL url = uri.toURL();
				HttpURLConnection httpCon = (HttpURLConnection) url.openConnection();
				httpCon.setDoOutput(true);
				httpCon.setRequestProperty("content-type", propertyValue.getMediaType().mediaType);
				httpCon.setRequestMethod(isAction ? "POST" : "PUT");
				if(securityAsToken != null) {
					httpCon.setRequestProperty("Authorization", "Bearer " + securityAsToken);
				}

				OutputStream out = httpCon.getOutputStream();
				out.write(propertyValue.getContent());
				out.close();

				InputStream is = httpCon.getInputStream();
				ByteArrayOutputStream baos = new ByteArrayOutputStream();
				int b;
				while ((b = is.read()) != -1) {
					baos.write(b);
				}

				String contentType = httpCon.getHeaderField("content-type");
				MediaType mediaType = MediaType.getMediaType(contentType);

				int responseCode = httpCon.getResponseCode();

				httpCon.disconnect();

				Content c = new Content(baos.toByteArray(), mediaType);

				// TODO generally all 2xx are success?
				// 204 No Content
				if (responseCode == 200 || responseCode == 204) {
					if(!isAction) {
						callback.onPut(name,  c);
					} else {
						callback.onAction(name, c);
					}
				} else {
					// error
					error(new RuntimeException("ResponseCode==" + responseCode));
				}
			} catch (Exception e) {
				error(e);
			}
		}

Try With Resources try(InputStream is=httpCon.getInputStream()) in method public run() : void from class io.thingweb.wot.fxui.client.impl.HttpClientImpl.CallbackPutActionTask


    /**
     * Enter the passed class into the lists of parsers
     *
     * @param clazz The main class of an InputParser
     */
    private void addToParserList(Class<InputParser> clazz) {
        try {
            InputParser ip = clazz.getDeclaredConstructor().newInstance();
            parserByMode.put(ip.getMode(), clazz);
            parserBySuffix.put(ip.getFileSuffix(), clazz);

            String helpString = ip.getSpecificHelp();
            if (helpString == null || helpString.equals(""))
                helpString = NO_SPECIFIC_HELP_AVAILABLE;
            helpByMode.put(ip.getMode(), helpString);
            modeAndSuffix.put(ip.getMode(), ip.getFileSuffix());
        } catch (InstantiationException | InvocationTargetException | NoSuchMethodException | IllegalAccessException e) {
            e.printStackTrace();
        }

    }

    /**
     * Enter the passed class into the lists of parsers
     *
     * @param clazz The main class of an InputParser
     */
    private void addToParserList(Class<InputParser> clazz) {
        try {
            InputParser ip = clazz.newInstance();
            parserByMode.put(ip.getMode(), clazz);
            parserBySuffix.put(ip.getFileSuffix(), clazz);

            String helpString = ip.getSpecificHelp();
            if (helpString == null || helpString.equals(""))
                helpString = NO_SPECIFIC_HELP_AVAILABLE;
            helpByMode.put(ip.getMode(), helpString);
            modeAndSuffix.put(ip.getMode(), ip.getFileSuffix());
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }

    }

Merge Catch [catch(InstantiationException e), catch(IllegalAccessException e)] to catch(InstantiationException|InvocationTargetException|NoSuchMethodException|IllegalAccessException e) in method private addToParserList(clazz Class<InputParser>) : void from class de.bsd.x2svg.ParserLoader


    /**
     * Set the output types that task output will also be converted to.
     * <p>
     * NB: This setter makes a copy of the supplied instance. It does
     * not keep a reference to the Set. This allows for heirarchical
     * addition of new output types down the tree.
     * </p>
     *
     * @param types The set of output types to convert output to.
     */
    public void setOutputTypes(final Set<OutputType> types) {
        this.types = new HashSet<>(types);
    }

    /**
     * Set the output types that task output will also be converted to.
     * <p>
     * NB: This setter makes a copy of the supplied instance. It does
     * not keep a reference to the Set. This allows for heirarchical
     * addition of new output types down the tree.
     * </p>
     *
     * @param types The set of output types to convert output to.
     */
    public void setOutputTypes(final Set<OutputType> types) {
        this.types = new HashSet<OutputType>(types);
    }

Replace Generic With Diamond HashSet<OutputType> with HashSet<> in method public setOutputTypes(types Set<OutputType>) : void from class de.bsd.x2svg.ant.X2SvgSubTask


/**
     * Load the properties that we want to display from the file set via
     * {@link #setInputFile(File)} and store it in the variable properties
     *
     * @throws ParserProblemException if the input file is not acessible
     */
    private void loadPropertiesFile() throws ParserProblemException {
        try (FileInputStream fis = new FileInputStream(pFile) ){
            // File is there, load the properties from it
            properties.load(fis);
        } catch (FileNotFoundException fne) {
            throw new ParserProblemException(pFile.getName() + " in " + pFile.getAbsolutePath() + Messages.getString("PropertiesParser.4")); //$NON-NLS-1$ //$NON-NLS-2$
        } catch (IOException ioe) {
            throw new ParserProblemException(Messages.getString("PropertiesParser.5") + pFile.getName() + ": IOException"); //$NON-NLS-1$ //$NON-NLS-2$
        }
    }

/**
     * Load the properties that we want to display from the file set via
     * {@link #setInputFile(File)} and store it in the variable properties
     *
     * @throws ParserProblemException if the input file is not acessible
     */
    private void loadPropertiesFile() throws ParserProblemException {
        FileInputStream fis = null;
        try {
            fis = new FileInputStream(pFile);

            // File is there, load the properties from it
            properties.load(fis);
        } catch (FileNotFoundException fne) {
            throw new ParserProblemException(pFile.getName() + " in " + pFile.getAbsolutePath() + Messages.getString("PropertiesParser.4")); //$NON-NLS-1$ //$NON-NLS-2$
        } catch (IOException ioe) {
            throw new ParserProblemException(Messages.getString("PropertiesParser.5") + pFile.getName() + ": IOException"); //$NON-NLS-1$ //$NON-NLS-2$
        } finally {
            IOUtil.close(fis);
        }
    }

Try With Resources try(FileInputStream fis=new FileInputStream(pFile)) in method private loadPropertiesFile() : void from class de.bsd.x2svg.parsers.PropertiesParser


    /**
     * Convert the passed SVG input file into the passed output file
     * @param type A valid OutputType
     * @param input A valid input file containing SVG data
     * @param output An output file to write the result to
     * @see OutputType
     * @throws ConversionException if anything in the conversion process goes wrong
     */
    public void convert(OutputType type, File input, File output) throws ConversionException {
        try (InputStream inputStream = new FileInputStream(input);
             OutputStream outputStream = new FileOutputStream(output);)
        {
            final SVGAbstractTranscoder tc = SVGTranscoderFactory.getTranscoderForOutputType(type);
            final TranscoderInput ti = new TranscoderInput(inputStream);
            final TranscoderOutput to = new TranscoderOutput(outputStream);
            tc.transcode(ti, to);
        } catch (TranscoderException e) {
            throw new ConversionException(e.getLocalizedMessage());
        } catch (IOException e) {
            throw new ConversionException(e.getLocalizedMessage());
        }
    }

    /**
     * Convert the passed SVG input file into the passed output file
     * @param type A valid OutputType
     * @param input A valid input file containing SVG data
     * @param output An output file to write the result to
     * @see OutputType
     * @throws ConversionException if anything in the conversion process goes wrong
     */
    public void convert(OutputType type, File input, File output) throws ConversionException {
        InputStream inputStream = null;
        OutputStream outputStream = null;
        try {
            final SVGAbstractTranscoder tc = SVGTranscoderFactory.getTranscoderForOutputType(type);
            inputStream = new FileInputStream(input);
            outputStream = new FileOutputStream(output);
            final TranscoderInput ti = new TranscoderInput(inputStream);
            final TranscoderOutput to = new TranscoderOutput(outputStream);
            tc.transcode(ti, to);
        } catch (TranscoderException e) {
            throw new ConversionException(e.getLocalizedMessage());
        } catch (IOException e) {
            throw new ConversionException(e.getLocalizedMessage());
        } finally {
            IOUtil.close(inputStream);
            IOUtil.close(outputStream);
        }
    }

Try With Resources try(InputStream inputStream=new FileInputStream(input); OutputStream outputStream=new FileOutputStream(output)) in method public convert(type OutputType, input File, output File) : void from class de.bsd.x2svg.output_converter.SvgConverter


    private void setLookAndFeel() {
        try {
            UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
        } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException e) {
            e.printStackTrace();
        }
    }

    private void setLookAndFeel() {
        try {
            UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (UnsupportedLookAndFeelException e) {
            e.printStackTrace();
        }
    }

Merge Catch [catch(ClassNotFoundException e), catch(InstantiationException e), catch(IllegalAccessException e), catch(UnsupportedLookAndFeelException e)] to catch(ClassNotFoundException|InstantiationException|IllegalAccessException|UnsupportedLookAndFeelException e) in method private setLookAndFeel() : void from class org.sloubi.view.MainFrame


		private Set<NodeRenderingHandler<?>> withCustomHeading(Set<NodeRenderingHandler<?>> src) {
			Set<NodeRenderingHandler<?>> withoutHeadline = src.stream()
				.filter(h -> !(h.getNodeType() == Heading.class))
				.collect(Collectors.toSet());
			LinkedHashSet<NodeRenderingHandler<?>> ret = Sets.newLinkedHashSet(withoutHeadline);
			ret.add(new NodeRenderingHandler<Heading>(Heading.class, new NodeRenderingHandler.CustomNodeRenderer<>() {
                    @Override
                    public void render(Heading node, NodeRendererContext context, HtmlWriter html) {
                    	CustomCoreNodeRenderer.this.renderHeading(node, context, html);
                    }
                }));
			ret.add(new NodeRenderingHandler<BlockQuote>(BlockQuote.class, new NodeRenderingHandler.CustomNodeRenderer<BlockQuote>() {
                    @Override
                    public void render(BlockQuote node, NodeRendererContext context, HtmlWriter html) {
                    	CustomCoreNodeRenderer.this.renderBlockQuote(node, context, html);
                    }
                }));
			return ret;
		}

		private Set<NodeRenderingHandler<?>> withCustomHeading(Set<NodeRenderingHandler<?>> src) {
			Set<NodeRenderingHandler<?>> withoutHeadline = src.stream()
				.filter(h -> !(h.getNodeType() == Heading.class))
				.collect(Collectors.toSet());
			LinkedHashSet<NodeRenderingHandler<?>> ret = Sets.newLinkedHashSet(withoutHeadline);
			ret.add(new NodeRenderingHandler<Heading>(Heading.class, new CustomNodeRenderer<Heading>() {
                    @Override
                    public void render(Heading node, NodeRendererContext context, HtmlWriter html) {
                    	CustomCoreNodeRenderer.this.renderHeading(node, context, html);
                    }
                }));
			ret.add(new NodeRenderingHandler<BlockQuote>(BlockQuote.class, new CustomNodeRenderer<BlockQuote>() {
                    @Override
                    public void render(BlockQuote node, NodeRendererContext context, HtmlWriter html) {
                    	CustomCoreNodeRenderer.this.renderBlockQuote(node, context, html);
                    }
                }));
			return ret;
		}

Replace Generic With Diamond NodeRenderingHandler<Heading> with NodeRenderingHandler<Heading> in method private withCustomHeading(src Set<NodeRenderingHandler<?>>) : Set<NodeRenderingHandler<?>> from class de.flapdoodle.solid.content.render.Markdown2Html.CustomCoreNodeRenderer


    public LogPanelDialog(MainPanel parent, List<String> logs) {
        super(parent);
        var list = new JList<>(new StringAbstractListModel(logs));
        list.setSelectionMode(ListSelectionModel.SINGLE_INTERVAL_SELECTION);
        add(new JScrollPane(list));
        setSize(1024, 768);
        var toolbarPanel = new JPanel(new FlowLayout(FlowLayout.LEADING));
        var copy = new JButton("Copy");
        toolbarPanel.add(copy);
        copy.addActionListener(e -> {
            var builder = new StringBuilder(10000);
            list.getSelectedValuesList().forEach(line -> builder.append(line).append('\n'));
            Toolkit.getDefaultToolkit()
                    .getSystemClipboard()
                    .setContents(new StringSelection(builder.toString()), null);
        });
        getContentPane().add(toolbarPanel, BorderLayout.NORTH);
    }

    public LogPanelDialog(MainPanel parent, List<String> logs) {
        super(parent);
        var list = new JList<>(new StringAbstractListModel(logs));
        list.setSelectionMode(ListSelectionModel.SINGLE_INTERVAL_SELECTION);
        add(new JScrollPane(list));
        setSize(1024, 768);
        var toolbarPanel = new JPanel(new FlowLayout(FlowLayout.LEADING));
        var copy = new JButton("Copy");
        toolbarPanel.add(copy);
        copy.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                StringBuilder builder = new StringBuilder(10000);
                list.getSelectedValuesList().forEach(line -> builder.append(line).append('\n'));
                Toolkit.getDefaultToolkit()
                        .getSystemClipboard()
                        .setContents(new StringSelection(builder.toString()), null);
            }
        });
        getContentPane().add(toolbarPanel, BorderLayout.NORTH);
    }

Replace Anonymous With Lambda com.kpouer.roadwork.ui.logpanel.LogPanelDialog.LogPanelDialog.addActionListener.new ActionListener with e -> {var builder=new StringBuilder(10000); in method public LogPanelDialog(parent MainPanel, logs List<String>) from class com.kpouer.roadwork.ui.logpanel.LogPanelDialog


    private void loadData() {
        try {
            mapView.setTileServer(opendataServiceManager.getTileServer());
            mapView.setCenter(opendataServiceManager.getCenter());
            mapView.removeAllMarkers();
            var roadworkDataOptional = opendataServiceManager.getData();
            roadworkDataOptional.ifPresent(this::setRoadworkData);
            mapView.fitToMarkers();
        } catch (IOException | RestClientException | OpenDataException e) {
            log.error("Error retrieving data", e);
            EventQueue.invokeLater(() -> JOptionPane.showMessageDialog(this, "Error retrieving data", "Error", JOptionPane.ERROR_MESSAGE));
        }
    }

    private void loadData() {
        try {
            mapView.setTileServer(opendataServiceManager.getTileServer());
            mapView.setCenter(opendataServiceManager.getCenter());
            mapView.removeAllMarkers();
            var roadworkDataOptional = opendataServiceManager.getData();
            roadworkDataOptional.ifPresent(this::setRoadworkData);
            mapView.fitToMarkers();
        } catch (IOException e) {
            throw new RuntimeException(e);
        } catch (RestClientException e) {
            log.error("Error retrieving data", e);
            EventQueue.invokeLater(() -> JOptionPane.showMessageDialog(this, "Error retrieving data", "Error", JOptionPane.ERROR_MESSAGE));
        }
    }

Merge Catch [catch(RestClientException e), catch(IOException e)] to catch(IOException|RestClientException|OpenDataException e) in method private loadData() : void from class com.kpouer.roadwork.ui.MainPanel


    @Override
    public void actionPerformed(@Nullable ActionEvent e) {
        Roadwork selectedRoadwork = softwareModel.getSelectedRoadwork();
        if (selectedRoadwork != null) {
            if (Desktop.isDesktopSupported() && Desktop.getDesktop().isSupported(Desktop.Action.BROWSE)) {
                try {
                    Desktop.getDesktop().browse(getWmeUrl(selectedRoadwork));
                } catch (IOException | URISyntaxException ex) {
                    throw new RuntimeException(ex);
                }
            }
        }
    }

    @Override
    public void actionPerformed(@Nullable ActionEvent e) {
        Roadwork selectedRoadwork = softwareModel.getSelectedRoadwork();
        if (selectedRoadwork != null) {
            if (Desktop.isDesktopSupported() && Desktop.getDesktop().isSupported(Desktop.Action.BROWSE)) {
                try {
                    Desktop.getDesktop().browse(new URI("https://waze.com/fr/editor?env=row&lat=" + selectedRoadwork.getLatitude() + "&lon=" + selectedRoadwork.getLongitude() + "&zoomLevel=19"));
                } catch (IOException ex) {
                    throw new RuntimeException(ex);
                } catch (URISyntaxException ex) {
                    throw new RuntimeException(ex);
                }
            }
        }
    }

Merge Catch [catch(IOException ex), catch(URISyntaxException ex)] to catch(IOException|URISyntaxException ex) in method public actionPerformed(e ActionEvent) : void from class com.kpouer.roadwork.action.WmeAction


    public List<String> getServices() {
        ObjectMapper objectMapper = new ObjectMapper();
        objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
        List<String> services = new ArrayList<>();
        Collections.addAll(services, applicationContext.getBeanNamesForType(OpendataService.class));
        try (Stream<Path> files = Files.list(Path.of("opendata/json"))) {
            files
                    .map(Path::toFile)
                    .map(File::getName)
                    .forEach(services::add);
        } catch (IOException e) {
            logger.error("Unable to read opendata services", e);
        }
        return services;
    }

    public List<String> getServices() {
        ObjectMapper objectMapper = new ObjectMapper();
        objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
        List<String> services = new ArrayList<>();
        Collections.addAll(services, applicationContext.getBeanNamesForType(OpendataService.class));
        try {
            Files.list(Path.of("opendata"))
                    .map(Path::toFile)
                    .map(File::getName)
                    .forEach(services::add);
        } catch (IOException e) {
            logger.error("Unable to read opendata services", e);
        }
        return services;
    }

Try With Resources try(Stream<Path> files=Files.list(Path.of("opendata/json"))) in method public getServices() : List<String> from class com.kpouer.roadwork.service.OpendataServiceManager