    @Bean
    public RestHighLevelClient restHighLevelClient() {

        final CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
        credentialsProvider.setCredentials(AuthScope.ANY,
                //es账号密码
                new UsernamePasswordCredentials(esProperties.getUsername(), esProperties.getPassword()));

        return new RestHighLevelClient(
                RestClient.builder(
                        new HttpHost(esProperties.getHost(), esProperties.getPort(), "http"))
                        .setHttpClientConfigCallback(httpClientBuilder -> {
                            //这里可以设置一些参数，比如cookie存储、代理等等
                            httpClientBuilder.disableAuthCaching();
                            return httpClientBuilder.setDefaultCredentialsProvider(credentialsProvider);
                        })
        );

    }

    @Bean
    public RestHighLevelClient restHighLevelClient() {

        final CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
        credentialsProvider.setCredentials(AuthScope.ANY,
                //es账号密码
                new UsernamePasswordCredentials(esProperties.getUsername(), esProperties.getPassword()));

        return new RestHighLevelClient(
                RestClient.builder(
                        new HttpHost(esProperties.getHost(), esProperties.getPort(), "http"))
                        .setHttpClientConfigCallback(new RestClientBuilder.HttpClientConfigCallback() {
                            public HttpAsyncClientBuilder customizeHttpClient(HttpAsyncClientBuilder httpClientBuilder) {
                                //这里可以设置一些参数，比如cookie存储、代理等等
                                httpClientBuilder.disableAuthCaching();
                                return httpClientBuilder.setDefaultCredentialsProvider(credentialsProvider);
                            }
                        })
        );

    }

Replace Anonymous With Lambda com.weweibuy.learning.es.rest.config.ESRestClientConfig.restHighLevelClient.new RestHighLevelClient.setHttpClientConfigCallback.new RestClientBuilder.HttpClientConfigCallback with httpClientBuilder -> {httpClientBuilder.disableAuthCaching(); in method public restHighLevelClient() : RestHighLevelClient from class com.weweibuy.learning.es.rest.config.ESRestClientConfig


    public static<T> CommonJsonResponse success(T data){
        return new CommonJsonResponse<>(CommonStatus.SUCCESS.toString(), null, null, data);
    }

    public static<T> CommonJsonResponse success(T data){
        return new CommonJsonResponse<T>(CommonStatus.SUCCESS.toString(), null, null, data);
    }

Replace Generic With Diamond CommonJsonResponse<T> with CommonJsonResponse<> in method public success(data T) : CommonJsonResponse from class com.weweibuy.webuy.common.dto.CommonJsonResponse


    public void playSound(String path, Float volume, boolean loop) {

        if(settings.equalsIgnoreCase("on")){
            volume=volume+this.generalVolume;

            //read audio data from whatever source (path)
            InputStream audioSrc = getClass().getResourceAsStream(path);

            //add buffer for mark/reset support (così funziona anche nel jar)
            InputStream bufferedIn = new BufferedInputStream(audioSrc);

            AudioInputStream audioInputStream = null;
            try {
                audioInputStream = AudioSystem.getAudioInputStream(bufferedIn);
                this.clip = AudioSystem.getClip();
                this.clip.open(audioInputStream);
            } catch (UnsupportedAudioFileException | IOException | LineUnavailableException e) {
                e.printStackTrace();
            }

            FloatControl gainControl = (FloatControl) clip.getControl(FloatControl.Type.MASTER_GAIN);//per controllare il volume
            gainControl.setValue(volume); // Reduce volume by "volume" decibels.

            if (loop) clip.loop(Clip.LOOP_CONTINUOUSLY);
            this.clip.start();
        }

    }

    public void playSound(String path, Float volume, Boolean loop) {

        if(settings.equalsIgnoreCase("on")){
            volume=volume+this.generalVolume;

            //read audio data from whatever source (path)
            InputStream audioSrc = getClass().getResourceAsStream(path);

            //add buffer for mark/reset support (così funziona anche nel jar)
            InputStream bufferedIn = new BufferedInputStream(audioSrc);

            AudioInputStream audioInputStream = null;
            try {
                audioInputStream = AudioSystem.getAudioInputStream(bufferedIn);
                this.clip = AudioSystem.getClip();
                this.clip.open(audioInputStream);
            } catch (UnsupportedAudioFileException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            } catch (LineUnavailableException e) {
                e.printStackTrace();
            }

            FloatControl gainControl = (FloatControl) clip.getControl(FloatControl.Type.MASTER_GAIN);//per controllare il volume
            gainControl.setValue(volume); // Reduce volume by "volume" decibels.

            if (loop) clip.loop(Clip.LOOP_CONTINUOUSLY);
            this.clip.start();
        }

    }

Merge Catch [catch(UnsupportedAudioFileException e), catch(IOException e), catch(LineUnavailableException e)] to catch(UnsupportedAudioFileException|IOException|LineUnavailableException e) in method public playSound(path String, volume Float, loop boolean) : void from class it.polimi.ingsw.view.GUIpackage.MakeSound


    public void setGod(int id, String god) {
        String[] toRemove = new String[2];
        for (String[] s : chosenGods) {
            if (s[0].equalsIgnoreCase(god)) {
                getPlayer(id).setGod(s);
                toRemove = s;
            }
        }
        chosenGods.remove(toRemove);
        ArrayList<String> godSelected= new ArrayList<>();
        godSelected.add(getPlayer(id).nickname);
        godSelected.add(god);
        selectedSingleGodListener.firePropertyChange("notifyGodSelected",null, godSelected);

    }

    public void setGod(int id, String god) {
        String[] toRemove = new String[2];
        for (String[] s : chosenGods) {
            if (s[0].equalsIgnoreCase(god)) {
                getPlayer(id).setGod(s);
                toRemove = s;
            }
        }
        chosenGods.remove(toRemove);
        ArrayList<String> godSelected= new ArrayList<String>();
        godSelected.add(getPlayer(id).nickname);
        godSelected.add(god);
        selectedSingleGodListener.firePropertyChange("notifyGodSelected",null, godSelected);

    }

Replace Generic With Diamond ArrayList<String> with ArrayList<> in method public setGod(id int, god String) : void from class it.polimi.ingsw.view.ModelView


    public TreeActionNode(Action data){
        this.data = data;
        this.children = new ArrayList<>();
    }

    public TreeActionNode(Action data){
        this.data = data;
        this.children = new ArrayList<TreeActionNode>();
    }

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


    public void start() {
        try {
            this.online = true;
            inputStream = new ObjectInputStream(socket.getInputStream());
            printStream = new ObjectOutputStream(socket.getOutputStream());

            new Thread(() -> {
                try {
                    while (true) {
                        final Object inputObject = inputStream.readObject();

                        if (inputObject instanceof PropertyChangeEvent) {;
                            view.notifyEvent((PropertyChangeEvent) inputObject);
                        } else if (inputObject instanceof SetupMessage) {
                            view.askNumOfPlayers();
                        }

                    }
                } catch (IOException | ClassNotFoundException e) {
                    logger.log(Level.SEVERE, e.getMessage());
                    e.printStackTrace();

                }
            }).start();
        } catch (IOException e) {
            logger.log(Level.SEVERE, e.getMessage());
        }
    }

    public void start() {
        try {
            this.online = true;
            inputStream = new ObjectInputStream(socket.getInputStream());
            printStream = new ObjectOutputStream(socket.getOutputStream());

            new Thread(new Runnable() {
                @Override
                public void run() {
                    try {
                        while (true) {
                            final Object inputObject = inputStream.readObject();

                            if (inputObject instanceof PropertyChangeEvent) {;
                                view.notifyEvent((PropertyChangeEvent) inputObject);
                            } else if (inputObject instanceof SetupMessage) {
                                view.askNumOfPlayers();
                            }

                        }
                    } catch (IOException | ClassNotFoundException e) {
                        logger.log(Level.SEVERE, e.getMessage());
                        e.printStackTrace();

                    }
                }
            }).start();
        } catch (IOException e) {
            logger.log(Level.SEVERE, e.getMessage());
        }
    }

Replace Anonymous With Lambda it.polimi.ingsw.network.Client.start.start.new Thread.new Runnable with () -> {trywhile(true){final Object inputObject=inputStream.readObject(); in method public start() : void from class it.polimi.ingsw.network.Client


    /**
     * Load all the courses' information from file into the system.
     *
     * @return a list of all the courses.
     */
    public static List<Course> loadCourses() {
        ObjectMapper objectMapper = new ObjectMapper();
        File courseFile = Paths.get(courseFileName).toFile();
        ArrayList<Course> allCourses = new ArrayList<>();

        try {
            allCourses = new ArrayList<>(Arrays.asList(objectMapper.readValue(courseFile, Course[].class)));
        } catch (IOException e) {
            System.out.println("Error happens when loading courses.");
            e.printStackTrace();
        }

        return allCourses;
    }

    /**
     * Load all the courses' information from file into the system.
     *
     * @return a list of all the courses.
     */
    public static List<Course> loadCourses() {
        ObjectMapper objectMapper = new ObjectMapper();
        File courseFile = Paths.get(courseFileName).toFile();
        ArrayList<Course> allCourses = new ArrayList<>();

        try {
            allCourses = new ArrayList<Course>(Arrays.asList(objectMapper.readValue(courseFile, Course[].class)));
        } catch (IOException e) {
            System.out.println("Error happens when loading courses.");
            e.printStackTrace();
        }

        return allCourses;
    }

Replace Generic With Diamond ArrayList<Course> with ArrayList<> in method public loadCourses() : List<Course> from class com.softeng306.io.FILEMgr


    /**
     * Load all the students' information from file into the system.
     *
     * @return a list of all the students.
     */
    public static List<Student> loadStudents() {
        BufferedReader fileReader = null;
        List<Student> students = new ArrayList<>(0);
        try {
            String line;
            fileReader = new BufferedReader(new FileReader(studentFileName));
            fileReader.readLine();//read the header to skip it
            int recentStudentID = 0;
            while ((line = fileReader.readLine()) != null) {
                String[] tokens = line.split(COMMA_DELIMITER);
                if (tokens.length > 0) {
                    recentStudentID = Math.max(recentStudentID, Integer.parseInt(tokens[studentIdIndex].substring(1, 8)));
                    Student student = new Student(tokens[studentIdIndex], tokens[studentNameIndex]);
                    student.setStudentSchool(tokens[studentSchoolIndex]);
                    student.setGender(tokens[studentGenderIndex]);
                    student.setGPA(Double.parseDouble(tokens[studentGPAIndex]));
                    student.setStudentYear(Integer.parseInt(tokens[studentYearIndex]));
                    students.add(student);
                }
            }
            // Set the recent student ID, let the newly added student have the ID onwards.
            // If there is no student in DB, set recentStudentID to 1800000 (2018 into Uni)

            Student.setIdNumber(recentStudentID > 0 ? recentStudentID : 1800000);
        } catch (Exception e) {
            System.out.println("Error occurs when loading students.");
            e.printStackTrace();
        } finally {
            try {
                fileReader.close();
            } catch (IOException e) {
                System.out.println("Error occurs when closing the fileReader.");
                e.printStackTrace();
            }
        }
        return students;
    }

    /**
     * Load all the students' information from file into the system.
     *
     * @return a list of all the students.
     */
    public static List<Student> loadStudents() {
        BufferedReader fileReader = null;
        List<Student> students = new ArrayList<Student>(0);
        try {
            String line;
            fileReader = new BufferedReader(new FileReader(studentFileName));
            fileReader.readLine();//read the header to skip it
            int recentStudentID = 0;
            while ((line = fileReader.readLine()) != null) {
                String[] tokens = line.split(COMMA_DELIMITER);
                if (tokens.length > 0) {
                    recentStudentID = Math.max(recentStudentID, Integer.parseInt(tokens[studentIdIndex].substring(1, 8)));
                    Student student = new Student(tokens[studentIdIndex], tokens[studentNameIndex]);
                    student.setStudentSchool(tokens[studentSchoolIndex]);
                    student.setGender(tokens[studentGenderIndex]);
                    student.setGPA(Double.parseDouble(tokens[studentGPAIndex]));
                    student.setStudentYear(Integer.parseInt(tokens[studentYearIndex]));
                    students.add(student);
                }
            }
            // Set the recent student ID, let the newly added student have the ID onwards.
            // If there is no student in DB, set recentStudentID to 1800000 (2018 into Uni)

            Student.setIdNumber(recentStudentID > 0 ? recentStudentID : 1800000);
        } catch (Exception e) {
            System.out.println("Error occurs when loading students.");
            e.printStackTrace();
        } finally {
            try {
                fileReader.close();
            } catch (IOException e) {
                System.out.println("Error occurs when closing the fileReader.");
                e.printStackTrace();
            }
        }
        return students;
    }

Replace Generic With Diamond ArrayList<Student> with ArrayList<> in method public loadStudents() : List<Student> from class com.softeng306.io.FILEMgr


    /**
     * Load all the professors' information from file into the system.
     *
     * @return a list of all the professors.
     */
    public static List<Professor> loadProfessors() {
        BufferedReader fileReader = null;
        List<Professor> professors = new ArrayList<>(0);
        try {
            String line;
            fileReader = new BufferedReader(new FileReader(professorFileName));
            //read the header to skip it
            fileReader.readLine();
            while ((line = fileReader.readLine()) != null) {
                String[] tokens = line.split(COMMA_DELIMITER);
                if (tokens.length > 0) {
                    Professor professor = new Professor(tokens[professorIdIndex], tokens[professorNameIndex]);
                    professor.setProfDepartment(tokens[professorDepartmentIndex]);
                    professors.add(professor);
                }
            }
        } catch (Exception e) {
            System.out.println("Error occurs when loading professors.");
            e.printStackTrace();
        } finally {
            try {
                fileReader.close();
            } catch (IOException e) {
                System.out.println("Error occurs when closing the fileReader.");
                e.printStackTrace();
            }
        }
        return professors;
    }

    /**
     * Load all the professors' information from file into the system.
     *
     * @return a list of all the professors.
     */
    public static List<Professor> loadProfessors() {
        BufferedReader fileReader = null;
        List<Professor> professors = new ArrayList<Professor>(0);
        try {
            String line;
            fileReader = new BufferedReader(new FileReader(professorFileName));
            //read the header to skip it
            fileReader.readLine();
            while ((line = fileReader.readLine()) != null) {
                String[] tokens = line.split(COMMA_DELIMITER);
                if (tokens.length > 0) {
                    Professor professor = new Professor(tokens[professorIdIndex], tokens[professorNameIndex]);
                    professor.setProfDepartment(tokens[professorDepartmentIndex]);
                    professors.add(professor);
                }
            }
        } catch (Exception e) {
            System.out.println("Error occurs when loading professors.");
            e.printStackTrace();
        } finally {
            try {
                fileReader.close();
            } catch (IOException e) {
                System.out.println("Error occurs when closing the fileReader.");
                e.printStackTrace();
            }
        }
        return professors;
    }

Replace Generic With Diamond ArrayList<Professor> with ArrayList<> in method public loadProfessors() : List<Professor> from class com.softeng306.io.FILEMgr


    /**
     * Load all the course registration records from file into the system.
     *
     * @return a list of all the course registration records.
     */
    public static List<CourseRegistration> loadCourseRegistration() {
        BufferedReader fileReader = null;
        List<CourseRegistration> courseRegistrations = new ArrayList<>(0);
        try {
            String line;
            Student currentStudent = null;
            Course currentCourse = null;
            List<Student> students = loadStudents();

            fileReader = new BufferedReader(new FileReader(courseRegistrationFileName));
            fileReader.readLine();//read the header to skip it

            while ((line = fileReader.readLine()) != null) {
                String[] tokens = line.split(COMMA_DELIMITER);
                if (tokens.length > 0) {
                    String studentID = tokens[studentIdInRegistrationIndex];

                    for (Student student : students) {
                        if (student.getStudentID().equals(studentID)) {
                            currentStudent = student;
                            break;
                        }
                    }
                    String courseID = tokens[courseIdInRegistrationIndex];
                    List<Course> courses = loadCourses();
                    for (Course course : courses) {
                        if (course.getCourseID().equals(courseID)) {
                            currentCourse = course;
                            break;
                        }
                    }
                    courseRegistrations.add(new CourseRegistration(currentStudent, currentCourse, tokens[lectureGroupInRegistrationIndex], tokens[tutorialGroupInRegistrationIndex], tokens[labGroupInRegistrationIndex]));
                }
            }
        } catch (Exception e) {
            System.out.println("Error occurs when loading course registrations.");
            e.printStackTrace();
        } finally {
            try {
                fileReader.close();
            } catch (IOException e) {
                System.out.println("Error occurs when closing the fileReader.");
                e.printStackTrace();
            }
        }
        return courseRegistrations;
    }

    /**
     * Load all the course registration records from file into the system.
     *
     * @return a list of all the course registration records.
     */
    public static List<CourseRegistration> loadCourseRegistration() {
        BufferedReader fileReader = null;
        List<CourseRegistration> courseRegistrations = new ArrayList<CourseRegistration>(0);
        try {
            String line;
            Student currentStudent = null;
            Course currentCourse = null;
            List<Student> students = loadStudents();

            fileReader = new BufferedReader(new FileReader(courseRegistrationFileName));
            fileReader.readLine();//read the header to skip it

            while ((line = fileReader.readLine()) != null) {
                String[] tokens = line.split(COMMA_DELIMITER);
                if (tokens.length > 0) {
                    String studentID = tokens[studentIdInRegistrationIndex];

                    for (Student student : students) {
                        if (student.getStudentID().equals(studentID)) {
                            currentStudent = student;
                            break;
                        }
                    }
                    String courseID = tokens[courseIdInRegistrationIndex];
                    List<Course> courses = loadCourses();
                    for (Course course : courses) {
                        if (course.getCourseID().equals(courseID)) {
                            currentCourse = course;
                            break;
                        }
                    }
                    courseRegistrations.add(new CourseRegistration(currentStudent, currentCourse, tokens[lectureGroupInRegistrationIndex], tokens[tutorialGroupInRegistrationIndex], tokens[labGroupInRegistrationIndex]));
                }
            }
        } catch (Exception e) {
            System.out.println("Error occurs when loading course registrations.");
            e.printStackTrace();
        } finally {
            try {
                fileReader.close();
            } catch (IOException e) {
                System.out.println("Error occurs when closing the fileReader.");
                e.printStackTrace();
            }
        }
        return courseRegistrations;
    }

Replace Generic With Diamond ArrayList<CourseRegistration> with ArrayList<> in method public loadCourseRegistration() : List<CourseRegistration> from class com.softeng306.io.FILEMgr


    /**
     * Gets all the departments as a list.
     *
     * @return a list of all the departments.
     */
    public static List<String> getAllDepartment() {
        Set<Department> departmentEnumSet = EnumSet.allOf(Department.class);
        List<String> departmentStringList = new ArrayList<>(0);
        Iterator iter = departmentEnumSet.iterator();
        while (iter.hasNext()) {
            departmentStringList.add(iter.next().toString());
        }
        return departmentStringList;

    }

    /**
     * Gets all the departments as a list.
     *
     * @return a list of all the departments.
     */
    public static List<String> getAllDepartment() {
        Set<Department> departmentEnumSet = EnumSet.allOf(Department.class);
        List<String> departmentStringList = new ArrayList<String>(0);
        Iterator iter = departmentEnumSet.iterator();
        while (iter.hasNext()) {
            departmentStringList.add(iter.next().toString());
        }
        return departmentStringList;

    }

Replace Generic With Diamond ArrayList<String> with ArrayList<> in method public getAllDepartment() : List<String> from class com.softeng306.io.HelpInfoMgr


    /**
     * Gets all the genders as a list.
     *
     * @return a list of all the genders.
     */
    public static List<String> getAllGender() {
        Set<Gender> genderEnumSet = EnumSet.allOf(Gender.class);
        List<String> genderStringList = new ArrayList<>(0);
        Iterator iter = genderEnumSet.iterator();
        while (iter.hasNext()) {
            genderStringList.add(iter.next().toString());
        }
        return genderStringList;
    }

    /**
     * Gets all the genders as a list.
     *
     * @return a list of all the genders.
     */
    public static List<String> getAllGender() {
        Set<Gender> genderEnumSet = EnumSet.allOf(Gender.class);
        List<String> genderStringList = new ArrayList<String>(0);
        Iterator iter = genderEnumSet.iterator();
        while (iter.hasNext()) {
            genderStringList.add(iter.next().toString());
        }
        return genderStringList;
    }

Replace Generic With Diamond ArrayList<String> with ArrayList<> in method public getAllGender() : List<String> from class com.softeng306.io.HelpInfoMgr


    /**
     * Gets all the course types as a list.
     *
     * @return a list of all the course types.
     */
    public static List<String> getAllCourseType() {
        Set<CourseType> courseTypeEnumSet = EnumSet.allOf(CourseType.class);
        List<String> courseTypeStringSet = new ArrayList<>(0);
        Iterator iter = courseTypeEnumSet.iterator();
        while (iter.hasNext()) {
            courseTypeStringSet.add(iter.next().toString());
        }
        return courseTypeStringSet;
    }

    /**
     * Gets all the course types as a list.
     *
     * @return a list of all the course types.
     */
    public static List<String> getAllCourseType() {
        Set<CourseType> courseTypeEnumSet = EnumSet.allOf(CourseType.class);
        List<String> courseTypeStringSet = new ArrayList<String>(0);
        Iterator iter = courseTypeEnumSet.iterator();
        while (iter.hasNext()) {
            courseTypeStringSet.add(iter.next().toString());
        }
        return courseTypeStringSet;
    }

Replace Generic With Diamond ArrayList<String> with ArrayList<> in method public getAllCourseType() : List<String> from class com.softeng306.io.HelpInfoMgr


    /**
     * Prints the students in a course according to their lecture group, tutorial group or lab group.
     */
    public static void printStudents() {
        System.out.println("printStudent is called");
        Course currentCourse = CourseValidator.checkCourseExists();

        System.out.println("Print student by: ");
        System.out.println("(1) Lecture group");
        System.out.println("(2) Tutorial group");
        System.out.println("(3) Lab group");
        // READ courseRegistrationFILE
        // return List of Object(student,course,lecture,tut,lab)
        List<CourseRegistration> allStuArray = FILEMgr.loadCourseRegistration();

        List<CourseRegistration> stuArray = new ArrayList<>(0);
        for (CourseRegistration courseRegistration : allStuArray) {
            if (courseRegistration.getCourse().getCourseID().equals(currentCourse.getCourseID())) {
                stuArray.add(courseRegistration);
            }
        }

        int opt;
        do {
            opt = scanner.nextInt();
            scanner.nextLine();

            System.out.println("------------------------------------------------------");

            if (stuArray.size() == 0) {
                System.out.println("No one has registered this course yet.");
            }

            if (opt == 1) { // print by LECTURE
                String newLec = "";
                Collections.sort(stuArray, LecComparator);   // Sort by Lecture group
                if (stuArray.size() > 0) {
                    for (int i = 0; i < stuArray.size(); i++) {  // loop through all of CourseRegistration Obj
                        if (!newLec.equals(stuArray.get(i).getLectureGroup())) {  // if new lecture group print out group name
                            newLec = stuArray.get(i).getLectureGroup();
                            System.out.println("Lecture group : " + newLec);
                        }
                        System.out.print("Student Name: " + stuArray.get(i).getStudent().getStudentName());
                        System.out.println(" Student ID: " + stuArray.get(i).getStudent().getStudentID());
                    }
                    System.out.println();
                }

            } else if (opt == 2) { // print by TUTORIAL
                String newTut = "";
                Collections.sort(stuArray, TutComparator);
                if (stuArray.size() > 0 && stuArray.get(0).getCourse().getTutorialGroups().size() == 0) {
                    System.out.println("This course does not contain any tutorial group.");
                } else if (stuArray.size() > 0) {
                    for (int i = 0; i < stuArray.size(); i++) {
                        if (!newTut.equals(stuArray.get(i).getTutorialGroup())) {
                            newTut = stuArray.get(i).getTutorialGroup();
                            System.out.println("Tutorial group : " + newTut);
                        }
                        System.out.print("Student Name: " + stuArray.get(i).getStudent().getStudentName());
                        System.out.println(" Student ID: " + stuArray.get(i).getStudent().getStudentID());
                    }
                    System.out.println();
                }

            } else if (opt == 3) { // print by LAB
                String newLab = "";
                Collections.sort(stuArray, LabComparator);
                if (stuArray.size() > 0 && stuArray.get(0).getCourse().getLabGroups().size() == 0) {
                    System.out.println("This course does not contain any lab group.");
                } else if (stuArray.size() > 0) {
                    for (int i = 0; i < stuArray.size(); i++) {
                        if (!newLab.equals(stuArray.get(i).getLabGroup())) {
                            newLab = stuArray.get(i).getLabGroup();
                            System.out.println("Lab group : " + newLab);
                        }
                        System.out.print("Student Name: " + stuArray.get(i).getStudent().getStudentName());
                        System.out.println(" Student ID: " + stuArray.get(i).getStudent().getStudentID());
                    }
                    System.out.println();
                }

            } else {
                System.out.println("Invalid input. Please re-enter.");
            }
            System.out.println("------------------------------------------------------");
        } while (opt < 1 || opt > 3);

    }

    /**
     * Prints the students in a course according to their lecture group, tutorial group or lab group.
     */
    public static void printStudents() {
        System.out.println("printStudent is called");
        Course currentCourse = CourseValidator.checkCourseExists();

        System.out.println("Print student by: ");
        System.out.println("(1) Lecture group");
        System.out.println("(2) Tutorial group");
        System.out.println("(3) Lab group");
        // READ courseRegistrationFILE
        // return List of Object(student,course,lecture,tut,lab)
        List<CourseRegistration> allStuArray = FILEMgr.loadCourseRegistration();

        List<CourseRegistration> stuArray = new ArrayList<CourseRegistration>(0);
        for (CourseRegistration courseRegistration : allStuArray) {
            if (courseRegistration.getCourse().getCourseID().equals(currentCourse.getCourseID())) {
                stuArray.add(courseRegistration);
            }
        }

        int opt;
        do {
            opt = scanner.nextInt();
            scanner.nextLine();

            System.out.println("------------------------------------------------------");

            if (stuArray.size() == 0) {
                System.out.println("No one has registered this course yet.");
            }

            if (opt == 1) { // print by LECTURE
                String newLec = "";
                Collections.sort(stuArray, LecComparator);   // Sort by Lecture group
                if (stuArray.size() > 0) {
                    for (int i = 0; i < stuArray.size(); i++) {  // loop through all of CourseRegistration Obj
                        if (!newLec.equals(stuArray.get(i).getLectureGroup())) {  // if new lecture group print out group name
                            newLec = stuArray.get(i).getLectureGroup();
                            System.out.println("Lecture group : " + newLec);
                        }
                        System.out.print("Student Name: " + stuArray.get(i).getStudent().getStudentName());
                        System.out.println(" Student ID: " + stuArray.get(i).getStudent().getStudentID());
                    }
                    System.out.println();
                }

            } else if (opt == 2) { // print by TUTORIAL
                String newTut = "";
                Collections.sort(stuArray, TutComparator);
                if (stuArray.size() > 0 && stuArray.get(0).getCourse().getTutorialGroups().size() == 0) {
                    System.out.println("This course does not contain any tutorial group.");
                } else if (stuArray.size() > 0) {
                    for (int i = 0; i < stuArray.size(); i++) {
                        if (!newTut.equals(stuArray.get(i).getTutorialGroup())) {
                            newTut = stuArray.get(i).getTutorialGroup();
                            System.out.println("Tutorial group : " + newTut);
                        }
                        System.out.print("Student Name: " + stuArray.get(i).getStudent().getStudentName());
                        System.out.println(" Student ID: " + stuArray.get(i).getStudent().getStudentID());
                    }
                    System.out.println();
                }

            } else if (opt == 3) { // print by LAB
                String newLab = "";
                Collections.sort(stuArray, LabComparator);
                if (stuArray.size() > 0 && stuArray.get(0).getCourse().getLabGroups().size() == 0) {
                    System.out.println("This course does not contain any lab group.");
                } else if (stuArray.size() > 0) {
                    for (int i = 0; i < stuArray.size(); i++) {
                        if (!newLab.equals(stuArray.get(i).getLabGroup())) {
                            newLab = stuArray.get(i).getLabGroup();
                            System.out.println("Lab group : " + newLab);
                        }
                        System.out.print("Student Name: " + stuArray.get(i).getStudent().getStudentName());
                        System.out.println(" Student ID: " + stuArray.get(i).getStudent().getStudentID());
                    }
                    System.out.println();
                }

            } else {
                System.out.println("Invalid input. Please re-enter.");
            }
            System.out.println("------------------------------------------------------");
        } while (opt < 1 || opt > 3);

    }

Replace Generic With Diamond ArrayList<CourseRegistration> with ArrayList<> in method public printStudents() : void from class com.softeng306.managers.CourseRegistrationMgr


    /**
     * Prints the course statics including enrollment rate, average result for every assessment component and the average overall performance of this course.
     */
    public static void printCourseStatistics() {
        System.out.println("printCourseStatistics is called");

        Course currentCourse = CourseValidator.checkCourseExists();
        String courseID = currentCourse.getCourseID();

        List<Mark> thisCourseMark = new ArrayList<>(0);
        for (Mark mark : MarkMgr.marks) {
            if (mark.getCourse().getCourseID().equals(courseID)) {
                thisCourseMark.add(mark);
            }
        }

        System.out.println("*************** Course Statistic ***************");
        System.out.println("Course ID: " + currentCourse.getCourseID() + "\tCourse Name: " + currentCourse.getCourseName());
        System.out.println("Course AU: " + currentCourse.getAU());
        System.out.println();
        System.out.print("Total Slots: " + currentCourse.getTotalSeats());
        int enrolledNumber = (currentCourse.getTotalSeats() - currentCourse.getVacancies());
        System.out.println("\tEnrolled Student: " + enrolledNumber);
        System.out.printf("Enrollment Rate: %4.2f %%\n", ((double) enrolledNumber / (double) currentCourse.getTotalSeats() * 100d));
        System.out.println();

        int examWeight = 0;
        boolean hasExam = false;
        double averageMark = 0;
        // Find marks for every assessment components
        for (CourseworkComponent courseworkComponent : currentCourse.getMainComponents()) {
            String thisComponentName = courseworkComponent.getComponentName();

            if (thisComponentName.equals("Exam")) {
                examWeight = courseworkComponent.getComponentWeight();
//                Leave the exam report to the last
                hasExam = true;
            } else {
                averageMark = 0;
                System.out.print("Main Component: " + courseworkComponent.getComponentName());
                System.out.print("\tWeight: " + courseworkComponent.getComponentWeight() + "%");

                averageMark += computeMark(thisCourseMark, thisComponentName);

                averageMark = averageMark / thisCourseMark.size();
                System.out.println("\t Average: " + averageMark);

                List<SubComponent> thisSubComponents = ((MainComponent) courseworkComponent).getSubComponents();
                if (thisSubComponents.size() == 0) {
                    continue;
                }
                for (SubComponent subComponent : thisSubComponents) {
                    averageMark = 0;
                    System.out.print("Sub Component: " + subComponent.getComponentName());
                    System.out.print("\tWeight: " + subComponent.getComponentWeight() + "% (in main component)");
                    String thisSubComponentName = subComponent.getComponentName();

                    averageMark += computeMark(thisCourseMark, thisSubComponentName);

                    averageMark = averageMark / thisCourseMark.size();
                    System.out.println("\t Average: " + averageMark);
                }
                System.out.println();
            }

        }

        if (hasExam) {
            averageMark = 0;
            System.out.print("Final Exam");
            System.out.print("\tWeight: " + examWeight + "%");
            for (Mark mark : thisCourseMark) {
                HashMap<CourseworkComponent, Double> thisComponentMarks = mark.getCourseWorkMarks();
                for (HashMap.Entry<CourseworkComponent, Double> entry : thisComponentMarks.entrySet()) {
                    CourseworkComponent key = entry.getKey();
                    double value = entry.getValue();
                    if (key.getComponentName().equals("Exam")) {
                        averageMark += value;
                        break;
                    }
                }
            }
            averageMark = averageMark / thisCourseMark.size();
            System.out.println("\t Average: " + averageMark);
        } else {
            System.out.println("This course does not have final exam.");
        }

        System.out.println();

        System.out.print("Overall Performance: ");
        averageMark = 0;
        for (Mark mark : thisCourseMark) {
            averageMark += mark.getTotalMark();
        }
        averageMark = averageMark / thisCourseMark.size();
        System.out.printf("%4.2f \n", averageMark);

        System.out.println();
        System.out.println("***********************************************");
        System.out.println();

    }

    /**
     * Prints the course statics including enrollment rate, average result for every assessment component and the average overall performance of this course.
     */
    public static void printCourseStatistics() {
        System.out.println("printCourseStatistics is called");

        Course currentCourse = CourseValidator.checkCourseExists();
        String courseID = currentCourse.getCourseID();

        List<Mark> thisCourseMark = new ArrayList<Mark>(0);
        for (Mark mark : MarkMgr.marks) {
            if (mark.getCourse().getCourseID().equals(courseID)) {
                thisCourseMark.add(mark);
            }
        }

        System.out.println("*************** Course Statistic ***************");
        System.out.println("Course ID: " + currentCourse.getCourseID() + "\tCourse Name: " + currentCourse.getCourseName());
        System.out.println("Course AU: " + currentCourse.getAU());
        System.out.println();
        System.out.print("Total Slots: " + currentCourse.getTotalSeats());
        int enrolledNumber = (currentCourse.getTotalSeats() - currentCourse.getVacancies());
        System.out.println("\tEnrolled Student: " + enrolledNumber);
        System.out.printf("Enrollment Rate: %4.2f %%\n", ((double) enrolledNumber / (double) currentCourse.getTotalSeats() * 100d));
        System.out.println();

        int examWeight = 0;
        boolean hasExam = false;
        double averageMark = 0;
        // Find marks for every assessment components
        for (CourseworkComponent courseworkComponent : currentCourse.getMainComponents()) {
            String thisComponentName = courseworkComponent.getComponentName();

            if (thisComponentName.equals("Exam")) {
                examWeight = courseworkComponent.getComponentWeight();
//                Leave the exam report to the last
                hasExam = true;
            } else {
                averageMark = 0;
                System.out.print("Main Component: " + courseworkComponent.getComponentName());
                System.out.print("\tWeight: " + courseworkComponent.getComponentWeight() + "%");

                averageMark += computeMark(thisCourseMark, thisComponentName);

                averageMark = averageMark / thisCourseMark.size();
                System.out.println("\t Average: " + averageMark);

                List<SubComponent> thisSubComponents = ((MainComponent) courseworkComponent).getSubComponents();
                if (thisSubComponents.size() == 0) {
                    continue;
                }
                for (SubComponent subComponent : thisSubComponents) {
                    averageMark = 0;
                    System.out.print("Sub Component: " + subComponent.getComponentName());
                    System.out.print("\tWeight: " + subComponent.getComponentWeight() + "% (in main component)");
                    String thisSubComponentName = subComponent.getComponentName();

                    averageMark += computeMark(thisCourseMark, thisSubComponentName);

                    averageMark = averageMark / thisCourseMark.size();
                    System.out.println("\t Average: " + averageMark);
                }
                System.out.println();
            }

        }

        if (hasExam) {
            averageMark = 0;
            System.out.print("Final Exam");
            System.out.print("\tWeight: " + examWeight + "%");
            for (Mark mark : thisCourseMark) {
                HashMap<CourseworkComponent, Double> thisComponentMarks = mark.getCourseWorkMarks();
                for (HashMap.Entry<CourseworkComponent, Double> entry : thisComponentMarks.entrySet()) {
                    CourseworkComponent key = entry.getKey();
                    double value = entry.getValue();
                    if (key.getComponentName().equals("Exam")) {
                        averageMark += value;
                        break;
                    }
                }
            }
            averageMark = averageMark / thisCourseMark.size();
            System.out.println("\t Average: " + averageMark);
        } else {
            System.out.println("This course does not have final exam.");
        }

        System.out.println();

        System.out.print("Overall Performance: ");
        averageMark = 0;
        for (Mark mark : thisCourseMark) {
            averageMark += mark.getTotalMark();
        }
        averageMark = averageMark / thisCourseMark.size();
        System.out.printf("%4.2f \n", averageMark);

        System.out.println();
        System.out.println("***********************************************");
        System.out.println();

    }

Replace Generic With Diamond ArrayList<Mark> with ArrayList<> in method public printCourseStatistics() : void from class com.softeng306.managers.MarkMgr


    /**
     * Prints transcript (Results of course taken) for a particular student
     */
    public static void  printStudentTranscript() {
        String studentID = StudentValidator.checkStudentExists().getStudentID();

        double studentGPA = 0d;
        int thisStudentAU = 0;
        List<Mark> thisStudentMark = new ArrayList<>(0);
        for (Mark mark : MarkMgr.marks) {
            if (mark.getStudent().getStudentID().equals(studentID)) {
                thisStudentMark.add(mark);
                thisStudentAU += mark.getCourse().getAU();
            }
        }

        if (thisStudentMark.size() == 0) {
            System.out.println("------ No transcript ready for this student yet ------");
            return;
        }
        System.out.println("----------------- Official Transcript ------------------");
        System.out.print("Student Name: " + thisStudentMark.get(0).getStudent().getStudentName());
        System.out.println("\tStudent ID: " + thisStudentMark.get(0).getStudent().getStudentID());
        System.out.println("AU for this semester: " + thisStudentAU);
        System.out.println();

        for (Mark mark : thisStudentMark) {
            System.out.print("Course ID: " + mark.getCourse().getCourseID());
            System.out.println("\tCourse Name: " + mark.getCourse().getCourseName());

            for (HashMap.Entry<CourseworkComponent, Double> entry : mark.getCourseWorkMarks().entrySet()) {
                CourseworkComponent assessment = entry.getKey();
                Double result = entry.getValue();
                if (assessment instanceof MainComponent) {
                    System.out.println("Main Assessment: " + assessment.getComponentName() + " ----- (" + assessment.getComponentWeight() + "%)");
                    int mainAssessmentWeight = assessment.getComponentWeight();
                    List<SubComponent> subAssessments = ((MainComponent) assessment).getSubComponents();
                    for (SubComponent subAssessment : subAssessments) {
                        System.out.print("Sub Assessment: " + subAssessment.getComponentName() + " -- (" + subAssessment.getComponentWeight() + "% * " + mainAssessmentWeight + "%) --- ");
                        String subAssessmentName = subAssessment.getComponentName();
                        for (HashMap.Entry<CourseworkComponent, Double> subEntry : mark.getCourseWorkMarks().entrySet()) {
                            CourseworkComponent subKey = subEntry.getKey();
                            Double subValue = subEntry.getValue();
                            if (subKey instanceof SubComponent && subKey.getComponentName().equals(subAssessmentName)) {
                                System.out.println("Mark: " + String.valueOf(subValue));
                                break;
                            }
                        }
                    }
                    System.out.println("Main Assessment Total: " + result);
                    System.out.println();
                }
            }

            System.out.println("Course Total: " + mark.getTotalMark());
            studentGPA += gpaCalcualtor(mark.getTotalMark()) * mark.getCourse().getAU();
            System.out.println();
        }
        studentGPA /= thisStudentAU;
        System.out.println("GPA for this semester: " + studentGPA);
        if (studentGPA >= 4.50) {
            System.out.println("On track of First Class Honor!");
        } else if (studentGPA >= 4.0) {
            System.out.println("On track of Second Upper Class Honor!");
        } else if (studentGPA >= 3.5) {
            System.out.println("On track of Second Lower Class Honor!");
        } else if (studentGPA >= 3) {
            System.out.println("On track of Third Class Honor!");
        } else {
            System.out.println("Advice: Study hard");
        }
        System.out.println("------------------ End of Transcript -------------------");
    }

    /**
     * Prints transcript (Results of course taken) for a particular student
     */
    public static void  printStudentTranscript() {
        String studentID = StudentValidator.checkStudentExists().getStudentID();

        double studentGPA = 0d;
        int thisStudentAU = 0;
        List<Mark> thisStudentMark = new ArrayList<Mark>(0);
        for (Mark mark : MarkMgr.marks) {
            if (mark.getStudent().getStudentID().equals(studentID)) {
                thisStudentMark.add(mark);
                thisStudentAU += mark.getCourse().getAU();
            }
        }

        if (thisStudentMark.size() == 0) {
            System.out.println("------ No transcript ready for this student yet ------");
            return;
        }
        System.out.println("----------------- Official Transcript ------------------");
        System.out.print("Student Name: " + thisStudentMark.get(0).getStudent().getStudentName());
        System.out.println("\tStudent ID: " + thisStudentMark.get(0).getStudent().getStudentID());
        System.out.println("AU for this semester: " + thisStudentAU);
        System.out.println();

        for (Mark mark : thisStudentMark) {
            System.out.print("Course ID: " + mark.getCourse().getCourseID());
            System.out.println("\tCourse Name: " + mark.getCourse().getCourseName());

            for (HashMap.Entry<CourseworkComponent, Double> entry : mark.getCourseWorkMarks().entrySet()) {
                CourseworkComponent assessment = entry.getKey();
                Double result = entry.getValue();
                if (assessment instanceof MainComponent) {
                    System.out.println("Main Assessment: " + assessment.getComponentName() + " ----- (" + assessment.getComponentWeight() + "%)");
                    int mainAssessmentWeight = assessment.getComponentWeight();
                    List<SubComponent> subAssessments = ((MainComponent) assessment).getSubComponents();
                    for (SubComponent subAssessment : subAssessments) {
                        System.out.print("Sub Assessment: " + subAssessment.getComponentName() + " -- (" + subAssessment.getComponentWeight() + "% * " + mainAssessmentWeight + "%) --- ");
                        String subAssessmentName = subAssessment.getComponentName();
                        for (HashMap.Entry<CourseworkComponent, Double> subEntry : mark.getCourseWorkMarks().entrySet()) {
                            CourseworkComponent subKey = subEntry.getKey();
                            Double subValue = subEntry.getValue();
                            if (subKey instanceof SubComponent && subKey.getComponentName().equals(subAssessmentName)) {
                                System.out.println("Mark: " + String.valueOf(subValue));
                                break;
                            }
                        }
                    }
                    System.out.println("Main Assessment Total: " + result);
                    System.out.println();
                }
            }

            System.out.println("Course Total: " + mark.getTotalMark());
            studentGPA += gpaCalcualtor(mark.getTotalMark()) * mark.getCourse().getAU();
            System.out.println();
        }
        studentGPA /= thisStudentAU;
        System.out.println("GPA for this semester: " + studentGPA);
        if (studentGPA >= 4.50) {
            System.out.println("On track of First Class Honor!");
        } else if (studentGPA >= 4.0) {
            System.out.println("On track of Second Upper Class Honor!");
        } else if (studentGPA >= 3.5) {
            System.out.println("On track of Second Lower Class Honor!");
        } else if (studentGPA >= 3) {
            System.out.println("On track of Third Class Honor!");
        } else {
            System.out.println("Advice: Study hard");
        }
        System.out.println("------------------ End of Transcript -------------------");
    }

Replace Generic With Diamond ArrayList<Mark> with ArrayList<> in method public printStudentTranscript() : void from class com.softeng306.managers.MarkMgr


    /**
     * Checks whether the inputted department is valid.
     *
     * @param groupType The type of this group.
     * @param groups    An array list of a certain type of groups in a course.
     * @return the name of the group chosen by the user.
     */
    public static String printGroupWithVacancyInfo(String groupType, ArrayList<Group> groups) {
        int index;
        HashMap<String, Integer> groupAssign = new HashMap<>(0);
        int selectedGroupNum;
        String selectedGroupName = null;

        if (groups.size() != 0) {
            System.out.println("Here is a list of all the " + groupType + " groups with available slots:");
            do {
                index = 0;
                for (Group group : groups) {
                    if (group.getAvailableVacancies() == 0) {
                        continue;
                    }
                    index++;
                    System.out.println(index + ": " + group.getGroupName() + " (" + group.getAvailableVacancies() + " vacancies)");
                    groupAssign.put(group.getGroupName(), index);
                }
                System.out.println("Please enter an integer for your choice:");
                selectedGroupNum = scanner.nextInt();
                scanner.nextLine();
                if (selectedGroupNum < 1 || selectedGroupNum > index) {
                    System.out.println("Invalid choice. Please re-enter.");
                } else {
                    break;
                }
            } while (true);

            for (HashMap.Entry<String, Integer> entry : groupAssign.entrySet()) {
                String groupName = entry.getKey();
                int num = entry.getValue();
                if (num == selectedGroupNum) {
                    selectedGroupName = groupName;
                    break;
                }
            }

            for (Group group : groups) {
                if (group.getGroupName().equals(selectedGroupName)) {
                    group.enrolledIn();
                    break;
                }
            }
        }
        return selectedGroupName;
    }

    /**
     * Checks whether the inputted department is valid.
     *
     * @param groupType The type of this group.
     * @param groups    An array list of a certain type of groups in a course.
     * @return the name of the group chosen by the user.
     */
    public static String printGroupWithVacancyInfo(String groupType, ArrayList<Group> groups) {
        int index;
        HashMap<String, Integer> groupAssign = new HashMap<String, Integer>(0);
        int selectedGroupNum;
        String selectedGroupName = null;

        if (groups.size() != 0) {
            System.out.println("Here is a list of all the " + groupType + " groups with available slots:");
            do {
                index = 0;
                for (Group group : groups) {
                    if (group.getAvailableVacancies() == 0) {
                        continue;
                    }
                    index++;
                    System.out.println(index + ": " + group.getGroupName() + " (" + group.getAvailableVacancies() + " vacancies)");
                    groupAssign.put(group.getGroupName(), index);
                }
                System.out.println("Please enter an integer for your choice:");
                selectedGroupNum = scanner.nextInt();
                scanner.nextLine();
                if (selectedGroupNum < 1 || selectedGroupNum > index) {
                    System.out.println("Invalid choice. Please re-enter.");
                } else {
                    break;
                }
            } while (true);

            for (HashMap.Entry<String, Integer> entry : groupAssign.entrySet()) {
                String groupName = entry.getKey();
                int num = entry.getValue();
                if (num == selectedGroupNum) {
                    selectedGroupName = groupName;
                    break;
                }
            }

            for (Group group : groups) {
                if (group.getGroupName().equals(selectedGroupName)) {
                    group.enrolledIn();
                    break;
                }
            }
        }
        return selectedGroupName;
    }

Replace Generic With Diamond HashMap<String,Integer> with HashMap<> in method public printGroupWithVacancyInfo(groupType String, groups ArrayList<Group>) : String from class com.softeng306.managers.GroupMgr


  /**
   * Writes a row with a sequence of text cells.
   * @param colorIndex Row background color.
   * @param cells Cells of the row.
   * @return New row object.
   */
  public static RtfRow rowWithBackgroundColor( int colorIndex, RtfText... cells )
  {
    if ( cells == null )
      throw new RtfException( "There has to be at least one cell in a row" );

    List<RtfPara> paras = new ArrayList<>();
    for ( RtfText cell : cells )
      paras.add( p(cell) );

    RtfPara[] parasArray = new RtfPara[ paras.size() ];
    return rowWithBackgroundColor( colorIndex, paras.toArray( parasArray ) );
  }

  /**
   * Writes a row with a sequence of text cells.
   * @param colorIndex Row background color.
   * @param cells Cells of the row.
   * @return New row object.
   */
  public static RtfRow rowWithBackgroundColor( int colorIndex, RtfText... cells )
  {
    if ( cells == null )
      throw new RtfException( "There has to be at least one cell in a row" );

    List<RtfPara> paras = new ArrayList<RtfPara>();
    for ( RtfText cell : cells )
      paras.add( p(cell) );

    RtfPara[] parasArray = new RtfPara[ paras.size() ];
    return rowWithBackgroundColor( colorIndex, paras.toArray( parasArray ) );
  }

Replace Generic With Diamond ArrayList<RtfPara> with ArrayList<> in method public rowWithBackgroundColor(colorIndex int, cells RtfText...) : RtfRow from class com.tutego.jrtf.RtfPara


  /**
   * Writes a row with a sequence of text cells. Every object is
   * converted to String and wrapped to a paragraph with the
   * method {@link RtfPara#p(Object...)}.
   * @param colorIndex Row background color.
   * @param cells Cells of the row.
   * @return New row object.
   */
  public static RtfRow rowWithBackgroundColor( int colorIndex, Object... cells )
  {
    if ( cells == null || cells.length == 0 )
      throw new RtfException( "There has to be at least one cell in a row" );

    List<RtfPara> paras = new ArrayList<>();
    for ( Object cell : cells )
    {
      if ( cell instanceof RtfPara )
        paras.add( (RtfPara) cell );
      else
        paras.add( p(cell) );
    }

    RtfPara[] parasArray = new RtfPara[ paras.size() ];
    return rowWithBackgroundColor( colorIndex, paras.toArray( parasArray ) );
  }

  /**
   * Writes a row with a sequence of text cells. Every object is
   * converted to String and wrapped to a paragraph with the
   * method {@link RtfPara#p(Object...)}.
   * @param colorIndex Row background color.
   * @param cells Cells of the row.
   * @return New row object.
   */
  public static RtfRow rowWithBackgroundColor( int colorIndex, Object... cells )
  {
    if ( cells == null || cells.length == 0 )
      throw new RtfException( "There has to be at least one cell in a row" );

    List<RtfPara> paras = new ArrayList<RtfPara>();
    for ( Object cell : cells )
    {
      if ( cell instanceof RtfPara )
        paras.add( (RtfPara) cell );
      else
        paras.add( p(cell) );
    }

    RtfPara[] parasArray = new RtfPara[ paras.size() ];
    return rowWithBackgroundColor( colorIndex, paras.toArray( parasArray ) );
  }

Replace Generic With Diamond ArrayList<RtfPara> with ArrayList<> in method public rowWithBackgroundColor(colorIndex int, cells Object...) : RtfRow from class com.tutego.jrtf.RtfPara


    private byte[] getImagen(String ruta) {
        File imagen = new File(ruta);
        try (InputStream input = new FileInputStream(imagen)) {
            byte[] icono = new byte[(int) imagen.length()];
            input.read(icono);
            return icono;
        } catch (Exception ex) {
            ex.printStackTrace();
            return null;
        }
    }

    private byte[] getImagen(String Ruta) {
        File imagen = new File(Ruta);
        try {
            byte[] icono = new byte[(int) imagen.length()];
            InputStream input = new FileInputStream(imagen);
            input.read(icono);
            return icono;
        } catch (Exception ex) {
            return null;
        }
    }

Try With Resources try(InputStream input=new FileInputStream(imagen)) in method private getImagen(ruta String) : byte[] from class interfaces.participantes.equipos


    @Override
    protected final void append(LoggingEvent event) {
        @SuppressWarnings("unchecked")
        Map<String, String> eventProps = event.getProperties();

        // The event is copied, because a host field is added in the properties
        LoggingEvent modifiedEvent = new LoggingEvent(event.getFQNOfLoggerClass(), event.getLogger(), event.getTimeStamp(), event.getLevel(), event.getMessage(),
                event.getThreadName(), event.getThrowableInformation(), event.getNDC(),
                locationInfo ? event.getLocationInformation() : null, new HashMap<>(eventProps));

        if (application != null) {
            modifiedEvent.setProperty("application", application);
        }
        modifiedEvent.setProperty("hostname", hostname);
        try {
            send(serializer.objectToBytes(modifiedEvent));
        } catch (IOException e) {
            errorHandler.error("failed to serialize event", e, ErrorCode.GENERIC_FAILURE);
        }
    }

    @Override
    protected final void append(LoggingEvent event) {
        @SuppressWarnings("unchecked")
        Map<String, String> eventProps = event.getProperties();

        // The event is copied, because a host field is added in the properties
        LoggingEvent modifiedEvent = new LoggingEvent(event.getFQNOfLoggerClass(), event.getLogger(), event.getTimeStamp(), event.getLevel(), event.getMessage(),
                event.getThreadName(), event.getThrowableInformation(), event.getNDC(),
                locationInfo ? event.getLocationInformation() : null, new HashMap<String,String>(eventProps));

        if (application != null) {
            modifiedEvent.setProperty("application", application);
        }
        modifiedEvent.setProperty("hostname", hostname);
        try {
            send(serializer.objectToBytes(modifiedEvent));
        } catch (IOException e) {
            errorHandler.error("failed to serialize event", e, ErrorCode.GENERIC_FAILURE);
        }
    }

Replace Generic With Diamond LoggingEvent with LoggingEvent in method protected append(event LoggingEvent) : void from class fr.loghub.log4j1.serializer.SerializerAppender


        public ZMQConfiguration<LoggerContext> configuration() {
            return new ZMQConfiguration<>(getConfiguration().getLoggerContext(),
                                        endpoint,
                                        SocketType.valueOf(type.toUpperCase(Locale.US)),
                                        Method.valueOf(method.toUpperCase(Locale.US)),
                                        hwm,
                                        maxMsgSize,
                                        linger);
        }

        public ZMQConfiguration<LoggerContext> configuration() {
            return new ZMQConfiguration<LoggerContext>(getConfiguration().getLoggerContext(),
                                        endpoint,
                                        SocketType.valueOf(type.toUpperCase(Locale.US)),
                                        Method.valueOf(method.toUpperCase(Locale.US)),
                                        hwm,
                                        maxMsgSize,
                                        linger);
        }

Replace Generic With Diamond ZMQConfiguration<LoggerContext> with ZMQConfiguration<> in method public configuration() : ZMQConfiguration<LoggerContext> from class fr.loghub.log4j2.appender.zmq.ZMQAppender.ZMQBuilder


    /**
     * Fills the map with words and their counts from the input file.
     *
     * @param map The map to populate
     * @param fileName The input file name
     * @return true if the file was processed successfully, false otherwise
     */
    public static boolean fillMap(MyMap<String, Integer> map, String fileName) {
        try (BufferedReader br = new BufferedReader(new FileReader(fileName))) {
            String line;

            while ((line = br.readLine()) != null) {
                line = line.replaceAll("[^a-zA-Z0-9\\s'-]+", " ").trim();
                String[] words = line.split("\\s+");

                for (String word : words) {
                    String normalizedWord = word.trim().toLowerCase();
                    if (normalizedWord.isEmpty()) continue;
                    if (normalizedWord.equals("www") || normalizedWord.equals("ftp")) continue;
                    if (normalizedWord.matches("[a-zA-Z]+(['-][a-zA-Z]+)*(--[a-zA-Z]+)?(--)?'?")) {
                        Integer count = map.get(normalizedWord);
                        map.put(normalizedWord, (count == null) ? 1 : count + 1);
                    }
                }
            }
        } catch (IOException e) {
            System.err.println("Error: An I/O error occurred reading '" + fileName + "'.");
            return false;
        }
        return true;
    }

    /**
    * Fills the map with words and their counts from the input file.
    * @param map The map to populate
    * @param fileName The input file name
    * @return true if the file was processed successfully, false otherwise
    */
    public static boolean fillMap(MyMap<String, Integer> map, String fileName) {
        try {
            BufferedReader br = new BufferedReader(new FileReader(fileName));
            String line;

            // Process the file line by line.
            while ((line = br.readLine()) != null) {
                // Replace unwanted characters, keep alphanumeric, apostrophes, and hyphens (including double hyphens).
                line = line.replaceAll("[^a-zA-Z0-9\\s'-]+", " ").trim();

                // Split cleaned line into words based on whitespace.
                String[] words = line.split("\\s+");

                for (String word : words) {
                    // Normalize the word: convert to lowercase and trim any remaining whitespace.
                    String normalizedWord = word.trim().toLowerCase();

                    // Ignore empty strings or isolated punctuation.
                    if (normalizedWord.isEmpty()) continue;

                    // Skip common non-word patterns like "www", "http", etc.
                    if (normalizedWord.equals("www") || normalizedWord.equals("ftp")) continue;

                    // Check if the word is valid (allows words with apostrophes, hyphens, double hyphens, and possessive apostrophes).
                    if (normalizedWord.matches("[a-zA-Z]+(['-][a-zA-Z]+)*(--[a-zA-Z]+)?(--)?'?")) {
                        // Add or update the count for the word in the map.
                        Integer count = map.get(normalizedWord);
                        map.put(normalizedWord, (count == null) ? 1 : count + 1);
                    }
                }
            }
            br.close();

        } catch (IOException e) {
            System.err.println("Error: An I/O error occurred reading '" + fileName + "'.");
            return false;
        }

        return true;
    }

Try With Resources try(BufferedReader br=new BufferedReader(new FileReader(fileName))) in method public fillMap(map MyMap<String,Integer>, fileName String) : boolean from class com.tymour.CommonWordFinder


    /**
     * Sorts the map entries first by frequency and then alphabetically.
     *
     * @param map The map to sort
     * @return A 2D array of sorted words and their counts
     */
    public static String[][] sortMap(MyMap<String, Integer> map) {
        String[][] words = new String[map.size()][2];
        int index = 0;
        Iterator<Entry<String, Integer>> itr = map.iterator();
        while (itr.hasNext()) {
            Entry<String, Integer> pair = itr.next();
            words[index][0] = pair.key;
            words[index++][1] = String.valueOf(pair.value);
        }

        Arrays.sort(words, (o1, o2) -> {
            int countComparison = Integer.compare(Integer.parseInt(o2[1]), Integer.parseInt(o1[1]));
            return (countComparison != 0) ? countComparison : o1[0].compareTo(o2[0]);
        });
        return words;
    }

    /**
     * Sorts the map entries first by frequency and then alphabetically.
     * @param map The map to sort
     * @return A 2D array of sorted words and their counts
     */
    public static String[][] sortMap(MyMap<String, Integer> map) {
        String[][] words = new String[map.size()][2];
        int index = 0;
        Iterator<Entry<String, Integer>> itr = map.iterator();
        while (itr.hasNext()) {
            Entry<String, Integer> pair = itr.next();
            words[index][0] = pair.key;
            words[index++][1] = String.valueOf(pair.value);
        }
        Arrays.sort(words, new Comparator<String[]>() {
            @Override
            public int compare(String[] o1, String[] o2) {
                int countComparison = Integer.compare(Integer.parseInt(o2[1]), Integer.parseInt(o1[1]));
                return (countComparison != 0) ? countComparison : o1[0].compareTo(o2[0]);
            }
        });
        return words;
    }

Replace Anonymous With Lambda com.tymour.CommonWordFinder.sortMap.sort.new Comparator<String[]> with (o1, o2) -> {int countComparison=Integer.compare(Integer.parseInt(o2[1]),Integer.parseInt(o1[1])); in method public sortMap(map MyMap<String,Integer>) : String[][] from class com.tymour.CommonWordFinder


    private void initComments() {
        try
        {
           pub=pS.selectWhere(publicationId);
            publicationtitle.setText(pub.getTitre());
            addcomment.setVisible(pub.getCom_ouvert());
            pagination.setPageCount((cS.countComments(pub) + PAGE_SIZE - 1) / PAGE_SIZE);
            loadComments(pagination.getCurrentPageIndex());
            Comments.setItems(commentsList);
            content.setCellValueFactory(new PropertyValueFactory<>("contenu"));
            userName.setCellValueFactory(cellData -> new SimpleStringProperty(cellData.getValue().getUser().getLastname()+" "+cellData.getValue().getUser().getFirstname()));
            state.setCellValueFactory(cellData -> new SimpleStringProperty(cellData.getValue().getValide() ? "Approved" : "Under Review"));
            postedAt.setCellValueFactory(cellData -> {
                LocalDateTime dateTime = cellData.getValue().getDate_c();
                DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd MMMM yyyy HH:mm:ss");
                String formattedDateTime = dateTime.format(formatter);
                return new SimpleStringProperty(formattedDateTime);
            });
            updatedAt.setCellValueFactory(cellData -> {
                LocalDateTime dateTime = cellData.getValue().getDate_m();
                DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd MMMM yyyy HH:mm:ss");
                String formattedDateTime = dateTime.format(formatter);
                return new SimpleStringProperty(formattedDateTime);
            });
            validate.setCellFactory(param -> new TableCell<>() {
                Button validateButton = new Button();
                {
                    validateButton.setStyle("-fx-background-color: transparent;");
                }
                @Override
                protected void updateItem(Void item, boolean empty) {
                    super.updateItem(item, empty);
                    if (empty || getTableRow() == null || getTableRow().getItem() == null) {
                        setGraphic(null);
                    } else {
                        Commentaire comment = getTableRow().getItem();
                        String stateValue = comment.getValide() ? "Unvalidate" : "Validate";
                        validateButton.setText(stateValue);
                        validateButton.setOnAction(event -> {
                            if (comment != null) {
                                try {
                                    cS.validate(comment.getId());
                                    commentsList.replaceAll(com -> {
                                        if (com.getId() == comment.getId()) {
                                            com.setValide(!com.getValide());
                                        }
                                        return com;
                                    });
                                    Comments.refresh();
                                } catch (SQLException e) {
                                    throw new RuntimeException(e);
                                }
                            }
                        });
                        setGraphic(validateButton);
                    }
                }
            });
            actions.setCellFactory(param -> new TableCell<>() {
                private final Button updateButton = new Button();
                private final Button deleteButton = new Button();
                {
                    FontAwesomeIcon updateIcon = new FontAwesomeIcon();
                    updateIcon.setIcon(FontAwesomeIcons.PENCIL);
                    updateButton.setGraphic(updateIcon);
                    FontAwesomeIcon deleteIcon = new FontAwesomeIcon();
                    deleteIcon.setIcon(FontAwesomeIcons.TRASH);
                    deleteButton.setGraphic(deleteIcon);
                    updateButton.setStyle("-fx-background-color: transparent;");
                    deleteButton.setStyle("-fx-background-color: transparent;");
                    updateButton.setOnAction(event -> {
                        Commentaire comment = getTableView().getItems().get(getIndex());
                        showUpdatecommentDialog(comment);
                    });
                    deleteButton.setOnAction(event -> {
                        Commentaire comment = getTableView().getItems().get(getIndex());
                        try {
                            showDeleteConfirmationDialog(comment);
                        } catch (SQLException e) {
                            throw new RuntimeException(e);
                        }
                    });
                }
                @Override
                protected void updateItem(Void item, boolean empty) {
                    super.updateItem(item, empty);
                    if (empty) {
                        setGraphic(null);
                    } else {
                        HBox buttonsBox = new HBox(updateButton, deleteButton);
                        buttonsBox.setSpacing(5);
                        setGraphic(buttonsBox);
                    }
                }
            });
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }

    private void initComments() {
        try
        {
           pub=pS.selectWhere(publicationId);
            publicationtitle.setText(pub.getTitre());
            addcomment.setVisible(pub.getCom_ouvert());
            pagination.setPageCount((cS.countComments(pub) + PAGE_SIZE - 1) / PAGE_SIZE);

            //commentsList = FXCollections.observableArrayList(cS.select(publicationId));
            //Comments.setItems(commentsList);
            loadComments(pagination.getCurrentPageIndex());
            Comments.setItems(commentsList);
            content.setCellValueFactory(new PropertyValueFactory<>("contenu"));
            userName.setCellValueFactory(cellData -> new SimpleStringProperty(cellData.getValue().getUser().getLastname()+" "+cellData.getValue().getUser().getFirstname()));
            state.setCellValueFactory(cellData -> new SimpleStringProperty(cellData.getValue().getValide() ? "Approved" : "Under Review"));
            postedAt.setCellValueFactory(cellData -> {
                LocalDateTime dateTime = cellData.getValue().getDate_c();
                DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd MMMM yyyy HH:mm:ss");
                String formattedDateTime = dateTime.format(formatter);
                return new SimpleStringProperty(formattedDateTime);
            });
            updatedAt.setCellValueFactory(cellData -> {
                LocalDateTime dateTime = cellData.getValue().getDate_m();
                DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd MMMM yyyy HH:mm:ss");
                String formattedDateTime = dateTime.format(formatter);
                return new SimpleStringProperty(formattedDateTime);
            });
            validate.setCellFactory(param -> new TableCell<Commentaire, Void>() {
                Button validateButton = new Button();

                {
                    validateButton.setStyle("-fx-background-color: transparent;");
                }

                @Override
                protected void updateItem(Void item, boolean empty) {
                    super.updateItem(item, empty);
                    if (empty || getTableRow() == null || getTableRow().getItem() == null) {
                        setGraphic(null);
                    } else {
                        Commentaire comment = getTableRow().getItem(); // Retrieve the Commentaire associated with the current row
                        String stateValue = comment.getValide() ? "Unvalidate" : "Validate";
                        validateButton.setText(stateValue); // Set the text of the button based on the state value
                        validateButton.setOnAction(event -> {
                            if (comment != null) {
                                try {
                                    // Proceed with your validation logic
                                    cS.validate(comment.getId());
                                    commentsList.replaceAll(com -> {
                                        if (com.getId() == comment.getId()) {
                                            com.setValide(!com.getValide());
                                        }
                                        return com;
                                    });
                                    Comments.refresh();
                                } catch (SQLException e) {
                                    throw new RuntimeException(e);
                                }
                            }
                        });
                        setGraphic(validateButton);
                    }
                }
            });

            actions.setCellFactory(param -> new TableCell<>() {
                private final Button updateButton = new Button();
                private final Button deleteButton = new Button();

                {
                    FontAwesomeIcon updateIcon = new FontAwesomeIcon();
                    updateIcon.setIcon(FontAwesomeIcons.PENCIL);
                    updateButton.setGraphic(updateIcon);

                    FontAwesomeIcon deleteIcon = new FontAwesomeIcon();
                    deleteIcon.setIcon(FontAwesomeIcons.TRASH);
                    deleteButton.setGraphic(deleteIcon);

                    updateButton.setStyle("-fx-background-color: transparent;");
                    deleteButton.setStyle("-fx-background-color: transparent;");

                    updateButton.setOnAction(event -> {
                        Commentaire comment = getTableView().getItems().get(getIndex());
                        // Handle view action here using publication.getId() or other relevant data
                        showUpdatecommentDialog(comment);
                    });

                    deleteButton.setOnAction(event -> {
                        Commentaire comment = getTableView().getItems().get(getIndex());
                        try {
                            showDeleteConfirmationDialog(comment);
                        } catch (SQLException e) {
                            throw new RuntimeException(e);
                        }
                    });
                }
                @Override
                protected void updateItem(Void item, boolean empty) {
                    super.updateItem(item, empty);
                    if (empty) {
                        setGraphic(null);
                    } else {
                        HBox buttonsBox = new HBox(updateButton, deleteButton);
                        buttonsBox.setSpacing(5);
                        setGraphic(buttonsBox);
                    }
                }
            });
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }

Replace Generic With Diamond TableCell<Commentaire,Void> with TableCell<> in method private initComments() : void from class org.example.controllers.CommentaireController


    @Override
    public void onPluginMessageReceived(String channel, Player player, byte[] message) {
        if (!channel.equals("HeliosPerms")) {
            return;
        }
        ByteArrayDataInput in = ByteStreams.newDataInput(message);
        String subchannel = in.readUTF();
        Bukkit.getScheduler().runTaskLater(Main.getInstance(), () -> {
            if (subchannel.equals("UpdatePermissions")) {
                PermissionType type = PermissionType.valueOf(in.readUTF().toUpperCase());
                if (type == PermissionType.GROUP)
                    HeliosPerms.getInstance().getGroupManager().updatePermissions();
                else
                    HeliosPerms.getInstance().getPlayerManager().updatePermissions();

                for (Player onlinePlayer : Bukkit.getOnlinePlayers()) {
                    Optional<PermissionPlayer> permissionPlayer = playerManager.getPlayer(onlinePlayer.getUniqueId());

                    if (!permissionPlayer.isPresent()) return;

                    try {
                        Field field = Main.getInstance().getNMSClass("entity.CraftHumanEntity").getDeclaredField("perm");
                        field.setAccessible(true);
                        field.set(onlinePlayer, new Permissible(onlinePlayer, permissionPlayer.get()));
                    } catch (NoSuchFieldException | IllegalAccessException e) {
                        e.printStackTrace();
                    }
                }
            }
        }, 100);
        if (subchannel.equals("UpdateGroup")) {
            String uuid = in.readUTF();
            Player target = Bukkit.getPlayer(UUID.fromString(uuid));
            String oldGroupId = in.readUTF();
            String newGroupId = in.readUTF();
            if (target != null) {
                Bukkit.getPluginManager().callEvent(new GroupChangeEvent(player.getUniqueId(), Integer.parseInt(oldGroupId), Integer.parseInt(newGroupId)));
            }
        }

    }

    @Override
    public void onPluginMessageReceived(String channel, Player player, byte[] message) {
        if (!channel.equals("HeliosPerms")) {
            return;
        }
        ByteArrayDataInput in = ByteStreams.newDataInput(message);
        String subchannel = in.readUTF();
        new BukkitRunnable() {

            @Override
            public void run() {
                if (subchannel.equals("UpdatePermissions")) {
                    PermissionType type = PermissionType.valueOf(in.readUTF().toUpperCase());
                    if (type == PermissionType.GROUP)
                        HeliosPerms.getInstance().getGroupManager().updatePermissions();
                    else
                        HeliosPerms.getInstance().getPlayerManager().updatePermissions();

                    for (Player onlinePlayer : Bukkit.getOnlinePlayers()) {
                        Optional<PermissionPlayer> permissionPlayer = playerManager.getPlayer(onlinePlayer.getUniqueId());

                        if (!permissionPlayer.isPresent()) return;

                        try {
                            Field field = Main.getInstance().getNMSClass("entity.CraftHumanEntity").getDeclaredField("perm");
                            field.setAccessible(true);
                            field.set(onlinePlayer, new Permissible(onlinePlayer, permissionPlayer.get()));
                        } catch (NoSuchFieldException | IllegalAccessException e) {
                            e.printStackTrace();
                        }
                    }
                }
            }
        }.runTaskLater(Main.getInstance(), 100);
        if (subchannel.equals("UpdateGroup")) {
            String uuid = in.readUTF();
            Player target = Bukkit.getPlayer(UUID.fromString(uuid));
            String oldGroupId = in.readUTF();
            String newGroupId = in.readUTF();
            if (target != null) {
                Bukkit.getPluginManager().callEvent(new GroupChangeEvent(player.getUniqueId(), Integer.parseInt(oldGroupId), Integer.parseInt(newGroupId)));
            }
        }

    }

Replace Anonymous With Lambda de.heliosdevelopment.heliosperms.listener.MessageListener.onPluginMessageReceived.runTaskLater.new BukkitRunnable with () -> {if(subchannel.equals("UpdatePermissions")){PermissionType type=PermissionType.valueOf(in.readUTF().toUpperCase()); in method public onPluginMessageReceived(channel String, player Player, message byte[]) : void from class de.heliosdevelopment.heliosperms.listener.MessageListener


    @Override
    public QueryExecute<E> build() {
        return new QueryExecute<>(baseEntity);
    }

    @Override
    public QueryExecute<E> build() {
        return new QueryExecute<E>(baseEntity);
    }

Replace Generic With Diamond QueryExecute<E> with QueryExecute<> in method public build() : QueryExecute<E> from class com.nn.core.wrapper.impl.QueryWrapper


  private Try<BlobResponse> sendRequestToPreviewService(HttpRequestBase request) {

    try (CloseableHttpClient httpClient = HttpClients.createMinimal();
      CloseableHttpResponse response = httpClient.execute(request)) {
      int statusCode = response.getStatusLine().getStatusCode();
      switch (statusCode) {
        case HttpStatus.SC_OK:
          return Try.success(new BlobResponse(response.getEntity()));
        case HttpStatus.SC_NOT_FOUND:
          return Try.failure(new ItemNotFound());
        case HttpStatus.SC_UNPROCESSABLE_ENTITY:
          return Try.failure(new ValidationError());
        case HttpStatus.SC_BAD_REQUEST:
          return Try.failure(new BadRequest());
        default:
          return Try.failure(new InternalServerError());
      }
    } catch (IOException exception) {
      return Try.failure(new InternalServerError(exception));
    }
  }

  private Try<BlobResponse> sendRequestToPreviewService(HttpRequestBase request) {

    CloseableHttpClient httpClient = HttpClients.createMinimal();
    try {
      CloseableHttpResponse response = httpClient.execute(request);
      int statusCode = response.getStatusLine().getStatusCode();
      switch (statusCode) {
        case HttpStatus.SC_OK:
          return Try.success(new BlobResponse(response.getEntity()));
        case HttpStatus.SC_NOT_FOUND:
          return Try.failure(new ItemNotFound());
        case HttpStatus.SC_UNPROCESSABLE_ENTITY:
          return Try.failure(new ValidationError());
        case HttpStatus.SC_BAD_REQUEST:
          return Try.failure(new BadRequest());
        default:
          return Try.failure(new InternalServerError());
      }
    } catch (IOException exception) {
      return Try.failure(new InternalServerError(exception));
    }
  }

Try With Resources try(CloseableHttpClient httpClient=HttpClients.createMinimal(); CloseableHttpResponse response=httpClient.execute(request)) in method private sendRequestToPreviewService(request HttpRequestBase) : Try<BlobResponse> from class com.zextras.carbonio.preview.PreviewClient


  @NonNull @Override
  public Route.Handler apply(@NonNull Route.Handler next) {
    return ctx -> {
      var sessionFactory = ctx.require(sessionFactoryKey);
      try (var session = sessionProvider.create(ctx, sessionFactory)) {

        Object result = next.apply(ctx);

        Transaction transaction = session.getTransaction();
        if (transaction.getStatus() == TransactionStatus.ACTIVE) {
          log.error(
              "Transaction state is still active (expected to be committed, or rolled "
                  + "back) after route pipeline completed, rolling back.");

          transaction.rollback();
        }

        return result;
      } finally {
        sessionProvider.release(sessionFactory);
      }
    };
  }

  @NonNull @Override
  public Route.Handler apply(@NonNull Route.Handler next) {
    return ctx -> {
      SessionFactory sessionFactory = ctx.require(sessionFactoryKey);
      SessionProvider sessionProvider = ctx.require(sessionProviderKey);
      Session session = sessionProvider.newSession(sessionFactory.withOptions());
      try {
        ManagedSessionContext.bind(session);

        Object result = next.apply(ctx);

        Transaction transaction = session.getTransaction();
        if (transaction.getStatus() == TransactionStatus.ACTIVE) {
          log.error(
              "Transaction state is still active (expected to be committed, or rolled "
                  + "back) after route pipeline completed, rolling back.");

          transaction.rollback();
        }

        return result;
      } finally {
        ManagedSessionContext.unbind(sessionFactory);
        if (session != null) {
          session.close();
        }
      }
    };
  }

Try With Resources try(var session=sessionProvider.create(ctx,sessionFactory)) in method public apply(next Route.Handler) : Route.Handler from class io.jooby.hibernate.SessionRequest


  private void handleClose(WebSocketCloseStatus status) {
    OnClose callback = onCloseCallback.getAndSet(null);
    if (isOpen()) {
      open.set(false);
      // close socket:
      sendClose(
          status.getCode(),
          status.getReason(),
          channel,
          new WebSocketCallback<>() {
            @Override
            public void onError(
                final WebSocketChannel channel,
                final UndertowWebSocket ws,
                final Throwable throwable) {
              IoUtils.safeClose(channel);
              ws.onError(channel, throwable);
            }

            @Override
            public void complete(final WebSocketChannel channel, final UndertowWebSocket ws) {
              IoUtils.safeClose(channel);
            }
          },
          this);
    }
    try {
      // fire callback:
      if (callback != null) {
        callback.onClose(this, status);
      }
    } catch (Throwable x) {
      // fire error:
      onError(channel, x);
    } finally {
      // clear from active sessions:
      removeSession(this);
    }
  }

  private void handleClose(WebSocketCloseStatus status) {
    OnClose callback = onCloseCallback.getAndSet(null);
    if (isOpen()) {
      open.set(false);
      // close socket:
      sendClose(
          status.getCode(),
          status.getReason(),
          channel,
          new WebSocketCallback<UndertowWebSocket>() {
            @Override
            public void onError(
                final WebSocketChannel channel,
                final UndertowWebSocket ws,
                final Throwable throwable) {
              IoUtils.safeClose(channel);
              ws.onError(channel, throwable);
            }

            @Override
            public void complete(final WebSocketChannel channel, final UndertowWebSocket ws) {
              IoUtils.safeClose(channel);
            }
          },
          this);
    }
    try {
      // fire callback:
      if (callback != null) {
        callback.onClose(this, status);
      }
    } catch (Throwable x) {
      // fire error:
      onError(channel, x);
    } finally {
      // clear from active sessions:
      removeSession(this);
    }
  }

Replace Generic With Diamond WebSocketCallback<UndertowWebSocket> with WebSocketCallback<> in method private handleClose(status WebSocketCloseStatus) : void from class io.jooby.internal.undertow.UndertowWebSocket


  @Override
  public @NonNull byte[] bytes() {
    try (var in = stream()) {
      return in.readAllBytes();
    } catch (IOException x) {
      throw SneakyThrows.propagate(x);
    }
  }

  @Override
  public byte[] bytes() {
    try {
      byte[] bytes = upload.getBytes();
      if (bytes == null) {
        return Files.readAllBytes(upload.getFile().toPath());
      }
      return bytes;
    } catch (IOException x) {
      throw SneakyThrows.propagate(x);
    }
  }

Try With Resources try(var in=stream()) in method public bytes() : byte[] from class io.jooby.internal.jetty.JettyFileUpload


  @Override
  public SSLContext create(ClassLoader loader, String provider, SslOptions options) {
    try (options) {
      KeyStore store = keystore(options, options.getCert(), options.getPassword());
      KeyManagerFactory kmf =
          KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
      kmf.init(store, toCharArray(options.getPassword()));
      KeyManager[] kms = kmf.getKeyManagers();
      SSLContext context =
          provider == null
              ? SSLContext.getInstance("TLS")
              : SSLContext.getInstance("TLS", provider);

      TrustManager[] tms;
      if (options.getTrustCert() != null) {
        KeyStore trustStore = keystore(options, options.getTrustCert(), options.getTrustPassword());

        TrustManagerFactory tmf =
            TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
        tmf.init(trustStore);
        tms = tmf.getTrustManagers();
      } else {
        tms = null;
      }

      context.init(kms, tms, null);
      return context;
    } catch (Exception x) {
      throw SneakyThrows.propagate(x);
    }
  }

  @Override
  public SSLContext create(ClassLoader loader, String provider, SslOptions options) {
    try {
      KeyStore store = keystore(options, loader, options.getCert(), options.getPassword());
      KeyManagerFactory kmf =
          KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
      kmf.init(store, toCharArray(options.getPassword()));
      KeyManager[] kms = kmf.getKeyManagers();
      SSLContext context =
          provider == null
              ? SSLContext.getInstance("TLS")
              : SSLContext.getInstance("TLS", provider);

      TrustManager[] tms;
      if (options.getTrustCert() != null) {
        KeyStore trustStore =
            keystore(options, loader, options.getTrustCert(), options.getTrustPassword());

        TrustManagerFactory tmf =
            TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
        tmf.init(trustStore);
        tms = tmf.getTrustManagers();
      } else {
        tms = null;
      }

      context.init(kms, tms, null);
      return context;
    } catch (Exception x) {
      throw SneakyThrows.propagate(x);
    }
  }

Try With Resources try(options) in method public create(loader ClassLoader, provider String, options SslOptions) : SSLContext from class io.jooby.internal.SslPkcs12Provider


  @Override
  public SSLContext create(ClassLoader loader, String provider, SslOptions options) {
    try (options) {
      SslContext sslContext =
          SslContext.newServerContextInternal(
              provider,
              options.getTrustCert(),
              options.getCert(),
              options.getPrivateKey(),
              null,
              0,
              0);

      return sslContext.context();
    } catch (Exception x) {
      throw SneakyThrows.propagate(x);
    }
  }

  @Override
  public SSLContext create(ClassLoader loader, String provider, SslOptions options) {
    try {
      InputStream trustCert;
      if (options.getTrustCert() == null) {
        trustCert = null;
      } else {
        trustCert = options.getResource(loader, options.getTrustCert());
      }
      InputStream keyStoreCert = options.getResource(loader, options.getCert());
      InputStream keyStoreKey = options.getResource(loader, options.getPrivateKey());

      SSLContext context =
          SslContext.newServerContextInternal(
                  provider, trustCert, keyStoreCert, keyStoreKey, null, 0, 0)
              .context();

      return context;
    } catch (Exception x) {
      throw SneakyThrows.propagate(x);
    }
  }

Try With Resources try(options) in method public create(loader ClassLoader, provider String, options SslOptions) : SSLContext from class io.jooby.internal.SslX509Provider