    @SuppressWarnings("restriction")
	private void initJFX() {

        Platform.runLater(() -> {
                WebView view = new WebView();
                view.setStyle("-fx-background-color: #656565;"
                		+ " -fx-font-color: white;"
                		+ " -fx-border-color: #00a7c8");
                engine = view.getEngine();
                Worker<?> worker = engine.getLoadWorker();
/*
                engine.titleProperty().addListener(new ChangeListener<String>() {
                    @Override
                    public void changed(ObservableValue<? extends String> observable, String oldValue, final String newValue) {
                        SwingUtilities.invokeLater(new Runnable() {
                            @Override
                            public void run() {
                                //SimpleSwingBrowser.this.setTitle(newValue);
                            }
                        });
                    }
                });
*/
                engine.setOnStatusChanged(new EventHandler<WebEvent<String>>() {
                    @Override
                    public void handle(final WebEvent<String> event) {
                        SwingUtilities.invokeLater(()->{
                        	//System.out.println("setOnStatusChanged()");
                        	// Note: it shows the content of the hyperlink (even before the user clicks on it.
                            String content = event.getData();
                            if (content != null && !content.equals(null)) {
                            	statusBarLbl.setText(content);
                                // TODO: tweak how lblStatus displays the loading of a internal file having file:///...
                                //System.out.println("BrowserJFX : event.getData() is [" + event.getData() + "]");
                            }
                        });
                    }
                });

                engine.locationProperty().addListener(new ChangeListener<String>() {
                    @Override
                    public void changed(ObservableValue<? extends String> ov, String oldValue, final String newValue) {
                        SwingUtilities.invokeLater(() ->{
                        	//System.out.println("locationProperty()");
                        	if (isLocalHtml) {
                            	// TODO: consider parsing what to display on the textfield AFTER the user clicks on it.
                        		if (isInternal)
                            		urlTF.setText(textInputCache);
                        		else
                        			urlTF.setText("");
                        		//System.out.println("BrowserJFX : isLocalHtml is true. setText() to null");
                        	}
                        	else {
                            	// Note: it displays the content of a remote URL AFTER the user clicks on it.
                        		urlTF.setText(newValue);
                        		//System.out.println("BrowserJFX : isLocalHtml is false. setText(newValue). newValue is " + newValue);
                        	}
                        });
                    }
                });

                worker.workDoneProperty().addListener(new ChangeListener<Number>() {
                    @Override
                    public void changed(ObservableValue<? extends Number> observableValue, Number oldValue, final Number newValue) {
                        SwingUtilities.invokeLater(()->{
                        	//System.out.println("workDoneProperty()");
                                progressBar.setValue(newValue.intValue());
                        });
                    }
                });

                worker.exceptionProperty().addListener(new ChangeListener<Throwable>() {

                public void changed(ObservableValue<? extends Throwable> o, Throwable old, final Throwable value) {
                	if (worker.getState() == FAILED) {
                		SwingUtilities.invokeLater(()-> {
                				System.out.println("exceptionProperty()");
                				//System.out.println("BrowserJFX : worker.getState() == FAILED");
/*                				JOptionPane.showMessageDialog(
                                            panel,
                                            (value != null) ?
                                            engine.getLocation() + "\n" + value.getMessage() :
                                            engine.getLocation() + "\nUnexpected error.",
                                            "Loading error...",
                                            JOptionPane.ERROR_MESSAGE);
*/
                		});
                	}

                }});

                // Listens for clicking on a hyperlink (internal link on a html file only)
                worker.stateProperty().addListener(new ChangeListener<javafx.concurrent.Worker.State>() {
                    public void changed(ObservableValue ov, State oldState, State newState) {
                        if (newState == javafx.concurrent.Worker.State.SUCCEEDED) {
                             // Note : classes are from org.w3c.dom domain
                        	EventListener listener = new EventListener() {
								@Override
								public void handleEvent(org.w3c.dom.events.Event ev) {
									//System.out.println("stateProperty()");
									String href = ((Element)ev.getTarget()).getAttribute("href");
									if (href != null && !href.equals(null)) {
										System.out.println("BrowserJFX : before calling parseInput(). href is " + href);
										parseInput(href, 1);

/*		                                if (isLocalHtml) {
											// Note: call up updateHistory to update index and buttons and load the local html file
		                                	updateHistory(href, false);
		                                }
		                                else {
		                                	updateHistory(href, true);
		                                }
*/	                                }
								}
                            };

                            Document doc = engine.getDocument();
                            NodeList nodeList = doc.getElementsByTagName("a");
                            for (int i = 0; i < nodeList.getLength(); i++) {
                                ((EventTarget) nodeList.item(i)).addEventListener(EVENT_TYPE_CLICK, listener, false);
                                //((EventTarget) nodeList.item(i)).addEventListener(EVENT_TYPE_MOUSEOVER, listener, false);
                                //((EventTarget) nodeList.item(i)).addEventListener(EVENT_TYPE_MOUSEOVER, listener, false);
                            }
                        }
                    }
                });

                jfxPanel.setScene(new Scene(view));
        });
    }

    @SuppressWarnings("restriction")
	private void initJFX() {

        Platform.runLater(new Runnable() {
            @SuppressWarnings("unchecked")
			@Override
            public void run() {

			    //GuideWindow gw = guideWindow;

                WebView view = new WebView();
                view.setStyle("-fx-background-color: #656565;"
                		+ " -fx-font-color: white;"
                		+ " -fx-border-color: #00a7c8");
                engine = view.getEngine();

                Worker worker = engine.getLoadWorker();
/*
                engine.titleProperty().addListener(new ChangeListener<String>() {
                    @Override
                    public void changed(ObservableValue<? extends String> observable, String oldValue, final String newValue) {
                        SwingUtilities.invokeLater(new Runnable() {
                            @Override
                            public void run() {
                                //SimpleSwingBrowser.this.setTitle(newValue);
                            }
                        });
                    }
                });
*/
                engine.setOnStatusChanged(new EventHandler<WebEvent<String>>() {
                    @Override
                    public void handle(final WebEvent<String> event) {
                        SwingUtilities.invokeLater(new Runnable() {
                            @Override
                            public void run() {
                                lblStatus.setText(event.getData());
                                //System.out.println("BrowserJFX : event.getData() is " + event.getData());
                            }
                        });
                    }
                });

                engine.locationProperty().addListener(new ChangeListener<String>() {
                    @Override
                    public void changed(ObservableValue<? extends String> ov, String oldValue, final String newValue) {
                        SwingUtilities.invokeLater(new Runnable() {
                            @Override
                            public void run() {
                            	if (isLocalHtml) {
                            		txtURL.setText("");
                            		//System.out.println("BrowserJFX : isLocalHtml is true. setText() to null");
                            	}
                            	else {
                            		txtURL.setText(newValue);
                            		//System.out.println("BrowserJFX : isLocalHtml is false. setText(newValue). newValue is " + newValue);
                            	}
                            }
                        });
                    }
                });

                worker.workDoneProperty().addListener(new ChangeListener<Number>() {
                    @Override
                    public void changed(ObservableValue<? extends Number> observableValue, Number oldValue, final Number newValue) {
                        SwingUtilities.invokeLater(new Runnable() {
                            @Override
                            public void run() {
                                progressBar.setValue(newValue.intValue());
                            }
                        });
                    }
                });

                worker.exceptionProperty().addListener(new ChangeListener<Throwable>() {

                public void changed(ObservableValue<? extends Throwable> o, Throwable old, final Throwable value) {
                	if (worker.getState() == FAILED) {
                		SwingUtilities.invokeLater(new Runnable() {
                			@Override
                			public void run() {
                				JOptionPane.showMessageDialog(
                                            panel,
                                            (value != null) ?
                                            engine.getLocation() + "\n" + value.getMessage() :
                                            engine.getLocation() + "\nUnexpected error.",
                                            "Loading error...",
                                            JOptionPane.ERROR_MESSAGE);
                			}
                		});
                	}

                }});

                worker.stateProperty().addListener(new ChangeListener<javafx.concurrent.Worker.State>() {
                    public void changed(ObservableValue ov, State oldState, State newState) {
                        if (newState == javafx.concurrent.Worker.State.SUCCEEDED) {
                                // note next classes are from org.w3c.dom domain
                        	EventListener listener = new EventListener() {
								@Override
								public void handleEvent(org.w3c.dom.events.Event ev) {

									String href = ((Element)ev.getTarget()).getAttribute("href");

									if (href != null) {
										//System.out.println("BrowserJFX : href is " + href);
	                                	updateHistory(href);
	                                }
								}
                            };

                            Document doc = engine.getDocument();
                            NodeList nodeList = doc.getElementsByTagName("a");
                            for (int i = 0; i < nodeList.getLength(); i++) {
                                ((EventTarget) nodeList.item(i)).addEventListener(EVENT_TYPE_CLICK, listener, false);
                                //((EventTarget) nodeList.item(i)).addEventListener(EVENT_TYPE_MOUSEOVER, listener, false);
                                //((EventTarget) nodeList.item(i)).addEventListener(EVENT_TYPE_MOUSEOVER, listener, false);
                            }
                        }
                    }
                });

                jfxPanel.setScene(new Scene(view));
            }
        });
    }

Replace Anonymous With Lambda org.mars_sim.msp.ui.javafx.BrowserJFX.initJFX.runLater.new Runnable with () -> {WebView view=new WebView(); in method private initJFX() : void from class org.mars_sim.msp.ui.javafx.BrowserJFX


                    @Override
                    public void handle(final WebEvent<String> event) {
                        SwingUtilities.invokeLater(()->{
                        	//System.out.println("setOnStatusChanged()");
                        	// Note: it shows the content of the hyperlink (even before the user clicks on it.
                            String content = event.getData();
                            if (content != null && !content.equals(null)) {
                            	statusBarLbl.setText(content);
                                // TODO: tweak how lblStatus displays the loading of a internal file having file:///...
                                //System.out.println("BrowserJFX : event.getData() is [" + event.getData() + "]");
                            }
                        });
                    }

                    @Override
                    public void handle(final WebEvent<String> event) {
                        SwingUtilities.invokeLater(new Runnable() {
                            @Override
                            public void run() {
                                lblStatus.setText(event.getData());
                                //System.out.println("BrowserJFX : event.getData() is " + event.getData());
                            }
                        });
                    }

Replace Anonymous With Lambda org.mars_sim.msp.ui.javafx.BrowserJFX.initJFX.runLater.new Runnable.run.setOnStatusChanged.new EventHandler<WebEvent<String>>.handle.invokeLater.new Runnable with () -> {String content=event.getData(); in method public handle(event WebEvent<String>) : void from class org.mars_sim.msp.ui.javafx.BrowserJFX.initJFX.runLater.setOnStatusChanged.new EventHandler<WebEvent<String>>


                    @Override
                    public void changed(ObservableValue<? extends Number> observableValue, Number oldValue, final Number newValue) {
                        SwingUtilities.invokeLater(()->{
                        	//System.out.println("workDoneProperty()");
                                progressBar.setValue(newValue.intValue());
                        });
                    }

                    @Override
                    public void changed(ObservableValue<? extends Number> observableValue, Number oldValue, final Number newValue) {
                        SwingUtilities.invokeLater(new Runnable() {
                            @Override
                            public void run() {
                                progressBar.setValue(newValue.intValue());
                            }
                        });
                    }

Replace Anonymous With Lambda org.mars_sim.msp.ui.javafx.BrowserJFX.initJFX.runLater.new Runnable.run.addListener.new ChangeListener<Number>.changed.invokeLater.new Runnable with () -> {progressBar.setValue(newValue.intValue()); in method public changed(observableValue ObservableValue<? extends Number>, oldValue Number, newValue Number) : void from class org.mars_sim.msp.ui.javafx.BrowserJFX.initJFX.runLater.addListener.new ChangeListener<Number>


    @SuppressWarnings("restriction")
	public void loadLocalURL(String input) {
       	isLocalHtml = true;

        Platform.runLater(()-> {
            //System.out.println("before, path is "+ path);
            //String p = path.replace("file://", "file:///").replace("file:/", "file:///");
            //System.out.println("after, path is "+ p);
            engine.load(input);
        });
    }

    @SuppressWarnings("restriction")
	public void loadLocalURL(String path) {
       	isLocalHtml = true;

        Platform.runLater(new Runnable() {
            @Override
            public void run() {
                //System.out.println("before, path is "+ path);
                String p = path.replace("file://", "file:///").replace("file:/", "file:///");
                //System.out.println("after, path is "+ p);
                engine.load(p);
            }
        });
    }

Replace Anonymous With Lambda org.mars_sim.msp.ui.javafx.BrowserJFX.loadLocalURL.runLater.new Runnable with () -> {engine.load(input); in method public loadLocalURL(input String) : void from class org.mars_sim.msp.ui.javafx.BrowserJFX


	@Override
	public void clockPulse(double time) {
		SwingUtilities.invokeLater(() -> {
		//SwingUtilities.invokeLater(
			//new Runnable() {
				//public void run() {
					// TODO: resolve the null below
					if (master == null)  {
						//System.out.println("TimeWindow : master is null");
						master = Simulation.instance().getMasterClock();
					}

			    	int solElapsed = MarsClock.getSolOfYear(master.getMarsClock());

					if (marsTime != null) {
						martianTimeLabel.setText(marsTime.getDateTimeStamp());
						// 2015-02-24 Added solElapsedCache
						if (solElapsed != solElapsedCache) {

							if (marsTime.getMonthName() != null)
								martianMonthLabel.setText(marsTime.getMonthName());

							setSeason();

							solElapsedCache = solElapsed;
						}
					}

					if (earthTime != null) {
						if (earthTime.getTimeStamp() != null)
							earthTimeLabel.setText(earthTime.getTimeStamp());
					}

					if (master != null) {
						DecimalFormat formatter = new DecimalFormat(Msg.getString("TimeWindow.decimalFormat")); //$NON-NLS-1$
						String pulsePerSecond = formatter.format(master.getPulsesPerSecond());
						pulsespersecondLabel.setText(pulsePerSecond);
					}

					if (uptimer != null) {
						uptimeLabel.setText(uptimer.getUptime());
					}

					calendarDisplay.update();
				//}

			}
		);
	}

	@Override
	public void clockPulse(double time) {
		SwingUtilities.invokeLater(
			new Runnable() {
				public void run() {
					// TODO: resolve the null below
					if (master == null)  {
						//System.out.println("TimeWindow : master is null");
						master = Simulation.instance().getMasterClock();
					}

			    	int solElapsed = MarsClock.getSolOfYear(master.getMarsClock());

					if (marsTime != null) {
						martianTimeLabel.setText(marsTime.getDateTimeStamp());
						// 2015-02-24 Added solElapsedCache
						if (solElapsed != solElapsedCache) {

							if (marsTime.getMonthName() != null)
								martianMonthLabel.setText(marsTime.getMonthName());

							setSeason();

							solElapsedCache = solElapsed;
						}
					}

					if (earthTime != null) {
						if (earthTime.getTimeStamp() != null)
							earthTimeLabel.setText(earthTime.getTimeStamp());
					}

					if (master != null) {
						DecimalFormat formatter = new DecimalFormat(Msg.getString("TimeWindow.decimalFormat")); //$NON-NLS-1$
						String pulsePerSecond = formatter.format(master.getPulsesPerSecond());
						pulsespersecondLabel.setText(pulsePerSecond);
					}

					if (uptimer != null) {
						uptimeLabel.setText(uptimer.getUptime());
					}

					calendarDisplay.update();
				}
			}
		);
	}

Replace Anonymous With Lambda org.mars_sim.msp.ui.swing.tool.time.TimeWindow.clockPulse.invokeLater.new Runnable with () -> {if(master == null){master=Simulation.instance().getMasterClock(); in method public clockPulse(time double) : void from class org.mars_sim.msp.ui.swing.tool.time.TimeWindow


    /**
     * Constructor
     * @throws Exception when error in creating surface features.
     */
    public SurfaceFeatures() {

        surfaceTerrain = new TerrainElevation();
        mineralMap = new RandomMineralMap();
        exploredLocations = new CopyOnWriteArrayList<>();
        areothermalMap = new AreothermalMap();

        //weather = Simulation.instance().getMars().getWeather();

        mars = Simulation.instance().getMars();
        //orbitInfo = mars.getOrbitInfo();
        missionManager = Simulation.instance().getMissionManager();

        try {
            landmarks = SimulationConfig.instance().getLandmarkConfiguration().getLandmarkList();
        } catch (Exception e) {
            throw new IllegalStateException("Landmarks could not be loaded: " + e.getMessage(), e);
        }

    }

    /**
     * Constructor
     * @throws Exception when error in creating surface features.
     */
    public SurfaceFeatures() {

        surfaceTerrain = new TerrainElevation();
        mineralMap = new RandomMineralMap();
        exploredLocations = new ArrayList<ExploredLocation>();
        areothermalMap = new AreothermalMap();

        //weather = Simulation.instance().getMars().getWeather();

        mars = Simulation.instance().getMars();
        //orbitInfo = mars.getOrbitInfo();
        missionManager = Simulation.instance().getMissionManager();

        try {
            landmarks = SimulationConfig.instance().getLandmarkConfiguration().getLandmarkList();
        } catch (Exception e) {
            throw new IllegalStateException("Landmarks could not be loaded: " + e.getMessage(), e);
        }

    }

Replace Generic With Diamond ArrayList<ExploredLocation> with CopyOnWriteArrayList<> in method public SurfaceFeatures() from class org.mars_sim.msp.core.mars.SurfaceFeatures


    /**
     * Gets the amount of the food item in the whole settlement.
     * @return dessertAvailable
     */
    // 2015-01-02 Modified pickOneOil()
	public String pickOneOil() {

	    	List<String> oilList = new CopyOnWriteArrayList<>();

	 	    if (getAmountAvailable("Soybean Oil") > AMOUNT_OF_OIL_PER_MEAL)
	 	    	oilList.add("Soybean Oil");
	 	    if (getAmountAvailable("Garlic Oil") > AMOUNT_OF_OIL_PER_MEAL)
	 	    	oilList.add("Garlic Oil");
	 	    if (getAmountAvailable("Sesame Oil") > AMOUNT_OF_OIL_PER_MEAL)
	 	    	oilList.add("Sesame Oil");
	 	    if (getAmountAvailable("Peanut Oil") > AMOUNT_OF_OIL_PER_MEAL)
	 	    	oilList.add("Peanut Oil");

			int upperbound = oilList.size();
	    	int lowerbound = 1;
	    	String selectedOil = "None";

	    	if (upperbound > 1) {
	    		int index = ThreadLocalRandom.current().nextInt(lowerbound, upperbound);
	    		//int number = (int)(Math.random() * ((upperbound - lowerbound) + 1) + lowerbound);
		    	selectedOil = oilList.get(index);
	    	}
	    	else if (upperbound == 1) {
		    	selectedOil = oilList.get(0);
	    	}
	    	else if (upperbound == 0) {
	    		selectedOil = "none";
	    		logger.info("Running out of oil in " + settlement.getName());
	    	}
	    	return selectedOil;
		}

    /**
     * Gets the amount of the food item in the whole settlement.
     * @return dessertAvailable
     */
    // 2015-01-02 Modified pickOneOil()
	public String pickOneOil() {

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

	 	    if (getAmountAvailable("Soybean Oil") > AMOUNT_OF_OIL_PER_MEAL)
	 	    	oilList.add("Soybean Oil");
	 	    if (getAmountAvailable("Garlic Oil") > AMOUNT_OF_OIL_PER_MEAL)
	 	    	oilList.add("Garlic Oil");
	 	    if (getAmountAvailable("Sesame Oil") > AMOUNT_OF_OIL_PER_MEAL)
	 	    	oilList.add("Sesame Oil");
	 	    if (getAmountAvailable("Peanut Oil") > AMOUNT_OF_OIL_PER_MEAL)
	 	    	oilList.add("Peanut Oil");

			int upperbound = oilList.size();
	    	int lowerbound = 1;
	    	String selectedOil = "None";

	    	if (upperbound > 1) {
	    		int index = ThreadLocalRandom.current().nextInt(lowerbound, upperbound);
	    		//int number = (int)(Math.random() * ((upperbound - lowerbound) + 1) + lowerbound);
		    	selectedOil = oilList.get(index);
	    	}
	    	else if (upperbound == 1) {
		    	selectedOil = oilList.get(0);
	    	}
	    	else if (upperbound == 0) {
	    		selectedOil = "none";
	    		logger.info("Running out of oil in " + settlement.getName());
	    	}
	    	return selectedOil;
		}

Replace Generic With Diamond ArrayList<String> with CopyOnWriteArrayList<> in method public pickOneOil() : String from class org.mars_sim.msp.core.structure.building.function.cooking.Cooking


	/**
	 * Sets an edit-check error.
	 * @param errorString the error description.
	 */
	private void setError(String errorString) {
		// Platform.runLater is needed to switch from Swing EDT to JavaFX Thread
		Platform.runLater(() -> {
			if (!hasError) {
    			hasError = true;
    			errorLabel.setText(errorString);
    			createButton.setDisable(true);
    		}
		});
	}

	/**
	 * Sets an edit-check error.
	 * @param errorString the error description.
	 */
	private void setError(String errorString) {
		Platform.runLater(new Runnable() {
            @Override
            public void run() {

        		if (!hasError) {
        			hasError = true;
        			errorLabel.setText(errorString);
        			createButton.setDisable(true);
        		}

            }
        });

	}

Replace Anonymous With Lambda org.mars_sim.msp.javafx.ScenarioConfigEditorFX.setError.runLater.new Runnable with () -> {if(!hasError){hasError=true; in method private setError(errorString String) : void from class org.mars_sim.msp.javafx.ScenarioConfigEditorFX


    /**
     * 加载字体到映射中
     *
     * @param file 字体文件路径
     */
    public void loadFont(File file) {
        String fileName = file.getName();
        int offset = fileName.lastIndexOf('.');
        String suffix = offset == -1 ? ".ttf" : fileName.substring(offset);
        try (TTFDataStream raf = new MemoryTTFDataStream(new FileInputStream(file))) {
            switch (suffix) {
                case ".otf":
                case ".ttf": {
                    TrueTypeFont font = new TrueTypeFont().parse(raf);
                    addSystemFontMapping(font, file.getPath());
                    font = null;
                    break;
                }
                case ".ttc": {
                    TrueTypeCollection trueTypeCollection = new TrueTypeCollection().parse(raf);
                    trueTypeCollection.foreach(font -> {
                        addSystemFontMapping(font, file.getPath());
                        font = null;
                    });
                    break;
                }
                default:
                    break;
            }
        } catch (Exception e) {
            log.info("字体无法解析，跳过 " + file.getAbsolutePath());
        }
    }

    /**
     * 加载字体到映射中
     *
     * @param file 字体文件
     */
    public void loadFont(File file) {
        String fileName = file.getName().toLowerCase();

        int offset = fileName.lastIndexOf('.');
        String suffix = offset == -1 ? ".ttf" : fileName.substring(offset);
        try {
            switch (suffix) {
                case ".otf":
                case ".ttf": {
                    OTFParser parser = new OTFParser(true);
                    OpenTypeFont openTypeFont = parser.parse(file);
                    NamingTable namingTable = openTypeFont.getNaming();
                    addSystemFontMapping(namingTable, file.getPath());
                    break;
                }
                case ".ttc": {
                    TrueTypeCollection trueTypeCollection = new TrueTypeCollection(file);
                    trueTypeCollection.processAllFonts(trueTypeFont -> {
                        NamingTable namingTable = trueTypeFont.getNaming();
                        addSystemFontMapping(namingTable, file.getPath());
                    });
                    break;
                }
                default:
                    break;
            }
        } catch (Exception e) {
            log.info("字体无法解析，跳过 " + file.getAbsolutePath());
        }
    }

Try With Resources try(TTFDataStream raf=new MemoryTTFDataStream(new FileInputStream(file))) in method public loadFont(file File) : void from class org.ofdrw.converter.FontLoader


    /**
     * OFD转换PDF
     *
     * @param input  OFD文件路径
     * @param output PDF输出流，支持OutputStream、Path、File、String（文件路径）
     */
    public static void toPdf(Path input, Object output) {

        try (DLOFDReader reader = new DLOFDReader(input);
             PDDocument pdfDocument = new PDDocument()) {

            List<OfdPageVo> ofdPageVoList = reader.getOFDDocumentVo().getOfdPageVoList();

            long start;
            long end;
            int pageNum = 1;

            PdfboxMaker pdfMaker = new PdfboxMaker(reader, pdfDocument);
            for (OfdPageVo ofdPageVo : ofdPageVoList) {
                start = System.currentTimeMillis();
                pdfMaker.makePage(ofdPageVo);
                end = System.currentTimeMillis();
                logger.info(String.format("page %d speed time %d", pageNum++, end - start));
            }

            if (output instanceof OutputStream) {
                pdfDocument.save((OutputStream) output);
            } else if (output instanceof File) {
                pdfDocument.save((File) output);
            } else if (output instanceof String) {
                pdfDocument.save((String) output);
            } else if (output instanceof Path) {
                pdfDocument.save(Files.newOutputStream((Path) output));
            } else {
                throw new IllegalArgumentException("不支持的输出格式(output)，仅支持OutputStream、Path、File、String");
            }
        } catch (IllegalArgumentException e){
            throw e;
        }catch (Exception e) {
            logger.error("convert to pdf failed", e);
            throw new GeneralConvertException(e);
        }
    }

    /**
     * 转PDF
     *
     * @param input  OFD输入路径
     * @param output PDF输出流
     */
    public static void toPdf(Path input, Object output) {
        DLOFDReader reader = null;
        PDDocument pdfDocument = null;
        try {
            reader = new DLOFDReader(input);
            pdfDocument = new PDDocument();

            List<OfdPageVo> ofdPageVoList = reader.getOFDDocumentVo().getOfdPageVoList();

            long start;
            long end;
            int pageNum = 1;

            PdfboxMaker pdfMaker = new PdfboxMaker(reader, pdfDocument);
            for (OfdPageVo ofdPageVo : ofdPageVoList) {
                start = System.currentTimeMillis();
                pdfMaker.makePage(ofdPageVo);
                end = System.currentTimeMillis();
                logger.info(String.format("page %d speed time %d", pageNum++, end - start));
            }

            if (output instanceof OutputStream) {
                pdfDocument.save((OutputStream) output);
            } else if (output instanceof File) {
                pdfDocument.save((File) output);
            } else if (output instanceof String) {
                pdfDocument.save((String) output);
            } else {
                throw new IllegalArgumentException("pdf save failed, output don't support");
            }
        } catch (Exception e) {
            logger.error("convert to pdf failed", e);
            throw new RuntimeException(e);
        } finally {
            try {
                if (reader != null) {
                    reader.close();
                }
                if (pdfDocument != null) {
                    pdfDocument.close();
                }
            } catch (IOException e) {
                logger.error("close OFDReader failed", e);
            }

        }
    }

Try With Resources try(DLOFDReader reader=new DLOFDReader(input); PDDocument pdfDocument=new PDDocument()) in method public toPdf(input Path, output Object) : void from class org.ofdrw.converter.ConvertHelper


    /**
     * 执行Canvas 渲染器
     *
     * @param layer      将要渲染到的图层
     * @param resManager 资源管理器
     * @param canvas     canvas对象
     * @param maxUnitID  最大ID
     * @throws RenderException 渲染发生错误
     */
    public static void render(CT_PageBlock layer,
                              ResManager resManager,
                              Canvas canvas,
                              AtomicInteger maxUnitID) throws RenderException {
        // 获取绘制器
        Drawer drawer = canvas.getDrawer();
        if (drawer == null) {
            return;
        }

        CT_PageBlock block = new CT_PageBlock();
        block.setObjID(maxUnitID.incrementAndGet());
        layer.addPageBlock(block);

        ST_Box boundary = new ST_Box(canvas.getX(), canvas.getY(), canvas.getWidth(), canvas.getHeight());
        // 构建上下文
        try (DrawContext ctx = new DrawContext(block, boundary, maxUnitID, resManager)) {
            // 执行绘制工作
            drawer.draw(ctx);
        } catch (IOException ioException) {
            throw new RenderException("Canvas绘制过程中发生异常", ioException);
        }
    }

    /**
     * 执行Canvas 渲染器
     *
     * @param layer      将要渲染到的图层
     * @param resManager 资源管理器
     * @param canvas     canvas对象
     * @param maxUnitID  最大ID
     * @throws RenderException 渲染发生错误
     */
    public static void render(CT_PageBlock layer,
                              ResManager resManager,
                              Canvas canvas,
                              AtomicInteger maxUnitID) throws RenderException {
        // 获取绘制器
        Drawer drawer = canvas.getDrawer();
        if (drawer == null) {
            return;
        }

        CT_PageBlock block = new CT_PageBlock();
        block.setObjID(maxUnitID.incrementAndGet());
        layer.addPageBlock(block);

        // 构建上下文
        DrawContext ctx = new DrawContext(block, maxUnitID, resManager);
        try {
            // 执行绘制工作
            drawer.draw(ctx);
        } catch (IOException ioException) {
            throw new RenderException("Canvas绘制过程中发生异常", ioException);
        }
    }

Try With Resources try(DrawContext ctx=new DrawContext(block,boundary,maxUnitID,resManager)) in method public render(layer CT_PageBlock, resManager ResManager, canvas Canvas, maxUnitID AtomicInteger) : void from class org.ofdrw.layout.engine.render.CanvasRender


    public ST_Array(String[] arr) {
        array = new ArrayList<>(arr.length);
        for (String item : arr) {
            if (item == null || item.length() == 0) {
                throw new IllegalArgumentException("数组元素为空");
            }
            array.add(item);
        }
    }

    public ST_Array(String[] arr) {
        array = new ArrayList<Object>(arr.length);
        for (String item : arr) {
            if (item == null || item.length() == 0) {
                throw new IllegalArgumentException("数组元素为空");
            }
            array.add(item);
        }
    }

Replace Generic With Diamond ArrayList<Object> with ArrayList<> in method public ST_Array(arr String[]) from class org.ofdrw.core.basicType.ST_Array


    public static Map<String, List<RDFNode>> getMap(String queryString, ResultSet resultSet) {
        //select var
        List<String> vars = Knowdip.getSparqlVar(queryString);
        Map<String, List<RDFNode>> rdfnode = new HashMap<>();
        while (resultSet.hasNext()) {
            QuerySolution next = resultSet.next();
            vars.forEach(v -> {
                if (rdfnode.containsKey(v)) {
                    rdfnode.get(v).add(next.get(v));
                } else {
                    ArrayList<RDFNode> arrayList = new ArrayList<>();
                    arrayList.add(next.get(v));
                    rdfnode.put(v, arrayList);
                }
            });
        }
        return rdfnode;
    }

    public static Map<String, List<RDFNode>> getMap(String queryString, ResultSet resultSet) {
        //select var
        List<String> vars = Knowdip.getSparqlVar(queryString);
        Map<String, List<RDFNode>> rdfnode = new HashMap<>();
        while (resultSet.hasNext()) {
            QuerySolution next = resultSet.next();
            vars.forEach(v -> {
                if (rdfnode.containsKey(v)) {
                    rdfnode.get(v).add(next.get(v));
                } else {
                    ArrayList<RDFNode> arrayList = new ArrayList<RDFNode>();
                    arrayList.add(next.get(v));
                    rdfnode.put(v, arrayList);
                }
            });
        }
        return rdfnode;
    }

Replace Generic With Diamond ArrayList<RDFNode> with ArrayList<> in method public getMap(queryString String, resultSet ResultSet) : Map<String,List<RDFNode>> from class info.ponciano.lab.knowdip.Knowdip


    public static void main(String[] args) {

        try {
            args = new String[2];
            args[0] = "src/main/resources/knowdip.owl";
            args[1] = "output/";
            /**
             *  ontologyPath,output directory, reset the output directory, using a triple store
             */
            Knowdip.init(args[0], args[1], false, true);

            Knowdip knowdip = Knowdip.get();
            knowdip.add(LoadCloud.class);
            knowdip.add(PatchesSegmentation.class);
            knowdip.add(GetPatchSize.class);
            knowdip.add(GetPatchColor.class);
            knowdip.add(GetPatchArea.class);
            knowdip.add(GetPatchDensity.class);
            knowdip.add(GetPatchDistanceX.class);
            knowdip.add(GetPatchDistanceY.class);
            knowdip.add(GetPatchDistanceZ.class);
            knowdip.add(GetPatchMaxZ.class);
            knowdip.add(GetPatchMinZ.class);
            knowdip.add(GetPatchNormalX.class);
            knowdip.add(GetPatchNormalY.class);
            knowdip.add(GetPatchNormalZ.class);
            knowdip.add(GetPatchVolume.class);

            //interprets all SPARQL queries contained in the file
            knowdip.interpretsFile("src/main/resources/queries.txt");

            /**
             * If no distance is found, perhaps they are not calculated.
            */
            System.out.println("Calculate distance between patches");
            if (!knowdip.select("SELECT ?c WHERE{ ?c rdf:type knowdip:Patch . ?c knowdip:has2m ?c2  }").hasNext()) {//Calculate the distance between patches.
                MinPatchesDistanceEstimation mde = new MinPatchesDistanceEstimation();
                mde.run();
            }
            String selectString = knowdip.selectAsText("SELECT ?c ?z WHERE{ ?c rdf:type knowdip:Patch . ?c knowdip:hasNormalZ ?z . Filter(?z <0.1 )  }");
            System.out.println(selectString);

            knowdip.save();
        } catch (IOException | KnowdipException | PiOntologyException ex) {
            Logger.getLogger(FileExempleWithTS.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    public static void main(String[] args) {

        try {
            args = new String[2];
            args[0] = "src/main/resources/knowdip.owl";
            args[1] = "output/";
            /**
             *  ontologyPath,output directory, reset the output directory, using a triple store
             */
            Knowdip.init(args[0], args[1], false, true);

            Knowdip knowdip = Knowdip.get();
            knowdip.add(LoadCloud.class);
            knowdip.add(PatchesSegmentation.class);
            knowdip.add(GetPatchSize.class);
            knowdip.add(GetPatchColor.class);
            knowdip.add(GetPatchArea.class);
            knowdip.add(GetPatchDensity.class);
            knowdip.add(GetPatchDistanceX.class);
            knowdip.add(GetPatchDistanceY.class);
            knowdip.add(GetPatchDistanceZ.class);
            knowdip.add(GetPatchMaxZ.class);
            knowdip.add(GetPatchMinZ.class);
            knowdip.add(GetPatchNormalX.class);
            knowdip.add(GetPatchNormalY.class);
            knowdip.add(GetPatchNormalZ.class);
            knowdip.add(GetPatchVolume.class);

            //interprets all SPARQL queries contained in the file
            knowdip.interpretsFile("src/main/resources/queries.txt");

            /**
             * If no distance is found, perhaps they are not calculated.
            */
            System.out.println("Calculate distance between patches");
            if (!knowdip.select("SELECT ?c WHERE{ ?c rdf:type knowdip:Patch . ?c knowdip:has2m ?c2  }").hasNext()) {//Calculate the distance between patches.
                MinPatchesDistanceEstimation mde = new MinPatchesDistanceEstimation();
                mde.run();
            }
            String selectString = knowdip.selectAsText("SELECT ?c ?z WHERE{ ?c rdf:type knowdip:Patch . ?c knowdip:hasNormalZ ?z . Filter(?z <0.1 )  }");
            System.out.println(selectString);

            knowdip.save();
        } catch (IOException | KnowdipException ex) {
            Logger.getLogger(FileExempleWithTS.class.getName()).log(Level.SEVERE, null, ex);
        } catch (PiOntologyException ex) {
            Logger.getLogger(FileExempleWithTS.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

Merge Catch [catch(IOException|KnowdipException ex), catch(PiOntologyException ex)] to catch(IOException|KnowdipException|PiOntologyException ex) in method public main(args String[]) : void from class examples.FileExempleWithTS


    public static void main(String[] args) {
        final JFrame jFrame = new JFrame("Jess Menu");
        jFrame.setLayout(new GridBagLayout());
        jFrame.setSize(300, 200);
        jFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        GridBagConstraints c = new GridBagConstraints();

        JLabel title = new JLabel("Jess");
        title.setText("Jess");
        title.setFont(new Font("Times New Roman", Font.BOLD, 50));
        c.fill = GridBagConstraints.VERTICAL;
        c.weightx = 0.0;
        c.gridwidth = 3;
        c.gridx = 0;
        c.gridy = 0;
        jFrame.add(title, c);

        JLabel options = new JLabel("Black or White?");
        options.setText("Black or White?");
        options.setFont(new Font("Times New Roman", Font.PLAIN, 20));
        c.fill = GridBagConstraints.VERTICAL;
        c.weightx = 0.0;
        c.gridwidth = 3;
        c.gridx = 0;
        c.gridy = 1;
        jFrame.add(options, c);

        JPanel iGotOptions = new JPanel();

        final JRadioButton b1 = new JRadioButton();
        b1.setText("White");
        b1.setSelected(true);
        iGotOptions.add(b1);
        final JRadioButton b2 = new JRadioButton();
        b2.setText("Black");
        iGotOptions.add(b2);

        c.gridx = 0;
        c.gridy = 2;
        jFrame.add(iGotOptions, c);

        ButtonGroup group = new ButtonGroup();
        group.add(b1);
        group.add(b2);

        JButton start = new JButton();
        start.setText("Start");
        c.fill = GridBagConstraints.VERTICAL;
        c.weightx = 0.5;
        c.gridwidth = 1;
        c.gridx = 0;
        c.gridy = 3;
        jFrame.add(start, c);

        jFrame.setLocationRelativeTo(null);
        jFrame.setResizable(false);
        jFrame.setVisible(true);

        // Button Listener
        start.addActionListener(e -> {
            if (b1.isSelected()) {
                whiteTurn = true;
                Chess game = new Chess();
                try {
                    game.start(true);
                } catch (IOException e1) {
                    e1.printStackTrace();
                }
            } else if (b2.isSelected()) {
                whiteTurn = false;
                Chess game = new Chess();
                try {
                    game.start(false);
                } catch (IOException e1) {
                    e1.printStackTrace();
                }
            }
            jFrame.dispose();
        });
    }

    public static void main(String[] args) {
        final JFrame jFrame = new JFrame("Jess Menu");
        jFrame.setLayout(new GridBagLayout());
        jFrame.setSize(300, 200);
        jFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        GridBagConstraints c = new GridBagConstraints();

        JLabel title = new JLabel("Jess");
        title.setText("Jess");
        title.setFont(new Font("Times New Roman", Font.BOLD, 50));
        c.fill = GridBagConstraints.VERTICAL;
        c.weightx = 0.0;
        c.gridwidth = 3;
        c.gridx = 0;
        c.gridy = 0;
        jFrame.add(title, c);

        JLabel options = new JLabel("Black or White?");
        options.setText("Black or White?");
        options.setFont(new Font("Times New Roman", Font.PLAIN, 20));
        c.fill = GridBagConstraints.VERTICAL;
        c.weightx = 0.0;
        c.gridwidth = 3;
        c.gridx = 0;
        c.gridy = 1;
        jFrame.add(options, c);

        JPanel iGotOptions = new JPanel();

        final JRadioButton b1 = new JRadioButton();
        b1.setText("White");
        b1.setSelected(true);
        iGotOptions.add(b1);
        final JRadioButton b2 = new JRadioButton();
        b2.setText("Black");
        iGotOptions.add(b2);

        c.gridx = 0;
        c.gridy = 2;
        jFrame.add(iGotOptions, c);

        ButtonGroup group = new ButtonGroup();
        group.add(b1);
        group.add(b2);

        JButton start = new JButton();
        start.setText("Start");
        c.fill = GridBagConstraints.VERTICAL;
        c.weightx = 0.5;
        c.gridwidth = 1;
        c.gridx = 0;
        c.gridy = 3;
        jFrame.add(start, c);

        jFrame.setLocationRelativeTo(null);
        jFrame.setResizable(false);
        jFrame.setVisible(true);

        // Button Listener
        start.addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent e) {
                if (b1.isSelected()) {
                    whiteTurn = true;
                    Chess game = new Chess();
                    try {
                        game.start(true);
                    } catch (IOException e1) {
                        e1.printStackTrace();
                    }
                } else if (b2.isSelected()) {
                    whiteTurn = false;
                    Chess game = new Chess();
                    try {
                        game.start(false);
                    } catch (IOException e1) {
                        e1.printStackTrace();
                    }
                }
                jFrame.dispose();
            }
        });
    }

Replace Anonymous With Lambda com.redplover.app.App.main.addActionListener.new ActionListener with e -> {if(b1.isSelected()){whiteTurn=true; in method public main(args String[]) : void from class com.redplover.app.App


    public static JSONObject readJsonFromUrl(String url) throws IOException {
        InputStream is = new URL(url).openStream();
        try (BufferedReader br = new BufferedReader(new InputStreamReader(is, StandardCharsets.UTF_8));
            ){
            String jsonText = readAll(br);
            return new JSONObject(jsonText);

        } finally {
            is.close();
        }
    }

    public static JSONObject readJsonFromUrl(String url) throws IOException {
        InputStream is = new URL(url).openStream();
        try {
            BufferedReader br = new BufferedReader(new InputStreamReader(is, StandardCharsets.UTF_8));
            String jsonText = readAll(br);
            return new JSONObject(jsonText);

        } finally {
            is.close();
        }
    }

Try With Resources try(BufferedReader br=new BufferedReader(new InputStreamReader(is,StandardCharsets.UTF_8))) in method public readJsonFromUrl(url String) : JSONObject from class json.JsonReader


    public static JSONArray readJsonArrayFromUrl(String url) throws IOException, JSONException {
        InputStream is = new URL(url).openStream();
        try (BufferedReader rd = new BufferedReader(new InputStreamReader(is, StandardCharsets.UTF_8));
            ){
            String jsonText = readAll(rd);
            return new JSONArray(jsonText);

        } finally {
            is.close();
        }
    }

    public static JSONArray readJsonArrayFromUrl(String url) throws IOException, JSONException {
        InputStream is = new URL(url).openStream();
        try {
            BufferedReader rd = new BufferedReader(new InputStreamReader(is, StandardCharsets.UTF_8));
            String jsonText = readAll(rd);
            return new JSONArray(jsonText);

        } finally {
            is.close();
        }
    }

Try With Resources try(BufferedReader rd=new BufferedReader(new InputStreamReader(is,StandardCharsets.UTF_8))) in method public readJsonArrayFromUrl(url String) : JSONArray from class json.JsonReader


    public static void main(String[] args) {
        //LOGGER.debug(dao.getStudentClass("物联网信息技术"));
        SwingUtilities.invokeLater(() -> {
            WebLookAndFeel.install();
            LanguageManager.setLanguage(new Language(new Locale("zh")));
            LanguageManager.addDictionary ( new Dictionary(
                    new ClassResource( Main.class, "resources/language.xml" )
            ) );
            initGobalFont(new Font("微软雅黑", Font.PLAIN, 15));

            //frame.setContentPane(new Login().getRoot());
            studentMain = new StudentMain();
            frame.setContentPane(studentMain.InitMainPanel());
            //frame.setExtendedState(JFrame.MAXIMIZED_BOTH);

            frame.setVisible(true);
            Main.LOGGER.debug(frame.getGraphics().getFontMetrics(frame.getFont()).stringWidth("A"));

            System.out.println(studentMain.utilsMenu.getHeight());
            System.out.println(studentMain.utilsMenu.getWidth());

            Dimension dimension = new Dimension(studentMain.utilsMenu.getWidth() / 5, studentMain.utilsMenu.getHeight() / 3);
            studentMain.utilsMenu.getAcademyComboBox().setPreferredSize(dimension);
            studentMain.utilsMenu.getGenderComboBox().setPreferredSize(dimension);
            studentMain.utilsMenu.getSpecializedComboBox().setPreferredSize(dimension);
            studentMain.utilsMenu.getStudentClassComboBox().setPreferredSize(dimension);
            studentMain.utilsMenu.getNameInput().setPreferredSize(dimension);
            studentMain.utilsMenu.getAgeInput().setPreferredSize(dimension);
            System.out.println(studentMain.topMenu.getWidth());
        });

        // 登录控件
        //frame.setSize(350, 300);
        //frame.setResizable(false);

        // 在控件失焦时提供回车登录事件监听
        //frame.addKeyListener(new LoginButtonListener().getKeyListener());

        /*dao.insertStudent(
                "ts",
                17,
                "男",
                "12",
                "123",
                "123",
                "123"
        );*/

        LOGGER.info("Nocl");

    }

    public static void main(String[] args) {
        //LOGGER.debug(dao.getStudentClass("物联网信息技术"));
        SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
                WebLookAndFeel.install();
                LanguageManager.setLanguage(new Language(new Locale("zh")));
                LanguageManager.addDictionary ( new Dictionary(
                        new ClassResource( Main.class, "resources/language.xml" )
                ) );
                initGobalFont(new Font("微软雅黑", Font.PLAIN, 15));

                //frame.setContentPane(new Login().getRoot());
                studentMain = new StudentMain();
                frame.setContentPane(studentMain.InitMainPanel());
                //frame.setExtendedState(JFrame.MAXIMIZED_BOTH);

                frame.setVisible(true);
                System.out.println(studentMain.utilsMenu.getHeight());
                System.out.println(studentMain.utilsMenu.getWidth());

                Dimension dimension = new Dimension(studentMain.utilsMenu.getWidth() / 5, studentMain.utilsMenu.getHeight() / 3);
                studentMain.utilsMenu.getAcademyComboBox().setPreferredSize(dimension);
                studentMain.utilsMenu.getGenderComboBox().setPreferredSize(dimension);
                studentMain.utilsMenu.getSpecializedComboBox().setPreferredSize(dimension);
                studentMain.utilsMenu.getStudentClassComboBox().setPreferredSize(dimension);
                studentMain.utilsMenu.getNameInput().setPreferredSize(dimension);
                studentMain.utilsMenu.getAgeInput().setPreferredSize(dimension);
            }
        });

        // 登录控件
        //frame.setSize(350, 300);
        //frame.setResizable(false);

        // 在控件失焦时提供回车登录事件监听
        //frame.addKeyListener(new LoginButtonListener().getKeyListener());

        /*dao.insertStudent(
                "ts",
                17,
                "男",
                "12",
                "123",
                "123",
                "123"
        );*/

        LOGGER.info("Nocl");
    }

Replace Anonymous With Lambda com.nocl.studentmanager.Main.main.invokeLater.new Runnable with () -> {WebLookAndFeel.install(); in method public main(args String[]) : void from class com.nocl.studentmanager.Main


    private void initPopupMenu() {
        menu = new PopupMenuGenerator();
        menu.setIconSettings ( "resources/icons", ".png" );
        menu.setLanguagePrefix ( "StudentMain.TopMenu.menu" );
        menu.getMenu().setFont(new Font("微软雅黑", Font.BOLD, 15));

        menu.addItem ( "add16", "add", e -> {
            AddStudentInfo addStudentInfo = new AddStudentInfo(Main.frame);
            addStudentInfo.setLocationRelativeTo(Main.frame);
            addStudentInfo.setModal(true);
            addStudentInfo.setVisible(true);
            /*NotificationManager.showNotification ( "StudentMain.TopMenu.menu.add" );*/
        });
    }

    private void initPopupMenu() {
        menu = new PopupMenuGenerator();
        menu.setIconSettings ( "resources/icons", ".png" );
        menu.setLanguagePrefix ( "StudentMain.TopMenu.menu" );
        menu.getMenu().setFont(new Font("微软雅黑", Font.BOLD, 15));

        menu.addItem ( "add16", "add", new ActionListener()
        {
            @Override
            public void actionPerformed ( final ActionEvent e )
            {
                AddStudentInfo addStudentInfo = new AddStudentInfo(Main.frame);
                addStudentInfo.setLocationRelativeTo(Main.frame);
                addStudentInfo.setModal(true);
                addStudentInfo.setVisible(true);
                /*NotificationManager.showNotification ( "StudentMain.TopMenu.menu.add" );*/
            }
        } );
    }

Replace Anonymous With Lambda com.nocl.studentmanager.view.main.layout.TopMenu.initPopupMenu.addItem.new ActionListener with e -> {AddStudentInfo addStudentInfo=new AddStudentInfo(Main.frame); in method private initPopupMenu() : void from class com.nocl.studentmanager.view.main.layout.TopMenu


    public static void main(String[] args) {
        SearcherMain tester;
        try {
            tester = new SearcherMain();
            tester.search("absemt"); // Choose Search Query here. Choose Field below.
        } catch (IOException | ParseException e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        SearcherMain tester;
        try {
            tester = new SearcherMain();
            tester.search("Nokia"); // Choose Search Query here. Choose Field below.
        } catch (IOException e) {
            e.printStackTrace();
        } catch (ParseException e) {
            e.printStackTrace();
        }
    }

Merge Catch [catch(IOException e), catch(ParseException e)] to catch(IOException|ParseException e) in method public main(args String[]) : void from class Searcher.SearcherMain


    @Override
    public Object postProcessAfterInitialization(@NonNull Object bean,
                                                 @NonNull String beanName) {
        if (bean instanceof DataSource dataSource) {
            try (Connection connection = dataSource.getConnection();
                 Statement statement = connection.createStatement()) {
                statement.execute(String.format("CREATE SCHEMA IF NOT EXISTS %s", schemaName));
            } catch (SQLException e) {
                throw new IllegalArgumentException(e);
            }
        }
        return bean;
    }

    @Override
    public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
        if (bean instanceof DataSource) {
            DataSource dataSource = (DataSource) bean;
            try {
                Connection conn = dataSource.getConnection();
                Statement statement = conn.createStatement();
                statement.execute(String.format("CREATE SCHEMA IF NOT EXISTS %s", schemaName));
            } catch (SQLException e) {
                throw new RuntimeException(e);
            }
        }
        return bean;
    }

Try With Resources try(Connection connection=dataSource.getConnection(); Statement statement=connection.createStatement()) in method public postProcessAfterInitialization(bean Object, beanName String) : Object from class ru.magarusik.studenttestingservice.components.SchemaInitializer


    @Override
    public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
        if (bean instanceof DataSource dataSource) {
            try (Connection connection = dataSource.getConnection();
                 Statement statement = connection.createStatement()) {
                statement.execute(String.format("CREATE SCHEMA IF NOT EXISTS %s", schemaName));
            } catch (SQLException e) {
                throw new RuntimeException(e);
            }
        }
        return bean;
    }

Try With Resources try(Connection connection=dataSource.getConnection(); Statement statement=connection.createStatement()) in method public postProcessAfterInitialization(bean Object, beanName String) : Object from class ru.magarusik.studenttestingclient.component.SchemaInitializer


    public void getCapitalsInRegion(String region, StringBuilder output) {
        String strSelect = "SELECT city.Name, city.Population FROM city "
                + "JOIN country ON city.ID = country.Capital "
                + "WHERE country.Region = ? "
                + "ORDER BY city.Population DESC";

        try (PreparedStatement pstmt = con.prepareStatement(strSelect)) {
            // Set the parameter for the region
            pstmt.setString(1, region);

            // Execute the query
            ResultSet rset = pstmt.executeQuery();
            boolean hasResults = false;

            // Iterate through the results and append them to the StringBuilder
            while (rset.next()) {
                hasResults = true;
                String cityName = rset.getString("Name");
                int population = rset.getInt("Population");
                output.append("Capital: " + cityName + " - Population: " + population + "\n");
            }

            // Check if any results were found
            if (!hasResults) {
                System.out.println("No results for region: " + region);
            } else {
                System.out.println("Results found:");
                System.out.println(output.toString());
            }

        } catch (SQLException e) {
            System.out.println("Failed to get population details: " + e.getMessage());
        }
    }

    public void getCapitalsInRegion(String region, StringBuilder output) {
        try {
            ResultSet rset = pstmt.executeQuery();
            while (rset.next()) {
                String cityName = rset.getString("Name");
                int population = rset.getInt("Population");
                output.append("Hauptstadt: " + cityName + " - Bevölkerung: " + population + "\n");
            }
        } catch (SQLException e) {
            System.out.println("Failed to get population details");
        }
    }

Try With Resources try(PreparedStatement pstmt=con.prepareStatement(strSelect)) in method public getCapitalsInRegion(region String, output StringBuilder) : void from class com.napier.sem.ListOfCapitalsInRegion


/**
    *
This method returns an infinite stream all numbers in the Fibonacci Sequence.
    * The stream starts with 0 which is known as the zeroth element in the sequence.
    * The stream is logically truely infinite (will never loop around or overflow)
    * but hardware will eventually run out of memory.

    *
    *
The Fibonacci Sequence aka golden sequence aka Lame's Sequence is defined by starting with
    * f(0)=0 and f(1)=1 and f(n)=f(n-2)+f(n-1).
    * Therefore the sequence starts out with: 0, 1, 1, 2, 3, 5, 8, 13, 21, 34...

    *
    * @return an infinite stream of the Fibonacci Sequence
    */
   public static Stream<MutableInfiniteInteger> streamFibonacciSequence()
   {
      final Iterator<MutableInfiniteInteger> iterator = new Iterator<>()
      {
         private MutableInfiniteInteger previous = null;
         private MutableInfiniteInteger back2 = null;

         @Override
         public boolean hasNext(){return true;}

         @Override
         public MutableInfiniteInteger next()
         {
            final MutableInfiniteInteger next;
            if (previous == null) next = MutableInfiniteInteger.valueOf(0);
            else if (back2 == null) next = MutableInfiniteInteger.valueOf(1);
            else next = previous.copy().add(back2);
            back2 = previous;
            previous = next;
            return next;
         }
      };
      return StreamSupport.stream(Spliterators.spliteratorUnknownSize(iterator, Spliterator.ORDERED | Spliterator.IMMUTABLE), false);
   }

/**
    *
This method returns an infinite stream all numbers in the Fibonacci Sequence.
    * The stream starts with 0 which is known as the zeroth element in the sequence.
    * The stream is logically truely infinite (will never loop around or overflow)
    * but hardware will eventually run out of memory.

    *
    *
The Fibonacci Sequence aka golden sequence aka Lame's Sequence is defined by starting with
    * f(0)=0 and f(1)=1 and f(n)=f(n-2)+f(n-1).
    * Therefore the sequence starts out with: 0, 1, 1, 2, 3, 5, 8, 13, 21, 34...

    *
    * @return an infinite stream of the Fibonacci Sequence
    */
   public static Stream<MutableInfiniteInteger> streamFibonacciSequence()
   {
      final Iterator<MutableInfiniteInteger> iterator = new Iterator<MutableInfiniteInteger>()
      {
         private MutableInfiniteInteger previous = null;
         private MutableInfiniteInteger back2 = null;

         @Override
         public boolean hasNext(){return true;}

         @Override
         public MutableInfiniteInteger next()
         {
            final MutableInfiniteInteger next;
            if (previous == null) next = MutableInfiniteInteger.valueOf(0);
            else if (back2 == null) next = MutableInfiniteInteger.valueOf(1);
            else next = previous.copy().add(back2);
            back2 = previous;
            previous = next;
            return next;
         }
      };
      return StreamSupport.stream(Spliterators.spliteratorUnknownSize(iterator, Spliterator.ORDERED | Spliterator.IMMUTABLE), false);
   }

Replace Generic With Diamond Iterator<MutableInfiniteInteger> with Iterator<> in method public streamFibonacciSequence() : Stream<MutableInfiniteInteger> from class com.github.skySpiral7.java.infinite.numbers.MutableInfiniteInteger


   /**
    * The no-arg construct creates an empty set.
    */
   public IdentityHashSet()
   {
      super();
      dataMap = new IdentityHashMap<>();
   }

   /**
    * The no-arg construct creates an empty set.
    */
   public IdentityHashSet()
   {
      super();
      dataMap = new IdentityHashMap<E, Boolean>();
   }

Replace Generic With Diamond IdentityHashMap<E,Boolean> with IdentityHashMap<> in method public IdentityHashSet() from class com.github.SkySpiral7.Java.dataStructures.IdentityHashSet


   /**
    * Returns an InfiniteInteger whose value is {@code (this + value)}.
    * Note that the formula used is designed for a long and is slightly more efficient
    * than calling add(InfiniteInteger.valueOf(value)) would be.
    *
    * @param value the operand to be added to this InfiniteInteger.
    *
    * @return the result including ±∞ and NaN
    *
    * @see #add(MutableInfiniteInteger)
    */
   @Override
   public MutableInfiniteInteger add(final long value)
   {
      if (!this.isFinite() || value == 0) return this;
      if (this.equals(0)) return set(MutableInfiniteInteger.valueOf(value));
      if (value == Long.MIN_VALUE) return this.add(MutableInfiniteInteger.valueOf(value));  //special case to avoid bug

      //delegations based on the sign of each
      if (!isNegative && value < 0) return this.subtract(Math.abs(value));
      if (isNegative && value > 0) return set(MutableInfiniteInteger.valueOf(value).subtract(this.abs()));

      //the rest is for if both positive or both negative
      long sum, valueRemaining = Math.abs(value);
      ListIterator<DequeNode<Integer>> thisIterator = new DequeNodeIterator.IndexAgnosticDequeIterator<>(this.magnitudeHead);
      DequeNode<Integer> thisCursor = null;
      int lowValue, highValue;
      while (thisIterator.hasNext())
      {
         thisCursor = thisIterator.next();
         //turns out (true for signed and unsigned) max long > max int * max int. (2^64-1) > ((2^32-1)*(2^32-1))
         lowValue = (int) valueRemaining;
         highValue = (int) (valueRemaining >>> 32);
         sum = Integer.toUnsignedLong(thisCursor.getData().intValue()) + Integer.toUnsignedLong(lowValue);

         thisCursor.setData((int) sum);
         sum >>>= 32;

         valueRemaining = sum + Integer.toUnsignedLong(highValue);  //TODO: make a test that proves I need to use unsigned
      }
      if (valueRemaining != 0)
      {
         //the addition's carry causes the return value to have more nodes
         lowValue = (int) valueRemaining;
         highValue = (int) (valueRemaining >>> 32);
         thisCursor = DequeNode.Factory.createNodeAfter(thisCursor, lowValue);
         thisCursor = DequeNode.Factory.createNodeAfter(thisCursor, highValue);
      }
      if (thisCursor.getData().intValue() == 0) thisCursor.remove();  //remove the last node since it is a leading 0
      //do not use else. this can occur either way
      //isNegative is already correct for positive or negative
      return this;
   }

   /**
    * Returns an InfiniteInteger whose value is {@code (this + value)}.
    * Note that the formula used is designed for a long and is slightly more efficient
    * than calling add(InfiniteInteger.valueOf(value)) would be.
    *
    * @param value the operand to be added to this InfiniteInteger.
    *
    * @return the result including ±∞ and NaN
    *
    * @see #add(MutableInfiniteInteger)
    */
   @Override
   public MutableInfiniteInteger add(final long value)
   {
      if (!this.isFinite() || value == 0) return this;
      if (this.equals(0)) return set(MutableInfiniteInteger.valueOf(value));
      if (value == Long.MIN_VALUE) return this.add(MutableInfiniteInteger.valueOf(value));  //special case to avoid bug

      //delegations based on the sign of each
      if (!isNegative && value < 0) return this.subtract(Math.abs(value));
      if (isNegative && value > 0) return set(MutableInfiniteInteger.valueOf(value).subtract(this.abs()));

      //the rest is for if both positive or both negative
      long sum, valueRemaining = Math.abs(value);
      ListIterator<DequeNode<Integer>> thisIterator = new DequeNodeIterator.IndexAgnosticDequeIterator<Integer>(this.magnitudeHead);
      DequeNode<Integer> thisCursor = null;
      int lowValue, highValue;
      while (thisIterator.hasNext())
      {
         thisCursor = thisIterator.next();
         //turns out (true for signed and unsigned) max long > max int * max int. (2^64-1) > ((2^32-1)*(2^32-1))
         lowValue = (int) valueRemaining;
         highValue = (int) (valueRemaining >>> 32);
         sum = Integer.toUnsignedLong(thisCursor.getData().intValue()) + Integer.toUnsignedLong(lowValue);

         thisCursor.setData((int) sum);
         sum >>>= 32;

         valueRemaining = sum + Integer.toUnsignedLong(highValue);  //TODO: make a test that proves I need to use unsigned
      }
      if (valueRemaining != 0)
      {
         //the addition's carry causes the return value to have more nodes
         lowValue = (int) valueRemaining;
         highValue = (int) (valueRemaining >>> 32);
         thisCursor = DequeNode.Factory.createNodeAfter(thisCursor, lowValue);
         thisCursor = DequeNode.Factory.createNodeAfter(thisCursor, highValue);
      }
      if (thisCursor.getData().intValue() == 0) thisCursor.remove();  //remove the last node since it is a leading 0
      //do not use else. this can occur either way
      //isNegative is already correct for positive or negative
      return this;
   }

Replace Generic With Diamond DequeNodeIterator.IndexAgnosticDequeIterator<Integer> with DequeNodeIterator.IndexAgnosticDequeIterator<> in method public add(value long) : MutableInfiniteInteger from class com.github.SkySpiral7.Java.numbers.MutableInfiniteInteger


   /**
    * Returns an InfiniteInteger whose value is {@code (this - value)}.
    * Note that the formula used is designed for a long and is slightly more efficient
    * than calling subtract(InfiniteInteger.valueOf(value)) would be.
    *
    * @param value the operand to be subtracted from this InfiniteInteger.
    *
    * @return the result including ±∞ and NaN
    *
    * @see #subtract(MutableInfiniteInteger)
    */
   @Override
   public MutableInfiniteInteger subtract(final long value)
   {
      if (!this.isFinite() || value == 0) return this;
      if (value == Long.MIN_VALUE) return this.add(MutableInfiniteInteger.valueOf(value).abs());  //special case to avoid bug
      if (this.equals(0)) return set(MutableInfiniteInteger.valueOf(-value));

      //delegations based on the sign of each
      if (!isNegative && value < 0) return this.add(Math.abs(value));
      if (isNegative && value > 0) return set(this.abs().add(value).negate());
      if (isNegative && value < 0) return set(MutableInfiniteInteger.valueOf(Math.abs(value)).subtract(this.abs()));

      //the rest is for if both positive
      if (this.equals(value)) return set(new MutableInfiniteInteger(0));
      if (is(this, LESS_THAN, MutableInfiniteInteger.valueOf(value)))
         return set(MutableInfiniteInteger.valueOf(value).subtract(this).negate());

      //this is greater than value
      long difference, valueRemaining = value;
      final ListIterator<DequeNode<Integer>> thisIterator = new DequeNodeIterator.IndexAgnosticDequeIterator<>(this.magnitudeHead);
      DequeNode<Integer> thisCursor = null;
      int lowValue, highValue;
      boolean borrow = false;
      while (thisIterator.hasNext())
      {
         thisCursor = thisIterator.next();
         lowValue = (int) valueRemaining;
         highValue = (int) (valueRemaining >>> 32);
         difference = Integer.toUnsignedLong(thisCursor.getData().intValue()) - Integer.toUnsignedLong(lowValue);
         //Long.min is not possible so there's no bug to check
         borrow = (difference < 0);
         if (borrow) difference += Integer.toUnsignedLong((int) BitWiseUtil.HIGH_64) + 1;  //add max unsigned int +1
         //this makes difference borrow
         //the +1 is here for the same reason that when borrowing in base 10 you add 10 instead of 9

         thisCursor.setData((int) difference);
         //assert((difference >>> 32) == 0);  //due to the borrowing above

         valueRemaining = Integer.toUnsignedLong(highValue);
         if (borrow) valueRemaining++;  //subtract 1 more
      }
      //assert(valueRemaining == 0);  //because this > value
      //TODO: isn't there always a leading 0?
      if (thisCursor.getData().intValue() == 0)
      {
         thisCursor = thisCursor.getPrev();
         thisCursor.getNext().remove();
      }
      //remove the last node since it is a leading 0
      if (thisCursor.getData().intValue() == 0) thisCursor.remove();  //there will be 2 leading 0s if the last node was borrowed down to 0

      return this;
   }

   /**
    * Returns an InfiniteInteger whose value is {@code (this - value)}.
    * Note that the formula used is designed for a long and is slightly more efficient
    * than calling subtract(InfiniteInteger.valueOf(value)) would be.
    *
    * @param value the operand to be subtracted from this InfiniteInteger.
    *
    * @return the result including ±∞ and NaN
    *
    * @see #subtract(MutableInfiniteInteger)
    */
   @Override
   public MutableInfiniteInteger subtract(final long value)
   {
      if (!this.isFinite() || value == 0) return this;
      if (value == Long.MIN_VALUE) return this.add(MutableInfiniteInteger.valueOf(value).abs());  //special case to avoid bug
      if (this.equals(0)) return set(MutableInfiniteInteger.valueOf(-value));

      //delegations based on the sign of each
      if (!isNegative && value < 0) return this.add(Math.abs(value));
      if (isNegative && value > 0) return set(this.abs().add(value).negate());
      if (isNegative && value < 0) return set(MutableInfiniteInteger.valueOf(Math.abs(value)).subtract(this.abs()));

      //the rest is for if both positive
      if (this.equals(value)) return set(new MutableInfiniteInteger(0));
      if (is(this, LESS_THAN, MutableInfiniteInteger.valueOf(value)))
         return set(MutableInfiniteInteger.valueOf(value).subtract(this).negate());

      //this is greater than value
      long difference, valueRemaining = value;
      final ListIterator<DequeNode<Integer>> thisIterator = new DequeNodeIterator.IndexAgnosticDequeIterator<Integer>(this.magnitudeHead);
      DequeNode<Integer> thisCursor = null;
      int lowValue, highValue;
      boolean borrow = false;
      while (thisIterator.hasNext())
      {
         thisCursor = thisIterator.next();
         lowValue = (int) valueRemaining;
         highValue = (int) (valueRemaining >>> 32);
         difference = Integer.toUnsignedLong(thisCursor.getData().intValue()) - Integer.toUnsignedLong(lowValue);
         //Long.min is not possible so there's no bug to check
         borrow = (difference < 0);
         if (borrow) difference += Integer.toUnsignedLong((int) BitWiseUtil.HIGH_64) + 1;  //add max unsigned int +1
         //this makes difference borrow
         //the +1 is here for the same reason that when borrowing in base 10 you add 10 instead of 9

         thisCursor.setData((int) difference);
         //assert((difference >>> 32) == 0);  //due to the borrowing above

         valueRemaining = Integer.toUnsignedLong(highValue);
         if (borrow) valueRemaining++;  //subtract 1 more
      }
      //assert(valueRemaining == 0);  //because this > value
      //TODO: isn't there always a leading 0?
      if (thisCursor.getData().intValue() == 0)
      {
         thisCursor = thisCursor.getPrev();
         thisCursor.getNext().remove();
      }
      //remove the last node since it is a leading 0
      if (thisCursor.getData().intValue() == 0) thisCursor.remove();  //there will be 2 leading 0s if the last node was borrowed down to 0

      return this;
   }

Replace Generic With Diamond DequeNodeIterator.IndexAgnosticDequeIterator<Integer> with DequeNodeIterator.IndexAgnosticDequeIterator<> in method public subtract(value long) : MutableInfiniteInteger from class com.github.SkySpiral7.Java.numbers.MutableInfiniteInteger


   /**
    * This method returns a read only list iterator of unknown size that iterates over the data of each of the nodes
    * of this InfiniteInteger. Each node is unsigned and they are in little endian order.
    * Calling nextIndex or previousIndex will return -1 and calling add, set, or remove will throw.
    * Note that there might be more than Long.Max elements (or even max BigInteger!).
    *
    * @throws UnsupportedOperationException if this is ±∞ or NaN
    * @see #magnitudeStream()
    * @see ReadOnlyListIterator
    * @see DequeNodeIterator.IndexAgnosticValueIterator
    */
   @Override
   public ReadOnlyListIterator<Integer> magnitudeIterator()
   {
      if (!this.isFinite()) throw new UnsupportedOperationException(this.toString() + " does not have nodes.");
      return new ReadOnlyListIterator<>(new DequeNodeIterator.IndexAgnosticValueIterator<>(magnitudeHead));
   }

   /**
    * This method returns a read only list iterator of unknown size that iterates over the data of each of the nodes
    * of this InfiniteInteger. Each node is unsigned and they are in little endian order.
    * Calling nextIndex or previousIndex will return -1 and calling add, set, or remove will throw.
    * Note that there might be more than Long.Max elements (or even max BigInteger!).
    *
    * @throws UnsupportedOperationException if this is ±∞ or NaN
    * @see #magnitudeStream()
    * @see ReadOnlyListIterator
    * @see DequeNodeIterator.IndexAgnosticValueIterator
    */
   @Override
   public ReadOnlyListIterator<Integer> magnitudeIterator()
   {
      if (!this.isFinite()) throw new UnsupportedOperationException(this.toString() + " does not have nodes.");
      return new ReadOnlyListIterator<Integer>(new DequeNodeIterator.IndexAgnosticValueIterator<Integer>(magnitudeHead));
   }

Replace Generic With Diamond ReadOnlyListIterator<Integer> with ReadOnlyListIterator<> in method public magnitudeIterator() : ReadOnlyListIterator<Integer> from class com.github.SkySpiral7.Java.numbers.MutableInfiniteInteger


/**
    *
Left difference of 2 sets is the set of elements that are in left that are not in right.
    * This is also known subtract and left outer join.

    *
    *
If left contains elements [A, B] and right contains [B, C] then the left difference
    * is [A]. You can also say left minus right or right subtracted from left.

    *
    *
The order of the parameters is important and they must be parameterized to contain the same class.
    * Note that leftDifference(left, right) is the same as rightDifference(right, left).

    *
    *
As a simple Ascii Venn diagram: (A {B) C} returns A

    *
    * @param left
    *       start with this set
    * @param right
    *       and remove these elements
    * @return a set of the elements that only exist in left
    *
    * @throws IllegalArgumentException
    *       if either parameter is null
    */
   public static <E> Set<E> leftDifference(Collection<? extends E> left, Collection<? extends E> right)
   {
      if (left == null) throw new IllegalArgumentException("Parameter left can't be null.");
      if (right == null) throw new IllegalArgumentException("Parameter right can't be null.");
      Set<E> result = new HashSet<>(left);
      result.removeAll(right);
      return result;
   }

/**
    *
Left difference of 2 sets is the set of elements that are in left that are not in right.
    * This is also known subtract and left outer join.

    *
    *
If left contains elements [A, B] and right contains [B, C] then the left difference
    * is [A]. You can also say left minus right or right subtracted from left.

    *
    *
The order of the parameters is important and they must be parameterized to contain the same class.
    * Note that leftDifference(left, right) is the same as rightDifference(right, left).

    *
    *
As a simple Ascii Venn diagram: (A {B) C} returns A

    *
    * @param left
    *       start with this set
    * @param right
    *       and remove these elements
    * @return a set of the elements that only exist in left
    *
    * @throws IllegalArgumentException
    *       if either parameter is null
    */
   public static <E> Set<E> leftDifference(Collection<? extends E> left, Collection<? extends E> right)
   {
      if (left == null) throw new IllegalArgumentException("Parameter left can't be null.");
      if (right == null) throw new IllegalArgumentException("Parameter right can't be null.");
      Set<E> result = new HashSet<E>(left);
      result.removeAll(right);
      return result;
   }

Replace Generic With Diamond HashSet<E> with HashSet<> in method public leftDifference(left Collection<? extends E>, right Collection<? extends E>) : Set<E> from class com.github.SkySpiral7.Java.util.BasicSetTheory


	/**
	 * This method opens the file, writes (which may create it), then closes the file.
	 * Therefore it is inefficient to call this more than once when appending.
	 *
	 * @param targetFile
	 *           writes to this file
	 * @param newContents
	 *           the string contents to be written
	 * @param encoding
	 *           the character encoding to write to the file in
	 * @param willAppend
	 *           true if the current file contents should be kept
	 * @throws RuntimeException
	 *            of FileNotFoundException or IOException
	 */
	public static void writeToFile(final File targetFile, final String newContents, final Charset encoding,
			final boolean willAppend)
	{
		if (targetFile.isDirectory()) throw new IllegalArgumentException("It is not possible to write to a directory");
		Objects.requireNonNull(newContents);

		try (final Writer writer = new BufferedWriter(new OutputStreamWriter(
				new FileOutputStream(targetFile, willAppend), encoding));)
		{
			// might create the file
			writer.write(newContents);
		}
		catch (final IOException e)
		{
			throw new RuntimeException(e);
		}
	}

	/**
	 * This method opens the file, writes (which may create it), then closes the file.
	 * Therefore it is inefficient to call this more than once.
	 *
	 * @param targetFile
	 *           writes to this file
	 * @param newContents
	 *           the string contents to be written
	 * @param encoding
	 *           the character encoding to write to the file in
	 * @param willAppend
	 *           true if the current file contents should be kept
	 * @throws RuntimeException
	 *            of FileNotFoundException or IOException
	 */
	public static void writeToFile(final File targetFile, final String newContents, final Charset encoding,
			final boolean willAppend)
	{
		if (targetFile.isDirectory()) throw new IllegalArgumentException("It is not possible to write to a directory");
		Objects.requireNonNull(newContents);
		try
		{
			// might create the file
			final Writer writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(targetFile, willAppend),
					encoding));
			writer.write(newContents);
			writer.close();
		}
		catch (final Exception e)
		{
			throw new RuntimeException(e);
		}
	}

Try With Resources try(final Writer writer=new BufferedWriter(new OutputStreamWriter(new FileOutputStream(targetFile,willAppend),encoding))) in method public writeToFile(targetFile File, newContents String, encoding Charset, willAppend boolean) : void from class com.github.SkySpiral7.Java.util.FileIoUtil


	/**
	 * This method reads the entire file and loads it into a string.
	 * This is obviously bad for performance.
	 *
	 * @param targetFile
	 *           the file to be read
	 * @param encoding
	 *           the character encoding to read the file with
	 * @return the entire file contents
	 * @throws RuntimeException
	 *            of FileNotFoundException or IOException
	 * @throws IllegalArgumentException
	 *            if the file is a directory or if the file doesn't exist
	 * @throws IllegalArgumentException
	 *            if the file is larger than a string can hold. The size is estimated however this method shouldn't be
	 *            used for files anywhere near the limit.
	 */
	public static String readTextFile(final File targetFile, final Charset encoding)
	{
		if (targetFile.isDirectory()) throw new IllegalArgumentException(
				"It is not possible to read file contents of a directory");
		if (!targetFile.exists()) throw new IllegalArgumentException("File doesn't exist");

		//this is only an estimate since character size is not always 1 byte
		if (targetFile.length() > Integer.MAX_VALUE) throw new IllegalArgumentException(
				"File too large to fit into a string");
		//for completeness I could count the number of characters read and throw but it's better to have this hedge

		final StringBuilder returnValue = new StringBuilder();
		try (final Reader reader = new BufferedReader(new InputStreamReader(new FileInputStream(
				targetFile.getAbsolutePath()), encoding));)
		{
			while (true)
			{
				final int charRead = reader.read();
				if (-1 == charRead) break;  // if end of file
				returnValue.append((char) charRead);
			}
		}
		catch (final Exception e)
		{
			throw new RuntimeException(e);
		}
		return returnValue.toString();
	}

	/**
	 * This method reads the entire file and loads it into a string.
	 * This is obviously bad for performance.
	 *
	 * @param targetFile
	 *           the file to be read
	 * @param encoding
	 *           the character encoding to read the file with
	 * @return the entire file contents
	 * @throws RuntimeException
	 *            of FileNotFoundException or IOException
	 * @throws IllegalArgumentException
	 *            if the file is a directory or if the file doesn't exist
	 * @throws IllegalArgumentException
	 *            if the file is larger than a string can hold. The size is estimated however this method shouldn't be
	 *            used for files anywhere near the limit.
	 */
	public static String readFromFileAsString(final File targetFile, final Charset encoding)
	{
		if (targetFile.isDirectory()) throw new IllegalArgumentException(
				"It is not possible to read file contents of a directory");
		if (!targetFile.exists()) throw new IllegalArgumentException("File doesn't exist");

		//this is only an estimate since character size is not always 1 byte
		if (targetFile.length() > Integer.MAX_VALUE) throw new IllegalArgumentException(
				"File too large to fit into a string");
		//for completeness I could count the number of characters read and throw but it's better to have this hedge

		final StringBuilder returnValue = new StringBuilder();
		Reader reader;
		try
		{
			reader = new BufferedReader(new InputStreamReader(new FileInputStream(targetFile.getAbsolutePath()), encoding));
			while (true)
			{
				final int charRead = reader.read();
				if (-1 == charRead) break;  // if end of file
				returnValue.append((char) charRead);
			}
			reader.close();
		}
		catch (final Exception e)
		{
			throw new RuntimeException(e);
		}
		return returnValue.toString();
	}

Try With Resources try(final Reader reader=new BufferedReader(new InputStreamReader(new FileInputStream(targetFile.getAbsolutePath()),encoding))) in method public readTextFile(targetFile File, encoding Charset) : String from class com.github.SkySpiral7.Java.util.FileIoUtil


    private void save() {
        try (BufferedWriter writer = new BufferedWriter(new FileWriter(csvFile))) {
            writer.write(String.join(",", headers.keySet()));
            writer.newLine();

            for (User user : accounts.values()) {
                String line = "%s,%s,%s,%s".formatted(
                        user.getUserEmail(), user.getUserName(), user.getUserPassword(), user.getCreatedAt());
                writer.write(line);
                writer.newLine();
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    private void save() {
        BufferedWriter writer;
        try {
            writer = new BufferedWriter(new FileWriter(csvFile));
            writer.write(String.join(",", headers.keySet()));
            writer.newLine();

            for (User user : accounts.values()) {
                String line = "%s,%s,%s,%s".formatted(
                        user.getUserEmail(), user.getUserName(), user.getUserPassword(), user.getCreatedAt());
                writer.write(line);
                writer.newLine();
            }

            writer.close();

        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

Try With Resources try(BufferedWriter writer=new BufferedWriter(new FileWriter(csvFile))) in method private save() : void from class frameworks.data_access.CSVDataAccessObject


    public void createLecture(DMLService dml, String title, String lecturer, String category) throws SQLException {
        final HashMap<String, Object> dataMap = new HashMap<>();

        dataMap.put("TITLE", title);
        dataMap.put("LECTURER", lecturer);
        dataMap.put("CATEGORY" , category);

        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm");
        String regDate = LocalDateTime.now().format(formatter);

        dataMap.put("REG_DATE" , regDate);

        dml.insertLecture(dataMap);
    }

    public void createLecture(DMLService dml, String title, String lecturer, String category) throws SQLException {
        final HashMap<String, Object> dataMap = new HashMap<String, Object>();

        dataMap.put("TITLE", title);
        dataMap.put("LECTURER", lecturer);
        dataMap.put("CATEGORY" , category);

        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm");
        String regDate = LocalDateTime.now().format(formatter);

        dataMap.put("REG_DATE" , regDate);

        dml.insertLecture(dataMap);
    }

Replace Generic With Diamond HashMap<String,Object> with HashMap<> in method public createLecture(dml DMLService, title String, lecturer String, category String) : void from class org.example.controllers.LectureController


    public void createUser(DMLService dml, String email, String password, String name) throws SQLException {
        final HashMap<String, Object> dataMap = new HashMap<>();

        dataMap.put("NAME", name);
        dataMap.put("EMAIL", email);
        dataMap.put("PASSWORD" , password);

        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm");
        String regDate = LocalDateTime.now().format(formatter);

        dataMap.put("RECENT_LOGIN_DATE" , regDate);
        dataMap.put("REG_DATE" , regDate);

        dml.insertPerson(dataMap);
    }

    public void createUser(DMLService dml, String email, String password, String name) throws SQLException {
        final HashMap<String, Object> dataMap = new HashMap<String, Object>();

        dataMap.put("NAME", name);
        dataMap.put("EMAIL", email);
        dataMap.put("PASSWORD" , password);

        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm");
        String regDate = LocalDateTime.now().format(formatter);

        dataMap.put("RECENT_LOGIN_DATE" , regDate);
        dataMap.put("REG_DATE" , regDate);

        dml.insertPerson(dataMap);
    }

Replace Generic With Diamond HashMap<String,Object> with HashMap<> in method public createUser(dml DMLService, email String, password String, name String) : void from class org.example.controllers.UserController


    /**
     * Validates the command Parameters args before execution using the defined
     * schema.
     *
     * @param args the parameters (arguments) to validate using this command's
     *             schema.
     * @return a list ValidationResults or an empty list (if no schema is set).
     * @see Parameters
     * @see ValidationResult
     */
    @Override
    public List<ValidationResult> validate(Parameters args) {
        if (_schema != null)
            return _schema.validate(args);

        return new ArrayList<>();
    }

    /**
     * Validates the command Parameters args before execution using the defined
     * schema.
     *
     * @param args the parameters (arguments) to validate using this command's
     *             schema.
     * @return a list ValidationResults or an empty list (if no schema is set).
     * @see Parameters
     * @see ValidationResult
     */
    @Override
    public List<ValidationResult> validate(Parameters args) {
        if (_schema != null)
            return _schema.validate(args);

        return new ArrayList<ValidationResult>();
    }

Replace Generic With Diamond ArrayList<ValidationResult> with ArrayList<> in method public validate(args Parameters) : List<ValidationResult> from class org.pipservices3.commons.commands.Command


	/**
	 * Validates Parameters args for command specified by its name using defined
	 * schema. If validation schema is not defined than the methods returns no
	 * errors. It returns validation error if the command is not found.
	 *
	 * @param commandName the name of the command for which the 'args' must be
	 *                    validated.
	 * @param args        the parameters (arguments) to validate.
	 * @return an array of ValidationResults. If no command is found by the given
	 *          name, then the returned array of ValidationResults will contain a
	 *          single entry, whose type will be ValidationResultType.Error.
	 *
	 * @see Command
	 * @see Parameters
	 * @see ValidationResult
	 */
	public List<ValidationResult> validate(String commandName, Parameters args) {
		ICommand cref = findCommand(commandName);
		if (cref == null) {
			List<ValidationResult> results = new ArrayList<>();
			results.add(new ValidationResult(null, ValidationResultType.Error, "CMD_NOT_FOUND",
					"Requested command does not exist", null, null));
			return results;
		}
		return cref.validate(args);
	}

	/**
	 * Validates Parameters args for command specified by its name using defined
	 * schema. If validation schema is not defined than the methods returns no
	 * errors. It returns validation error if the command is not found.
	 *
	 * @param commandName the name of the command for which the 'args' must be
	 *                    validated.
	 * @param args        the parameters (arguments) to validate.
	 * @return an array of ValidationResults. If no command is found by the given
	 *          name, then the returned array of ValidationResults will contain a
	 *          single entry, whose type will be ValidationResultType.Error.
	 *
	 * @see Command
	 * @see Parameters
	 * @see ValidationResult
	 */
	public List<ValidationResult> validate(String commandName, Parameters args) {
		ICommand cref = findCommand(commandName);
		if (cref == null) {
			List<ValidationResult> results = new ArrayList<ValidationResult>();
			results.add(new ValidationResult(null, ValidationResultType.Error, "CMD_NOT_FOUND",
					"Requested command does not exist", null, null));
			return results;
		}
		return cref.validate(args);
	}

Replace Generic With Diamond ArrayList<ValidationResult> with ArrayList<> in method public validate(commandName String, args Parameters) : List<ValidationResult> from class org.pipservices3.commons.commands.CommandSet


    /**
     * Converts value into array object with empty array as default. Strings with
     * comma-delimited values are split into array of strings.
     *
     * @param value the list to convert.
     * @return array object or empty array when value is null
     * @see ArrayConverter#toArray(Object)
     */
    public static List<Object> listToArray(Object value) {
        if (value == null)
            return new ArrayList<>();
        if (value instanceof String)
            value = ((String) value).split(",");
        return ArrayConverter.toArray(value);
    }

    /**
     * Converts value into array object with empty array as default. Strings with
     * comma-delimited values are split into array of strings.
     *
     * @param value the list to convert.
     * @return array object or empty array when value is null
     * @see ArrayConverter#toArray(Object)
     */
    public static List<Object> listToArray(Object value) {
        if (value == null)
            return new ArrayList<Object>();
        if (value instanceof String)
            value = ((String) value).split(",");
        return ArrayConverter.toArray(value);
    }

Replace Generic With Diamond ArrayList<Object> with ArrayList<> in method public listToArray(value Object) : List<Object> from class org.pipservices3.commons.convert.ArrayConverter


    private static Map<String, Object> listToMap(Collection<Object> list) {
        Map<String, Object> result = new HashMap<>();
        int index = 0;
        for (Object item : list) {
            result.put(Integer.toString(index), item);
            index++;
        }
        return result;
    }

    private static Map<String, Object> listToMap(Collection<Object> list) {
        Map<String, Object> result = new HashMap<String, Object>();
        int index = 0;
        for (Object item : list) {
            result.put(Integer.toString(index), item);
            index++;
        }
        return result;
    }

Replace Generic With Diamond HashMap<String,Object> with HashMap<> in method private listToMap(list Collection<Object>) : Map<String,Object> from class org.pipservices3.commons.convert.MapConverter


    private static Map<String, Object> arrayToMap(Object[] array) {
        Map<String, Object> result = new HashMap<>();
        int index = 0;
        for (Object item : array) {
            result.put(Integer.toString(index), item);
            index++;
        }
        return result;
    }

    private static Map<String, Object> arrayToMap(Object[] array) {
        Map<String, Object> result = new HashMap<String, Object>();
        int index = 0;
        for (Object item : array) {
            result.put(Integer.toString(index), item);
            index++;
        }
        return result;
    }

Replace Generic With Diamond HashMap<String,Object> with HashMap<> in method private arrayToMap(array Object[]) : Map<String,Object> from class org.pipservices3.commons.convert.MapConverter


    private static Map<String, Object> mapToMap(Map<Object, Object> map) {
        Map<String, Object> result = new HashMap<>();
        for (Map.Entry<Object, Object> entry : map.entrySet()) {
            result.put(StringConverter.toString(entry.getKey()), entry.getValue());
        }
        return result;
    }

    private static Map<String, Object> mapToMap(Map<Object, Object> map) {
        Map<String, Object> result = new HashMap<String, Object>();
        for (Map.Entry<Object, Object> entry : map.entrySet()) {
            result.put(StringConverter.toString(entry.getKey()), entry.getValue());
        }
        return result;
    }

Replace Generic With Diamond HashMap<String,Object> with HashMap<> in method private mapToMap(map Map<Object,Object>) : Map<String,Object> from class org.pipservices3.commons.convert.MapConverter


    private static List<Object> listToMap(Collection<Object> list) {
        List<Object> result = new ArrayList<>();
        for (Object item : list)
            result.add(valueToMap(item));
        return result;
    }

    private static List<Object> listToMap(Collection<Object> list) {
        List<Object> result = new ArrayList<Object>();
        for (Object item : list)
            result.add(valueToMap(item));
        return result;
    }

Replace Generic With Diamond ArrayList<Object> with ArrayList<> in method private listToMap(list Collection<Object>) : List<Object> from class org.pipservices3.commons.convert.RecursiveMapConverter


    private static List<Object> arrayToMap(Object[] array) {
        List<Object> result = new ArrayList<>();
        for (Object item : array)
            result.add(valueToMap(item));
        return result;
    }

    private static List<Object> arrayToMap(Object[] array) {
        List<Object> result = new ArrayList<Object>();
        for (Object item : array)
            result.add(valueToMap(item));
        return result;
    }

Replace Generic With Diamond ArrayList<Object> with ArrayList<> in method private arrayToMap(array Object[]) : List<Object> from class org.pipservices3.commons.convert.RecursiveMapConverter