output
stringlengths
64
73.2k
input
stringlengths
208
73.3k
instruction
stringclasses
1 value
#fixed code @Override public void run() { try { LOGGER.info(I18n.UPDATE_LOADING); URLConnection con = new URL("https://raw.githubusercontent.com/ron190/jsql-injection/master/.version").openConnection(); con.setReadTimeout(60000); con.setConnectTimeout(60000); BufferedReader reader = new BufferedReader(new InputStreamReader(con.getInputStream())); String line, pageSource = ""; while ((line = reader.readLine()) != null) { pageSource += line + "\n"; } reader.close(); Float gitVersion = Float.parseFloat(pageSource); MediatorGUI.model(); if (gitVersion <= Float.parseFloat(InjectionModel.JSQLVERSION)) { LOGGER.debug(I18n.UPDATE_UPTODATE); } else { LOGGER.warn(I18n.UPDATE_NEW_VERSION_AVAILABLE); } } catch (NumberFormatException e) { LOGGER.warn(I18n.UPDATE_EXCEPTION); LOGGER.error(e, e); } catch (IOException e) { LOGGER.warn(I18n.UPDATE_EXCEPTION); LOGGER.error(e, e); } }
#vulnerable code @Override public void run() { try { LOGGER.info(I18n.UPDATE_LOADING); URLConnection con = new URL("http://jsql-injection.googlecode.com/git/.version").openConnection(); con.setReadTimeout(60000); con.setConnectTimeout(60000); BufferedReader reader = new BufferedReader(new InputStreamReader(con.getInputStream())); String line, pageSource = ""; while ((line = reader.readLine()) != null) { pageSource += line + "\n"; } reader.close(); Float gitVersion = Float.parseFloat(pageSource); MediatorGUI.model(); if (gitVersion <= Float.parseFloat(InjectionModel.JSQLVERSION)) { LOGGER.debug(I18n.UPDATE_UPTODATE); } else { LOGGER.warn(I18n.UPDATE_NEW_VERSION_AVAILABLE); } } catch (NumberFormatException e) { LOGGER.warn(I18n.UPDATE_EXCEPTION); LOGGER.error(e, e); } catch (IOException e) { LOGGER.warn(I18n.UPDATE_EXCEPTION); LOGGER.error(e, e); } } #location 9 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public String tamper(String sqlQueryDefault) { String lead = null; String sqlQuery = null; String trail = null; // Transform only SQL query without HTTP parameters and syntax changed, like p=1'+[sql] Matcher matcherSql = Pattern.compile("(?s)(.*<tampering>)(.*)(</tampering>.*)").matcher(sqlQueryDefault); if (matcherSql.find()) { lead = matcherSql.group(1); sqlQuery = matcherSql.group(2); trail = matcherSql.group(3); } if (this.isEval) { sqlQuery = eval(sqlQuery, this.customTamper); } if (this.isRandomCase) { sqlQuery = eval(sqlQuery, TamperingType.RANDOM_CASE.instance().getJavascript()); } if (this.isEqualToLike) { sqlQuery = eval(sqlQuery, TamperingType.EQUAL_TO_LIKE.instance().getJavascript()); } sqlQuery = lead + sqlQuery + trail; sqlQuery = sqlQuery.replaceAll("(?i)<tampering>", StringUtils.EMPTY); sqlQuery = sqlQuery.replaceAll("(?i)</tampering>", StringUtils.EMPTY); // Empty when checking character insertion if (StringUtils.isEmpty(sqlQuery)) { return StringUtils.EMPTY; } // Transform all query, SQL and HTTP if (this.isHexToChar) { sqlQuery = eval(sqlQuery, TamperingType.HEX_TO_CHAR.instance().getJavascript()); } if (this.isStringToChar) { sqlQuery = eval(sqlQuery, TamperingType.STRING_TO_CHAR.instance().getJavascript()); } if (this.isFunctionComment) { sqlQuery = eval(sqlQuery, TamperingType.COMMENT_TO_METHOD_SIGNATURE.instance().getJavascript()); } if (this.isVersionComment) { sqlQuery = eval(sqlQuery, TamperingType.VERSIONED_COMMENT_TO_METHOD_SIGNATURE.instance().getJavascript()); } // Dependency to: EQUAL_TO_LIKE if (this.isSpaceToDashComment) { sqlQuery = eval(sqlQuery, TamperingType.SPACE_TO_DASH_COMMENT.instance().getJavascript()); } else if (this.isSpaceToMultilineComment) { sqlQuery = eval(sqlQuery, TamperingType.SPACE_TO_MULTILINE_COMMENT.instance().getJavascript()); } else if (this.isSpaceToSharpComment) { sqlQuery = eval(sqlQuery, TamperingType.SPACE_TO_SHARP_COMMENT.instance().getJavascript()); } if (this.isBase64) { sqlQuery = eval(sqlQuery, TamperingType.BASE64.instance().getJavascript()); } // Include character insertion at the beginning of query if (this.isQuoteToUtf8) { sqlQuery = eval(sqlQuery, TamperingType.QUOTE_TO_UTF8.instance().getJavascript()); } return sqlQuery; }
#vulnerable code public String tamper(String sqlQueryDefault) { String lead = null; String sqlQuery = null; String trail = null; Matcher matcherSql = Pattern.compile("(?s)(.*<tampering>)(.*)(</tampering>.*)").matcher(sqlQueryDefault); if (matcherSql.find()) { lead = matcherSql.group(1); sqlQuery = matcherSql.group(2); trail = matcherSql.group(3); } // Empty when checking character insertion if (StringUtils.isEmpty(sqlQuery)) { return StringUtils.EMPTY; } if (this.isHexToChar) { sqlQuery = eval(sqlQuery, TamperingType.HEX_TO_CHAR.instance().getJavascript()); } if (this.isStringToChar) { sqlQuery = eval(sqlQuery, TamperingType.STRING_TO_CHAR.instance().getJavascript()); } if (this.isFunctionComment) { sqlQuery = eval(sqlQuery, TamperingType.COMMENT_TO_METHOD_SIGNATURE.instance().getJavascript()); } if (this.isVersionComment) { sqlQuery = eval(sqlQuery, TamperingType.VERSIONED_COMMENT_TO_METHOD_SIGNATURE.instance().getJavascript()); } if (this.isEqualToLike) { sqlQuery = eval(sqlQuery, TamperingType.EQUAL_TO_LIKE.instance().getJavascript()); } // Dependency to: EQUAL_TO_LIKE if (this.isSpaceToDashComment) { sqlQuery = eval(sqlQuery, TamperingType.SPACE_TO_DASH_COMMENT.instance().getJavascript()); } else if (this.isSpaceToMultilineComment) { sqlQuery = eval(sqlQuery, TamperingType.SPACE_TO_MULTILINE_COMMENT.instance().getJavascript()); } else if (this.isSpaceToSharpComment) { sqlQuery = eval(sqlQuery, TamperingType.SPACE_TO_SHARP_COMMENT.instance().getJavascript()); } if (this.isRandomCase) { sqlQuery = eval(sqlQuery, TamperingType.RANDOM_CASE.instance().getJavascript()); } if (this.isEval) { sqlQuery = eval(sqlQuery, this.customTamper); } if (this.isBase64) { sqlQuery = eval(sqlQuery, TamperingType.BASE64.instance().getJavascript()); } sqlQuery = lead + sqlQuery + trail; // Include character insertion at the beginning of query if (this.isQuoteToUtf8) { sqlQuery = eval(sqlQuery, TamperingType.QUOTE_TO_UTF8.instance().getJavascript()); } // Problme si le tag contient des caractres spciaux sqlQuery = sqlQuery.replaceAll("(?i)<tampering>", StringUtils.EMPTY); sqlQuery = sqlQuery.replaceAll("(?i)</tampering>", StringUtils.EMPTY); return sqlQuery; } #location 63 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public String tamper(String sqlQueryDefault) { String lead = null; String sqlQuery = null; String trail = null; // Transform only SQL query without HTTP parameters and syntax changed, like p=1'+[sql] Matcher matcherSql = Pattern.compile("(?s)(.*<tampering>)(.*)(</tampering>.*)").matcher(sqlQueryDefault); if (matcherSql.find()) { lead = matcherSql.group(1); sqlQuery = matcherSql.group(2); trail = matcherSql.group(3); } if (this.isEval) { sqlQuery = eval(sqlQuery, this.customTamper); } if (this.isRandomCase) { sqlQuery = eval(sqlQuery, TamperingType.RANDOM_CASE.instance().getJavascript()); } if (this.isEqualToLike) { sqlQuery = eval(sqlQuery, TamperingType.EQUAL_TO_LIKE.instance().getJavascript()); } sqlQuery = lead + sqlQuery + trail; sqlQuery = sqlQuery.replaceAll("(?i)<tampering>", StringUtils.EMPTY); sqlQuery = sqlQuery.replaceAll("(?i)</tampering>", StringUtils.EMPTY); // Empty when checking character insertion if (StringUtils.isEmpty(sqlQuery)) { return StringUtils.EMPTY; } // Transform all query, SQL and HTTP if (this.isHexToChar) { sqlQuery = eval(sqlQuery, TamperingType.HEX_TO_CHAR.instance().getJavascript()); } if (this.isStringToChar) { sqlQuery = eval(sqlQuery, TamperingType.STRING_TO_CHAR.instance().getJavascript()); } if (this.isFunctionComment) { sqlQuery = eval(sqlQuery, TamperingType.COMMENT_TO_METHOD_SIGNATURE.instance().getJavascript()); } if (this.isVersionComment) { sqlQuery = eval(sqlQuery, TamperingType.VERSIONED_COMMENT_TO_METHOD_SIGNATURE.instance().getJavascript()); } // Dependency to: EQUAL_TO_LIKE if (this.isSpaceToDashComment) { sqlQuery = eval(sqlQuery, TamperingType.SPACE_TO_DASH_COMMENT.instance().getJavascript()); } else if (this.isSpaceToMultilineComment) { sqlQuery = eval(sqlQuery, TamperingType.SPACE_TO_MULTILINE_COMMENT.instance().getJavascript()); } else if (this.isSpaceToSharpComment) { sqlQuery = eval(sqlQuery, TamperingType.SPACE_TO_SHARP_COMMENT.instance().getJavascript()); } if (this.isBase64) { sqlQuery = eval(sqlQuery, TamperingType.BASE64.instance().getJavascript()); } // Include character insertion at the beginning of query if (this.isQuoteToUtf8) { sqlQuery = eval(sqlQuery, TamperingType.QUOTE_TO_UTF8.instance().getJavascript()); } return sqlQuery; }
#vulnerable code public String tamper(String sqlQueryDefault) { String lead = null; String sqlQuery = null; String trail = null; Matcher matcherSql = Pattern.compile("(?s)(.*<tampering>)(.*)(</tampering>.*)").matcher(sqlQueryDefault); if (matcherSql.find()) { lead = matcherSql.group(1); sqlQuery = matcherSql.group(2); trail = matcherSql.group(3); } // Empty when checking character insertion if (StringUtils.isEmpty(sqlQuery)) { return StringUtils.EMPTY; } if (this.isHexToChar) { sqlQuery = eval(sqlQuery, TamperingType.HEX_TO_CHAR.instance().getJavascript()); } if (this.isStringToChar) { sqlQuery = eval(sqlQuery, TamperingType.STRING_TO_CHAR.instance().getJavascript()); } if (this.isFunctionComment) { sqlQuery = eval(sqlQuery, TamperingType.COMMENT_TO_METHOD_SIGNATURE.instance().getJavascript()); } if (this.isVersionComment) { sqlQuery = eval(sqlQuery, TamperingType.VERSIONED_COMMENT_TO_METHOD_SIGNATURE.instance().getJavascript()); } if (this.isEqualToLike) { sqlQuery = eval(sqlQuery, TamperingType.EQUAL_TO_LIKE.instance().getJavascript()); } // Dependency to: EQUAL_TO_LIKE if (this.isSpaceToDashComment) { sqlQuery = eval(sqlQuery, TamperingType.SPACE_TO_DASH_COMMENT.instance().getJavascript()); } else if (this.isSpaceToMultilineComment) { sqlQuery = eval(sqlQuery, TamperingType.SPACE_TO_MULTILINE_COMMENT.instance().getJavascript()); } else if (this.isSpaceToSharpComment) { sqlQuery = eval(sqlQuery, TamperingType.SPACE_TO_SHARP_COMMENT.instance().getJavascript()); } if (this.isRandomCase) { sqlQuery = eval(sqlQuery, TamperingType.RANDOM_CASE.instance().getJavascript()); } if (this.isEval) { sqlQuery = eval(sqlQuery, this.customTamper); } if (this.isBase64) { sqlQuery = eval(sqlQuery, TamperingType.BASE64.instance().getJavascript()); } sqlQuery = lead + sqlQuery + trail; // Include character insertion at the beginning of query if (this.isQuoteToUtf8) { sqlQuery = eval(sqlQuery, TamperingType.QUOTE_TO_UTF8.instance().getJavascript()); } // Problme si le tag contient des caractres spciaux sqlQuery = sqlQuery.replaceAll("(?i)<tampering>", StringUtils.EMPTY); sqlQuery = sqlQuery.replaceAll("(?i)</tampering>", StringUtils.EMPTY); return sqlQuery; } #location 29 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public String tamper(String sqlQueryDefault) { String lead = null; String sqlQuery = null; String trail = null; // Transform only SQL query without HTTP parameters and syntax changed, like p=1'+[sql] Matcher matcherSql = Pattern.compile("(?s)(.*<tampering>)(.*)(</tampering>.*)").matcher(sqlQueryDefault); if (matcherSql.find()) { lead = matcherSql.group(1); sqlQuery = matcherSql.group(2); trail = matcherSql.group(3); } if (this.isEval) { sqlQuery = eval(sqlQuery, this.customTamper); } if (this.isRandomCase) { sqlQuery = eval(sqlQuery, TamperingType.RANDOM_CASE.instance().getJavascript()); } if (this.isEqualToLike) { sqlQuery = eval(sqlQuery, TamperingType.EQUAL_TO_LIKE.instance().getJavascript()); } sqlQuery = lead + sqlQuery + trail; sqlQuery = sqlQuery.replaceAll("(?i)<tampering>", StringUtils.EMPTY); sqlQuery = sqlQuery.replaceAll("(?i)</tampering>", StringUtils.EMPTY); // Empty when checking character insertion if (StringUtils.isEmpty(sqlQuery)) { return StringUtils.EMPTY; } // Transform all query, SQL and HTTP if (this.isHexToChar) { sqlQuery = eval(sqlQuery, TamperingType.HEX_TO_CHAR.instance().getJavascript()); } if (this.isStringToChar) { sqlQuery = eval(sqlQuery, TamperingType.STRING_TO_CHAR.instance().getJavascript()); } if (this.isFunctionComment) { sqlQuery = eval(sqlQuery, TamperingType.COMMENT_TO_METHOD_SIGNATURE.instance().getJavascript()); } if (this.isVersionComment) { sqlQuery = eval(sqlQuery, TamperingType.VERSIONED_COMMENT_TO_METHOD_SIGNATURE.instance().getJavascript()); } // Dependency to: EQUAL_TO_LIKE if (this.isSpaceToDashComment) { sqlQuery = eval(sqlQuery, TamperingType.SPACE_TO_DASH_COMMENT.instance().getJavascript()); } else if (this.isSpaceToMultilineComment) { sqlQuery = eval(sqlQuery, TamperingType.SPACE_TO_MULTILINE_COMMENT.instance().getJavascript()); } else if (this.isSpaceToSharpComment) { sqlQuery = eval(sqlQuery, TamperingType.SPACE_TO_SHARP_COMMENT.instance().getJavascript()); } if (this.isBase64) { sqlQuery = eval(sqlQuery, TamperingType.BASE64.instance().getJavascript()); } // Include character insertion at the beginning of query if (this.isQuoteToUtf8) { sqlQuery = eval(sqlQuery, TamperingType.QUOTE_TO_UTF8.instance().getJavascript()); } return sqlQuery; }
#vulnerable code public String tamper(String sqlQueryDefault) { String lead = null; String sqlQuery = null; String trail = null; Matcher matcherSql = Pattern.compile("(?s)(.*<tampering>)(.*)(</tampering>.*)").matcher(sqlQueryDefault); if (matcherSql.find()) { lead = matcherSql.group(1); sqlQuery = matcherSql.group(2); trail = matcherSql.group(3); } // Empty when checking character insertion if (StringUtils.isEmpty(sqlQuery)) { return StringUtils.EMPTY; } if (this.isHexToChar) { sqlQuery = eval(sqlQuery, TamperingType.HEX_TO_CHAR.instance().getJavascript()); } if (this.isStringToChar) { sqlQuery = eval(sqlQuery, TamperingType.STRING_TO_CHAR.instance().getJavascript()); } if (this.isFunctionComment) { sqlQuery = eval(sqlQuery, TamperingType.COMMENT_TO_METHOD_SIGNATURE.instance().getJavascript()); } if (this.isVersionComment) { sqlQuery = eval(sqlQuery, TamperingType.VERSIONED_COMMENT_TO_METHOD_SIGNATURE.instance().getJavascript()); } if (this.isEqualToLike) { sqlQuery = eval(sqlQuery, TamperingType.EQUAL_TO_LIKE.instance().getJavascript()); } // Dependency to: EQUAL_TO_LIKE if (this.isSpaceToDashComment) { sqlQuery = eval(sqlQuery, TamperingType.SPACE_TO_DASH_COMMENT.instance().getJavascript()); } else if (this.isSpaceToMultilineComment) { sqlQuery = eval(sqlQuery, TamperingType.SPACE_TO_MULTILINE_COMMENT.instance().getJavascript()); } else if (this.isSpaceToSharpComment) { sqlQuery = eval(sqlQuery, TamperingType.SPACE_TO_SHARP_COMMENT.instance().getJavascript()); } if (this.isRandomCase) { sqlQuery = eval(sqlQuery, TamperingType.RANDOM_CASE.instance().getJavascript()); } if (this.isEval) { sqlQuery = eval(sqlQuery, this.customTamper); } if (this.isBase64) { sqlQuery = eval(sqlQuery, TamperingType.BASE64.instance().getJavascript()); } sqlQuery = lead + sqlQuery + trail; // Include character insertion at the beginning of query if (this.isQuoteToUtf8) { sqlQuery = eval(sqlQuery, TamperingType.QUOTE_TO_UTF8.instance().getJavascript()); } // Problme si le tag contient des caractres spciaux sqlQuery = sqlQuery.replaceAll("(?i)<tampering>", StringUtils.EMPTY); sqlQuery = sqlQuery.replaceAll("(?i)</tampering>", StringUtils.EMPTY); return sqlQuery; } #location 58 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public String tamper(String sqlQueryDefault) { String lead = null; String sqlQuery = null; String trail = null; // Transform only SQL query without HTTP parameters and syntax changed, like p=1'+[sql] Matcher matcherSql = Pattern.compile("(?s)(.*<tampering>)(.*)(</tampering>.*)").matcher(sqlQueryDefault); if (matcherSql.find()) { lead = matcherSql.group(1); sqlQuery = matcherSql.group(2); trail = matcherSql.group(3); } if (this.isEval) { sqlQuery = eval(sqlQuery, this.customTamper); } if (this.isRandomCase) { sqlQuery = eval(sqlQuery, TamperingType.RANDOM_CASE.instance().getJavascript()); } if (this.isEqualToLike) { sqlQuery = eval(sqlQuery, TamperingType.EQUAL_TO_LIKE.instance().getJavascript()); } sqlQuery = lead + sqlQuery + trail; sqlQuery = sqlQuery.replaceAll("(?i)<tampering>", StringUtils.EMPTY); sqlQuery = sqlQuery.replaceAll("(?i)</tampering>", StringUtils.EMPTY); // Empty when checking character insertion if (StringUtils.isEmpty(sqlQuery)) { return StringUtils.EMPTY; } // Transform all query, SQL and HTTP if (this.isHexToChar) { sqlQuery = eval(sqlQuery, TamperingType.HEX_TO_CHAR.instance().getJavascript()); } if (this.isStringToChar) { sqlQuery = eval(sqlQuery, TamperingType.STRING_TO_CHAR.instance().getJavascript()); } if (this.isFunctionComment) { sqlQuery = eval(sqlQuery, TamperingType.COMMENT_TO_METHOD_SIGNATURE.instance().getJavascript()); } if (this.isVersionComment) { sqlQuery = eval(sqlQuery, TamperingType.VERSIONED_COMMENT_TO_METHOD_SIGNATURE.instance().getJavascript()); } // Dependency to: EQUAL_TO_LIKE if (this.isSpaceToDashComment) { sqlQuery = eval(sqlQuery, TamperingType.SPACE_TO_DASH_COMMENT.instance().getJavascript()); } else if (this.isSpaceToMultilineComment) { sqlQuery = eval(sqlQuery, TamperingType.SPACE_TO_MULTILINE_COMMENT.instance().getJavascript()); } else if (this.isSpaceToSharpComment) { sqlQuery = eval(sqlQuery, TamperingType.SPACE_TO_SHARP_COMMENT.instance().getJavascript()); } if (this.isBase64) { sqlQuery = eval(sqlQuery, TamperingType.BASE64.instance().getJavascript()); } // Include character insertion at the beginning of query if (this.isQuoteToUtf8) { sqlQuery = eval(sqlQuery, TamperingType.QUOTE_TO_UTF8.instance().getJavascript()); } return sqlQuery; }
#vulnerable code public String tamper(String sqlQueryDefault) { String lead = null; String sqlQuery = null; String trail = null; Matcher matcherSql = Pattern.compile("(?s)(.*<tampering>)(.*)(</tampering>.*)").matcher(sqlQueryDefault); if (matcherSql.find()) { lead = matcherSql.group(1); sqlQuery = matcherSql.group(2); trail = matcherSql.group(3); } // Empty when checking character insertion if (StringUtils.isEmpty(sqlQuery)) { return StringUtils.EMPTY; } if (this.isHexToChar) { sqlQuery = eval(sqlQuery, TamperingType.HEX_TO_CHAR.instance().getJavascript()); } if (this.isStringToChar) { sqlQuery = eval(sqlQuery, TamperingType.STRING_TO_CHAR.instance().getJavascript()); } if (this.isFunctionComment) { sqlQuery = eval(sqlQuery, TamperingType.COMMENT_TO_METHOD_SIGNATURE.instance().getJavascript()); } if (this.isVersionComment) { sqlQuery = eval(sqlQuery, TamperingType.VERSIONED_COMMENT_TO_METHOD_SIGNATURE.instance().getJavascript()); } if (this.isEqualToLike) { sqlQuery = eval(sqlQuery, TamperingType.EQUAL_TO_LIKE.instance().getJavascript()); } // Dependency to: EQUAL_TO_LIKE if (this.isSpaceToDashComment) { sqlQuery = eval(sqlQuery, TamperingType.SPACE_TO_DASH_COMMENT.instance().getJavascript()); } else if (this.isSpaceToMultilineComment) { sqlQuery = eval(sqlQuery, TamperingType.SPACE_TO_MULTILINE_COMMENT.instance().getJavascript()); } else if (this.isSpaceToSharpComment) { sqlQuery = eval(sqlQuery, TamperingType.SPACE_TO_SHARP_COMMENT.instance().getJavascript()); } if (this.isRandomCase) { sqlQuery = eval(sqlQuery, TamperingType.RANDOM_CASE.instance().getJavascript()); } if (this.isEval) { sqlQuery = eval(sqlQuery, this.customTamper); } if (this.isBase64) { sqlQuery = eval(sqlQuery, TamperingType.BASE64.instance().getJavascript()); } sqlQuery = lead + sqlQuery + trail; // Include character insertion at the beginning of query if (this.isQuoteToUtf8) { sqlQuery = eval(sqlQuery, TamperingType.QUOTE_TO_UTF8.instance().getJavascript()); } // Problme si le tag contient des caractres spciaux sqlQuery = sqlQuery.replaceAll("(?i)<tampering>", StringUtils.EMPTY); sqlQuery = sqlQuery.replaceAll("(?i)</tampering>", StringUtils.EMPTY); return sqlQuery; } #location 73 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public String tamper(String sqlQueryDefault) { String lead = null; String sqlQuery = null; String trail = null; // Transform only SQL query without HTTP parameters and syntax changed, like p=1'+[sql] Matcher matcherSql = Pattern.compile("(?s)(.*<tampering>)(.*)(</tampering>.*)").matcher(sqlQueryDefault); if (matcherSql.find()) { lead = matcherSql.group(1); sqlQuery = matcherSql.group(2); trail = matcherSql.group(3); } if (this.isEval) { sqlQuery = eval(sqlQuery, this.customTamper); } if (this.isRandomCase) { sqlQuery = eval(sqlQuery, TamperingType.RANDOM_CASE.instance().getJavascript()); } if (this.isEqualToLike) { sqlQuery = eval(sqlQuery, TamperingType.EQUAL_TO_LIKE.instance().getJavascript()); } sqlQuery = lead + sqlQuery + trail; sqlQuery = sqlQuery.replaceAll("(?i)<tampering>", StringUtils.EMPTY); sqlQuery = sqlQuery.replaceAll("(?i)</tampering>", StringUtils.EMPTY); // Empty when checking character insertion if (StringUtils.isEmpty(sqlQuery)) { return StringUtils.EMPTY; } // Transform all query, SQL and HTTP if (this.isHexToChar) { sqlQuery = eval(sqlQuery, TamperingType.HEX_TO_CHAR.instance().getJavascript()); } if (this.isStringToChar) { sqlQuery = eval(sqlQuery, TamperingType.STRING_TO_CHAR.instance().getJavascript()); } if (this.isFunctionComment) { sqlQuery = eval(sqlQuery, TamperingType.COMMENT_TO_METHOD_SIGNATURE.instance().getJavascript()); } if (this.isVersionComment) { sqlQuery = eval(sqlQuery, TamperingType.VERSIONED_COMMENT_TO_METHOD_SIGNATURE.instance().getJavascript()); } // Dependency to: EQUAL_TO_LIKE if (this.isSpaceToDashComment) { sqlQuery = eval(sqlQuery, TamperingType.SPACE_TO_DASH_COMMENT.instance().getJavascript()); } else if (this.isSpaceToMultilineComment) { sqlQuery = eval(sqlQuery, TamperingType.SPACE_TO_MULTILINE_COMMENT.instance().getJavascript()); } else if (this.isSpaceToSharpComment) { sqlQuery = eval(sqlQuery, TamperingType.SPACE_TO_SHARP_COMMENT.instance().getJavascript()); } if (this.isBase64) { sqlQuery = eval(sqlQuery, TamperingType.BASE64.instance().getJavascript()); } // Include character insertion at the beginning of query if (this.isQuoteToUtf8) { sqlQuery = eval(sqlQuery, TamperingType.QUOTE_TO_UTF8.instance().getJavascript()); } return sqlQuery; }
#vulnerable code public String tamper(String sqlQueryDefault) { String lead = null; String sqlQuery = null; String trail = null; Matcher matcherSql = Pattern.compile("(?s)(.*<tampering>)(.*)(</tampering>.*)").matcher(sqlQueryDefault); if (matcherSql.find()) { lead = matcherSql.group(1); sqlQuery = matcherSql.group(2); trail = matcherSql.group(3); } // Empty when checking character insertion if (StringUtils.isEmpty(sqlQuery)) { return StringUtils.EMPTY; } if (this.isHexToChar) { sqlQuery = eval(sqlQuery, TamperingType.HEX_TO_CHAR.instance().getJavascript()); } if (this.isStringToChar) { sqlQuery = eval(sqlQuery, TamperingType.STRING_TO_CHAR.instance().getJavascript()); } if (this.isFunctionComment) { sqlQuery = eval(sqlQuery, TamperingType.COMMENT_TO_METHOD_SIGNATURE.instance().getJavascript()); } if (this.isVersionComment) { sqlQuery = eval(sqlQuery, TamperingType.VERSIONED_COMMENT_TO_METHOD_SIGNATURE.instance().getJavascript()); } if (this.isEqualToLike) { sqlQuery = eval(sqlQuery, TamperingType.EQUAL_TO_LIKE.instance().getJavascript()); } // Dependency to: EQUAL_TO_LIKE if (this.isSpaceToDashComment) { sqlQuery = eval(sqlQuery, TamperingType.SPACE_TO_DASH_COMMENT.instance().getJavascript()); } else if (this.isSpaceToMultilineComment) { sqlQuery = eval(sqlQuery, TamperingType.SPACE_TO_MULTILINE_COMMENT.instance().getJavascript()); } else if (this.isSpaceToSharpComment) { sqlQuery = eval(sqlQuery, TamperingType.SPACE_TO_SHARP_COMMENT.instance().getJavascript()); } if (this.isRandomCase) { sqlQuery = eval(sqlQuery, TamperingType.RANDOM_CASE.instance().getJavascript()); } if (this.isEval) { sqlQuery = eval(sqlQuery, this.customTamper); } if (this.isBase64) { sqlQuery = eval(sqlQuery, TamperingType.BASE64.instance().getJavascript()); } sqlQuery = lead + sqlQuery + trail; // Include character insertion at the beginning of query if (this.isQuoteToUtf8) { sqlQuery = eval(sqlQuery, TamperingType.QUOTE_TO_UTF8.instance().getJavascript()); } // Problme si le tag contient des caractres spciaux sqlQuery = sqlQuery.replaceAll("(?i)<tampering>", StringUtils.EMPTY); sqlQuery = sqlQuery.replaceAll("(?i)</tampering>", StringUtils.EMPTY); return sqlQuery; } #location 54 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public String tamper(String sqlQueryDefault) { String lead = null; String sqlQuery = null; String trail = null; // Transform only SQL query without HTTP parameters and syntax changed, like p=1'+[sql] Matcher matcherSql = Pattern.compile("(?s)(.*<tampering>)(.*)(</tampering>.*)").matcher(sqlQueryDefault); if (matcherSql.find()) { lead = matcherSql.group(1); sqlQuery = matcherSql.group(2); trail = matcherSql.group(3); } if (this.isEval) { sqlQuery = eval(sqlQuery, this.customTamper); } if (this.isRandomCase) { sqlQuery = eval(sqlQuery, TamperingType.RANDOM_CASE.instance().getJavascript()); } if (this.isEqualToLike) { sqlQuery = eval(sqlQuery, TamperingType.EQUAL_TO_LIKE.instance().getJavascript()); } sqlQuery = lead + sqlQuery + trail; sqlQuery = sqlQuery.replaceAll("(?i)<tampering>", StringUtils.EMPTY); sqlQuery = sqlQuery.replaceAll("(?i)</tampering>", StringUtils.EMPTY); // Empty when checking character insertion if (StringUtils.isEmpty(sqlQuery)) { return StringUtils.EMPTY; } // Transform all query, SQL and HTTP if (this.isHexToChar) { sqlQuery = eval(sqlQuery, TamperingType.HEX_TO_CHAR.instance().getJavascript()); } if (this.isStringToChar) { sqlQuery = eval(sqlQuery, TamperingType.STRING_TO_CHAR.instance().getJavascript()); } if (this.isFunctionComment) { sqlQuery = eval(sqlQuery, TamperingType.COMMENT_TO_METHOD_SIGNATURE.instance().getJavascript()); } if (this.isVersionComment) { sqlQuery = eval(sqlQuery, TamperingType.VERSIONED_COMMENT_TO_METHOD_SIGNATURE.instance().getJavascript()); } // Dependency to: EQUAL_TO_LIKE if (this.isSpaceToDashComment) { sqlQuery = eval(sqlQuery, TamperingType.SPACE_TO_DASH_COMMENT.instance().getJavascript()); } else if (this.isSpaceToMultilineComment) { sqlQuery = eval(sqlQuery, TamperingType.SPACE_TO_MULTILINE_COMMENT.instance().getJavascript()); } else if (this.isSpaceToSharpComment) { sqlQuery = eval(sqlQuery, TamperingType.SPACE_TO_SHARP_COMMENT.instance().getJavascript()); } if (this.isBase64) { sqlQuery = eval(sqlQuery, TamperingType.BASE64.instance().getJavascript()); } // Include character insertion at the beginning of query if (this.isQuoteToUtf8) { sqlQuery = eval(sqlQuery, TamperingType.QUOTE_TO_UTF8.instance().getJavascript()); } return sqlQuery; }
#vulnerable code public String tamper(String sqlQueryDefault) { String lead = null; String sqlQuery = null; String trail = null; Matcher matcherSql = Pattern.compile("(?s)(.*<tampering>)(.*)(</tampering>.*)").matcher(sqlQueryDefault); if (matcherSql.find()) { lead = matcherSql.group(1); sqlQuery = matcherSql.group(2); trail = matcherSql.group(3); } // Empty when checking character insertion if (StringUtils.isEmpty(sqlQuery)) { return StringUtils.EMPTY; } if (this.isHexToChar) { sqlQuery = eval(sqlQuery, TamperingType.HEX_TO_CHAR.instance().getJavascript()); } if (this.isStringToChar) { sqlQuery = eval(sqlQuery, TamperingType.STRING_TO_CHAR.instance().getJavascript()); } if (this.isFunctionComment) { sqlQuery = eval(sqlQuery, TamperingType.COMMENT_TO_METHOD_SIGNATURE.instance().getJavascript()); } if (this.isVersionComment) { sqlQuery = eval(sqlQuery, TamperingType.VERSIONED_COMMENT_TO_METHOD_SIGNATURE.instance().getJavascript()); } if (this.isEqualToLike) { sqlQuery = eval(sqlQuery, TamperingType.EQUAL_TO_LIKE.instance().getJavascript()); } // Dependency to: EQUAL_TO_LIKE if (this.isSpaceToDashComment) { sqlQuery = eval(sqlQuery, TamperingType.SPACE_TO_DASH_COMMENT.instance().getJavascript()); } else if (this.isSpaceToMultilineComment) { sqlQuery = eval(sqlQuery, TamperingType.SPACE_TO_MULTILINE_COMMENT.instance().getJavascript()); } else if (this.isSpaceToSharpComment) { sqlQuery = eval(sqlQuery, TamperingType.SPACE_TO_SHARP_COMMENT.instance().getJavascript()); } if (this.isRandomCase) { sqlQuery = eval(sqlQuery, TamperingType.RANDOM_CASE.instance().getJavascript()); } if (this.isEval) { sqlQuery = eval(sqlQuery, this.customTamper); } if (this.isBase64) { sqlQuery = eval(sqlQuery, TamperingType.BASE64.instance().getJavascript()); } sqlQuery = lead + sqlQuery + trail; // Include character insertion at the beginning of query if (this.isQuoteToUtf8) { sqlQuery = eval(sqlQuery, TamperingType.QUOTE_TO_UTF8.instance().getJavascript()); } // Problme si le tag contient des caractres spciaux sqlQuery = sqlQuery.replaceAll("(?i)<tampering>", StringUtils.EMPTY); sqlQuery = sqlQuery.replaceAll("(?i)</tampering>", StringUtils.EMPTY); return sqlQuery; } #location 39 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Override public void run() { try { LOGGER.info(I18n.UPDATE_LOADING); URLConnection con = new URL("https://raw.githubusercontent.com/ron190/jsql-injection/master/.version").openConnection(); con.setReadTimeout(60000); con.setConnectTimeout(60000); BufferedReader reader = new BufferedReader(new InputStreamReader(con.getInputStream())); String line, pageSource = ""; while ((line = reader.readLine()) != null) { pageSource += line + "\n"; } reader.close(); Float gitVersion = Float.parseFloat(pageSource); MediatorGUI.model(); if (gitVersion <= Float.parseFloat(InjectionModel.JSQLVERSION)) { LOGGER.debug(I18n.UPDATE_UPTODATE); } else { LOGGER.warn(I18n.UPDATE_NEW_VERSION_AVAILABLE); } } catch (NumberFormatException e) { LOGGER.warn(I18n.UPDATE_EXCEPTION); LOGGER.error(e, e); } catch (IOException e) { LOGGER.warn(I18n.UPDATE_EXCEPTION); LOGGER.error(e, e); } }
#vulnerable code @Override public void run() { try { LOGGER.info(I18n.UPDATE_LOADING); URLConnection con = new URL("http://jsql-injection.googlecode.com/git/.version").openConnection(); con.setReadTimeout(60000); con.setConnectTimeout(60000); BufferedReader reader = new BufferedReader(new InputStreamReader(con.getInputStream())); String line, pageSource = ""; while ((line = reader.readLine()) != null) { pageSource += line + "\n"; } reader.close(); Float gitVersion = Float.parseFloat(pageSource); MediatorGUI.model(); if (gitVersion <= Float.parseFloat(InjectionModel.JSQLVERSION)) { LOGGER.debug(I18n.UPDATE_UPTODATE); } else { LOGGER.warn(I18n.UPDATE_NEW_VERSION_AVAILABLE); } } catch (NumberFormatException e) { LOGGER.warn(I18n.UPDATE_EXCEPTION); LOGGER.error(e, e); } catch (IOException e) { LOGGER.warn(I18n.UPDATE_EXCEPTION); LOGGER.error(e, e); } } #location 23 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public static void start(Class<?> clazz,String path) throws Exception { InitSetting.setting(clazz,path) ; NettyBootStrap.startServer(); }
#vulnerable code public static void start(Class<?> clazz,String path) throws Exception { long start = System.currentTimeMillis(); //init application AppConfig.getInstance().setRootPackageName(clazz.getPackage().getName()); AppConfig.getInstance().setRootPath(path); InputStream resourceAsStream = CicadaServer.class.getClassLoader().getResourceAsStream("application.properties"); Properties prop = new Properties(); prop.load(resourceAsStream); int port = Integer.parseInt(prop.get(CicadaConstant.CICADA_PORT).toString()); AppConfig.getInstance().setPort(port); List<Class<?>> configuration = ClassScanner.getConfiguration(AppConfig.getInstance().getRootPackageName()); for (Class<?> aClass : configuration) { AbstractCicadaConfiguration conf = (AbstractCicadaConfiguration) aClass.newInstance() ; InputStream stream = CicadaServer.class.getClassLoader().getResourceAsStream(conf.getPropertiesName()); Properties properties = new Properties(); properties.load(stream); conf.setProperties(properties) ; ConfigurationHolder.addConfiguration(aClass.getName(),conf) ; } try { ServerBootstrap bootstrap = new ServerBootstrap() .group(boss, work) .channel(NioServerSocketChannel.class) .childHandler(new CicadaInitializer()); ChannelFuture future = bootstrap.bind(port).sync(); if (future.isSuccess()) { long end = System.currentTimeMillis(); LOGGER.info("Cicada started on port: {}.cost {}ms", port ,end-start); } Channel channel = future.channel(); channel.closeFuture().sync(); } finally { boss.shutdownGracefully(); work.shutdownGracefully(); } } #location 18 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code private void handlePostValidate(UIInput component) { BeanValidator beanValidator = getBeanValidator(component); if (beanValidator != null) { String originalValidationGroups = (String) component.getAttributes().remove(ATTRIBUTE_ORIGINAL_VALIDATION_GROUPS); beanValidator.setValidationGroups(originalValidationGroups); } }
#vulnerable code private void handlePostValidate(UIInput component) { final BeanValidator beanValidator = getBeanValidator(component); final String originalValidationGroups = (String) component.getAttributes().remove(ATTRIBUTE_ORIGINAL_VALIDATION_GROUPS); beanValidator.setValidationGroups(originalValidationGroups); } #location 4 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Override public void apply(FaceletContext context, UIComponent parent) throws IOException { if (!ComponentHandler.isNew(parent)) { return; } if (!TRUE.equals(getApplicationAttribute(context.getFacesContext(), Socket.class.getName()))) { throw new IllegalStateException(ERROR_ENDPOINT_NOT_ENABLED); } String channelName = channel.getValue(context); if (!PATTERN_CHANNEL.matcher(channelName).matches()) { throw new IllegalArgumentException(String.format(ERROR_INVALID_CHANNEL, channelName)); } SocketScopeManager scopeManager = getReference(SocketScopeManager.class); String scopeName = getString(context, scope); String scopeId; try { scopeId = scopeManager.register(channelName, scopeName); } catch (IllegalArgumentException ignore) { throw new IllegalArgumentException(String.format(ERROR_INVALID_SCOPE, scopeName)); } if (scopeId == null) { throw new IllegalArgumentException(String.format(ERROR_DUPLICATE_CHANNEL, channelName)); } Integer portNumber = getObject(context, port, Integer.class); String onmessageFunction = onmessage.getValue(context); String oncloseFunction = getString(context, onclose); String functions = onmessageFunction + "," + oncloseFunction; ValueExpression connectedExpression = getValueExpression(context, connected, Boolean.class); SystemEventListener listener = new SocketEventListener(portNumber, channelName, scopeId, functions, connectedExpression); subscribeToViewEvent(PostAddToViewEvent.class, listener); subscribeToViewEvent(PreRenderViewEvent.class, listener); }
#vulnerable code @Override public void apply(FaceletContext context, UIComponent parent) throws IOException { if (!ComponentHandler.isNew(parent)) { return; } if (!TRUE.equals(getApplicationAttribute(context.getFacesContext(), Socket.class.getName()))) { throw new IllegalStateException(ERROR_ENDPOINT_NOT_ENABLED); } String channelName = channel.getValue(context); if (!PATTERN_CHANNEL_NAME.matcher(channelName).matches()) { throw new IllegalArgumentException(String.format(ERROR_ILLEGAL_CHANNEL_NAME, channelName)); } String scopeId = getReference(SocketScope.class).register(channelName, Scope.of(getString(context, scope))); if (scopeId == null) { throw new IllegalArgumentException(String.format(ERROR_DUPLICATE_CHANNEL, channelName)); } Integer portNumber = getObject(context, port, Integer.class); String onmessageFunction = onmessage.getValue(context); String oncloseFunction = getString(context, onclose); String functions = onmessageFunction + "," + oncloseFunction; ValueExpression connectedExpression = getValueExpression(context, connected, Boolean.class); SystemEventListener listener = new SocketEventListener(portNumber, channelName, scopeId, functions, connectedExpression); subscribeToViewEvent(PostAddToViewEvent.class, listener); subscribeToViewEvent(PreRenderViewEvent.class, listener); } #location 17 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public static <T> T getInstance(BeanManager beanManager, Class<T> beanClass) { Bean<T> bean = resolve(beanManager, beanClass); return (bean != null) ? getInstance(beanManager, bean, true) : null; }
#vulnerable code public static <T> T getInstance(BeanManager beanManager, Class<T> beanClass) { return getInstance(beanManager, resolve(beanManager, beanClass), true); } #location 2 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Override public void encodeBegin(FacesContext context) throws IOException { Components.validateHasNoChildren(this); ExternalContext externalContext = context.getExternalContext(); HttpServletRequest request = (HttpServletRequest) externalContext.getRequest(); HttpServletResponse response = (HttpServletResponse) externalContext.getResponse(); BufferedHttpServletResponse bufferedResponse = new BufferedHttpServletResponse(response); try { request.getRequestDispatcher((String) getAttributes().get("path")).include(request, bufferedResponse); } catch (ServletException e) { throw new FacesException(e); } context.getResponseWriter().write(new String(bufferedResponse.getBuffer(), response.getCharacterEncoding())); }
#vulnerable code @Override public void encodeBegin(FacesContext context) throws IOException { Components.validateHasNoChildren(this); try { ExternalContext externalContext = context.getExternalContext(); HttpServletRequest request = (HttpServletRequest) externalContext.getRequest(); HttpServletResponse response = (HttpServletResponse) externalContext.getResponse(); // Create dispatcher for the resource given by the component's page attribute. RequestDispatcher requestDispatcher = request.getRequestDispatcher((String) getAttributes().get("path")); // Catch the resource's output. CharResponseWrapper responseWrapper = new CharResponseWrapper(response); requestDispatcher.include(request, responseWrapper); // Write the output from the resource to the JSF response writer. context.getResponseWriter().write(responseWrapper.toString()); } catch (ServletException e) { throw new IOException(); } } #location 18 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @OnClose public void close(Session session) { BeanManager.INSTANCE.getReference(SocketPushContext.class).remove(session); // @Inject in @ServerEndpoint doesn't work in Tomcat+Weld. }
#vulnerable code @OnClose public void close(Session session) { BeanManager.INSTANCE.getReference(PushContextImpl.class).remove(session); // @Inject in @ServerEndpoint doesn't work in Tomcat+Weld. } #location 3 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code private synchronized void loadResources() { if (!isEmpty(resources)) { return; } FacesContext context = FacesContext.getCurrentInstance(); resources = new LinkedHashSet<>(); contentLength = 0; lastModified = 0; for (ResourceIdentifier resourceIdentifier : resourceIdentifiers) { Resource resource = createResource(context, resourceIdentifier.getLibrary(), resourceIdentifier.getName()); if (resource == null) { if (logger.isLoggable(WARNING)) { logger.log(WARNING, format(LOG_RESOURCE_NOT_FOUND, resourceIdentifier, id)); } resources.clear(); return; } resources.add(resource); URLConnection connection = openConnection(context, resource); if (connection == null) { return; } contentLength += connection.getContentLength(); long resourceLastModified = connection.getLastModified(); if (resourceLastModified > lastModified) { lastModified = resourceLastModified; } } }
#vulnerable code private synchronized void loadResources() { if (!isEmpty(resources)) { return; } FacesContext context = FacesContext.getCurrentInstance(); ResourceHandler handler = context.getApplication().getResourceHandler(); resources = new LinkedHashSet<>(); contentLength = 0; lastModified = 0; for (ResourceIdentifier resourceIdentifier : resourceIdentifiers) { Resource resource = handler.createResource(resourceIdentifier.getName(), resourceIdentifier.getLibrary()); if (resource == null) { if (logger.isLoggable(WARNING)) { logger.log(WARNING, format(LOG_RESOURCE_NOT_FOUND, resourceIdentifier, id)); } resources.clear(); return; } resources.add(resource); URLConnection connection; try { connection = resource.getURL().openConnection(); } catch (Exception richFacesDoesNotSupportThis) { logger.log(FINEST, "Ignoring thrown exception; this can only be caused by a buggy component library.", richFacesDoesNotSupportThis); try { connection = new URL(getRequestDomainURL(context) + resource.getRequestPath()).openConnection(); } catch (IOException ignore) { logger.log(FINEST, "Ignoring thrown exception; cannot handle it at this point, it would be thrown during getInputStream() anyway.", ignore); return; } } contentLength += connection.getContentLength(); long resourceLastModified = connection.getLastModified(); if (resourceLastModified > lastModified) { lastModified = resourceLastModified; } } } #location 43 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public static <T> T getReference(BeanManager beanManager, Class<T> beanClass) { Bean<T> bean = resolve(beanManager, beanClass); return (bean != null) ? getReference(beanManager, bean) : null; }
#vulnerable code public static <T> T getReference(BeanManager beanManager, Class<T> beanClass) { return getReference(beanManager, resolve(beanManager, beanClass)); } #location 2 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @OnOpen public void open(Session session, @PathParam("channel") String channel) { BeanManager.INSTANCE.getReference(SocketPushContext.class).add(session, channel); // @Inject in @ServerEndpoint doesn't work in Tomcat+Weld. }
#vulnerable code @OnOpen public void open(Session session, @PathParam("channel") String channel) { BeanManager.INSTANCE.getReference(PushContextImpl.class).add(session, channel); // @Inject in @ServerEndpoint doesn't work in Tomcat+Weld. } #location 3 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Override public <S extends Serializable> Map<S, Set<Future<Void>>> send(Object message, Collection<S> users) { Map<S, Set<Future<Void>>> resultsByUser = new HashMap<>(users.size()); for (S user : users) { Set<String> userChannelIds = userManager.getUserChannelIds(user, channel); Set<Future<Void>> results = new HashSet<>(userChannelIds.size()); for (String channelId : userChannelIds) { results.addAll(sessionManager.send(channelId, message)); } resultsByUser.put(user, results); } return resultsByUser; }
#vulnerable code @Override public <S extends Serializable> Map<S, Set<Future<Void>>> send(Object message, Collection<S> users) { SocketSessionManager manager = SocketSessionManager.getInstance(); Map<S, Set<Future<Void>>> resultsByUser = new HashMap<>(users.size()); for (S user : users) { Set<String> userChannelIds = getUserChannelIds(user, channel); Set<Future<Void>> results = new HashSet<>(userChannelIds.size()); for (String channelId : userChannelIds) { results.addAll(manager.send(channelId, message)); } resultsByUser.put(user, results); } return resultsByUser; } #location 11 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Override public void processEvent(SystemEvent event) throws AbortProcessingException { if (event instanceof PreDestroyViewMapEvent) { getReference(ViewScopeManager.class).preDestroyView(); } }
#vulnerable code @Override public void processEvent(SystemEvent event) throws AbortProcessingException { if (event instanceof PreDestroyViewMapEvent) { BeanManager.INSTANCE.getReference(ViewScopeManager.class).preDestroyView(); } } #location 4 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Override public String getActionURL(FacesContext context, String viewId) { String actionURL = super.getActionURL(context, viewId); ServletContext servletContext = getServletContext(context); Map<String, String> mappedResources = getMappedResources(servletContext); if (mappedResources.containsKey(viewId) && (extensionless || isOriginalViewExtensionless(context))) { // User has requested to always render extensionless, or the requested viewId was mapped and the current // request is extensionless; render the action URL extensionless as well. String[] uriAndQueryString = actionURL.split("\\?", 2); String uri = stripWelcomeFilePrefix(servletContext, removeExtensionIfNecessary(servletContext, uriAndQueryString[0], viewId)); String queryString = uriAndQueryString.length > 1 ? ("?" + uriAndQueryString[1]) : ""; String pathInfo = context.getViewRoot().getViewId().equals(viewId) ? coalesce(getRequestPathInfo(context), "") : ""; return (pathInfo.isEmpty() ? uri : (stripTrailingSlash(uri) + pathInfo)) + queryString; } // Not a resource we mapped or not a forwarded one, take the version from the parent view handler. return actionURL; }
#vulnerable code @Override public String getActionURL(FacesContext context, String viewId) { String actionURL = super.getActionURL(context, viewId); ServletContext servletContext = getServletContext(context); Map<String, String> mappedResources = getMappedResources(servletContext); if (mappedResources.containsKey(viewId) && (extensionless || isOriginalViewExtensionless(context))) { // User has requested to always render extensionless, or the requested viewId was mapped and the current // request is extensionless; render the action URL extensionless as well. String pathInfo = context.getViewRoot().getViewId().equals(viewId) ? coalesce(getRequestPathInfo(context), "") : ""; actionURL = removeExtension(servletContext, actionURL, viewId); return pathInfo.isEmpty() ? actionURL : (stripTrailingSlash(actionURL) + pathInfo + getQueryString(actionURL)); } // Not a resource we mapped or not a forwarded one, take the version from the parent view handler. return actionURL; } #location 12 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @SuppressWarnings("unchecked") public static <T> void destroy(BeanManager beanManager, T instance) { if (instance instanceof Class) { // Java prefers T over Class<T> when varargs is not specified :( destroy(beanManager, (Class<T>) instance, new Annotation[0]); } else { Bean<T> bean = (Bean<T>) resolve(beanManager, instance.getClass()); if (bean != null) { destroy(beanManager, bean, instance); } } }
#vulnerable code @SuppressWarnings("unchecked") public static <T> void destroy(BeanManager beanManager, T instance) { if (instance instanceof Class) { destroy(beanManager, (Class<T>) instance, new Annotation[0]); } else if (instance instanceof Bean) { destroy(beanManager, (Bean<T>) instance); } else { Bean<T> bean = (Bean<T>) resolve(beanManager, instance.getClass()); bean.destroy(instance, beanManager.createCreationalContext(bean)); } } #location 11 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Override public UIViewRoot restoreView(FacesContext context, String viewId) { if (isUnloadRequest(context)) { UIViewRoot createdView = createView(context, viewId); createdView.restoreViewScopeState(context, getRenderKit(context).getResponseStateManager().getState(context, viewId)); context.setProcessingEvents(true); context.getApplication().publishEvent(context, PreDestroyViewMapEvent.class, UIViewRoot.class, createdView); responseComplete(); return createdView; } UIViewRoot restoredView = super.restoreView(context, viewId); if (!(isRestorableViewEnabled(context) && restoredView == null && context.isPostback())) { return restoredView; } try { UIViewRoot createdView = buildView(viewId); return isRestorableView(createdView) ? createdView : null; } catch (IOException e) { throw new FacesException(e); } }
#vulnerable code @Override public UIViewRoot restoreView(FacesContext context, String viewId) { if (isUnloadRequest(context)) { UIViewRoot createdView = createView(context, viewId); createdView.restoreViewScopeState(context, getRenderKit(context).getResponseStateManager().getState(context, viewId)); getReference(ViewScopeManager.class).preDestroyView(); responseComplete(); return createdView; } UIViewRoot restoredView = super.restoreView(context, viewId); if (!(isRestorableViewEnabled(context) && restoredView == null && context.isPostback())) { return restoredView; } try { UIViewRoot createdView = buildView(viewId); return isRestorableView(createdView) ? createdView : null; } catch (IOException e) { throw new FacesException(e); } } #location 6 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Override public void contextInitialized(ServletContextEvent event) { checkCDIAvailable(); EagerBeansRepository.getInstance().instantiateApplicationScoped(); FacesViews.addMappings(event.getServletContext()); CacheInitializer.loadProviderAndRegisterFilter(event.getServletContext()); }
#vulnerable code @Override public void contextInitialized(ServletContextEvent event) { checkCDIAvailable(); BeanManager.INSTANCE.getReference(EagerBeansRepository.class).instantiateApplicationScoped(); FacesViews.addMappings(event.getServletContext()); CacheInitializer.loadProviderAndRegisterFilter(event.getServletContext()); } #location 4 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Override public Object getAsObject(FacesContext context, UIComponent component, String submittedValue) { String string = submittedValue; if (!isEmpty(string)) { DecimalFormat formatter = getFormatter(); if (formatter != null) { String symbol = getSymbol(formatter); if (!string.contains(symbol)) { string = PATTERN_NUMBER.matcher(formatter.format(0)).replaceAll(submittedValue); } } } return super.getAsObject(context, component, string); }
#vulnerable code @Override public Object getAsObject(FacesContext context, UIComponent component, String submittedValue) { String string = submittedValue; if (!isEmpty(string)) { DecimalFormat formatter = getFormatter(); String symbol = getSymbol(formatter); if (!string.contains(symbol)) { string = PATTERN_NUMBER.matcher(formatter.format(0)).replaceAll(submittedValue); } } return super.getAsObject(context, component, string); } #location 10 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code private void handlePreValidate(UIInput component) { BeanValidator beanValidator = getBeanValidator(component); if (beanValidator == null) { return; } String newValidationGroups = disabled ? NoValidationGroup.class.getName() : validationGroups; String originalValidationGroups = beanValidator.getValidationGroups(); if (originalValidationGroups != null) { component.getAttributes().put(ATTRIBUTE_ORIGINAL_VALIDATION_GROUPS, originalValidationGroups); } beanValidator.setValidationGroups(newValidationGroups); if (LOGGER.isLoggable(Level.FINER)) { LOGGER.finer(String.format(LOG_VALIDATION_GROUPS_OVERRIDDEN, component.getClientId(), originalValidationGroups, newValidationGroups)); } }
#vulnerable code private void handlePreValidate(UIInput component) { final BeanValidator beanValidator = getBeanValidator(component); final String newValidationGroups = disabled ? NoValidationGroup.class.getName() : validationGroups; final String originalValidationGroups = beanValidator.getValidationGroups(); if (originalValidationGroups != null) { component.getAttributes().put(ATTRIBUTE_ORIGINAL_VALIDATION_GROUPS, originalValidationGroups); } beanValidator.setValidationGroups(newValidationGroups); if (LOGGER.isLoggable(Level.FINER)) { LOGGER.finer(String.format(LOG_VALIDATION_GROUPS_OVERRIDDEN, component.getClientId(), originalValidationGroups, newValidationGroups)); } } #location 4 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Override public UIViewRoot restoreView(FacesContext context, String viewId) { if (isUnloadRequest(context)) { UIViewRoot createdView = createView(context, viewId); createdView.restoreViewScopeState(context, getRenderKit(context).getResponseStateManager().getState(context, viewId)); getReference(ViewScopeManager.class).preDestroyView(); responseComplete(); return createdView; } UIViewRoot restoredView = super.restoreView(context, viewId); if (!(isRestorableViewEnabled(context) && restoredView == null && context.isPostback())) { return restoredView; } try { UIViewRoot createdView = buildView(viewId); return isRestorableView(createdView) ? createdView : null; } catch (IOException e) { throw new FacesException(e); } }
#vulnerable code @Override public UIViewRoot restoreView(FacesContext context, String viewId) { if (isUnloadRequest(context)) { UIViewRoot createdView = createView(context, viewId); createdView.restoreViewScopeState(context, getRenderKit(context).getResponseStateManager().getState(context, viewId)); BeanManager.INSTANCE.getReference(ViewScopeManager.class).preDestroyView(); responseComplete(); return createdView; } UIViewRoot restoredView = super.restoreView(context, viewId); if (!(isRestorableViewEnabled(context) && restoredView == null && context.isPostback())) { return restoredView; } try { UIViewRoot createdView = buildView(viewId); return isRestorableView(createdView) ? createdView : null; } catch (IOException e) { throw new FacesException(e); } } #location 6 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Override public void encodeChildren(FacesContext context) throws IOException { if (!TRUE.equals(getApplicationAttribute(context, Socket.class.getName()))) { throw new IllegalStateException(ERROR_ENDPOINT_NOT_ENABLED); } if (SocketFacesListener.register(context, this)) { String channel = getChannel(); if (channel == null || !PATTERN_CHANNEL.matcher(channel).matches()) { throw new IllegalArgumentException(format(ERROR_INVALID_CHANNEL, channel)); } Integer port = getPort(); String host = (port != null ? ":" + port : "") + getRequestContextPath(context); String channelId = SocketChannelManager.getInstance().register(channel, getScope(), getUser()); String functions = getOnopen() + "," + getOnmessage() + "," + getOnclose(); String behaviors = getBehaviorScripts(); boolean connected = isConnected(); String script = format(SCRIPT_INIT, host, channelId, functions, behaviors, connected); context.getResponseWriter().write(script); } }
#vulnerable code @Override public void encodeChildren(FacesContext context) throws IOException { if (!TRUE.equals(getApplicationAttribute(context, Socket.class.getName()))) { throw new IllegalStateException(ERROR_ENDPOINT_NOT_ENABLED); } if (SocketFacesListener.register(context, this)) { String channel = getChannel(); if (channel == null || !PATTERN_CHANNEL.matcher(channel).matches()) { throw new IllegalArgumentException(format(ERROR_INVALID_CHANNEL, channel)); } Integer port = getPort(); String host = (port != null ? ":" + port : "") + getRequestContextPath(context); String channelId = getReference(SocketChannelManager.class).register(channel, getScope(), getUser()); String functions = getOnopen() + "," + getOnmessage() + "," + getOnclose(); String behaviors = getBehaviorScripts(); boolean connected = isConnected(); String script = format(SCRIPT_INIT, host, channelId, functions, behaviors, connected); context.getResponseWriter().write(script); } } #location 16 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Override public void apply(FaceletContext context, UIComponent parent) throws IOException { if (!ComponentHandler.isNew(parent)) { return; } if (!TRUE.equals(getApplicationAttribute(context.getFacesContext(), Socket.class.getName()))) { throw new IllegalStateException(ERROR_ENDPOINT_NOT_ENABLED); } Integer portNumber = getObject(context, port, Integer.class); String channelName = getChannelName(context, channel); String channelId = getChannelId(context, channelName, scope, user); String functions = getString(context, onopen) + "," + onmessage.getValue(context) + "," + getString(context, onclose); ValueExpression connectedExpression = getValueExpression(context, connected, Boolean.class); SystemEventListener listener = new SocketFacesListener(portNumber, channelName, channelId, functions, connectedExpression); subscribeToViewEvent(PostAddToViewEvent.class, listener); subscribeToViewEvent(PreRenderViewEvent.class, listener); }
#vulnerable code @Override public void apply(FaceletContext context, UIComponent parent) throws IOException { if (!ComponentHandler.isNew(parent)) { return; } if (!TRUE.equals(getApplicationAttribute(context.getFacesContext(), Socket.class.getName()))) { throw new IllegalStateException(ERROR_ENDPOINT_NOT_ENABLED); } String channelName = channel.isLiteral() ? channel.getValue(context) : null; if (channelName == null || !PATTERN_CHANNEL.matcher(channelName).matches()) { throw new IllegalArgumentException(String.format(ERROR_INVALID_CHANNEL, channelName)); } Object userObject = getObject(context, user); if (userObject != null && !(userObject instanceof Serializable)) { throw new IllegalArgumentException(String.format(ERROR_INVALID_USER, userObject)); } SocketChannelManager channelManager = getReference(SocketChannelManager.class); String scopeName = (scope == null) ? null : scope.isLiteral() ? getString(context, scope) : ""; String channelId; try { channelId = channelManager.register(channelName, scopeName, (Serializable) userObject); } catch (IllegalArgumentException ignore) { throw new IllegalArgumentException(String.format(ERROR_INVALID_SCOPE, scopeName)); } if (channelId == null) { throw new IllegalArgumentException(String.format(ERROR_DUPLICATE_CHANNEL, channelName)); } Integer portNumber = getObject(context, port, Integer.class); String onopenFunction = getString(context, onopen); String onmessageFunction = onmessage.getValue(context); String oncloseFunction = getString(context, onclose); String functions = onopenFunction + "," + onmessageFunction + "," + oncloseFunction; ValueExpression connectedExpression = getValueExpression(context, connected, Boolean.class); SystemEventListener listener = new SocketFacesListener(portNumber, channelName, channelId, functions, connectedExpression); subscribeToViewEvent(PostAddToViewEvent.class, listener); subscribeToViewEvent(PreRenderViewEvent.class, listener); } #location 28 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Override public void contextInitialized(ServletContextEvent event) { checkCDIAvailable(); try { ServletContext servletContext = event.getServletContext(); EagerBeansRepository.instantiateApplicationScopedAndRegisterListener(servletContext); FacesViews.addMappings(servletContext); CacheInitializer.loadProviderAndRegisterFilter(servletContext); } catch (Throwable e) { logger.log(Level.SEVERE, "OmniFaces failed to initialize! Report an issue to OmniFaces.", e); throw e; } }
#vulnerable code @Override public void contextInitialized(ServletContextEvent event) { checkCDIAvailable(); try { EagerBeansRepository.getInstance().instantiateApplicationScoped(); FacesViews.addMappings(event.getServletContext()); CacheInitializer.loadProviderAndRegisterFilter(event.getServletContext()); } catch (Throwable e) { logger.log(Level.SEVERE, "OmniFaces failed to initialize! Report an issue to OmniFaces.", e); throw e; } } #location 6 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code private synchronized void loadResources() { if (!isEmpty(resources)) { return; } FacesContext context = FacesContext.getCurrentInstance(); resources = new LinkedHashSet<>(); contentLength = 0; lastModified = 0; for (ResourceIdentifier resourceIdentifier : resourceIdentifiers) { Resource resource = createResource(context, resourceIdentifier.getLibrary(), resourceIdentifier.getName()); if (resource == null) { if (logger.isLoggable(WARNING)) { logger.log(WARNING, format(LOG_RESOURCE_NOT_FOUND, resourceIdentifier, id)); } resources.clear(); return; } resources.add(resource); URLConnection connection = openConnection(context, resource); if (connection == null) { return; } contentLength += connection.getContentLength(); long resourceLastModified = connection.getLastModified(); if (resourceLastModified > lastModified) { lastModified = resourceLastModified; } } }
#vulnerable code private synchronized void loadResources() { if (!isEmpty(resources)) { return; } FacesContext context = FacesContext.getCurrentInstance(); ResourceHandler handler = context.getApplication().getResourceHandler(); resources = new LinkedHashSet<>(); contentLength = 0; lastModified = 0; for (ResourceIdentifier resourceIdentifier : resourceIdentifiers) { Resource resource = handler.createResource(resourceIdentifier.getName(), resourceIdentifier.getLibrary()); if (resource == null) { if (logger.isLoggable(WARNING)) { logger.log(WARNING, format(LOG_RESOURCE_NOT_FOUND, resourceIdentifier, id)); } resources.clear(); return; } resources.add(resource); URLConnection connection; try { connection = resource.getURL().openConnection(); } catch (Exception richFacesDoesNotSupportThis) { logger.log(FINEST, "Ignoring thrown exception; this can only be caused by a buggy component library.", richFacesDoesNotSupportThis); try { connection = new URL(getRequestDomainURL(context) + resource.getRequestPath()).openConnection(); } catch (IOException ignore) { logger.log(FINEST, "Ignoring thrown exception; cannot handle it at this point, it would be thrown during getInputStream() anyway.", ignore); return; } } contentLength += connection.getContentLength(); long resourceLastModified = connection.getLastModified(); if (resourceLastModified > lastModified) { lastModified = resourceLastModified; } } } #location 43 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Override public String getActionURL(FacesContext context, String viewId) { String actionURL = super.getActionURL(context, viewId); ServletContext servletContext = getServletContext(context); Map<String, String> mappedResources = getMappedResources(servletContext); if (mappedResources.containsKey(viewId) && (extensionless || isOriginalViewExtensionless(context))) { // User has requested to always render extensionless, or the requested viewId was mapped and the current // request is extensionless; render the action URL extensionless as well. String pathInfo = context.getViewRoot().getViewId().equals(viewId) ? coalesce(getRequestPathInfo(context), "") : ""; String queryString = getQueryString(actionURL); if (mode == BUILD_WITH_PARENT_QUERY_PARAMETERS) { return getRequestContextPath(context) + stripExtension(viewId) + pathInfo + queryString; } else { actionURL = removeExtension(servletContext, actionURL, viewId); return (pathInfo.isEmpty() ? actionURL : (stripTrailingSlash(actionURL) + pathInfo)) + queryString; } } // Not a resource we mapped or not a forwarded one, take the version from the parent view handler. return actionURL; }
#vulnerable code @Override public String getActionURL(FacesContext context, String viewId) { String actionURL = super.getActionURL(context, viewId); ServletContext servletContext = getServletContext(context); Map<String, String> mappedResources = getMappedResources(servletContext); if (mappedResources.containsKey(viewId) && (extensionless || isOriginalViewExtensionless(context))) { // User has requested to always render extensionless, or the requested viewId was mapped and the current // request is extensionless; render the action URL extensionless as well. String pathInfo = context.getViewRoot().getViewId().equals(viewId) ? coalesce(getRequestPathInfo(context), "") : ""; if (mode == BUILD_WITH_PARENT_QUERY_PARAMETERS) { return getRequestContextPath(context) + stripExtension(viewId) + pathInfo + getQueryString(actionURL); } else { actionURL = removeExtension(servletContext, actionURL, viewId); return pathInfo.isEmpty() ? actionURL : (stripTrailingSlash(actionURL) + pathInfo + getQueryString(actionURL)); } } // Not a resource we mapped or not a forwarded one, take the version from the parent view handler. return actionURL; } #location 18 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public static <T> T getInstance(BeanManager beanManager, Class<T> beanClass, boolean create) { Bean<T> bean = resolve(beanManager, beanClass); return (bean != null) ? getInstance(beanManager, bean, create) : null; }
#vulnerable code public static <T> T getInstance(BeanManager beanManager, Class<T> beanClass, boolean create) { return getInstance(beanManager, resolve(beanManager, beanClass), create); } #location 2 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Override public void encodeChildren(FacesContext context) throws IOException { if (!TRUE.equals(getApplicationAttribute(context, Socket.class.getName()))) { throw new IllegalStateException(ERROR_ENDPOINT_NOT_ENABLED); } String channel = getChannel(); if (channel == null || !PATTERN_CHANNEL.matcher(channel).matches()) { throw new IllegalArgumentException(String.format(ERROR_INVALID_CHANNEL, channel)); } boolean connected = isConnected(); Boolean switched = hasSwitched(context, channel, connected); String script = null; if (switched == null) { Integer port = getPort(); String host = (port != null ? ":" + port : "") + getRequestContextPath(context); String channelId = getReference(SocketChannelManager.class).register(channel, getScope(), getUser()); String functions = getOnopen() + "," + getOnmessage() + "," + getOnclose(); script = String.format(SCRIPT_INIT, host, channelId, functions, getBehaviorScripts(), connected); } else if (switched) { script = String.format(connected ? SCRIPT_OPEN : SCRIPT_CLOSE, channel); } if (script != null) { context.getResponseWriter().write(script); } rendered = super.isRendered(); }
#vulnerable code @Override public void encodeChildren(FacesContext context) throws IOException { if (!TRUE.equals(getApplicationAttribute(context, Socket.class.getName()))) { throw new IllegalStateException(ERROR_ENDPOINT_NOT_ENABLED); } String channel = getChannel(); if (channel == null || !PATTERN_CHANNEL.matcher(channel).matches()) { throw new IllegalArgumentException(String.format(ERROR_INVALID_CHANNEL, channel)); } boolean connected = isConnected(); Boolean switched = hasSwitched(context, channel, connected); String script = null; if (switched == null) { Integer port = getPort(); String host = (port != null ? ":" + port : "") + getRequestContextPath(context); String channelId = getReference(SocketChannelManager.class).register(channel, getScope(), getUser()); String functions = getOnopen() + "," + getOnmessage() + "," + getOnclose(); script = String.format(SCRIPT_INIT, host, channelId, functions, getBehaviorScripts(), connected); } else if (switched) { script = String.format(connected ? SCRIPT_OPEN : SCRIPT_CLOSE, channel); } if (script != null) { context.getResponseWriter().write(script); } } #location 20 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Override public void apply(FaceletContext context, UIComponent parent) throws IOException { if (!ComponentHandler.isNew(parent)) { return; } if (!TRUE.equals(getApplicationAttribute(context.getFacesContext(), Socket.class.getName()))) { throw new IllegalStateException(ERROR_ENDPOINT_NOT_ENABLED); } String channelName = channel.getValue(context); if (!PATTERN_CHANNEL.matcher(channelName).matches()) { throw new IllegalArgumentException(String.format(ERROR_INVALID_CHANNEL, channelName)); } SocketChannelManager channelManager = getReference(SocketChannelManager.class); String scopeName = getString(context, scope); String channelId; try { channelId = channelManager.register(channelName, scopeName); } catch (IllegalArgumentException ignore) { throw new IllegalArgumentException(String.format(ERROR_INVALID_SCOPE, scopeName)); } if (channelId == null) { throw new IllegalArgumentException(String.format(ERROR_DUPLICATE_CHANNEL, channelName)); } Integer portNumber = getObject(context, port, Integer.class); String onmessageFunction = onmessage.getValue(context); String oncloseFunction = getString(context, onclose); String functions = onmessageFunction + "," + oncloseFunction; ValueExpression connectedExpression = getValueExpression(context, connected, Boolean.class); SystemEventListener listener = new SocketEventListener(portNumber, channelName, channelId, functions, connectedExpression); subscribeToViewEvent(PostAddToViewEvent.class, listener); subscribeToViewEvent(PreRenderViewEvent.class, listener); }
#vulnerable code @Override public void apply(FaceletContext context, UIComponent parent) throws IOException { if (!ComponentHandler.isNew(parent)) { return; } if (!TRUE.equals(getApplicationAttribute(context.getFacesContext(), Socket.class.getName()))) { throw new IllegalStateException(ERROR_ENDPOINT_NOT_ENABLED); } String channelName = channel.getValue(context); if (!PATTERN_CHANNEL.matcher(channelName).matches()) { throw new IllegalArgumentException(String.format(ERROR_INVALID_CHANNEL, channelName)); } SocketScopeManager scopeManager = getReference(SocketScopeManager.class); String scopeName = getString(context, scope); String scopeId; try { scopeId = scopeManager.register(channelName, scopeName); } catch (IllegalArgumentException ignore) { throw new IllegalArgumentException(String.format(ERROR_INVALID_SCOPE, scopeName)); } if (scopeId == null) { throw new IllegalArgumentException(String.format(ERROR_DUPLICATE_CHANNEL, channelName)); } Integer portNumber = getObject(context, port, Integer.class); String onmessageFunction = onmessage.getValue(context); String oncloseFunction = getString(context, onclose); String functions = onmessageFunction + "," + oncloseFunction; ValueExpression connectedExpression = getValueExpression(context, connected, Boolean.class); SystemEventListener listener = new SocketEventListener(portNumber, channelName, scopeId, functions, connectedExpression); subscribeToViewEvent(PostAddToViewEvent.class, listener); subscribeToViewEvent(PreRenderViewEvent.class, listener); } #location 22 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Override public void processEvent(SystemEvent event) throws AbortProcessingException { if (event instanceof PreDestroyViewMapEvent) { processPreDestroyView(); } else if (event instanceof PostRestoreStateEvent && "unload".equals(getRequestParameter("omnifaces.event"))) { processPreDestroyView(); responseComplete(); } }
#vulnerable code @Override public void processEvent(SystemEvent event) throws AbortProcessingException { if (event instanceof PreDestroyViewMapEvent) { BeanManager.INSTANCE.getReference(ViewScopeManager.class).preDestroyView(); } } #location 4 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Override public Set<Future<Void>> send(Object message) { return sessionManager.send(getChannelId(channel, sessionScopeIds, viewScopeIds), message); }
#vulnerable code @Override public Set<Future<Void>> send(Object message) { return SocketSessionManager.getInstance().send(getChannelId(channel, sessionScopeIds, viewScopeIds), message); } #location 3 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public static InjectionPoint getCurrentInjectionPoint(BeanManager beanManager, CreationalContext<?> creationalContext) { Bean<InjectionPointGenerator> bean = resolve(beanManager, InjectionPointGenerator.class); return (bean != null) ? (InjectionPoint) beanManager.getInjectableReference(bean.getInjectionPoints().iterator().next(), creationalContext) : null; }
#vulnerable code public static InjectionPoint getCurrentInjectionPoint(BeanManager beanManager, CreationalContext<?> creationalContext) { return (InjectionPoint) beanManager.getInjectableReference( resolve(beanManager, InjectionPointGenerator.class).getInjectionPoints().iterator().next(), creationalContext ); } #location 3 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Override public void processAction(ActionEvent event) throws AbortProcessingException { FacesContext context = FacesContext.getCurrentInstance(); PartialViewContext partialViewContext = context.getPartialViewContext(); if (partialViewContext.isAjaxRequest()) { Collection<String> renderIds = getRenderIds(partialViewContext); Collection<String> executeIds = partialViewContext.getExecuteIds(); if (!renderIds.isEmpty() && !renderIds.containsAll(executeIds)) { resetEditableValueHolders(VisitContext.createVisitContext( context, renderIds, VISIT_HINTS), context.getViewRoot(), executeIds); } } if (wrapped != null && event != null) { wrapped.processAction(event); } }
#vulnerable code @Override public void processAction(ActionEvent event) throws AbortProcessingException { FacesContext context = FacesContext.getCurrentInstance(); PartialViewContext partialViewContext = context.getPartialViewContext(); if (partialViewContext.isAjaxRequest()) { Collection<String> renderIds = getRenderIds(partialViewContext); Collection<String> executeIds = partialViewContext.getExecuteIds(); if (!renderIds.isEmpty() && !renderIds.containsAll(executeIds)) { final Set<EditableValueHolder> inputs = new HashSet<EditableValueHolder>(); // First find all to be rendered inputs in the current view and add them to the set. findAndAddEditableValueHolders(VisitContext.createVisitContext( context, renderIds, VISIT_HINTS), context.getViewRoot(), inputs); // Then find all executed inputs in the current form and remove them from the set. findAndRemoveEditableValueHolders(VisitContext.createVisitContext( context, executeIds, VISIT_HINTS), Components.getCurrentForm(), inputs); // The set now contains inputs which are to be rendered, but which are not been executed. Reset them. for (EditableValueHolder input : inputs) { input.resetValue(); } } } if (wrapped != null && event != null) { wrapped.processAction(event); } } #location 18 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code private TreeModel<T> getPreviousSibling(TreeModel<T> parent, int index) { if (parent == null) { return null; } else if (index >= 0) { return parent.getChildren().get(index); } else { TreeModel<T> previousParent = parent.getPreviousSibling(); return getPreviousSibling(previousParent, (previousParent != null ? previousParent.getChildCount() : 0) - 1); } }
#vulnerable code private TreeModel<T> getPreviousSibling(TreeModel<T> parent, int index) { if (isRoot()) { return null; } else if (index >= 0) { return parent.getChildren().get(index); } else { TreeModel<T> previousParent = parent.getPreviousSibling(); return getPreviousSibling(previousParent, (previousParent != null ? previousParent.getChildCount() : 0) - 1); } } #location 10 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Test public void shouldBeAbleToConvertNumbers(){ assertThat(((Character) converter.convert("r", char.class, bundle)).charValue(), is(equalTo('r'))); }
#vulnerable code @Test public void shouldBeAbleToConvertNumbers(){ assertThat(((Character) converter.convert("r", char.class, errors, bundle)).charValue(), is(equalTo('r'))); } #location 3 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public void prepareRemotingContainer() throws IOException, InterruptedException { // if remoting container already exists, we reuse it if (context.getRemotingContainer() != null) { if (driver.hasContainer(localLauncher, context.getRemotingContainer().getId())) { return; } } final ContainerInstance remotingContainer = driver.createRemotingContainer(localLauncher, remotingImage); context.setRemotingContainer(remotingContainer); }
#vulnerable code public void prepareRemotingContainer() throws IOException, InterruptedException { // if remoting container already exists, we reuse it if (context.getRemotingContainer() != null) { if (driver.hasContainer(localLauncher, context.getRemotingContainer())) { return; } } driver.createRemotingContainer(localLauncher, context.getRemotingContainer()); } #location 8 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Test public void readerWriterTest() throws URISyntaxException, IOException, TransformationException, SAXException { File file = new File(HTMLDocContentStructureConvertersTest.class.getResource(modelFilePath).toURI()); String expectedHTML = FileUtils.readFileToString(file, "UTF-8"); InputStream is = HTMLDocContentStructureConvertersTest.class.getResourceAsStream(modelFilePath); InputStreamReader isr = new InputStreamReader(is, "UTF-8"); ContentStructure structure = reader.read(isr); String structureHTML = writer.write(structure); XMLUnit.setIgnoreWhitespace(true); Diff diff = new Diff(expectedHTML, structureHTML); assertTrue(diff.similar()); }
#vulnerable code @Test public void readerWriterTest() throws URISyntaxException, IOException, TransformationException, SAXException { File file = new File(HTMLDocContentStructureConvertersTest.class.getResource(modelFilePath).toURI()); String expectedHTML = FileUtils.readFileToString(file, "UTF-8"); InputStream is = HTMLDocContentStructureConvertersTest.class.getResourceAsStream(modelFilePath); InputStreamReader isr = new InputStreamReader(is); ContentStructure structure = reader.read(isr); String structureHTML = writer.write(structure); XMLUnit.setIgnoreWhitespace(true); Diff diff = new Diff(expectedHTML, structureHTML); assertTrue(diff.similar()); } #location 8 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public BxDocument getDocument() throws TransformationException { InputStreamReader isr = null; try { isr = new InputStreamReader(inputStream, "UTF-8"); TrueVizToBxDocumentReader reader = new TrueVizToBxDocumentReader(); return new BxDocument().setPages(reader.read(isr)); } catch (UnsupportedEncodingException ex) { throw new TransformationException("Unsupported encoding!", ex); } finally { try { if (isr != null) { isr.close(); } } catch (IOException ex) { Logger.getLogger(FileExtractor.class.getName()).log(Level.SEVERE, null, ex); } } }
#vulnerable code public BxDocument getDocument() throws TransformationException { InputStreamReader isr = new InputStreamReader(inputStream); TrueVizToBxDocumentReader reader = new TrueVizToBxDocumentReader(); return new BxDocument().setPages(reader.read(isr)); } #location 5 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public static void main(String[] args) throws AnalysisException, TransformationException, IOException { // args[0] path to xml directory if(args.length != 1) { System.err.println("Source directory needed!"); System.exit(1); } SVMInitialZoneClassifier classifier = new SVMInitialZoneClassifier("/pl/edu/icm/cermine/structure/svm_initial_classifier", "/pl/edu/icm/cermine/structure/svm_initial_classifier.range"); ReadingOrderResolver ror = new HierarchicalReadingOrderResolver(); BxDocumentToTrueVizWriter tvw = new BxDocumentToTrueVizWriter(); List<BxDocument> docs = EvaluationUtils.getDocumentsFromPath(args[0]); for(BxDocument doc: docs) { System.out.println(">> " + doc.getFilename()); ror.resolve(doc); classifier.classifyZones(doc); BufferedWriter out = null; try { // Create file FileWriter fstream = new FileWriter(doc.getFilename()); out = new BufferedWriter(fstream); out.write(tvw.write(doc.getPages())); out.close(); } catch (Exception e){//Catch exception if any System.err.println("Error: " + e.getMessage()); } finally { if(out != null) { out.close(); } } } }
#vulnerable code public static void main(String[] args) throws AnalysisException, TransformationException, IOException { // args[0] path to xml directory if(args.length != 1) { System.err.println("Source directory needed!"); System.exit(1); } InputStreamReader modelISR = new InputStreamReader(Thread.currentThread().getClass() .getResourceAsStream("/pl/edu/icm/cermine/structure/svm_initial_classifier")); BufferedReader modelFile = new BufferedReader(modelISR); InputStreamReader rangeISR = new InputStreamReader(Thread.currentThread().getClass() .getResourceAsStream("/pl/edu/icm/cermine/structure/svm_initial_classifier.range")); BufferedReader rangeFile = new BufferedReader(rangeISR); SVMZoneClassifier classifier = new SVMInitialZoneClassifier(modelFile, rangeFile); ReadingOrderResolver ror = new HierarchicalReadingOrderResolver(); BxDocumentToTrueVizWriter tvw = new BxDocumentToTrueVizWriter(); List<BxDocument> docs = EvaluationUtils.getDocumentsFromPath(args[0]); for(BxDocument doc: docs) { System.out.println(">> " + doc.getFilename()); ror.resolve(doc); classifier.classifyZones(doc); BufferedWriter out = null; try { // Create file FileWriter fstream = new FileWriter(doc.getFilename()); out = new BufferedWriter(fstream); out.write(tvw.write(doc.getPages())); out.close(); } catch (Exception e){//Catch exception if any System.err.println("Error: " + e.getMessage()); } finally { if(out != null) { out.close(); } } } } #location 15 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public static void main(String[] args) throws ParseException, IOException, TransformationException, AnalysisException, CloneNotSupportedException { Options options = new Options(); options.addOption("under", false, "use undersampling for data selection"); options.addOption("over", false, "use oversampling for data selection"); options.addOption("normal", false, "don't use any special strategy for data selection"); CommandLineParser parser = new GnuParser(); CommandLine line = parser.parse(options, args); if (args.length != 2 || !(line.hasOption("under") ^ line.hasOption("over") ^ line.hasOption("normal"))) { HelpFormatter formatter = new HelpFormatter(); formatter.printHelp(" [-options] input-directory", options); System.exit(1); } String inputDirPath = line.getArgs()[0]; File inputDirFile = new File(inputDirPath); SampleSelector<BxZoneLabel> sampler = null; if (line.hasOption("over")) { sampler = new OversamplingSelector<BxZoneLabel>(1.0); } else if (line.hasOption("under")) { sampler = new UndersamplingSelector<BxZoneLabel>(1.0); } else if (line.hasOption("normal")) { sampler = new NormalSelector<BxZoneLabel>(); } else { System.err.println("Sampling pattern is not specified!"); System.exit(1); } List<TrainingSample<BxZoneLabel>> initialTrainingElements = new ArrayList<TrainingSample<BxZoneLabel>>(); List<TrainingSample<BxZoneLabel>> metaTrainingElements = new ArrayList<TrainingSample<BxZoneLabel>>(); HierarchicalReadingOrderResolver ror = new HierarchicalReadingOrderResolver(); EvaluationUtils.DocumentsIterator iter = new DocumentsIterator(inputDirPath); FeatureVectorBuilder<BxZone, BxPage> vectorBuilder; Integer docIdx = 0; for(BxDocument doc: iter) { System.out.println(docIdx + ": " + doc.getFilename()); String filename = doc.getFilename(); doc = ror.resolve(doc); doc.setFilename(filename); //// for (BxZone zone : doc.asZones()) { if (zone.getLabel() != null) { if (zone.getLabel().getCategory() != BxZoneLabelCategory.CAT_METADATA) { zone.setLabel(zone.getLabel().getGeneralLabel()); } } else { zone.setLabel(BxZoneLabel.OTH_UNKNOWN); } } vectorBuilder = SVMMetadataZoneClassifier.getFeatureVectorBuilder(); List<TrainingSample<BxZoneLabel>> newSamples = BxDocsToTrainingSamplesConverter.getZoneTrainingSamples(doc, vectorBuilder, BxZoneLabel.getIdentityMap()); for(TrainingSample<BxZoneLabel> sample: newSamples) { if(sample.getLabel().getCategory() == BxZoneLabelCategory.CAT_METADATA) { metaTrainingElements.add(sample); } } //// vectorBuilder = SVMInitialZoneClassifier.getFeatureVectorBuilder(); newSamples = BxDocsToTrainingSamplesConverter.getZoneTrainingSamples(doc, vectorBuilder, BxZoneLabel.getLabelToGeneralMap()); initialTrainingElements.addAll(newSamples); //// ++docIdx; } initialTrainingElements = sampler.pickElements(initialTrainingElements); metaTrainingElements = sampler.pickElements(metaTrainingElements); toLibSVM(initialTrainingElements, "initial_" + inputDirFile.getName() + ".dat"); toLibSVM(metaTrainingElements, "meta_" + inputDirFile.getName() + ".dat"); }
#vulnerable code public static void main(String[] args) throws ParseException, IOException, TransformationException, AnalysisException, CloneNotSupportedException { Options options = new Options(); options.addOption("under", false, "use undersampling for data selection"); options.addOption("over", false, "use oversampling for data selection"); options.addOption("normal", false, "don't use any special strategy for data selection"); CommandLineParser parser = new GnuParser(); CommandLine line = parser.parse(options, args); if (args.length != 2 || !(line.hasOption("under") ^ line.hasOption("over") ^ line.hasOption("normal"))) { HelpFormatter formatter = new HelpFormatter(); formatter.printHelp(" [-options] input-directory", options); System.exit(1); } String inputDirPath = line.getArgs()[0]; File inputDirFile = new File(inputDirPath); SampleSelector<BxZoneLabel> sampler = null; if (line.hasOption("over")) { sampler = new OversamplingSelector<BxZoneLabel>(1.0); } else if (line.hasOption("under")) { sampler = new UndersamplingSelector<BxZoneLabel>(1.0); } else if (line.hasOption("normal")) { sampler = new NormalSelector<BxZoneLabel>(); } else { System.err.println("Sampling pattern is not specified!"); System.exit(1); } List<TrainingSample<BxZoneLabel>> initialTrainingElements = new ArrayList<TrainingSample<BxZoneLabel>>(); List<TrainingSample<BxZoneLabel>> metaTrainingElements = new ArrayList<TrainingSample<BxZoneLabel>>(); HierarchicalReadingOrderResolver ror = new HierarchicalReadingOrderResolver(); EvaluationUtils.DocumentsIterator iter = new DocumentsIterator(inputDirPath); FeatureVectorBuilder<BxZone, BxPage> vectorBuilder; Integer docIdx = 0; for(BxDocument doc: iter) { doc = ror.resolve(doc); System.out.println(docIdx + ": " + doc.getFilename()); String filename = doc.getFilename(); doc = ror.resolve(doc); doc.setFilename(filename); //// for (BxZone zone : doc.asZones()) { if (zone.getLabel() != null) { if (zone.getLabel().getCategory() != BxZoneLabelCategory.CAT_METADATA) { zone.setLabel(zone.getLabel().getGeneralLabel()); } } else { zone.setLabel(BxZoneLabel.OTH_UNKNOWN); } } vectorBuilder = SVMMetadataZoneClassifier.getFeatureVectorBuilder(); List<TrainingSample<BxZoneLabel>> newSamples = BxDocsToTrainingSamplesConverter.getZoneTrainingSamples(doc, vectorBuilder, BxZoneLabel.getIdentityMap()); for(TrainingSample<BxZoneLabel> sample: newSamples) { if(sample.getLabel().getCategory() == BxZoneLabelCategory.CAT_METADATA) { metaTrainingElements.add(sample); } } //// vectorBuilder = SVMInitialZoneClassifier.getFeatureVectorBuilder(); newSamples = BxDocsToTrainingSamplesConverter.getZoneTrainingSamples(doc, vectorBuilder, BxZoneLabel.getLabelToGeneralMap()); initialTrainingElements.addAll(newSamples); //// ++docIdx; } initialTrainingElements = sampler.pickElements(initialTrainingElements); metaTrainingElements = sampler.pickElements(metaTrainingElements); toLibSVM(initialTrainingElements, "initial_" + inputDirFile.getName() + ".dat"); toLibSVM(metaTrainingElements, "meta_" + inputDirFile.getName() + ".dat"); } #location 38 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public static void toLibSVM(List<TrainingElement<BxZoneLabel>> trainingElements, String filePath) throws IOException { BufferedWriter svmDataFile = null; try { FileWriter fstream = new FileWriter(filePath); svmDataFile = new BufferedWriter(fstream); for (TrainingElement<BxZoneLabel> elem : trainingElements) { svmDataFile.write(String.valueOf(elem.getLabel().ordinal())); svmDataFile.write(" "); Integer featureCounter = 1; for (Double value : elem.getObservation().getFeatures()) { StringBuilder sb = new StringBuilder(); Formatter formatter = new Formatter(sb, Locale.US); formatter.format("%d:%.5f", featureCounter++, value); svmDataFile.write(sb.toString()); svmDataFile.write(" "); } svmDataFile.write("\n"); } svmDataFile.close(); } catch (Exception e) { System.err.println("Error: " + e.getMessage()); return; } finally { if(svmDataFile != null) { svmDataFile.close(); } } System.out.println("Done."); }
#vulnerable code public static void toLibSVM(List<TrainingElement<BxZoneLabel>> trainingElements, String filePath) { try { FileWriter fstream = new FileWriter(filePath); BufferedWriter svmDataFile = new BufferedWriter(fstream); for (TrainingElement<BxZoneLabel> elem : trainingElements) { svmDataFile.write(String.valueOf(elem.getLabel().ordinal())); svmDataFile.write(" "); Integer featureCounter = 1; for (Double value : elem.getObservation().getFeatures()) { StringBuilder sb = new StringBuilder(); Formatter formatter = new Formatter(sb, Locale.US); formatter.format("%d:%.5f", featureCounter++, value); svmDataFile.write(sb.toString()); svmDataFile.write(" "); } svmDataFile.write("\n"); } svmDataFile.close(); } catch (Exception e) { System.err.println("Error: " + e.getMessage()); return; } System.out.println("Done."); } #location 20 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Override public List<BxDocument> getDocuments() throws TransformationException { String dirPath = directory.getPath(); TrueVizToBxDocumentReader tvReader = new TrueVizToBxDocumentReader(); List<BxDocument> documents = new ArrayList<BxDocument>(); if (!dirPath.endsWith(File.separator)) { dirPath += File.separator; } for (String filename : directory.list()) { if (!new File(dirPath + filename).isFile()) { continue; } if (filename.endsWith("xml")) { InputStream is = null; try { is = new FileInputStream(dirPath + filename); List<BxPage> pages = tvReader.read(new InputStreamReader(is, "UTF-8")); BxDocument newDoc = new BxDocument(); for (BxPage page : pages) { page.setParent(newDoc); } newDoc.setFilename(filename); newDoc.setPages(pages); documents.add(newDoc); } catch (IllegalStateException ex) { System.err.println(ex.getMessage()); System.err.println(dirPath + filename); throw ex; } catch (FileNotFoundException ex) { throw new TransformationException("File not found!", ex); } catch (UnsupportedEncodingException ex) { throw new TransformationException("Unsupported encoding!", ex); } finally { if (is != null) { try { is.close(); } catch (IOException ex) { throw new TransformationException("Cannot close stream!", ex); } } } } } return documents; }
#vulnerable code @Override public List<BxDocument> getDocuments() throws TransformationException { String dirPath = directory.getPath(); TrueVizToBxDocumentReader tvReader = new TrueVizToBxDocumentReader(); List<BxDocument> documents = new ArrayList<BxDocument>(); if (!dirPath.endsWith(File.separator)) { dirPath += File.separator; } for (String filename : directory.list()) { if (!new File(dirPath + filename).isFile()) { continue; } if (filename.endsWith("xml")) { InputStream is = null; try { is = new FileInputStream(dirPath + filename); List<BxPage> pages = tvReader.read(new InputStreamReader(is)); BxDocument newDoc = new BxDocument(); for (BxPage page : pages) { page.setParent(newDoc); } newDoc.setFilename(filename); newDoc.setPages(pages); documents.add(newDoc); } catch (IllegalStateException ex) { System.err.println(ex.getMessage()); System.err.println(dirPath + filename); throw ex; } catch (FileNotFoundException ex) { throw new TransformationException("File not found!", ex); } finally { if (is != null) { try { is.close(); } catch (IOException ex) { throw new TransformationException("Cannot close stream!", ex); } } } } } return documents; } #location 18 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public static void main(String[] args) throws ParseException, IOException, TransformationException, AnalysisException, CloneNotSupportedException { Options options = new Options(); options.addOption("under", false, "use undersampling for data selection"); options.addOption("over", false, "use oversampling for data selection"); options.addOption("normal", false, "don't use any special strategy for data selection"); CommandLineParser parser = new GnuParser(); CommandLine line = parser.parse(options, args); if (args.length != 2 || !(line.hasOption("under") ^ line.hasOption("over") ^ line.hasOption("normal"))) { HelpFormatter formatter = new HelpFormatter(); formatter.printHelp(" [-options] input-directory", options); System.exit(1); } String inputDirPath = line.getArgs()[0]; File inputDirFile = new File(inputDirPath); SampleSelector<BxZoneLabel> sampler = null; if (line.hasOption("over")) { sampler = new OversamplingSelector<BxZoneLabel>(1.0); } else if (line.hasOption("under")) { sampler = new UndersamplingSelector<BxZoneLabel>(1.0); } else if (line.hasOption("normal")) { sampler = new NormalSelector<BxZoneLabel>(); } else { System.err.println("Sampling pattern is not specified!"); System.exit(1); } List<TrainingSample<BxZoneLabel>> initialTrainingElements = new ArrayList<TrainingSample<BxZoneLabel>>(); List<TrainingSample<BxZoneLabel>> metaTrainingElements = new ArrayList<TrainingSample<BxZoneLabel>>(); HierarchicalReadingOrderResolver ror = new HierarchicalReadingOrderResolver(); EvaluationUtils.DocumentsIterator iter = new DocumentsIterator(inputDirPath); FeatureVectorBuilder<BxZone, BxPage> vectorBuilder; Integer docIdx = 0; for(BxDocument doc: iter) { doc = ror.resolve(doc); System.out.println(docIdx + ": " + doc.getFilename()); String filename = doc.getFilename(); doc = ror.resolve(doc); doc.setFilename(filename); //// for (BxZone zone : doc.asZones()) { if (zone.getLabel() != null) { if (zone.getLabel().getCategory() != BxZoneLabelCategory.CAT_METADATA) { zone.setLabel(zone.getLabel().getGeneralLabel()); } } else { zone.setLabel(BxZoneLabel.OTH_UNKNOWN); } } vectorBuilder = SVMMetadataZoneClassifier.getFeatureVectorBuilder(); List<TrainingSample<BxZoneLabel>> newSamples = BxDocsToTrainingSamplesConverter.getZoneTrainingSamples(doc, vectorBuilder, BxZoneLabel.getIdentityMap()); for(TrainingSample<BxZoneLabel> sample: newSamples) { if(sample.getLabel().getCategory() == BxZoneLabelCategory.CAT_METADATA) { metaTrainingElements.add(sample); } } //// vectorBuilder = SVMInitialZoneClassifier.getFeatureVectorBuilder(); newSamples = BxDocsToTrainingSamplesConverter.getZoneTrainingSamples(doc, vectorBuilder, BxZoneLabel.getLabelToGeneralMap()); initialTrainingElements.addAll(newSamples); //// ++docIdx; } initialTrainingElements = sampler.pickElements(initialTrainingElements); metaTrainingElements = sampler.pickElements(metaTrainingElements); toLibSVM(initialTrainingElements, "initial_" + inputDirFile.getName() + ".dat"); toLibSVM(metaTrainingElements, "meta_" + inputDirFile.getName() + ".dat"); }
#vulnerable code public static void main(String[] args) throws ParseException, IOException, TransformationException, AnalysisException { Options options = new Options(); options.addOption("under", false, "use undersampling for data selection"); options.addOption("over", false, "use oversampling for data selection"); options.addOption("normal", false, "don't use any special strategy for data selection"); CommandLineParser parser = new GnuParser(); CommandLine line = parser.parse(options, args); if (args.length != 2 || !(line.hasOption("under") ^ line.hasOption("over") ^ line.hasOption("normal"))) { HelpFormatter formatter = new HelpFormatter(); formatter.printHelp(" [-options] input-directory", options); System.exit(1); } String inputDirPath = line.getArgs()[0]; File inputDirFile = new File(inputDirPath); SampleSelector<BxZoneLabel> sampler = null; if (line.hasOption("over")) { sampler = new OversamplingSelector<BxZoneLabel>(1.0); } else if (line.hasOption("under")) { sampler = new UndersamplingSelector<BxZoneLabel>(2.0); } else if (line.hasOption("normal")) { sampler = new NormalSelector<BxZoneLabel>(); } else { System.err.println("Sampling pattern is not specified!"); System.exit(1); } List<TrainingSample<BxZoneLabel>> initialTrainingElements = new ArrayList<TrainingSample<BxZoneLabel>>(); List<TrainingSample<BxZoneLabel>> metaTrainingElements = new ArrayList<TrainingSample<BxZoneLabel>>(); EvaluationUtils.DocumentsIterator iter = new DocumentsIterator(inputDirPath); FeatureVectorBuilder<BxZone, BxPage> vectorBuilder; Integer docIdx = 0; for(BxDocument doc: iter) { System.out.println(docIdx + ": " + doc.getFilename()); //// for (BxZone zone : doc.asZones()) { if (zone.getLabel() != null) { if (zone.getLabel().getCategory() != BxZoneLabelCategory.CAT_METADATA) { zone.setLabel(zone.getLabel().getGeneralLabel()); } } else { zone.setLabel(BxZoneLabel.OTH_UNKNOWN); } } vectorBuilder = SVMMetadataZoneClassifier.getFeatureVectorBuilder(); List<TrainingSample<BxZoneLabel>> newSamples = BxDocsToTrainingSamplesConverter.getZoneTrainingSamples(doc, vectorBuilder, BxZoneLabel.getIdentityMap()); for(TrainingSample<BxZoneLabel> sample: newSamples) { if(sample.getLabel().getCategory() == BxZoneLabelCategory.CAT_METADATA) { metaTrainingElements.add(sample); } } //// vectorBuilder = SVMInitialZoneClassifier.getFeatureVectorBuilder(); newSamples = BxDocsToTrainingSamplesConverter.getZoneTrainingSamples(doc, vectorBuilder, BxZoneLabel.getLabelToGeneralMap()); initialTrainingElements.addAll(newSamples); //// ++docIdx; } initialTrainingElements = sampler.pickElements(initialTrainingElements); metaTrainingElements = sampler.pickElements(metaTrainingElements); toLibSVM(initialTrainingElements, "initial_" + inputDirFile.getName() + ".dat"); toLibSVM(metaTrainingElements, "meta_" + inputDirFile.getName() + ".dat"); } #location 37 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public static BxDocument getDocument(File file) throws IOException, TransformationException { TrueVizToBxDocumentReader tvReader = new TrueVizToBxDocumentReader(); BxDocument newDoc = new BxDocument(); InputStream is = new FileInputStream(file); try { List<BxPage> pages = tvReader.read(new InputStreamReader(is, "UTF-8")); for (BxPage page : pages) { page.setParent(newDoc); } newDoc.setFilename(file.getName()); newDoc.setPages(pages); return newDoc; } finally { is.close(); } }
#vulnerable code public static BxDocument getDocument(File file) throws IOException, TransformationException { TrueVizToBxDocumentReader tvReader = new TrueVizToBxDocumentReader(); BxDocument newDoc = new BxDocument(); InputStream is = new FileInputStream(file); try { List<BxPage> pages = tvReader.read(new InputStreamReader(is)); for (BxPage page : pages) { page.setParent(newDoc); } newDoc.setFilename(file.getName()); newDoc.setPages(pages); return newDoc; } finally { is.close(); } } #location 6 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public void loadModelFromFile(String modelFilePath, String rangeFilePath) throws IOException { BufferedReader modelFile = new BufferedReader(new InputStreamReader(new FileInputStream(modelFilePath), "UTF-8")); BufferedReader rangeFile = null; if (rangeFilePath != null) { rangeFile = new BufferedReader(new InputStreamReader(new FileInputStream(rangeFilePath), "UTF-8")); } loadModelFromFile(modelFile, rangeFile); }
#vulnerable code public void loadModelFromFile(String modelFilePath, String rangeFilePath) throws IOException { BufferedReader modelFile = new BufferedReader(new InputStreamReader(new FileInputStream(modelFilePath))); BufferedReader rangeFile = null; if (rangeFilePath != null) { rangeFile = new BufferedReader(new InputStreamReader(new FileInputStream(rangeFilePath))); } loadModelFromFile(modelFile, rangeFile); } #location 7 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Override public List<BxDocument> getDocuments() throws TransformationException { TrueVizToBxDocumentReader tvReader = new TrueVizToBxDocumentReader(); List<BxDocument> documents = new ArrayList<BxDocument>(); for (File file : FileUtils.listFiles(directory, new String[]{"xml"}, true)) { InputStream is = null; try { is = new FileInputStream(file); List<BxPage> pages = tvReader.read(new InputStreamReader(is, "UTF-8")); BxDocument doc = new BxDocument(); doc.setFilename(file.getName()); doc.setPages(pages); documents.add(doc); } catch (FileNotFoundException ex) { throw new TransformationException(ex); } catch (UnsupportedEncodingException ex) { throw new TransformationException(ex); } finally { if (is != null) { try { is.close(); } catch (IOException ex) { throw new TransformationException("Cannot close stream!", ex); } } } } return documents; }
#vulnerable code @Override public List<BxDocument> getDocuments() throws TransformationException { TrueVizToBxDocumentReader tvReader = new TrueVizToBxDocumentReader(); List<BxDocument> documents = new ArrayList<BxDocument>(); for (File file : FileUtils.listFiles(directory, new String[]{"xml"}, true)) { InputStream is = null; try { is = new FileInputStream(file); List<BxPage> pages = tvReader.read(new InputStreamReader(is)); BxDocument doc = new BxDocument(); doc.setFilename(file.getName()); doc.setPages(pages); documents.add(doc); } catch (FileNotFoundException ex) { throw new TransformationException(ex); } finally { if (is != null) { try { is.close(); } catch (IOException ex) { throw new TransformationException("Cannot close stream!", ex); } } } } return documents; } #location 10 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Test public void testSegmentPages() throws TransformationException, AnalysisException, UnsupportedEncodingException { Reader reader = new InputStreamReader(getResource("DocstrumPageSegmenter01.xml"), "UTF-8"); BxDocument inDoc = new BxDocument().setPages(new TrueVizToBxDocumentReader().read(reader)); new UnsegmentedPagesFlattener().process(inDoc); DocstrumSegmenter pageSegmenter = new ParallelDocstrumSegmenter(); BxDocument outDoc = pageSegmenter.segmentDocument(inDoc); // Check whether zones are correctly detected assertEquals(1, outDoc.childrenCount()); // Check whether lines are correctly detected List<BxZone> outZones = Lists.newArrayList(outDoc.getFirstChild()); assertEquals(3, outZones.size()); assertEquals(3, outZones.get(0).childrenCount()); assertEquals(16, outZones.get(1).childrenCount()); assertEquals(16, outZones.get(2).childrenCount()); assertEquals(24, outZones.get(1).getFirstChild().childrenCount()); assertEquals("A", outZones.get(1).getFirstChild().getFirstChild().toText()); for (BxZone zone : outZones) { for (BxLine line : zone) { for (BxWord word : line) { for (BxChunk chunk : word) { assertContains(zone.getBounds(), chunk.getBounds()); } assertContains(zone.getBounds(), word.getBounds()); } assertContains(zone.getBounds(), line.getBounds()); } } assertNotNull(outDoc.getFirstChild().getBounds()); }
#vulnerable code @Test public void testSegmentPages() throws TransformationException, AnalysisException { Reader reader = new InputStreamReader(getResource("DocstrumPageSegmenter01.xml")); BxDocument inDoc = new BxDocument().setPages(new TrueVizToBxDocumentReader().read(reader)); new UnsegmentedPagesFlattener().process(inDoc); DocstrumSegmenter pageSegmenter = new ParallelDocstrumSegmenter(); BxDocument outDoc = pageSegmenter.segmentDocument(inDoc); // Check whether zones are correctly detected assertEquals(1, outDoc.childrenCount()); // Check whether lines are correctly detected List<BxZone> outZones = Lists.newArrayList(outDoc.getFirstChild()); assertEquals(3, outZones.size()); assertEquals(3, outZones.get(0).childrenCount()); assertEquals(16, outZones.get(1).childrenCount()); assertEquals(16, outZones.get(2).childrenCount()); assertEquals(24, outZones.get(1).getFirstChild().childrenCount()); assertEquals("A", outZones.get(1).getFirstChild().getFirstChild().toText()); for (BxZone zone : outZones) { for (BxLine line : zone) { for (BxWord word : line) { for (BxChunk chunk : word) { assertContains(zone.getBounds(), chunk.getBounds()); } assertContains(zone.getBounds(), word.getBounds()); } assertContains(zone.getBounds(), line.getBounds()); } } assertNotNull(outDoc.getFirstChild().getBounds()); } #location 4 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Test public void testSegmentPages() throws TransformationException, AnalysisException, UnsupportedEncodingException { Reader reader = new InputStreamReader(getResource("DocstrumPageSegmenter01.xml"), "UTF-8"); BxDocument inDoc = new BxDocument().setPages(new TrueVizToBxDocumentReader().read(reader)); new UnsegmentedPagesFlattener().process(inDoc); DocstrumSegmenter pageSegmenter = new DocstrumSegmenter(); BxDocument outDoc = pageSegmenter.segmentDocument(inDoc); // Check whether zones are correctly detected assertEquals(1, outDoc.childrenCount()); // Check whether lines are correctly detected assertEquals(3, outDoc.getFirstChild().childrenCount()); assertEquals(3, outDoc.getFirstChild().getChild(0).childrenCount()); assertEquals(16, outDoc.getFirstChild().getChild(1).childrenCount()); assertEquals(16, outDoc.getFirstChild().getChild(2).childrenCount()); assertEquals(24, outDoc.getFirstChild().getChild(1).getFirstChild().childrenCount()); assertEquals("A", outDoc.getFirstChild().getChild(1).getFirstChild().getFirstChild().toText()); for (BxZone zone : outDoc.getFirstChild()) { for (BxLine line : zone) { for (BxWord word : line) { for (BxChunk chunk : word) { assertContains(zone.getBounds(), chunk.getBounds()); } assertContains(zone.getBounds(), word.getBounds()); } assertContains(zone.getBounds(), line.getBounds()); } } assertNotNull(outDoc.getFirstChild().getBounds()); }
#vulnerable code @Test public void testSegmentPages() throws TransformationException, AnalysisException { Reader reader = new InputStreamReader(getResource("DocstrumPageSegmenter01.xml")); BxDocument inDoc = new BxDocument().setPages(new TrueVizToBxDocumentReader().read(reader)); new UnsegmentedPagesFlattener().process(inDoc); DocstrumSegmenter pageSegmenter = new DocstrumSegmenter(); BxDocument outDoc = pageSegmenter.segmentDocument(inDoc); // Check whether zones are correctly detected assertEquals(1, outDoc.childrenCount()); // Check whether lines are correctly detected assertEquals(3, outDoc.getFirstChild().childrenCount()); assertEquals(3, outDoc.getFirstChild().getChild(0).childrenCount()); assertEquals(16, outDoc.getFirstChild().getChild(1).childrenCount()); assertEquals(16, outDoc.getFirstChild().getChild(2).childrenCount()); assertEquals(24, outDoc.getFirstChild().getChild(1).getFirstChild().childrenCount()); assertEquals("A", outDoc.getFirstChild().getChild(1).getFirstChild().getFirstChild().toText()); for (BxZone zone : outDoc.getFirstChild()) { for (BxLine line : zone) { for (BxWord word : line) { for (BxChunk chunk : word) { assertContains(zone.getBounds(), chunk.getBounds()); } assertContains(zone.getBounds(), word.getBounds()); } assertContains(zone.getBounds(), line.getBounds()); } } assertNotNull(outDoc.getFirstChild().getBounds()); } #location 4 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public void loadModelFromResources(String modelFilePath, String rangeFilePath) throws IOException { InputStreamReader modelISR = new InputStreamReader(SVMClassifier.class.getResourceAsStream(modelFilePath), "UTF-8"); BufferedReader modelFile = new BufferedReader(modelISR); InputStreamReader rangeISR = new InputStreamReader(SVMClassifier.class.getResourceAsStream(rangeFilePath), "UTF-8"); BufferedReader rangeFile = new BufferedReader(rangeISR); loadModelFromFile(modelFile, rangeFile); }
#vulnerable code public void loadModelFromResources(String modelFilePath, String rangeFilePath) throws IOException { InputStreamReader modelISR = new InputStreamReader(SVMClassifier.class.getResourceAsStream(modelFilePath)); BufferedReader modelFile = new BufferedReader(modelISR); InputStreamReader rangeISR = new InputStreamReader(SVMClassifier.class.getResourceAsStream(rangeFilePath)); BufferedReader rangeFile = new BufferedReader(rangeISR); loadModelFromFile(modelFile, rangeFile); } #location 7 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public String getErrorMessage() { String res; if (error != null) { res = error.getMessage(); if(res==null || res.isEmpty()) { res = "Exception is: "+error.getClass().toString(); } } else { res = "Unknown error"; log.warn("Unexpected question for error message while no exception. Wazzup?"); } return res; }
#vulnerable code public String getErrorMessage() { String res = ""; if (error != null) { res = error.getMessage(); if(res==null || res.isEmpty()) { res = "Exception is: "+res.getClass().toString(); } } else { res = "Unknown error"; log.warn("Unexpected question for error message while no exception. Wazzup?"); } return res; } #location 6 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Test public void testImporter() throws IOException, ParserConfigurationException, SAXException, TransformationException { BxPage page = new TrueVizToBxDocumentReader().read(new InputStreamReader(TrueVizToBxDocumentReaderTest.class.getResourceAsStream("/pl/edu/icm/cermine/structure/imports/MargImporterTest1.xml"), "UTF-8")).get(0); boolean contains = false; boolean rightText = false; boolean rightSize = false; for (BxZone zone : page) { if (zone.getLabel() != null) { if (zone.getLabel().equals(BxZoneLabel.MET_AUTHOR)) { contains = true; if (zone.toText().trim().equalsIgnoreCase("Howard M Schachter Ba Pham Jim King tt\nStephanie Langford David Moher".trim())) { rightText = true; } if (zone.getBounds().getX() == 72 && zone.getBounds().getY() == 778 && zone.getBounds().getWidth() == 989 && zone.getBounds().getHeight() == 122) { rightSize = true; } } } } assertTrue(contains); assertTrue(rightText); assertTrue(rightSize); BxWord word = page.getChild(0).getChild(0).getChild(0); assertEquals("font-1", word.getChild(0).getFontName()); assertEquals("font-2", word.getChild(1).getFontName()); }
#vulnerable code @Test public void testImporter() throws IOException, ParserConfigurationException, SAXException, TransformationException { BxPage page = new TrueVizToBxDocumentReader().read(new InputStreamReader(TrueVizToBxDocumentReaderTest.class.getResourceAsStream("/pl/edu/icm/cermine/structure/imports/MargImporterTest1.xml"))).get(0); boolean contains = false; boolean rightText = false; boolean rightSize = false; for (BxZone zone : page) { if (zone.getLabel() != null) { if (zone.getLabel().equals(BxZoneLabel.MET_AUTHOR)) { contains = true; if (zone.toText().trim().equalsIgnoreCase("Howard M Schachter Ba Pham Jim King tt\nStephanie Langford David Moher".trim())) { rightText = true; } if (zone.getBounds().getX() == 72 && zone.getBounds().getY() == 778 && zone.getBounds().getWidth() == 989 && zone.getBounds().getHeight() == 122) { rightSize = true; } } } } assertTrue(contains); assertTrue(rightText); assertTrue(rightSize); BxWord word = page.getChild(0).getChild(0).getChild(0); assertEquals("font-1", word.getChild(0).getFontName()); assertEquals("font-2", word.getChild(1).getFontName()); } #location 4 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Test public void metadataExtractionTest() throws AnalysisException, JDOMException, IOException, SAXException, TransformationException, URISyntaxException { InputStream expStream = AbstractBibReferenceExtractorTest.class.getResourceAsStream(EXP_FILE); BufferedReader expReader = new BufferedReader(new InputStreamReader(expStream, "UTF-8")); StringBuilder sb = new StringBuilder(); String line; while ((line = expReader.readLine()) != null) { sb.append(line); sb.append("\n"); } expStream.close(); expReader.close(); URL url = AbstractBibReferenceExtractorTest.class.getResource(TEST_FILE); ZipFile zipFile = new ZipFile(new File(url.toURI())); InputStream inputStream = zipFile.getInputStream(zipFile.getEntry("out.xml")); BxDocument expDocument = new BxDocument().setPages(bxReader.read(new InputStreamReader(inputStream, "UTF-8"))); String[] references = getExtractor().extractBibReferences(expDocument); assertEquals(StringUtils.join(references, "\n"), sb.toString().trim()); }
#vulnerable code @Test public void metadataExtractionTest() throws AnalysisException, JDOMException, IOException, SAXException, TransformationException, URISyntaxException { InputStream expStream = AbstractBibReferenceExtractorTest.class.getResourceAsStream(EXP_FILE); BufferedReader expReader = new BufferedReader(new InputStreamReader(expStream)); StringBuilder sb = new StringBuilder(); String line; while ((line = expReader.readLine()) != null) { sb.append(line); sb.append("\n"); } expStream.close(); expReader.close(); URL url = AbstractBibReferenceExtractorTest.class.getResource(TEST_FILE); ZipFile zipFile = new ZipFile(new File(url.toURI())); InputStream inputStream = zipFile.getInputStream(zipFile.getEntry("out.xml")); BxDocument expDocument = new BxDocument().setPages(bxReader.read(new InputStreamReader(inputStream))); String[] references = getExtractor().extractBibReferences(expDocument); assertEquals(StringUtils.join(references, "\n"), sb.toString().trim()); } #location 11 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Override public List<BxDocument> getDocuments() throws TransformationException { List<BxDocument> documents = new ArrayList<BxDocument>(); TrueVizToBxDocumentReader tvReader = new TrueVizToBxDocumentReader(); Enumeration<? extends ZipEntry> entries = zipFile.entries(); while (entries.hasMoreElements()) { ZipEntry zipEntry = (ZipEntry) entries.nextElement(); if (zipEntry.getName().endsWith("xml")) { try { List<BxPage> pages = tvReader.read(new InputStreamReader(zipFile.getInputStream(zipEntry), "UTF-8")); BxDocument newDoc = new BxDocument(); for (BxPage page : pages) { page.setParent(newDoc); } newDoc.setFilename(zipEntry.getName()); newDoc.setPages(pages); documents.add(newDoc); } catch (IOException ex) { throw new TransformationException("Cannot read file!", ex); } } } return documents; }
#vulnerable code @Override public List<BxDocument> getDocuments() throws TransformationException { List<BxDocument> documents = new ArrayList<BxDocument>(); TrueVizToBxDocumentReader tvReader = new TrueVizToBxDocumentReader(); Enumeration<? extends ZipEntry> entries = zipFile.entries(); while (entries.hasMoreElements()) { ZipEntry zipEntry = (ZipEntry) entries.nextElement(); if (zipEntry.getName().endsWith("xml")) { try { List<BxPage> pages = tvReader.read(new InputStreamReader(zipFile.getInputStream(zipEntry))); BxDocument newDoc = new BxDocument(); for (BxPage page : pages) { page.setParent(newDoc); } newDoc.setFilename(zipEntry.getName()); newDoc.setPages(pages); documents.add(newDoc); } catch (IOException ex) { throw new TransformationException("Cannot read file!", ex); } } } return documents; } #location 11 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public static void main(String[] args) throws JDOMException, IOException, AnalysisException { if (args.length != 3) { System.err.println("USAGE: ReferenceParsingEvaluator <foldness> <model_path> <test_path>"); System.exit(1); } int foldness = Integer.parseInt(args[0]); String modelPathSuffix = args[1]; String testPathSuffix = args[2]; Map<String, List<Result>> results = new HashMap<String, List<Result>>(); for (int i = 0; i < foldness; i++) { System.out.println("Fold "+i); String modelPath = modelPathSuffix + i; CRFBibReferenceParser parser = new CRFBibReferenceParser(modelPath); String testPath = testPathSuffix + i; File testFile = new File(testPath); List<Citation> testCitations; InputStream testIS = null; try { testIS = new FileInputStream(testFile); InputSource testSource = new InputSource(testIS); testCitations = NlmCitationExtractor.extractCitations(testSource); } finally { if (testIS != null) { testIS.close(); } } System.out.println(testCitations.size()); List<BibEntry> testEntries = new ArrayList<BibEntry>(); for (Citation c : testCitations) { BibEntry entry = CitationUtils.citationToBibref(c); testEntries.add(entry); for (String key : entry.getFieldKeys()) { if (results.get(key) == null) { results.put(key, new ArrayList<Result>()); } } } int j = 0; for (BibEntry orig : testEntries) { BibEntry test = parser.parseBibReference(orig.getText()); System.out.println(); System.out.println(); System.out.println(orig.toBibTeX()); System.out.println(test.toBibTeX()); Map<String, Result> map = new HashMap<String, Result>(); for (String s : orig.getFieldKeys()) { if (map.get(s) == null) { map.put(s, new Result()); } map.get(s).addOrig(orig.getAllFieldValues(s).size()); } for (String s : test.getFieldKeys()) { if (map.get(s) == null) { map.put(s, new Result()); } map.get(s).addExtr(test.getAllFieldValues(s).size()); } for (String s : test.getFieldKeys()) { List<String> origVals = orig.getAllFieldValues(s); for (String testVal : test.getAllFieldValues(s)) { boolean found = false; if (origVals.contains(testVal)) { map.get(s).addSuccess(); origVals.remove(testVal); found = true; } if (!found) { System.out.println("WRONG "+s); } } } for (Map.Entry<String, Result> s : map.entrySet()) { System.out.println(""); System.out.println(s.getKey()); System.out.println(s.getValue()); System.out.println(s.getValue().getPrecision()); System.out.println(s.getValue().getRecall()); results.get(s.getKey()).add(s.getValue()); } j++; System.out.println("Tested "+j+" out of "+testEntries.size()); } } for (Map.Entry<String, List<Result>> e : results.entrySet()) { System.out.println(""); System.out.println(e.getKey()); System.out.println(e.getValue().size()); double precision = 0; int precisionCount = 0; double recall = 0; int recallCount = 0; for (Result r : e.getValue()) { if (r.getPrecision() != null) { precision += r.getPrecision(); precisionCount++; } if (r.getRecall() != null) { recall += r.getRecall(); recallCount++; } } System.out.println("Precision count "+precisionCount); System.out.println("Mean precision "+(precision / precisionCount)); System.out.println("Recall count "+recallCount); System.out.println("Mean recall "+(recall / recallCount)); } }
#vulnerable code public static void main(String[] args) throws JDOMException, IOException, AnalysisException { if (args.length != 3) { System.err.println("USAGE: ReferenceParsingEvaluator <foldness> <model_path> <test_path>"); System.exit(1); } int foldness = Integer.parseInt(args[0]); String modelPathSuffix = args[1]; String testPathSuffix = args[2]; Map<String, List<Result>> results = new HashMap<String, List<Result>>(); for (int i = 0; i < foldness; i++) { System.out.println("Fold "+i); String modelPath = modelPathSuffix + i; CRFBibReferenceParser parser = new CRFBibReferenceParser(modelPath); String testPath = testPathSuffix + i; File testFile = new File(testPath); List<Citation> testCitations; InputStream testIS = null; try { testIS = new FileInputStream(testFile); InputSource testSource = new InputSource(testIS); testCitations = NlmCitationExtractor.extractCitations(testSource); } finally { if (testIS != null) { testIS.close(); } } System.out.println(testCitations.size()); List<BibEntry> testEntries = new ArrayList<BibEntry>(); for (Citation c : testCitations) { BibEntry entry = CitationUtils.citationToBibref(c); testEntries.add(entry); for (String key : entry.getFieldKeys()) { if (results.get(key) == null) { results.put(key, new ArrayList<Result>()); } } } int j = 0; for (BibEntry orig : testEntries) { BibEntry test = parser.parseBibReference(orig.getText()); System.out.println(); System.out.println(); System.out.println(orig.toBibTeX()); System.out.println(test.toBibTeX()); Map<String, Result> map = new HashMap<String, Result>(); for (String s : orig.getFieldKeys()) { if (map.get(s) == null) { map.put(s, new Result()); } map.get(s).addOrig(orig.getAllFieldValues(s).size()); } for (String s : test.getFieldKeys()) { if (map.get(s) == null) { map.put(s, new Result()); } map.get(s).addExtr(test.getAllFieldValues(s).size()); } for (String s : test.getFieldKeys()) { List<String> origVals = orig.getAllFieldValues(s); for (String testVal : test.getAllFieldValues(s)) { boolean found = false; if (origVals.contains(testVal)) { map.get(s).addSuccess(); origVals.remove(testVal); found = true; } if (!found) { System.out.println("WRONG "+s); } } } for (Map.Entry<String, Result> s : map.entrySet()) { System.out.println(""); System.out.println(s.getKey()); System.out.println(s.getValue()); System.out.println(s.getValue().getPrecision()); System.out.println(s.getValue().getRecall()); results.get(s.getKey()).add(s.getValue()); } j++; System.out.println("Tested "+j+" out of "+testEntries.size()); } } for (String s : results.keySet()) { System.out.println(""); System.out.println(s); System.out.println(results.get(s).size()); double precision = 0; int precisionCount = 0; double recall = 0; int recallCount = 0; for (Result r : results.get(s)) { if (r.getPrecision() != null) { precision += r.getPrecision(); precisionCount++; } if (r.getRecall() != null) { recall += r.getRecall(); recallCount++; } } System.out.println("Precision count "+precisionCount); System.out.println("Mean precision "+(precision / precisionCount)); System.out.println("Recall count "+recallCount); System.out.println("Mean recall "+(recall / recallCount)); } } #location 103 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Test public void deepCloneTest() throws TransformationException, UnsupportedEncodingException { InputStream stream = BxModelUtilsTest.class.getResourceAsStream(EXP_STR_LAB_1); TrueVizToBxDocumentReader reader = new TrueVizToBxDocumentReader(); BxDocument doc = new BxDocument().setPages(reader.read(new InputStreamReader(stream, "UTF-8"))); BxDocument copy = BxModelUtils.deepClone(doc); assertFalse(doc == copy); assertTrue(BxModelUtils.areEqual(doc, copy)); Stack<BxPage> pages = new Stack<BxPage>(); Stack<BxZone> zones = new Stack<BxZone>(); Stack<BxLine> lines = new Stack<BxLine>(); Stack<BxWord> words = new Stack<BxWord>(); Stack<BxChunk> chunks = new Stack<BxChunk>(); for (BxPage page : copy) { assertTrue(page.getParent() == copy); for (BxZone zone : page) { assertTrue(zone.getParent() == page); for (BxLine line : zone) { assertTrue(line.getParent() == zone); for (BxWord word : line) { assertTrue(word.getParent() == line); for (BxChunk chunk : word) { assertTrue(chunk.getParent() == word); } } } } } BxPage page = copy.getFirstChild(); while (page != null) { pages.push(page); page = page.getNext(); } page = pages.peek(); BxZone zone = copy.getFirstChild().getFirstChild(); while (zone != null) { zones.push(zone); zone = zone.getNext(); } zone = zones.peek(); BxLine line = copy.getFirstChild().getFirstChild().getFirstChild(); while (line != null) { lines.push(line); line = line.getNext(); } line = lines.peek(); BxWord word = copy.getFirstChild().getFirstChild().getFirstChild().getFirstChild(); while (word != null) { words.push(word); word = word.getNext(); } word = words.peek(); BxChunk chunk = copy.getFirstChild().getFirstChild().getFirstChild().getFirstChild().getFirstChild(); while (chunk != null) { chunks.push(chunk); chunk = chunk.getNext(); } chunk = chunks.peek(); while (!pages.empty() && !zones.empty() && !lines.empty() && !words.empty() && !chunks.empty()) { BxChunk ch = chunks.pop(); assertTrue(ch.getParent() == words.peek()); assertTrue(words.peek().getParent() == lines.peek()); assertTrue(lines.peek().getParent() == zones.peek()); assertTrue(zones.peek().getParent() == pages.peek()); if (chunks.empty()) { words.pop(); lines.pop(); zones.pop(); pages.pop(); } else if (ch.getParent() != chunks.peek().getParent()) { BxWord w = words.pop(); assertFalse(words.empty()); if (w.getParent() != words.peek().getParent()) { BxLine l = lines.pop(); assertFalse(lines.empty()); if (l.getParent() != lines.peek().getParent()) { BxZone z = zones.pop(); assertFalse(zones.empty()); if (z.getParent() != zones.peek().getParent()) { pages.pop(); assertFalse(pages.empty()); } } } } } assertTrue(pages.empty()); assertTrue(zones.empty()); assertTrue(lines.empty()); assertTrue(words.empty()); assertTrue(chunks.empty()); while (page != null) { pages.push(page); page = page.getPrev(); } while (zone != null) { zones.push(zone); zone = zone.getPrev(); } while (line != null) { lines.push(line); line = line.getPrev(); } while (word != null) { words.push(word); word = word.getPrev(); } while (chunk != null) { chunks.push(chunk); chunk = chunk.getPrev(); } while (!pages.empty() && !zones.empty() && !lines.empty() && !words.empty() && !chunks.empty()) { BxChunk ch = chunks.pop(); assertTrue(ch.getParent() == words.peek()); assertTrue(words.peek().getParent() == lines.peek()); assertTrue(lines.peek().getParent() == zones.peek()); assertTrue(zones.peek().getParent() == pages.peek()); if (chunks.empty()) { words.pop(); lines.pop(); zones.pop(); pages.pop(); } else if (ch.getParent() != chunks.peek().getParent()) { BxWord w = words.pop(); assertFalse(words.empty()); if (w.getParent() != words.peek().getParent()) { BxLine l = lines.pop(); assertFalse(lines.empty()); if (l.getParent() != lines.peek().getParent()) { BxZone z = zones.pop(); assertFalse(zones.empty()); if (z.getParent() != zones.peek().getParent()) { pages.pop(); assertFalse(pages.empty()); } } } } } assertTrue(pages.empty()); assertTrue(zones.empty()); assertTrue(lines.empty()); assertTrue(words.empty()); assertTrue(chunks.empty()); }
#vulnerable code @Test public void deepCloneTest() throws TransformationException { InputStream stream = BxModelUtilsTest.class.getResourceAsStream(EXP_STR_LAB_1); TrueVizToBxDocumentReader reader = new TrueVizToBxDocumentReader(); BxDocument doc = new BxDocument().setPages(reader.read(new InputStreamReader(stream))); BxDocument copy = BxModelUtils.deepClone(doc); assertFalse(doc == copy); assertTrue(BxModelUtils.areEqual(doc, copy)); Stack<BxPage> pages = new Stack<BxPage>(); Stack<BxZone> zones = new Stack<BxZone>(); Stack<BxLine> lines = new Stack<BxLine>(); Stack<BxWord> words = new Stack<BxWord>(); Stack<BxChunk> chunks = new Stack<BxChunk>(); for (BxPage page : copy) { assertTrue(page.getParent() == copy); for (BxZone zone : page) { assertTrue(zone.getParent() == page); for (BxLine line : zone) { assertTrue(line.getParent() == zone); for (BxWord word : line) { assertTrue(word.getParent() == line); for (BxChunk chunk : word) { assertTrue(chunk.getParent() == word); } } } } } BxPage page = copy.getFirstChild(); while (page != null) { pages.push(page); page = page.getNext(); } page = pages.peek(); BxZone zone = copy.getFirstChild().getFirstChild(); while (zone != null) { zones.push(zone); zone = zone.getNext(); } zone = zones.peek(); BxLine line = copy.getFirstChild().getFirstChild().getFirstChild(); while (line != null) { lines.push(line); line = line.getNext(); } line = lines.peek(); BxWord word = copy.getFirstChild().getFirstChild().getFirstChild().getFirstChild(); while (word != null) { words.push(word); word = word.getNext(); } word = words.peek(); BxChunk chunk = copy.getFirstChild().getFirstChild().getFirstChild().getFirstChild().getFirstChild(); while (chunk != null) { chunks.push(chunk); chunk = chunk.getNext(); } chunk = chunks.peek(); while (!pages.empty() && !zones.empty() && !lines.empty() && !words.empty() && !chunks.empty()) { BxChunk ch = chunks.pop(); assertTrue(ch.getParent() == words.peek()); assertTrue(words.peek().getParent() == lines.peek()); assertTrue(lines.peek().getParent() == zones.peek()); assertTrue(zones.peek().getParent() == pages.peek()); if (chunks.empty()) { words.pop(); lines.pop(); zones.pop(); pages.pop(); } else if (ch.getParent() != chunks.peek().getParent()) { BxWord w = words.pop(); assertFalse(words.empty()); if (w.getParent() != words.peek().getParent()) { BxLine l = lines.pop(); assertFalse(lines.empty()); if (l.getParent() != lines.peek().getParent()) { BxZone z = zones.pop(); assertFalse(zones.empty()); if (z.getParent() != zones.peek().getParent()) { pages.pop(); assertFalse(pages.empty()); } } } } } assertTrue(pages.empty()); assertTrue(zones.empty()); assertTrue(lines.empty()); assertTrue(words.empty()); assertTrue(chunks.empty()); while (page != null) { pages.push(page); page = page.getPrev(); } while (zone != null) { zones.push(zone); zone = zone.getPrev(); } while (line != null) { lines.push(line); line = line.getPrev(); } while (word != null) { words.push(word); word = word.getPrev(); } while (chunk != null) { chunks.push(chunk); chunk = chunk.getPrev(); } while (!pages.empty() && !zones.empty() && !lines.empty() && !words.empty() && !chunks.empty()) { BxChunk ch = chunks.pop(); assertTrue(ch.getParent() == words.peek()); assertTrue(words.peek().getParent() == lines.peek()); assertTrue(lines.peek().getParent() == zones.peek()); assertTrue(zones.peek().getParent() == pages.peek()); if (chunks.empty()) { words.pop(); lines.pop(); zones.pop(); pages.pop(); } else if (ch.getParent() != chunks.peek().getParent()) { BxWord w = words.pop(); assertFalse(words.empty()); if (w.getParent() != words.peek().getParent()) { BxLine l = lines.pop(); assertFalse(lines.empty()); if (l.getParent() != lines.peek().getParent()) { BxZone z = zones.pop(); assertFalse(zones.empty()); if (z.getParent() != zones.peek().getParent()) { pages.pop(); assertFalse(pages.empty()); } } } } } assertTrue(pages.empty()); assertTrue(zones.empty()); assertTrue(lines.empty()); assertTrue(words.empty()); assertTrue(chunks.empty()); } #location 5 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public void loadModelFromResources(String modelFilePath, String rangeFilePath) throws IOException { InputStreamReader modelISR = new InputStreamReader(this.getClass().getResourceAsStream(modelFilePath)); BufferedReader modelFile = new BufferedReader(modelISR); InputStreamReader rangeISR = new InputStreamReader(this.getClass().getResourceAsStream(rangeFilePath)); BufferedReader rangeFile = new BufferedReader(rangeISR); loadModelFromFile(modelFile, rangeFile); }
#vulnerable code public void loadModelFromResources(String modelFilePath, String rangeFilePath) throws IOException { InputStreamReader modelISR = new InputStreamReader(SVMClassifier.class .getResourceAsStream(modelFilePath)); BufferedReader modelFile = new BufferedReader(modelISR); BufferedReader rangeFile = null; if (rangeFilePath != null) { InputStreamReader rangeISR = new InputStreamReader(SVMClassifier.class .getResourceAsStream(rangeFilePath)); rangeFile = new BufferedReader(rangeISR); } loadModelFromFile(modelFile, rangeFile); } #location 13 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public void loadModelFromResources(String modelFilePath, String rangeFilePath) throws IOException { InputStreamReader modelISR = new InputStreamReader(SVMClassifier.class.getResourceAsStream(modelFilePath), "UTF-8"); BufferedReader modelFile = new BufferedReader(modelISR); InputStreamReader rangeISR = new InputStreamReader(SVMClassifier.class.getResourceAsStream(rangeFilePath), "UTF-8"); BufferedReader rangeFile = new BufferedReader(rangeISR); loadModelFromFile(modelFile, rangeFile); }
#vulnerable code public void loadModelFromResources(String modelFilePath, String rangeFilePath) throws IOException { InputStreamReader modelISR = new InputStreamReader(SVMClassifier.class.getResourceAsStream(modelFilePath)); BufferedReader modelFile = new BufferedReader(modelISR); InputStreamReader rangeISR = new InputStreamReader(SVMClassifier.class.getResourceAsStream(rangeFilePath)); BufferedReader rangeFile = new BufferedReader(rangeISR); loadModelFromFile(modelFile, rangeFile); } #location 7 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public void loadModelFromFile(String modelFilePath, String rangeFilePath) throws IOException { BufferedReader modelFile = new BufferedReader(new InputStreamReader(new FileInputStream(modelFilePath), "UTF-8")); BufferedReader rangeFile = null; if (rangeFilePath != null) { rangeFile = new BufferedReader(new InputStreamReader(new FileInputStream(rangeFilePath), "UTF-8")); } loadModelFromFile(modelFile, rangeFile); }
#vulnerable code public void loadModelFromFile(String modelFilePath, String rangeFilePath) throws IOException { BufferedReader modelFile = new BufferedReader(new InputStreamReader(new FileInputStream(modelFilePath))); BufferedReader rangeFile = null; if (rangeFilePath != null) { rangeFile = new BufferedReader(new InputStreamReader(new FileInputStream(rangeFilePath))); } loadModelFromFile(modelFile, rangeFile); } #location 6 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code private BxDocument getDocumentFromZip(String filename) throws TransformationException, IOException { TrueVizToBxDocumentReader tvReader = new TrueVizToBxDocumentReader(); Enumeration<? extends ZipEntry> entries = zipFile.entries(); while (entries.hasMoreElements()) { ZipEntry zipEntry = (ZipEntry) entries.nextElement(); if (zipEntry.getName().equals(filename)) { List<BxPage> pages = tvReader.read(new InputStreamReader(zipFile.getInputStream(zipEntry), "UTF-8")); BxDocument newDoc = new BxDocument(); for (BxPage page : pages) { page.setParent(newDoc); } newDoc.setFilename(zipEntry.getName()); newDoc.setPages(pages); return newDoc; } } return null; }
#vulnerable code private BxDocument getDocumentFromZip(String filename) throws TransformationException, IOException { TrueVizToBxDocumentReader tvReader = new TrueVizToBxDocumentReader(); Enumeration<? extends ZipEntry> entries = zipFile.entries(); while (entries.hasMoreElements()) { ZipEntry zipEntry = (ZipEntry) entries.nextElement(); if (zipEntry.getName().equals(filename)) { List<BxPage> pages = tvReader.read(new InputStreamReader(zipFile.getInputStream(zipEntry))); BxDocument newDoc = new BxDocument(); for (BxPage page : pages) { page.setParent(newDoc); } newDoc.setFilename(zipEntry.getName()); newDoc.setPages(pages); return newDoc; } } return null; } #location 7 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public static void main(String[] args) throws AnalysisException, TransformationException, IOException { // args[0] path to xml directory if(args.length != 1) { System.err.println("Source directory needed!"); System.exit(1); } SVMInitialZoneClassifier classifier = new SVMInitialZoneClassifier("/pl/edu/icm/cermine/structure/svm_initial_classifier", "/pl/edu/icm/cermine/structure/svm_initial_classifier.range"); ReadingOrderResolver ror = new HierarchicalReadingOrderResolver(); BxDocumentToTrueVizWriter tvw = new BxDocumentToTrueVizWriter(); List<BxDocument> docs = EvaluationUtils.getDocumentsFromPath(args[0]); for(BxDocument doc: docs) { System.out.println(">> " + doc.getFilename()); ror.resolve(doc); classifier.classifyZones(doc); BufferedWriter out = null; try { // Create file FileWriter fstream = new FileWriter(doc.getFilename()); out = new BufferedWriter(fstream); out.write(tvw.write(doc.getPages())); out.close(); } catch (Exception e){//Catch exception if any System.err.println("Error: " + e.getMessage()); } finally { if(out != null) { out.close(); } } } }
#vulnerable code public static void main(String[] args) throws AnalysisException, TransformationException, IOException { // args[0] path to xml directory if(args.length != 1) { System.err.println("Source directory needed!"); System.exit(1); } InputStreamReader modelISR = new InputStreamReader(Thread.currentThread().getClass() .getResourceAsStream("/pl/edu/icm/cermine/structure/svm_initial_classifier")); BufferedReader modelFile = new BufferedReader(modelISR); InputStreamReader rangeISR = new InputStreamReader(Thread.currentThread().getClass() .getResourceAsStream("/pl/edu/icm/cermine/structure/svm_initial_classifier.range")); BufferedReader rangeFile = new BufferedReader(rangeISR); SVMZoneClassifier classifier = new SVMInitialZoneClassifier(modelFile, rangeFile); ReadingOrderResolver ror = new HierarchicalReadingOrderResolver(); BxDocumentToTrueVizWriter tvw = new BxDocumentToTrueVizWriter(); List<BxDocument> docs = EvaluationUtils.getDocumentsFromPath(args[0]); for(BxDocument doc: docs) { System.out.println(">> " + doc.getFilename()); ror.resolve(doc); classifier.classifyZones(doc); BufferedWriter out = null; try { // Create file FileWriter fstream = new FileWriter(doc.getFilename()); out = new BufferedWriter(fstream); out.write(tvw.write(doc.getPages())); out.close(); } catch (Exception e){//Catch exception if any System.err.println("Error: " + e.getMessage()); } finally { if(out != null) { out.close(); } } } } #location 15 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public static String getFileSha1(File file) { if (!file.isFile()) { return null; } MessageDigest digest = null; FileInputStream in = null; byte[] buffer = new byte[8192]; int len; try { digest = MessageDigest.getInstance("SHA-1"); in = new FileInputStream(file); while ((len = in.read(buffer)) != -1) { digest.update(buffer, 0, len); } BigInteger bigInt = new BigInteger(1, digest.digest()); return bigInt.toString(16); } catch (Exception e) { e.printStackTrace(); return null; } finally { try { if (in != null) { in.close(); } } catch (Exception e) { e.printStackTrace(); } } }
#vulnerable code public static String getFileSha1(File file) { if (!file.isFile()) { return null; } MessageDigest digest = null; FileInputStream in = null; byte buffer[] = new byte[8192]; int len; try { digest = MessageDigest.getInstance("SHA-1"); in = new FileInputStream(file); while ((len = in.read(buffer)) != -1) { digest.update(buffer, 0, len); } BigInteger bigInt = new BigInteger(1, digest.digest()); return bigInt.toString(16); } catch (Exception e) { e.printStackTrace(); return null; } finally { try { in.close(); } catch (Exception e) { e.printStackTrace(); } } } #location 22 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public void writeToXml() throws Exception { // 排版缩进的格式 OutputFormat format = OutputFormat.createPrettyPrint(); // 设置编码 format.setEncoding("UTF-8"); // 创建XMLWriter对象,指定了写出文件及编码格式 XMLWriter writer = null; writer = new XMLWriter( new OutputStreamWriter(new FileOutputStream(new File(ConstantsTools.PATH_CONFIG)), StandardCharsets.UTF_8), format); // 写入 writer.write(document); writer.flush(); writer.close(); }
#vulnerable code public void writeToXml() throws Exception { // 排版缩进的格式 OutputFormat format = OutputFormat.createPrettyPrint(); // 设置编码 format.setEncoding("UTF-8"); // 创建XMLWriter对象,指定了写出文件及编码格式 XMLWriter writer = null; writer = new XMLWriter( new OutputStreamWriter(new FileOutputStream(new File(ConstantsTools.PATH_CONFIG)), "UTF-8"), format); // 写入 writer.write(document); writer.flush(); writer.close(); } #location 8 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code GitHub(String apiUrl, String login, String oauthAccessToken, String jwtToken, String password, HttpConnector connector, RateLimitHandler rateLimitHandler, AbuseLimitHandler abuseLimitHandler) throws IOException { if (apiUrl.endsWith("/")) apiUrl = apiUrl.substring(0, apiUrl.length() - 1); // normalize this.apiUrl = apiUrl; if (null != connector) this.connector = connector; if (oauthAccessToken != null) { encodedAuthorization = "token " + oauthAccessToken; } else { if (jwtToken != null) { encodedAuthorization = "Bearer " + jwtToken; } else if (password != null) { String authorization = (login + ':' + password); String charsetName = Charsets.UTF_8.name(); encodedAuthorization = "Basic " + new String(Base64.encodeBase64(authorization.getBytes(charsetName)), charsetName); } else {// anonymous access encodedAuthorization = null; } } users = new ConcurrentHashMap<String, GHUser>(); orgs = new ConcurrentHashMap<String, GHOrganization>(); this.rateLimitHandler = rateLimitHandler; this.abuseLimitHandler = abuseLimitHandler; if (login == null && encodedAuthorization != null && jwtToken == null) login = getMyself().getLogin(); this.login = login; }
#vulnerable code <T extends GHMetaExamples.GHMetaExample> GHMetaExamples.GHMetaExample getMetaExample(Class<T> clazz) throws IOException { return retrieve().to("/meta", clazz); } #location 3 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Override protected String getApiRoute() { if (owner == null) { // Issues returned from search to do not have an owner. Attempt to use url. final URL url = Objects.requireNonNull(getUrl(), "Missing instance URL!"); return StringUtils.prependIfMissing(url.toString().replace(root.getApiUrl(), ""), "/"); } return "/repos/" + owner.getOwnerName() + "/" + owner.getName() + "/pulls/" + number; }
#vulnerable code @Override protected String getApiRoute() { if (owner == null) { // Issues returned from search to do not have an owner. Attempt to use url. return StringUtils.prependIfMissing(getUrl().toString().replace(root.getApiUrl(), ""), "/"); } return "/repos/" + owner.getOwnerName() + "/" + owner.getName() + "/pulls/" + number; } #location 5 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public <T> T to(URL url, Class<T> type) throws IOException { HttpURLConnection uc = (HttpURLConnection) url.openConnection(); uc.setDoOutput(true); uc.setRequestProperty("Content-type","application/x-www-form-urlencoded"); uc.setRequestMethod("POST"); StringBuilder body = new StringBuilder(); for (Entry<String, String> e : args.entrySet()) { if (body.length()>0) body.append('&'); body.append(URLEncoder.encode(e.getKey(),"UTF-8")); body.append('='); body.append(URLEncoder.encode(e.getValue(),"UTF-8")); } OutputStreamWriter o = new OutputStreamWriter(uc.getOutputStream(), "UTF-8"); o.write(body.toString()); o.close(); try { InputStreamReader r = new InputStreamReader(uc.getInputStream(), "UTF-8"); if (type==null) { String data = IOUtils.toString(r); return null; } return MAPPER.readValue(r,type); } catch (IOException e) { throw (IOException)new IOException(IOUtils.toString(uc.getErrorStream(),"UTF-8")).initCause(e); } }
#vulnerable code public <T> T to(URL url, Class<T> type) throws IOException { HttpURLConnection uc = (HttpURLConnection) url.openConnection(); uc.setDoOutput(true); uc.setRequestProperty("Content-type","application/x-www-form-urlencoded"); uc.setRequestMethod("POST"); StringBuilder body = new StringBuilder(); for (Entry<String, String> e : args.entrySet()) { if (body.length()>0) body.append('&'); body.append(URLEncoder.encode(e.getKey(),"UTF-8")); body.append('='); body.append(URLEncoder.encode(e.getValue(),"UTF-8")); } OutputStreamWriter o = new OutputStreamWriter(uc.getOutputStream(), "UTF-8"); o.write(body.toString()); o.close(); try { InputStreamReader r = new InputStreamReader(uc.getInputStream(), "UTF-8"); if (type==null) return null; return MAPPER.readValue(r,type); } catch (IOException e) { throw (IOException)new IOException(IOUtils.toString(uc.getErrorStream(),"UTF-8")).initCause(e); } } #location 24 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code protected String getIssuesApiRoute() { if (owner == null) { // Issues returned from search to do not have an owner. Attempt to use url. final URL url = Objects.requireNonNull(getUrl(), "Missing instance URL!"); return StringUtils.prependIfMissing(url.toString().replace(root.getApiUrl(), ""), "/"); } return "/repos/" + owner.getOwnerName() + "/" + owner.getName() + "/issues/" + number; }
#vulnerable code protected String getIssuesApiRoute() { if (owner == null) { // Issues returned from search to do not have an owner. Attempt to use url. return StringUtils.prependIfMissing(getUrl().toString().replace(root.getApiUrl(), ""), "/"); } return "/repos/" + owner.getOwnerName() + "/" + owner.getName() + "/issues/" + number; } #location 4 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code static PagedIterable<GHDiscussion> readAll(GHTeam team) throws IOException { return team.root.createRequest() .setRawUrlPath(getRawUrlPath(team, null)) .toIterable(GHDiscussion[].class, item -> item.wrapUp(team)); }
#vulnerable code static PagedIterable<GHDiscussion> readAll(GHTeam team) throws IOException { return team.root.createRequest() .setRawUrlPath(team.getUrl().toString() + "/discussions") .toIterable(GHDiscussion[].class, item -> item.wrapUp(team)); } #location 3 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code static GHDiscussion read(GHTeam team, long discussionNumber) throws IOException { return team.root.createRequest() .setRawUrlPath(getRawUrlPath(team, discussionNumber)) .fetch(GHDiscussion.class) .wrapUp(team); }
#vulnerable code static GHDiscussion read(GHTeam team, long discussionNumber) throws IOException { return team.root.createRequest() .setRawUrlPath(team.getUrl().toString() + "/discussions/" + discussionNumber) .fetch(GHDiscussion.class) .wrapUp(team); } #location 3 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public void delete() throws IOException { team.root.createRequest().method("DELETE").setRawUrlPath(getRawUrlPath(team, number)).send(); }
#vulnerable code public void delete() throws IOException { team.root.createRequest() .method("DELETE") .setRawUrlPath(team.getUrl().toString() + "/discussions/" + number) .send(); } #location 4 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public <T> T to(URL url, Class<T> type) throws IOException { HttpURLConnection uc = (HttpURLConnection) url.openConnection(); uc.setDoOutput(true); uc.setRequestProperty("Content-type","application/x-www-form-urlencoded"); uc.setRequestMethod("POST"); StringBuilder body = new StringBuilder(); for (Entry<String, String> e : args.entrySet()) { if (body.length()>0) body.append('&'); body.append(URLEncoder.encode(e.getKey(),"UTF-8")); body.append('='); body.append(URLEncoder.encode(e.getValue(),"UTF-8")); } OutputStreamWriter o = new OutputStreamWriter(uc.getOutputStream(), "UTF-8"); o.write(body.toString()); o.close(); try { InputStreamReader r = new InputStreamReader(uc.getInputStream(), "UTF-8"); if (type==null) { String data = IOUtils.toString(r); return null; } return MAPPER.readValue(r,type); } catch (IOException e) { throw (IOException)new IOException(IOUtils.toString(uc.getErrorStream(),"UTF-8")).initCause(e); } }
#vulnerable code public <T> T to(URL url, Class<T> type) throws IOException { HttpURLConnection uc = (HttpURLConnection) url.openConnection(); uc.setDoOutput(true); uc.setRequestProperty("Content-type","application/x-www-form-urlencoded"); uc.setRequestMethod("POST"); StringBuilder body = new StringBuilder(); for (Entry<String, String> e : args.entrySet()) { if (body.length()>0) body.append('&'); body.append(URLEncoder.encode(e.getKey(),"UTF-8")); body.append('='); body.append(URLEncoder.encode(e.getValue(),"UTF-8")); } OutputStreamWriter o = new OutputStreamWriter(uc.getOutputStream(), "UTF-8"); o.write(body.toString()); o.close(); try { InputStreamReader r = new InputStreamReader(uc.getInputStream(), "UTF-8"); if (type==null) return null; return MAPPER.readValue(r,type); } catch (IOException e) { throw (IOException)new IOException(IOUtils.toString(uc.getErrorStream(),"UTF-8")).initCause(e); } } #location 24 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Test public void testWindowPeer() throws Exception { if (Platform.isMacOSX() || System.getProperty("java.version").matches("1\\.6\\..*")) { // Oracle Java and jawt: it's complicated. // See http://forum.lwjgl.org/index.php?topic=4326.0 // OpenJDK 6 + Linux seem problematic too. return; } assertEquals(6 * Pointer.SIZE, BridJ.sizeOf(JAWT_DrawingSurface.class)); assertEquals(4 * 4, BridJ.sizeOf(JAWT_Rectangle.class)); //assertEquals(4 + 5 * Pointer.SIZE, BridJ.sizeOf(JAWT.class)); //assertEquals(2 * 4 * 4 + 4 + Pointer.SIZE, BridJ.sizeOf(JAWT_DrawingSurfaceInfo.class)); Frame f = new Frame(); f.pack(); f.setVisible(true); Thread.sleep(500); long p = JAWTUtils.getNativePeerHandle(f); assertTrue(p != 0); f.setVisible(false); }
#vulnerable code @Test public void testWindowPeer() throws Exception { if (Platform.isMacOSX() || System.getProperty("java.version)").matches("1\\.6\\..*")) { // Oracle Java and jawt: it's complicated. // See http://forum.lwjgl.org/index.php?topic=4326.0 // OpenJDK 6 + Linux seem problematic too. return; } assertEquals(6 * Pointer.SIZE, BridJ.sizeOf(JAWT_DrawingSurface.class)); assertEquals(4 * 4, BridJ.sizeOf(JAWT_Rectangle.class)); //assertEquals(4 + 5 * Pointer.SIZE, BridJ.sizeOf(JAWT.class)); //assertEquals(2 * 4 * 4 + 4 + Pointer.SIZE, BridJ.sizeOf(JAWT_DrawingSurfaceInfo.class)); Frame f = new Frame(); f.pack(); f.setVisible(true); Thread.sleep(500); long p = JAWTUtils.getNativePeerHandle(f); assertTrue(p != 0); f.setVisible(false); } #location 4 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code private HttpClient getHttpClient(PrintStream logger) throws Exception { boolean ignoreUnverifiedSSL = ignoreUnverifiedSSLPeer; String stashServer = stashServerBaseUrl; DescriptorImpl descriptor = getDescriptor(); if ("".equals(stashServer) || stashServer == null) { stashServer = descriptor.getStashRootUrl(); } if (!ignoreUnverifiedSSL) { ignoreUnverifiedSSL = descriptor.isIgnoreUnverifiedSsl(); } URL url = new URL(stashServer); HttpClientBuilder builder = HttpClientBuilder.create(); if (url.getProtocol().equals("https") && ignoreUnverifiedSSL) { // add unsafe trust manager to avoid thrown // SSLPeerUnverifiedException try { TrustStrategy easyStrategy = new TrustStrategy() { public boolean isTrusted(X509Certificate[] chain, String authType) throws CertificateException { return true; } }; SSLContext sslContext = SSLContexts.custom() .loadTrustMaterial(null, easyStrategy) .useTLS().build(); SSLConnectionSocketFactory sslConnSocketFactory = new SSLConnectionSocketFactory(sslContext, SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER); builder.setSSLSocketFactory(sslConnSocketFactory); Registry<ConnectionSocketFactory> registry = RegistryBuilder.<ConnectionSocketFactory>create() .register("https", sslConnSocketFactory) .build(); HttpClientConnectionManager ccm = new BasicHttpClientConnectionManager(registry); builder.setConnectionManager(ccm); } catch (NoSuchAlgorithmException nsae) { logger.println("Couldn't establish SSL context:"); nsae.printStackTrace(logger); } catch (KeyManagementException kme) { logger.println("Couldn't initialize SSL context:"); kme.printStackTrace(logger); } catch (KeyStoreException kse) { logger.println("Couldn't initialize SSL context:"); kse.printStackTrace(logger); } } // Configure the proxy, if needed // Using the Jenkins methods handles the noProxyHost settings ProxyConfiguration proxyConfig = Jenkins.getInstance().proxy; if (proxyConfig != null) { Proxy proxy = proxyConfig.createProxy(url.getHost()); if (proxy != null && proxy.type() == Proxy.Type.HTTP) { SocketAddress addr = proxy.address(); if (addr != null && addr instanceof InetSocketAddress) { InetSocketAddress proxyAddr = (InetSocketAddress) addr; HttpHost proxyHost = new HttpHost(proxyAddr.getAddress().getHostAddress(), proxyAddr.getPort()); builder = builder.setProxy(proxyHost); String proxyUser = proxyConfig.getUserName(); if (proxyUser != null) { String proxyPass = proxyConfig.getPassword(); CredentialsProvider cred = new BasicCredentialsProvider(); cred.setCredentials(new AuthScope(proxyHost), new UsernamePasswordCredentials(proxyUser, proxyPass)); builder = builder .setDefaultCredentialsProvider(cred) .setProxyAuthenticationStrategy(new ProxyAuthenticationStrategy()); } } } } return builder.build(); }
#vulnerable code private HttpClient getHttpClient(PrintStream logger) { HttpClient client = null; boolean ignoreUnverifiedSSL = ignoreUnverifiedSSLPeer; String url = stashServerBaseUrl; DescriptorImpl descriptor = getDescriptor(); if ("".equals(url) || url == null) { url = descriptor.getStashRootUrl(); } if (!ignoreUnverifiedSSL) { ignoreUnverifiedSSL = descriptor.isIgnoreUnverifiedSsl(); } if (url.startsWith("https") && ignoreUnverifiedSSL) { // add unsafe trust manager to avoid thrown // SSLPeerUnverifiedException try { HttpClientBuilder builder = HttpClientBuilder.create(); TrustStrategy easyStrategy = new TrustStrategy() { public boolean isTrusted(X509Certificate[] chain, String authType) throws CertificateException { return true; } }; SSLContext sslContext = SSLContexts.custom() .loadTrustMaterial(null, easyStrategy) .useTLS().build(); SSLConnectionSocketFactory sslConnSocketFactory = new SSLConnectionSocketFactory(sslContext, SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER); builder.setSSLSocketFactory(sslConnSocketFactory); Registry<ConnectionSocketFactory> registry = RegistryBuilder.<ConnectionSocketFactory>create() .register("https", sslConnSocketFactory) .build(); HttpClientConnectionManager ccm = new BasicHttpClientConnectionManager(registry); builder.setConnectionManager(ccm); client = builder.build(); } catch (NoSuchAlgorithmException nsae) { logger.println("Couldn't establish SSL context:"); nsae.printStackTrace(logger); } catch (KeyManagementException kme) { logger.println("Couldn't initialize SSL context:"); kme.printStackTrace(logger); } catch (KeyStoreException kse) { logger.println("Couldn't initialize SSL context:"); kse.printStackTrace(logger); } finally { if (client == null) { logger.println("Trying with safe trust manager, instead!"); client = HttpClientBuilder.create().build(); } } } else { client = HttpClientBuilder.create().build(); } ProxyConfiguration proxy = Jenkins.getInstance().proxy; if(proxy != null && !proxy.name.isEmpty() && !proxy.name.startsWith("http") && !isHostOnNoProxyList(proxy)){ SchemeRegistry schemeRegistry = client.getConnectionManager().getSchemeRegistry(); schemeRegistry.register(new Scheme("http", proxy.port, new PlainSocketFactory())); client.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, new HttpHost(proxy.name, proxy.port)); } return client; } #location 12 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public static void main(String[] args) { AppUtil appUtil = new AppUtil(); AService service = (AService) appUtil.getComponentInstance("aService"); AggregateRootA aggregateRootA = service.getAggregateRootA("11"); DomainMessage res = service.commandA("11", aggregateRootA, 100); long start = System.currentTimeMillis(); int result = 0; DomainMessage res1 = (DomainMessage) res.getBlockEventResult(); if (res1 != null && res1.getBlockEventResult() != null) result = (Integer) res1.getBlockEventResult(); long stop = System.currentTimeMillis(); Assert.assertEquals(result, 400); System.out.print("\n ok \n" + result + " time:" + (stop - start)); }
#vulnerable code public static void main(String[] args) { AppUtil appUtil = new AppUtil(); AService service = (AService) appUtil.getComponentInstance("aService"); AggregateRootA aggregateRootA = service.getAggregateRootA("11"); DomainMessage res = service.commandA("11", aggregateRootA, 100); long start = System.currentTimeMillis(); int result = 0; DomainMessage res1 = (DomainMessage) res.getBlockEventResult(); if (res1.getBlockEventResult() != null) result = (Integer) res1.getBlockEventResult(); long stop = System.currentTimeMillis(); Assert.assertEquals(result, 400); System.out.print("\n ok \n" + result + (stop - start)); } #location 10 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public boolean doExists(String name, Locale locale, String path) throws Exception { if (file != null && file.exists()) { ZipFile zipFile = new ZipFile(file); try { return zipFile.getEntry(name) != null; } finally { zipFile.close(); } } return false; }
#vulnerable code public boolean doExists(String name, Locale locale, String path) throws Exception { return file != null && file.exists() && new ZipFile(file).getEntry(name) != null; } #location 2 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public long getLastModified() { try { JarFile jarFile = new JarFile(file); return jarFile.getEntry(getName()).getTime(); } catch (Throwable e) { return super.getLastModified(); } }
#vulnerable code public long getLastModified() { try { JarFile zipFile = new JarFile(file); return zipFile.getEntry(getName()).getTime(); } catch (Throwable e) { return super.getLastModified(); } } #location 4 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public Template extend(String name, Locale locale, String encoding) throws IOException, ParseException { if (name == null || name.length() == 0) { throw new IllegalArgumentException("include template name == null"); } String macro = null; int i = name.indexOf('#'); if (i > 0) { macro = name.substring(i + 1); name = name.substring(0, i); } Template template = Context.getContext().getTemplate(); if (template != null) { if (encoding == null || encoding.length() == 0) { encoding = template.getEncoding(); } name = UrlUtils.relativeUrl(name, template.getName()); if (locale == null) { locale = template.getLocale(); } } Template extend = engine.getTemplate(name); if (macro != null && macro.length() > 0) { extend = extend.getMacros().get(macro); } if (template != null) { if (template == extend) { throw new IllegalStateException("The template " + template.getName() + " can not be recursive extending the self template."); } Context.getContext().putAll(template.getMacros()); } return extend; }
#vulnerable code public Template extend(String name, Locale locale, String encoding) throws IOException, ParseException { if (name == null || name.length() == 0) { throw new IllegalArgumentException("include template name == null"); } String macro = null; int i = name.indexOf('#'); if (i > 0) { macro = name.substring(i + 1); name = name.substring(0, i); } Template template = Context.getContext().getTemplate(); if (template != null) { if (encoding == null || encoding.length() == 0) { encoding = template.getEncoding(); } name = UrlUtils.relativeUrl(name, template.getName()); if (locale == null) { locale = template.getLocale(); } } Template extend = engine.getTemplate(name); if (macro != null && macro.length() > 0) { extend = extend.getMacros().get(macro); } if (template != null && template == extend) { throw new IllegalStateException("The template " + template.getName() + " can not be recursive extending the self template."); } Context.getContext().putAll(template.getMacros()); return extend; } #location 28 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public Template parse(String name, String encoding) throws IOException, ParseException { if (name == null || name.length() == 0) { throw new IllegalArgumentException("include template name == null"); } String macro = null; int i = name.indexOf('#'); if (i > 0) { macro = name.substring(i + 1); name = name.substring(0, i); } Template template = Context.getContext().getTemplate(); if (template != null) { if (encoding == null || encoding.length() == 0) { encoding = template.getEncoding(); } name = UrlUtils.relativeUrl(name, template.getName()); } template = engine.getTemplate(name, encoding); if (macro != null && macro.length() > 0) { return template.getMacros().get(macro); } return template; }
#vulnerable code public Template parse(String name, String encoding) throws IOException, ParseException { if (name == null || name.length() == 0) { throw new IllegalArgumentException("include template name == null"); } String macro = null; int i = name.indexOf('#'); if (i > 0) { macro = name.substring(i + 1); name = name.substring(0, i); } Template template = Context.getContext().getTemplate(); if (template != null) { if (encoding == null || encoding.length() == 0) { encoding = template.getEncoding(); } name = UrlUtils.relativeUrl(name, template.getName()); } name = UrlUtils.cleanUrl(name.trim()); template = engine.getTemplate(name, encoding); if (macro != null && macro.length() > 0) { return template.getMacros().get(macro); } return template; } #location 18 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public boolean doExists(String name, Locale locale, String path) throws Exception { if (file != null && file.exists()) { JarFile jarFile = new JarFile(file); try { return jarFile.getEntry(name) != null; } finally { jarFile.close(); } } return false; }
#vulnerable code public boolean doExists(String name, Locale locale, String path) throws Exception { return file != null && file.exists() && new JarFile(file).getEntry(name) != null; } #location 2 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public static Object decodeToObject( String encodedObject, int options, final ClassLoader loader ) throws java.io.IOException, java.lang.ClassNotFoundException { // Decode and gunzip if necessary byte[] objBytes = decode( encodedObject, options ); java.io.ByteArrayInputStream bais = null; java.io.ObjectInputStream ois = null; Object obj = null; try { bais = new java.io.ByteArrayInputStream( objBytes ); // If no custom class loader is provided, use Java's builtin OIS. if( loader == null ){ ois = new java.io.ObjectInputStream( bais ); } // end if: no loader provided // Else make a customized object input stream that uses // the provided class loader. else { ois = new java.io.ObjectInputStream(bais){ @Override public Class<?> resolveClass(java.io.ObjectStreamClass streamClass) throws java.io.IOException, ClassNotFoundException { Class<?> c = Class.forName(streamClass.getName(), false, loader); if( c == null ){ return super.resolveClass(streamClass); } else { return c; // Class loader knows of this class. } // end else: not null } // end resolveClass }; // end ois } // end else: no custom class loader obj = ois.readObject(); } // end try catch( java.io.IOException e ) { throw e; // Catch and throw in order to execute finally{} } // end catch catch( java.lang.ClassNotFoundException e ) { throw e; // Catch and throw in order to execute finally{} } // end catch finally { try { if (bais != null) bais.close(); } finally { if (ois != null) ois.close(); } } // end finally return obj; }
#vulnerable code public static Object decodeToObject( String encodedObject, int options, final ClassLoader loader ) throws java.io.IOException, java.lang.ClassNotFoundException { // Decode and gunzip if necessary byte[] objBytes = decode( encodedObject, options ); java.io.ByteArrayInputStream bais = null; java.io.ObjectInputStream ois = null; Object obj = null; try { bais = new java.io.ByteArrayInputStream( objBytes ); // If no custom class loader is provided, use Java's builtin OIS. if( loader == null ){ ois = new java.io.ObjectInputStream( bais ); } // end if: no loader provided // Else make a customized object input stream that uses // the provided class loader. else { ois = new java.io.ObjectInputStream(bais){ @Override public Class<?> resolveClass(java.io.ObjectStreamClass streamClass) throws java.io.IOException, ClassNotFoundException { Class<?> c = Class.forName(streamClass.getName(), false, loader); if( c == null ){ return super.resolveClass(streamClass); } else { return c; // Class loader knows of this class. } // end else: not null } // end resolveClass }; // end ois } // end else: no custom class loader obj = ois.readObject(); } // end try catch( java.io.IOException e ) { throw e; // Catch and throw in order to execute finally{} } // end catch catch( java.lang.ClassNotFoundException e ) { throw e; // Catch and throw in order to execute finally{} } // end catch finally { try{ bais.close(); } catch( Exception e ){} try{ ois.close(); } catch( Exception e ){} } // end finally return obj; } #location 47 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Test public void testException() throws Exception { boolean profile = "true".equals(System.getProperty("profile")); Engine engine = Engine.getEngine("httl-exception.properties"); String dir = engine.getProperty("template.directory", ""); if (dir.length() > 0 && dir.startsWith("/")) { dir = dir.substring(1); } if (dir.length() > 0 && ! dir.endsWith("/")) { dir += "/"; } URL url = this.getClass().getClassLoader().getResource(dir + "results/" + templateName + ".txt"); if (url == null) { throw new FileNotFoundException("Not found file: " + dir + "results/" + templateName + ".txt"); } File result = new File(url.getFile()); if (! result.exists()) { throw new FileNotFoundException("Not found file: " + result.getAbsolutePath()); } try { engine.getTemplate("/templates/" + templateName); fail(templateName); } catch (ParseException e) { if (! profile) { String message = e.getMessage(); assertTrue(StringUtils.isNotEmpty(message)); List<String> expected = IOUtils.readLines(new FileReader(result)); assertTrue(expected != null && expected.size() > 0); for (String part : expected) { assertTrue(StringUtils.isNotEmpty(part)); part = StringUtils.unescapeString(part).trim(); assertTrue(templateName + ", exception message: \"" + message + "\" not contains: \"" + part + "\"", message.contains(part)); } } } }
#vulnerable code @Test public void testException() throws Exception { boolean profile = "true".equals(System.getProperty("profile")); if (! profile) System.out.println("========httl-exception.properties========"); Engine engine = Engine.getEngine("httl-exception.properties"); String dir = engine.getProperty("template.directory", ""); if (dir.length() > 0 && dir.startsWith("/")) { dir = dir.substring(1); } if (dir.length() > 0 && ! dir.endsWith("/")) { dir += "/"; } File directory = new File(this.getClass().getClassLoader().getResource(dir + "templates/").getFile()); assertTrue(directory.isDirectory()); File[] files = directory.listFiles(); for (int i = 0, n = files.length; i < n; i ++) { File file = files[i]; System.out.println(file.getName()); URL url = this.getClass().getClassLoader().getResource(dir + "results/" + file.getName() + ".txt"); if (url == null) { throw new FileNotFoundException("Not found file: " + dir + "results/" + file.getName() + ".txt"); } File result = new File(url.getFile()); if (! result.exists()) { throw new FileNotFoundException("Not found file: " + result.getAbsolutePath()); } try { engine.getTemplate("/templates/" + file.getName()); fail(file.getName()); } catch (ParseException e) { if (! profile) { String message = e.getMessage(); assertTrue(StringUtils.isNotEmpty(message)); List<String> expected = IOUtils.readLines(new FileReader(result)); assertTrue(expected != null && expected.size() > 0); for (String part : expected) { assertTrue(StringUtils.isNotEmpty(part)); part = StringUtils.unescapeString(part).trim(); assertTrue(file.getName() + ", exception message: \"" + message + "\" not contains: \"" + part + "\"", message.contains(part)); } } } } } #location 17 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public long getLength() { try { JarFile jarFile = new JarFile(file); try { return jarFile.getEntry(getName()).getSize(); } finally { jarFile.close(); } } catch (IOException e) { return super.getLength(); } }
#vulnerable code public long getLength() { try { JarFile jarFile = new JarFile(file); return jarFile.getEntry(getName()).getSize(); } catch (IOException e) { return super.getLength(); } } #location 4 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public static void setServletContext(ServletContext servletContext) { if (servletContext == null) { return; } if (ServletLoader.getServletContext() == null) { ServletLoader.setServletContext(servletContext); } if (ENGINE == null) { synchronized (WebEngine.class) { if (ENGINE == null) { // double check Properties properties = new Properties(); String config = servletContext.getInitParameter(CONFIG_KEY); if (StringUtils.isEmpty(config)) { config = WEBINF_CONFIG; } if (config.startsWith("/")) { InputStream in = servletContext.getResourceAsStream(config); if (in != null) { try { properties.load(in); } catch (IOException e) { throw new IllegalStateException("Failed to load httl config " + config + " in wepapp. cause: " + e.getMessage(), e); } } else if (servletContext.getInitParameter(CONFIG_KEY) != null) { // 用户主动配置错误提醒 throw new IllegalStateException("Not found httl config " + config + " in wepapp."); } else { config = null; } } ENGINE = Engine.getEngine(config, addProperties(properties)); logConfigPath(ENGINE, servletContext, config); } } } }
#vulnerable code public static void setServletContext(ServletContext servletContext) { if (servletContext == null) { return; } if (ServletLoader.getServletContext() == null) { ServletLoader.setServletContext(servletContext); } if (ENGINE == null) { synchronized (WebEngine.class) { if (ENGINE == null) { // double check Properties properties = new Properties(); String config = servletContext.getInitParameter(CONFIG_KEY); if (config == null || config.length() == 0) { config = WEBINF_CONFIG; } if (config.startsWith("/")) { InputStream in = servletContext.getResourceAsStream(config); if (in != null) { try { properties.load(in); } catch (IOException e) { throw new IllegalStateException("Failed to load httl config " + config + " in wepapp. cause: " + e.getMessage(), e); } } else if (servletContext.getInitParameter(CONFIG_KEY) != null) { // 用户主动配置错误提醒 throw new IllegalStateException("Not found httl config " + config + " in wepapp."); } else { config = null; } } ENGINE = Engine.getEngine(config, addProperties(properties)); logConfigPath(ENGINE, servletContext, config); } } } } #location 5 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public static String encodeObject( java.io.Serializable serializableObject, int options ) throws java.io.IOException { if( serializableObject == null ){ throw new NullPointerException( "Cannot serialize a null object." ); } // end if: null // Streams java.io.ByteArrayOutputStream baos = null; java.io.OutputStream b64os = null; java.util.zip.GZIPOutputStream gzos = null; java.io.ObjectOutputStream oos = null; try { // ObjectOutputStream -> (GZIP) -> Base64 -> ByteArrayOutputStream baos = new java.io.ByteArrayOutputStream(); b64os = new Base64.OutputStream( baos, ENCODE | options ); if( (options & GZIP) != 0 ){ // Gzip gzos = new java.util.zip.GZIPOutputStream(b64os); oos = new java.io.ObjectOutputStream( gzos ); } else { // Not gzipped oos = new java.io.ObjectOutputStream( b64os ); } oos.writeObject( serializableObject ); } // end try catch( java.io.IOException e ) { // Catch it and then throw it immediately so that // the finally{} block is called for cleanup. throw e; } // end catch finally { try { if (oos != null) oos.close(); } finally { try { if (gzos != null) gzos.close(); } finally { try { if (b64os != null) b64os.close(); } finally { if (baos != null) baos.close(); } } } } // end finally // Return value according to relevant encoding. try { return new String( baos.toByteArray(), PREFERRED_ENCODING ); } // end try catch (java.io.UnsupportedEncodingException uue){ // Fall back to some Java default return new String( baos.toByteArray() ); } // end catch }
#vulnerable code public static String encodeObject( java.io.Serializable serializableObject, int options ) throws java.io.IOException { if( serializableObject == null ){ throw new NullPointerException( "Cannot serialize a null object." ); } // end if: null // Streams java.io.ByteArrayOutputStream baos = null; java.io.OutputStream b64os = null; java.util.zip.GZIPOutputStream gzos = null; java.io.ObjectOutputStream oos = null; try { // ObjectOutputStream -> (GZIP) -> Base64 -> ByteArrayOutputStream baos = new java.io.ByteArrayOutputStream(); b64os = new Base64.OutputStream( baos, ENCODE | options ); if( (options & GZIP) != 0 ){ // Gzip gzos = new java.util.zip.GZIPOutputStream(b64os); oos = new java.io.ObjectOutputStream( gzos ); } else { // Not gzipped oos = new java.io.ObjectOutputStream( b64os ); } oos.writeObject( serializableObject ); } // end try catch( java.io.IOException e ) { // Catch it and then throw it immediately so that // the finally{} block is called for cleanup. throw e; } // end catch finally { try{ oos.close(); } catch( Exception e ){} try{ gzos.close(); } catch( Exception e ){} try{ b64os.close(); } catch( Exception e ){} try{ baos.close(); } catch( Exception e ){} } // end finally // Return value according to relevant encoding. try { return new String( baos.toByteArray(), PREFERRED_ENCODING ); } // end try catch (java.io.UnsupportedEncodingException uue){ // Fall back to some Java default return new String( baos.toByteArray() ); } // end catch } #location 35 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code private static String getRefValue(Properties result, String v) { while (v != null && v.startsWith(REF)) { String ref = v.substring(1); v = result.getProperty(ref); if (v == null) { v = System.getProperty(ref); } } return v == null ? "" : v; }
#vulnerable code private static String getRefValue(Properties result, String v) { if (v != null) { while (v.startsWith(REF)) { String ref = v.substring(1); v = result.getProperty(ref); if (v == null) { v = System.getProperty(ref); } } } return v == null ? "" : v; } #location 3 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public long getLength() { try { ZipFile zipFile = new ZipFile(file); try { return zipFile.getEntry(getName()).getSize(); } finally { zipFile.close(); } } catch (IOException e) { return super.getLength(); } }
#vulnerable code public long getLength() { try { ZipFile zipFile = new ZipFile(file); return zipFile.getEntry(getName()).getSize(); } catch (IOException e) { return super.getLength(); } } #location 4 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public static void setServletContext(ServletContext servletContext) { if (servletContext == null) { return; } if (ServletLoader.getServletContext() == null) { ServletLoader.setServletContext(servletContext); } if (ENGINE == null) { synchronized (WebEngine.class) { if (ENGINE == null) { // double check Properties properties = new Properties(); String config = servletContext.getInitParameter(CONFIG_KEY); if (StringUtils.isEmpty(config)) { config = WEBINF_CONFIG; } if (config.startsWith("/")) { InputStream in = servletContext.getResourceAsStream(config); if (in != null) { try { properties.load(in); } catch (IOException e) { throw new IllegalStateException("Failed to load httl config " + config + " in wepapp. cause: " + e.getMessage(), e); } } else if (servletContext.getInitParameter(CONFIG_KEY) != null) { // 用户主动配置错误提醒 throw new IllegalStateException("Not found httl config " + config + " in wepapp."); } else { config = null; } } ENGINE = Engine.getEngine(config, addProperties(properties)); logConfigPath(ENGINE, servletContext, config); } } } }
#vulnerable code public static void setServletContext(ServletContext servletContext) { if (servletContext == null) { return; } if (ServletLoader.getServletContext() == null) { ServletLoader.setServletContext(servletContext); } if (ENGINE == null) { synchronized (WebEngine.class) { if (ENGINE == null) { // double check Properties properties = new Properties(); String config = servletContext.getInitParameter(CONFIG_KEY); if (config == null || config.length() == 0) { config = WEBINF_CONFIG; } if (config.startsWith("/")) { InputStream in = servletContext.getResourceAsStream(config); if (in != null) { try { properties.load(in); } catch (IOException e) { throw new IllegalStateException("Failed to load httl config " + config + " in wepapp. cause: " + e.getMessage(), e); } } else if (servletContext.getInitParameter(CONFIG_KEY) != null) { // 用户主动配置错误提醒 throw new IllegalStateException("Not found httl config " + config + " in wepapp."); } else { config = null; } } ENGINE = Engine.getEngine(config, addProperties(properties)); logConfigPath(ENGINE, servletContext, config); } } } } #location 6 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public static byte[] decode( String s, int options ) throws java.io.IOException { if( s == null ){ throw new NullPointerException( "Input string was null." ); } // end if byte[] bytes; try { bytes = s.getBytes( PREFERRED_ENCODING ); } // end try catch( java.io.UnsupportedEncodingException uee ) { bytes = s.getBytes(); } // end catch //</change> // Decode bytes = decode( bytes, 0, bytes.length, options ); // Check to see if it's gzip-compressed // GZIP Magic Two-Byte Number: 0x8b1f (35615) boolean dontGunzip = (options & DONT_GUNZIP) != 0; if( (bytes != null) && (bytes.length >= 4) && (!dontGunzip) ) { int head = ((int)bytes[0] & 0xff) | ((bytes[1] << 8) & 0xff00); if( java.util.zip.GZIPInputStream.GZIP_MAGIC == head ) { java.io.ByteArrayInputStream bais = null; java.util.zip.GZIPInputStream gzis = null; java.io.ByteArrayOutputStream baos = null; byte[] buffer = new byte[2048]; int length = 0; try { baos = new java.io.ByteArrayOutputStream(); bais = new java.io.ByteArrayInputStream( bytes ); gzis = new java.util.zip.GZIPInputStream( bais ); while( ( length = gzis.read( buffer ) ) >= 0 ) { baos.write(buffer,0,length); } // end while: reading input // No error? Get new bytes. bytes = baos.toByteArray(); } // end try catch( java.io.IOException e ) { // Just return originally-decoded bytes } // end catch finally { try { if (baos != null) baos.close(); } finally { try { if (gzis != null) gzis.close(); } finally { if (bais != null) bais.close(); } } } // end finally } // end if: gzipped } // end if: bytes.length >= 2 return bytes; }
#vulnerable code public static byte[] decode( String s, int options ) throws java.io.IOException { if( s == null ){ throw new NullPointerException( "Input string was null." ); } // end if byte[] bytes; try { bytes = s.getBytes( PREFERRED_ENCODING ); } // end try catch( java.io.UnsupportedEncodingException uee ) { bytes = s.getBytes(); } // end catch //</change> // Decode bytes = decode( bytes, 0, bytes.length, options ); // Check to see if it's gzip-compressed // GZIP Magic Two-Byte Number: 0x8b1f (35615) boolean dontGunzip = (options & DONT_GUNZIP) != 0; if( (bytes != null) && (bytes.length >= 4) && (!dontGunzip) ) { int head = ((int)bytes[0] & 0xff) | ((bytes[1] << 8) & 0xff00); if( java.util.zip.GZIPInputStream.GZIP_MAGIC == head ) { java.io.ByteArrayInputStream bais = null; java.util.zip.GZIPInputStream gzis = null; java.io.ByteArrayOutputStream baos = null; byte[] buffer = new byte[2048]; int length = 0; try { baos = new java.io.ByteArrayOutputStream(); bais = new java.io.ByteArrayInputStream( bytes ); gzis = new java.util.zip.GZIPInputStream( bais ); while( ( length = gzis.read( buffer ) ) >= 0 ) { baos.write(buffer,0,length); } // end while: reading input // No error? Get new bytes. bytes = baos.toByteArray(); } // end try catch( java.io.IOException e ) { // Just return originally-decoded bytes } // end catch finally { try{ baos.close(); } catch( Exception e ){} try{ gzis.close(); } catch( Exception e ){} try{ bais.close(); } catch( Exception e ){} } // end finally } // end if: gzipped } // end if: bytes.length >= 2 return bytes; } #location 50 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public boolean doExists(String name, Locale locale, String path) throws Exception { InputStream in = new URL(path).openStream(); try { return in != null; } finally { if (in != null) in.close(); } }
#vulnerable code public boolean doExists(String name, Locale locale, String path) throws Exception { InputStream in = new URL(path).openStream(); try { return in != null; } finally { in.close(); } } #location 6 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public void init() { defaultFilterVariable = "$" + filterVariable; defaultFormatterVariable = "$" + formatterVariable; if (importVariables != null && importVariables.length > 0) { this.importTypes = new HashMap<String, Class<?>>(); for (String var : importVariables) { int i = var.lastIndexOf(' '); if (i < 0) { throw new IllegalArgumentException("Illegal config import.setVariables"); } this.importTypes.put(var.substring(i + 1), ClassUtils.forName(importPackages, var.substring(0, i))); } } }
#vulnerable code public void init() { defaultFilterVariable = "$" + filterVariable; defaultFormatterVariable = "$" + formatterVariable; if (importVariables != null && importVariables.length > 0) { this.importTypes = new HashMap<String, Class<?>>(); for (String var : importVariables) { int i = var.lastIndexOf(' '); if (i < 0) { throw new IllegalArgumentException("Illegal config import.setVariables"); } this.importTypes.put(var.substring(i + 1), ClassUtils.forName(importPackages, var.substring(0, i))); } } if (importMethods != null && importMethods.length > 0) { for (String method : importMethods) { Class<?> cls = ClassUtils.forName(importPackages, method); Object ins; try { ins = cls.newInstance(); } catch (Exception e) { ins = cls; } this.functions.put(cls, ins); } } } #location 19 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public static Object parseXbean(String xml) { if (xml == null) { return null; } ByteArrayInputStream bi = new ByteArrayInputStream(xml.getBytes()); XMLDecoder xd = new XMLDecoder(bi); try { return xd.readObject(); } finally { xd.close(); } }
#vulnerable code public static Object parseXbean(String xml) { if (xml == null) { return null; } ByteArrayInputStream bi = new ByteArrayInputStream(xml.getBytes()); XMLDecoder xd = new XMLDecoder(bi); return xd.readObject(); } #location 7 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public static byte[] encodeBytesToBytes( byte[] source, int off, int len, int options ) throws java.io.IOException { if( source == null ){ throw new NullPointerException( "Cannot serialize a null array." ); } // end if: null if( off < 0 ){ throw new IllegalArgumentException( "Cannot have negative offset: " + off ); } // end if: off < 0 if( len < 0 ){ throw new IllegalArgumentException( "Cannot have length offset: " + len ); } // end if: len < 0 if( off + len > source.length ){ throw new IllegalArgumentException( String.format( "Cannot have offset of %d and length of %d with array of length %d", off,len,source.length)); } // end if: off < 0 // Compress? if( (options & GZIP) != 0 ) { java.io.ByteArrayOutputStream baos = null; java.util.zip.GZIPOutputStream gzos = null; Base64.OutputStream b64os = null; try { // GZip -> Base64 -> ByteArray baos = new java.io.ByteArrayOutputStream(); b64os = new Base64.OutputStream( baos, ENCODE | options ); gzos = new java.util.zip.GZIPOutputStream( b64os ); gzos.write( source, off, len ); gzos.close(); } // end try catch( java.io.IOException e ) { // Catch it and then throw it immediately so that // the finally{} block is called for cleanup. throw e; } // end catch finally { try { if (gzos != null) gzos.close(); } finally { try { if (b64os != null) b64os.close(); } finally { if (baos != null) baos.close(); } } } // end finally return baos.toByteArray(); } // end if: compress // Else, don't compress. Better not to use streams at all then. else { boolean breakLines = (options & DO_BREAK_LINES) != 0; //int len43 = len * 4 / 3; //byte[] outBuff = new byte[ ( len43 ) // Main 4:3 // + ( (len % 3) > 0 ? 4 : 0 ) // Account for padding // + (breakLines ? ( len43 / MAX_LINE_LENGTH ) : 0) ]; // New lines // Try to determine more precisely how big the array needs to be. // If we get it right, we don't have to do an array copy, and // we save a bunch of memory. int encLen = ( len / 3 ) * 4 + ( len % 3 > 0 ? 4 : 0 ); // Bytes needed for actual encoding if( breakLines ){ encLen += encLen / MAX_LINE_LENGTH; // Plus extra newline characters } byte[] outBuff = new byte[ encLen ]; int d = 0; int e = 0; int len2 = len - 2; int lineLength = 0; for( ; d < len2; d+=3, e+=4 ) { encode3to4( source, d+off, 3, outBuff, e, options ); lineLength += 4; if( breakLines && lineLength >= MAX_LINE_LENGTH ) { outBuff[e+4] = NEW_LINE; e++; lineLength = 0; } // end if: end of line } // en dfor: each piece of array if( d < len ) { encode3to4( source, d+off, len - d, outBuff, e, options ); e += 4; } // end if: some padding needed // Only resize array if we didn't guess it right. if( e <= outBuff.length - 1 ){ // If breaking lines and the last byte falls right at // the line length (76 bytes per line), there will be // one extra byte, and the array will need to be resized. // Not too bad of an estimate on array size, I'd say. byte[] finalOut = new byte[e]; System.arraycopy(outBuff,0, finalOut,0,e); //System.err.println("Having to resize array from " + outBuff.length + " to " + e ); return finalOut; } else { //System.err.println("No need to resize array."); return outBuff; } } // end else: don't compress }
#vulnerable code public static byte[] encodeBytesToBytes( byte[] source, int off, int len, int options ) throws java.io.IOException { if( source == null ){ throw new NullPointerException( "Cannot serialize a null array." ); } // end if: null if( off < 0 ){ throw new IllegalArgumentException( "Cannot have negative offset: " + off ); } // end if: off < 0 if( len < 0 ){ throw new IllegalArgumentException( "Cannot have length offset: " + len ); } // end if: len < 0 if( off + len > source.length ){ throw new IllegalArgumentException( String.format( "Cannot have offset of %d and length of %d with array of length %d", off,len,source.length)); } // end if: off < 0 // Compress? if( (options & GZIP) != 0 ) { java.io.ByteArrayOutputStream baos = null; java.util.zip.GZIPOutputStream gzos = null; Base64.OutputStream b64os = null; try { // GZip -> Base64 -> ByteArray baos = new java.io.ByteArrayOutputStream(); b64os = new Base64.OutputStream( baos, ENCODE | options ); gzos = new java.util.zip.GZIPOutputStream( b64os ); gzos.write( source, off, len ); gzos.close(); } // end try catch( java.io.IOException e ) { // Catch it and then throw it immediately so that // the finally{} block is called for cleanup. throw e; } // end catch finally { try{ gzos.close(); } catch( Exception e ){} try{ b64os.close(); } catch( Exception e ){} try{ baos.close(); } catch( Exception e ){} } // end finally return baos.toByteArray(); } // end if: compress // Else, don't compress. Better not to use streams at all then. else { boolean breakLines = (options & DO_BREAK_LINES) != 0; //int len43 = len * 4 / 3; //byte[] outBuff = new byte[ ( len43 ) // Main 4:3 // + ( (len % 3) > 0 ? 4 : 0 ) // Account for padding // + (breakLines ? ( len43 / MAX_LINE_LENGTH ) : 0) ]; // New lines // Try to determine more precisely how big the array needs to be. // If we get it right, we don't have to do an array copy, and // we save a bunch of memory. int encLen = ( len / 3 ) * 4 + ( len % 3 > 0 ? 4 : 0 ); // Bytes needed for actual encoding if( breakLines ){ encLen += encLen / MAX_LINE_LENGTH; // Plus extra newline characters } byte[] outBuff = new byte[ encLen ]; int d = 0; int e = 0; int len2 = len - 2; int lineLength = 0; for( ; d < len2; d+=3, e+=4 ) { encode3to4( source, d+off, 3, outBuff, e, options ); lineLength += 4; if( breakLines && lineLength >= MAX_LINE_LENGTH ) { outBuff[e+4] = NEW_LINE; e++; lineLength = 0; } // end if: end of line } // en dfor: each piece of array if( d < len ) { encode3to4( source, d+off, len - d, outBuff, e, options ); e += 4; } // end if: some padding needed // Only resize array if we didn't guess it right. if( e <= outBuff.length - 1 ){ // If breaking lines and the last byte falls right at // the line length (76 bytes per line), there will be // one extra byte, and the array will need to be resized. // Not too bad of an estimate on array size, I'd say. byte[] finalOut = new byte[e]; System.arraycopy(outBuff,0, finalOut,0,e); //System.err.println("Having to resize array from " + outBuff.length + " to " + e ); return finalOut; } else { //System.err.println("No need to resize array."); return outBuff; } } // end else: don't compress } #location 43 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public void init() { if (importVariables != null && importVariables.length > 0) { this.importTypes = new HashMap<String, Class<?>>(); for (String var : importVariables) { int i = var.lastIndexOf(' '); if (i < 0) { throw new IllegalArgumentException("Illegal config import.setVariables"); } this.importTypes.put(var.substring(i + 1), ClassUtils.forName(importPackages, var.substring(0, i))); } } }
#vulnerable code public void init() { if (importVariables != null && importVariables.length > 0) { this.importTypes = new HashMap<String, Class<?>>(); for (String var : importVariables) { int i = var.lastIndexOf(' '); if (i < 0) { throw new IllegalArgumentException("Illegal config import.setVariables"); } this.importTypes.put(var.substring(i + 1), ClassUtils.forName(importPackages, var.substring(0, i))); } } if (importMethods != null && importMethods.length > 0) { for (String method : importMethods) { Class<?> cls = ClassUtils.forName(importPackages, method); Object ins; try { ins = cls.newInstance(); } catch (Exception e) { ins = cls; } this.functions.put(cls, ins); } } } #location 17 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public InputStream getInputStream() throws IOException { // 注:JarFile与File的设计是不一样的,File相当于C#的FileInfo,只持有信息, // 而JarFile构造时即打开流,所以每次读取数据时,重新new新的实例,而不作为属性字段持有。 JarFile jarFile = new JarFile(file); return jarFile.getInputStream(jarFile.getEntry(getName())); }
#vulnerable code public InputStream getInputStream() throws IOException { // 注:JarFile与File的设计是不一样的,File相当于C#的FileInfo,只持有信息, // 而JarFile构造时即打开流,所以每次读取数据时,重新new新的实例,而不作为属性字段持有。 JarFile zipFile = new JarFile(file); return zipFile.getInputStream(zipFile.getEntry(getName())); } #location 5 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Test public void testNoProcessorWroManagerFactory() throws IOException { final WroManagerFactory factory = new ServletContextAwareWroManagerFactory(); manager = factory.getInstance(); manager.setModelFactory(getValidModelFactory()); final HttpServletRequest request = Mockito.mock(HttpServletRequest.class); final HttpServletResponse response = Context.get().getResponse(); final ByteArrayOutputStream out = new ByteArrayOutputStream(); Mockito.when(response.getOutputStream()).thenReturn(new DelegatingServletOutputStream(out)); Mockito.when(request.getRequestURI()).thenReturn("/app/g1.css"); manager.process(request, response); //compare written bytes to output stream with the content from specified css. WroTestUtils.compare(getInputStream("classpath:ro/isdc/wro/manager/noProcessorsResult.css"), new ByteArrayInputStream(out.toByteArray())); }
#vulnerable code @Test public void testNoProcessorWroManagerFactory() throws IOException { final WroManagerFactory factory = new ServletContextAwareWroManagerFactory(); manager = factory.getInstance(); manager.setModelFactory(getValidModelFactory()); final HttpServletRequest request = Mockito.mock(HttpServletRequest.class); final OutputStream os = System.out; final HttpServletResponse response = Context.get().getResponse(); final InputStream actualStream = WroTestUtils.convertToInputStream(os); Mockito.when(response.getOutputStream()).thenReturn(new DelegatingServletOutputStream(os)); Mockito.when(request.getRequestURI()).thenReturn("/app/g1.css"); manager.process(request, response); WroTestUtils.compare(getInputStream("classpath:ro/isdc/wro/manager/noProcessorsResult.css"), actualStream); } #location 11 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public void process(final Resource resource, final Reader reader, final Writer writer) throws IOException { try { // using ReaderInputStream instead of ByteArrayInputStream, cause processing to freeze final String encoding = Context.get().getConfig().getEncoding(); final InputStream is = new BomStripperInputStream(new ByteArrayInputStream(IOUtils.toByteArray(reader, encoding))); IOUtils.copy(is, writer, encoding); } finally { reader.close(); writer.close(); } }
#vulnerable code public void process(final Resource resource, final Reader reader, final Writer writer) throws IOException { try { System.out.println("BOM:"); // using ReaderInputStream instead of ByteArrayInputStream, cause processing to freeze final InputStream is = new BomStripperInputStream(new ByteArrayInputStream(IOUtils.toByteArray(reader))); IOUtils.copy(is, writer, Context.get().getConfig().getEncoding()); System.out.println("END BOM"); } finally { reader.close(); writer.close(); } } #location 10 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.