protected AttackResult injectableQuery(String login_count, String accountName) {
        String queryString = "SELECT * From user_data WHERE Login_Count = ? and userid= " + accountName;
        try (Connection connection = dataSource.getConnection()) {
            PreparedStatement query = connection.prepareStatement(queryString, ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);

            int count = 0;
            try {
                count = Integer.parseInt(login_count);
            } catch (Exception e) {
                return trackProgress(failed().output("Could not parse: " + login_count + " to a number" +
                        "
 Your query was: " + queryString.replace("?", login_count)).build());
            }

            query.setInt(1, count);
            //String query = "SELECT * FROM user_data WHERE Login_Count = " + login_count + " and userid = " + accountName, ;
            try {
                ResultSet results = query.executeQuery();

                if ((results != null) && (results.first() == true)) {
                    ResultSetMetaData resultsMetaData = results.getMetaData();
                    StringBuffer output = new StringBuffer();

                    output.append(SqlInjectionLesson5a.writeTable(results, resultsMetaData));
                    results.last();

                    // If they get back more than one user they succeeded
                    if (results.getRow() >= 6) {
                        return trackProgress(success().feedback("sql-injection.5b.success").output("Your query was: " + queryString.replace("?", login_count)).feedbackArgs(output.toString()).build());
                    } else {
                        return trackProgress(failed().output(output.toString() + "
 Your query was: " + queryString.replace("?", login_count)).build());
                    }

                } else {
                    return trackProgress(failed().feedback("sql-injection.5b.no.results").output("Your query was: " + queryString.replace("?", login_count)).build());

//                    output.append(getLabelManager().get("NoResultsMatched"));
                }
            } catch (SQLException sqle) {

                return trackProgress(failed().output(sqle.getMessage() + "
 Your query was: " + queryString.replace("?", login_count)).build());
            }
        } catch (Exception e) {
            return trackProgress(failed().output(this.getClass().getName() + " : " + e.getMessage() + "
 Your query was: " + queryString.replace("?", login_count)).build());
        }
    }

protected AttackResult injectableQuery(String login_count, String accountName) {
    String queryString = "SELECT * From user_data WHERE Login_Count = ? and userid= " + accountName;
    try {
      Connection connection = DatabaseUtilities.getConnection(getWebSession());
      PreparedStatement query = connection.prepareStatement(queryString, ResultSet.TYPE_SCROLL_INSENSITIVE,
              ResultSet.CONCUR_READ_ONLY);

      int count = 0;
      try {
        count = Integer.parseInt(login_count);
      } catch(Exception e) {
        return trackProgress(failed().output("Could not parse: " + login_count + " to a number" +
                "
 Your query was: " + queryString.replace("?", login_count)).build());
      }

      query.setInt(1, count);
      //String query = "SELECT * FROM user_data WHERE Login_Count = " + login_count + " and userid = " + accountName, ;
      try {
        Statement statement = connection.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,
                ResultSet.CONCUR_READ_ONLY);
        ResultSet results = query.executeQuery();

        if ((results != null) && (results.first() == true)) {
          ResultSetMetaData resultsMetaData = results.getMetaData();
          StringBuffer output = new StringBuffer();

          output.append(SqlInjectionLesson5a.writeTable(results, resultsMetaData));
          results.last();

          // If they get back more than one user they succeeded
          if (results.getRow() >= 6) {
            return trackProgress(success().feedback("sql-injection.5b.success").output("Your query was: " + queryString.replace("?", login_count)).feedbackArgs(output.toString()).build());
          } else {
            return trackProgress(failed().output(output.toString() + "
 Your query was: " + queryString.replace("?", login_count)).build());
          }

        } else {
          return trackProgress(failed().feedback("sql-injection.5b.no.results").output("Your query was: " + queryString.replace("?", login_count)).build());

//                    output.append(getLabelManager().get("NoResultsMatched"));
        }
      } catch (SQLException sqle) {

        return trackProgress(failed().output(sqle.getMessage() + "
 Your query was: " + queryString.replace("?", login_count)).build());
      }
    } catch (Exception e) {
      return trackProgress(failed().output(this.getClass().getName() + " : " + e.getMessage() + "
 Your query was: " + queryString.replace("?", login_count)).build());
    }
  }

Try With Resources try(Connection connection=dataSource.getConnection()) in method protected injectableQuery(login_count String, accountName String) : AttackResult from class org.owasp.webgoat.sql_injection.introduction.SqlInjectionLesson5b


protected AttackResult injectableQueryConfidentiality(String name, String auth_tan) {
        StringBuffer output = new StringBuffer();
        String query = "SELECT * FROM employees WHERE last_name = '" + name + "' AND auth_tan = '" + auth_tan + "'";

        try (Connection connection = dataSource.getConnection()) {
            try {
                Statement statement = connection.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_UPDATABLE);
                log(connection, query);
                ResultSet results = statement.executeQuery(query);

                if (results.getStatement() != null) {
                    if (results.first()) {
                        output.append(generateTable(results));
                        results.last();

                        if (results.getRow() > 1) {
                            // more than one record, the user succeeded
                            return trackProgress(success().feedback("sql-injection.8.success").output(output.toString()).build());
                        } else {
                            // only one record
                            return trackProgress(failed().feedback("sql-injection.8.one").output(output.toString()).build());
                        }

                    } else {
                        // no results
                        return trackProgress(failed().feedback("sql-injection.8.no.results").build());
                    }
                } else {
                    return trackProgress(failed().feedback("sql-injection.error").build());
                }
            } catch (SQLException e) {
                return trackProgress(failed().feedback("sql-injection.error").output("
" + e.getMessage() + "").build());
            }

        } catch (Exception e) {
            return trackProgress(failed().feedback("sql-injection.error").output("
" + e.getMessage() + "").build());
        }
    }

protected AttackResult injectableQueryConfidentiality(String name, String auth_tan) {
        StringBuffer output = new StringBuffer();
        String query = "SELECT * FROM employees WHERE last_name = '" + name + "' AND auth_tan = '" + auth_tan + "'";

        try {
            Connection connection = DatabaseUtilities.getConnection(getWebSession());

            try {
                Statement statement = connection.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
                log(connection, query);
                ResultSet results = statement.executeQuery(query);

                if (results.getStatement() != null) {
                    if (results.first()) {
                        output.append(generateTable(results));
                        results.last();

                        if (results.getRow() > 1) {
                            // more than one record, the user succeeded
                            return trackProgress(success().feedback("sql-injection.8.success").output(output.toString()).build());
                        } else {
                            // only one record
                            return trackProgress(failed().feedback("sql-injection.8.one").output(output.toString()).build());
                        }

                    } else {
                        // no results
                        return trackProgress(failed().feedback("sql-injection.8.no.results").build());
                    }
                } else {
                    return trackProgress(failed().feedback("sql-injection.error").build());
                }
            } catch (SQLException e) {
                return trackProgress(failed().feedback("sql-injection.error").output("
" + e.getMessage() + "").build());
            }

        } catch (Exception e) {
            return trackProgress(failed().feedback("sql-injection.error").output("
" + e.getMessage() + "").build());
        }
    }

Try With Resources try(Connection connection=dataSource.getConnection()) in method protected injectableQueryConfidentiality(name String, auth_tan String) : AttackResult from class org.owasp.webgoat.sql_injection.introduction.SqlInjectionLesson8


protected AttackResult injectableQueryIntegrity(String name, String auth_tan) {
        StringBuffer output = new StringBuffer();
        String query = "SELECT * FROM employees WHERE last_name = '" + name + "' AND auth_tan = '" + auth_tan + "'";
        try (Connection connection = dataSource.getConnection()) {
            try {
                Statement statement = connection.createStatement(TYPE_SCROLL_SENSITIVE, CONCUR_UPDATABLE);
                SqlInjectionLesson8.log(connection, query);
                ResultSet results = statement.executeQuery(query);
                var test = results.getRow() != 0;
                if (results.getStatement() != null) {
                    if (results.first()) {
                        output.append(SqlInjectionLesson8.generateTable(results));
                    } else {
                        // no results
                        return trackProgress(failed().feedback("sql-injection.8.no.results").build());
                    }
                }
            } catch (SQLException e) {
                System.err.println(e.getMessage());
                return trackProgress(failed().feedback("sql-injection.error").output("
" + e.getMessage() + "").build());
            }

            return checkSalaryRanking(connection, output);

        } catch (Exception e) {
            System.err.println(e.getMessage());
            return trackProgress(failed().feedback("sql-injection.error").output("
" + e.getMessage() + "").build());
        }
    }

protected AttackResult injectableQueryIntegrity(String name, String auth_tan) {
        StringBuffer output = new StringBuffer();
        String query = "SELECT * FROM employees WHERE last_name = '" + name + "' AND auth_tan = '" + auth_tan + "'";

        try {
            Connection connection = DatabaseUtilities.getConnection(getWebSession());

            try {
                Statement statement = connection.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
                SqlInjectionLesson8.log(connection, query);
                ResultSet results = statement.executeQuery(query);

                if (results.getStatement() != null) {
                    if (results.first()) {
                        output.append(SqlInjectionLesson8.generateTable(results));
                    } else {
                        // no results
                        return trackProgress(failed().feedback("sql-injection.8.no.results").build());
                    }

                }
            } catch (SQLException e) {
                System.err.println(e.getMessage());
                return trackProgress(failed().feedback("sql-injection.error").output("
" + e.getMessage() + "").build());
            }

            return checkSalaryRanking(connection, output);

        } catch (Exception e) {
            System.err.println(e.getMessage());
            return trackProgress(failed().feedback("sql-injection.error").output("
" + e.getMessage() + "").build());
        }
    }

Try With Resources try(Connection connection=dataSource.getConnection()) in method protected injectableQueryIntegrity(name String, auth_tan String) : AttackResult from class org.owasp.webgoat.sql_injection.introduction.SqlInjectionLesson9


private AttackResult checkSalaryRanking(Connection connection, StringBuffer output) {
        try {
            String query = "SELECT * FROM employees ORDER BY salary DESC";
            try (Statement statement = connection.createStatement(TYPE_SCROLL_SENSITIVE, CONCUR_UPDATABLE);
            ) {
                ResultSet results = statement.executeQuery(query);

                results.first();
                // user completes lesson if John Smith is the first in the list
                if ((results.getString(2).equals("John")) && (results.getString(3).equals("Smith"))) {
                    output.append(SqlInjectionLesson8.generateTable(results));
                    return trackProgress(success().feedback("sql-injection.9.success").output(output.toString()).build());
                } else {
                    return trackProgress(failed().feedback("sql-injection.9.one").output(output.toString()).build());
                }
            }
        } catch (SQLException e) {
            return trackProgress(failed().feedback("sql-injection.error").output("
" + e.getMessage() + "").build());
        }
    }

private AttackResult checkSalaryRanking(Connection connection, StringBuffer output) {
        try {
            String query = "SELECT * FROM employees ORDER BY salary DESC";
            Statement statement = connection.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
            ResultSet results = statement.executeQuery(query);

            results.first();
            // user completes lesson if John Smith is the first in the list
            if ((results.getString(2).equals("John")) && (results.getString(3).equals("Smith"))) {
                output.append(SqlInjectionLesson8.generateTable(results));
                return trackProgress(success().feedback("sql-injection.9.success").output(output.toString()).build());
            } else {
                return trackProgress(failed().feedback("sql-injection.9.one").output(output.toString()).build());
            }

        } catch (SQLException e) {
            System.err.println(e.getMessage());
            return trackProgress(failed().feedback("sql-injection.error").output("
" + e.getMessage() + "").build());
        }
    }

Try With Resources try(Statement statement=connection.createStatement(TYPE_SCROLL_SENSITIVE,CONCUR_UPDATABLE)) in method private checkSalaryRanking(connection Connection, output StringBuffer) : AttackResult from class org.owasp.webgoat.sql_injection.introduction.SqlInjectionLesson9


protected AttackResult injectableQuery(String accountName) {
        String query = "";
        try(Connection connection = DatabaseUtilities.getConnection(getWebSession())) {
            boolean usedUnion = true;
            query = "SELECT * FROM user_data WHERE last_name = '" + accountName + "'";
            //Check if Union is used
            if(!accountName.matches("(?i)(^[^-/*;)]*)(\\s*)UNION(.*$)")) {
                usedUnion = false;
            }
            try(Statement statement = connection.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,
                    ResultSet.CONCUR_READ_ONLY)) {
                ResultSet results = statement.executeQuery(query);

                if ((results != null) && (results.first())) {
                    ResultSetMetaData resultsMetaData = results.getMetaData();
                    StringBuffer output = new StringBuffer();

                    output.append(SqlInjectionLesson5a.writeTable(results, resultsMetaData));

                    String appendingWhenSucceded;
                    if(usedUnion)
                        appendingWhenSucceded = "Well done! Can you also figure out a solution, by appending a new Sql Statement?";
                    else
                        appendingWhenSucceded = "Well done! Can you also figure out a solution, by using a UNION?";
                    results.last();

                    if (output.toString().contains("dave") && output.toString().contains("passW0rD")) {
                        output.append(appendingWhenSucceded);
                        return trackProgress(informationMessage().feedback("sql-injection.advanced.6a.success").feedbackArgs(output.toString()).output(" Your query was: " + query).build());
                    } else {
                        return trackProgress(failed().output(output.toString() + "
 Your query was: " + query).build());
                    }
                } else {
                    return trackProgress(failed().feedback("sql-injection.advanced.6a.no.results").output(" Your query was: " + query).build());
                }
            } catch (SQLException sqle) {
                return trackProgress(failed().output(sqle.getMessage() + "
 Your query was: " + query).build());
            }
        } catch (Exception e) {
            e.printStackTrace();
            return trackProgress(failed().output(this.getClass().getName() + " : " + e.getMessage() + "
 Your query was: " + query).build());
        }
    }

protected AttackResult injectableQuery(String accountName) {
        String query = "";
        try {
            boolean usedUnion = true;
            Connection connection = DatabaseUtilities.getConnection(getWebSession());
            query = "SELECT * FROM user_data WHERE last_name = '" + accountName + "'";
            //Check if Union is used
            if(!accountName.matches("(?i)(^[^-/*;)]*)(\\s*)UNION(.*$)")) {
                usedUnion = false;
            }
            try {
                Statement statement = connection.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,
                        ResultSet.CONCUR_READ_ONLY);
                ResultSet results = statement.executeQuery(query);

                if ((results != null) && (results.first())) {
                    ResultSetMetaData resultsMetaData = results.getMetaData();
                    StringBuffer output = new StringBuffer();

                    output.append(SqlInjectionLesson5a.writeTable(results, resultsMetaData));
                    if(! usedUnion)
                        output.append("To successfully complete this Assignment you have to use a UNION");
                    results.last();

                    // If they get back more than one user they succeeded
                    if (results.getRow() >= 5 && usedUnion) {
                        return trackProgress(success().feedback("sql-injection.advanced.6a.success").feedbackArgs(output.toString()).output(" Your query was: " + query).build());
                    } else if((output.toString().contains("dave") && output.toString().contains("passW0rD")) && !usedUnion) {
                        return trackProgress(failed().output("To successfully complete this Assignment you have to use a UNION" + "
 Your query was: " + query).build());
                    } else {
                        return trackProgress(failed().output(output.toString() + "
 Your query was: " + query).build());
                    }
                } else {
                    return trackProgress(failed().feedback("sql-injection.advanced.6a.no.results").output(" Your query was: " + query).build());
                }
            } catch (SQLException sqle) {
                return trackProgress(failed().output(sqle.getMessage() + "
 Your query was: " + query).build());
            }
        } catch (Exception e) {
            e.printStackTrace();
            return trackProgress(failed().output(this.getClass().getName() + " : " + e.getMessage() + "
 Your query was: " + query).build());
        }
    }

Try With Resources try(Statement statement=connection.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,ResultSet.CONCUR_READ_ONLY)) in method protected injectableQuery(accountName String) : AttackResult from class org.owasp.webgoat.plugin.advanced.SqlInjectionLesson6a


protected AttackResult injectableQuery(String accountName) {
    String query = "";
    try {
      Connection connection = DatabaseUtilities.getConnection(getWebSession());
      query = "SELECT * FROM user_data WHERE first_name = 'John' and last_name = '" + accountName + "'";
      try(Statement statement = connection.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,
              ResultSet.CONCUR_READ_ONLY)) {

        ResultSet results = statement.executeQuery(query);

        if ((results != null) && (results.first())) {
          ResultSetMetaData resultsMetaData = results.getMetaData();
          StringBuilder output = new StringBuilder();

          output.append(writeTable(results, resultsMetaData));
          results.last();

          // If they get back more than one user they succeeded
          if (results.getRow() >= 6) {
            return trackProgress(success().feedback("sql-injection.5a.success").output("Your query was: " + query + EXPLANATION).feedbackArgs(output.toString()).build());
          } else {
            return trackProgress(failed().output(output.toString() + "
 Your query was: " + query).build());
          }
        } else {
          return trackProgress(failed().feedback("sql-injection.5a.no.results").output("Your query was: " + query).build());

        }
      } catch (SQLException sqle) {

        return trackProgress(failed().output(sqle.getMessage() + "
 Your query was: " + query).build());
      }
    } catch (Exception e) {
      return trackProgress(failed().output(this.getClass().getName() + " : " + e.getMessage() + "
 Your query was: " + query).build());
    }
  }

protected AttackResult injectableQuery(String accountName) {
    String query = "";
    try {
      Connection connection = DatabaseUtilities.getConnection(getWebSession());
      System.out.println(accountName);
      query = "SELECT * FROM user_data WHERE first_name = 'John' and last_name = '" + accountName + "'";
      try {
        Statement statement = connection.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,
                ResultSet.CONCUR_READ_ONLY);
        ResultSet results = statement.executeQuery(query);

        if ((results != null) && (results.first())) {
          ResultSetMetaData resultsMetaData = results.getMetaData();
          StringBuffer output = new StringBuffer();

          output.append(writeTable(results, resultsMetaData));
          results.last();

          // If they get back more than one user they succeeded
          if (results.getRow() >= 6) {
            return trackProgress(success().feedback("sql-injection.5a.success").output("Your query was: " + query).feedbackArgs(output.toString()).build());
          } else {
            return trackProgress(failed().output(output.toString() + "
 Your query was: " + query).build());
          }
        } else {
          return trackProgress(failed().feedback("sql-injection.5a.no.results").output("Your query was: " + query).build());

        }
      } catch (SQLException sqle) {

        return trackProgress(failed().output(sqle.getMessage() + "
 Your query was: " + query).build());
      }
    } catch (Exception e) {
      return trackProgress(failed().output(this.getClass().getName() + " : " + e.getMessage() + "
 Your query was: " + query).build());
    }
  }

Try With Resources try(Statement statement=connection.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,ResultSet.CONCUR_READ_ONLY)) in method protected injectableQuery(accountName String) : AttackResult from class org.owasp.webgoat.plugin.introduction.SqlInjectionLesson5a


    private List<Callable<Plugin>> extractJars(List<URL> jars) {
        List<Callable<Plugin>> extractorCallables = Lists.newArrayList();
        ClassLoader parentClassLoader = PluginClassLoader.class.getClassLoader();
        final PluginClassLoader classLoader = new PluginClassLoader(parentClassLoader);

        for (final URL jar : jars) {
            classLoader.addURL(jar);
            extractorCallables.add(() -> {
                PluginExtractor extractor = new PluginExtractor();
                return extractor.extractJarFile(ResourceUtils.getFile(jar), pluginTarget.toFile(), classLoader);
            });
        }
        return extractorCallables;
    }

    private List<Callable<Plugin>> extractJars(List<URL> jars) {
        List<Callable<Plugin>> extractorCallables = Lists.newArrayList();
        ClassLoader parentClassLoader = PluginClassLoader.class.getClassLoader();
        final PluginClassLoader classLoader = new PluginClassLoader(parentClassLoader);

        for (final URL jar : jars) {
            classLoader.addURL(jar);
            extractorCallables.add(new Callable<Plugin>() {

                @Override
                public Plugin call() throws Exception {
                    PluginExtractor extractor = new PluginExtractor();
                    return extractor.extractJarFile(ResourceUtils.getFile(jar), pluginTarget.toFile(), classLoader);
                }
            });
        }
        return extractorCallables;
    }

Replace Anonymous With Lambda org.owasp.webgoat.plugins.PluginsLoader.extractJars.add.new Callable<Plugin> with () -> {PluginExtractor extractor=new PluginExtractor(); in method private extractJars(jars List<URL>) : List<Callable<Plugin>> from class org.owasp.webgoat.plugins.PluginsLoader


    /**
     * Checks if debugging of labels is enabled or disabled
     *
     * @return a {@link org.springframework.http.ResponseEntity} object.
     */
    @RequestMapping(path = URL_DEBUG_LABELS_MVC, produces = MediaType.APPLICATION_JSON_VALUE)
    public @ResponseBody
    ResponseEntity<Map<String, Object>> checkDebuggingStatus() {
        logger.debug("Checking label debugging, it is " + labelDebugger.isEnabled()); // FIXME parameterize
        Map<String, Object> result = createResponse(labelDebugger.isEnabled());
        return new ResponseEntity<>(result, HttpStatus.OK);
    }

    /**
     * Checks if debugging of labels is enabled or disabled
     *
     * @return a {@link org.springframework.http.ResponseEntity} object.
     */
    @RequestMapping(path = URL_DEBUG_LABELS_MVC, produces = MediaType.APPLICATION_JSON_VALUE)
    public @ResponseBody
    ResponseEntity<Map<String, Object>> checkDebuggingStatus() {
        logger.debug("Checking label debugging, it is " + labelDebugger.isEnabled()); // FIXME parameterize
        Map<String, Object> result = createResponse(labelDebugger.isEnabled());
        return new ResponseEntity<Map<String, Object>>(result, HttpStatus.OK);
    }

Replace Generic With Diamond ResponseEntity<Map<String,Object>> with ResponseEntity<> in method public checkDebuggingStatus() : ResponseEntity<Map<String,Object>> from class org.owasp.webgoat.service.LabelDebugService


      /**
      * Sets the enabled flag on the label debugger to the given parameter
      *
      * @return a {@link org.springframework.http.ResponseEntity} object.
     * @throws Exception
      */
     @RequestMapping(value = URL_DEBUG_LABELS_MVC, produces = MediaType.APPLICATION_JSON_VALUE, params = KEY_ENABLED)
     public @ResponseBody
     ResponseEntity<Map<String, Object>> setDebuggingStatus(@RequestParam("enabled") Boolean enabled) throws Exception {
         logger.debug("Setting label debugging to " + labelDebugger.isEnabled()); // FIXME parameterize
         Map<String, Object> result = createResponse(enabled);
         labelDebugger.setEnabled(enabled);
         return new ResponseEntity<>(result, HttpStatus.OK);
     }

      /**
      * Sets the enabled flag on the label debugger to the given parameter
      *
      * @return a {@link org.springframework.http.ResponseEntity} object.
     * @throws Exception
      */
     @RequestMapping(value = URL_DEBUG_LABELS_MVC, produces = MediaType.APPLICATION_JSON_VALUE, params = KEY_ENABLED)
     public @ResponseBody
     ResponseEntity<Map<String, Object>> setDebuggingStatus(@RequestParam("enabled") Boolean enabled) throws Exception {
         logger.debug("Setting label debugging to " + labelDebugger.isEnabled()); // FIXME parameterize
         Map<String, Object> result = createResponse(enabled);
         labelDebugger.setEnabled(enabled);
         return new ResponseEntity<Map<String, Object>>(result, HttpStatus.OK);
     }

Replace Generic With Diamond ResponseEntity<Map<String,Object>> with ResponseEntity<> in method public setDebuggingStatus(enabled Boolean) : ResponseEntity<Map<String,Object>> from class org.owasp.webgoat.service.LabelDebugService


    public void extract() {
        try (FileSystem zip = createZipFileSystem()) {
            final Path root = zip.getPath("/");
            baseDirectory = Paths.get(System.getProperty("java.io.tmpdir"), DIRECTORY);
            Files.walkFileTree(root, new SimpleFileVisitor<Path>() {
                @Override
                public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
                    if (file.toString().endsWith(".class")) {
                        ByteArrayOutputStream bos = new ByteArrayOutputStream();
                        Files.copy(file, bos);
                        classes.put(file.toString(), bos.toByteArray());
                    }
                    Files.copy(file, Paths.get(baseDirectory.toString(), file.toString()), REPLACE_EXISTING);
                    return FileVisitResult.CONTINUE;
                }
            });
        } catch (IOException io) {
            logger.error(String.format("Unable to extract: %s", pluginArchive.getFileName()), io);
        }
    }

    public void extract() {
        FileSystem zip = null;
        try {
            zip = createZipFileSystem();
            final Path root = zip.getPath("/");
            baseDirectory = Paths.get(System.getProperty("java.io.tmpdir"), DIRECTORY);
            Files.walkFileTree(root, new SimpleFileVisitor<Path>() {
                @Override
                public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
                    if (file.toString().endsWith(".class")) {
                        ByteArrayOutputStream bos = new ByteArrayOutputStream();
                        Files.copy(file, bos);
                        classes.put(file.toString(), bos.toByteArray());
                    }
                    Files.copy(file, Paths.get(baseDirectory.toString(), file.toString()), REPLACE_EXISTING);
                    return FileVisitResult.CONTINUE;
                }
            });
        } catch (IOException io) {
            logger.error(String.format("Unable to extract: %s", pluginArchive.getFileName()), io);
        } finally {
            closeZipFileSystem(zip);
        }
    }

Try With Resources try(FileSystem zip=createZipFileSystem()) in method public extract() : void from class org.owasp.webgoat.plugins.PluginExtractor


	@Override
	@SuppressWarnings("PMD.NPathComplexity")
	public List<Team> getTeams() {
	    List<Team> result = new ArrayList<>();

		try {
			URL url = new URL(featureSettings.getJiraBaseUrl() + (featureSettings.getJiraBaseUrl().endsWith("/")? "" : "/")
						+ TEMPO_TEAMS_REST_SUFFIX);
			URLConnection connection = null;

			if (featureSettings.getJiraProxyUrl() != null && !featureSettings.getJiraProxyUrl().isEmpty() && (featureSettings.getJiraProxyPort() != null)) {
				String fullProxyUrl = featureSettings.getJiraProxyUrl() + ":" + featureSettings.getJiraProxyPort();
				URL proxyUrl = new URL(fullProxyUrl);
				URI proxyUri = new URI(proxyUrl.getProtocol(), proxyUrl.getUserInfo(),
					proxyUrl.getHost(), proxyUrl.getPort(), proxyUrl.getPath(), proxyUrl.getQuery(), null);
				Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(proxyUri.getHost(), proxyUri.getPort()));
				connection = url.openConnection(proxy);

				if (!StringUtils.isEmpty(featureSettings.getJiraCredentials())) {
					String[] creds = (new String(Base64.decodeBase64(featureSettings.getJiraCredentials()))).split(":");
					final String uname = creds[0];
					final String pword = creds.length > 1? creds[1] : null;
					Authenticator.setDefault(new Authenticator() {
						protected PasswordAuthentication getPasswordAuthentication() {
							return new PasswordAuthentication(uname, pword.toCharArray());
						}
					});
					connection.setRequestProperty("Proxy-Authorization", "Basic " + featureSettings.getJiraCredentials());
				}
			} else {
				connection = url.openConnection();
			}

			HttpURLConnection request = (HttpURLConnection) connection;
			request.setRequestProperty("Authorization" , "Basic " + featureSettings.getJiraCredentials());
			request.connect();

			try (InputStreamReader streamReader = new InputStreamReader((InputStream) request.getContent(), Charset.forName("UTF-8"));
			        BufferedReader inReader = new BufferedReader(streamReader)) {
			    StringBuilder sb = new StringBuilder();
    			int cp;
    		    while ((cp = inReader.read()) != -1) {
    				sb.append((char) cp);
    		    }

                JSONParser parser = new JSONParser();
                try {
                    JSONArray teamsJson = (JSONArray) parser.parse(sb.toString());

                    if (teamsJson != null) {
                        for (Object obj : teamsJson) {
                            String teamId = TOOLS.sanitizeResponse(((JSONObject) obj).get("id"));
                            String teamName = TOOLS.sanitizeResponse(getJSONString((JSONObject) obj, "name"));
                            result.add(new Team(teamId, teamName));
                        }
                    }
                } catch (ParseException pe) {
                    LOGGER.error("Parser exception when parsing teams", pe);
                }
			}
        } catch (org.springframework.web.client.RestClientException rce) {
            LOGGER.error("Client exception when loading teams", rce);
            throw rce;
        }  catch (MalformedURLException mfe) {
            LOGGER.error("Malformed url for loading teams", mfe);
        } catch (IOException ioe) {
			LOGGER.error("IOException", ioe);
		} catch (URISyntaxException urie) {
			LOGGER.error("URISyntaxException for Jira connection", urie);
		}

		return result;
	}

	@Override
	public JSONArray getTeams() {
		JSONArray result = null;

		try {
			URL url = new URL(featureSettings.getJiraBaseUrl() + (featureSettings.getJiraBaseUrl().endsWith("/")? "" : "/")
						+ TEMPO_TEAMS_REST_SUFFIX);
			URLConnection connection = null;

			if (featureSettings.getJiraProxyUrl() != null && !featureSettings.getJiraProxyUrl().isEmpty() && (featureSettings.getJiraProxyPort() != null)) {
				String fullProxyUrl = featureSettings.getJiraProxyUrl() + ":" + featureSettings.getJiraProxyPort();
				URL proxyUrl = new URL(fullProxyUrl);
				URI proxyUri = new URI(proxyUrl.getProtocol(), proxyUrl.getUserInfo(),
					proxyUrl.getHost(), proxyUrl.getPort(), proxyUrl.getPath(), proxyUrl.getQuery(), null);
				Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(proxyUri.getHost(), proxyUri.getPort()));
				connection = url.openConnection(proxy);

				if (!StringUtils.isEmpty(featureSettings.getJiraCredentials())) {
					String[] creds = (new String(Base64.decodeBase64(featureSettings.getJiraCredentials()))).split(":");
					final String uname = creds[0];
					final String pword = creds.length > 1? creds[1] : null;
					Authenticator.setDefault(new Authenticator() {
						protected PasswordAuthentication getPasswordAuthentication() {
							return new PasswordAuthentication(uname, pword.toCharArray());
						}
					});
					connection.setRequestProperty("Proxy-Authorization", "Basic " + featureSettings.getJiraCredentials());
				}
			} else {
				connection = url.openConnection();
			}

			HttpURLConnection request = (HttpURLConnection) connection;
			request.setRequestProperty("Authorization" , "Basic " + featureSettings.getJiraCredentials());
			request.connect();

			InputStream in = (InputStream) request.getContent();
			BufferedReader inReader = new BufferedReader(new InputStreamReader(in, Charset.forName("UTF-8")));
			StringBuilder sb = new StringBuilder();

			int cp;
		    while ((cp = inReader.read()) != -1) {
				sb.append((char) cp);
		    }
            JSONParser parser = new JSONParser();

            try {
                result = (JSONArray) parser.parse(sb.toString());
            } catch (ParseException pe) {
                LOGGER.error("Parser exception when parsing teams", pe);
            }
        } catch (org.springframework.web.client.RestClientException rce) {
            LOGGER.error("Client exception when loading teams", rce);
            throw rce;
        }  catch (MalformedURLException mfe) {
            LOGGER.error("Malformed url for loading teams", mfe);
        } catch (IOException ioe) {
			LOGGER.error("IOException", ioe);
		} catch (URISyntaxException urie) {
			LOGGER.error("URISyntaxException for Jira connection", urie);
		}

		return result;
	}

Try With Resources try(InputStreamReader streamReader=new InputStreamReader((InputStream)request.getContent(),Charset.forName("UTF-8")); BufferedReader inReader=new BufferedReader(streamReader)) in method public getTeams() : List<Team> from class com.capitalone.dashboard.client.DefaultJiraClient


    private ImageIcon getImageFromResources(String path) {
        try (InputStream resource = DisplayConfiguration.class.getResourceAsStream(fullPieceImagePath(path))) {
            Image image = ImageIO.read(resource);
            return new ImageIcon(image);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    private ImageIcon getImageFromResources(String path) {
        URL url = DisplayConfiguration.class.getResource(fullPieceImagePath(path));
        try {
            if (url == null) {
                throw new RuntimeException("Cant read piece from resources");
            }
            Image image = ImageIO.read(url);
            return new ImageIcon(image);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

Try With Resources try(InputStream resource=DisplayConfiguration.class.getResourceAsStream(fullPieceImagePath(path))) in method private getImageFromResources(path String) : ImageIcon from class gui.DisplayConfiguration


    Diagram Load(String Namefile){
        try (ObjectInputStream inputStream = new ObjectInputStream(new FileInputStream(Namefile+".bin"))) {
            Diagram neu = (Diagram) inputStream.readObject();
            return neu;
        } catch (IOException | ClassNotFoundException e) {
            e.printStackTrace();
        }
        return null;
    }

    Diagram Load(String Namefile){
        try (ObjectInputStream inputStream = new ObjectInputStream(new FileInputStream(Namefile+".bin"))) {
            Diagram neu = (Diagram) inputStream.readObject();
            return neu;
        }
        catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
        return null;
    }

Merge Catch [catch(FileNotFoundException e), catch(IOException e), catch(ClassNotFoundException e)] to catch(IOException|ClassNotFoundException e) in method package Load(Namefile String) : Diagram from class prg.Database_editor


    public Administrador(String nome, String telefone, String email, String senha) {
        super(nome, telefone, email, senha);
        this.produtos = new HashMap<>();
        this.horarios = new Horario(0);
    }

    public Administrador(String nome, String telefone, String email, String senha) {
        super(nome, telefone, email, senha);
        this.produtos = new HashMap<String, Double>();
        this.horarios = new Horario(0);
    }

Replace Generic With Diamond HashMap<String,Double> with HashMap<> in method public Administrador(nome String, telefone String, email String, senha String) from class com.dcc025.trabalhooop.Administrador


    public ArrayList<String> getHhrsIndisponiveis(int diaSemana) {
        ArrayList<String> horariosIndisponiveis = new ArrayList<>();
        if (diaSemana >= 0 && diaSemana < this.diasUteis) { // se for um dia valido
            HashMap<String, Integer> horariosDia = horarios.get(diaSemana);// pega todos os horarios desse dia
            for (String horario : horariosDia.keySet()) {// percorre todos os horariosdesse dia
                if (horariosDia.get(horario) == 2) {// verifica se esse horario ainda tem 2 pessoas marcadas
                    horariosIndisponiveis.add(horario);// adiciona esse horario na lista de horarios indisponiveis
                }
            }
        }
        return horariosIndisponiveis;
    }

   public ArrayList<String> getHhrsIndisponiveis(int diaSemana) {
      ArrayList<String> horariosIndisponiveis = new ArrayList<String>();
      if (diaSemana >= 0 && diaSemana < this.diasUteis) { // se for um dia valido
         HashMap<String, Integer> horariosDia = horarios.get(diaSemana);// pega todos os horarios desse dia
         for (String horario : horariosDia.keySet()) {// percorre todos os horariosdesse dia
            if (horariosDia.get(horario) == 2) {// verifica se esse horario ainda tem 2 pessoas marcadas
               horariosIndisponiveis.add(horario);// adiciona esse horario na lista de horarios indisponiveis
            }
         }
      }
      return horariosIndisponiveis;
   }

Replace Generic With Diamond ArrayList<String> with ArrayList<> in method public getHhrsIndisponiveis(diaSemana int) : ArrayList<String> from class com.dcc025.trabalhooop.Horario


	public Place(String name) {
		this.name = name;
		this.produtos = new HashMap<>();
	}

	public Place(String name) {
		this.name = name;
		this.produtos = new HashMap<String, Double>();
	}

Replace Generic With Diamond HashMap<String,Double> with HashMap<> in method public Place(name String) from class com.dcc025.trabalhooop.Place


    public HashMap<String, String[]> getCategories() {
        this.categories = new HashMap<>();
        this.categories.put("Animal", new String[]{"lion", "panda", "camel", "pig", "dog", "cat", "horse", "sheep", "fox", "cow"});
        this.categories.put("Fruit", new String[]{"apple", "banana", "orange", "mango", "grapes", "pineapple", "avocado", "lime"});
        return categories;
    }

    public HashMap<String, String[]> getCategories() {
        this.categories = new HashMap<String, String[]>();
        this.categories.put("Animal", new String[]{"lion", "panda", "camel", "pig", "dog", "cat", "horse", "sheep", "fox", "cow"});
        this.categories.put("Fruit", new String[]{"apple", "banana", "orange", "mango", "grapes", "pineapple", "avocado", "lime"});
        return categories;
    }

Replace Generic With Diamond HashMap<String,String[]> with HashMap<> in method public getCategories() : HashMap<String,String[]> from class aryahmph.entity.Game


    @Override
    public void stop()
    {
        try(  FileOutputStream file_stream = new FileOutputStream(this.path.toFile());
              ObjectOutputStream stream = new ObjectOutputStream(file_stream);) {

            stream.flush();
            stream.writeObject(this.history);

        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void stop() {
        try {
            FileOutputStream file_stream = new FileOutputStream(this.path.toFile());
            file_stream.flush();
            ObjectOutputStream stream = new ObjectOutputStream(file_stream);
            stream.writeObject(this.history);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

Try With Resources try(FileOutputStream file_stream=new FileOutputStream(this.path.toFile()); ObjectOutputStream stream=new ObjectOutputStream(file_stream)) in method public stop() : void from class org.openjfx.hellofx.BaseApp


    public Manage() {
        nVars = 0;
        variables = new ArrayList<>();
    }

    public Manage() {
        nVars = 0;
        variables = new ArrayList<ManageVar>();
    }

Replace Generic With Diamond ArrayList<ManageVar> with ArrayList<> in method public Manage() from class com.hans0924.fsd.manager.Manage


    private Status createUser(String username, String password) {
        if (isInputInvalid(username, password)) {
            return Status.BAD_REQUEST;
        }
        if (userExists(username) != Status.NOT_FOUND) {
            return Status.BAD_REQUEST;
        }

        try (CallableStatement statement = getConnection().prepareCall("{call CreateUser(?,?)}")) {
            statement.setString(1, username);
            statement.setString(2, password);
            statement.execute();

            if (statement.getUpdateCount() != 1) {
                return Status.BAD_REQUEST;
            }

        } catch (SQLException e) {
            e.printStackTrace();
            return Status.INTERNAL_SERVER_ERROR;
        }

        return Status.OK;
    }

    private Status createUser(String username, String password) {
        try {
            if (isInputInvalid(username, password)){
                return Status.BAD_REQUEST;
            }
            if (userExists(username) != Status.NOT_FOUND){
                return Status.BAD_REQUEST;
            }

            CallableStatement statement = con.prepareCall("{call CreateUser(?,?)}");
            statement.setString(1, username);
            statement.setString(2, password);

            statement.execute();

            if (statement.getUpdateCount() != 1){
                return Status.BAD_REQUEST;
            }

        } catch (SQLException e) {
            e.printStackTrace();
            return Status.INTERNAL_SERVER_ERROR;
        }

        return Status.OK;
    }

Try With Resources try(CallableStatement statement=getConnection().prepareCall("{call CreateUser(?,?)}")) in method private createUser(username String, password String) : Status from class Controller.Database.DbRequestCaller


    private List<Animation> createAnimations() throws AnimationInstantiationException {
        final List<Animation> animations = new ArrayList<>();
        for (final AnimationBuilder animationFactory : this.getAnimationBuilders()) {
            animations.add(animationFactory.buildAnimation());
        }
        return animations;
    }

    private List<Animation> createAnimations() throws AnimationInstantiationException {
        final List<Animation> animations = new ArrayList<Animation>();
        for (final AnimationBuilder animationFactory : this.getAnimationBuilders()) {
            animations.add(animationFactory.buildAnimation());
        }
        return animations;
    }

Replace Generic With Diamond ArrayList<Animation> with ArrayList<> in method private createAnimations() : List<Animation> from class com.group_finity.mascot.config.ActionBuilder


    private TopLevelMenuRep createPopupRep() {
        var config = Main.getInstance().getConfiguration(getImageSet());
        boolean translateNames = Main.getInstance().shouldTranslateBehaviorNames();

        List<MenuItemRep> behaviorItems = new ArrayList<>();
        Behavior behaviour;
        for (String behaviorName : config.getBehaviorNames()) {
            String lblName = translateNames ? Tr.trBv(behaviorName) : behaviorName;
            try {
                behaviour = config.buildBehavior(behaviorName);
                if (!behaviour.isHidden()) {
                    behaviorItems.add(new MenuItemRep(lblName, () -> {
                        try {
                            setBehavior(config.buildBehavior(behaviorName));
                        } catch (Exception err) {
                            log.log(Level.SEVERE, "Error ({0})");
                            Main.showError(Tr.tr("CouldNotSetBehaviourErrorMessage")
                                    + "\n" + err.getMessage()
                                    + "\n" + Tr.tr("SeeLogForDetails"));
                        }
                    }));
                }
            } catch (Exception ignored) {
                behaviorItems.add(new MenuItemRep(lblName, null, false));
            }
        }

        TopLevelMenuRep mainMenu = new TopLevelMenuRep("Shimeji Popup",
                new MenuItemRep(Tr.tr("CallAnother"), () -> Main.getInstance().createMascot(getImageSet())),
                MenuItemRep.SEPARATOR,
                new MenuItemRep(Tr.tr("FollowCursor"), () ->
                        getManager().setBehaviorAll(config, Main.BEHAVIOR_GATHER, getImageSet())
                ),
                new MenuItemRep(Tr.tr("RestoreWindows"), () -> NativeFactory.getInstance().getEnvironment().restoreIE()),
                new MenuItemRep(Tr.tr("RevealStatistics"), () -> {
                    if (debugWindow == null) {
                        debugWindow = new DebugWindow();
                    }
                    debugWindow.setVisible(true);
                }),
                MenuItemRep.SEPARATOR,
                new MenuRep(Tr.tr("SetBehaviour"), behaviorItems.toArray(new MenuItemRep[0])),
                MenuItemRep.SEPARATOR,
                new MenuItemRep(Tr.tr("Dismiss"), this::dispose),
                new MenuItemRep(Tr.tr("DismissOthers"), () -> getManager().remainOne(getImageSet())),
                new MenuItemRep(Tr.tr("DismissAllOthers"), () -> getManager().remainOne(this)),
                new MenuItemRep(Tr.tr("DismissAll"), () -> System.exit(0))
        );

        mainMenu.setOnOpenAction(() -> this.setAnimating(false));
        mainMenu.setOnCloseAction(() -> this.setAnimating(true));

        return mainMenu;
    }

    private TopLevelMenuRep createPopupRep() {
        var config = Main.getInstance().getConfiguration(getImageSet());
        boolean translateNames = Main.getInstance().shouldTranslateBehaviorNames();

        List<MenuItemRep> behaviorItems = new ArrayList<MenuItemRep>();
        Behavior behaviour;
        for (String behaviorName : config.getBehaviorNames()) {
            String lblName = translateNames ? Tr.trBv(behaviorName) : behaviorName;
            try {
                behaviour = config.buildBehavior(behaviorName);
                if (!behaviour.isHidden()) {
                    behaviorItems.add(new MenuItemRep(lblName, () -> {
                        try {
                            setBehavior(config.buildBehavior(behaviorName));
                        } catch (Exception err) {
                            log.log(Level.SEVERE, "Error ({0})");
                            Main.showError(Tr.tr("CouldNotSetBehaviourErrorMessage")
                                    + "\n" + err.getMessage()
                                    + "\n" + Tr.tr("SeeLogForDetails"));
                        }
                    }));
                }
            } catch (Exception ignored) {
                behaviorItems.add(new MenuItemRep(lblName, null, false));
            }
        }

        TopLevelMenuRep mainMenu = new TopLevelMenuRep("Shimeji Popup",
                new MenuItemRep(Tr.tr("CallAnother"), () -> Main.getInstance().createMascot(getImageSet())),
                MenuItemRep.SEPARATOR,
                new MenuItemRep(Tr.tr("FollowCursor"), () ->
                        getManager().setBehaviorAll(config, Main.BEHAVIOR_GATHER, getImageSet())
                ),
                new MenuItemRep(Tr.tr("RestoreWindows"), () -> NativeFactory.getInstance().getEnvironment().restoreIE()),
                new MenuItemRep(Tr.tr("RevealStatistics"), () -> {
                    if (debugWindow == null) {
                        debugWindow = new DebugWindow();
                    }
                    debugWindow.setVisible(true);
                }),
                MenuItemRep.SEPARATOR,
                new MenuRep(Tr.tr("SetBehaviour"), behaviorItems.toArray(new MenuItemRep[0])),
                MenuItemRep.SEPARATOR,
                new MenuItemRep(Tr.tr("Dismiss"), this::dispose),
                new MenuItemRep(Tr.tr("DismissOthers"), () -> getManager().remainOne(getImageSet())),
                new MenuItemRep(Tr.tr("DismissAllOthers"), () -> getManager().remainOne(this)),
                new MenuItemRep(Tr.tr("DismissAll"), () -> System.exit(0))
        );

        mainMenu.setOnOpenAction(() -> this.setAnimating(false));
        mainMenu.setOnCloseAction(() -> this.setAnimating(true));

        return mainMenu;
    }

Replace Generic With Diamond ArrayList<MenuItemRep> with ArrayList<> in method private createPopupRep() : TopLevelMenuRep from class com.group_finity.mascot.Mascot


    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(() -> {
            new WindowsInteractiveWindowForm(new javax.swing.JFrame(), true).display();
            System.exit(0);
        });
    }

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new WindowsInteractiveWindowForm(new javax.swing.JFrame(), true).display();
                System.exit(0);
            }
        });
    }

Replace Anonymous With Lambda com.group_finity.mascotnative.win.WindowsInteractiveWindowForm.main.invokeLater.new Runnable with () -> {new WindowsInteractiveWindowForm(new javax.swing.JFrame(),true).display(); in method public main(args String[]) : void from class com.group_finity.mascotnative.win.WindowsInteractiveWindowForm


        public MenuScrollTimer(final int increment, int interval) {
            super(interval, e -> {
                firstIndex += increment;
                refreshMenu();
            });
        }

    public MenuScrollTimer(final int increment, int interval) {
      super(interval, new ActionListener() {

        @Override
        public void actionPerformed(ActionEvent e) {
          firstIndex += increment;
          refreshMenu();
        }
      });
    }

Replace Anonymous With Lambda com.group_finity.mascot.menu.MenuScroller.MenuScrollTimer.MenuScrollTimer.new ActionListener with e -> {firstIndex+=increment; in method public MenuScrollTimer(increment int, interval int) from class com.group_finity.mascot.menu.MenuScroller.MenuScrollTimer


    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(() -> {
            try {
                new Home().setVisible(true);
            } catch (ClassNotFoundException | SQLException ex) {
                Logger.getLogger(Home.class.getName()).log(Level.SEVERE, null, ex);
            }
        });
    }

    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                try {
                    new Home().setVisible(true);
                } catch (ClassNotFoundException ex) {
                    Logger.getLogger(Home.class.getName()).log(Level.SEVERE, null, ex);
                } catch (SQLException ex) {
                    Logger.getLogger(Home.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
        });
    }

Replace Anonymous With Lambda .Home.main.invokeLater.new Runnable with () -> {trynew Home().setVisible(true); in method public main(args String[]) : void from class Home


    public static StringBuilder readSaveFile(File saveFile)
    {
        StringBuilder stringBuilder = new StringBuilder();
        try (BufferedReader bufferedReader = new BufferedReader(new FileReader(saveFile))){
            String line;
            while((line = bufferedReader.readLine()) != null)
            {
                stringBuilder.append(line).append("\n").append("\n");
            }
        } catch (IOException e) {
                logger.error("Save file can't be read");
        }
        return stringBuilder;
    }

    public static StringBuilder readSaveFile(File saveFile)
    {
        StringBuilder stringBuilder = new StringBuilder();
        try {
            BufferedReader bufferedReader = new BufferedReader(new FileReader(saveFile));
            String line;
            while((line = bufferedReader.readLine()) != null)
            {
                stringBuilder.append(line).append("\n").append("\n");
            }
            bufferedReader.close();
        } catch (IOException e) {
                logger.error("Save file can't be read");
        }
        return stringBuilder;
    }

Try With Resources try(BufferedReader bufferedReader=new BufferedReader(new FileReader(saveFile))) in method public readSaveFile(saveFile File) : StringBuilder from class util.FileUtil


    public static void storePerfectFile()
    {
        try (FileWriter fileWriter = new FileWriter(PathUtil.PERFECT_SCORE_FILE)) {
            perfectScoreFile.store(fileWriter, "");
        } catch (IOException e) {
            logger.error("Perfect score file can't be store");
        }
    }

    public static void storePerfectFile()
    {
        try {
            perfectScoreFile.store(new FileWriter(PathUtil.PERFECT_SCORE_FILE), "");
        } catch (IOException e) {
            logger.error("Perfect score file can't be store");
        }
    }

Try With Resources try(FileWriter fileWriter=new FileWriter(PathUtil.PERFECT_SCORE_FILE)) in method public storePerfectFile() : void from class util.FileUtil


    public static void storeCupFile()
    {
        try (FileWriter fileWriter = new FileWriter(PathUtil.CUP_FILE)){
            cupFile.store(fileWriter, "");
        } catch (IOException e) {
            logger.error("Cup file can't be store");
        }
    }

    public static void storeCupFile()
    {
        try {
            cupFile.store(new FileWriter(PathUtil.CUP_FILE), "");
        } catch (IOException e) {
            logger.error("Cup file can't be store");
        }
    }

Try With Resources try(FileWriter fileWriter=new FileWriter(PathUtil.CUP_FILE)) in method public storeCupFile() : void from class util.FileUtil


    public void loadEngTradFile()
    {
        try (FileInputStream fileInputStream = new FileInputStream(PathUtil.ENG_TRAD_PROPERTIES_FILE)) {
            engTradFile.load(fileInputStream);
        } catch (IOException e) {
            logger.error("English trad file can't be load");
        }
    }

    public void loadEngTradFile()
    {
        try {
            engTradFile.load(Files.newInputStream(Path.of(PathUtil.ENG_TRAD_PROPERTIES_FILE)));
        } catch (IOException e) {
            logger.error("English trad file can't be load");
        }
    }

Try With Resources try(FileInputStream fileInputStream=new FileInputStream(PathUtil.ENG_TRAD_PROPERTIES_FILE)) in method public loadEngTradFile() : void from class util.UtilTranslateString


    public void loadFrTradFile()
    {
        try (FileInputStream fileInputStream = new FileInputStream(PathUtil.FR_TRAD_PROPERTIES_FILE)){
            frTradFile.load(fileInputStream);
        } catch (IOException e) {
            logger.error("French trad file can't be load");
        }
    }

    public void loadFrTradFile()
    {
        try {
            frTradFile.load(Files.newInputStream(Path.of(PathUtil.FR_TRAD_PROPERTIES_FILE)));
        } catch (IOException e) {
            logger.error("French trad file can't be load");
        }

    }

Try With Resources try(FileInputStream fileInputStream=new FileInputStream(PathUtil.FR_TRAD_PROPERTIES_FILE)) in method public loadFrTradFile() : void from class util.UtilTranslateString


    public void writeInCupFile(File file, String stringToUse, String lineToReplace)
    {
        try {
            FileWriter fw = new FileWriter(file.getAbsoluteFile());
            try (BufferedWriter bw = new BufferedWriter(fw)) {
                String lineReplacement = lineToReplace.replace(lineToReplace, stringToUse);
                bw.write(lineReplacement);
            }
        }catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void writeInCupFile(File file, String stringToUse, String lineToReplace)
    {
        try {
            FileWriter fw = new FileWriter(file.getAbsoluteFile());
            BufferedWriter bw = new BufferedWriter(fw);
            String lineReplacement = lineToReplace.replace(lineToReplace, stringToUse);
            bw.write(lineReplacement);
            bw.close();
        }catch (IOException e) {
            e.printStackTrace();
        }
    }

Try With Resources try(BufferedWriter bw=new BufferedWriter(fw)) in method public writeInCupFile(file File, stringToUse String, lineToReplace String) : void from class view.TrophyHandler


    public void writeInPerfectCupFile(File file, String stringToUse, String lineToReplace)
    {
        try {
            FileWriter fw = new FileWriter(file.getAbsoluteFile());
            try (BufferedWriter bw = new BufferedWriter(fw)) {
                String lineReplacement = lineToReplace.replace(lineToReplace, stringToUse);
                bw.write(lineReplacement);
            }
        }catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void writeInPerfectCupFile(File file, String stringToUse, String lineToReplace)
    {
        try {
            FileWriter fw = new FileWriter(file.getAbsoluteFile());
            BufferedWriter bw = new BufferedWriter(fw);
            String lineReplacement = lineToReplace.replace(lineToReplace, stringToUse);
            bw.write(lineReplacement);
            bw.close();
        }catch (IOException e) {
            e.printStackTrace();
        }
    }

Try With Resources try(BufferedWriter bw=new BufferedWriter(fw)) in method public writeInPerfectCupFile(file File, stringToUse String, lineToReplace String) : void from class view.ResultScene


    protected void selectProdutoCategoria(String categoria) {
        try (Connection conn = this.connect();){
            String query = "SELECT \n" +
                    "Produtos.Nome, Produtos.Preco " +
                    "FROM " +
                    "Produtos " +
                    "Inner Join Categorias " +
                    "ON Categorias.ID_categoria = Produtos.ID_categoria " +
                    "WHERE " +
                    "Categorias.Nome LIKE ?";

            PreparedStatement pst = conn.prepareStatement(query);
            pst.setString(1, categoria);

            ResultSet rs = pst.executeQuery();

            while (rs.next()) {
                System.out.println(rs.getString("Nome") + "\t" +
                        rs.getString("Preco"));
            }

        } catch (SQLException | ClassNotFoundException e) {
            e.printStackTrace();
        }
    }

    protected void selectProdutoCategoria(String categoria) {
        try {
            String query = "SELECT \n" +
                    "Produtos.Nome, Produtos.Preco " +
                    "FROM " +
                    "Produtos " +
                    "Inner Join Categorias " +
                    "ON Categorias.ID_categoria = Produtos.ID_categoria " +
                    "WHERE " +
                    "Categorias.Nome LIKE ?";
            Connection conn = this.connect();
            PreparedStatement pst = conn.prepareStatement(query);
            pst.setString(1, categoria);

            ResultSet rs = pst.executeQuery();

            while (rs.next()) {
                System.out.println(rs.getString("Nome") + "\t" +
                        rs.getString("Preco"));
            }

        } catch (SQLException | ClassNotFoundException e) {
            e.printStackTrace();
        }
    }

Try With Resources try(Connection conn=this.connect()) in method protected selectProdutoCategoria(categoria String) : void from class tools.Database


    protected void selectProdutoPesquisa(String produto) {
        try (Connection conn = this.connect();){
            String query = "SELECT " +
                    "ID_produto, Nome, Preco " +
                    "FROM Produtos " +
                    "WHERE " +
                    "Nome LIKE ? || '%'";

            PreparedStatement pst = conn.prepareStatement(query);
            pst.setString(1, produto);

            ResultSet rs = pst.executeQuery();

            while (rs.next()) {
                System.out.printf("\nID: %s; \nNome: %s; \nPreco: \n%s;\n",
                        rs.getString("ID_produto"), rs.getString("Nome"),
                        rs.getString("Preco"));
            }

        } catch (SQLException | ClassNotFoundException e) {
            e.printStackTrace();
        }
    }

    protected void selectProdutoPesquisa(String produto) {
        try {
            String query = "SELECT " +
                    "Nome, Preco " +
                    "FROM Produtos " +
                    "WHERE " +
                    "Nome LIKE ? || '%'";
            Connection conn = this.connect();
            PreparedStatement pst = conn.prepareStatement(query);
            pst.setString(1, produto);

            ResultSet rs = pst.executeQuery();

            while (rs.next()) {
                System.out.println(rs.getString("Nome") + "\t" +
                        rs.getString("Preco"));
            }

        } catch (SQLException | ClassNotFoundException e) {
            e.printStackTrace();
        }
    }

Try With Resources try(Connection conn=this.connect()) in method protected selectProdutoPesquisa(produto String) : void from class tools.Database


    protected boolean login(String usuario, String senha, int tipo_usuario) {
        try( Connection conn = this.connect();) {
            String query = "SELECT (count(*) > 0) as found FROM Usuarios " +
                    "WHERE " +
                    "login LIKE ? AND " +
                    "senha LIKE ? AND " +
                    "TipoUsuario = ?";

            PreparedStatement pst = conn.prepareStatement(query);
            pst.setString(1, usuario);
            pst.setString(2, senha);
            pst.setInt(3, tipo_usuario);

            try (ResultSet rs = pst.executeQuery()) {
                if (rs.next()) {
                    return (rs.getBoolean(1));
                }
            }
        } catch (SQLException | ClassNotFoundException e) {
            return false;
        }
        return false;
    }

    protected boolean login(String usuario, String senha, int tipo_usuario) {
        try {
            String query = "SELECT (count(*) > 0) as found FROM Usuarios " +
                    "WHERE " +
                    "login LIKE ? AND " +
                    "senha LIKE ? AND " +
                    "TipoUsuario = ?";
            Connection conn = this.connect();
            PreparedStatement pst = conn.prepareStatement(query);
            pst.setString(1, usuario);
            pst.setString(2, senha);
            pst.setInt(3, tipo_usuario);

            try (ResultSet rs = pst.executeQuery()) {
                if (rs.next()) {
                    return (rs.getBoolean(1));
                }
            }
        } catch (SQLException | ClassNotFoundException e) {
            return false;
        }
        return false;
    }

Try With Resources try(Connection conn=this.connect()) in method protected login(usuario String, senha String, tipo_usuario int) : boolean from class tools.Database


    protected int idUsuario() {
        try (Connection conn = this.connect();){
            String query = "SELECT " +
                    "ID_usuario " +
                    "FROM Usuarios " +
                    "WHERE " +
                    "login LIKE ?";

            PreparedStatement pst = conn.prepareStatement(query);
            pst.setString(1, Crud.USUARIO);
            ResultSet rs = pst.executeQuery();

            while (rs.next()) {
                return rs.getInt("ID_usuario");
            }

        } catch (SQLException | ClassNotFoundException e) {
            e.printStackTrace();
        }
        return 0;
    }

    protected void update(String matricula, String nome) {
        if (this.checkIsExist(matricula)) {
            try {
                String query = "UPDATE alunos SET nome = ? WHERE matricula = ?";
                Connection conn = this.connect();
                PreparedStatement pst = conn.prepareStatement(query);
                pst.setString(1, nome);
                pst.setString(2, matricula);

                pst.executeUpdate();

                System.out.printf("Matricula %s atualizada. \n", matricula);
            } catch (SQLException | ClassNotFoundException e) {
                e.printStackTrace();
            }
        } else {
            System.out.println("Matrícula não encontrada.");
        }
    }

Try With Resources try(Connection conn=this.connect()) in method protected idUsuario() : int from class tools.Database


   /**
    * Constructs a pages.QuestionEditorPage object.
    *
    * @param controller The game controller instance for managing the navigation.
    */
   public QuestionEditorPage(GameController controller) {
      super("Customize Questions");

      this.controller = controller;

      // Set the layout manager
      setLayout(new BorderLayout());

      // Load the image
      try {
         image = ImageIO.read(getClass().getResource("/images/BitsPleaseLogo.jpg")); // Replace with your image path
      } catch (IOException e) {
         e.printStackTrace();
      }
      ImageIcon pageIcon = new ImageIcon(image);
      this.setIconImage(pageIcon.getImage()); // change icon of frame

      lastUpdatedLabel = new JLabel("Last Updated: N/A");
      lastUpdatedLabel.setHorizontalAlignment(SwingConstants.RIGHT);
      lastUpdatedLabel.setFont(lastUpdatedLabel.getFont().deriveFont(Font.BOLD));

      checkbox = new JCheckBox("Use Default Question Bank Trivia Questions?");
      checkbox.addActionListener(e -> {
         JCheckBox source = (JCheckBox) e.getSource();
         if (source.isSelected()) {
            GameData.setUseDefaultQuestions(true);
            refreshQuestions();
            changeComponentEditability(false);
         } else {
            GameData.setUseDefaultQuestions(false);
            refreshQuestions();
            changeComponentEditability(true);
         }
      });

      // Create a panel to hold the last updated label
      JPanel lastUpdatedPanel = new JPanel(new BorderLayout());
      lastUpdatedPanel.add(checkbox, BorderLayout.WEST);
      lastUpdatedPanel.add(lastUpdatedLabel, BorderLayout.EAST);

      // Question Button Panel
      JPanel questionButtonPanel = new JPanel();
      newQuestionButton = new JButton("New Question");
      newQuestionButton.addActionListener(e -> tableModel.addRow(new Object[tableModel.getColumnCount()]));

      saveQuestionButton = new JButton("Save Questions");
      saveQuestionButton.addActionListener(e -> saveQuestions());

      refreshQuestionsButton = new JButton("Refresh Questions");
      refreshQuestionsButton.addActionListener(e -> refreshQuestions());

      deleteQuestionButton = new JButton("Delete Question");
      deleteQuestionButton.addActionListener(e -> deleteSelectedQuestion());
      questionButtonPanel.add(newQuestionButton);
      questionButtonPanel.add(saveQuestionButton);
      questionButtonPanel.add(refreshQuestionsButton);
      questionButtonPanel.add(deleteQuestionButton);

      // Table Panel
      JPanel tablePanel = new JPanel();
      tablePanel.setLayout(new BorderLayout());

      // Create table model with column names
      String[] columnNames = { "Question", "Category", "Answer", "Multiple Choice 1", "Multiple Choice 2",
            "Multiple Choice 3", "Multiple Choice 4", "Difficulty" };
      tableModel = new DefaultTableModel(columnNames, 0);

      // Create table and set table model
      questionTable = new JTable(tableModel);
      JScrollPane scrollPane = new JScrollPane(questionTable);
      tablePanel.add(scrollPane, BorderLayout.CENTER);

      // GUI Control Button Panel
      JPanel buttonPanel = new JPanel();
      JButton backButton = new JButton("Back");
      backButton.addActionListener(e -> controller.showWelcomePage());
      JButton instructionsButton = new JButton("Instructions");
      instructionsButton.addActionListener(e -> controller.showInstructionsPage("EDITOR"));
      buttonPanel.add(instructionsButton);
      buttonPanel.add(backButton);

      // Add components to the frame
      JPanel northPanel = new JPanel(new BorderLayout());
      northPanel.add(lastUpdatedPanel, BorderLayout.NORTH);
      northPanel.add(questionButtonPanel, BorderLayout.SOUTH);

      // Filter Box
      categoryFilterBox = new JComboBox<>();
      populateCategoryFilterBox();
      categoryFilterBox.addActionListener(e -> displayQuestions(tempQuestionList));

      JPanel filterPanel = new JPanel();
      filterPanel.add(new JLabel("Filter by Category:"));
      filterPanel.add(categoryFilterBox);
      northPanel.add(filterPanel, BorderLayout.CENTER);

      add(northPanel, BorderLayout.NORTH);
      add(tablePanel, BorderLayout.CENTER);
      add(buttonPanel, BorderLayout.SOUTH);

      // Set frame properties
      setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

      // Set the size to 75% of the screen's height and width
      Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
      int screenWidth = (int) (screenSize.getWidth() * 0.75);
      int screenHeight = (int) (screenSize.getHeight() * 0.75);
      setSize(screenWidth, screenHeight);

      setLocationRelativeTo(null); // Center the frame on the screen

      // Display the retrieved questions in the table
      try {
         tempQuestionList = Question.retrieveAllClientQuestions();
      } catch (APIRequestException e) {
         tempQuestionList = null;
      }
      refreshQuestions();
      updateLastUpdatedLabel();
      changeComponentEditability(true);
   }

   /**
    * Constructs a pages.QuestionEditorPage object.
    *
    * @param controller The game controller instance for managing the navigation.
    */
   public QuestionEditorPage(GameController controller) {
      super("Customize Questions");

      this.controller = controller;

      // Set the layout manager
      setLayout(new BorderLayout());

      // Load the image
      try {
         image = ImageIO.read(getClass().getResource("/images/BitsPleaseLogo.jpg")); // Replace with your image path
      } catch (IOException e) {
         e.printStackTrace();
      }
      ImageIcon pageIcon = new ImageIcon(image);
      this.setIconImage(pageIcon.getImage()); // change icon of frame

      lastUpdatedLabel = new JLabel("Last Updated: N/A");
      lastUpdatedLabel.setHorizontalAlignment(SwingConstants.RIGHT);
      lastUpdatedLabel.setFont(lastUpdatedLabel.getFont().deriveFont(Font.BOLD));

      checkbox = new JCheckBox("Use Default Question Bank Trivia Questions?");
      checkbox.addChangeListener(new ChangeListener() {
         public void stateChanged(ChangeEvent e) {
            JCheckBox source = (JCheckBox) e.getSource();
            if (source.isSelected()) {
               GameData.setUseDefaultQuestions(true);
               refreshQuestions();
               changeComponentEditability(false);
            } else {
               GameData.setUseDefaultQuestions(false);
               refreshQuestions();
               changeComponentEditability(true);
            }
         }
      });

      // Create a panel to hold the last updated label
      JPanel lastUpdatedPanel = new JPanel(new BorderLayout());
      lastUpdatedPanel.add(checkbox, BorderLayout.WEST);
      lastUpdatedPanel.add(lastUpdatedLabel, BorderLayout.EAST);

      // Question Button Panel
      JPanel questionButtonPanel = new JPanel();
      newQuestionButton = new JButton("New Question");
      newQuestionButton.addActionListener(e -> tableModel.addRow(new Object[tableModel.getColumnCount()]));

      saveQuestionButton = new JButton("Save Questions");
      saveQuestionButton.addActionListener(e -> saveQuestions());

      refreshQuestionsButton = new JButton("Refresh Questions");
      refreshQuestionsButton.addActionListener(e -> refreshQuestions());

      deleteQuestionButton = new JButton("Delete Question");
      deleteQuestionButton.addActionListener(e -> deleteSelectedQuestion());
      questionButtonPanel.add(newQuestionButton);
      questionButtonPanel.add(saveQuestionButton);
      questionButtonPanel.add(refreshQuestionsButton);
      questionButtonPanel.add(deleteQuestionButton);

      // Table Panel
      JPanel tablePanel = new JPanel();
      tablePanel.setLayout(new BorderLayout());

      // Create table model with column names
      String[] columnNames = { "Question", "Category", "Answer", "Multiple Choice 1", "Multiple Choice 2",
            "Multiple Choice 3", "Multiple Choice 4", "Difficulty" };
      tableModel = new DefaultTableModel(columnNames, 0);

      // Create table and set table model
      questionTable = new JTable(tableModel);
      JScrollPane scrollPane = new JScrollPane(questionTable);
      tablePanel.add(scrollPane, BorderLayout.CENTER);

      // GUI Control Button Panel
      JPanel buttonPanel = new JPanel();
      // JButton nextButton = new JButton("Next");
      // nextButton.addActionListener(e -> controller.showGameSettingsPage());
      JButton backButton = new JButton("Back");
      backButton.addActionListener(e -> controller.showWelcomePage());
      JButton instructionsButton = new JButton("Instructions");
      instructionsButton.addActionListener(e -> controller.showInstructionsPage("EDITOR"));
      buttonPanel.add(instructionsButton);
      buttonPanel.add(backButton);
      // buttonPanel.add(nextButton);

      // Add components to the frame
      JPanel northPanel = new JPanel(new BorderLayout());
      northPanel.add(lastUpdatedPanel, BorderLayout.NORTH);
      northPanel.add(questionButtonPanel, BorderLayout.SOUTH);

      // Filter Box
      categoryFilterBox = new JComboBox<>();
      populateCategoryFilterBox();
      categoryFilterBox.addActionListener(e -> displayQuestions(tempQuestionList));

      JPanel filterPanel = new JPanel();
      filterPanel.add(new JLabel("Filter by Category:"));
      filterPanel.add(categoryFilterBox);
      northPanel.add(filterPanel, BorderLayout.CENTER);

      add(northPanel, BorderLayout.NORTH);
      add(tablePanel, BorderLayout.CENTER);
      add(buttonPanel, BorderLayout.SOUTH);

      // Set frame properties
      setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

      // Set the size to 75% of the screen's height and width
      Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
      int screenWidth = (int) (screenSize.getWidth() * 0.75);
      int screenHeight = (int) (screenSize.getHeight() * 0.75);
      setSize(screenWidth, screenHeight);

      setLocationRelativeTo(null); // Center the frame on the screen

      // Display the retrieved questions in the table
      try {
         tempQuestionList = Question.retrieveAllClientQuestions();
      } catch (APIRequestException e) {
         tempQuestionList = null;
      }
      displayQuestions(tempQuestionList);
      updateLastUpdatedLabel();
      changeComponentEditability(true);
   }

Replace Anonymous With Lambda pages.QuestionEditorPage.QuestionEditorPage.addChangeListener.new ChangeListener with e -> {JCheckBox source=(JCheckBox)e.getSource(); in method public QuestionEditorPage(controller GameController) from class pages.QuestionEditorPage


    /**
     * Prints the tree in a breadth first search order This is similar to
     * pre-order traversal, but instead of being implemented with a stack (or
     * recursion), it is implemented with a queue
     *
     * @param localRoot The local root of the binary tree
     */
    public void bfs(Node localRoot) {
        // Create a queue for the order of the nodes
        Queue<Node> queue = new LinkedList<>();

        // If the give root is null, then we don't add to the queue
        // and won't do anything
        if (localRoot != null) {
            queue.add(localRoot);
        }

        // Continue until the queue is empty
        while (!queue.isEmpty()) {
            // Get the next node on the queue to visit
            localRoot = queue.remove();

            // Print the data from the node we are visiting
            System.out.print(localRoot.data + " ");

            // Add the children to the queue if not null
            if (localRoot.right != null) {
                queue.add(localRoot.right);
            }
            if (localRoot.left != null) {
                queue.add(localRoot.left);
            }
        }
    }

    /**
     * Prints the tree in a breadth first search order This is similar to
     * pre-order traversal, but instead of being implemented with a stack (or
     * recursion), it is implemented with a queue
     *
     * @param localRoot The local root of the binary tree
     */
    public void bfs(Node localRoot) {
        // Create a queue for the order of the nodes
        Queue<Node> queue = new LinkedList<Node>();

        // If the give root is null, then we don't add to the queue
        // and won't do anything
        if (localRoot != null) {
            queue.add(localRoot);
        }

        // Continue until the queue is empty
        while (!queue.isEmpty()) {
            // Get the next node on the queue to visit
            localRoot = queue.remove();

            // Print the data from the node we are visiting
            System.out.print(localRoot.data + " ");

            // Add the children to the queue if not null
            if (localRoot.right != null) {
                queue.add(localRoot.right);
            }
            if (localRoot.left != null) {
                queue.add(localRoot.left);
            }
        }
    }

Replace Generic With Diamond LinkedList<Node> with LinkedList<> in method public bfs(localRoot Node) : void from class com.thealgorithms.datastructures.trees.BinaryTree


    private List<User> getUsersFromDB(String query) {
        try (Connection connection =
                     DriverManager.getConnection(JdbcConstants.URL, JdbcConstants.USERNAME, JdbcConstants.PASSWORD)) {

            Statement statement = connection.createStatement();
            ResultSet resultSet = statement.executeQuery(query);
            List<User> users = new ArrayList<>();

            while (resultSet.next()) {
                User user = new User();
                user.setId(resultSet.getInt(1));
                user.setFirstName(resultSet.getString(2));
                user.setLastName(resultSet.getString(3));
                user.setAge(resultSet.getInt(4));
                user.setGender(Gender.valueOf(resultSet.getString(5)));
                users.add(user);
            }

            connection.close();
            return users;
        } catch (SQLException e) {
            throw new RuntimeException(e.getMessage());
        }
    }

    private List<User> getUsersFromDB(Connection connection, String query) {
        try {
            Statement statement = connection.createStatement();
            ResultSet resultSet = statement.executeQuery(query);
            List<User> users = new ArrayList<>();

            while (resultSet.next()) {
                User user = new User();
                user.setId(resultSet.getInt(1));
                user.setFirstName(resultSet.getString(2));
                user.setLastName(resultSet.getString(3));
                user.setAge(resultSet.getInt(4));
                user.setGender(Gender.valueOf(resultSet.getString(5)));
                users.add(user);
            }

            connection.close();
            return users;
        } catch (SQLException e) {
            throw new RuntimeException(e.getMessage());
        }
    }

Try With Resources try(Connection connection=DriverManager.getConnection(JdbcConstants.URL,JdbcConstants.USERNAME,JdbcConstants.PASSWORD)) in method private getUsersFromDB(query String) : List<User> from class com.naidiuk.service.UserServiceImpl


    public void setActions() {
        actions = new ArrayList<>(Arrays.asList(Actions.values()));
    }

    public void setActions() {
        actions = new ArrayList<Actions>(Arrays.asList(Actions.values()));
    }

Replace Generic With Diamond ArrayList<Actions> with ArrayList<> in method public setActions() : void from class it.polimi.ingsw.client.ClientActionController


    public SocketServerConnection() {
        socketListener = new Thread(() -> {
            while (isActive()) {
                Object o = null;
                try {
                    o = receive();
                } catch (IOException | ClassNotFoundException e) {
                    close();

                }
                messageHandler(o);
            }
        });

        pingSender = new Thread(() -> {
            while (isActive()) {
                try {
                    Thread.sleep(10000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                send(new PingMessage());
            }
        });
    }

    public SocketServerConnection() {
        socketListener = new Thread(() -> {
            while (isActive()) {
                Object o = null;
                try {
                    o = receive();
                } catch (IOException e) {
                    close();

                } catch (ClassNotFoundException e) {
                    close();

                }
                messageHandler(o);
            }
        });

        pingSender = new Thread(() -> {
            while (isActive()) {
                try {
                    Thread.sleep(10000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                send(new PingMessage());
            }
        });
    }

Merge Catch [catch(IOException e), catch(ClassNotFoundException e)] to catch(IOException|ClassNotFoundException e) in method public SocketServerConnection() from class it.polimi.ingsw.client.SocketServerConnection


    public Game(int gameID, int numPlayer,  boolean firstvatican, boolean secondvatican, boolean thirdvatican, boolean gameOver) {
        this.gameID = gameID;
        this.numPlayer = numPlayer;
        this.firstvatican = firstvatican;
        this.secondvatican = secondvatican;
        this.thirdvatican = thirdvatican;
        this.gameOver = gameOver;
        this.board = new Board();
        this.turn = new Turn();
        this.players = new ArrayList<>();
        this.communication = new Communication();
    }

    public Game(int gameID, int numPlayer,  boolean firstvatican, boolean secondvatican, boolean thirdvatican, boolean gameOver) {
        this.gameID = gameID;
        this.numPlayer = numPlayer;
        this.firstvatican = firstvatican;
        this.secondvatican = secondvatican;
        this.thirdvatican = thirdvatican;
        this.gameOver = gameOver;
        this.board = new Board();
        this.turn = new Turn();
        this.players = new ArrayList<Player>();
        this.communication = new Communication();
    }

Replace Generic With Diamond ArrayList<Player> with ArrayList<> in method public Game(gameID int, numPlayer int, firstvatican boolean, secondvatican boolean, thirdvatican boolean, gameOver boolean) from class it.polimi.ingsw.model.Game


    public Game clone(){
        Game clone = new Game();
        clone.gameID = this.gameID;
        clone.numPlayer = this.numPlayer;
        clone.firstvatican = this.firstvatican;
        clone.secondvatican = this.secondvatican;
        clone.thirdvatican = this.thirdvatican;
        clone.gameOver = this.gameOver;
        clone.board = board.clone();
        clone.turn  = turn.clone();
        clone.communication = communication.clone();
        clone.players = new ArrayList<>();

        for (Player p: this.players){
            clone.players.add(p.clone());
        }

        return clone;
    }

    public Game clone(){
        Game clone = new Game();
        clone.gameID = this.gameID;
        clone.numPlayer = this.numPlayer;
        clone.firstvatican = this.firstvatican;
        clone.secondvatican = this.secondvatican;
        clone.thirdvatican = this.thirdvatican;
        clone.gameOver = this.gameOver;
        clone.board = board.clone();
        clone.turn  = turn.clone();
        clone.communication = communication.clone();
        clone.players = new ArrayList<Player>();

        for (Player p: this.players){
            clone.players.add(p.clone());
        }

        return clone;
    }

Replace Generic With Diamond ArrayList<Player> with ArrayList<> in method public clone() : Game from class it.polimi.ingsw.model.Game


    private void printLeftOut() {
        String color = this.marbleOut.getRes().getColor();
        ArrayList<Ball> b= new ArrayList<>(Arrays.asList(Ball.values()));
        for (Ball ball : b)  {
            if (ball.toString().equals("Ball1"))  {
            System.out.println(color +  ball.getBallLine() + Color.ANSI_RESET);
        }
        else {
                System.out.println(color + "                   " +  ball.getBallLine() + Color.ANSI_RESET);
            }
        }
    }

    private void printLeftOut() {
        String color = this.marbleOut.getRes().getColor();
        ArrayList<Ball> b= new ArrayList<Ball>(Arrays.asList(Ball.values()));
        for (Ball ball : b)  {
            if (ball.toString().equals("Ball1"))  {
            System.out.println(color +  ball.getBallLine() + Color.ANSI_RESET);
        }
        else {
                System.out.println(color + "                   " +  ball.getBallLine() + Color.ANSI_RESET);
            }
        }
    }

Replace Generic With Diamond ArrayList<Ball> with ArrayList<> in method private printLeftOut() : void from class it.polimi.ingsw.model.Market


    private void printRow(List<Marble> asList) {
        ArrayList<Ball> b = new ArrayList<>(Arrays.asList(Ball.values()));
        for (Ball ball : b) {
            String ballLine = ball.getBallLine();
            System.out.println(asList.get(0).getRes().getColor() + ballLine +
                    asList.get(1).getRes().getColor() + ballLine +
                    asList.get(2).getRes().getColor() + ballLine +
                    asList.get(3).getRes().getColor() + ballLine + Color.ANSI_RESET);
        }
    }

    private void printRow(List<Marble> asList) {
        ArrayList<Ball> b = new ArrayList<Ball>(Arrays.asList(Ball.values()));
        for (Ball ball : b) {
            String ballLine = ball.getBallLine();
            System.out.println(asList.get(0).getRes().getColor() + ballLine +
                    asList.get(1).getRes().getColor() + ballLine +
                    asList.get(2).getRes().getColor() + ballLine +
                    asList.get(3).getRes().getColor() + ballLine + Color.ANSI_RESET);
        }
    }

Replace Generic With Diamond ArrayList<Ball> with ArrayList<> in method private printRow(asList List<Marble>) : void from class it.polimi.ingsw.model.Market


    public ShelfWarehouse() {
        ArrayList<Shelf> s = new ArrayList<>();
        s.add(new Shelf(ResourceType.EMPTY, 0));
        s.add(new Shelf(ResourceType.EMPTY, 0));
        s.add(new Shelf(ResourceType.EMPTY, 0));
        s.add(new Shelf(null, 0));
        s.add(new Shelf(null, 0));
        this.shelves = s;
    }

    public ShelfWarehouse() {
        ArrayList<Shelf> s = new ArrayList<Shelf>();
        s.add(new Shelf(ResourceType.EMPTY, 0));
        s.add(new Shelf(ResourceType.EMPTY, 0));
        s.add(new Shelf(ResourceType.EMPTY, 0));
        s.add(new Shelf(null, 0));
        s.add(new Shelf(null, 0));
        this.shelves = s;
    }

Replace Generic With Diamond ArrayList<Shelf> with ArrayList<> in method public ShelfWarehouse() from class it.polimi.ingsw.model.ShelfWarehouse


    public Strongbox() {
        this.infinityShelf = new ArrayList<>();
        this.infinityShelf.add(0, new Shelf(ResourceType.COIN, 0));
        this.infinityShelf.add(1, new Shelf(ResourceType.STONE, 0));
        this.infinityShelf.add(2, new Shelf(ResourceType.SERVANT, 0));
        this.infinityShelf.add(3, new Shelf(ResourceType.SHIELD, 0));
        this.earnedCoin = 0;
        this.earnedServant = 0;
        this.earnedShield = 0;
        this.earnedStone = 0;
    }

    public Strongbox() {
        this.infinityShelf = new ArrayList<Shelf>();
        this.infinityShelf.add(0, new Shelf(ResourceType.COIN, 0));
        this.infinityShelf.add(1, new Shelf(ResourceType.STONE, 0));
        this.infinityShelf.add(2, new Shelf(ResourceType.SERVANT, 0));
        this.infinityShelf.add(3, new Shelf(ResourceType.SHIELD, 0));
        this.earnedCoin = 0;
        this.earnedServant = 0;
        this.earnedShield = 0;
        this.earnedStone = 0;
    }

Replace Generic With Diamond ArrayList<Shelf> with ArrayList<> in method public Strongbox() from class it.polimi.ingsw.model.Strongbox


    public Strongbox() {
//        this.coinNum = coinNum;
//        this.stoneNum = stoneNum;
//        this.servantNum = servantNum;
//        this.shieldNum = shieldNum;
        this.infinityShelf = new ArrayList<>();
        this.infinityShelf.add(0, new Shelf(ResourceType.COIN, 0));
        this.infinityShelf.add(1, new Shelf(ResourceType.STONE, 0));
        this.infinityShelf.add(2, new Shelf(ResourceType.SERVANT, 0));
        this.infinityShelf.add(3, new Shelf(ResourceType.SHIELD, 0));
        this.earnedCoin = 0;
        this.earnedServant = 0;
        this.earnedShield = 0;
        this.earnedStone = 0;
    }

    public Strongbox() {
//        this.coinNum = coinNum;
//        this.stoneNum = stoneNum;
//        this.servantNum = servantNum;
//        this.shieldNum = shieldNum;
        this.infinityShelf = new ArrayList<Shelf>();
        this.infinityShelf.add(0, new Shelf(ResourceType.COIN, 0));
        this.infinityShelf.add(1, new Shelf(ResourceType.STONE, 0));
        this.infinityShelf.add(2, new Shelf(ResourceType.SERVANT, 0));
        this.infinityShelf.add(3, new Shelf(ResourceType.SHIELD, 0));
        this.earnedCoin = 0;
        this.earnedServant = 0;
        this.earnedShield = 0;
        this.earnedStone = 0;
    }


    /**
     * XLSファイルから値を抽出する.
     *
     * @param templateFile
     *            エクセルファイル解析に使用するXMLファイル
     * @param excelFile
     *            エクセルファイル
     * @param model
     *            抽出した値を設定するオブジェクトを格納したMap
     * @return エクセルファイル解析結果
     * @throws InvalidFormatException
     *             {@link InvalidFormatException}
     * @throws IOException
     *             {@link IOException}
     * @throws SAXException
     *             {@link SAXException}
     */
    public XLSReadStatus read(Resource templateFile, MultipartFile excelFile, Map<?, ?> model) throws InvalidFormatException, IOException, SAXException {
        try (InputStream templateInputStream = templateFile.getInputStream();
                InputStream excelInputStream = excelFile.getInputStream();) {
            ReaderConfig.getInstance().setSkipErrors(true);

            return ReaderBuilder.buildFromXML(templateInputStream).read(excelInputStream, model);
        }
    }

    /**
     * XLSファイルから値を抽出する.
     *
     * @param templateFile
     *            エクセルファイル解析に使用するXMLファイル
     * @param excelFile
     *            エクセルファイル
     * @param model
     *            抽出した値を設定するオブジェクトを格納したMap
     * @return エクセルファイル解析結果
     * @throws InvalidFormatException
     *             {@link InvalidFormatException}
     * @throws IOException
     *             {@link IOException}
     * @throws SAXException
     *             {@link SAXException}
     */
    public XLSReadStatus read(Resource templateFile, MultipartFile excelFile, Map<?, ?> model) throws InvalidFormatException, IOException, SAXException {
        InputStream templateInputStream = null;
        InputStream excelInputStream = null;

        try {
            ReaderConfig.getInstance().setSkipErrors(true);
            templateInputStream = templateFile.getInputStream();
            excelInputStream = excelFile.getInputStream();

            return ReaderBuilder.buildFromXML(templateInputStream).read(excelInputStream, model);
        } finally {
            IOUtils.closeQuietly(templateInputStream);
            IOUtils.closeQuietly(excelInputStream);
        }
    }

Try With Resources try(InputStream templateInputStream=templateFile.getInputStream(); InputStream excelInputStream=excelFile.getInputStream()) in method public read(templateFile Resource, excelFile MultipartFile, model Map<?,?>) : XLSReadStatus from class common.webapp.converter.util.JxlsFileReader


    /**
     * {@inheritDoc}
     */
    @Override
    protected void renderMergedOutputModel(Map<String, Object> model, HttpServletRequest request, HttpServletResponse response) throws IOException {
        try (InputStream is = getTemplateSource(getUrl(), request);
                OutputStream os = response.getOutputStream()) {
            Transformer transformer = TransformerFactory.createTransformer(is, os);
            ((JexlExpressionEvaluator) transformer.getTransformationConfig().getExpressionEvaluator()).getJexlEngine().setSilent(true);
            AreaBuilder areaBuilder = new XlsCommentAreaBuilder(transformer);
            List<Area> xlsAreaList = areaBuilder.build();
            Area xlsArea = xlsAreaList.get(0);
            Context context = new Context();

            model.entrySet().forEach(mode -> context.putVar(mode.getKey(), mode.getValue()));

            xlsArea.applyAt(new CellRef("Sheet1!A1"), context);
            transformer.write();
        }
    }

    /**
     * {@inheritDoc}
     */
    @Override
    protected void renderMergedOutputModel(Map<String, Object> model, HttpServletRequest request, HttpServletResponse response) throws IOException {
        InputStream is = null;
        OutputStream os = null;

        try {
            is = getTemplateSource(getUrl(), request);
            os = response.getOutputStream();

            Transformer transformer = TransformerFactory.createTransformer(is, os);
            ((JexlExpressionEvaluator) transformer.getTransformationConfig().getExpressionEvaluator()).getJexlEngine().setSilent(true);
            AreaBuilder areaBuilder = new XlsCommentAreaBuilder(transformer);
            List<Area> xlsAreaList = areaBuilder.build();
            Area xlsArea = xlsAreaList.get(0);
            Context context = new Context();

            model.entrySet().forEach(mode -> context.putVar(mode.getKey(), mode.getValue()));

            xlsArea.applyAt(new CellRef("Sheet1!A1"), context);
            transformer.write();
        } finally {
            IOUtils.closeQuietly(is);
            IOUtils.closeQuietly(os);
        }
    }

Try With Resources try(InputStream is=getTemplateSource(getUrl(),request); OutputStream os=response.getOutputStream()) in method protected renderMergedOutputModel(model Map<String,Object>, request HttpServletRequest, response HttpServletResponse) : void from class common.webapp.converter.util.JxlsView