    @Override
    public IntBinaryOperator getMathOperation(CommandContext cmdCtx, String key) throws CommandSyntaxException {
        ArgumentMathOperation.a result = ArgumentMathOperation.a(cmdCtx, key);

        return (left, right) -> {

            ScoreboardScore int1 = new ScoreboardScore(new net.minecraft.server.v1_14_R1.Scoreboard(), null, null);
            ScoreboardScore int2 = new ScoreboardScore(new net.minecraft.server.v1_14_R1.Scoreboard(), null, null);

            int1.setScore(left);
            int2.setScore(right);

            try {
                result.apply(int1, int2);
            } catch (CommandSyntaxException e) {
                e.printStackTrace();
            }

            return int1.getScore();
        };
    }

	@Override
	public IntBinaryOperator getMathOperation(CommandContext cmdCtx, String key) throws CommandSyntaxException {
		ArgumentMathOperation.a result = ArgumentMathOperation.a(cmdCtx, key);

		return new IntBinaryOperator() {

			@Override
			public int applyAsInt(int left, int right) {

				ScoreboardScore int1 = new ScoreboardScore(new net.minecraft.server.v1_14_R1.Scoreboard(), null, null);
				ScoreboardScore int2 = new ScoreboardScore(new net.minecraft.server.v1_14_R1.Scoreboard(), null, null);

				int1.setScore(left);
				int2.setScore(right);

				try {
					result.apply(int1, int2);
				} catch (CommandSyntaxException e) {
					e.printStackTrace();
				}

				return int1.getScore();
			}
		};
	}

Replace Anonymous With Lambda io.github.jorelali.commandapi.api.nms.NMS_1_14_R1.getMathOperation.new IntBinaryOperator with (left, right) -> {ScoreboardScore int1=new ScoreboardScore(new net.minecraft.server.v1_14_R1.Scoreboard(),null,null); in method public getMathOperation(cmdCtx CommandContext, key String) : IntBinaryOperator from class io.github.jorelali.commandapi.api.nms.NMS_1_14_3


    private static Node createContentNode(Value value) {
        Type returnType = value.getReturnType();
        if (returnType == PrimitiveType.BOOLEAN) {
            BooleanValue val = (BooleanValue) value;
            CheckBox checkBoxValue = new CheckBox();
            StackPane.setMargin(checkBoxValue, MARGIN);
            checkBoxValue.setPadding(new Insets(5, 0, 5, 5));//Don't ask me why, it works! (makes a non-text checkbox a sqare pane
            checkBoxValue.setContentDisplay(ContentDisplay.GRAPHIC_ONLY);
            checkBoxValue.selectedProperty().bindBidirectional(val.valueProperty());
            return checkBoxValue;
        } else if (returnType == PrimitiveType.NUMBER) {
            NumberValue val2 = (NumberValue) value;
            Spinner<Double> spinnerValue = new Spinner<>(-Double.MAX_VALUE, Double.MAX_VALUE, Double.NaN);
            StackPane.setMargin(spinnerValue, MARGIN);
            spinnerValue.getValueFactory().setConverter(new StringConverter<>() {
                @Override
                public String toString(Double value) {
                    // If the specified value is null, return a zero-length String
                    if (value == null) {
                        return "";
                    }
                    String stringValue = value.toString();
                    if (stringValue.endsWith(".0")) {
                        stringValue = stringValue.substring(0, stringValue.length() - 2);
                    }
                    return stringValue;
                }

                @Override
                public Double fromString(String value) {
                    try {
                        // If the specified value is null or zero-length, return null
                        if (value == null) {
                            return null;
                        }

                        value = value.trim();

                        if (value.length() < 1) {
                            return 0.0;
                        }

                        value = value.replaceAll("[^0-9.-]", "");

                        // Perform the requested parsing
                        return Double.parseDouble(value);
                    } catch (NumberFormatException ex) {
                        return 0.0;
                    }
                }
            });
            spinnerValue.getEditor().setPrefWidth(14);
            spinnerValue.minWidthProperty().bind(minTextFieldWidthProperty(spinnerValue.getEditor()).add(24));//Spinner does not resize automatically like textfield :(
            spinnerValue.setEditable(true);
            spinnerValue.getValueFactory().valueProperty().bindBidirectional(val2.valueProperty());
            return spinnerValue;
        } else if (returnType == PrimitiveType.TEXT) {
            TextValue val3 = (TextValue) value;
            TextField textFieldValue = new TextField();
            StackPane.setMargin(textFieldValue, MARGIN);
            textFieldValue.prefWidthProperty().bind(minTextFieldWidthProperty(textFieldValue));
            textFieldValue.textProperty().bindBidirectional(val3.valueProperty());
            return textFieldValue;
        } else if (returnType instanceof ObjectType) {
            ObjectValue val4 = (ObjectValue) value;
            Text textType = new Text();
            StackPane.setMargin(textType, MARGIN);
            textType.textProperty().bind(val4.getReturnType().simpleNameProperty());
            textType.setFill(Color.BLACK);
            return textType;
        }
        Text errorText = new Text("Error");
        errorText.setFill(Color.RED);
        return errorText;
    }

    private static Node createContentNode(Value value) {
        Type returnType = value.getReturnType();
        if (returnType == PrimitiveType.BOOLEAN) {
            BooleanValue val = (BooleanValue) value;
            CheckBox checkBoxValue = new CheckBox();
            StackPane.setMargin(checkBoxValue, MARGIN);
            checkBoxValue.setPadding(new Insets(5, 0, 5, 5));//Don't ask me why, it works! (makes a non-text checkbox a sqare pane
            checkBoxValue.setContentDisplay(ContentDisplay.GRAPHIC_ONLY);
            checkBoxValue.selectedProperty().bindBidirectional(val.valueProperty());
            return checkBoxValue;
        } else if (returnType == PrimitiveType.NUMBER) {
            NumberValue val2 = (NumberValue) value;
            Spinner<Double> spinnerValue = new Spinner<>(-Double.MAX_VALUE, Double.MAX_VALUE, Double.NaN);
            StackPane.setMargin(spinnerValue, MARGIN);
            spinnerValue.getValueFactory().setConverter(new StringConverter<Double>() {
                @Override
                public String toString(Double value) {
                    // If the specified value is null, return a zero-length String
                    if (value == null) {
                        return "";
                    }
                    String stringValue = value.toString();
                    if (stringValue.endsWith(".0")) {
                        stringValue = stringValue.substring(0, stringValue.length() - 2);
                    }
                    return stringValue;
                }

                @Override
                public Double fromString(String value) {
                    try {
                        // If the specified value is null or zero-length, return null
                        if (value == null) {
                            return null;
                        }

                        value = value.trim();

                        if (value.length() < 1) {
                            return 0.0;
                        }

                        value = value.replaceAll("[^0-9\\.-]", "");

                        // Perform the requested parsing
                        return Double.parseDouble(value);
                    } catch (NumberFormatException ex) {
                        return 0.0;
                    }
                }
            });
            spinnerValue.getEditor().setPrefWidth(14);
            spinnerValue.minWidthProperty().bind(minTextFieldWidthProperty(spinnerValue.getEditor()).add(24));//Spinner does not resize automatically like textfield :(
            spinnerValue.setEditable(true);
            spinnerValue.getValueFactory().valueProperty().bindBidirectional(val2.valueProperty());
            return spinnerValue;
        } else if (returnType == PrimitiveType.TEXT) {
            TextValue val3 = (TextValue) value;
            TextField textFieldValue = new TextField();
            StackPane.setMargin(textFieldValue, MARGIN);
            textFieldValue.prefWidthProperty().bind(minTextFieldWidthProperty(textFieldValue));
            textFieldValue.textProperty().bindBidirectional(val3.valueProperty());
            return textFieldValue;
        } else if (returnType instanceof ObjectType) {
            ObjectValue<?> val4 = (ObjectValue) value;
            Text textType = new Text();
            StackPane.setMargin(textType, MARGIN);
            textType.textProperty().bind(val4.getReturnType().getSimpleName());
            textType.setFill(Color.BLACK);
            return textType;
        }
        Text errorText = new Text("Error");
        errorText.setFill(Color.RED);
        return errorText;
    }

Replace Generic With Diamond StringConverter<Double> with StringConverter<> in method private createContentNode(value Value) : Node from class sharknoon.dualide.ui.bodies.ValueBody


    public void addStudentToSubject(Subject subject, AppUser appUser) {
        if (!subject.grades.containsKey(appUser)) {
            subject.grades.put(appUser, new ArrayList<>());
        }
    }

    public void addStudentToSubject(Subject subject, AppUser appUser) {
        if (!subject.grades.containsKey(appUser)) {
            subject.grades.put(appUser, new ArrayList<Integer>());
        }
    }

Replace Generic With Diamond ArrayList<Integer> with ArrayList<> in method public addStudentToSubject(subject Subject, appUser AppUser) : void from class app.data.SubjectRepository


    /**
     * Post请求，请求内容必须为键值对参数
     *
     * @param url    请求地址
     * @param config 配置项，如果null则使用默认配置
     * @param body   请求内容键值对参数
     * @return 响应结果字符串
     */
    public static String post(String url, Map<String, String> body, HttpClientConfig config) {
        try (CloseableHttpClient httpClient = buildHttpClient(url)) {
            HttpPost httpPost = new HttpPost(url);
            if (config == null) {
                config = new HttpClientConfig();
            }
            httpPost.setConfig(config.buildRequestConfig());
            Map<String, String> header = config.getHeader();
            for (String key : header.keySet()) {
                httpPost.addHeader(key, header.get(key));
            }
            if (body != null && body.size() > 0) {
                List<NameValuePair> nvps = new ArrayList<>();
                for (String key : body.keySet()) {
                    nvps.add(new BasicNameValuePair(key, body.get(key)));
                }
                try {
                    httpPost.setEntity(new UrlEncodedFormEntity(nvps, config.getCharset()));
                } catch (Exception e) {
                    logger.error("HttpClient转换编码错误", e);
                    throw new DEException(SYSTEM_INNER_ERROR.code(), "HttpClient转换编码错误: " + e.getMessage());
                }
            }

            HttpResponse response = httpClient.execute(httpPost);
            return getResponseStr(response, config);
        } catch (Exception e) {
            logger.error("HttpClient查询失败", e);
            throw new DEException(SYSTEM_INNER_ERROR.code(), "HttpClient查询失败: " + e.getMessage());
        }
    }

    /**
     * Post请求，请求内容必须为键值对参数
     *
     * @param url    请求地址
     * @param config 配置项，如果null则使用默认配置
     * @param body   请求内容键值对参数
     * @return 响应结果字符串
     */
    public static String post(String url, Map<String, String> body, HttpClientConfig config) {
        CloseableHttpClient httpClient = null;

        try {
            buildHttpClient(url);
            HttpPost httpPost = new HttpPost(url);
            if (config == null) {
                config = new HttpClientConfig();
            }
            httpPost.setConfig(config.buildRequestConfig());
            Map<String, String> header = config.getHeader();
            for (String key : header.keySet()) {
                httpPost.addHeader(key, header.get(key));
            }
            if (body != null && body.size() > 0) {
                List<NameValuePair> nvps = new ArrayList<>();
                for (String key : body.keySet()) {
                    nvps.add(new BasicNameValuePair(key, body.get(key)));
                }
                try {
                    httpPost.setEntity(new UrlEncodedFormEntity(nvps, config.getCharset()));
                } catch (Exception e) {
                    logger.error("HttpClient转换编码错误", e);
                    throw new DEException(SYSTEM_INNER_ERROR.code(), "HttpClient转换编码错误: " + e.getMessage());
                }
            }

            HttpResponse response = httpClient.execute(httpPost);
            return getResponseStr(response, config);
        } catch (Exception e) {
            logger.error("HttpClient查询失败", e);
            throw new DEException(SYSTEM_INNER_ERROR.code(), "HttpClient查询失败: " + e.getMessage());
        } finally {
            try {
                if(httpClient != null){
                    httpClient.close();
                }
            } catch (Exception e) {
                logger.error("HttpClient关闭连接失败", e);
            }
        }
    }

Try With Resources try(CloseableHttpClient httpClient=buildHttpClient(url)) in method public post(url String, body Map<String,String>, config HttpClientConfig) : String from class io.dataease.utils.HttpClientUtil


    private List<DynamicMenuDto> buildTree(List<DynamicMenuDto> lists) {
        List<DynamicMenuDto> rootNodes = new ArrayList<>();
        lists.forEach(node -> {
            if (isParent(node.getPid())) {
                rootNodes.add(node);
            }
            lists.forEach(tNode -> {
                if (tNode.getPid().equals(node.getId())) {
                    if (node.getChildren() == null) {
                        node.setChildren(new ArrayList<>());
                        node.setRedirect(node.getPath() + "/" + tNode.getPath());//第一个子节点的path
                    }
                    node.getChildren().add(tNode);
                }
            });
        });
        return rootNodes;

    }

    private List<DynamicMenuDto> buildTree(List<DynamicMenuDto> lists) {
        List<DynamicMenuDto> rootNodes = new ArrayList<>();
        lists.forEach(node -> {
            if (isParent(node.getPid())) {
                rootNodes.add(node);
            }
            lists.forEach(tNode -> {
                if (tNode.getPid().equals(node.getId())) {
                    if (node.getChildren() == null) {
                        node.setChildren(new ArrayList<DynamicMenuDto>());
                        node.setRedirect(node.getPath() + "/" + tNode.getPath());//第一个子节点的path
                    }
                    node.getChildren().add(tNode);
                }
            });
        });
        return rootNodes;

    }

Replace Generic With Diamond ArrayList<DynamicMenuDto> with ArrayList<> in method private buildTree(lists List<DynamicMenuDto>) : List<DynamicMenuDto> from class io.dataease.auth.service.impl.DynamicMenuServiceImpl


    public boolean isKettleRunning() {
        try {
            if (!InetAddress.getByName(carte).isReachable(1000)) {
                return false;
            }
        } catch (Exception e) {
            return false;
        }
        HttpGet getMethod = new HttpGet("http://" + carte + ":" + port);
        HttpClientManager.HttpClientBuilderFacade clientBuilder = HttpClientManager.getInstance().createBuilder();
        clientBuilder.setConnectionTimeout(1);
        clientBuilder.setCredentials(user, passwd);
        try (CloseableHttpClient httpClient = clientBuilder.build()){
            HttpResponse httpResponse = httpClient.execute(getMethod);
            int statusCode = httpResponse.getStatusLine().getStatusCode();
            if (statusCode != -1 && statusCode < 400) {
                httpResponse.getEntity().getContent().close();
                return true;
            } else {
                return false;
            }
        } catch (Exception e) {
            return false;
        }
    }

    public boolean isKettleRunning() {
        try {
            if (!InetAddress.getByName(carte).isReachable(1000)) {
                return false;
            }
        } catch (Exception e) {
            return false;
        }

        HttpGet getMethod = new HttpGet("http://" + carte + ":" + port);
        HttpClientManager.HttpClientBuilderFacade clientBuilder = HttpClientManager.getInstance().createBuilder();
        clientBuilder.setConnectionTimeout(1);
        clientBuilder.setCredentials(user, passwd);
        CloseableHttpClient httpClient = clientBuilder.build();
        try {
            HttpResponse httpResponse = httpClient.execute(getMethod);
            int statusCode = httpResponse.getStatusLine().getStatusCode();
            if (statusCode != -1 && statusCode < 400) {
                httpResponse.getEntity().getContent().close();
                return true;
            } else {
                return false;
            }
        } catch (Exception e) {
            return false;
        }
    }

Try With Resources try(CloseableHttpClient httpClient=clientBuilder.build()) in method public isKettleRunning() : boolean from class io.dataease.service.dataset.ExtractDataService


    /**
     * 这里使用声明式缓存不是很妥当
     * 改为chartViewService中使用编程式缓存
    @Cacheable(
            value = JdbcConstants.JDBC_PROVIDER_KEY,
            key = "'provider_sql_' + #dsr.datasource.id + '_' + #dsr.table + '_' + #dsr.query",
            condition = "#dsr.pageSize == null || #dsr.pageSize == 0L"
    )
     */
    @Override
    public List<String[]> getData(DatasourceRequest dsr) throws Exception {
        List<String[]> list = new LinkedList<>();
        try (Connection connection = getConnectionFromPool(dsr); Statement stat = connection.createStatement(); ResultSet rs = stat.executeQuery(dsr.getQuery())){
            list = fetchResult(rs);
            if(dsr.isPageable() && dsr.getDatasource().getType().equalsIgnoreCase(DatasourceTypes.sqlServer.name())){
                Integer realSize = dsr.getPage() * dsr.getPageSize() < list.size() ? dsr.getPage() * dsr.getPageSize(): list.size();
                list = list.subList((dsr.getPage() - 1) * dsr.getPageSize(), realSize);
            }

        } catch (SQLException e) {
            DataEaseException.throwException(e);
        } catch (Exception e) {
            DataEaseException.throwException(e);
        }
        return list;
    }

    /**
     * 这里使用声明式缓存不是很妥当
     * 改为chartViewService中使用编程式缓存
    @Cacheable(
            value = JdbcConstants.JDBC_PROVIDER_KEY,
            key = "'provider_sql_' + #dsr.datasource.id + '_' + #dsr.table + '_' + #dsr.query",
            condition = "#dsr.pageSize == null || #dsr.pageSize == 0L"
    )
     */
    @Override
    public List<String[]> getData(DatasourceRequest dsr) throws Exception {
        List<String[]> list = new LinkedList<>();
        Connection connection = null;
        try {
            connection = getConnection(dsr);
            Statement stat = connection.createStatement();
            ResultSet rs = stat.executeQuery(dsr.getQuery());
            list = fetchResult(rs);

            if(dsr.isPageable() && dsr.getDatasource().getType().equalsIgnoreCase(DatasourceTypes.sqlServer.name())){
                Integer realSize = dsr.getPage() * dsr.getPageSize() < list.size() ? dsr.getPage() * dsr.getPageSize(): list.size();
                list = list.subList((dsr.getPage() - 1) * dsr.getPageSize(), realSize);
            }

        } catch (SQLException e) {
            DataEaseException.throwException(e);
        } catch (Exception e) {
            DataEaseException.throwException(e);
        } finally {
            if(connection != null){
                connection.close();
            }
        }
        return list;
    }

Try With Resources try(Connection connection=getConnectionFromPool(dsr); Statement stat=connection.createStatement(); ResultSet rs=stat.executeQuery(dsr.getQuery())) in method public getData(dsr DatasourceRequest) : List<String[]> from class io.dataease.datasource.provider.JdbcProvider


    public void exec(DatasourceRequest datasourceRequest) throws Exception {
        try (Connection connection = getConnectionFromPool(datasourceRequest); Statement stat = connection.createStatement()){
            Boolean result = stat.execute(datasourceRequest.getQuery());
        } catch (SQLException e) {
            DataEaseException.throwException(e);
        } catch (Exception e) {
            DataEaseException.throwException(e);
        }
    }

    public void exec(DatasourceRequest datasourceRequest) throws Exception {
        Connection connection = null;
        try {
            connection = getConnectionFromPool(datasourceRequest);
            Statement stat = connection.createStatement();
            Boolean result = stat.execute(datasourceRequest.getQuery());
            stat.close();
        } catch (SQLException e) {
            DataEaseException.throwException(e);
        } catch (Exception e) {
            DataEaseException.throwException(e);
        } finally {
            if(connection != null){
                connection.close();
            }
        }
    }

Try With Resources try(Connection connection=getConnectionFromPool(datasourceRequest); Statement stat=connection.createStatement()) in method public exec(datasourceRequest DatasourceRequest) : void from class io.dataease.datasource.provider.JdbcProvider


    @Override
    public List<String[]> fetchResult(DatasourceRequest datasourceRequest) throws Exception {
        try (Connection connection = getConnectionFromPool(datasourceRequest); Statement stat = connection.createStatement(); ResultSet rs = stat.executeQuery(datasourceRequest.getQuery())){
            return fetchResult(rs);
        } catch (SQLException e) {
            DataEaseException.throwException(e);
        } catch (Exception e) {
            DataEaseException.throwException(e);
        }
        return new ArrayList<>();
    }

    @Override
    public List<String[]> fetchResult(DatasourceRequest datasourceRequest) throws Exception {
        ResultSet rs;
        Connection connection = null;
        try {
            connection = getConnectionFromPool(datasourceRequest);
            Statement stat = connection.createStatement();
            rs = stat.executeQuery(datasourceRequest.getQuery());
            return fetchResult(rs);
        } catch (SQLException e) {
            DataEaseException.throwException(e);
        } catch (Exception e) {
            DataEaseException.throwException(e);
        } finally {
            if(connection != null){
                connection.close();
            }
        }
        return new ArrayList<>();
    }

Try With Resources try(Connection connection=getConnectionFromPool(datasourceRequest); Statement stat=connection.createStatement(); ResultSet rs=stat.executeQuery(datasourceRequest.getQuery())) in method public fetchResult(datasourceRequest DatasourceRequest) : List<String[]> from class io.dataease.datasource.provider.JdbcProvider


    @Override
    public List<TableFiled> fetchResultField(DatasourceRequest datasourceRequest) throws Exception {
        try (Connection connection = getConnectionFromPool(datasourceRequest); Statement stat = connection.createStatement(); ResultSet rs = stat.executeQuery(datasourceRequest.getQuery())){
            return fetchResultField(rs, datasourceRequest);
        } catch (SQLException e) {
            DataEaseException.throwException(e);
        } catch (Exception e) {
            DataEaseException.throwException(Translator.get("i18n_datasource_connect_error") + e.getMessage());
        }
        return new ArrayList<>();
    }

    @Override
    public List<TableFiled> fetchResultField(DatasourceRequest datasourceRequest) throws Exception {
        ResultSet rs;
        Connection connection = null;
        try {
            connection = getConnectionFromPool(datasourceRequest);
            Statement stat = connection.createStatement();
            rs = stat.executeQuery(datasourceRequest.getQuery());
            return fetchResultField(rs, datasourceRequest);
        } catch (SQLException e) {
            DataEaseException.throwException(e);
        } catch (Exception e) {
            DataEaseException.throwException(Translator.get("i18n_datasource_connect_error") + e.getMessage());
        } finally {
            if(connection != null){
                connection.close();
            }
        }
        return new ArrayList<>();
    }

Try With Resources try(Connection connection=getConnectionFromPool(datasourceRequest); Statement stat=connection.createStatement(); ResultSet rs=stat.executeQuery(datasourceRequest.getQuery())) in method public fetchResultField(datasourceRequest DatasourceRequest) : List<TableFiled> from class io.dataease.datasource.provider.JdbcProvider


    @Override
    public Map<String, List> fetchResultAndField(DatasourceRequest datasourceRequest) throws Exception {
        Map<String, List> result = new HashMap<>();
        List<String[]> dataList = new LinkedList<>();
        List<TableFiled> fieldList = new ArrayList<>();
        try (Connection connection = getConnectionFromPool(datasourceRequest); Statement stat = connection.createStatement(); ResultSet rs = stat.executeQuery(datasourceRequest.getQuery())){
            dataList = fetchResult(rs);
            fieldList = fetchResultField(rs, datasourceRequest);
            result.put("dataList", dataList);
            result.put("fieldList", fieldList);
            return result;
        } catch (SQLException e) {
            DataEaseException.throwException(e);
        } catch (Exception e) {
            DataEaseException.throwException(e);
        }
        return new HashMap<>();
    }

    @Override
    public Map<String, List> fetchResultAndField(DatasourceRequest datasourceRequest) throws Exception {
        ResultSet rs;
        Map<String, List> result = new HashMap<>();
        Connection connection = null;
        List<String[]> dataList = new LinkedList<>();
        List<TableFiled> fieldList = new ArrayList<>();
        try {
            connection = getConnectionFromPool(datasourceRequest);
            Statement stat = connection.createStatement();
            rs = stat.executeQuery(datasourceRequest.getQuery());
            dataList = fetchResult(rs);
            fieldList = fetchResultField(rs, datasourceRequest);
            result.put("dataList", dataList);
            result.put("fieldList", fieldList);
            return result;
        } catch (SQLException e) {
            DataEaseException.throwException(e);
        } catch (Exception e) {
            DataEaseException.throwException(e);
        } finally {
            if(connection != null){
                connection.close();
            }
        }
        return new HashMap<>();
    }

Try With Resources try(Connection connection=getConnectionFromPool(datasourceRequest); Statement stat=connection.createStatement(); ResultSet rs=stat.executeQuery(datasourceRequest.getQuery())) in method public fetchResultAndField(datasourceRequest DatasourceRequest) : Map<String,List> from class io.dataease.datasource.provider.JdbcProvider


    @Override
    public List<String> getTables(DatasourceRequest datasourceRequest) throws Exception {
        List<String> tables = new ArrayList<>();
        String queryStr = getTablesSql(datasourceRequest);
        try (Connection con = getConnectionFromPool(datasourceRequest); Statement statement = con.createStatement(); ResultSet resultSet = statement.executeQuery(queryStr)){
            while (resultSet.next()) {
                tables.add(resultSet.getString(1));
            }
        } catch (Exception e) {
            DataEaseException.throwException(e);
        }

        String queryView = getViewSql(datasourceRequest);
        try (Connection con = getConnectionFromPool(datasourceRequest); Statement statement = con.createStatement(); ResultSet resultSet = statement.executeQuery(queryView)){
            while (resultSet.next()) {
                tables.add(resultSet.getString(1));
            }
        } catch (Exception e) {
            DataEaseException.throwException(e);
        }
        return tables;
    }

    @Override
    public List<String> getTables(DatasourceRequest datasourceRequest) throws Exception {
        List<String> tables = new ArrayList<>();
        Connection con = null;
        try {
            String queryStr = getTablesSql(datasourceRequest);
            con = getConnection(datasourceRequest);
            Statement statement = con.createStatement();
            ResultSet resultSet = statement.executeQuery(queryStr);
            while (resultSet.next()) {
                tables.add(resultSet.getString(1));
            }
            resultSet.close();
            statement.close();

            String queryView = getViewSql(datasourceRequest);
            if(StringUtils.isNotEmpty(queryView)){
                con = getConnection(datasourceRequest);
                statement = con.createStatement();
                resultSet = statement.executeQuery(queryView);
                while (resultSet.next()) {
                    tables.add(resultSet.getString(1));
                }
                resultSet.close();
                statement.close();
            }

            return tables;
        } catch (Exception e) {
            DataEaseException.throwException(e);
        } finally {
            if(con != null){
                con.close();
            }
        }
        return new ArrayList<>();
    }

Try With Resources try(Connection con=getConnectionFromPool(datasourceRequest); Statement statement=con.createStatement(); ResultSet resultSet=statement.executeQuery(queryStr)) in method public getTables(datasourceRequest DatasourceRequest) : List<String> from class io.dataease.datasource.provider.JdbcProvider


    @Override
    public List<String> getSchema(DatasourceRequest datasourceRequest) throws Exception {
        List<String> schemas = new ArrayList<>();
        String queryStr = getSchemaSql(datasourceRequest);
        try (Connection con = getConnection(datasourceRequest); Statement statement = con.createStatement(); ResultSet resultSet = statement.executeQuery(queryStr)){
            while (resultSet.next()) {
                schemas.add(resultSet.getString(1));
            }
            return schemas;
        } catch (Exception e) {
            DataEaseException.throwException(e);
        }
        return new ArrayList<>();
    }

    @Override
    public List<String> getSchema(DatasourceRequest datasourceRequest) throws Exception {
        List<String> schemas = new ArrayList<>();
        String queryStr = getSchemaSql(datasourceRequest);
        Connection con = null;
        try {
            con = getConnection(datasourceRequest);
            Statement statement = con.createStatement();
            ResultSet resultSet = statement.executeQuery(queryStr);
            while (resultSet.next()) {
                schemas.add(resultSet.getString(1));
            }
            resultSet.close();
            statement.close();
            return schemas;
        } catch (Exception e) {
            DataEaseException.throwException(e);
        } finally {
            if(con != null){
                con.close();
            }
        }
        return new ArrayList<>();
    }

Try With Resources try(Connection con=getConnection(datasourceRequest); Statement statement=con.createStatement(); ResultSet resultSet=statement.executeQuery(queryStr)) in method public getSchema(datasourceRequest DatasourceRequest) : List<String> from class io.dataease.datasource.provider.JdbcProvider


  private void storeFiles(List<TaskFile> taskFiles, File inputFilesFolder) throws IOException {

    for (TaskFile taskFile : taskFiles) {
      TaskFileMetadata meta = taskFile.getMeta();

      Vector<InputStream> inputStreams = new Vector<>();
      while (taskFile.hasNext()) {
        inputStreams.add(taskFile.next());
      }
      SequenceInputStream combinedStream = new SequenceInputStream(inputStreams.elements());

      FileUtils.copyInputStreamToFile(combinedStream, new File(inputFilesFolder
          + File.separator + meta.getFileName() + "." + meta.getFileType()));
    }
  }

  private void storeFiles(List<TaskFile> taskFiles, File inputFilesFolder) throws IOException {

    for (TaskFile taskFile : taskFiles) {
      TaskFileMetadata meta = taskFile.getMeta();

      Vector<InputStream> inputStreams = new Vector<InputStream>();
      while (taskFile.hasNext()) {
        inputStreams.add(taskFile.next());
      }
      SequenceInputStream combinedStream = new SequenceInputStream(inputStreams.elements());

      FileUtils.copyInputStreamToFile(combinedStream, new File(inputFilesFolder
          + File.separator + meta.getFileName() + "." + meta.getFileType()));
    }
  }

Replace Generic With Diamond Vector<InputStream> with Vector<> in method private storeFiles(taskFiles List<TaskFile>, inputFilesFolder File) : void from class org.crunchycookie.orion.master.service.store.impl.LocalStorageCentralStore


    @Test
    public void test1() throws IOException {
        VMData vm = providerRule.getProvider().createVM(OS.UbuntuWilyAmd64);

        try (SSHClient ssh = new SSHClient()) {
            ssh.addHostKeyVerifier(new PromiscuousVerifier());
            //ssh.loadKnownHosts();

            ssh.connect("localhost", vm.getSshForwardPort());
            //ssh.authPublickey(System.getProperty("user.name"));
            ssh.authPassword("root", "");

            // sftp file and data transfer
            try (SFTPClient sftp = ssh.newSFTPClient()) {
                String src = FredClientTest.class.getResource("application-context.xml").getFile();
                sftp.put(new FileSystemFile(src), "/tmp");
                sftp.put(src, "/tmp/2.xml");

                // structured remote file listings
                List<RemoteResourceInfo> rris = sftp.ls("/tmp");
                for (RemoteResourceInfo rri : rris) {
                    LOG.info(rri.toString());
                }

                // remote random read access
                RemoteFile rf = sftp.open("/tmp/2.xml");
                byte[] to = new byte[3];
                assertEquals(3, rf.read(2, to, 0, 3));
                assertEquals("xml", new String(to, "ASCII"));
                rf.close();

                // random write access
                Set<OpenMode> omode = new HashSet<>();
                omode.add(OpenMode.CREAT);
                omode.add(OpenMode.WRITE);
                omode.add(OpenMode.READ);
                omode.add(OpenMode.EXCL);
                rf = sftp.open("/tmp/3.xml", omode);
                rf.write(100, "abc".getBytes("ASCII"), 0, 3);
                assertEquals(3, rf.read(99, to, 0, 3));
                assertEquals("\0ab", new String(to, "ASCII"));
                rf.close();
            }

            try (Session session = ssh.startSession()) {
                Command cmd = session.exec("ls -lrt /tmp");
                LOG.info(IOUtils.readFully(cmd.getInputStream()).toString());
                LOG.info("start join");
                cmd.join(5, TimeUnit.SECONDS);
                LOG.info("\n** exit status: " + cmd.getExitStatus());
            }
            ssh.disconnect();
        }
    }

    @Test
    public void test1() throws IOException {
        VMData vm = providerRule.getProvider().createVM(OS.UbuntuWilyAmd64);

        final SSHClient ssh = new SSHClient();
        ssh.addHostKeyVerifier(new PromiscuousVerifier());
        //ssh.loadKnownHosts();

        ssh.connect("localhost", vm.getSshForwardPort());
        try {
            //ssh.authPublickey(System.getProperty("user.name"));
            ssh.authPassword("root", "");
            final Session session = ssh.startSession();
            try {
                final Command cmd = session.exec("ls -l /");
                System.out.println(IOUtils.readFully(cmd.getInputStream()).toString());
                cmd.join(5, TimeUnit.SECONDS);
                System.out.println("\n** exit status: " + cmd.getExitStatus());
            } finally {
                session.close();
            }
        } finally {
            ssh.disconnect();
        }
    }

Try With Resources try(SSHClient ssh=new SSHClient()) in method public test1() : void from class com.hierynomus.sshj.SSHJTest


    public boolean isEmailExists(String email) {
        boolean exists = false;
        try {
            String sql = "SELECT COUNT(*) FROM user WHERE email=?";
            try (PreparedStatement ps = conn.prepareStatement(sql)) {
                ps.setString(1, email);

                try (ResultSet rs = ps.executeQuery()) {
                    if (rs.next()) {
                        int count = rs.getInt(1);
                        exists = count > 0;
                    }
                }
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }

        return exists;
    }

    public boolean isEmailExists(String email) {
        boolean exists = false;
        try {
            String sql = "SELECT COUNT(*) FROM user WHERE email=?";
            PreparedStatement ps = conn.prepareStatement(sql);
            ps.setString(1, email);

            ResultSet rs = ps.executeQuery();
            rs.next();

            int count = rs.getInt(1);
            if (count > 0) {
                exists = true;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return exists;
    }

Try With Resources try(PreparedStatement ps=conn.prepareStatement(sql)) in method public isEmailExists(email String) : boolean from class com.DAO.UserDAOimpl


    private void initGameplay() {
        //Activation des entrées / sorties clavier
        IOEngine.enableKeyboardIO();

        //Joueur
        player = new Player(30, 30, 2, textures, 1, 3);

        //Id des murs
        ArrayList<Entity> walls = new ArrayList<>();

        //Génération des murs
        for (int i = 0; i < 2; i++) {
            for (int j = 0; j < 6; j++) {
                Entity wall = KernelEngine.generateEntity();
                walls.add(wall);
                PhysicsEngine.move(wall.getPhysicEntity(),30 + (30*j),100 + (60*i));
                PhysicsEngine.resize(wall.getPhysicEntity(),30,30);
                GraphicsEngine.bindColor(wall.getGraphicEntity(),0,0,255);
                PhysicsEngine.addCollisions(player.getPhysicEntity(), wall.getPhysicEntity());
            }
        }
        Entity wall = KernelEngine.generateEntity();
        walls.add(wall);
        PhysicsEngine.move(wall.getPhysicEntity(),0,160);
        PhysicsEngine.resize(wall.getPhysicEntity(),30,30);
        GraphicsEngine.bindColor(wall.getGraphicEntity(),0,0,255);
        PhysicsEngine.addCollisions(player.getPhysicEntity(), wall.getPhysicEntity());

        //Id des boules
        ArrayList<Entity> balls = new ArrayList<>();

        //Génération des boules
        for (int i = 0; i < 6; i++) {
            Entity ball = KernelEngine.generateEntity();
            balls.add(ball);
            PhysicsEngine.move(ball.getPhysicEntity(),30 + (30*i),130);
            PhysicsEngine.resize(ball.getPhysicEntity(),30,30);
            GraphicsEngine.bindTexture(ball.getGraphicEntity(),textures,10,2);
            KernelEngine.addEvent("eraseBall" + i,() -> GraphicsEngine.erase(ball.getGraphicEntity()));
            PhysicsEngine.bindEventOnSameLocation(player.getPhysicEntity(), ball.getPhysicEntity(), "eraseBall" + i);
        }

        //Ajout des collisions de la scène
        PhysicsEngine.addBoundLimits(player.getPhysicEntity(), 0,0,300,300);

        //Scène principale
        int mainScene = GraphicsEngine.generateScene(300, 300);
        GraphicsEngine.setSceneBackgroundColor(mainScene,0,0,0);
        GraphicsEngine.bindScene(mainScene);
        for (Entity entity : walls)
            GraphicsEngine.addToCurrentScene(entity.getGraphicEntity());
        for (Entity entity : balls)
            GraphicsEngine.addToCurrentScene(entity.getGraphicEntity());
        GraphicsEngine.addToCurrentScene(player.getGraphicEntity());

        //Démarrage du jeu
        KernelEngine.start();
    }

    private void initGameplay() {
        //Activation des entrées / sorties clavier
        IOEngine.enableKeyboardIO();

        //Joueur
        player = new Player(30, 30, 2, textures, 1, 3);

        //Id des murs
        ArrayList<Entity> walls = new ArrayList<>();

        //Génération des murs
        for (int i = 0; i < 2; i++) {
            for (int j = 0; j < 6; j++) {
                Entity wall = KernelEngine.generateEntity();
                walls.add(wall);
                PhysicsEngine.move(wall.getPhysicEntity(),30 + (30*j),100 + (60*i));
                PhysicsEngine.resize(wall.getPhysicEntity(),30,30);
                GraphicsEngine.bindColor(wall.getGraphicEntity(),0,0,255);
                PhysicsEngine.addCollisions(player.getPhysicEntity(), wall.getPhysicEntity());
            }
        }
        Entity wall = KernelEngine.generateEntity();
        walls.add(wall);
        PhysicsEngine.move(wall.getPhysicEntity(),0,160);
        PhysicsEngine.resize(wall.getPhysicEntity(),30,30);
        GraphicsEngine.bindColor(wall.getGraphicEntity(),0,0,255);
        PhysicsEngine.addCollisions(player.getPhysicEntity(), wall.getPhysicEntity());

        //Id des boules
        ArrayList<Entity> balls = new ArrayList<>();

        //Génération des boules
        for (int i = 0; i < 6; i++) {
            Entity ball = KernelEngine.generateEntity();
            balls.add(ball);
            PhysicsEngine.move(ball.getPhysicEntity(),30 + (30*i),130);
            PhysicsEngine.resize(ball.getPhysicEntity(),30,30);
            GraphicsEngine.bindTexture(ball.getGraphicEntity(),textures,10,2);
            KernelEngine.addEvent("eraseBall" + i, new Event() {
                @Override
                public void run() { GraphicsEngine.erase(ball.getGraphicEntity()); }
            });
            PhysicsEngine.bindEventOnSameLocation(player.getPhysicEntity(), ball.getPhysicEntity(), "eraseBall" + i);
        }

        //Ajout des collisions de la scène
        PhysicsEngine.addBoundLimits(player.getPhysicEntity(), 0,0,300,300);

        //Scène principale
        int mainScene = GraphicsEngine.generateScene(300, 300);
        GraphicsEngine.setSceneBackgroundColor(mainScene,0,0,0);
        GraphicsEngine.bindScene(mainScene);
        for (Entity entity : walls)
            GraphicsEngine.addToCurrentScene(entity.getGraphicEntity());
        for (Entity entity : balls)
            GraphicsEngine.addToCurrentScene(entity.getGraphicEntity());
        GraphicsEngine.addToCurrentScene(player.getGraphicEntity());

        //Démarrage du jeu
        KernelEngine.start();
    }

Replace Anonymous With Lambda gameplay.Gameplay.initGameplay.addEvent.new Event with () -> GraphicsEngine.erase(ball.getGraphicEntity()) in method private initGameplay() : void from class gameplay.Gameplay


  /** Initializes the controller class. */
  @Override
  public void initialize(URL url, ResourceBundle rb) {
    permCheckList.getItems().addAll(PersimssionQueries.getPermissions());
    permCheckList.setCellFactory((ListView<PermissionEntity> listView) -> new CheckBoxListCell<PermissionEntity>(
            item -> permCheckList.getItemBooleanProperty(item),
            new StringConverter<PermissionEntity>() {
                @Override
                public PermissionEntity fromString(String arg0) {
                    return null;
                }

                @Override
                public String toString(PermissionEntity per) {
                    return per.getPermissionDisplayName();
                }
            }));
  }

  /** Initializes the controller class. */
  @Override
  public void initialize(URL url, ResourceBundle rb) {
    permCheckList.getItems().addAll(PersimssionQueries.getPermissions());
    permCheckList.setCellFactory(
        new Callback<ListView<PermissionEntity>, ListCell<PermissionEntity>>() {
          public ListCell<PermissionEntity> call(ListView<PermissionEntity> listView) {
            return new CheckBoxListCell<PermissionEntity>(
                item -> permCheckList.getItemBooleanProperty(item),
                new StringConverter<PermissionEntity>() {
                  @Override
                  public PermissionEntity fromString(String arg0) {
                    return null;
                  }

                  @Override
                  public String toString(PermissionEntity per) {
                    return per.getPermissionDisplayName();
                  }
                });
          }
        });
  }

Replace Anonymous With Lambda gr.codebb.protoerp.userManagement.RolesDetailView.initialize.setCellFactory.new Callback<ListView<PermissionEntity>,ListCell<PermissionEntity>> with (listView) -> new CheckBoxListCell<PermissionEntity>(item -> permCheckList.getItemBooleanProperty(item),new StringConverter<PermissionEntity>(){ in method public initialize(url URL, rb ResourceBundle) : void from class gr.codebb.protoerp.userManagement.RolesDetailView


    @Test
    void printSalaries()
    {
        ArrayList<Employee> employees = new ArrayList<>();
        Employee emp = new Employee();
        emp.emp_no = 1;
        emp.first_name = "Kevin";
        emp.last_name = "Chalmers";
        emp.title = "Engineer";
        emp.salary = 55000;
        employees.add(emp);
        app.printSalaries(employees);
    }

    @Test
    void printSalaries()
    {
        ArrayList<Employee> employees = new ArrayList<Employee>();
        Employee emp = new Employee();
        emp.emp_no = 1;
        emp.first_name = "Kevin";
        emp.last_name = "Chalmers";
        emp.title = "Engineer";
        emp.salary = 55000;
        employees.add(emp);
        app.printSalaries(employees);
    }

Replace Generic With Diamond ArrayList<Employee> with ArrayList<> in method package printSalaries() : void from class com.napier.sem.AppTest


        /**
         * Gets all the current employees and salaries.
         * @return A list of all employees and salaries, or null if there is an error.
         */
    public ArrayList<Employee> getAllSalaries()
    {
        try
        {
            // Create an SQL statement
            Statement stmt = con.createStatement();
            // Create string for SQL statement
            String strSelect =
                    "SELECT employees.emp_no, employees.first_name, employees.last_name, salaries.salary "
                            + "FROM employees, salaries "
                            + "WHERE employees.emp_no = salaries.emp_no AND salaries.to_date = '9999-01-01' "
                            + "ORDER BY employees.emp_no ASC";
            // Execute SQL statement
            ResultSet rset = stmt.executeQuery(strSelect);
            // Extract employee information
            ArrayList<Employee> employees = new ArrayList<>();
            while (rset.next())
            {
                Employee emp = new Employee();
                emp.emp_no = rset.getInt("employees.emp_no");
                emp.first_name = rset.getString("employees.first_name");
                emp.last_name = rset.getString("employees.last_name");
                emp.salary = rset.getInt("salaries.salary");
                employees.add(emp);
            }
            return employees;
        }
        catch (Exception e)
        {
            System.out.println(e.getMessage());
            System.out.println("Failed to get salary details");
            return null;
        }
    }

        /**
         * Gets all the current employees and salaries.
         * @return A list of all employees and salaries, or null if there is an error.
         */
    public ArrayList<Employee> getAllSalaries()
    {
        try
        {
            // Create an SQL statement
            Statement stmt = con.createStatement();
            // Create string for SQL statement
            String strSelect =
                    "SELECT employees.emp_no, employees.first_name, employees.last_name, salaries.salary "
                            + "FROM employees, salaries "
                            + "WHERE employees.emp_no = salaries.emp_no AND salaries.to_date = '9999-01-01' "
                            + "ORDER BY employees.emp_no ASC";
            // Execute SQL statement
            ResultSet rset = stmt.executeQuery(strSelect);
            // Extract employee information
            ArrayList<Employee> employees = new ArrayList<Employee>();
            while (rset.next())
            {
                Employee emp = new Employee();
                emp.emp_no = rset.getInt("employees.emp_no");
                emp.first_name = rset.getString("employees.first_name");
                emp.last_name = rset.getString("employees.last_name");
                emp.salary = rset.getInt("salaries.salary");
                employees.add(emp);
            }
            return employees;
        }
        catch (Exception e)
        {
            System.out.println(e.getMessage());
            System.out.println("Failed to get salary details");
            return null;
        }
    }

Replace Generic With Diamond ArrayList<Employee> with ArrayList<> in method public getAllSalaries() : ArrayList<Employee> from class com.napier.sem.App


    public static long getFolderSize(Logger logger, Path folder) {
        try (Stream<Path> walk = Files.walk(folder, 3, FileVisitOption.FOLLOW_LINKS)) {
            return walk
                    .parallel()
                    .mapToLong(path -> {
                        try {
                            return Files.size(path);
                        } catch (IOException e) {
                            return 0;
                        }
                    }).sum();
        } catch (IOException ioEx) {
            logger.log(Level.INFO, "Cannot walk file tree to calculate folder size", ioEx);
        }

        return -1;
    }

    public static long getFolderSize(Logger logger, Path folder) {
        try {
            return Files.walk(folder, 3, FileVisitOption.FOLLOW_LINKS)
                    .parallel()
                    .mapToLong(path -> {
                        try {
                            return Files.size(path);
                        } catch (IOException e) {
                            return 0;
                        }
                    }).sum();
        } catch (IOException ioEx) {
            logger.log(Level.INFO, "Cannot walk file tree to calculate folder size", ioEx);
        }

        return -1;
    }

Try With Resources try(Stream<Path> walk=Files.walk(folder,3,FileVisitOption.FOLLOW_LINKS)) in method public getFolderSize(logger Logger, folder Path) : long from class com.github.games647.lagmonitor.utils.LagUtils


    public void createTables() throws SQLException {
        try (Connection con = dataSource.getConnection(); Statement tableStmt = con.createStatement()) {
            tableStmt.execute("CREATE TABLE IF NOT EXISTS " + tablePrefix + TPS_TABLE + " ("
                    + "tps_id INTEGER UNSIGNED PRIMARY KEY AUTO_INCREMENT, "
                    + "tps FLOAT UNSIGNED NOT NULL, "
                    + "updated TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP"
                    + ')');

            tableStmt.execute("CREATE TABLE IF NOT EXISTS " + tablePrefix + MONITOR_TABLE + " ("
                    + "monitor_id INTEGER UNSIGNED PRIMARY KEY AUTO_INCREMENT, "
                    + "process_usage FLOAT UNSIGNED NOT NULL, "
                    + "os_usage FLOAT UNSIGNED NOT NULL, "
                    + "free_ram MEDIUMINT UNSIGNED NOT NULL, "
                    + "free_ram_pct FLOAT UNSIGNED NOT NULL, "
                    + "os_free_ram MEDIUMINT UNSIGNED NOT NULL, "
                    + "os_free_ram_pct FLOAT UNSIGNED NOT NULL, "
                    + "load_avg FLOAT UNSIGNED NOT NULL, "
                    + "updated TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP"
                    + ')');

            tableStmt.execute("CREATE TABLE IF NOT EXISTS " + tablePrefix + WORLDS_TABLE + " ("
                    + "world_id INTEGER UNSIGNED PRIMARY KEY AUTO_INCREMENT, "
                    + "monitor_id INTEGER UNSIGNED NOT NULL, "
                    + "world_name VARCHAR(255) NOT NULL, "
                    + "chunks_loaded SMALLINT UNSIGNED NOT NULL, "
                    + "tile_entities SMALLINT UNSIGNED NOT NULL, "
                    + "world_size SMALLINT UNSIGNED NOT NULL, "
                    + "entities INT UNSIGNED NOT NULL, "
                    + "FOREIGN KEY (monitor_id) REFERENCES " + tablePrefix + MONITOR_TABLE + "(monitor_id) "
                    + ')');

            tableStmt.execute("CREATE TABLE IF NOT EXISTS " + tablePrefix + PLAYERS_TABLE + " ("
                    + "world_id INTEGER UNSIGNED, "
                    + "uuid CHAR(40) NOT NULL, "
                    + "name VARCHAR(16) NOT NULL, "
                    + "ping SMALLINT UNSIGNED NOT NULL, "
                    + "PRIMARY KEY (world_id, uuid), "
                    + "FOREIGN KEY (world_id) REFERENCES " + tablePrefix + WORLDS_TABLE + "(world_id) "
                    + ')');

            tableStmt.execute("CREATE TABLE IF NOT EXISTS " + tablePrefix + NATIVE_TABLE + " ("
                    + "native_id INTEGER UNSIGNED PRIMARY KEY AUTO_INCREMENT, "
                    + "mc_read SMALLINT UNSIGNED , "
                    + "mc_write SMALLINT UNSIGNED, "
                    + "free_space INT UNSIGNED, "
                    + "free_space_pct FLOAT UNSIGNED, "
                    + "disk_read SMALLINT UNSIGNED, "
                    + "disk_write SMALLINT UNSIGNED, "
                    + "net_read SMALLINT UNSIGNED, "
                    + "net_write SMALLINT UNSIGNED, "
                    + "updated TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP"
                    + ')');
        }
    }

    public void createTables() throws SQLException {
        Connection con = null;
        Statement createTpsStmt = null;
        try {
            con = getConnection();

            createTpsStmt = con.createStatement();
            createTpsStmt.execute("CREATE TABLE IF NOT EXISTS " + tablePrefix + TPS_TABLE + " ("
                    + "tps_id INTEGER UNSIGNED PRIMARY KEY AUTO_INCREMENT, "
                    + "tps FLOAT UNSIGNED NOT NULL, "
                    + "updated TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP"
                    + ')');

            createTpsStmt.execute("CREATE TABLE IF NOT EXISTS " + tablePrefix + MONITOR_TABLE + " ("
                    + "monitor_id INTEGER UNSIGNED PRIMARY KEY AUTO_INCREMENT, "
                    + "process_usage FLOAT UNSIGNED NOT NULL, "
                    + "os_usage FLOAT UNSIGNED NOT NULL, "
                    + "free_ram MEDIUMINT UNSIGNED NOT NULL, "
                    + "free_ram_pct FLOAT UNSIGNED NOT NULL, "
                    + "os_free_ram MEDIUMINT UNSIGNED NOT NULL, "
                    + "os_free_ram_pct FLOAT UNSIGNED NOT NULL, "
                    + "load_avg FLOAT UNSIGNED NOT NULL, "
                    + "updated TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP"
                    + ')');

            createTpsStmt.execute("CREATE TABLE IF NOT EXISTS " + tablePrefix + WORLDS_TABLE + " ("
                    + "world_id INTEGER UNSIGNED PRIMARY KEY AUTO_INCREMENT, "
                    + "monitor_id INTEGER UNSIGNED NOT NULL, "
                    + "world_name VARCHAR(255) NOT NULL, "
                    + "chunks_loaded SMALLINT UNSIGNED NOT NULL, "
                    + "tile_entities SMALLINT UNSIGNED NOT NULL, "
                    + "world_size SMALLINT UNSIGNED NOT NULL, "
                    + "entities INT UNSIGNED NOT NULL, "
                    + "FOREIGN KEY (monitor_id) REFERENCES " + tablePrefix + MONITOR_TABLE + "(monitor_id) "
                    + ')');

            createTpsStmt.execute("CREATE TABLE IF NOT EXISTS " + tablePrefix + PLAYERS_TABLE + " ("
                    + "world_id INTEGER UNSIGNED, "
                    + "uuid CHAR(40) NOT NULL, "
                    + "name VARCHAR(16) NOT NULL, "
                    + "ping SMALLINT UNSIGNED NOT NULL, "
                    + "PRIMARY KEY (world_id, uuid), "
                    + "FOREIGN KEY (world_id) REFERENCES " + tablePrefix + WORLDS_TABLE + "(world_id) "
                    + ')');

            createTpsStmt.execute("CREATE TABLE IF NOT EXISTS " + tablePrefix + NATIVE_TABLE + " ("
                    + "native_id INTEGER UNSIGNED PRIMARY KEY AUTO_INCREMENT, "
                    + "mc_read SMALLINT UNSIGNED , "
                    + "mc_write SMALLINT UNSIGNED, "
                    + "free_space INT UNSIGNED, "
                    + "free_space_pct FLOAT UNSIGNED, "
                    + "disk_read SMALLINT UNSIGNED, "
                    + "disk_write SMALLINT UNSIGNED, "
                    + "net_read SMALLINT UNSIGNED, "
                    + "net_write SMALLINT UNSIGNED, "
                    + "updated TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP"
                    + ')');
        } finally {
            closeQuietly(createTpsStmt);
            closeQuietly(con);
        }
    }

Try With Resources try(Connection con=dataSource.getConnection(); Statement tableStmt=con.createStatement()) in method public createTables() : void from class com.github.games647.lagmonitor.storage.Storage


    public int saveMonitor(float procUsage, float osUsage, int freeRam, float freeRamPct, int osRam, float osRamPct
            , float loadAvg) {
        try (Connection con = dataSource.getConnection();
             PreparedStatement stmt = con.prepareStatement("INSERT INTO " + tablePrefix + MONITOR_TABLE
                     + " (process_usage, os_usage, free_ram, free_ram_pct, os_free_ram, os_free_ram_pct, load_avg)"
                     + " VALUES (?, ?, ?, ?, ?, ?, ?)", Statement.RETURN_GENERATED_KEYS)) {
            stmt.setFloat(1, procUsage);
            stmt.setFloat(2, osUsage);
            stmt.setInt(3, freeRam);
            stmt.setFloat(4, freeRamPct);
            stmt.setInt(5, osRam);
            stmt.setFloat(6, osRamPct);
            stmt.setFloat(7, loadAvg);
            stmt.execute();

            try (ResultSet generatedKeys = stmt.getGeneratedKeys()) {
                if (generatedKeys.next()) {
                    return generatedKeys.getInt(1);
                }
            }
        } catch (SQLException sqlEx) {
            plugin.getLogger().log(Level.SEVERE, "Error saving monitor data to database", sqlEx);
            plugin.getLogger().log(Level.SEVERE, "Using this data {0}"
                    , Lists.newArrayList(procUsage, osUsage, freeRam, freeRamPct, osRam, osRamPct, loadAvg));
        }

        return -1;
    }

    public int saveMonitor(float procUsage, float osUsage, int freeRam, float freeRamPct, int osRam, float osRamPct
            , float loadAvg) {
        Connection con = null;
        PreparedStatement saveMonitorStmt = null;
        ResultSet generatedKeys = null;
        try {
            con = getConnection();

            saveMonitorStmt = con.prepareStatement("INSERT INTO " + tablePrefix + MONITOR_TABLE
                    + " (process_usage, os_usage, free_ram, free_ram_pct, os_free_ram, os_free_ram_pct, load_avg)"
                    + " VALUES (?, ?, ?, ?, ?, ?, ?)", Statement.RETURN_GENERATED_KEYS);
            saveMonitorStmt.setFloat(1, procUsage);
            saveMonitorStmt.setFloat(2, osUsage);
            saveMonitorStmt.setInt(3, freeRam);
            saveMonitorStmt.setFloat(4, freeRamPct);
            saveMonitorStmt.setInt(5, osRam);
            saveMonitorStmt.setFloat(6, osRamPct);
            saveMonitorStmt.setFloat(7, loadAvg);
            saveMonitorStmt.execute();

            generatedKeys = saveMonitorStmt.getGeneratedKeys();
            if (generatedKeys.next()) {
                return generatedKeys.getInt(1);
            }
        } catch (SQLException sqlEx) {
            plugin.getLogger().log(Level.SEVERE, "Error saving monitor data to database", sqlEx);
            plugin.getLogger().log(Level.SEVERE, "Using this data {0}"
                    , Lists.newArrayList(procUsage, osUsage, freeRam, freeRamPct, osRam, osRamPct, loadAvg));
        } finally {
            closeQuietly(generatedKeys);
            closeQuietly(saveMonitorStmt);
            closeQuietly(con);
        }

        return -1;
    }

Try With Resources try(Connection con=dataSource.getConnection(); PreparedStatement stmt=con.prepareStatement("INSERT INTO " + tablePrefix + MONITOR_TABLE + " (process_usage, os_usage, free_ram, free_ram_pct, os_free_ram, os_free_ram_pct, load_avg)" + " VALUES (?, ?, ?, ?, ?, ?, ?)",Statement.RETURN_GENERATED_KEYS)) in method public saveMonitor(procUsage float, osUsage float, freeRam int, freeRamPct float, osRam int, osRamPct float, loadAvg float) : int from class com.github.games647.lagmonitor.storage.Storage


    public boolean saveWorlds(int monitorId, Collection<WorldData> worldsData) {
        if (worldsData.isEmpty()) {
            return false;
        }

        try (Connection con = dataSource.getConnection();
             PreparedStatement stmt = con.prepareStatement("INSERT INTO " + tablePrefix + WORLDS_TABLE
                     + " (monitor_id, world_name, chunks_loaded, tile_entities, entities, world_size)"
                     + " VALUES (?, ?, ?, ?, ?, ?)", Statement.RETURN_GENERATED_KEYS)) {
            for (WorldData worldData : worldsData) {
                stmt.setInt(1, monitorId);
                stmt.setString(2, worldData.getWorldName());
                stmt.setInt(3, worldData.getLoadedChunks());
                stmt.setInt(4, worldData.getTileEntities());
                stmt.setInt(5, worldData.getEntities());
                stmt.setInt(6, worldData.getWorldSize());
                stmt.addBatch();
            }

            stmt.executeBatch();

            try (ResultSet generatedKeys = stmt.getGeneratedKeys()) {
                for (WorldData worldData : worldsData) {
                    if (generatedKeys.next()) {
                        worldData.setRowId(generatedKeys.getInt(1));
                    }
                }
            }

            return true;
        } catch (SQLException sqlEx) {
            plugin.getLogger().log(Level.SEVERE, "Error saving worlds data to database", sqlEx);
            plugin.getLogger().log(Level.SEVERE, "Using this data {0}", worldsData);
        }

        return false;
    }

    public boolean saveWorlds(int monitorId, Collection<WorldData> worldsData) {
        if (worldsData.isEmpty()) {
            return false;
        }

        Connection con = null;
        PreparedStatement saveMonitorStmt = null;
        ResultSet generatedKeys = null;
        try {
            con = getConnection();

            saveMonitorStmt = con.prepareStatement("INSERT INTO " + tablePrefix + WORLDS_TABLE
                    + " (monitor_id, world_name, chunks_loaded, tile_entities, entities, world_size)"
                    + " VALUES (?, ?, ?, ?, ?, ?)", Statement.RETURN_GENERATED_KEYS);

            for (WorldData worldData : worldsData) {
                saveMonitorStmt.setInt(1, monitorId);
                saveMonitorStmt.setString(2, worldData.getWorldName());
                saveMonitorStmt.setInt(3, worldData.getLoadedChunks());
                saveMonitorStmt.setInt(4, worldData.getTileEntities());
                saveMonitorStmt.setInt(5, worldData.getEntities());
                saveMonitorStmt.setInt(6, worldData.getWorldSize());
                saveMonitorStmt.addBatch();
            }

            saveMonitorStmt.executeBatch();
            generatedKeys = saveMonitorStmt.getGeneratedKeys();
            for (WorldData worldData : worldsData) {
                if (generatedKeys.next()) {
                    worldData.setRowId(generatedKeys.getInt(1));
                }
            }

            return true;
        } catch (SQLException sqlEx) {
            plugin.getLogger().log(Level.SEVERE, "Error saving worlds data to database", sqlEx);
            plugin.getLogger().log(Level.SEVERE, "Using this data {0}", worldsData);
        } finally {
            closeQuietly(generatedKeys);
            closeQuietly(saveMonitorStmt);
            closeQuietly(con);
        }

        return false;
    }

Try With Resources try(Connection con=dataSource.getConnection(); PreparedStatement stmt=con.prepareStatement("INSERT INTO " + tablePrefix + WORLDS_TABLE + " (monitor_id, world_name, chunks_loaded, tile_entities, entities, world_size)" + " VALUES (?, ?, ?, ?, ?, ?)",Statement.RETURN_GENERATED_KEYS)) in method public saveWorlds(monitorId int, worldsData Collection<WorldData>) : boolean from class com.github.games647.lagmonitor.storage.Storage


    public void saveNative(int mcRead, int mcWrite, long freeSpace, float freePct, int diskRead, int diskWrite
            , int netRead, int netWrite) {
        try (Connection con = dataSource.getConnection();
            PreparedStatement stmt = con.prepareStatement("INSERT INTO " + tablePrefix + NATIVE_TABLE
                    + " (mc_read, mc_write, free_space, free_space_pct, disk_read, disk_write, net_read, net_write)"
                    + " VALUES (?, ?, ?, ?, ?, ?, ?, ?)")) {
            stmt.setInt(1, mcRead);
            stmt.setInt(2, mcWrite);

            stmt.setInt(3, (int) freeSpace);

            stmt.setFloat(4, freePct);

            stmt.setInt(5, diskRead);
            stmt.setInt(6, diskWrite);

            stmt.setInt(7, netRead);
            stmt.setInt(8, netWrite);
            stmt.execute();
        } catch (SQLException sqlEx) {
            plugin.getLogger().log(Level.SEVERE, "Error saving native stats to database", sqlEx);
            plugin.getLogger().log(Level.SEVERE, "Using this data {0}"
                    , Lists.newArrayList(mcRead, mcWrite, freeSpace, freePct, diskRead, diskWrite, netRead, netWrite));
        }
    }

    public void saveNative(int mcRead, int mcWrite, long freeSpace, float freePct, int diskRead, int diskWrite
            , int netRead, int netWrite) {
        Connection con = null;
        PreparedStatement saveNativeStmt = null;
        try {
            con = getConnection();

            saveNativeStmt = con.prepareStatement("INSERT INTO " + tablePrefix + NATIVE_TABLE
                    + " (mc_read, mc_write, free_space, free_space_pct, disk_read, disk_write, net_read, net_write)"
                    + " VALUES (?, ?, ?, ?, ?, ?, ?, ?)");
            saveNativeStmt.setInt(1, mcRead);
            saveNativeStmt.setInt(2, mcWrite);

            saveNativeStmt.setInt(3, (int) freeSpace);

            saveNativeStmt.setFloat(4, freePct);

            saveNativeStmt.setInt(5, diskRead);
            saveNativeStmt.setInt(6, diskWrite);

            saveNativeStmt.setInt(7, netRead);
            saveNativeStmt.setInt(8, netWrite);
            saveNativeStmt.execute();
        } catch (SQLException sqlEx) {
            plugin.getLogger().log(Level.SEVERE, "Error saving native stats to database", sqlEx);
            plugin.getLogger().log(Level.SEVERE, "Using this data {0}"
                    , Lists.newArrayList(mcRead, mcWrite, freeSpace, freePct, diskRead, diskWrite, netRead, netWrite));
        } finally {
            closeQuietly(saveNativeStmt);
            closeQuietly(con);
        }
    }

Try With Resources try(Connection con=dataSource.getConnection(); PreparedStatement stmt=con.prepareStatement("INSERT INTO " + tablePrefix + NATIVE_TABLE + " (mc_read, mc_write, free_space, free_space_pct, disk_read, disk_write, net_read, net_write)" + " VALUES (?, ?, ?, ?, ?, ?, ?, ?)")) in method public saveNative(mcRead int, mcWrite int, freeSpace long, freePct float, diskRead int, diskWrite int, netRead int, netWrite int) : void from class com.github.games647.lagmonitor.storage.Storage


    public void saveTps(float tps) {
        try (Connection con = dataSource.getConnection();
             PreparedStatement stmt = con.prepareStatement("INSERT INTO " + tablePrefix
                     + TPS_TABLE + " (tps) VALUES (?)")) {
            stmt.setFloat(1, tps);
            stmt.execute();
        } catch (SQLException sqlEx) {
            plugin.getLogger().log(Level.SEVERE, "Error saving tps to database", sqlEx);
            plugin.getLogger().log(Level.SEVERE, "Using this data {0}", new Object[] {tps});
        }
    }

    public void saveTps(float tps) {
        Connection con = null;
        PreparedStatement saveTpsStmt = null;
        try {
            con = getConnection();

            saveTpsStmt = con.prepareStatement("INSERT INTO " + tablePrefix + TPS_TABLE + " (tps) VALUES (?)");
            saveTpsStmt.setFloat(1, tps);
            saveTpsStmt.execute();
        } catch (SQLException sqlEx) {
            plugin.getLogger().log(Level.SEVERE, "Error saving tps to database", sqlEx);
            plugin.getLogger().log(Level.SEVERE, "Using this data {0}", new Object[] {tps});
        } finally {
            closeQuietly(saveTpsStmt);
            closeQuietly(con);
        }
    }

Try With Resources try(Connection con=dataSource.getConnection(); PreparedStatement stmt=con.prepareStatement("INSERT INTO " + tablePrefix + TPS_TABLE + " (tps) VALUES (?)")) in method public saveTps(tps float) : void from class com.github.games647.lagmonitor.storage.Storage


    public boolean savePlayers(Collection<PlayerData> playerData) {
        if (playerData.isEmpty()) {
            return false;
        }

        try (Connection con = dataSource.getConnection();
            PreparedStatement stmt = con.prepareStatement("INSERT INTO " + tablePrefix + PLAYERS_TABLE
                    + " (world_id, uuid, name, ping) "
                    + "VALUES (?, ?, ?, ?)")) {
            for (PlayerData data : playerData) {
                stmt.setInt(1, data.getWorldId());
                stmt.setString(2, data.getUuid().toString());
                stmt.setString(3, data.getPlayerName());
                stmt.setInt(4, data.getPing());
                stmt.addBatch();
            }

            stmt.executeBatch();
            return true;
        } catch (SQLException sqlEx) {
            plugin.getLogger().log(Level.SEVERE, "Error saving player data to database", sqlEx);
            plugin.getLogger().log(Level.SEVERE, "Using this data {0}", playerData);
        }

        return false;
    }

    public boolean savePlayers(int monitorId, Collection<PlayerData> playerData) {
        if (playerData.isEmpty()) {
            return false;
        }

        Connection con = null;
        PreparedStatement saveMonitorStmt = null;
        ResultSet generatedKeys = null;
        try {
            con = getConnection();

            saveMonitorStmt = con.prepareStatement("INSERT INTO " + tablePrefix + PLAYERS_TABLE
                    + " (world_id, uuid, name, ping) "
                    + "VALUES (?, ?, ?, ?)");

            for (PlayerData data : playerData) {
                saveMonitorStmt.setInt(1, data.getWorldId());
                saveMonitorStmt.setString(2, data.getUuid().toString());
                saveMonitorStmt.setString(3, data.getPlayerName());
                saveMonitorStmt.setInt(4, data.getPing());
                saveMonitorStmt.addBatch();
            }

            saveMonitorStmt.executeBatch();
            return true;
        } catch (SQLException sqlEx) {
            plugin.getLogger().log(Level.SEVERE, "Error saving player data to database", sqlEx);
            plugin.getLogger().log(Level.SEVERE, "Using this data {0}", playerData);
        } finally {
            closeQuietly(generatedKeys);
            closeQuietly(saveMonitorStmt);
            closeQuietly(con);
        }

        return false;
    }

Try With Resources try(Connection con=dataSource.getConnection(); PreparedStatement stmt=con.prepareStatement("INSERT INTO " + tablePrefix + PLAYERS_TABLE + " (world_id, uuid, name, ping) " + "VALUES (?, ?, ?, ?)")) in method public savePlayers(playerData Collection<PlayerData>) : boolean from class com.github.games647.lagmonitor.storage.Storage


    public String paste() {
        try {
            HttpURLConnection httpConnection = (HttpURLConnection) new URL(PASTE_URL).openConnection();
            httpConnection.setRequestMethod("POST");
            httpConnection.setDoOutput(true);
            httpConnection.setDoInput(true);

            try (OutputStream outputStream = httpConnection.getOutputStream();
                 BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(outputStream, Charsets.UTF_8))) {
                writer.write("content=" + URLEncoder.encode(toString(), Charsets.UTF_8.name()));
                writer.write("&from=" + URLEncoder.encode(plugin.getName(), Charsets.UTF_8.name()));
                writer.flush();
            }

            StringBuilder inputBuilder = new StringBuilder();
            String line;
            try (BufferedReader reader = new BufferedReader(new InputStreamReader(httpConnection.getInputStream()))) {
                while ((line = reader.readLine()) != null) {
                    inputBuilder.append(line);
                }
            }

            String input = inputBuilder.toString();
            plugin.getLogger().log(Level.FINE, input);

            Object object = JSONValue.parse(input);
            if (object instanceof Map) {
                @SuppressWarnings("unchecked")
                String urlString = String.valueOf(((Map<Object, Object>) object).get("url"));
                return urlString;
            }

            plugin.getLogger().info("Failed to parse url");
        } catch (IOException ex) {
            plugin.getLogger().log(Level.SEVERE, null, ex);
        }

        return null;
    }

    public String paste() {
        Closer closer = Closer.create();
        try {
            HttpURLConnection httpConnection = (HttpURLConnection) new URL(PASTE_URL).openConnection();
            httpConnection.setRequestMethod("POST");
            httpConnection.setDoOutput(true);
            httpConnection.setDoInput(true);

            OutputStream outputStream = closer.register(httpConnection.getOutputStream());
            OutputStreamWriter streamWriter = closer.register(new OutputStreamWriter(outputStream, Charsets.UTF_8));
            BufferedWriter writer = closer.register(new BufferedWriter(streamWriter));

            writer.write("content=" + URLEncoder.encode(toString(), Charsets.UTF_8.name()));
            writer.write("&from=" + URLEncoder.encode(plugin.getName(), Charsets.UTF_8.name()));
            writer.flush();

            BufferedReader reader = closer
                    .register(new BufferedReader(closer
                            .register(new InputStreamReader(closer
                                    .register(httpConnection.getInputStream())))));

            StringBuilder inputBuilder = new StringBuilder();
            String line;
            while ((line = reader.readLine()) != null) {
                inputBuilder.append(line);
            }

            String input = inputBuilder.toString();
            plugin.getLogger().log(Level.FINE, input);

            Object object = JSONValue.parse(input);
            if (object instanceof Map) {
                @SuppressWarnings("unchecked")
                String urlString = String.valueOf(((Map<Object, Object>) object).get("url"));
                return urlString;
            }

            plugin.getLogger().info("Failed to parse url");
        } catch (IOException ex) {
            plugin.getLogger().log(Level.SEVERE, null, ex);
        } finally {
            try {
                closer.close();
            } catch (IOException ex) {
                plugin.getLogger().log(Level.SEVERE, null, ex);
            }
        }

        return null;
    }

Try With Resources try(OutputStream outputStream=httpConnection.getOutputStream(); BufferedWriter writer=new BufferedWriter(new OutputStreamWriter(outputStream,Charsets.UTF_8))) in method public paste() : String from class com.github.games647.lagmonitor.tasks.MonitorTask


    /**
     * Search for the first publically and privately defined method of the given name and parameter count.
     *
     * @param clazz - a class to start with.
     * @param methodName - the method name, or NULL to skip.
     * @param returnType - the expected return type, or NULL to ignore.
     * @param params - the expected parameters.
     * @return An object that invokes this specific method.
     * @throws IllegalStateException If we cannot find this method.
     */
    public static MethodInvoker getTypedMethod(Class<?> clazz, String methodName, Class<?> returnType, Class<?>... params) {
        for (final Method method : clazz.getDeclaredMethods()) {
            if ((methodName == null || method.getName().equals(methodName)) && (returnType == null) || method.getReturnType().equals(returnType) && Arrays.equals(method.getParameterTypes(), params)) {
                method.setAccessible(true);

                return (target, arguments) -> {
                    try {
                        return method.invoke(target, arguments);
                    } catch (Exception e) {
                        throw new RuntimeException("Cannot invoke method " + method, e);
                    }
                };
            }
        }

        // Search in every superclass
        if (clazz.getSuperclass() != null) {
            return getMethod(clazz.getSuperclass(), methodName, params);
        }

        throw new IllegalStateException(String.format("Unable to find method %s (%s).", methodName, Arrays.asList(params)));
    }

    /**
     * Search for the first publically and privately defined method of the given name and parameter count.
     *
     * @param clazz - a class to start with.
     * @param methodName - the method name, or NULL to skip.
     * @param returnType - the expected return type, or NULL to ignore.
     * @param params - the expected parameters.
     * @return An object that invokes this specific method.
     * @throws IllegalStateException If we cannot find this method.
     */
    public static MethodInvoker getTypedMethod(Class<?> clazz, String methodName, Class<?> returnType, Class<?>... params) {
        for (final Method method : clazz.getDeclaredMethods()) {
            if ((methodName == null || method.getName().equals(methodName)) && (returnType == null) || method.getReturnType().equals(returnType) && Arrays.equals(method.getParameterTypes(), params)) {
                method.setAccessible(true);

                return new MethodInvoker() {

                    @Override
                    public Object invoke(Object target, Object... arguments) {
                        try {
                            return method.invoke(target, arguments);
                        } catch (Exception e) {
                            throw new RuntimeException("Cannot invoke method " + method, e);
                        }
                    }

                };
            }
        }

        // Search in every superclass
        if (clazz.getSuperclass() != null) {
            return getMethod(clazz.getSuperclass(), methodName, params);
        }

        throw new IllegalStateException(String.format("Unable to find method %s (%s).", methodName, Arrays.asList(params)));
    }

Replace Anonymous With Lambda com.github.games647.lagmonitor.traffic.Reflection.getTypedMethod.new MethodInvoker with (target, arguments) -> {tryreturn method.invoke(target,arguments); in method public getTypedMethod(clazz Class<?>, methodName String, returnType Class<?>, params Class<?>...) : MethodInvoker from class com.github.games647.lagmonitor.traffic.Reflection


    /**
     * Search for the first publically and privately defined constructor of the given name and parameter count.
     *
     * @param clazz - a class to start with.
     * @param params - the expected parameters.
     * @return An object that invokes this constructor.
     * @throws IllegalStateException If we cannot find this method.
     */
    public static ConstructorInvoker getConstructor(Class<?> clazz, Class<?>... params) {
        for (final Constructor<?> constructor : clazz.getDeclaredConstructors()) {
            if (Arrays.equals(constructor.getParameterTypes(), params)) {
                constructor.setAccessible(true);

                return arguments -> {
                    try {
                        return constructor.newInstance(arguments);
                    } catch (Exception e) {
                        throw new RuntimeException("Cannot invoke constructor " + constructor, e);
                    }
                };
            }
        }

        throw new IllegalStateException(String.format("Unable to find constructor for %s (%s).", clazz, Arrays.asList(params)));
    }

    /**
     * Search for the first publically and privately defined constructor of the given name and parameter count.
     *
     * @param clazz - a class to start with.
     * @param params - the expected parameters.
     * @return An object that invokes this constructor.
     * @throws IllegalStateException If we cannot find this method.
     */
    public static ConstructorInvoker getConstructor(Class<?> clazz, Class<?>... params) {
        for (final Constructor<?> constructor : clazz.getDeclaredConstructors()) {
            if (Arrays.equals(constructor.getParameterTypes(), params)) {
                constructor.setAccessible(true);

                return new ConstructorInvoker() {

                    @Override
                    public Object invoke(Object... arguments) {
                        try {
                            return constructor.newInstance(arguments);
                        } catch (Exception e) {
                            throw new RuntimeException("Cannot invoke constructor " + constructor, e);
                        }
                    }

                };
            }
        }

        throw new IllegalStateException(String.format("Unable to find constructor for %s (%s).", clazz, Arrays.asList(params)));
    }

Replace Anonymous With Lambda com.github.games647.lagmonitor.traffic.Reflection.getConstructor.new ConstructorInvoker with arguments -> {tryreturn constructor.newInstance(arguments); in method public getConstructor(clazz Class<?>, params Class<?>...) : ConstructorInvoker from class com.github.games647.lagmonitor.traffic.Reflection


    private void pasteMonitor(final CommandSender sender) {
        Timer timer = plugin.getMonitorTimer();
        if (monitorTask == null && timer == null) {
            sender.sendMessage(ChatColor.DARK_RED + "Monitor is not running");
        }

        Bukkit.getScheduler().runTaskAsynchronously(plugin, () -> {
            String reportUrl = monitorTask.paste();
            if (reportUrl == null) {
                sender.sendMessage(ChatColor.DARK_RED + "Error occured. Please check the console");
            } else {
                sender.sendMessage(ChatColor.DARK_GREEN + "Report url: " + reportUrl + ".profile");
            }
        });
    }

    private void pasteMonitor(final CommandSender sender) {
        Timer timer = plugin.getMonitorTimer();
        if (monitorTask == null && timer == null) {
            sender.sendMessage(ChatColor.DARK_RED + "Monitor is not running");
        }

        Bukkit.getScheduler().runTaskAsynchronously(plugin, new Runnable() {
            @Override
            public void run() {
                String reportUrl = monitorTask.paste();
                if (reportUrl == null) {
                    sender.sendMessage(ChatColor.DARK_RED + "Error occured. Please check the console");
                } else {
                    sender.sendMessage(ChatColor.DARK_GREEN + "Report url: " + reportUrl + ".profile");
                }
            }
        });
    }

Replace Anonymous With Lambda com.github.games647.lagmonitor.commands.MonitorCommand.pasteMonitor.runTaskAsynchronously.new Runnable with () -> {String reportUrl=monitorTask.paste(); in method private pasteMonitor(sender CommandSender) : void from class com.github.games647.lagmonitor.commands.MonitorCommand


    private List<PlayerData> getPlayerData(final Map<UUID, WorldData> worldsData)
            throws InterruptedException, ExecutionException {
        Future<List<PlayerData>> playerFuture = Bukkit.getScheduler()
                .callSyncMethod(plugin, () -> {
                    Collection<? extends Player> onlinePlayers = Bukkit.getOnlinePlayers();
                    List<PlayerData> playerData = Lists.newArrayListWithCapacity(onlinePlayers.size());
                    for (Player player : onlinePlayers) {
                        UUID worldId = player.getWorld().getUID();

                        int worldRowId = 0;
                        WorldData worldData = worldsData.get(worldId);
                        if (worldData != null) {
                            worldRowId = worldData.getRowId();
                        }

                        int lastPing = (int) plugin.getPingHistoryTask().getHistory(player).getLastSample();
                        String playerName = player.getName();
                        UUID playerId = player.getUniqueId();
                        playerData.add(new PlayerData(worldRowId, playerId, playerName, lastPing));
                    }

                    return playerData;
                });

        return playerFuture.get();
    }

    private List<PlayerData> getPlayerData(final Map<UUID, WorldData> worldsData)
            throws InterruptedException, ExecutionException {
        Future<List<PlayerData>> playerFuture = Bukkit.getScheduler()
                .callSyncMethod(plugin, new Callable<List<PlayerData>>() {
                    @Override
                    public List<PlayerData> call() throws Exception {
                        Collection<? extends Player> onlinePlayers = Bukkit.getOnlinePlayers();
                        List<PlayerData> playerData = Lists.newArrayListWithCapacity(onlinePlayers.size());
                        for (Player player : onlinePlayers) {
                            UUID worldId = player.getWorld().getUID();

                            int worldRowId = 0;
                            WorldData worldData = worldsData.get(worldId);
                            if (worldData != null) {
                                worldRowId = worldData.getRowId();
                            }

                            int lastPing = (int) plugin.getPingHistoryTask().getHistory(player).getLastSample();
                            String playerName = player.getName();
                            UUID playerId = player.getUniqueId();
                            playerData.add(new PlayerData(worldRowId, playerId, playerName, lastPing));
                        }

                        return playerData;
                    }
                });

        return playerFuture.get();
    }

Replace Anonymous With Lambda com.github.games647.lagmonitor.storage.MonitorSaveTask.getPlayerData.playerFuture.callSyncMethod.new Callable<List<PlayerData>> with () -> {Collection<? extends Player> onlinePlayers=Bukkit.getOnlinePlayers(); in method private getPlayerData(worldsData Map<UUID,WorldData>) : List<PlayerData> from class com.github.games647.lagmonitor.storage.MonitorSaveTask


    private Map<UUID, WorldData> getWorldData()
            throws ExecutionException, InterruptedException {
        //this is not thread-safe and have to run sync
        Future<Map<UUID, WorldData>> worldFuture = Bukkit.getScheduler()
                .callSyncMethod(plugin, () -> {
                    List<World> worlds = Bukkit.getWorlds();
                    Map<UUID, WorldData> worldsData = Maps.newHashMapWithExpectedSize(worlds.size());
                    for (World world : worlds) {
                        UUID worldId = world.getUID();
                        String worldName = world.getName();
                        int tileEntities = 0;
                        for (Chunk loadedChunk : world.getLoadedChunks()) {
                            tileEntities += loadedChunk.getTileEntities().length;
                        }

                        int entities = world.getEntities().size();
                        int chunks = world.getLoadedChunks().length;

                        WorldData worldData = new WorldData(worldName, chunks, tileEntities, entities);
                        worldsData.put(worldId, worldData);
                    }

                    return worldsData;
                });

        Map<UUID, WorldData> worldsData = worldFuture.get();
        //this can run async because it's thread-safe
        for (Entry<UUID, WorldData> entry : worldsData.entrySet()) {
            UUID worldId = entry.getKey();
            WorldData worldData = entry.getValue();
            File worldFolder = Bukkit.getWorld(worldId).getWorldFolder();
            worldData.setWorldSize(byteToMega(getFolderSize(worldFolder)));
        }

        return worldsData;
    }

    private Map<UUID, WorldData> getWorldData()
            throws ExecutionException, InterruptedException {
        //this is not thread-safe and have to run sync
        Future<Map<UUID, WorldData>> worldFuture = Bukkit.getScheduler()
                .callSyncMethod(plugin, new Callable<Map<UUID, WorldData>>() {
                    @Override
                    public Map<UUID, WorldData> call() throws Exception {
                        List<World> worlds = Bukkit.getWorlds();
                        Map<UUID, WorldData> worldsData = Maps.newHashMapWithExpectedSize(worlds.size());
                        for (World world : worlds) {
                            UUID worldId = world.getUID();
                            String worldName = world.getName();
                            int tileEntities = 0;
                            for (Chunk loadedChunk : world.getLoadedChunks()) {
                                tileEntities += loadedChunk.getTileEntities().length;
                            }

                            int entities = world.getEntities().size();
                            int chunks = world.getLoadedChunks().length;

                            WorldData worldData = new WorldData(worldName, chunks, tileEntities, entities);
                            worldsData.put(worldId, worldData);
                        }

                        return worldsData;
                    }
                });

        Map<UUID, WorldData> worldsData = worldFuture.get();
        //this can run async because it's thread-safe
        for (Entry<UUID, WorldData> entry : worldsData.entrySet()) {
            UUID worldId = entry.getKey();
            WorldData worldData = entry.getValue();
            File worldFolder = Bukkit.getWorld(worldId).getWorldFolder();
            worldData.setWorldSize(byteToMega(getFolderSize(worldFolder)));
        }

        return worldsData;
    }

Replace Anonymous With Lambda com.github.games647.lagmonitor.storage.MonitorSaveTask.getWorldData.worldFuture.callSyncMethod.new Callable<Map<UUID,WorldData>> with () -> {List<World> worlds=Bukkit.getWorlds(); in method private getWorldData() : Map<UUID,WorldData> from class com.github.games647.lagmonitor.storage.MonitorSaveTask


    @Override
    public void run() {
        final float lastSample = plugin.getTpsHistoryTask().getLastSample();
        Bukkit.getScheduler().runTaskAsynchronously(plugin, () -> plugin.getStorage().saveTps(lastSample));
    }

    @Override
    public void run() {
        final float lastSample = plugin.getTpsHistoryTask().getLastSample();
        Bukkit.getScheduler().runTaskAsynchronously(plugin, new Runnable() {
            @Override
            public void run() {
                plugin.getStorage().saveTps(lastSample);
            }
        });
    }

Replace Anonymous With Lambda com.github.games647.lagmonitor.storage.TpsSaveTask.run.runTaskAsynchronously.new Runnable with () -> plugin.getStorage().saveTps(lastSample) in method public run() : void from class com.github.games647.lagmonitor.storage.TpsSaveTask


    /**
     * Construct a new instance of TinyProtocol, and start intercepting packets for all connected clients and future
     * clients.
     * <p>
     * You can construct multiple instances per plugin.
     *
     * @param plugin - the plugin.
     */
    public TinyProtocol(final Plugin plugin) {
        this.plugin = plugin;

        try {
            registerChannelHandler();
        } catch (IllegalArgumentException illegalArgumentException) {
            // Damn you, late bind
            plugin.getLogger().info("[TinyProtocol] Delaying server channel injection due to late bind.");

            // Damn you, late bind
            Bukkit.getScheduler().runTask(plugin, () -> {
                registerChannelHandler();
                plugin.getLogger().info("[TinyProtocol] Late bind injection successful.");
            });
        }
    }

    /**
     * Construct a new instance of TinyProtocol, and start intercepting packets for all connected clients and future
     * clients.
     * <p>
     * You can construct multiple instances per plugin.
     *
     * @param plugin - the plugin.
     */
    public TinyProtocol(final Plugin plugin) {
        this.plugin = plugin;

        try {
            registerChannelHandler();
        } catch (IllegalArgumentException illegalArgumentException) {
            // Damn you, late bind
            plugin.getLogger().info("[TinyProtocol] Delaying server channel injection due to late bind.");

            // Damn you, late bind
            Bukkit.getScheduler().runTask(plugin, new Runnable() {

                @Override
                public void run() {
                    registerChannelHandler();
                    plugin.getLogger().info("[TinyProtocol] Late bind injection successful.");
                }
            });
        }
    }

Replace Anonymous With Lambda com.github.games647.lagmonitor.traffic.TinyProtocol.TinyProtocol.runTask.new Runnable with () -> {registerChannelHandler(); in method public TinyProtocol(plugin Plugin) from class com.github.games647.lagmonitor.traffic.TinyProtocol


    public static void main(String[] args) {
        Configuration configuration = new Configuration().addAnnotatedClass(Person.class);

        SessionFactory sessionFactory = configuration.buildSessionFactory();

        try (sessionFactory) {
            Session session = sessionFactory.getCurrentSession();
            session.beginTransaction();

            Person person = session.get(Person.class, "Bob the builder");
            System.out.println(person);

            person.setAge(666);
            System.out.println(session.get(Person.class, "Bob the builder"));

            session.getTransaction().commit();
        }
    }

    public static void main(String[] args) {
        Configuration configuration = new Configuration().addAnnotatedClass(Person.class);

        SessionFactory sessionFactory = configuration.buildSessionFactory();
        Session session = sessionFactory.getCurrentSession();

        try {
            session.beginTransaction();

            Person person = session.get(Person.class, 3);
            System.out.println(person);

            session.getTransaction().commit();
        }
        finally {
            sessionFactory.close();
        }
    }

Try With Resources try(sessionFactory) in method public main(args String[]) : void from class Hibernate.Main


    public <T> T tx(final Function<Session, T> command) {
        final Session session = sf.openSession();
        final Transaction tx = session.beginTransaction();
        try (session) {
            T rsl = command.apply(session);
            tx.commit();
            return rsl;
        } catch (final Exception e) {
            if (tx.isActive()) {
                tx.rollback();
            }
            LOG.error("Hibernate transaction exception");
            throw (e);
        }
    }

    public <T> T tx(Function<Session, T> command) {
        final Session session = sf.openSession();
        try {
            Transaction tx = session.beginTransaction();
            T rsl = command.apply(session);
            tx.commit();
            return rsl;
        } catch (TransactionException e) {
            Transaction tx = session.getTransaction();
            if (tx.isActive()) {
                tx.rollback();
            }
            LOG.error("Hibernate transaction exception");
            throw (e);
        }
    }

Try With Resources try(session) in method public tx(command Function<Session,T>) : T from class ru.job4j.store.CrudRepository


	public static <T, D extends Dto> T convertToModel(D dto, Class<T> modelType)
			throws InstantiationException, IllegalAccessException {
		PropertyDescriptor[] props = PropertyUtils.getPropertyDescriptors(modelType);
		T mdl = modelType.newInstance();

		for (PropertyDescriptor prop : props) {
			Object value;
			try {
				value = PropertyUtils.getProperty(dto, prop.getName());
				PropertyUtils.setProperty(mdl, prop.getName(), value);
			} catch (IllegalAccessException | InvocationTargetException | NoSuchMethodException e) {
			}

		}
		return mdl;

	}

	public static <T, D extends Dto> T convertToModel(D dto, Class<T> modelType)
			throws InstantiationException, IllegalAccessException {
		PropertyDescriptor[] props = PropertyUtils.getPropertyDescriptors(modelType);
		T mdl = modelType.newInstance();

		for (PropertyDescriptor prop : props) {
			Object value;
			try {
				value = PropertyUtils.getProperty(dto, prop.getName());
				PropertyUtils.setProperty(mdl, prop.getName(), value);
			} catch (IllegalAccessException e) {
			} catch (InvocationTargetException e) {
			} catch (NoSuchMethodException e) {
			}

		}
		return mdl;

	}

Merge Catch [catch(IllegalAccessException e), catch(InvocationTargetException e), catch(NoSuchMethodException e)] to catch(IllegalAccessException|InvocationTargetException|NoSuchMethodException e) in method public convertToModel(dto D, modelType Class<T>) : T from class org.ttrung.mai.tool.util.common.DtoUtil