input
stringlengths
205
73.3k
output
stringlengths
64
73.2k
instruction
stringclasses
1 value
#vulnerable code public List<Pair<String, Integer>> getColumns(String schema, String table) throws SQLException { if (!columnsCache.isEmpty()){ return columnsCache; } DbmsQueryResult queryResult = connection.executeQuery(syntax.getColumnsCommand(schema, table)); JdbcResultSet jdbcQueryResult = new JdbcResultSet(queryResult); while (queryResult.next()) { String type = jdbcQueryResult.getString(syntax.getColumnTypeColumnIndex()); // remove the size of type type = type.replaceAll("\\(.*\\)", ""); columnsCache.add(new ImmutablePair<>(jdbcQueryResult.getString(syntax.getColumnNameColumnIndex()), DataTypeConverter.typeInt(type))); } return columnsCache; } #location 3 #vulnerability type RESOURCE_LEAK
#fixed code public List<Pair<String, Integer>> getColumns(String schema, String table) throws SQLException { if (!columnsCache.isEmpty()){ return columnsCache; } columnsCache.addAll(connection.getColumns(schema, table)); return columnsCache; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code void print(int indentSpace) { StringBuilder builder = new StringBuilder(); for (int i = 0; i < indentSpace; i++) { builder.append(" "); } builder.append(this.toString()); System.out.println(builder.toString()); for (QueryExecutionNode dep : dependents) { dep.print(indentSpace + 2); } } #location 6 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code void addParent(QueryExecutionNode parent) { parents.add(parent); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public List<String> getTables(String schema) throws SQLException { if (!tablesCache.isEmpty()){ return tablesCache; } DbmsQueryResult queryResult = connection.executeQuery(syntax.getTableCommand(schema)); JdbcResultSet jdbcQueryResult = new JdbcResultSet(queryResult); while (queryResult.next()) { tablesCache.add(jdbcQueryResult.getString(syntax.getTableNameColumnIndex())); } return tablesCache; } #location 3 #vulnerability type RESOURCE_LEAK
#fixed code public List<String> getTables(String schema) throws SQLException { if (!tablesCache.isEmpty()){ return tablesCache; } tablesCache.addAll(connection.getTables(schema)); return tablesCache; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Override public List<String> getPartitionColumns(String schema, String table) throws VerdictDBDbmsException { List<String> partition = new ArrayList<>(); DbmsQueryResult queryResult = execute(syntax.getPartitionCommand(schema, table)); JdbcResultSet jdbcResultSet = new JdbcResultSet(queryResult); // the result of postgresql is a vector of column index try { if (syntax instanceof PostgresqlSyntax) { queryResult.next(); Object o = jdbcResultSet.getObject(1); String[] arr = o.toString().split(" "); List<Pair<String, String>> columns = getColumns(schema, table); for (int i=0; i<arr.length; i++) { partition.add(columns.get(Integer.valueOf(arr[i])-1).getKey()); } } else { while (queryResult.next()) { partition.add(jdbcResultSet.getString(1)); } } } catch (SQLException e) { throw new VerdictDBDbmsException(e); } finally { jdbcResultSet.close(); } jdbcResultSet.close(); return partition; } #location 5 #vulnerability type NULL_DEREFERENCE
#fixed code @Override public List<String> getPartitionColumns(String schema, String table) throws VerdictDBDbmsException { List<String> partition = new ArrayList<>(); DbmsQueryResult queryResult = execute(syntax.getPartitionCommand(schema, table)); while (queryResult.next()) { partition.add((String) queryResult.getValue(0)); } return partition; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void testConvertFlatToProgressiveAgg() throws VerdictDBValueException { SelectQuery aggQuery = SelectQuery.create( ColumnOp.count(), new BaseTable("myschema", "mytable", "t")); AggExecutionNode aggnode = AggExecutionNode.create(aggQuery, "myschema"); AggExecutionNodeBlock block = new AggExecutionNodeBlock(aggnode); ScrambleMeta scrambleMeta = generateTestScrambleMeta(); QueryExecutionNode converted = block.convertToProgressiveAgg(scrambleMeta); converted.print(); } #location 10 #vulnerability type NULL_DEREFERENCE
#fixed code @Test public void testConvertFlatToProgressiveAgg() throws VerdictDBValueException { SelectQuery aggQuery = SelectQuery.create( new AliasedColumn(ColumnOp.count(), "agg"), new BaseTable(newSchema, newTable, "t")); AggExecutionNode aggnode = AggExecutionNode.create(aggQuery, newSchema); AggExecutionNodeBlock block = new AggExecutionNodeBlock(aggnode); QueryExecutionNode converted = block.convertToProgressiveAgg(newSchema, scrambleMeta); converted.print(); converted.execute(new JdbcConnection(conn, new H2Syntax())); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Override public ExactRelation rewriteWithSubsampledErrorBounds() { // if this is not an approximate relation effectively, we don't need any special rewriting. if (!doesIncludeSample()) { return getOriginalRelation(); } ExactRelation r = rewriteWithPartition(true); // String newAlias = genTableAlias(); // put another layer to combine per-partition aggregates List<SelectElem> newElems = new ArrayList<SelectElem>(); List<SelectElem> oldElems = ((AggregatedRelation) r).getElemList(); List<Expr> newGroupby = new ArrayList<Expr>(); for (int i = 0; i < oldElems.size(); i++) { SelectElem elem = oldElems.get(i); // used to identify the original aggregation type Optional<SelectElem> originalElem = Optional.absent(); if (i < this.elems.size()) { originalElem = Optional.fromNullable(this.elems.get(i)); } if (!elem.isagg()) { // skip the partition number if (elem.aliasPresent() && elem.getAlias().equals(partitionColumnName())) { continue; } SelectElem newElem = null; Expr newExpr = null; if (elem.getAlias() == null) { newExpr = elem.getExpr().withTableSubstituted(r.getAlias()); newElem = new SelectElem(vc, newExpr, elem.getAlias()); } else { newExpr = new ColNameExpr(vc, elem.getAlias(), r.getAlias()); newElem = new SelectElem(vc, newExpr, elem.getAlias()); } // groupby element may not be present in the select list. if (originalElem.isPresent()) { newElems.add(newElem); } newGroupby.add(newExpr); } else { // skip the partition size column if (elem.getAlias().equals(partitionSizeAlias)) { continue; } // skip the extra columns inserted if (!originalElem.isPresent()) { continue; } ColNameExpr est = new ColNameExpr(vc, elem.getAlias(), r.getAlias()); ColNameExpr psize = new ColNameExpr(vc, partitionSizeAlias, r.getAlias()); // average estimate Expr averaged = null; Expr originalExpr = originalElem.get().getExpr(); if (originalExpr.isCountDistinct()) { // for count-distinct (i.e., universe samples), weighted average should not be used. averaged = FuncExpr.round(FuncExpr.avg(est)); } else if (originalExpr.isMax()) { averaged = FuncExpr.max(est); } else if (originalExpr.isMin()) { averaged = FuncExpr.min(est); } else { // weighted average averaged = BinaryOpExpr.from(vc, FuncExpr.sum(BinaryOpExpr.from(vc, est, psize, "*")), FuncExpr.sum(psize), "/"); if (originalElem.get().getExpr().isCount()) { averaged = FuncExpr.round(averaged); } } newElems.add(new SelectElem(vc, averaged, elem.getAlias())); // error estimation // scale by sqrt(subsample size) / sqrt(sample size) if (originalExpr.isMax() || originalExpr.isMin()) { // no error estimations for extreme statistics } else { Expr error = BinaryOpExpr.from(vc, BinaryOpExpr.from(vc, FuncExpr.stddev(est), FuncExpr.sqrt(FuncExpr.avg(psize)), "*"), FuncExpr.sqrt(FuncExpr.sum(psize)), "/"); error = BinaryOpExpr.from(vc, error, ConstantExpr.from(vc, confidenceIntervalMultiplier()), "*"); newElems.add(new SelectElem(vc, error, Relation.errorBoundColumn(elem.getAlias()))); } } } // this extra aggregation stage should be grouped by non-agg elements except for __vpart // List<Expr> newGroupby = new ArrayList<Expr>(); // if (source instanceof ApproxGroupedRelation) { // for (Expr g : ((ApproxGroupedRelation) source).getGroupby()) { // if (g instanceof ColNameExpr && ((ColNameExpr) g).getCol().equals(partitionColumnName())) { // continue; // } else { // newGroupby.add(g.withTableSubstituted(r.getAlias())); // } // } // } for (SelectElem elem : elems) { if (!elem.isagg()) { if (elem.aliasPresent()) { if (!elem.getAlias().equals(partitionColumnName())) { newGroupby.add(new ColNameExpr(vc, elem.getAlias(), r.getAlias())); } } else { if (!elem.getExpr().toString().equals(partitionColumnName())) { newGroupby.add(elem.getExpr().withTableSubstituted(r.getAlias())); } } } } if (newGroupby.size() > 0) { r = new GroupedRelation(vc, r, newGroupby); } r = new AggregatedRelation(vc, r, newElems); r.setAlias(getAlias()); return r; } #location 112 #vulnerability type NULL_DEREFERENCE
#fixed code @Override public ExactRelation rewriteWithSubsampledErrorBounds() { // if this is not an approximate relation effectively, we don't need any special rewriting. if (!doesIncludeSample()) { return getOriginalRelation(); } ExactRelation r = rewriteWithPartition(true); // String newAlias = genTableAlias(); // put another layer to combine per-partition aggregates List<SelectElem> newElems = new ArrayList<SelectElem>(); List<SelectElem> oldElems = ((AggregatedRelation) r).getElemList(); List<Expr> newGroupby = new ArrayList<Expr>(); for (int i = 0; i < oldElems.size(); i++) { SelectElem elem = oldElems.get(i); // used to identify the original aggregation type Optional<SelectElem> originalElem = Optional.absent(); if (i < this.elems.size()) { originalElem = Optional.fromNullable(this.elems.get(i)); } if (!elem.isagg()) { // skip the partition number if (elem.aliasPresent() && elem.getAlias().equals(partitionColumnName())) { continue; } SelectElem newElem = null; Expr newExpr = null; if (elem.getAlias() == null) { newExpr = elem.getExpr().withTableSubstituted(r.getAlias()); newElem = new SelectElem(vc, newExpr, elem.getAlias()); } else { newExpr = new ColNameExpr(vc, elem.getAlias(), r.getAlias()); newElem = new SelectElem(vc, newExpr, elem.getAlias()); } // groupby element may not be present in the select list. if (originalElem.isPresent()) { newElems.add(newElem); } newGroupby.add(newExpr); } else { // skip the partition size column if (elem.getAlias().equals(partitionSizeAlias)) { continue; } // skip the extra columns inserted if (!originalElem.isPresent()) { continue; } ColNameExpr est = new ColNameExpr(vc, elem.getAlias(), r.getAlias()); ColNameExpr psize = new ColNameExpr(vc, partitionSizeAlias, r.getAlias()); // average estimate Expr averaged = null; Expr originalExpr = originalElem.get().getExpr(); if (originalExpr.isCountDistinct()) { // for count-distinct (i.e., universe samples), weighted average should not be used. averaged = FuncExpr.round(FuncExpr.avg(est)); } else if (originalExpr.isMax()) { averaged = FuncExpr.max(est); } else if (originalExpr.isMin()) { averaged = FuncExpr.min(est); } else { // weighted average averaged = BinaryOpExpr.from(vc, FuncExpr.sum(BinaryOpExpr.from(vc, est, psize, "*")), FuncExpr.sum(psize), "/"); if (originalElem.get().getExpr().isCount()) { averaged = FuncExpr.round(averaged); } } newElems.add(new SelectElem(vc, averaged, elem.getAlias())); // error estimation // scale by sqrt(subsample size) / sqrt(sample size) if (originalExpr.isMax() || originalExpr.isMin()) { // no error estimations for extreme statistics } else { Expr error = BinaryOpExpr.from(vc, BinaryOpExpr.from(vc, FuncExpr.stddev(est), FuncExpr.sqrt(FuncExpr.avg(psize)), "*"), FuncExpr.sqrt(FuncExpr.sum(psize)), "/"); error = BinaryOpExpr.from(vc, error, ConstantExpr.from(vc, confidenceIntervalMultiplier()), "*"); newElems.add(new SelectElem(vc, error, Relation.errorBoundColumn(elem.getAlias()))); } } } // this extra aggregation stage should be grouped by non-agg elements except for __vpart // List<Expr> newGroupby = new ArrayList<Expr>(); // if (source instanceof ApproxGroupedRelation) { // for (Expr g : ((ApproxGroupedRelation) source).getGroupby()) { // if (g instanceof ColNameExpr && ((ColNameExpr) g).getCol().equals(partitionColumnName())) { // continue; // } else { // newGroupby.add(g.withTableSubstituted(r.getAlias())); // } // } // } // for (SelectElem elem : elems) { // if (!elem.isagg()) { // if (elem.aliasPresent()) { // if (!elem.getAlias().equals(partitionColumnName())) { // newGroupby.add(new ColNameExpr(vc, elem.getAlias(), r.getAlias())); // } // } else { // does not happen // if (!elem.getExpr().toString().equals(partitionColumnName())) { // newGroupby.add(elem.getExpr().withTableSubstituted(r.getAlias())); // } // } // } // } if (newGroupby.size() > 0) { r = new GroupedRelation(vc, r, newGroupby); } r = new AggregatedRelation(vc, r, newElems); r.setAlias(getAlias()); return r; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Override public List<String> getTables(String schema) throws VerdictDBDbmsException { List<String> tables = new ArrayList<>(); DbmsQueryResult queryResult = execute(syntax.getTableCommand(schema)); JdbcResultSet jdbcResultSet = new JdbcResultSet(queryResult); try { while (queryResult.next()) { tables.add(jdbcResultSet.getString(syntax.getTableNameColumnIndex()+1)); } } catch (SQLException e) { throw new VerdictDBDbmsException(e); } finally { jdbcResultSet.close(); } return tables; } #location 5 #vulnerability type NULL_DEREFERENCE
#fixed code @Override public List<String> getTables(String schema) throws VerdictDBDbmsException { List<String> tables = new ArrayList<>(); DbmsQueryResult queryResult = execute(syntax.getTableCommand(schema)); while (queryResult.next()) { tables.add((String) queryResult.getValue(syntax.getTableNameColumnIndex())); } return tables; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public List<Pair<String, Integer>> getColumns(String schema, String table) throws SQLException { if (!columnsCache.isEmpty()){ return columnsCache; } DbmsQueryResult queryResult = connection.executeQuery(syntax.getColumnsCommand(schema, table)); JdbcResultSet jdbcQueryResult = new JdbcResultSet(queryResult); while (queryResult.next()) { String type = jdbcQueryResult.getString(syntax.getColumnTypeColumnIndex()); // remove the size of type type = type.replaceAll("\\(.*\\)", ""); columnsCache.add(new ImmutablePair<>(jdbcQueryResult.getString(syntax.getColumnNameColumnIndex()), DataTypeConverter.typeInt(type))); } return columnsCache; } #location 3 #vulnerability type RESOURCE_LEAK
#fixed code public List<Pair<String, Integer>> getColumns(String schema, String table) throws SQLException { if (!columnsCache.isEmpty()){ return columnsCache; } columnsCache.addAll(connection.getColumns(schema, table)); return columnsCache; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void testExecuteNode() throws VerdictDBException { BaseTable base = new BaseTable(originalSchema, originalTable, "t"); SelectQuery query = SelectQuery.create(Arrays.<SelectItem>asList(new AsteriskColumn()), base); QueryExecutionNode root = CreateTableAsSelectExecutionNode.create(query, "newschema"); // LinkedBlockingDeque<ExecutionResult> resultQueue = new LinkedBlockingDeque<>(); root.executeNode(conn, null); // no information to pass conn.executeUpdate(String.format("DROP TABLE \"%s\".\"%s\"", newSchema, "verdictdbtemptable_0")); } #location 7 #vulnerability type NULL_DEREFERENCE
#fixed code @Test public void testExecuteNode() throws VerdictDBException { BaseTable base = new BaseTable(originalSchema, originalTable, "t"); SelectQuery query = SelectQuery.create(Arrays.<SelectItem>asList(new AsteriskColumn()), base); QueryExecutionNode root = CreateTableAsSelectExecutionNode.create(query, "newschema"); // ExecutionInfoToken token = new ExecutionInfoToken(); ExecutionInfoToken newTableName = root.executeNode(conn, Arrays.<ExecutionInfoToken>asList()); // no information to pass String schemaName = (String) newTableName.getValue("schemaName"); String tableName = (String) newTableName.getValue("tableName"); conn.executeUpdate(String.format("DROP TABLE \"%s\".\"%s\"", schemaName, tableName)); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public List<String> getTables(String schema) throws SQLException { if (!tablesCache.isEmpty()){ return tablesCache; } DbmsQueryResult queryResult = connection.executeQuery(syntax.getTableCommand(schema)); JdbcResultSet jdbcQueryResult = new JdbcResultSet(queryResult); while (queryResult.next()) { tablesCache.add(jdbcQueryResult.getString(syntax.getTableNameColumnIndex())); } return tablesCache; } #location 3 #vulnerability type RESOURCE_LEAK
#fixed code public List<String> getTables(String schema) throws SQLException { if (!tablesCache.isEmpty()){ return tablesCache; } tablesCache.addAll(connection.getTables(schema)); return tablesCache; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Override protected Map<TableUniqueName, String> tableSubstitution() { return ImmutableMap.of(); } #location 2 #vulnerability type CHECKERS_IMMUTABLE_CAST
#fixed code @Override protected Map<TableUniqueName, String> tableSubstitution() { return source.tableSubstitution(); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Override public List<String> getSchemas() throws VerdictDBDbmsException { List<String> schemas = new ArrayList<>(); DbmsQueryResult queryResult = execute(syntax.getSchemaCommand()); JdbcResultSet jdbcResultSet = new JdbcResultSet(queryResult); try { while (queryResult.next()) { schemas.add(jdbcResultSet.getString(syntax.getSchemaNameColumnIndex()+1)); } } catch (SQLException e) { throw new VerdictDBDbmsException(e); } finally { jdbcResultSet.close(); } return schemas; } #location 5 #vulnerability type NULL_DEREFERENCE
#fixed code @Override public List<String> getSchemas() throws VerdictDBDbmsException { List<String> schemas = new ArrayList<>(); DbmsQueryResult queryResult = execute(syntax.getSchemaCommand()); while (queryResult.next()) { schemas.add((String) queryResult.getValue(syntax.getSchemaNameColumnIndex())); } return schemas; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public List<String> getPartitionColumns(String schema, String table) throws SQLException { if (!syntax.doesSupportTablePartitioning()) { throw new SQLException("Database does not support table partitioning"); } if (!partitionCache.isEmpty()){ return partitionCache; } DbmsQueryResult queryResult = connection.executeQuery(syntax.getPartitionCommand(schema, table)); JdbcResultSet jdbcQueryResult = new JdbcResultSet(queryResult); while (queryResult.next()) { partitionCache.add(jdbcQueryResult.getString(0)); } return partitionCache; } #location 6 #vulnerability type RESOURCE_LEAK
#fixed code public List<String> getPartitionColumns(String schema, String table) throws SQLException { if (!syntax.doesSupportTablePartitioning()) { throw new SQLException("Database does not support table partitioning"); } if (!partitionCache.isEmpty()){ return partitionCache; } partitionCache.addAll(getPartitionColumns(schema, table)); return partitionCache; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public List<String> getSchemas() throws SQLException { if (!schemaCache.isEmpty()){ return schemaCache; } DbmsQueryResult queryResult = connection.executeQuery(syntax.getSchemaCommand()); JdbcResultSet jdbcQueryResult = new JdbcResultSet(queryResult); while (queryResult.next()) { schemaCache.add(jdbcQueryResult.getString(syntax.getSchemaNameColumnIndex())); } return schemaCache; } #location 3 #vulnerability type RESOURCE_LEAK
#fixed code public List<String> getSchemas() throws SQLException { if (!schemaCache.isEmpty()){ return schemaCache; } schemaCache.addAll(connection.getSchemas()); return schemaCache; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void testSingleAggCombiningWithH2() throws VerdictDBDbmsException, VerdictDBException { QueryExecutionPlan plan = new QueryExecutionPlan("newschema"); BaseTable base = new BaseTable(originalSchema, originalTable, "t"); SelectQuery leftQuery = SelectQuery.create(new AliasedColumn(ColumnOp.count(), "mycount"), base); leftQuery.addFilterByAnd(ColumnOp.lessequal(new BaseColumn("t", "value"), ConstantColumn.valueOf(5.0))); SelectQuery rightQuery = SelectQuery.create(new AliasedColumn(ColumnOp.count(), "mycount"), base); rightQuery.addFilterByAnd(ColumnOp.greater(new BaseColumn("t", "value"), ConstantColumn.valueOf(5.0))); AggExecutionNode leftNode = AggExecutionNode.create(plan, leftQuery); AggExecutionNode rightNode = AggExecutionNode.create(plan, rightQuery); // ExecutionTokenQueue queue = new ExecutionTokenQueue(); AggCombinerExecutionNode combiner = AggCombinerExecutionNode.create(plan, leftNode, rightNode); combiner.print(); ExecutionTokenReader reader = ExecutablePlanRunner.getTokenReader( conn, new SimpleTreePlan(combiner)); // combiner.addBroadcastingQueue(queue); // combiner.executeAndWaitForTermination(conn); ExecutionInfoToken token = reader.next(); String schemaName = (String) token.getValue("schemaName"); String tableName = (String) token.getValue("tableName"); conn.execute(QueryToSql.convert( new H2Syntax(), SelectQuery.create(ColumnOp.count(), base))); DbmsQueryResult result = conn.getResult(); result.next(); int expectedCount = Integer.valueOf(result.getValue(0).toString()); conn.execute(QueryToSql.convert( new H2Syntax(), SelectQuery.create(new AsteriskColumn(), new BaseTable(schemaName, tableName, "t")))); DbmsQueryResult result2 = conn.getResult(); result2.next(); int actualCount = Integer.valueOf(result2.getValue(0).toString()); assertEquals(expectedCount, actualCount); conn.execute(QueryToSql.convert( new H2Syntax(), DropTableQuery.create(schemaName, tableName))); } #location 25 #vulnerability type NULL_DEREFERENCE
#fixed code @Test public void testSingleAggCombiningWithH2() throws VerdictDBDbmsException, VerdictDBException { QueryExecutionPlan plan = new QueryExecutionPlan("newschema"); BaseTable base = new BaseTable(originalSchema, originalTable, "t"); SelectQuery leftQuery = SelectQuery.create(new AliasedColumn(ColumnOp.count(), "mycount"), base); leftQuery.addFilterByAnd(ColumnOp.lessequal(new BaseColumn("t", "value"), ConstantColumn.valueOf(5.0))); SelectQuery rightQuery = SelectQuery.create(new AliasedColumn(ColumnOp.count(), "mycount"), base); rightQuery.addFilterByAnd(ColumnOp.greater(new BaseColumn("t", "value"), ConstantColumn.valueOf(5.0))); AggExecutionNode leftNode = AggExecutionNode.create(plan, leftQuery); AggExecutionNode rightNode = AggExecutionNode.create(plan, rightQuery); // ExecutionTokenQueue queue = new ExecutionTokenQueue(); AggCombinerExecutionNode combiner = AggCombinerExecutionNode.create(plan, leftNode, rightNode); combiner.print(); ExecutionTokenReader reader = ExecutablePlanRunner.getTokenReader( conn, new SimpleTreePlan(combiner)); // combiner.addBroadcastingQueue(queue); // combiner.executeAndWaitForTermination(conn); ExecutionInfoToken token = reader.next(); String schemaName = (String) token.getValue("schemaName"); String tableName = (String) token.getValue("tableName"); DbmsQueryResult result = conn.execute(QueryToSql.convert( new H2Syntax(), SelectQuery.create(ColumnOp.count(), base))); result.next(); int expectedCount = Integer.valueOf(result.getValue(0).toString()); DbmsQueryResult result2 = conn.execute(QueryToSql.convert( new H2Syntax(), SelectQuery.create(new AsteriskColumn(), new BaseTable(schemaName, tableName, "t")))); result2.next(); int actualCount = Integer.valueOf(result2.getValue(0).toString()); assertEquals(expectedCount, actualCount); conn.execute(QueryToSql.convert( new H2Syntax(), DropTableQuery.create(schemaName, tableName))); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Override public String visitSelect_list_elem(VerdictSQLParser.Select_list_elemContext ctx) { select_list_elem_num++; String newSelectListElem = null; Pair<String, Alias> colName2Alias = null; if (ctx.getText().equals("*")) { // TODO: replace * with all columns in the (joined) source table. newSelectListElem = "*"; } else { StringBuilder elem = new StringBuilder(); elem.append(visit(ctx.expression())); SelectStatementBaseRewriter baseRewriter = new SelectStatementBaseRewriter(queryString); String colName = baseRewriter.visit(ctx.expression()); if (ctx.column_alias() != null) { Alias alias = new Alias(colName, ctx.column_alias().getText()); elem.append(String.format(" AS %s", alias)); colName2Alias = Pair.of(colName, alias); } else { // We add a pseudo column alias Alias alias = Alias.genAlias(depth, colName); elem.append(String.format(" AS %s", alias)); colName2Alias = Pair.of(baseRewriter.visit(ctx.expression()), alias); } newSelectListElem = elem.toString(); } colName2Aliases.add(Pair.of(colName2Alias.getKey(), colName2Alias.getValue())); return newSelectListElem; } #location 31 #vulnerability type NULL_DEREFERENCE
#fixed code @Override public String visitSelect_list_elem(VerdictSQLParser.Select_list_elemContext ctx) { select_list_elem_num++; String newSelectListElem = null; Pair<String, Alias> colName2Alias = null; if (ctx.getText().equals("*")) { // TODO: replace * with all columns in the (joined) source table. newSelectListElem = "*"; } else { StringBuilder elem = new StringBuilder(); // We use a baseRewriter to prevent that "COUNT(*)" is rewritten to "COUNT(*) * (1/sample_ratio)" SelectStatementBaseRewriter baseRewriter = new SelectStatementBaseRewriter(queryString); String tabColName = baseRewriter.visit(ctx.expression()); String tabName = NameHelpers.tabNameOfColName(tabColName); TableUniqueName tabUniqueName = NameHelpers.tabUniqueNameOfColName(vc, tabColName); String colName = NameHelpers.colNameOfColName(tabColName); // if a table name is specified, we change it to its alias name. if (tableAliases.containsKey(tabUniqueName)) { tabName = tableAliases.get(tabUniqueName).toString(); } // if there was derived table(s), we may need to substitute aliased name for the colName. for (Map.Entry<String, Map<String, Alias>> e : derivedTableColName2Aliases.entrySet()) { String derivedTabName = e.getKey(); if (tabName.length() > 0 && !tabName.equals(derivedTabName)) { // this is the case where there are more than one derived tables, and a user specifically referencing // a column in one of those derived tables. continue; } if (e.getValue().containsKey(colName)) { Alias alias = e.getValue().get(colName); if (alias.autoGenerated()) { colName = alias.toString(); } } } if (tabName.length() > 0) { elem.append(String.format("%s.%s", tabName, colName)); } else { elem.append(colName); } if (ctx.column_alias() != null) { Alias alias = new Alias(colName, ctx.column_alias().getText()); elem.append(String.format(" AS %s", alias)); colName2Alias = Pair.of(colName, alias); } else { // We add a pseudo column alias Alias alias = Alias.genAlias(depth, colName); elem.append(String.format(" AS %s", alias)); colName2Alias = Pair.of(baseRewriter.visit(ctx.expression()), alias); } newSelectListElem = elem.toString(); } colName2Aliases.add(Pair.of(colName2Alias.getKey(), colName2Alias.getValue())); return newSelectListElem; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public static void main(String[] a) throws Exception { PropertyConfigurator.configure(FoxCfg.LOG_FILE); String in = "University of Leipzig in Leipzig.."; String query = "select * from search.termextract where context="; URIBuilder builder = new URIBuilder(); builder.setScheme("http").setHost("query.yahooapis.com").setPath("/v1/public/yql").setParameter("diagnostics", "false").setParameter("q", query + "'" + in + "'"); HttpGet httpget = new HttpGet(builder.build()); System.out.println(httpget.getURI()); HttpClient httpclient = new DefaultHttpClient(); HttpResponse response = httpclient.execute(httpget); HttpEntity entity = response.getEntity(); if (entity != null) { InputStream instream = entity.getContent(); try { String myString = IOUtils.toString(instream, "UTF-8"); System.out.println(myString); } finally { instream.close(); } } } #location 14 #vulnerability type RESOURCE_LEAK
#fixed code public static void main(String[] a) throws Exception { PropertyConfigurator.configure(FoxCfg.LOG_FILE); String in = "University of Leipzig in Leipzig.."; String query = "select * from search.termextract where context="; URIBuilder builder = new URIBuilder(); builder.setScheme("http").setHost("query.yahooapis.com").setPath("/v1/public/yql").setParameter("diagnostics", "false").setParameter("q", query + "'" + in + "'"); HttpGet httpget = new HttpGet(builder.build()); System.out.println(httpget.getURI()); HttpClient httpclient = HttpClientBuilder.create().build(); HttpResponse response = httpclient.execute(httpget); HttpEntity entity = response.getEntity(); if (entity != null) { InputStream instream = entity.getContent(); try { String myString = IOUtils.toString(instream, "UTF-8"); System.out.println(myString); } finally { instream.close(); } } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Override public Swagger read(Set<Class<?>> classes) throws GenerateException { //relate all methods to one base request mapping if multiple controllers exist for that mapping //get all methods from each controller & find their request mapping //create map - resource string (after first slash) as key, new SpringResource as value Map<String, SpringResource> resourceMap = generateResourceMap(classes); for (String str : resourceMap.keySet()) { SpringResource resource = resourceMap.get(str); swagger = read(resource); } return swagger; } #location 9 #vulnerability type NULL_DEREFERENCE
#fixed code @Override public Swagger read(Set<Class<?>> classes) throws GenerateException { //relate all methods to one base request mapping if multiple controllers exist for that mapping //get all methods from each controller & find their request mapping //create map - resource string (after first slash) as key, new SpringResource as value Map<String, SpringResource> resourceMap = generateResourceMap(classes); for (String str : resourceMap.keySet()) { SpringResource resource = resourceMap.get(str); read(resource); } return swagger; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code protected List<Parameter> getParameters(Type type, List<Annotation> annotations) { // look for path, query Iterator<SwaggerExtension> chain = SwaggerExtensions.chain(); List<Parameter> parameters = null; LOG.info("getParameters for " + type.getClass().getName()); Set<Type> typesToSkip = new HashSet<Type>(); if (chain.hasNext()) { SwaggerExtension extension = chain.next(); LOG.info("trying extension " + extension); parameters = extension.extractParameters(annotations, type, typesToSkip, chain); } if (parameters.size() > 0) { for (Parameter parameter : parameters) { ParameterProcessor.applyAnnotations(swagger, parameter, type, annotations); } } else { LOG.info("no parameter found, looking at body params"); if (typesToSkip.contains(type) == false) { Parameter param = null; param = ParameterProcessor.applyAnnotations(swagger, null, type, annotations); if (param != null) { for (Annotation annotation : annotations) { if (annotation instanceof ApiParam) { ApiParam apiParam = (ApiParam) annotation; param.setRequired(apiParam.required()); break; } } parameters.add(param); } } } return parameters; } #location 14 #vulnerability type NULL_DEREFERENCE
#fixed code protected List<Parameter> getParameters(Type type, List<Annotation> annotations) { Iterator<SwaggerExtension> chain = SwaggerExtensions.chain(); List<Parameter> parameters = new ArrayList<Parameter>(); LOG.info("Looking for path/query/header/form/cookie params in" + type.getClass().getName()); Set<Type> typesToSkip = new HashSet<Type>(); if (chain.hasNext()) { SwaggerExtension extension = chain.next(); LOG.info("trying extension " + extension); parameters = extension.extractParameters(annotations, type, typesToSkip, chain); } if (parameters.size() > 0) { for (Parameter parameter : parameters) { ParameterProcessor.applyAnnotations(swagger, parameter, type, annotations); } } else { // look for body parameters LOG.info("Looking for body params in" + type.getClass().getName()); if (typesToSkip.contains(type) == false) { Parameter param = ParameterProcessor.applyAnnotations(swagger, null, type, annotations); if (param != null) { parameters.add(param); } } } return parameters; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public void toDocuments() throws GenerateException { if (outputTemplate == null) { prepareMustacheTemplate(); } if (outputTemplate.getApiDocuments().isEmpty()) { LOG.warn("nothing to write."); return; } LOG.info("Writing doc to " + outputPath + "..."); FileOutputStream fileOutputStream = null; try { fileOutputStream = new FileOutputStream(outputPath); } catch (FileNotFoundException e) { throw new GenerateException(e); } OutputStreamWriter writer = new OutputStreamWriter(fileOutputStream, Charset.forName("UTF-8")); try { URL url = getTemplateUri().toURL(); InputStreamReader reader = new InputStreamReader(url.openStream(), Charset.forName("UTF-8")); Mustache mustache = getMustacheFactory().compile(reader, templatePath); mustache.execute(writer, outputTemplate).flush(); writer.close(); LOG.info("Done!"); } catch (MalformedURLException e) { throw new GenerateException(e); } catch (IOException e) { throw new GenerateException(e); } } #location 27 #vulnerability type RESOURCE_LEAK
#fixed code public void toDocuments() throws GenerateException { if (outputTemplate == null) { prepareMustacheTemplate(); } if (outputTemplate.getApiDocuments().isEmpty()) { LOG.warn("nothing to write."); return; } LOG.info("Writing doc to " + outputPath + "..."); FileOutputStream fileOutputStream = null; try { fileOutputStream = new FileOutputStream(outputPath); } catch (FileNotFoundException e) { throw new GenerateException(e); } OutputStreamWriter writer = new OutputStreamWriter(fileOutputStream, Charset.forName("UTF-8")); MustacheFactory mf = new DefaultMustacheFactory(); URI uri = null; try { uri = new URI(templatePath); } catch (URISyntaxException e) { throw new GenerateException(e); } if (!uri.isAbsolute()) { File file = new File(templatePath); if (!file.exists()) { throw new GenerateException("Template " + file.getAbsoluteFile() + " not found. You can go to https://github.com/kongchen/api-doc-template to get templates."); } else { uri = new File(templatePath).toURI(); } } URL url = null; try { url = uri.toURL(); InputStreamReader reader = new InputStreamReader(url.openStream(), Charset.forName("UTF-8")); Mustache mustache = mf.compile(reader, templatePath); mustache.execute(writer, outputTemplate).flush(); writer.close(); LOG.info("Done!"); } catch (MalformedURLException e) { throw new GenerateException(e); } catch (IOException e) { throw new GenerateException(e); } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public Swagger read(SpringResource resource) { if (swagger == null) { swagger = new Swagger(); } List<Method> methods = resource.getMethods(); Map<String, Tag> tags = new HashMap<String, Tag>(); List<SecurityRequirement> resourceSecurities = new ArrayList<SecurityRequirement>(); // Add the description from the controller api Class<?> controller = resource.getControllerClass(); RequestMapping apiPath = controller.getAnnotation(RequestMapping.class); if (controller != null && controller.isAnnotationPresent(Api.class)) { Api api = controller.getAnnotation(Api.class); if (!canReadApi(false, api)) { return null; } tags = updateTagsForApi(null, api); resourceSecurities = getSecurityRequirements(api); // description = api.description(); // position = api.position(); } resourcePath = resource.getControllerMapping(); Map<String, List<Method>> apiMethodMap = new HashMap<String, List<Method>>(); //collect api from method with @RequestMapping collectApisByRequestMapping(methods, apiMethodMap); for (String p : apiMethodMap.keySet()) { List<Operation> operations = new ArrayList<Operation>(); for (Method method : apiMethodMap.get(p)) { RequestMapping requestMapping = method.getAnnotation(RequestMapping.class); ApiOperation apiOperation = method.getAnnotation(ApiOperation.class); String operationPath = p; //getPath(apiPath, requestMapping, ""); String operationId; String httpMethod = null; if (operationPath != null && apiOperation != null) { Map<String, String> regexMap = new HashMap<String, String>(); operationPath = parseOperationPath(operationPath, regexMap); //http method if (requestMapping.method() != null && requestMapping.method().length != 0) { httpMethod = requestMapping.method()[0].toString().toLowerCase(); } Operation operation = parseMethod(method); updateOperationParameters(new ArrayList<Parameter>(), regexMap, operation); updateOperationProtocols(apiOperation, operation); String[] apiConsumes = new String[0]; String[] apiProduces = new String[0]; RequestMapping rm = controller.getAnnotation(RequestMapping.class); String[] pps = new String[0]; String[] pcs = new String[0]; if (rm != null) { pcs = rm.consumes(); pps = rm.produces(); } apiConsumes = updateOperationConsumes(method, pcs, apiConsumes, operation); apiProduces = updateOperationProduces(method, pps, apiProduces, operation); // can't continue without a valid http method // httpMethod = httpMethod == null ? parentMethod : httpMethod; ApiOperation op = method.getAnnotation(ApiOperation.class); updateTagsForOperation(operation, op); updateOperation(apiConsumes, apiProduces, tags, resourceSecurities, operation); updatePath(operationPath, httpMethod, operation); } } } return swagger; } #location 38 #vulnerability type NULL_DEREFERENCE
#fixed code public Swagger read(SpringResource resource) { if (swagger == null) { swagger = new Swagger(); } String description; List<Method> methods = resource.getMethods(); Map<String, Tag> tags = new HashMap<String, Tag>(); List<SecurityRequirement> resourceSecurities = new ArrayList<SecurityRequirement>(); // Add the description from the controller api Class<?> controller = resource.getControllerClass(); RequestMapping controllerRM = controller.getAnnotation(RequestMapping.class); String[] controllerProduces = new String[0]; String[] controllerConsumes = new String[0]; if (controllerRM != null) { controllerConsumes = controllerRM.consumes(); controllerProduces = controllerRM.produces(); } if (controller != null && controller.isAnnotationPresent(Api.class)) { Api api = controller.getAnnotation(Api.class); if (!canReadApi(false, api)) { return swagger; } tags = updateTagsForApi(null, api); resourceSecurities = getSecurityRequirements(api); description = api.description(); } resourcePath = resource.getControllerMapping(); //collect api from method with @RequestMapping Map<String, List<Method>> apiMethodMap = collectApisByRequestMapping(methods); for (String path : apiMethodMap.keySet()) { for (Method method : apiMethodMap.get(path)) { RequestMapping requestMapping = method.getAnnotation(RequestMapping.class); if (requestMapping == null) { continue; } ApiOperation apiOperation = method.getAnnotation(ApiOperation.class); if (apiOperation == null) { continue; } String httpMethod = null; Map<String, String> regexMap = new HashMap<String, String>(); String operationPath = parseOperationPath(path, regexMap); //http method if (requestMapping.method() != null && requestMapping.method().length != 0) { httpMethod = requestMapping.method()[0].toString().toLowerCase(); if (httpMethod == null) { continue; } } Operation operation = parseMethod(method); updateOperationParameters(new ArrayList<Parameter>(), regexMap, operation); updateOperationProtocols(apiOperation, operation); String[] apiProduces = requestMapping.produces(); String[] apiConsumes = requestMapping.consumes(); apiProduces = (apiProduces == null || apiProduces.length == 0 ) ? controllerProduces : apiProduces; apiConsumes = (apiConsumes == null || apiProduces.length == 0 ) ? controllerConsumes : apiConsumes; apiConsumes = updateOperationConsumes(new String[0], apiConsumes, operation); apiProduces = updateOperationProduces(new String[0], apiProduces, operation); ApiOperation op = method.getAnnotation(ApiOperation.class); updateTagsForOperation(operation, op); updateOperation(apiConsumes, apiProduces, tags, resourceSecurities, operation); updatePath(operationPath, httpMethod, operation); } } return swagger; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code private Map<String, List<Method>> collectApisByRequestMapping(List<Method> methods) { Map<String, List<Method>> apiMethodMap = new HashMap<String, List<Method>>(); for (Method method : methods) { if (method.isAnnotationPresent(RequestMapping.class)) { RequestMapping requestMapping = Annotations.get(method, RequestMapping.class); String path = ""; if (requestMapping.value() != null && requestMapping.value().length != 0) { path = generateFullPath(requestMapping.value()[0]); } else { path = resourcePath; } if (apiMethodMap.containsKey(path)) { apiMethodMap.get(path).add(method); } else { List<Method> ms = new ArrayList<Method>(); ms.add(method); apiMethodMap.put(path, ms); } } } return apiMethodMap; } #location 7 #vulnerability type NULL_DEREFERENCE
#fixed code private Map<String, List<Method>> collectApisByRequestMapping(List<Method> methods) { Map<String, List<Method>> apiMethodMap = new HashMap<String, List<Method>>(); for (Method method : methods) { if (method.isAnnotationPresent(RequestMapping.class)) { RequestMapping requestMapping = AnnotationUtils.findAnnotation(method, RequestMapping.class); String path = ""; if (requestMapping.value() != null && requestMapping.value().length != 0) { path = generateFullPath(requestMapping.value()[0]); } else { path = resourcePath; } if (apiMethodMap.containsKey(path)) { apiMethodMap.get(path).add(method); } else { List<Method> ms = new ArrayList<Method>(); ms.add(method); apiMethodMap.put(path, ms); } } } return apiMethodMap; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public Operation parseMethod(String httpMethod, Method method) { int responseCode = 200; Operation operation = new Operation(); ApiOperation apiOperation = AnnotationUtils.findAnnotation(method, ApiOperation.class); String operationId = getOperationId(method, httpMethod); String responseContainer = null; Type responseClassType = null; Map<String, Property> defaultResponseHeaders = null; if (apiOperation != null) { if (apiOperation.hidden()) { return null; } if (!apiOperation.nickname().isEmpty()) { operationId = apiOperation.nickname(); } defaultResponseHeaders = parseResponseHeaders(apiOperation.responseHeaders()); operation.summary(apiOperation.value()).description(apiOperation.notes()); Map<String, Object> customExtensions = BaseReaderUtils.parseExtensions(apiOperation.extensions()); operation.setVendorExtensions(customExtensions); if (!apiOperation.response().equals(Void.class) && !apiOperation.response().equals(void.class)) { responseClassType = apiOperation.response(); } if (!apiOperation.responseContainer().isEmpty()) { responseContainer = apiOperation.responseContainer(); } List<SecurityRequirement> securities = new ArrayList<>(); for (Authorization auth : apiOperation.authorizations()) { if (!auth.value().isEmpty()) { SecurityRequirement security = new SecurityRequirement(); security.setName(auth.value()); for (AuthorizationScope scope : auth.scopes()) { if (!scope.scope().isEmpty()) { security.addScope(scope.scope()); } } securities.add(security); } } for (SecurityRequirement sec : securities) { operation.security(sec); } } operation.operationId(operationId); if (responseClassType == null) { // pick out response from method declaration LOGGER.debug("picking up response class from method " + method); responseClassType = method.getGenericReturnType(); } boolean hasApiAnnotation = false; if (responseClassType instanceof Class) { hasApiAnnotation = AnnotationUtils.findAnnotation((Class) responseClassType, Api.class) != null; } if ((responseClassType != null) && !responseClassType.equals(Void.class) && !responseClassType.equals(void.class) && !responseClassType.equals(javax.ws.rs.core.Response.class) && !hasApiAnnotation && !isSubResource(httpMethod, method)) { if (isPrimitive(responseClassType)) { Property property = ModelConverters.getInstance().readAsProperty(responseClassType); if (property != null) { Property responseProperty = RESPONSE_CONTAINER_CONVERTER.withResponseContainer(responseContainer, property); operation.response(responseCode, new Response() .description("successful operation") .schema(responseProperty) .headers(defaultResponseHeaders)); } } else if (!responseClassType.equals(Void.class) && !responseClassType.equals(void.class)) { Map<String, Model> models = readModels(responseClassType); if (models.isEmpty()) { Property p = ModelConverters.getInstance().readAsProperty(responseClassType); operation.response(responseCode, new Response() .description("successful operation") .schema(p) .headers(defaultResponseHeaders)); } for (String key : models.keySet()) { Property responseProperty = RESPONSE_CONTAINER_CONVERTER.withResponseContainer(responseContainer, new RefProperty().asDefault(key)); operation.response(responseCode, new Response() .description("successful operation") .schema(responseProperty) .headers(defaultResponseHeaders)); swagger.model(key, models.get(key)); } } Map<String, Model> models = readAllModels(responseClassType); for (Map.Entry<String, Model> entry : models.entrySet()) { swagger.model(entry.getKey(), entry.getValue()); } } Consumes consumes = AnnotationUtils.findAnnotation(method, Consumes.class); if (consumes != null) { for (String mediaType : consumes.value()) { operation.consumes(mediaType); } } Produces produces = AnnotationUtils.findAnnotation(method, Produces.class); if (produces != null) { for (String mediaType : produces.value()) { operation.produces(mediaType); } } ApiResponses responseAnnotation = AnnotationUtils.findAnnotation(method, ApiResponses.class); if (responseAnnotation != null) { updateApiResponse(operation, responseAnnotation); } if (AnnotationUtils.findAnnotation(method, Deprecated.class) != null) { operation.deprecated(true); } // process parameters Class<?>[] parameterTypes = method.getParameterTypes(); Type[] genericParameterTypes = method.getGenericParameterTypes(); Annotation[][] paramAnnotations = findParamAnnotations(method); for (int i = 0; i < parameterTypes.length; i++) { Type type = genericParameterTypes[i]; List<Annotation> annotations = Arrays.asList(paramAnnotations[i]); List<Parameter> parameters = getParameters(type, annotations); for (Parameter parameter : parameters) { if (hasCommonParameter(parameter)) { Parameter refParameter = new RefParameter(RefType.PARAMETER.getInternalPrefix() + parameter.getName()); operation.parameter(refParameter); } else { parameter = replaceArrayModelForOctetStream(operation, parameter); operation.parameter(parameter); } } } if (operation.getResponses() == null) { operation.defaultResponse(new Response().description("successful operation")); } // Process @ApiImplicitParams this.readImplicitParameters(method, operation); processOperationDecorator(operation, method); return operation; } #location 80 #vulnerability type NULL_DEREFERENCE
#fixed code public Operation parseMethod(String httpMethod, Method method) { int responseCode = 200; Operation operation = new Operation(); ApiOperation apiOperation = AnnotationUtils.findAnnotation(method, ApiOperation.class); String operationId = getOperationId(method, httpMethod); String responseContainer = null; Type responseClassType = null; Map<String, Property> defaultResponseHeaders = null; if (apiOperation != null) { if (apiOperation.hidden()) { return null; } if (!apiOperation.nickname().isEmpty()) { operationId = apiOperation.nickname(); } defaultResponseHeaders = parseResponseHeaders(apiOperation.responseHeaders()); operation.summary(apiOperation.value()).description(apiOperation.notes()); Map<String, Object> customExtensions = BaseReaderUtils.parseExtensions(apiOperation.extensions()); operation.setVendorExtensions(customExtensions); if (!apiOperation.response().equals(Void.class) && !apiOperation.response().equals(void.class)) { responseClassType = apiOperation.response(); } if (!apiOperation.responseContainer().isEmpty()) { responseContainer = apiOperation.responseContainer(); } List<SecurityRequirement> securities = new ArrayList<>(); for (Authorization auth : apiOperation.authorizations()) { if (!auth.value().isEmpty()) { SecurityRequirement security = new SecurityRequirement(); security.setName(auth.value()); for (AuthorizationScope scope : auth.scopes()) { if (!scope.scope().isEmpty()) { security.addScope(scope.scope()); } } securities.add(security); } } for (SecurityRequirement sec : securities) { operation.security(sec); } } operation.operationId(operationId); if (responseClassType == null) { // pick out response from method declaration LOGGER.debug("picking up response class from method " + method); responseClassType = method.getGenericReturnType(); } boolean hasApiAnnotation = false; if (responseClassType instanceof Class) { hasApiAnnotation = AnnotationUtils.findAnnotation((Class) responseClassType, Api.class) != null; } if ((responseClassType != null) && !responseClassType.equals(Void.class) && !responseClassType.equals(void.class) && !responseClassType.equals(javax.ws.rs.core.Response.class) && !hasApiAnnotation && !isSubResource(httpMethod, method)) { if (isPrimitive(responseClassType)) { Property property = ModelConverters.getInstance().readAsProperty(responseClassType); if (property != null) { Property responseProperty = RESPONSE_CONTAINER_CONVERTER.withResponseContainer(responseContainer, property); operation.response(responseCode, new Response() .description("successful operation") .schema(responseProperty) .headers(defaultResponseHeaders)); } } else if (!responseClassType.equals(Void.class) && !responseClassType.equals(void.class)) { Map<String, Model> models = ModelConverters.getInstance().read(responseClassType); if (models.isEmpty()) { Property p = ModelConverters.getInstance().readAsProperty(responseClassType); operation.response(responseCode, new Response() .description("successful operation") .schema(p) .headers(defaultResponseHeaders)); } for (String key : models.keySet()) { Property responseProperty = RESPONSE_CONTAINER_CONVERTER.withResponseContainer(responseContainer, new RefProperty().asDefault(key)); operation.response(responseCode, new Response() .description("successful operation") .schema(responseProperty) .headers(defaultResponseHeaders)); swagger.model(key, models.get(key)); } } Map<String, Model> models = readAllModels(responseClassType); for (Map.Entry<String, Model> entry : models.entrySet()) { swagger.model(entry.getKey(), entry.getValue()); } } Consumes consumes = AnnotationUtils.findAnnotation(method, Consumes.class); if (consumes != null) { for (String mediaType : consumes.value()) { operation.consumes(mediaType); } } Produces produces = AnnotationUtils.findAnnotation(method, Produces.class); if (produces != null) { for (String mediaType : produces.value()) { operation.produces(mediaType); } } ApiResponses responseAnnotation = AnnotationUtils.findAnnotation(method, ApiResponses.class); if (responseAnnotation != null) { updateApiResponse(operation, responseAnnotation); } if (AnnotationUtils.findAnnotation(method, Deprecated.class) != null) { operation.deprecated(true); } // process parameters Class<?>[] parameterTypes = method.getParameterTypes(); Type[] genericParameterTypes = method.getGenericParameterTypes(); Annotation[][] paramAnnotations = findParamAnnotations(method); for (int i = 0; i < parameterTypes.length; i++) { Type type = genericParameterTypes[i]; List<Annotation> annotations = Arrays.asList(paramAnnotations[i]); List<Parameter> parameters = getParameters(type, annotations); for (Parameter parameter : parameters) { if (hasCommonParameter(parameter)) { Parameter refParameter = new RefParameter(RefType.PARAMETER.getInternalPrefix() + parameter.getName()); operation.parameter(refParameter); } else { parameter = replaceArrayModelForOctetStream(operation, parameter); operation.parameter(parameter); } } } if (operation.getResponses() == null) { operation.defaultResponse(new Response().description("successful operation")); } // Process @ApiImplicitParams this.readImplicitParameters(method, operation); processOperationDecorator(operation, method); return operation; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code private Operation parseMethod(Method method) { Operation operation = new Operation(); RequestMapping requestMapping = Annotations.get(method, RequestMapping.class); Class<?> responseClass = null; List<String> produces = new ArrayList<String>(); List<String> consumes = new ArrayList<String>(); String responseContainer = null; String operationId = method.getName(); Map<String, Property> defaultResponseHeaders = null; Set<Map<String, Object>> customExtensions = null; ApiOperation apiOperation = Annotations.get(method, ApiOperation.class); if (apiOperation.hidden()) return null; if (!"".equals(apiOperation.nickname())) operationId = apiOperation.nickname(); defaultResponseHeaders = parseResponseHeaders(apiOperation.responseHeaders()); operation.summary(apiOperation.value()).description(apiOperation.notes()); customExtensions = parseCustomExtensions(apiOperation.extensions()); if (customExtensions != null) { for (Map<String, Object> extension : customExtensions) { if (extension != null) { for (Map.Entry<String, Object> map : extension.entrySet()) { operation.setVendorExtension(map.getKey().startsWith("x-") ? map.getKey() : "x-" + map.getKey(), map.getValue()); } } } } if (apiOperation.response() != null && !Void.class.equals(apiOperation.response())) responseClass = apiOperation.response(); if (!"".equals(apiOperation.responseContainer())) responseContainer = apiOperation.responseContainer(); ///security if (apiOperation.authorizations() != null) { List<SecurityRequirement> securities = new ArrayList<SecurityRequirement>(); for (Authorization auth : apiOperation.authorizations()) { if (auth.value() != null && !"".equals(auth.value())) { SecurityRequirement security = new SecurityRequirement(); security.setName(auth.value()); AuthorizationScope[] scopes = auth.scopes(); for (AuthorizationScope scope : scopes) { if (scope.scope() != null && !"".equals(scope.scope())) { security.addScope(scope.scope()); } } securities.add(security); } } if (securities.size() > 0) { for (SecurityRequirement sec : securities) operation.security(sec); } } if (responseClass == null) { // pick out response from method declaration LOG.info("picking up response class from method " + method); Type t = method.getGenericReturnType(); responseClass = method.getReturnType(); if (responseClass.equals(ResponseEntity.class)) { responseClass = getGenericSubtype(method.getReturnType(), method.getGenericReturnType()); } if (!responseClass.equals(Void.class) && !"void".equals(responseClass.toString()) && Annotations.get(responseClass, Api.class) == null) { LOG.info("reading model " + responseClass); Map<String, Model> models = ModelConverters.getInstance().readAll(t); } } if (responseClass != null && !responseClass.equals(Void.class) && !responseClass.equals(ResponseEntity.class) && Annotations.get(responseClass, Api.class) == null) { if (isPrimitive(responseClass)) { Property responseProperty = null; Property property = ModelConverters.getInstance().readAsProperty(responseClass); if (property != null) { if ("list".equalsIgnoreCase(responseContainer)) responseProperty = new ArrayProperty(property); else if ("map".equalsIgnoreCase(responseContainer)) responseProperty = new MapProperty(property); else responseProperty = property; operation.response(apiOperation.code(), new Response() .description("successful operation") .schema(responseProperty) .headers(defaultResponseHeaders)); } } else if (!responseClass.equals(Void.class) && !"void".equals(responseClass.toString())) { Map<String, Model> models = ModelConverters.getInstance().read(responseClass); if (models.size() == 0) { Property pp = ModelConverters.getInstance().readAsProperty(responseClass); operation.response(apiOperation.code(), new Response() .description("successful operation") .schema(pp) .headers(defaultResponseHeaders)); } for (String key : models.keySet()) { Property responseProperty = null; if ("list".equalsIgnoreCase(responseContainer)) responseProperty = new ArrayProperty(new RefProperty().asDefault(key)); else if ("map".equalsIgnoreCase(responseContainer)) responseProperty = new MapProperty(new RefProperty().asDefault(key)); else responseProperty = new RefProperty().asDefault(key); operation.response(apiOperation.code(), new Response() .description("successful operation") .schema(responseProperty) .headers(defaultResponseHeaders)); swagger.model(key, models.get(key)); } models = ModelConverters.getInstance().readAll(responseClass); for (String key : models.keySet()) { swagger.model(key, models.get(key)); } } } operation.operationId(operationId); if (requestMapping.produces() != null) { for (String str : Arrays.asList(requestMapping.produces())) { if (!produces.contains(str)) { produces.add(str); } } } if (requestMapping.consumes() != null) { for (String str : Arrays.asList(requestMapping.consumes())) { if (!consumes.contains(str)) { consumes.add(str); } } } ApiResponses responseAnnotation = Annotations.get(method, ApiResponses.class); if (responseAnnotation != null) { updateApiResponse(operation, responseAnnotation); } else { ResponseStatus responseStatus = Annotations.get(method, ResponseStatus.class); if (responseStatus != null) { operation.response(responseStatus.value().value(), new Response().description(responseStatus.reason())); } } Deprecated annotation = Annotations.get(method, Deprecated.class); if (annotation != null) operation.deprecated(true); // FIXME `hidden` is never used boolean hidden = false; if (apiOperation != null) hidden = apiOperation.hidden(); // process parameters Class[] parameterTypes = method.getParameterTypes(); Type[] genericParameterTypes = method.getGenericParameterTypes(); Annotation[][] paramAnnotations = method.getParameterAnnotations(); // paramTypes = method.getParameterTypes // genericParamTypes = method.getGenericParameterTypes for (int i = 0; i < parameterTypes.length; i++) { Type type = genericParameterTypes[i]; List<Annotation> annotations = Arrays.asList(paramAnnotations[i]); List<Parameter> parameters = getParameters(type, annotations); for (Parameter parameter : parameters) { operation.parameter(parameter); } } if (operation.getResponses() == null) { operation.defaultResponse(new Response().description("successful operation")); } // Process @ApiImplicitParams this.readImplicitParameters(method, operation); return operation; } #location 15 #vulnerability type NULL_DEREFERENCE
#fixed code private Operation parseMethod(Method method) { Operation operation = new Operation(); RequestMapping requestMapping = AnnotationUtils.findAnnotation(method, RequestMapping.class); Class<?> responseClass = null; List<String> produces = new ArrayList<String>(); List<String> consumes = new ArrayList<String>(); String responseContainer = null; String operationId = method.getName(); Map<String, Property> defaultResponseHeaders = null; Set<Map<String, Object>> customExtensions = null; ApiOperation apiOperation = AnnotationUtils.findAnnotation(method, ApiOperation.class); if (apiOperation.hidden()) return null; if (!"".equals(apiOperation.nickname())) operationId = apiOperation.nickname(); defaultResponseHeaders = parseResponseHeaders(apiOperation.responseHeaders()); operation.summary(apiOperation.value()).description(apiOperation.notes()); customExtensions = parseCustomExtensions(apiOperation.extensions()); if (customExtensions != null) { for (Map<String, Object> extension : customExtensions) { if (extension != null) { for (Map.Entry<String, Object> map : extension.entrySet()) { operation.setVendorExtension(map.getKey().startsWith("x-") ? map.getKey() : "x-" + map.getKey(), map.getValue()); } } } } if (apiOperation.response() != null && !Void.class.equals(apiOperation.response())) responseClass = apiOperation.response(); if (!"".equals(apiOperation.responseContainer())) responseContainer = apiOperation.responseContainer(); ///security if (apiOperation.authorizations() != null) { List<SecurityRequirement> securities = new ArrayList<SecurityRequirement>(); for (Authorization auth : apiOperation.authorizations()) { if (auth.value() != null && !"".equals(auth.value())) { SecurityRequirement security = new SecurityRequirement(); security.setName(auth.value()); AuthorizationScope[] scopes = auth.scopes(); for (AuthorizationScope scope : scopes) { if (scope.scope() != null && !"".equals(scope.scope())) { security.addScope(scope.scope()); } } securities.add(security); } } if (securities.size() > 0) { for (SecurityRequirement sec : securities) operation.security(sec); } } if (responseClass == null) { // pick out response from method declaration LOG.info("picking up response class from method " + method); Type t = method.getGenericReturnType(); responseClass = method.getReturnType(); if (responseClass.equals(ResponseEntity.class)) { responseClass = getGenericSubtype(method.getReturnType(), method.getGenericReturnType()); } if (!responseClass.equals(Void.class) && !"void".equals(responseClass.toString()) && AnnotationUtils.findAnnotation(responseClass, Api.class) == null) { LOG.info("reading model " + responseClass); Map<String, Model> models = ModelConverters.getInstance().readAll(t); } } if (responseClass != null && !responseClass.equals(Void.class) && !responseClass.equals(ResponseEntity.class) && AnnotationUtils.findAnnotation(responseClass, Api.class) == null) { if (isPrimitive(responseClass)) { Property responseProperty = null; Property property = ModelConverters.getInstance().readAsProperty(responseClass); if (property != null) { if ("list".equalsIgnoreCase(responseContainer)) responseProperty = new ArrayProperty(property); else if ("map".equalsIgnoreCase(responseContainer)) responseProperty = new MapProperty(property); else responseProperty = property; operation.response(apiOperation.code(), new Response() .description("successful operation") .schema(responseProperty) .headers(defaultResponseHeaders)); } } else if (!responseClass.equals(Void.class) && !"void".equals(responseClass.toString())) { Map<String, Model> models = ModelConverters.getInstance().read(responseClass); if (models.size() == 0) { Property pp = ModelConverters.getInstance().readAsProperty(responseClass); operation.response(apiOperation.code(), new Response() .description("successful operation") .schema(pp) .headers(defaultResponseHeaders)); } for (String key : models.keySet()) { Property responseProperty = null; if ("list".equalsIgnoreCase(responseContainer)) responseProperty = new ArrayProperty(new RefProperty().asDefault(key)); else if ("map".equalsIgnoreCase(responseContainer)) responseProperty = new MapProperty(new RefProperty().asDefault(key)); else responseProperty = new RefProperty().asDefault(key); operation.response(apiOperation.code(), new Response() .description("successful operation") .schema(responseProperty) .headers(defaultResponseHeaders)); swagger.model(key, models.get(key)); } models = ModelConverters.getInstance().readAll(responseClass); for (String key : models.keySet()) { swagger.model(key, models.get(key)); } } } operation.operationId(operationId); if (requestMapping.produces() != null) { for (String str : Arrays.asList(requestMapping.produces())) { if (!produces.contains(str)) { produces.add(str); } } } if (requestMapping.consumes() != null) { for (String str : Arrays.asList(requestMapping.consumes())) { if (!consumes.contains(str)) { consumes.add(str); } } } ApiResponses responseAnnotation = AnnotationUtils.findAnnotation(method, ApiResponses.class); if (responseAnnotation != null) { updateApiResponse(operation, responseAnnotation); } else { ResponseStatus responseStatus = AnnotationUtils.findAnnotation(method, ResponseStatus.class); if (responseStatus != null) { operation.response(responseStatus.value().value(), new Response().description(responseStatus.reason())); } } Deprecated annotation = AnnotationUtils.findAnnotation(method, Deprecated.class); if (annotation != null) operation.deprecated(true); // FIXME `hidden` is never used boolean hidden = false; if (apiOperation != null) hidden = apiOperation.hidden(); // process parameters Class[] parameterTypes = method.getParameterTypes(); Type[] genericParameterTypes = method.getGenericParameterTypes(); Annotation[][] paramAnnotations = method.getParameterAnnotations(); // paramTypes = method.getParameterTypes // genericParamTypes = method.getGenericParameterTypes for (int i = 0; i < parameterTypes.length; i++) { Type type = genericParameterTypes[i]; List<Annotation> annotations = Arrays.asList(paramAnnotations[i]); List<Parameter> parameters = getParameters(type, annotations); for (Parameter parameter : parameters) { operation.parameter(parameter); } } if (operation.getResponses() == null) { operation.defaultResponse(new Response().description("successful operation")); } // Process @ApiImplicitParams this.readImplicitParameters(method, operation); return operation; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void testGeneratedDoc() throws Exception { mojo.execute(); BufferedReader actualReader = null; BufferedReader expectReader = null; FileInputStream swaggerJson = null; BufferedReader swaggerReader = null; try { File actual = docOutput; File expected = new File(this.getClass().getResource("/sample-springmvc.html").getFile()); FileAssert.assertEquals(expected, actual); swaggerJson = new FileInputStream(new File(swaggerOutputDir, "swagger.json")); swaggerReader = new BufferedReader(new InputStreamReader(swaggerJson)); String s = swaggerReader.readLine(); while (s != null) { if (s.contains("\"parameters\" : [ ],")) { assertFalse("should not have null parameters", true); } s = swaggerReader.readLine(); } } finally { if (actualReader != null) { actualReader.close(); } if (expectReader != null) { expectReader.close(); } if (swaggerJson != null) { swaggerJson.close(); } if (swaggerReader != null) { swaggerReader.close(); } } } #location 21 #vulnerability type RESOURCE_LEAK
#fixed code @Test public void testGeneratedDoc() throws Exception { mojo.execute(); FileInputStream swaggerJson = null; BufferedReader swaggerReader = null; try { File actual = docOutput; File expected = new File(this.getClass().getResource("/sample-springmvc.html").getFile()); String exptectedFileContent = CharMatcher.breakingWhitespace().removeFrom(Files.toString(expected, Charset.forName("UTF-8"))); String actualFileContent = CharMatcher.breakingWhitespace().removeFrom(Files.toString(actual, Charset.forName("UTF-8"))); assertEquals(exptectedFileContent, actualFileContent); swaggerJson = new FileInputStream(new File(swaggerOutputDir, "swagger.json")); swaggerReader = new BufferedReader(new InputStreamReader(swaggerJson)); String s = swaggerReader.readLine(); while (s != null) { if (s.contains("\"parameters\" : [ ],")) { fail("should not have null parameters"); } s = swaggerReader.readLine(); } } finally { if (swaggerJson != null) { swaggerJson.close(); } if (swaggerReader != null) { swaggerReader.close(); } } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public void toDocuments() throws GenerateException { if (outputTemplate == null) { prepareMustacheTemplate(); } if (outputTemplate.getApiDocuments().isEmpty()) { LOG.warn("nothing to write."); return; } LOG.info("Writing doc to " + outputPath + "..."); FileOutputStream fileOutputStream = null; try { fileOutputStream = new FileOutputStream(outputPath); } catch (FileNotFoundException e) { throw new GenerateException(e); } OutputStreamWriter writer = new OutputStreamWriter(fileOutputStream, Charset.forName("UTF-8")); MustacheFactory mf = new DefaultMustacheFactory(); URI uri = null; try { uri = new URI(templatePath); } catch (URISyntaxException e) { throw new GenerateException(e); } if (!uri.isAbsolute()) { File file = new File(templatePath); if (!file.exists()) { throw new GenerateException("Template " + file.getAbsoluteFile() + " not found. You can go to https://github.com/kongchen/api-doc-template to get templates."); } else { uri = new File(templatePath).toURI(); } } URL url = null; try { url = uri.toURL(); InputStreamReader reader = new InputStreamReader(url.openStream(), Charset.forName("UTF-8")); Mustache mustache = mf.compile(reader, templatePath); mustache.execute(writer, outputTemplate).flush(); writer.close(); LOG.info("Done!"); } catch (MalformedURLException e) { throw new GenerateException(e); } catch (IOException e) { throw new GenerateException(e); } } #location 30 #vulnerability type RESOURCE_LEAK
#fixed code public void toDocuments() throws GenerateException { if (outputTemplate == null) { prepareMustacheTemplate(); } if (outputTemplate.getApiDocuments().isEmpty()) { LOG.warn("nothing to write."); return; } LOG.info("Writing doc to " + outputPath + "..."); FileOutputStream fileOutputStream = null; try { fileOutputStream = new FileOutputStream(outputPath); } catch (FileNotFoundException e) { throw new GenerateException(e); } OutputStreamWriter writer = new OutputStreamWriter(fileOutputStream, Charset.forName("UTF-8")); try { URL url = getTemplateUri().toURL(); InputStreamReader reader = new InputStreamReader(url.openStream(), Charset.forName("UTF-8")); Mustache mustache = getMustacheFactory().compile(reader, templatePath); mustache.execute(writer, outputTemplate).flush(); writer.close(); LOG.info("Done!"); } catch (MalformedURLException e) { throw new GenerateException(e); } catch (IOException e) { throw new GenerateException(e); } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code private boolean stopUsingMysqldadmin() { boolean retValue = false; Reader stdOut = null; Reader stdErr = null; LogFileProcessor processor = null; Set<String> successPatterns = Sets.newHashSet( "'Can't connect to MySQL server on 'localhost'", Platform.detect() == Windows ? "mysqld.exe: Shutdown complete" : "mysqld: Shutdown complete"); try { String cmd = Paths.get(getExecutable().getFile().generatedBaseDir().getAbsolutePath(), "bin", "mysqladmin").toString(); Process p = Runtime.getRuntime().exec(new String[] { cmd, "--no-defaults", "--protocol=tcp", String.format("-u%s", MysqldConfig.SystemDefaults.USERNAME), "shutdown"}); retValue = p.waitFor() == 0; OutputWatchStreamProcessor outputWatch = new OutputWatchStreamProcessor( successPatterns, Sets.newHashSet("[ERROR]"), StreamToLineProcessor.wrap(getRuntimeConfig().getProcessOutput().getOutput())); processor = new LogFileProcessor(new File(this.getExecutable().executable.generatedBaseDir() + "/data/error.log"), outputWatch); stdOut = new InputStreamReader(p.getInputStream()); stdErr = new InputStreamReader(p.getErrorStream()); if (retValue) { outputWatch.waitForResult(getConfig().getTimeout()); if (!outputWatch.isInitWithSuccess()) { logger.error("mysql shutdown failed. Expected to find in output: 'Shutdown complete', got: " + outputWatch.getFailureFound()); retValue = false; } } else { logger.error("mysql shutdown failed with error code: " + p.waitFor() + " and message: " + CharStreams.toString(stdErr)); } } catch (InterruptedException e) { logger.warn("Encountered error why shutting down process.", e); } catch (IOException e) { logger.warn("Encountered error why shutting down process.", e); } finally { closeCloseables(stdOut, stdErr); if (processor != null) processor.shutdown(); } return retValue; } #location 39 #vulnerability type RESOURCE_LEAK
#fixed code private boolean stopUsingMysqldadmin() { boolean retValue = false; Reader stdOut = null; Reader stdErr = null; LogFileProcessor processor = null; Set<String> successPatterns = Sets.newHashSet( "'Can't connect to MySQL server on 'localhost'", Platform.detect() == Windows ? "mysqld.exe: Shutdown complete" : "mysqld: Shutdown complete"); try { String cmd = Paths.get(getExecutable().getFile().generatedBaseDir().getAbsolutePath(), "bin", "mysqladmin").toString(); Process p = Runtime.getRuntime().exec(new String[] { cmd, "--no-defaults", "--protocol=tcp", String.format("-u%s", MysqldConfig.SystemDefaults.USERNAME), "shutdown"}); retValue = p.waitFor() == 0; OutputWatchStreamProcessor outputWatch = new OutputWatchStreamProcessor( successPatterns, Sets.newHashSet("[ERROR]"), StreamToLineProcessor.wrap(getRuntimeConfig().getProcessOutput().getOutput())); processor = new LogFileProcessor(new File(this.getExecutable().executable.generatedBaseDir() + "/data/error.log"), outputWatch); stdOut = new InputStreamReader(p.getInputStream()); stdErr = new InputStreamReader(p.getErrorStream()); if (retValue) { outputWatch.waitForResult(getConfig().getTimeout()); if (!outputWatch.isInitWithSuccess()) { logger.error("mysql shutdown failed. Expected to find in output: 'Shutdown complete', got: " + outputWatch.getFailureFound()); retValue = false; } } else { String errOutput = CharStreams.toString(stdErr); if (errOutput.contains("Can't connect to MySQL server on")) { logger.warn("mysql was already shutdown - no need to add extra shutdown hook - process does it out of the box."); retValue = true; } else { logger.error("mysql shutdown failed with error code: " + p.waitFor() + " and message: " + CharStreams.toString(stdErr)); } } } catch (InterruptedException e) { logger.warn("Encountered error why shutting down process.", e); } catch (IOException e) { logger.warn("Encountered error why shutting down process.", e); } finally { closeCloseables(stdOut, stdErr); if (processor != null) processor.shutdown(); } return retValue; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code private void execute(final String sql) { String command = (Platform.detect() == Windows) ? format("\"%s\"", sql) : sql; try { Process p = Runtime.getRuntime().exec(new String[]{ Paths.get(executable.getBaseDir().getAbsolutePath(), "bin", "mysql").toString(), "--protocol=tcp", format("--user=%s", SystemDefaults.USERNAME), format("--port=%s", config.getPort()), "-e", command, schemaName}); if (p.waitFor() != 0) { String out = IOUtils.toString(p.getInputStream()); String err = IOUtils.toString(p.getErrorStream()); if (isNullOrEmpty(out)) throw new CommandFailedException(command, schemaName, p.waitFor(), err); else throw new CommandFailedException(command, schemaName, p.waitFor(), out); } } catch (IOException | InterruptedException e) { throw new CommandFailedException(command, schemaName, e.getMessage(), e); } } #location 18 #vulnerability type RESOURCE_LEAK
#fixed code private void execute(final String sql) { String command = (Platform.detect() == Windows) ? format("\"%s\"", sql) : sql; try { Process p = new ProcessBuilder(new String[]{ Paths.get(executable.getBaseDir().getAbsolutePath(), "bin", "mysql").toString(), "--protocol=tcp", format("--user=%s", SystemDefaults.USERNAME), format("--port=%s", config.getPort()), schemaName}).start(); IOUtils.copy(new StringReader(sql), p.getOutputStream(), Charset.defaultCharset()); p.getOutputStream().close(); if (p.waitFor() != 0) { String out = IOUtils.toString(p.getInputStream()); String err = IOUtils.toString(p.getErrorStream()); if (isNullOrEmpty(out)) throw new CommandFailedException(command, schemaName, p.waitFor(), err); else throw new CommandFailedException(command, schemaName, p.waitFor(), out); } } catch (IOException | InterruptedException e) { throw new CommandFailedException(command, schemaName, e.getMessage(), e); } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code private boolean stopUsingMysqldadmin() { boolean retValue = false; Reader stdOut = null; Reader stdErr = null; LogFileProcessor processor = null; Set<String> successPatterns = Sets.newHashSet("'Can't connect to MySQL server on 'localhost'"); try { Process p; if (Platform.detect() == Platform.Windows) { String cmd = Paths.get(getExecutable().getFile().generatedBaseDir().getAbsolutePath(), "bin", "mysqladmin.exe").toString(); successPatterns.add("mysqld.exe: Shutdown complete"); p = Runtime.getRuntime().exec(new String[] { cmd, "--no-defaults", "--protocol=tcp", String.format("-u%s", MysqldConfig.SystemDefaults.USERNAME), "shutdown"}); } else { String cmd = Paths.get(getExecutable().getFile().generatedBaseDir().getAbsolutePath(), "bin", "mysqladmin").toString(); successPatterns.add("mysqld: Shutdown complete"); p = Runtime.getRuntime().exec(new String[] { cmd, "--no-defaults", "--protocol=tcp", String.format("-u%s", MysqldConfig.SystemDefaults.USERNAME), //String.format("--socket=%s", sockFile(getExecutable().executable)), "shutdown"}); } retValue = p.waitFor() == 0; OutputWatchStreamProcessor outputWatch = new OutputWatchStreamProcessor( successPatterns, Sets.newHashSet("[ERROR]"), StreamToLineProcessor.wrap(unsafeRuntimeConfig.getProcessOutput().getOutput())); processor = new LogFileProcessor(new File(this.getExecutable().executable.generatedBaseDir() + "/data/error.log"), outputWatch); stdOut = new InputStreamReader(p.getInputStream()); stdErr = new InputStreamReader(p.getErrorStream()); if (retValue) { outputWatch.waitForResult(getConfig().getTimeout()); if (!outputWatch.isInitWithSuccess()) { logger.error("mysql shutdown failed. Expected to find in output: 'Shutdown complete', got: " + outputWatch.getFailureFound()); retValue = false; } } else { logger.error("mysql shutdown failed with error code: " + p.waitFor() + " and message: " + CharStreams.toString(stdErr)); } } catch (InterruptedException e) { logger.warn("Encountered error why shutting down process.", e); } catch (IOException e) { logger.warn("Encountered error why shutting down process.", e); } finally { closeCloseable(stdOut); closeCloseable(stdErr); if (processor != null) processor.shutdown(); } return retValue; } #location 59 #vulnerability type RESOURCE_LEAK
#fixed code private boolean stopUsingMysqldadmin() { boolean retValue = false; Reader stdOut = null; Reader stdErr = null; LogFileProcessor processor = null; Set<String> successPatterns = Sets.newHashSet( "'Can't connect to MySQL server on 'localhost'", Platform.detect() == Windows ? "mysqld.exe: Shutdown complete" : "mysqld: Shutdown complete"); try { String cmd = Paths.get(getExecutable().getFile().generatedBaseDir().getAbsolutePath(), "bin", "mysqladmin").toString(); Process p = Runtime.getRuntime().exec(new String[] { cmd, "--no-defaults", "--protocol=tcp", String.format("-u%s", MysqldConfig.SystemDefaults.USERNAME), "shutdown"}); retValue = p.waitFor() == 0; OutputWatchStreamProcessor outputWatch = new OutputWatchStreamProcessor( successPatterns, Sets.newHashSet("[ERROR]"), StreamToLineProcessor.wrap(getRuntimeConfig().getProcessOutput().getOutput())); processor = new LogFileProcessor(new File(this.getExecutable().executable.generatedBaseDir() + "/data/error.log"), outputWatch); stdOut = new InputStreamReader(p.getInputStream()); stdErr = new InputStreamReader(p.getErrorStream()); if (retValue) { outputWatch.waitForResult(getConfig().getTimeout()); if (!outputWatch.isInitWithSuccess()) { logger.error("mysql shutdown failed. Expected to find in output: 'Shutdown complete', got: " + outputWatch.getFailureFound()); retValue = false; } } else { logger.error("mysql shutdown failed with error code: " + p.waitFor() + " and message: " + CharStreams.toString(stdErr)); } } catch (InterruptedException e) { logger.warn("Encountered error why shutting down process.", e); } catch (IOException e) { logger.warn("Encountered error why shutting down process.", e); } finally { closeCloseables(stdOut, stdErr); if (processor != null) processor.shutdown(); } return retValue; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code private boolean stopUsingMysqldadmin() { boolean retValue = false; Reader stdOut = null; Reader stdErr = null; LogFileProcessor processor = null; Set<String> successPatterns = Sets.newHashSet( "'Can't connect to MySQL server on 'localhost'", Platform.detect() == Windows ? "mysqld.exe: Shutdown complete" : "mysqld: Shutdown complete"); try { String cmd = Paths.get(getExecutable().getFile().baseDir().getAbsolutePath(), "bin", "mysqladmin").toString(); Process p = Runtime.getRuntime().exec(new String[] { cmd, "--no-defaults", "--protocol=tcp", format("-u%s", MysqldConfig.SystemDefaults.USERNAME), format("--port=%s", getConfig().getPort()), "shutdown"}); retValue = p.waitFor() == 0; OutputWatchStreamProcessor outputWatch = new OutputWatchStreamProcessor(successPatterns, "[ERROR]", StreamToLineProcessor.wrap(getRuntimeConfig().getProcessOutput().getOutput())); processor = new LogFileProcessor(new File(this.getExecutable().getBaseDir() + "/data/error.log"), outputWatch); stdOut = new InputStreamReader(p.getInputStream()); stdErr = new InputStreamReader(p.getErrorStream()); if (retValue) { outputWatch.waitForResult(getConfig().getTimeout()); if (!outputWatch.isInitWithSuccess()) { logger.error("mysql shutdown failed. Expected to find in output: 'Shutdown complete', got: " + outputWatch.getFailureFound()); retValue = false; } } else { String errOutput = CharStreams.toString(stdErr); if (errOutput.contains("Can't connect to MySQL server on")) { logger.warn("mysql was already shutdown - no need to add extra shutdown hook - process does it out of the box."); retValue = true; } else { logger.error("mysql shutdown failed with error code: " + p.waitFor() + " and message: " + CharStreams.toString(stdErr)); } } } catch (InterruptedException | IOException e) { logger.warn("Encountered error why shutting down process.", e); } finally { closeCloseables(stdOut, stdErr); if (processor != null) processor.shutdown(); } return retValue; } #location 51 #vulnerability type RESOURCE_LEAK
#fixed code private boolean stopUsingMysqldadmin() { ResultMatchingListener shutdownListener = outputWatch.addListener(new ResultMatchingListener(": Shutdown complete")); boolean retValue = false; Reader stdErr = null; try { String cmd = Paths.get(getExecutable().getFile().baseDir().getAbsolutePath(), "bin", "mysqladmin").toString(); Process p = Runtime.getRuntime().exec(new String[]{ cmd, "--no-defaults", "--protocol=tcp", format("-u%s", MysqldConfig.SystemDefaults.USERNAME), format("--port=%s", getConfig().getPort()), "shutdown"}); retValue = p.waitFor() == 0; stdErr = new InputStreamReader(p.getErrorStream()); if (retValue) { shutdownListener.waitForResult(getConfig().getTimeout()); if (!shutdownListener.isInitWithSuccess()) { logger.error("mysql shutdown failed. Expected to find in output: 'Shutdown complete', got: " + shutdownListener.getFailureFound()); retValue = false; } else { retValue = true; } } else { String errOutput = CharStreams.toString(stdErr); if (errOutput.contains("Can't connect to MySQL server on")) { logger.warn("mysql was already shutdown - no need to add extra shutdown hook - process does it out of the box."); retValue = true; } else { logger.error("mysql shutdown failed with error code: " + p.waitFor() + " and message: " + errOutput); } } } catch (InterruptedException | IOException e) { logger.warn("Encountered error why shutting down process.", e); } finally { closeCloseables(stdErr); } return retValue; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code private void execute(final String sql) { String command = (Platform.detect() == Windows) ? format("\"%s\"", sql) : sql; try { Process p = Runtime.getRuntime().exec(new String[]{ Paths.get(executable.getBaseDir().getAbsolutePath(), "bin", "mysql").toString(), "--protocol=tcp", format("--user=%s", SystemDefaults.USERNAME), format("--port=%s", config.getPort()), "-e", command, schemaName}); if (p.waitFor() != 0) { String out = IOUtils.toString(p.getInputStream()); String err = IOUtils.toString(p.getErrorStream()); if (isNullOrEmpty(out)) throw new CommandFailedException(command, schemaName, p.waitFor(), err); else throw new CommandFailedException(command, schemaName, p.waitFor(), out); } } catch (IOException | InterruptedException e) { throw new CommandFailedException(command, schemaName, e.getMessage(), e); } } #location 21 #vulnerability type RESOURCE_LEAK
#fixed code private void execute(final String sql) { String command = (Platform.detect() == Windows) ? format("\"%s\"", sql) : sql; try { Process p = new ProcessBuilder(new String[]{ Paths.get(executable.getBaseDir().getAbsolutePath(), "bin", "mysql").toString(), "--protocol=tcp", format("--user=%s", SystemDefaults.USERNAME), format("--port=%s", config.getPort()), schemaName}).start(); IOUtils.copy(new StringReader(sql), p.getOutputStream(), Charset.defaultCharset()); p.getOutputStream().close(); if (p.waitFor() != 0) { String out = IOUtils.toString(p.getInputStream()); String err = IOUtils.toString(p.getErrorStream()); if (isNullOrEmpty(out)) throw new CommandFailedException(command, schemaName, p.waitFor(), err); else throw new CommandFailedException(command, schemaName, p.waitFor(), out); } } catch (IOException | InterruptedException e) { throw new CommandFailedException(command, schemaName, e.getMessage(), e); } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code private void execute(final String sql) { String command = (Platform.detect() == Windows) ? format("\"%s\"", sql) : sql; try { Process p = Runtime.getRuntime().exec(new String[]{ Paths.get(executable.getBaseDir().getAbsolutePath(), "bin", "mysql").toString(), "--protocol=tcp", format("--user=%s", SystemDefaults.USERNAME), format("--port=%s", config.getPort()), "-e", command, schemaName}); if (p.waitFor() != 0) { String out = IOUtils.toString(p.getInputStream()); String err = IOUtils.toString(p.getErrorStream()); if (isNullOrEmpty(out)) throw new CommandFailedException(command, schemaName, p.waitFor(), err); else throw new CommandFailedException(command, schemaName, p.waitFor(), out); } } catch (IOException | InterruptedException e) { throw new CommandFailedException(command, schemaName, e.getMessage(), e); } } #location 20 #vulnerability type RESOURCE_LEAK
#fixed code private void execute(final String sql) { String command = (Platform.detect() == Windows) ? format("\"%s\"", sql) : sql; try { Process p = new ProcessBuilder(new String[]{ Paths.get(executable.getBaseDir().getAbsolutePath(), "bin", "mysql").toString(), "--protocol=tcp", format("--user=%s", SystemDefaults.USERNAME), format("--port=%s", config.getPort()), schemaName}).start(); IOUtils.copy(new StringReader(sql), p.getOutputStream(), Charset.defaultCharset()); p.getOutputStream().close(); if (p.waitFor() != 0) { String out = IOUtils.toString(p.getInputStream()); String err = IOUtils.toString(p.getErrorStream()); if (isNullOrEmpty(out)) throw new CommandFailedException(command, schemaName, p.waitFor(), err); else throw new CommandFailedException(command, schemaName, p.waitFor(), out); } } catch (IOException | InterruptedException e) { throw new CommandFailedException(command, schemaName, e.getMessage(), e); } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code private boolean stopUsingMysqldadmin() { boolean retValue = false; Reader stdOut = null; Reader stdErr = null; LogFileProcessor processor = null; Set<String> successPatterns = Sets.newHashSet("'Can't connect to MySQL server on 'localhost'"); try { Process p; if (Platform.detect() == Platform.Windows) { String cmd = Paths.get(getExecutable().getFile().generatedBaseDir().getAbsolutePath(), "bin", "mysqladmin.exe").toString(); successPatterns.add("mysqld.exe: Shutdown complete"); p = Runtime.getRuntime().exec(new String[] { cmd, "--no-defaults", "--protocol=tcp", String.format("-u%s", MysqldConfig.SystemDefaults.USERNAME), "shutdown"}); } else { String cmd = Paths.get(getExecutable().getFile().generatedBaseDir().getAbsolutePath(), "bin", "mysqladmin").toString(); successPatterns.add("mysqld: Shutdown complete"); p = Runtime.getRuntime().exec(new String[] { cmd, "--no-defaults", "--protocol=tcp", String.format("-u%s", MysqldConfig.SystemDefaults.USERNAME), //String.format("--socket=%s", sockFile(getExecutable().executable)), "shutdown"}); } retValue = p.waitFor() == 0; OutputWatchStreamProcessor outputWatch = new OutputWatchStreamProcessor( successPatterns, Sets.newHashSet("[ERROR]"), StreamToLineProcessor.wrap(unsafeRuntimeConfig.getProcessOutput().getOutput())); processor = new LogFileProcessor(new File(this.getExecutable().executable.generatedBaseDir() + "/data/error.log"), outputWatch); stdOut = new InputStreamReader(p.getInputStream()); stdErr = new InputStreamReader(p.getErrorStream()); if (retValue) { outputWatch.waitForResult(getConfig().getTimeout()); if (!outputWatch.isInitWithSuccess()) { logger.error("mysql shutdown failed. Expected to find in output: 'Shutdown complete', got: " + outputWatch.getFailureFound()); retValue = false; } } else { logger.error("mysql shutdown failed with error code: " + p.waitFor() + " and message: " + CharStreams.toString(stdErr)); } } catch (InterruptedException e) { logger.warn("Encountered error why shutting down process.", e); } catch (IOException e) { logger.warn("Encountered error why shutting down process.", e); } finally { closeCloseable(stdOut); closeCloseable(stdErr); if (processor != null) processor.shutdown(); } return retValue; } #location 60 #vulnerability type RESOURCE_LEAK
#fixed code private boolean stopUsingMysqldadmin() { boolean retValue = false; Reader stdOut = null; Reader stdErr = null; LogFileProcessor processor = null; Set<String> successPatterns = Sets.newHashSet( "'Can't connect to MySQL server on 'localhost'", Platform.detect() == Windows ? "mysqld.exe: Shutdown complete" : "mysqld: Shutdown complete"); try { String cmd = Paths.get(getExecutable().getFile().generatedBaseDir().getAbsolutePath(), "bin", "mysqladmin").toString(); Process p = Runtime.getRuntime().exec(new String[] { cmd, "--no-defaults", "--protocol=tcp", String.format("-u%s", MysqldConfig.SystemDefaults.USERNAME), "shutdown"}); retValue = p.waitFor() == 0; OutputWatchStreamProcessor outputWatch = new OutputWatchStreamProcessor( successPatterns, Sets.newHashSet("[ERROR]"), StreamToLineProcessor.wrap(getRuntimeConfig().getProcessOutput().getOutput())); processor = new LogFileProcessor(new File(this.getExecutable().executable.generatedBaseDir() + "/data/error.log"), outputWatch); stdOut = new InputStreamReader(p.getInputStream()); stdErr = new InputStreamReader(p.getErrorStream()); if (retValue) { outputWatch.waitForResult(getConfig().getTimeout()); if (!outputWatch.isInitWithSuccess()) { logger.error("mysql shutdown failed. Expected to find in output: 'Shutdown complete', got: " + outputWatch.getFailureFound()); retValue = false; } } else { logger.error("mysql shutdown failed with error code: " + p.waitFor() + " and message: " + CharStreams.toString(stdErr)); } } catch (InterruptedException e) { logger.warn("Encountered error why shutting down process.", e); } catch (IOException e) { logger.warn("Encountered error why shutting down process.", e); } finally { closeCloseables(stdOut, stdErr); if (processor != null) processor.shutdown(); } return retValue; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code protected SettableBeanProperty _resolvedObjectIdProperty(DeserializationContext ctxt, SettableBeanProperty prop) throws JsonMappingException { ObjectIdInfo objectIdInfo = prop.getObjectIdInfo(); JsonDeserializer<Object> valueDeser = prop.getValueDeserializer(); ObjectIdReader objectIdReader = valueDeser.getObjectIdReader(); if (objectIdInfo == null && objectIdReader == null) { return prop; } return new ObjectIdReferenceProperty(prop, objectIdInfo); } #location 6 #vulnerability type NULL_DEREFERENCE
#fixed code protected SettableBeanProperty _resolvedObjectIdProperty(DeserializationContext ctxt, SettableBeanProperty prop) throws JsonMappingException { ObjectIdInfo objectIdInfo = prop.getObjectIdInfo(); JsonDeserializer<Object> valueDeser = prop.getValueDeserializer(); ObjectIdReader objectIdReader = (valueDeser == null) ? null : valueDeser.getObjectIdReader(); if (objectIdInfo == null && objectIdReader == null) { return prop; } return new ObjectIdReferenceProperty(prop, objectIdInfo); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code void runOnce() throws Exception { final ObjectMapper mapper = getObjectMapper(); Callable<String> writeJson = new Callable<String>() { @Override public String call() throws Exception { Wrapper wrapper = new Wrapper(new TypeOne("test")); return mapper.writeValueAsString(wrapper); } }; int numThreads = 4; ExecutorService executor = Executors.newFixedThreadPool(numThreads); List<Future<String>> jsonFutures = new ArrayList<Future<String>>(); for (int i = 0; i < numThreads; i++) { jsonFutures.add(executor.submit(writeJson)); } executor.shutdown(); executor.awaitTermination(5, TimeUnit.SECONDS); for (Future<String> jsonFuture : jsonFutures) { String json = jsonFuture.get(); JsonNode tree = mapper.readTree(json); JsonNode wrapped = tree.get("hasSubTypes"); if (!wrapped.has("one")) { throw new IllegalStateException("Missing 'one', source: "+json); } } } #location 26 #vulnerability type NULL_DEREFERENCE
#fixed code void runOnce(int round, int max) throws Exception { final ObjectMapper mapper = getObjectMapper(); Callable<String> writeJson = new Callable<String>() { @Override public String call() throws Exception { Wrapper wrapper = new Wrapper(new TypeOne("test")); return mapper.writeValueAsString(wrapper); } }; int numThreads = 4; ExecutorService executor = Executors.newFixedThreadPool(numThreads); List<Future<String>> jsonFutures = new ArrayList<Future<String>>(); for (int i = 0; i < numThreads; i++) { jsonFutures.add(executor.submit(writeJson)); } executor.shutdown(); executor.awaitTermination(5, TimeUnit.SECONDS); for (Future<String> jsonFuture : jsonFutures) { String json = jsonFuture.get(); JsonNode tree = mapper.readTree(json); JsonNode wrapped = tree.get("hasSubTypes"); if (!wrapped.has("one")) { System.out.println("JSON wrong: "+json); throw new IllegalStateException("Round #"+round+"/"+max+" ; missing property 'one', source: "+json); } System.out.println("JSON fine: "+json); } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public void testDeepPrefixedUnwrappingDeserialize() throws Exception { DeepPrefixUnwrap bean = mapper.readValue("{\"u.name\":\"Bubba\",\"u._x\":2,\"u._y\":3}", DeepPrefixUnwrap.class); assertNotNull(bean.unwrapped); assertNotNull(bean.unwrapped.location); assertEquals(2, bean.unwrapped.location.x); assertEquals(3, bean.unwrapped.location.y); assertEquals("Bubba", bean.unwrapped.name); } #location 5 #vulnerability type NULL_DEREFERENCE
#fixed code public void testDeepPrefixedUnwrappingDeserialize() throws Exception { DeepPrefixUnwrap bean = MAPPER.readValue("{\"u.name\":\"Bubba\",\"u._x\":2,\"u._y\":3}", DeepPrefixUnwrap.class); assertNotNull(bean.unwrapped); assertNotNull(bean.unwrapped.location); assertEquals(2, bean.unwrapped.location.x); assertEquals(3, bean.unwrapped.location.y); assertEquals("Bubba", bean.unwrapped.name); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public void testHierarchicConfigRoundTrip() throws Exception { ConfigAlternate input = new ConfigAlternate(123, "Joe", 42); String json = mapper.writeValueAsString(input); ConfigAlternate root = mapper.readValue(json, ConfigAlternate.class); assertEquals(123, root.id); assertNotNull(root.general); assertNotNull(root.general.names); assertNotNull(root.misc); assertEquals("Joe", root.general.names.name); assertEquals(42, root.misc.value); } #location 7 #vulnerability type NULL_DEREFERENCE
#fixed code public void testHierarchicConfigRoundTrip() throws Exception { ConfigAlternate input = new ConfigAlternate(123, "Joe", 42); String json = MAPPER.writeValueAsString(input); ConfigAlternate root = MAPPER.readValue(json, ConfigAlternate.class); assertEquals(123, root.id); assertNotNull(root.general); assertNotNull(root.general.names); assertNotNull(root.misc); assertEquals("Joe", root.general.names.name); assertEquals(42, root.misc.value); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public void testBytestoCharArray() throws Exception { byte[] input = new byte[] { 1, 2, 3, 4, 5, 6, 7 }; // first, do baseline encoding char[] expEncoded = mapper.convertValue(input, String.class).toCharArray(); // then compare char[] actEncoded = mapper.convertValue(input, char[].class); assertArrayEquals(expEncoded, actEncoded); } #location 5 #vulnerability type NULL_DEREFERENCE
#fixed code public void testBytestoCharArray() throws Exception { byte[] input = new byte[] { 1, 2, 3, 4, 5, 6, 7 }; // first, do baseline encoding char[] expEncoded = MAPPER.convertValue(input, String.class).toCharArray(); // then compare char[] actEncoded = MAPPER.convertValue(input, char[].class); assertArrayEquals(expEncoded, actEncoded); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public void testSimpleMapImitation() throws Exception { MapImitator mapHolder = MAPPER.readValue ("{ \"a\" : 3, \"b\" : true }", MapImitator.class); Map<String,Object> result = mapHolder._map; assertEquals(2, result.size()); assertEquals(Integer.valueOf(3), result.get("a")); assertEquals(Boolean.TRUE, result.get("b")); } #location 5 #vulnerability type NULL_DEREFERENCE
#fixed code public void testSimpleMapImitation() throws Exception { MapImitator mapHolder = MAPPER.readValue ("{ \"a\" : 3, \"b\" : true, \"c\":[1,2,3] }", MapImitator.class); Map<String,Object> result = mapHolder._map; assertEquals(3, result.size()); assertEquals(Integer.valueOf(3), result.get("a")); assertEquals(Boolean.TRUE, result.get("b")); Object ob = result.get("c"); assertTrue(ob instanceof List<?>); List<?> l = (List<?>)ob; assertEquals(3, l.size()); assertEquals(Integer.valueOf(3), l.get(2)); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public void testHierarchicConfigDeserialize() throws Exception { ConfigRoot root = mapper.readValue("{\"general.names.name\":\"Bob\",\"misc.value\":3}", ConfigRoot.class); assertNotNull(root.general); assertNotNull(root.general.names); assertNotNull(root.misc); assertEquals(3, root.misc.value); assertEquals("Bob", root.general.names.name); } #location 5 #vulnerability type NULL_DEREFERENCE
#fixed code public void testHierarchicConfigDeserialize() throws Exception { ConfigRoot root = MAPPER.readValue("{\"general.names.name\":\"Bob\",\"misc.value\":3}", ConfigRoot.class); assertNotNull(root.general); assertNotNull(root.general.names); assertNotNull(root.misc); assertEquals(3, root.misc.value); assertEquals("Bob", root.general.names.name); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public void testAtomicReference() throws Exception { ObjectMapper mapper = new ObjectMapper(); AtomicReference<long[]> value = mapper.readValue("[1,2]", new com.fasterxml.jackson.core.type.TypeReference<AtomicReference<long[]>>() { }); Object ob = value.get(); assertNotNull(ob); assertEquals(long[].class, ob.getClass()); long[] longs = (long[]) ob; assertNotNull(longs); assertEquals(2, longs.length); assertEquals(1, longs[0]); assertEquals(2, longs[1]); } #location 6 #vulnerability type NULL_DEREFERENCE
#fixed code public void testAtomicReference() throws Exception { AtomicReference<long[]> value = MAPPER.readValue("[1,2]", new com.fasterxml.jackson.core.type.TypeReference<AtomicReference<long[]>>() { }); Object ob = value.get(); assertNotNull(ob); assertEquals(long[].class, ob.getClass()); long[] longs = (long[]) ob; assertNotNull(longs); assertEquals(2, longs.length); assertEquals(1, longs[0]); assertEquals(2, longs[1]); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public <T> MappingIterator<T> readValues(File src) throws IOException, JsonProcessingException { if (_dataFormatReaders != null) { return _detectBindAndReadValues( _dataFormatReaders.findFormat(_inputStream(src)), false); } return _bindAndReadValues(considerFilter(_parserFactory.createParser(src))); } #location 8 #vulnerability type RESOURCE_LEAK
#fixed code public <T> MappingIterator<T> readValues(File src) throws IOException, JsonProcessingException { if (_dataFormatReaders != null) { return _detectBindAndReadValues( _dataFormatReaders.findFormat(_inputStream(src)), false); } return _bindAndReadValues(_considerFilter(_parserFactory.createParser(src))); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public void testRootBeans() throws Exception { final String JSON = aposToQuotes("{'a':3} {'b':5}"); MappingIterator<Bean> it = MAPPER.readerFor(Bean.class).readValues(JSON); // First one should be fine assertTrue(it.hasNextValue()); Bean bean = it.nextValue(); assertEquals(3, bean.a); // but second one not try { bean = it.nextValue(); fail("Should not have succeeded"); } catch (JsonMappingException e) { verifyException(e, "Unrecognized field"); } // 24-Mar-2015, tatu: With 2.5, best we can do is to avoid infinite loop; // also, since the next token is END_OBJECT, will produce empty Object assertTrue(it.hasNextValue()); bean = it.nextValue(); assertEquals(0, bean.a); // and we should be done now assertFalse(it.hasNextValue()); it.close(); } #location 15 #vulnerability type RESOURCE_LEAK
#fixed code public void testRootBeans() throws Exception { final String JSON = aposToQuotes("{'a':3} {'x':5}"); MappingIterator<Bean> it = MAPPER.readerFor(Bean.class).readValues(JSON); // First one should be fine assertTrue(it.hasNextValue()); Bean bean = it.nextValue(); assertEquals(3, bean.a); // but second one not try { bean = it.nextValue(); fail("Should not have succeeded"); } catch (JsonMappingException e) { verifyException(e, "Unrecognized field \"x\""); } // 21-May-2015, tatu: With [databind#734], recovery, we now know there's no more data! assertFalse(it.hasNextValue()); it.close(); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @SuppressWarnings("resource") public <T> MappingIterator<T> readValues(Reader src) throws IOException, JsonProcessingException { if (_dataFormatReaders != null) { _reportUndetectableSource(src); } JsonParser p = considerFilter(_parserFactory.createParser(src)); _initForMultiRead(p); p.nextToken(); DeserializationContext ctxt = createDeserializationContext(p); return _newIterator(p, ctxt, _findRootDeserializer(ctxt), true); } #location 12 #vulnerability type RESOURCE_LEAK
#fixed code @SuppressWarnings("resource") public <T> MappingIterator<T> readValues(Reader src) throws IOException, JsonProcessingException { if (_dataFormatReaders != null) { _reportUndetectableSource(src); } JsonParser p = _considerFilter(_parserFactory.createParser(src)); _initForMultiRead(p); p.nextToken(); DeserializationContext ctxt = createDeserializationContext(p); return _newIterator(p, ctxt, _findRootDeserializer(ctxt), true); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public void testAtomicBoolean() throws Exception { ObjectMapper mapper = new ObjectMapper(); AtomicBoolean b = mapper.readValue("true", AtomicBoolean.class); assertTrue(b.get()); } #location 5 #vulnerability type NULL_DEREFERENCE
#fixed code public void testAtomicBoolean() throws Exception { AtomicBoolean b = MAPPER.readValue("true", AtomicBoolean.class); assertTrue(b.get()); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Override public PropertyMetadata getMetadata() { final Boolean b = _findRequired(); final String desc = _findDescription(); final Integer idx = _findIndex(); final String def = _findDefaultValue(); if (b == null && idx == null && def == null) { return (desc == null) ? PropertyMetadata.STD_REQUIRED_OR_OPTIONAL : PropertyMetadata.STD_REQUIRED_OR_OPTIONAL.withDescription(desc); } return PropertyMetadata.construct(b.booleanValue(), desc, idx, def); } #location 11 #vulnerability type NULL_DEREFERENCE
#fixed code @Override public PropertyMetadata getMetadata() { final Boolean b = _findRequired(); final String desc = _findDescription(); final Integer idx = _findIndex(); final String def = _findDefaultValue(); if (b == null && idx == null && def == null) { return (desc == null) ? PropertyMetadata.STD_REQUIRED_OR_OPTIONAL : PropertyMetadata.STD_REQUIRED_OR_OPTIONAL.withDescription(desc); } return PropertyMetadata.construct(b, desc, idx, def); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Override public String idFromValue(Object value) { Class<?> cls = _typeFactory.constructType(value.getClass()).getRawClass(); final String key = cls.getName(); String name; synchronized (_typeToId) { name = _typeToId.get(key); if (name == null) { // 24-Feb-2011, tatu: As per [JACKSON-498], may need to dynamically look up name // can either throw an exception, or use default name... if (_config.isAnnotationProcessingEnabled()) { BeanDescription beanDesc = _config.introspectClassAnnotations(cls); name = _config.getAnnotationIntrospector().findTypeName(beanDesc.getClassInfo()); } if (name == null) { // And if still not found, let's choose default? name = _defaultTypeId(cls); } _typeToId.put(key, name); } } return name; } #location 4 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code @Override public String idFromValue(Object value) { return idFromClass(value.getClass()); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public <T> MappingIterator<T> readValues(byte[] src, int offset, int length) throws IOException, JsonProcessingException { if (_dataFormatReaders != null) { return _detectBindAndReadValues(_dataFormatReaders.findFormat(src, offset, length), false); } return _bindAndReadValues(considerFilter(_parserFactory.createParser(src))); } #location 7 #vulnerability type RESOURCE_LEAK
#fixed code public <T> MappingIterator<T> readValues(byte[] src, int offset, int length) throws IOException, JsonProcessingException { if (_dataFormatReaders != null) { return _detectBindAndReadValues(_dataFormatReaders.findFormat(src, offset, length), false); } return _bindAndReadValues(_considerFilter(_parserFactory.createParser(src))); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public void testAtomicLong() throws Exception { ObjectMapper mapper = new ObjectMapper(); AtomicLong value = mapper.readValue("12345678901", AtomicLong.class); assertEquals(12345678901L, value.get()); } #location 5 #vulnerability type NULL_DEREFERENCE
#fixed code public void testAtomicLong() throws Exception { AtomicLong value = MAPPER.readValue("12345678901", AtomicLong.class); assertEquals(12345678901L, value.get()); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public void testMapUnwrapDeserialize() throws Exception { MapUnwrap root = mapper.readValue("{\"map.test\": 6}", MapUnwrap.class); assertEquals(1, root.map.size()); assertEquals(6, ((Number)root.map.get("test")).intValue()); } #location 5 #vulnerability type NULL_DEREFERENCE
#fixed code public void testMapUnwrapDeserialize() throws Exception { MapUnwrap root = MAPPER.readValue("{\"map.test\": 6}", MapUnwrap.class); assertEquals(1, root.map.size()); assertEquals(6, ((Number)root.map.get("test")).intValue()); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public void withTree749() throws Exception { Map<KeyEnum, Object> inputMap = new LinkedHashMap<KeyEnum, Object>(); Map<TestEnum, Map<String, String>> replacements = new LinkedHashMap<TestEnum, Map<String, String>>(); Map<String, String> reps = new LinkedHashMap<String, String>(); reps.put("1", "one"); replacements.put(TestEnum.GREEN, reps); inputMap.put(KeyEnum.replacements, replacements); ObjectMapper mapper = TestEnumModule.setupObjectMapper(new ObjectMapper()); JsonNode tree = mapper.valueToTree(inputMap); ObjectNode ob = (ObjectNode) tree; JsonNode inner = ob.get("replacements"); String firstFieldName = inner.fieldNames().next(); assertEquals("green", firstFieldName); } #location 12 #vulnerability type NULL_DEREFERENCE
#fixed code public void withTree749() throws Exception { ObjectMapper mapper = new ObjectMapper().registerModule(new TestEnumModule()); Map<KeyEnum, Object> inputMap = new LinkedHashMap<KeyEnum, Object>(); Map<TestEnum, Map<String, String>> replacements = new LinkedHashMap<TestEnum, Map<String, String>>(); Map<String, String> reps = new LinkedHashMap<String, String>(); reps.put("1", "one"); replacements.put(TestEnum.GREEN, reps); inputMap.put(KeyEnum.replacements, replacements); JsonNode tree = mapper.valueToTree(inputMap); ObjectNode ob = (ObjectNode) tree; JsonNode inner = ob.get("replacements"); String firstFieldName = inner.fieldNames().next(); assertEquals("green", firstFieldName); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public <T> MappingIterator<T> readValues(InputStream src) throws IOException, JsonProcessingException { if (_dataFormatReaders != null) { return _detectBindAndReadValues(_dataFormatReaders.findFormat(src), false); } return _bindAndReadValues(considerFilter(_parserFactory.createParser(src))); } #location 8 #vulnerability type RESOURCE_LEAK
#fixed code public <T> MappingIterator<T> readValues(InputStream src) throws IOException, JsonProcessingException { if (_dataFormatReaders != null) { return _detectBindAndReadValues(_dataFormatReaders.findFormat(src), false); } return _bindAndReadValues(_considerFilter(_parserFactory.createParser(src))); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public void testAtomicInt() throws Exception { ObjectMapper mapper = new ObjectMapper(); AtomicInteger value = mapper.readValue("13", AtomicInteger.class); assertEquals(13, value.get()); } #location 5 #vulnerability type NULL_DEREFERENCE
#fixed code public void testAtomicInt() throws Exception { AtomicInteger value = MAPPER.readValue("13", AtomicInteger.class); assertEquals(13, value.get()); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public <T> MappingIterator<T> readValues(URL src) throws IOException, JsonProcessingException { if (_dataFormatReaders != null) { return _detectBindAndReadValues( _dataFormatReaders.findFormat(_inputStream(src)), true); } return _bindAndReadValues(considerFilter(_parserFactory.createParser(src))); } #location 8 #vulnerability type RESOURCE_LEAK
#fixed code public <T> MappingIterator<T> readValues(URL src) throws IOException, JsonProcessingException { if (_dataFormatReaders != null) { return _detectBindAndReadValues( _dataFormatReaders.findFormat(_inputStream(src)), true); } return _bindAndReadValues(_considerFilter(_parserFactory.createParser(src))); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public void testPrefixedUnwrapping() throws Exception { PrefixUnwrap bean = mapper.readValue("{\"name\":\"Axel\",\"_x\":4,\"_y\":7}", PrefixUnwrap.class); assertNotNull(bean); assertEquals("Axel", bean.name); assertNotNull(bean.location); assertEquals(4, bean.location.x); assertEquals(7, bean.location.y); } #location 5 #vulnerability type NULL_DEREFERENCE
#fixed code public void testPrefixedUnwrapping() throws Exception { PrefixUnwrap bean = MAPPER.readValue("{\"name\":\"Axel\",\"_x\":4,\"_y\":7}", PrefixUnwrap.class); assertNotNull(bean); assertEquals("Axel", bean.name); assertNotNull(bean.location); assertEquals(4, bean.location.x); assertEquals(7, bean.location.y); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code protected SiteMap processText(String sitemapUrl, byte[] content) throws IOException { LOG.debug("Processing textual Sitemap"); SiteMap textSiteMap = new SiteMap(sitemapUrl); textSiteMap.setType(SitemapType.TEXT); BOMInputStream bomIs = new BOMInputStream(new ByteArrayInputStream(content)); @SuppressWarnings("resource") BufferedReader reader = new BufferedReader(new InputStreamReader(bomIs, "UTF-8")); String line; int i = 1; while ((line = reader.readLine()) != null) { if (line.length() > 0 && i <= MAX_URLS) { addUrlIntoSitemap(line, textSiteMap, null, null, null, i++); } } textSiteMap.setProcessed(true); return textSiteMap; } #location 20 #vulnerability type RESOURCE_LEAK
#fixed code protected SiteMap processText(String sitemapUrl, byte[] content) throws IOException { LOG.debug("Processing textual Sitemap"); SiteMap textSiteMap = new SiteMap(sitemapUrl); textSiteMap.setType(SitemapType.TEXT); BOMInputStream bomIs = new BOMInputStream(new ByteArrayInputStream(content)); @SuppressWarnings("resource") BufferedReader reader = new BufferedReader(new InputStreamReader(bomIs, UTF_8)); String line; int i = 1; while ((line = reader.readLine()) != null) { if (line.length() > 0 && i <= MAX_URLS) { addUrlIntoSitemap(line, textSiteMap, null, null, null, i++); } } textSiteMap.setProcessed(true); return textSiteMap; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code private AbstractSiteMap processXml(URL sitemapUrl, byte[] xmlContent) throws UnknownFormatException { BOMInputStream bomIs = new BOMInputStream(new ByteArrayInputStream(xmlContent)); InputSource is = new InputSource(); is.setCharacterStream(new BufferedReader(new InputStreamReader(bomIs))); return processXml(sitemapUrl, is); } #location 5 #vulnerability type RESOURCE_LEAK
#fixed code private AbstractSiteMap processXml(URL sitemapUrl, byte[] xmlContent) throws UnknownFormatException { BOMInputStream bomIs = new BOMInputStream(new ByteArrayInputStream(xmlContent)); InputSource is = new InputSource(); try { is.setCharacterStream(new BufferedReader(new InputStreamReader(bomIs, "UTF-8"))); } catch (UnsupportedEncodingException e) { IOUtils.closeQuietly(bomIs); throw new RuntimeException("Impossible exception", e); } return processXml(sitemapUrl, is); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void testVideosSitemap() throws UnknownFormatException, IOException { SiteMapParser parser = new SiteMapParser(); parser.enableExtension(Extension.VIDEO); String contentType = "text/xml"; byte[] content = SiteMapParserTest.getResourceAsBytes("src/test/resources/sitemaps/extension/sitemap-videos.xml"); URL url = new URL("http://www.example.com/sitemap-video.xml"); AbstractSiteMap asm = parser.parseSiteMap(contentType, content, url); assertEquals(false, asm.isIndex()); assertEquals(true, asm instanceof SiteMap); SiteMap sm = (SiteMap) asm; assertEquals(1, sm.getSiteMapUrls().size()); VideoAttributes expectedVideoAttributes = new VideoAttributes(new URL("http://www.example.com/thumbs/123.jpg"), "Grilling steaks for summer", "Alkis shows you how to get perfectly done steaks every time", new URL("http://www.example.com/video123.flv"), new URL("http://www.example.com/videoplayer.swf?video=123")); expectedVideoAttributes.setDuration(600); ZonedDateTime dt = ZonedDateTime.parse("2009-11-05T19:20:30+08:00"); expectedVideoAttributes.setExpirationDate(dt); dt = ZonedDateTime.parse("2007-11-05T19:20:30+08:00"); expectedVideoAttributes.setPublicationDate(dt); expectedVideoAttributes.setRating(4.2f); expectedVideoAttributes.setViewCount(12345); expectedVideoAttributes.setFamilyFriendly(true); expectedVideoAttributes.setTags(new String[] { "sample_tag1", "sample_tag2" }); expectedVideoAttributes.setAllowedCountries(new String[] { "IE", "GB", "US", "CA" }); expectedVideoAttributes.setGalleryLoc(new URL("http://cooking.example.com")); expectedVideoAttributes.setGalleryTitle("Cooking Videos"); expectedVideoAttributes.setPrices(new VideoAttributes.VideoPrice[] { new VideoAttributes.VideoPrice("EUR", 1.99f, VideoAttributes.VideoPriceType.own) }); expectedVideoAttributes.setRequiresSubscription(true); expectedVideoAttributes.setUploader("GrillyMcGrillerson"); expectedVideoAttributes.setUploaderInfo(new URL("http://www.example.com/users/grillymcgrillerson")); expectedVideoAttributes.setLive(false); for (SiteMapURL su : sm.getSiteMapUrls()) { assertNotNull(su.getAttributesForExtension(Extension.VIDEO)); VideoAttributes attr = (VideoAttributes) su.getAttributesForExtension(Extension.VIDEO)[0]; assertEquals(expectedVideoAttributes, attr); } } #location 37 #vulnerability type NULL_DEREFERENCE
#fixed code @Test public void testVideosSitemap() throws UnknownFormatException, IOException { SiteMapParser parser = new SiteMapParser(); parser.enableExtension(Extension.VIDEO); String contentType = "text/xml"; byte[] content = SiteMapParserTest.getResourceAsBytes("src/test/resources/sitemaps/extension/sitemap-videos.xml"); URL url = new URL("http://www.example.com/sitemap-video.xml"); AbstractSiteMap asm = parser.parseSiteMap(contentType, content, url); assertEquals(false, asm.isIndex()); assertEquals(true, asm instanceof SiteMap); SiteMap sm = (SiteMap) asm; assertEquals(2, sm.getSiteMapUrls().size()); Iterator<SiteMapURL> siter = sm.getSiteMapUrls().iterator(); // first <loc> element: nearly all video attributes VideoAttributes expectedVideoAttributes = new VideoAttributes(new URL("http://www.example.com/thumbs/123.jpg"), "Grilling steaks for summer", "Alkis shows you how to get perfectly done steaks every time", new URL("http://www.example.com/video123.flv"), new URL("http://www.example.com/videoplayer.swf?video=123")); expectedVideoAttributes.setDuration(600); ZonedDateTime dt = ZonedDateTime.parse("2009-11-05T19:20:30+08:00"); expectedVideoAttributes.setExpirationDate(dt); dt = ZonedDateTime.parse("2007-11-05T19:20:30+08:00"); expectedVideoAttributes.setPublicationDate(dt); expectedVideoAttributes.setRating(4.2f); expectedVideoAttributes.setViewCount(12345); expectedVideoAttributes.setFamilyFriendly(true); expectedVideoAttributes.setTags(new String[] { "sample_tag1", "sample_tag2" }); expectedVideoAttributes.setAllowedCountries(new String[] { "IE", "GB", "US", "CA" }); expectedVideoAttributes.setGalleryLoc(new URL("http://cooking.example.com")); expectedVideoAttributes.setGalleryTitle("Cooking Videos"); expectedVideoAttributes.setPrices(new VideoAttributes.VideoPrice[] { new VideoAttributes.VideoPrice("EUR", 1.99f, VideoAttributes.VideoPriceType.own) }); expectedVideoAttributes.setRequiresSubscription(true); expectedVideoAttributes.setUploader("GrillyMcGrillerson"); expectedVideoAttributes.setUploaderInfo(new URL("http://www.example.com/users/grillymcgrillerson")); expectedVideoAttributes.setLive(false); VideoAttributes attr = (VideoAttributes) siter.next().getAttributesForExtension(Extension.VIDEO)[0]; assertNotNull(attr); assertEquals(expectedVideoAttributes, attr); // locale-specific number format in <video:price>, test #220 expectedVideoAttributes = new VideoAttributes(new URL("http://www.example.com/thumbs/123-2.jpg"), "Grilling steaks for summer, episode 2", "Alkis shows you how to get perfectly done steaks every time", new URL("http://www.example.com/video123-2.flv"), null); expectedVideoAttributes.setPrices(new VideoAttributes.VideoPrice[] { new VideoAttributes.VideoPrice("EUR", null, VideoAttributes.VideoPriceType.own) }); attr = (VideoAttributes) siter.next().getAttributesForExtension(Extension.VIDEO)[0]; assertNotNull(attr); assertEquals(expectedVideoAttributes, attr); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code protected AbstractSiteMap processXml(URL sitemapUrl, byte[] xmlContent) throws UnknownFormatException { BOMInputStream bomIs = new BOMInputStream(new ByteArrayInputStream(xmlContent)); InputSource is = new InputSource(); try { is.setCharacterStream(new BufferedReader(new InputStreamReader(bomIs, "UTF-8"))); } catch (UnsupportedEncodingException e) { IOUtils.closeQuietly(bomIs); throw new RuntimeException("Impossible exception", e); } return processXml(sitemapUrl, is); } #location 6 #vulnerability type RESOURCE_LEAK
#fixed code protected AbstractSiteMap processXml(URL sitemapUrl, byte[] xmlContent) throws UnknownFormatException { BOMInputStream bomIs = new BOMInputStream(new ByteArrayInputStream(xmlContent)); InputSource is = new InputSource(); is.setCharacterStream(new BufferedReader(new InputStreamReader(bomIs, UTF_8))); return processXml(sitemapUrl, is); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public boolean validate(UserPersonalInfo info) { validator.validate(info); if(validator.hasErrors()){ return false; } if (info.getUser() == null) { validator.add(new ValidationMessage("user.errors.wrong", "error")); } if(!info.getUser().getEmail().equals(info.getEmail())){ emailValidator.validate(info.getEmail()); } if(info.getBirthDate().getYear() > DateTime.now().getYear()-12){ validator.add(new ValidationMessage("user.errors.invalid_birth_date.min_age", "error")); } if(!info.getUser().getName().equals(info.getName())){ DateTime nameLastTouchedAt = info.getUser().getNameLastTouchedAt(); if(nameLastTouchedAt.isAfter(new DateTime().minusDays(30))){ validator.add(new ValidationMessage("user.errors.name.min_time", "error", nameLastTouchedAt.plusDays(30).toString())); } } return !validator.hasErrors(); } #location 13 #vulnerability type NULL_DEREFERENCE
#fixed code public boolean validate(UserPersonalInfo info) { validator.validate(info); if(validator.hasErrors()){ return false; } if (info.getUser() == null) { validator.add(new ValidationMessage("user.errors.wrong", "error")); } if (!info.getUser().getEmail().equals(info.getEmail())){ emailValidator.validate(info.getEmail()); } if (info.getBirthDate() != null && info.getBirthDate().getYear() > DateTime.now().getYear()-12){ validator.add(new ValidationMessage("user.errors.invalid_birth_date.min_age", "error")); } if(!info.getUser().getName().equals(info.getName())){ DateTime nameLastTouchedAt = info.getUser().getNameLastTouchedAt(); if(nameLastTouchedAt.isAfter(new DateTime().minusDays(30))){ validator.add(new ValidationMessage("user.errors.name.min_time", "error", nameLastTouchedAt.plusDays(30).toString())); } } return !validator.hasErrors(); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void moderator_should_approve_question_information() throws Exception { Question question = question("question title", "question description", author); Information approvedInfo = new QuestionInformation("edited title", "edited desc", new LoggedUser(otherUser, null), new ArrayList<Tag>(), "comment"); moderator.approve(question, approvedInfo); assertEquals(approvedInfo, question.getInformation()); assertTrue(question.getInformation().isModerated()); } #location 10 #vulnerability type NULL_DEREFERENCE
#fixed code @Test public void moderator_should_approve_question_information() throws Exception { Information approvedInfo = new QuestionInformation("edited title", "edited desc", new LoggedUser(otherUser, null), new ArrayList<Tag>(), "comment"); moderator.approve(myQuestion, approvedInfo); assertEquals(approvedInfo, myQuestion.getInformation()); assertTrue(myQuestion.getInformation().isModerated()); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public boolean validate(UserPersonalInfo info) { validator.validate(info); if (info.getUser() == null) { validator.add(new ValidationMessage("error","user.errors.wrong")); } if(!info.getUser().getName().equals(info.getName())){ userNameValidator.validate(info.getName()); } if (!info.getUser().getEmail().equals(info.getEmail())){ emailValidator.validate(info.getEmail()); } return !validator.hasErrors(); } #location 9 #vulnerability type NULL_DEREFERENCE
#fixed code public boolean validate(UserPersonalInfo info) { validator.validate(info); if (info.getUser() == null) { validator.add(new ValidationMessage("user.errors.wrong", "error")); } if(!info.getUser().getName().equals(info.getName())){ userNameValidator.validate(info.getName()); } if(!info.getUser().getEmail().equals(info.getEmail())){ emailValidator.validate(info.getEmail()); } if(info.getUser().getNameLastTouchedAt() != null){ if(info.getUser().getNameLastTouchedAt().isAfter(new DateTime().minusDays(30))){ validator.add(new ValidationMessage("user.errors.name.min_time", "error")); } } return !validator.hasErrors(); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public void testAlternateDefaultEncoding(final String cT, final String bomEnc, final String streamEnc, final String prologEnc, final String alternateEnc) throws Exception { try { final InputStream is; if (prologEnc == null) { is = getXmlStream(bomEnc, XML1, streamEnc, prologEnc); } else { is = getXmlStream(bomEnc, XML3, streamEnc, prologEnc); } XmlReader.setDefaultEncoding(alternateEnc); final XmlReader xmlReader = new XmlReader(is, cT, false); if (!streamEnc.equals("UTF-16")) { // we can not assert things here becuase UTF-8, US-ASCII and // ISO-8859-1 look alike for the chars used for detection } else { final String enc; if (alternateEnc != null) { enc = alternateEnc; } else { enc = streamEnc; } assertEquals(xmlReader.getEncoding().substring(0, streamEnc.length()), streamEnc); } } finally { XmlReader.setDefaultEncoding(null); } } #location 22 #vulnerability type RESOURCE_LEAK
#fixed code public void testAlternateDefaultEncoding(final String cT, final String bomEnc, final String streamEnc, final String prologEnc, final String alternateEnc) throws Exception { XmlReader xmlReader = null; try { final InputStream is; if (prologEnc == null) { is = getXmlStream(bomEnc, XML1, streamEnc, prologEnc); } else { is = getXmlStream(bomEnc, XML3, streamEnc, prologEnc); } XmlReader.setDefaultEncoding(alternateEnc); xmlReader = new XmlReader(is, cT, false); if (!streamEnc.equals("UTF-16")) { // we can not assert things here becuase UTF-8, US-ASCII and // ISO-8859-1 look alike for the chars used for detection } else { assertEquals(xmlReader.getEncoding().substring(0, streamEnc.length()), streamEnc); } } finally { XmlReader.setDefaultEncoding(null); if (xmlReader != null) { xmlReader.close(); } } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code protected void testRawNoBomValid(final String encoding) throws Exception { InputStream is = getXmlStream("no-bom", XML1, encoding, encoding); XmlReader xmlReader = new XmlReader(is, false); assertEquals(xmlReader.getEncoding(), "UTF-8"); is = getXmlStream("no-bom", XML2, encoding, encoding); xmlReader = new XmlReader(is); assertEquals(xmlReader.getEncoding(), "UTF-8"); is = getXmlStream("no-bom", XML3, encoding, encoding); xmlReader = new XmlReader(is); assertEquals(xmlReader.getEncoding(), encoding); is = getXmlStream("no-bom", XML4, encoding, encoding); xmlReader = new XmlReader(is); assertEquals(xmlReader.getEncoding(), encoding); is = getXmlStream("no-bom", XML5, encoding, encoding); xmlReader = new XmlReader(is); assertEquals(xmlReader.getEncoding(), encoding); } #location 4 #vulnerability type RESOURCE_LEAK
#fixed code protected void testRawNoBomValid(final String encoding) throws Exception { checkEncoding(XML1, encoding, "UTF-8"); checkEncoding(XML2, encoding, "UTF-8"); checkEncoding(XML3, encoding, encoding); checkEncoding(XML4, encoding, encoding); checkEncoding(XML5, encoding, encoding); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code protected void testRawNoBomValid(final String encoding) throws Exception { InputStream is = getXmlStream("no-bom", XML1, encoding, encoding); XmlReader xmlReader = new XmlReader(is, false); assertEquals(xmlReader.getEncoding(), "UTF-8"); is = getXmlStream("no-bom", XML2, encoding, encoding); xmlReader = new XmlReader(is); assertEquals(xmlReader.getEncoding(), "UTF-8"); is = getXmlStream("no-bom", XML3, encoding, encoding); xmlReader = new XmlReader(is); assertEquals(xmlReader.getEncoding(), encoding); is = getXmlStream("no-bom", XML4, encoding, encoding); xmlReader = new XmlReader(is); assertEquals(xmlReader.getEncoding(), encoding); is = getXmlStream("no-bom", XML5, encoding, encoding); xmlReader = new XmlReader(is); assertEquals(xmlReader.getEncoding(), encoding); } #location 12 #vulnerability type RESOURCE_LEAK
#fixed code protected void testRawNoBomValid(final String encoding) throws Exception { checkEncoding(XML1, encoding, "UTF-8"); checkEncoding(XML2, encoding, "UTF-8"); checkEncoding(XML3, encoding, encoding); checkEncoding(XML4, encoding, encoding); checkEncoding(XML5, encoding, encoding); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code private static Date parseUsingMask(final String[] masks, String sDate) { sDate = sDate != null ? sDate.trim() : null; ParsePosition pp = null; Date d = null; for (int i = 0; d == null && i < masks.length; i++) { final DateFormat df = new SimpleDateFormat(masks[i], Locale.US); // df.setLenient(false); df.setLenient(true); try { pp = new ParsePosition(0); d = df.parse(sDate, pp); if (pp.getIndex() != sDate.length()) { d = null; } // System.out.println("pp["+pp.getIndex()+"] s["+sDate+" m["+masks[i]+"] d["+d+"]"); } catch (final Exception ex1) { // System.out.println("s: "+sDate+" m: "+masks[i]+" d: "+null); } } return d; } #location 12 #vulnerability type NULL_DEREFERENCE
#fixed code private static Date parseUsingMask(final String[] masks, String sDate) { if (sDate != null) { sDate = sDate.trim(); } ParsePosition pp = null; Date d = null; for (int i = 0; d == null && i < masks.length; i++) { final DateFormat df = new SimpleDateFormat(masks[i], Locale.US); // df.setLenient(false); df.setLenient(true); try { pp = new ParsePosition(0); d = df.parse(sDate, pp); if (pp.getIndex() != sDate.length()) { d = null; } // System.out.println("pp["+pp.getIndex()+"] s["+sDate+" m["+masks[i]+"] d["+d+"]"); } catch (final Exception ex1) { // System.out.println("s: "+sDate+" m: "+masks[i]+" d: "+null); } } return d; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public void testAlternateDefaultEncoding(final String cT, final String bomEnc, final String streamEnc, final String prologEnc, final String alternateEnc) throws Exception { try { final InputStream is; if (prologEnc == null) { is = getXmlStream(bomEnc, XML1, streamEnc, prologEnc); } else { is = getXmlStream(bomEnc, XML3, streamEnc, prologEnc); } XmlReader.setDefaultEncoding(alternateEnc); final XmlReader xmlReader = new XmlReader(is, cT, false); if (!streamEnc.equals("UTF-16")) { // we can not assert things here becuase UTF-8, US-ASCII and // ISO-8859-1 look alike for the chars used for detection } else { final String enc; if (alternateEnc != null) { enc = alternateEnc; } else { enc = streamEnc; } assertEquals(xmlReader.getEncoding().substring(0, streamEnc.length()), streamEnc); } } finally { XmlReader.setDefaultEncoding(null); } } #location 12 #vulnerability type RESOURCE_LEAK
#fixed code public void testAlternateDefaultEncoding(final String cT, final String bomEnc, final String streamEnc, final String prologEnc, final String alternateEnc) throws Exception { XmlReader xmlReader = null; try { final InputStream is; if (prologEnc == null) { is = getXmlStream(bomEnc, XML1, streamEnc, prologEnc); } else { is = getXmlStream(bomEnc, XML3, streamEnc, prologEnc); } XmlReader.setDefaultEncoding(alternateEnc); xmlReader = new XmlReader(is, cT, false); if (!streamEnc.equals("UTF-16")) { // we can not assert things here becuase UTF-8, US-ASCII and // ISO-8859-1 look alike for the chars used for detection } else { assertEquals(xmlReader.getEncoding().substring(0, streamEnc.length()), streamEnc); } } finally { XmlReader.setDefaultEncoding(null); if (xmlReader != null) { xmlReader.close(); } } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code protected void testRawNoBomValid(final String encoding) throws Exception { InputStream is = getXmlStream("no-bom", XML1, encoding, encoding); XmlReader xmlReader = new XmlReader(is, false); assertEquals(xmlReader.getEncoding(), "UTF-8"); is = getXmlStream("no-bom", XML2, encoding, encoding); xmlReader = new XmlReader(is); assertEquals(xmlReader.getEncoding(), "UTF-8"); is = getXmlStream("no-bom", XML3, encoding, encoding); xmlReader = new XmlReader(is); assertEquals(xmlReader.getEncoding(), encoding); is = getXmlStream("no-bom", XML4, encoding, encoding); xmlReader = new XmlReader(is); assertEquals(xmlReader.getEncoding(), encoding); is = getXmlStream("no-bom", XML5, encoding, encoding); xmlReader = new XmlReader(is); assertEquals(xmlReader.getEncoding(), encoding); } #location 12 #vulnerability type RESOURCE_LEAK
#fixed code protected void testRawNoBomValid(final String encoding) throws Exception { checkEncoding(XML1, encoding, "UTF-8"); checkEncoding(XML2, encoding, "UTF-8"); checkEncoding(XML3, encoding, encoding); checkEncoding(XML4, encoding, encoding); checkEncoding(XML5, encoding, encoding); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code protected void testRawBomInvalid(final String bomEnc, final String streamEnc, final String prologEnc) throws Exception { final InputStream is = getXmlStream(bomEnc, XML3, streamEnc, prologEnc); try { final XmlReader xmlReader = new XmlReader(is, false); fail("It should have failed for BOM " + bomEnc + ", streamEnc " + streamEnc + " and prologEnc " + prologEnc); } catch (final IOException ex) { assertTrue(ex.getMessage().indexOf("Invalid encoding,") > -1); } } #location 4 #vulnerability type RESOURCE_LEAK
#fixed code protected void testRawBomInvalid(final String bomEnc, final String streamEnc, final String prologEnc) throws Exception { final InputStream is = getXmlStream(bomEnc, XML3, streamEnc, prologEnc); try { final XmlReader xmlReader = new XmlReader(is, false); fail("It should have failed for BOM " + bomEnc + ", streamEnc " + streamEnc + " and prologEnc " + prologEnc); xmlReader.close(); } catch (final IOException ex) { assertTrue(ex.getMessage().indexOf("Invalid encoding,") > -1); } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Override public SyndFeedInfo remove(final URL url) { SyndFeedInfo info = null; final String fileName = cachePath + File.separator + "feed_" + replaceNonAlphanumeric(url.toString(), '_').trim(); FileInputStream fis; try { fis = new FileInputStream(fileName); final ObjectInputStream ois = new ObjectInputStream(fis); info = (SyndFeedInfo) ois.readObject(); fis.close(); final File file = new File(fileName); if (file.exists()) { file.delete(); } } catch (final FileNotFoundException fnfe) { // That's OK, we'l return null } catch (final ClassNotFoundException cnfe) { // Error writing to cahce is fatal throw new RuntimeException("Attempting to read from cache", cnfe); } catch (final IOException fnfe) { // Error writing to cahce is fatal throw new RuntimeException("Attempting to read from cache", fnfe); } return info; } #location 16 #vulnerability type RESOURCE_LEAK
#fixed code @Override public SyndFeedInfo remove(final URL url) { SyndFeedInfo info = null; final String fileName = cachePath + File.separator + "feed_" + replaceNonAlphanumeric(url.toString(), '_').trim(); FileInputStream fis = null; ObjectInputStream ois = null; try { fis = new FileInputStream(fileName); ois = new ObjectInputStream(fis); info = (SyndFeedInfo) ois.readObject(); final File file = new File(fileName); if (file.exists()) { file.delete(); } } catch (final FileNotFoundException fnfe) { // That's OK, we'l return null } catch (final ClassNotFoundException cnfe) { // Error writing to cahce is fatal throw new RuntimeException("Attempting to read from cache", cnfe); } catch (final IOException fnfe) { // Error writing to cahce is fatal throw new RuntimeException("Attempting to read from cache", fnfe); } finally { if (fis != null) { try { fis.close(); } catch (final IOException e) { } } if (ois != null) { try { ois.close(); } catch (final IOException e) { } } } return info; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public void testHttpValid(final String cT, final String bomEnc, final String streamEnc, final String prologEnc) throws Exception { final InputStream is; if (prologEnc == null) { is = getXmlStream(bomEnc, XML1, streamEnc, prologEnc); } else { is = getXmlStream(bomEnc, XML3, streamEnc, prologEnc); } final XmlReader xmlReader = new XmlReader(is, cT, false); if (!streamEnc.equals("UTF-16")) { // we can not assert things here becuase UTF-8, US-ASCII and // ISO-8859-1 look alike for the chars used for detection } else { assertEquals(xmlReader.getEncoding().substring(0, streamEnc.length()), streamEnc); } } #location 9 #vulnerability type RESOURCE_LEAK
#fixed code public void testHttpValid(final String cT, final String bomEnc, final String streamEnc, final String prologEnc) throws Exception { final InputStream is; if (prologEnc == null) { is = getXmlStream(bomEnc, XML1, streamEnc, prologEnc); } else { is = getXmlStream(bomEnc, XML3, streamEnc, prologEnc); } final XmlReader xmlReader = new XmlReader(is, cT, false); if (!streamEnc.equals("UTF-16")) { // we can not assert things here becuase UTF-8, US-ASCII and // ISO-8859-1 look alike for the chars used for detection } else { assertEquals(xmlReader.getEncoding().substring(0, streamEnc.length()), streamEnc); } xmlReader.close(); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public void testEncodingAttributeXML() throws Exception { final InputStream is = new ByteArrayInputStream(ENCODING_ATTRIBUTE_XML.getBytes()); final XmlReader xmlReader = new XmlReader(is, "", true); assertEquals(xmlReader.getEncoding(), "UTF-8"); } #location 4 #vulnerability type RESOURCE_LEAK
#fixed code public void testEncodingAttributeXML() throws Exception { final InputStream is = new ByteArrayInputStream(ENCODING_ATTRIBUTE_XML.getBytes()); final XmlReader xmlReader = new XmlReader(is, "", true); assertEquals(xmlReader.getEncoding(), "UTF-8"); xmlReader.close(); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code protected void testRawNoBomInvalid(final String encoding) throws Exception { final InputStream is = getXmlStream("no-bom", XML3, encoding, encoding); try { final XmlReader xmlReader = new XmlReader(is, false); fail("It should have failed"); } catch (final IOException ex) { assertTrue(ex.getMessage().indexOf("Invalid encoding,") > -1); } } #location 4 #vulnerability type RESOURCE_LEAK
#fixed code protected void testRawNoBomInvalid(final String encoding) throws Exception { InputStream is = null; XmlReader xmlReader = null; try { is = getXmlStream("no-bom", XML3, encoding, encoding); xmlReader = new XmlReader(is, false); fail("It should have failed"); } catch (final IOException ex) { assertTrue(ex.getMessage().indexOf("Invalid encoding,") > -1); } finally { if (xmlReader != null) { xmlReader.close(); } if (is != null) { is.close(); } } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public void testHttpValid(final String cT, final String bomEnc, final String streamEnc, final String prologEnc) throws Exception { final InputStream is; if (prologEnc == null) { is = getXmlStream(bomEnc, XML1, streamEnc, prologEnc); } else { is = getXmlStream(bomEnc, XML3, streamEnc, prologEnc); } final XmlReader xmlReader = new XmlReader(is, cT, false); if (!streamEnc.equals("UTF-16")) { // we can not assert things here becuase UTF-8, US-ASCII and // ISO-8859-1 look alike for the chars used for detection } else { assertEquals(xmlReader.getEncoding().substring(0, streamEnc.length()), streamEnc); } } #location 13 #vulnerability type RESOURCE_LEAK
#fixed code public void testHttpValid(final String cT, final String bomEnc, final String streamEnc, final String prologEnc) throws Exception { final InputStream is; if (prologEnc == null) { is = getXmlStream(bomEnc, XML1, streamEnc, prologEnc); } else { is = getXmlStream(bomEnc, XML3, streamEnc, prologEnc); } final XmlReader xmlReader = new XmlReader(is, cT, false); if (!streamEnc.equals("UTF-16")) { // we can not assert things here becuase UTF-8, US-ASCII and // ISO-8859-1 look alike for the chars used for detection } else { assertEquals(xmlReader.getEncoding().substring(0, streamEnc.length()), streamEnc); } xmlReader.close(); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Override public SyndFeedInfo getFeedInfo(final URL url) { SyndFeedInfo info = null; final String fileName = cachePath + File.separator + "feed_" + replaceNonAlphanumeric(url.toString(), '_').trim(); FileInputStream fis; try { fis = new FileInputStream(fileName); final ObjectInputStream ois = new ObjectInputStream(fis); info = (SyndFeedInfo) ois.readObject(); fis.close(); } catch (final FileNotFoundException fnfe) { // That's OK, we'l return null } catch (final ClassNotFoundException cnfe) { // Error writing to cache is fatal throw new RuntimeException("Attempting to read from cache", cnfe); } catch (final IOException fnfe) { // Error writing to cache is fatal throw new RuntimeException("Attempting to read from cache", fnfe); } return info; } #location 11 #vulnerability type RESOURCE_LEAK
#fixed code @Override public SyndFeedInfo getFeedInfo(final URL url) { SyndFeedInfo info = null; final String fileName = cachePath + File.separator + "feed_" + replaceNonAlphanumeric(url.toString(), '_').trim(); FileInputStream fis = null; ObjectInputStream ois = null; try { fis = new FileInputStream(fileName); ois = new ObjectInputStream(fis); info = (SyndFeedInfo) ois.readObject(); } catch (final FileNotFoundException e) { // That's OK, we'l return null } catch (final ClassNotFoundException e) { // Error writing to cache is fatal throw new RuntimeException("Attempting to read from cache", e); } catch (final IOException e) { // Error writing to cache is fatal throw new RuntimeException("Attempting to read from cache", e); } finally { if (fis != null) { try { fis.close(); } catch (final IOException e) { } } if (ois != null) { try { ois.close(); } catch (final IOException e) { } } } return info; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code protected void testRawBomValid(final String encoding) throws Exception { final InputStream is = getXmlStream(encoding + "-bom", XML3, encoding, encoding); final XmlReader xmlReader = new XmlReader(is, false); if (!encoding.equals("UTF-16")) { assertEquals(xmlReader.getEncoding(), encoding); } else { assertEquals(xmlReader.getEncoding().substring(0, encoding.length()), encoding); } } #location 7 #vulnerability type RESOURCE_LEAK
#fixed code protected void testRawBomValid(final String encoding) throws Exception { final InputStream is = getXmlStream(encoding + "-bom", XML3, encoding, encoding); final XmlReader xmlReader = new XmlReader(is, false); if (!encoding.equals("UTF-16")) { assertEquals(xmlReader.getEncoding(), encoding); } else { assertEquals(xmlReader.getEncoding().substring(0, encoding.length()), encoding); } xmlReader.close(); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code protected void testRawNoBomValid(final String encoding) throws Exception { InputStream is = getXmlStream("no-bom", XML1, encoding, encoding); XmlReader xmlReader = new XmlReader(is, false); assertEquals(xmlReader.getEncoding(), "UTF-8"); is = getXmlStream("no-bom", XML2, encoding, encoding); xmlReader = new XmlReader(is); assertEquals(xmlReader.getEncoding(), "UTF-8"); is = getXmlStream("no-bom", XML3, encoding, encoding); xmlReader = new XmlReader(is); assertEquals(xmlReader.getEncoding(), encoding); is = getXmlStream("no-bom", XML4, encoding, encoding); xmlReader = new XmlReader(is); assertEquals(xmlReader.getEncoding(), encoding); is = getXmlStream("no-bom", XML5, encoding, encoding); xmlReader = new XmlReader(is); assertEquals(xmlReader.getEncoding(), encoding); } #location 12 #vulnerability type RESOURCE_LEAK
#fixed code protected void testRawNoBomValid(final String encoding) throws Exception { checkEncoding(XML1, encoding, "UTF-8"); checkEncoding(XML2, encoding, "UTF-8"); checkEncoding(XML3, encoding, encoding); checkEncoding(XML4, encoding, encoding); checkEncoding(XML5, encoding, encoding); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public void testParse() { final Calendar cal = new GregorianCalendar(); cal.setTimeZone(TimeZone.getTimeZone("GMT")); // four-digit year String sDate = "Tue, 19 Jul 2005 23:00:51 GMT"; cal.setTime(DateParser.parseRFC822(sDate)); assertEquals(2005, cal.get(Calendar.YEAR)); assertEquals(6, cal.get(Calendar.MONTH)); // month is zero-indexed assertEquals(19, cal.get(Calendar.DAY_OF_MONTH)); assertEquals(3, cal.get(Calendar.DAY_OF_WEEK)); assertEquals(23, cal.get(Calendar.HOUR_OF_DAY)); assertEquals(0, cal.get(Calendar.MINUTE)); assertEquals(51, cal.get(Calendar.SECOND)); // two-digit year sDate = "Tue, 19 Jul 05 23:00:51 GMT"; cal.setTime(DateParser.parseRFC822(sDate)); assertEquals(2005, cal.get(Calendar.YEAR)); assertEquals(6, cal.get(Calendar.MONTH)); // month is zero-indexed assertEquals(19, cal.get(Calendar.DAY_OF_MONTH)); assertEquals(3, cal.get(Calendar.DAY_OF_WEEK)); assertEquals(23, cal.get(Calendar.HOUR_OF_DAY)); assertEquals(0, cal.get(Calendar.MINUTE)); assertEquals(51, cal.get(Calendar.SECOND)); // four-digit year sDate = "Tue, 19 Jul 2005 23:00:51 UT"; cal.setTime(DateParser.parseRFC822(sDate)); assertEquals(2005, cal.get(Calendar.YEAR)); assertEquals(6, cal.get(Calendar.MONTH)); // month is zero-indexed assertEquals(19, cal.get(Calendar.DAY_OF_MONTH)); assertEquals(3, cal.get(Calendar.DAY_OF_WEEK)); assertEquals(23, cal.get(Calendar.HOUR_OF_DAY)); assertEquals(0, cal.get(Calendar.MINUTE)); assertEquals(51, cal.get(Calendar.SECOND)); // two-digit year sDate = "Tue, 19 Jul 05 23:00:51 UT"; cal.setTime(DateParser.parseRFC822(sDate)); assertEquals(2005, cal.get(Calendar.YEAR)); assertEquals(6, cal.get(Calendar.MONTH)); // month is zero-indexed assertEquals(19, cal.get(Calendar.DAY_OF_MONTH)); assertEquals(3, cal.get(Calendar.DAY_OF_WEEK)); assertEquals(23, cal.get(Calendar.HOUR_OF_DAY)); assertEquals(0, cal.get(Calendar.MINUTE)); assertEquals(51, cal.get(Calendar.SECOND)); // RFC822 sDate = "Tue, 19 Jul 2005 23:00:51 GMT"; assertNotNull(DateParser.parseDate(sDate)); // RFC822 sDate = "Tue, 19 Jul 05 23:00:51 GMT"; assertNotNull(DateParser.parseDate(sDate)); final Calendar c = Calendar.getInstance(TimeZone.getTimeZone("GMT")); c.set(2000, Calendar.JANUARY, 01, 0, 0, 0); final Date expectedDate = c.getTime(); // W3C sDate = "2000-01-01T00:00:00Z"; assertEquals(expectedDate.getTime() / 1000, DateParser.parseDate(sDate).getTime() / 1000); // W3C sDate = "2000-01-01T00:00Z"; assertEquals(expectedDate.getTime() / 1000, DateParser.parseDate(sDate).getTime() / 1000); // W3C sDate = "2000-01-01"; assertEquals(expectedDate.getTime() / 1000, DateParser.parseDate(sDate).getTime() / 1000); // W3C sDate = "2000-01"; assertEquals(expectedDate.getTime() / 1000, DateParser.parseDate(sDate).getTime() / 1000); // W3C sDate = "2000"; assertEquals(expectedDate.getTime() / 1000, DateParser.parseDate(sDate).getTime() / 1000); // EXTRA sDate = "18:10 2000/10/10"; assertNotNull(DateParser.parseDate(sDate)); // INVALID sDate = "X20:10 2000-10-10"; assertNull(DateParser.parseDate(sDate)); } #location 67 #vulnerability type NULL_DEREFERENCE
#fixed code public void testParse() { final Calendar cal = new GregorianCalendar(); cal.setTimeZone(TimeZone.getTimeZone("GMT")); // four-digit year String sDate = "Tue, 19 Jul 2005 23:00:51 GMT"; cal.setTime(DateParser.parseRFC822(sDate, Locale.US)); assertEquals(2005, cal.get(Calendar.YEAR)); assertEquals(6, cal.get(Calendar.MONTH)); // month is zero-indexed assertEquals(19, cal.get(Calendar.DAY_OF_MONTH)); assertEquals(3, cal.get(Calendar.DAY_OF_WEEK)); assertEquals(23, cal.get(Calendar.HOUR_OF_DAY)); assertEquals(0, cal.get(Calendar.MINUTE)); assertEquals(51, cal.get(Calendar.SECOND)); // two-digit year sDate = "Tue, 19 Jul 05 23:00:51 GMT"; cal.setTime(DateParser.parseRFC822(sDate, Locale.US)); assertEquals(2005, cal.get(Calendar.YEAR)); assertEquals(6, cal.get(Calendar.MONTH)); // month is zero-indexed assertEquals(19, cal.get(Calendar.DAY_OF_MONTH)); assertEquals(3, cal.get(Calendar.DAY_OF_WEEK)); assertEquals(23, cal.get(Calendar.HOUR_OF_DAY)); assertEquals(0, cal.get(Calendar.MINUTE)); assertEquals(51, cal.get(Calendar.SECOND)); // four-digit year sDate = "Tue, 19 Jul 2005 23:00:51 UT"; cal.setTime(DateParser.parseRFC822(sDate, Locale.US)); assertEquals(2005, cal.get(Calendar.YEAR)); assertEquals(6, cal.get(Calendar.MONTH)); // month is zero-indexed assertEquals(19, cal.get(Calendar.DAY_OF_MONTH)); assertEquals(3, cal.get(Calendar.DAY_OF_WEEK)); assertEquals(23, cal.get(Calendar.HOUR_OF_DAY)); assertEquals(0, cal.get(Calendar.MINUTE)); assertEquals(51, cal.get(Calendar.SECOND)); // two-digit year sDate = "Tue, 19 Jul 05 23:00:51 UT"; cal.setTime(DateParser.parseRFC822(sDate, Locale.US)); assertEquals(2005, cal.get(Calendar.YEAR)); assertEquals(6, cal.get(Calendar.MONTH)); // month is zero-indexed assertEquals(19, cal.get(Calendar.DAY_OF_MONTH)); assertEquals(3, cal.get(Calendar.DAY_OF_WEEK)); assertEquals(23, cal.get(Calendar.HOUR_OF_DAY)); assertEquals(0, cal.get(Calendar.MINUTE)); assertEquals(51, cal.get(Calendar.SECOND)); // RFC822 sDate = "Tue, 19 Jul 2005 23:00:51 GMT"; assertNotNull(DateParser.parseDate(sDate, Locale.US)); // RFC822 sDate = "Tue, 19 Jul 05 23:00:51 GMT"; assertNotNull(DateParser.parseDate(sDate, Locale.US)); final Calendar c = Calendar.getInstance(TimeZone.getTimeZone("GMT")); c.set(2000, Calendar.JANUARY, 01, 0, 0, 0); final Date expectedDate = c.getTime(); // W3C sDate = "2000-01-01T00:00:00Z"; assertEquals(expectedDate.getTime() / 1000, DateParser.parseDate(sDate, Locale.US).getTime() / 1000); // W3C sDate = "2000-01-01T00:00Z"; assertEquals(expectedDate.getTime() / 1000, DateParser.parseDate(sDate, Locale.US).getTime() / 1000); // W3C sDate = "2000-01-01"; assertEquals(expectedDate.getTime() / 1000, DateParser.parseDate(sDate, Locale.US).getTime() / 1000); // W3C sDate = "2000-01"; assertEquals(expectedDate.getTime() / 1000, DateParser.parseDate(sDate, Locale.US).getTime() / 1000); // W3C sDate = "2000"; assertEquals(expectedDate.getTime() / 1000, DateParser.parseDate(sDate, Locale.US).getTime() / 1000); // EXTRA sDate = "18:10 2000/10/10"; assertNotNull(DateParser.parseDate(sDate, Locale.US)); // INVALID sDate = "X20:10 2000-10-10"; assertNull(DateParser.parseDate(sDate, Locale.US)); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code protected void testHttpLenient(final String cT, final String bomEnc, final String streamEnc, final String prologEnc, final String shouldbe) throws Exception { final InputStream is; if (prologEnc == null) { is = getXmlStream(bomEnc, XML2, streamEnc, prologEnc); } else { is = getXmlStream(bomEnc, XML3, streamEnc, prologEnc); } final XmlReader xmlReader = new XmlReader(is, cT, true); assertEquals(xmlReader.getEncoding(), shouldbe); } #location 10 #vulnerability type RESOURCE_LEAK
#fixed code protected void testHttpLenient(final String cT, final String bomEnc, final String streamEnc, final String prologEnc, final String shouldbe) throws Exception { final InputStream is; if (prologEnc == null) { is = getXmlStream(bomEnc, XML2, streamEnc, prologEnc); } else { is = getXmlStream(bomEnc, XML3, streamEnc, prologEnc); } final XmlReader xmlReader = new XmlReader(is, cT, true); assertEquals(xmlReader.getEncoding(), shouldbe); xmlReader.close(); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code protected void testRawBomValid(final String encoding) throws Exception { final InputStream is = getXmlStream(encoding + "-bom", XML3, encoding, encoding); final XmlReader xmlReader = new XmlReader(is, false); if (!encoding.equals("UTF-16")) { assertEquals(xmlReader.getEncoding(), encoding); } else { assertEquals(xmlReader.getEncoding().substring(0, encoding.length()), encoding); } } #location 5 #vulnerability type RESOURCE_LEAK
#fixed code protected void testRawBomValid(final String encoding) throws Exception { final InputStream is = getXmlStream(encoding + "-bom", XML3, encoding, encoding); final XmlReader xmlReader = new XmlReader(is, false); if (!encoding.equals("UTF-16")) { assertEquals(xmlReader.getEncoding(), encoding); } else { assertEquals(xmlReader.getEncoding().substring(0, encoding.length()), encoding); } xmlReader.close(); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public void testParse() { final Calendar cal = new GregorianCalendar(); cal.setTimeZone(TimeZone.getTimeZone("GMT")); // four-digit year String sDate = "Tue, 19 Jul 2005 23:00:51 GMT"; cal.setTime(DateParser.parseRFC822(sDate)); assertEquals(2005, cal.get(Calendar.YEAR)); assertEquals(6, cal.get(Calendar.MONTH)); // month is zero-indexed assertEquals(19, cal.get(Calendar.DAY_OF_MONTH)); assertEquals(3, cal.get(Calendar.DAY_OF_WEEK)); assertEquals(23, cal.get(Calendar.HOUR_OF_DAY)); assertEquals(0, cal.get(Calendar.MINUTE)); assertEquals(51, cal.get(Calendar.SECOND)); // two-digit year sDate = "Tue, 19 Jul 05 23:00:51 GMT"; cal.setTime(DateParser.parseRFC822(sDate)); assertEquals(2005, cal.get(Calendar.YEAR)); assertEquals(6, cal.get(Calendar.MONTH)); // month is zero-indexed assertEquals(19, cal.get(Calendar.DAY_OF_MONTH)); assertEquals(3, cal.get(Calendar.DAY_OF_WEEK)); assertEquals(23, cal.get(Calendar.HOUR_OF_DAY)); assertEquals(0, cal.get(Calendar.MINUTE)); assertEquals(51, cal.get(Calendar.SECOND)); // four-digit year sDate = "Tue, 19 Jul 2005 23:00:51 UT"; cal.setTime(DateParser.parseRFC822(sDate)); assertEquals(2005, cal.get(Calendar.YEAR)); assertEquals(6, cal.get(Calendar.MONTH)); // month is zero-indexed assertEquals(19, cal.get(Calendar.DAY_OF_MONTH)); assertEquals(3, cal.get(Calendar.DAY_OF_WEEK)); assertEquals(23, cal.get(Calendar.HOUR_OF_DAY)); assertEquals(0, cal.get(Calendar.MINUTE)); assertEquals(51, cal.get(Calendar.SECOND)); // two-digit year sDate = "Tue, 19 Jul 05 23:00:51 UT"; cal.setTime(DateParser.parseRFC822(sDate)); assertEquals(2005, cal.get(Calendar.YEAR)); assertEquals(6, cal.get(Calendar.MONTH)); // month is zero-indexed assertEquals(19, cal.get(Calendar.DAY_OF_MONTH)); assertEquals(3, cal.get(Calendar.DAY_OF_WEEK)); assertEquals(23, cal.get(Calendar.HOUR_OF_DAY)); assertEquals(0, cal.get(Calendar.MINUTE)); assertEquals(51, cal.get(Calendar.SECOND)); // RFC822 sDate = "Tue, 19 Jul 2005 23:00:51 GMT"; assertNotNull(DateParser.parseDate(sDate)); // RFC822 sDate = "Tue, 19 Jul 05 23:00:51 GMT"; assertNotNull(DateParser.parseDate(sDate)); final Calendar c = Calendar.getInstance(TimeZone.getTimeZone("GMT")); c.set(2000, Calendar.JANUARY, 01, 0, 0, 0); final Date expectedDate = c.getTime(); // W3C sDate = "2000-01-01T00:00:00Z"; assertEquals(expectedDate.getTime() / 1000, DateParser.parseDate(sDate).getTime() / 1000); // W3C sDate = "2000-01-01T00:00Z"; assertEquals(expectedDate.getTime() / 1000, DateParser.parseDate(sDate).getTime() / 1000); // W3C sDate = "2000-01-01"; assertEquals(expectedDate.getTime() / 1000, DateParser.parseDate(sDate).getTime() / 1000); // W3C sDate = "2000-01"; assertEquals(expectedDate.getTime() / 1000, DateParser.parseDate(sDate).getTime() / 1000); // W3C sDate = "2000"; assertEquals(expectedDate.getTime() / 1000, DateParser.parseDate(sDate).getTime() / 1000); // EXTRA sDate = "18:10 2000/10/10"; assertNotNull(DateParser.parseDate(sDate)); // INVALID sDate = "X20:10 2000-10-10"; assertNull(DateParser.parseDate(sDate)); } #location 67 #vulnerability type NULL_DEREFERENCE
#fixed code public void testParse() { final Calendar cal = new GregorianCalendar(); cal.setTimeZone(TimeZone.getTimeZone("GMT")); // four-digit year String sDate = "Tue, 19 Jul 2005 23:00:51 GMT"; cal.setTime(DateParser.parseRFC822(sDate, Locale.US)); assertEquals(2005, cal.get(Calendar.YEAR)); assertEquals(6, cal.get(Calendar.MONTH)); // month is zero-indexed assertEquals(19, cal.get(Calendar.DAY_OF_MONTH)); assertEquals(3, cal.get(Calendar.DAY_OF_WEEK)); assertEquals(23, cal.get(Calendar.HOUR_OF_DAY)); assertEquals(0, cal.get(Calendar.MINUTE)); assertEquals(51, cal.get(Calendar.SECOND)); // two-digit year sDate = "Tue, 19 Jul 05 23:00:51 GMT"; cal.setTime(DateParser.parseRFC822(sDate, Locale.US)); assertEquals(2005, cal.get(Calendar.YEAR)); assertEquals(6, cal.get(Calendar.MONTH)); // month is zero-indexed assertEquals(19, cal.get(Calendar.DAY_OF_MONTH)); assertEquals(3, cal.get(Calendar.DAY_OF_WEEK)); assertEquals(23, cal.get(Calendar.HOUR_OF_DAY)); assertEquals(0, cal.get(Calendar.MINUTE)); assertEquals(51, cal.get(Calendar.SECOND)); // four-digit year sDate = "Tue, 19 Jul 2005 23:00:51 UT"; cal.setTime(DateParser.parseRFC822(sDate, Locale.US)); assertEquals(2005, cal.get(Calendar.YEAR)); assertEquals(6, cal.get(Calendar.MONTH)); // month is zero-indexed assertEquals(19, cal.get(Calendar.DAY_OF_MONTH)); assertEquals(3, cal.get(Calendar.DAY_OF_WEEK)); assertEquals(23, cal.get(Calendar.HOUR_OF_DAY)); assertEquals(0, cal.get(Calendar.MINUTE)); assertEquals(51, cal.get(Calendar.SECOND)); // two-digit year sDate = "Tue, 19 Jul 05 23:00:51 UT"; cal.setTime(DateParser.parseRFC822(sDate, Locale.US)); assertEquals(2005, cal.get(Calendar.YEAR)); assertEquals(6, cal.get(Calendar.MONTH)); // month is zero-indexed assertEquals(19, cal.get(Calendar.DAY_OF_MONTH)); assertEquals(3, cal.get(Calendar.DAY_OF_WEEK)); assertEquals(23, cal.get(Calendar.HOUR_OF_DAY)); assertEquals(0, cal.get(Calendar.MINUTE)); assertEquals(51, cal.get(Calendar.SECOND)); // RFC822 sDate = "Tue, 19 Jul 2005 23:00:51 GMT"; assertNotNull(DateParser.parseDate(sDate, Locale.US)); // RFC822 sDate = "Tue, 19 Jul 05 23:00:51 GMT"; assertNotNull(DateParser.parseDate(sDate, Locale.US)); final Calendar c = Calendar.getInstance(TimeZone.getTimeZone("GMT")); c.set(2000, Calendar.JANUARY, 01, 0, 0, 0); final Date expectedDate = c.getTime(); // W3C sDate = "2000-01-01T00:00:00Z"; assertEquals(expectedDate.getTime() / 1000, DateParser.parseDate(sDate, Locale.US).getTime() / 1000); // W3C sDate = "2000-01-01T00:00Z"; assertEquals(expectedDate.getTime() / 1000, DateParser.parseDate(sDate, Locale.US).getTime() / 1000); // W3C sDate = "2000-01-01"; assertEquals(expectedDate.getTime() / 1000, DateParser.parseDate(sDate, Locale.US).getTime() / 1000); // W3C sDate = "2000-01"; assertEquals(expectedDate.getTime() / 1000, DateParser.parseDate(sDate, Locale.US).getTime() / 1000); // W3C sDate = "2000"; assertEquals(expectedDate.getTime() / 1000, DateParser.parseDate(sDate, Locale.US).getTime() / 1000); // EXTRA sDate = "18:10 2000/10/10"; assertNotNull(DateParser.parseDate(sDate, Locale.US)); // INVALID sDate = "X20:10 2000-10-10"; assertNull(DateParser.parseDate(sDate, Locale.US)); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code protected void testRawNoBomValid(final String encoding) throws Exception { InputStream is = getXmlStream("no-bom", XML1, encoding, encoding); XmlReader xmlReader = new XmlReader(is, false); assertEquals(xmlReader.getEncoding(), "UTF-8"); is = getXmlStream("no-bom", XML2, encoding, encoding); xmlReader = new XmlReader(is); assertEquals(xmlReader.getEncoding(), "UTF-8"); is = getXmlStream("no-bom", XML3, encoding, encoding); xmlReader = new XmlReader(is); assertEquals(xmlReader.getEncoding(), encoding); is = getXmlStream("no-bom", XML4, encoding, encoding); xmlReader = new XmlReader(is); assertEquals(xmlReader.getEncoding(), encoding); is = getXmlStream("no-bom", XML5, encoding, encoding); xmlReader = new XmlReader(is); assertEquals(xmlReader.getEncoding(), encoding); } #location 4 #vulnerability type RESOURCE_LEAK
#fixed code protected void testRawNoBomValid(final String encoding) throws Exception { checkEncoding(XML1, encoding, "UTF-8"); checkEncoding(XML2, encoding, "UTF-8"); checkEncoding(XML3, encoding, encoding); checkEncoding(XML4, encoding, encoding); checkEncoding(XML5, encoding, encoding); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code Element pop() { // todo - dev, remove validation check if (stack.peekLast().nodeName().equals("td") && !state.name().equals("InCell")) Validate.isFalse(true, "pop td not in cell"); if (stack.peekLast().nodeName().equals("html")) Validate.isFalse(true, "popping html!"); return stack.pollLast(); } #location 3 #vulnerability type NULL_DEREFERENCE
#fixed code HtmlTreeBuilder() {}
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code private static String readInputStream(InputStream inStream, String charsetName) throws IOException { char[] buffer = new char[0x20000]; // ~ 130K StringBuilder data = new StringBuilder(0x20000); Reader inReader = new InputStreamReader(inStream, charsetName); int read; do { read = inReader.read(buffer, 0, buffer.length); if (read > 0) { data.append(buffer, 0, read); } } while (read >= 0); return data.toString(); } #location 14 #vulnerability type RESOURCE_LEAK
#fixed code private static String readInputStream(InputStream inStream, String charsetName) throws IOException { byte[] buffer = new byte[bufferSize]; ByteArrayOutputStream outStream = new ByteArrayOutputStream(bufferSize); int read; while(true) { read = inStream.read(buffer); if (read == -1) break; outStream.write(buffer, 0, read); } ByteBuffer byteData = ByteBuffer.wrap(outStream.toByteArray()); String docData; if (charsetName == null) { // determine from http-equiv. safe parse as UTF-8 docData = Charset.forName(defaultCharset).decode(byteData).toString(); Document doc = Jsoup.parse(docData); Element httpEquiv = doc.select("meta[http-equiv]").first(); if (httpEquiv != null) { // if not found, will keep utf-8 as best attempt String foundCharset = getCharsetFromContentType(httpEquiv.attr("content")); if (foundCharset != null && !foundCharset.equals(defaultCharset)) { // need to re-decode byteData.rewind(); docData = Charset.forName(foundCharset).decode(byteData).toString(); } } } else { // specified by content type header (or by user on file load) docData = Charset.forName(charsetName).decode(byteData).toString(); } return docData; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code static String load(File in, String charsetName) throws IOException { char[] buffer = new char[0x20000]; // ~ 130K StringBuilder data = new StringBuilder(0x20000); InputStream inStream = new FileInputStream(in); Reader inReader = new InputStreamReader(inStream, charsetName); int read; do { read = inReader.read(buffer, 0, buffer.length); if (read > 0) { data.append(buffer, 0, read); } } while (read >= 0); return data.toString(); } #location 5 #vulnerability type RESOURCE_LEAK
#fixed code static String load(File in, String charsetName) throws IOException { InputStream inStream = new FileInputStream(in); String data = readInputStream(inStream, charsetName); inStream.close(); return data; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public Document normalise() { if (select("html").isEmpty()) appendElement("html"); if (head() == null) select("html").first().prependElement("head"); if (body() == null) select("html").first().appendElement("body"); normalise(this); normalise(select("html").first()); normalise(head()); return this; } #location 10 #vulnerability type NULL_DEREFERENCE
#fixed code public Document normalise() { if (select("html").isEmpty()) appendElement("html"); if (head() == null) select("html").first().prependElement("head"); if (body() == null) select("html").first().appendElement("body"); // pull text nodes out of root, html, and head els, and push into body. non-text nodes are already taken care // of. do in inverse order to maintain text order. normalise(head()); normalise(select("html").first()); normalise(this); return this; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public Document parse() { // TODO: figure out implicit head & body elements Document doc = new Document(); stack.add(doc); while (tokenStream.hasNext()) { Token token = tokenStream.next(); if (token.isStartTag()) { Attributes attributes = attributeParser.parse(token.getAttributeString()); Tag tag = Tag.valueOf(token.getTagName()); StartTag startTag = new StartTag(tag, attributes); // if tag is "html", we already have it, so OK to ignore skip. todo: abstract this. and can there be attributes to set? if (doc.getTag().equals(tag)) continue; Element parent = popStackToSuitableContainer(tag); Validate.notNull(parent, "Should always have a viable container"); Element node = new Element(parent, startTag); parent.addChild(node); stack.add(node); } if (token.isEndTag()) { // empty tags are both start and end tags stack.removeLast(); } // TODO[must] handle comments else if (token.isTextNode()) { String text = token.getData(); TextNode textNode = new TextNode(stack.peek(), text); stack.getLast().addChild(textNode); } } return doc; } #location 20 #vulnerability type NULL_DEREFERENCE
#fixed code public Document parse() { // TODO: figure out implicit head & body elements Document doc = new Document(); stack.add(doc); StringBuilder commentAccum = null; while (tokenStream.hasNext()) { Token token = tokenStream.next(); if (token.isFullComment()) { // <!-- comment --> Comment comment = new Comment(stack.peek(), token.getCommentData()); stack.getLast().addChild(comment); } else if (token.isStartComment()) { // <!-- comment commentAccum = new StringBuilder(token.getCommentData()); } else if (token.isEndComment() && commentAccum != null) { // comment --> commentAccum.append(token.getCommentData()); Comment comment = new Comment(stack.peek(), commentAccum.toString()); stack.getLast().addChild(comment); commentAccum = null; } else if (commentAccum != null) { // within a comment commentAccum.append(token.getData()); } else if (token.isStartTag()) { Attributes attributes = attributeParser.parse(token.getAttributeString()); Tag tag = Tag.valueOf(token.getTagName()); StartTag startTag = new StartTag(tag, attributes); // if tag is "html", we already have it, so OK to ignore skip. todo: abstract this. and can there be attributes to set? if (doc.getTag().equals(tag)) continue; Element parent = popStackToSuitableContainer(tag); Validate.notNull(parent, "Should always have a viable container"); Element node = new Element(parent, startTag); parent.addChild(node); stack.add(node); } if (token.isEndTag() && commentAccum == null) { // empty tags are both start and end tags stack.removeLast(); } // TODO[must] handle comments else if (token.isTextNode()) { String text = token.getData(); TextNode textNode = new TextNode(stack.peek(), text); stack.getLast().addChild(textNode); } } return doc; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public Node previousSibling() { List<Node> siblings = parentNode.childNodes; Integer index = indexInList(this, siblings); Validate.notNull(index); if (index > 0) return siblings.get(index-1); else return null; } #location 5 #vulnerability type NULL_DEREFERENCE
#fixed code public Node previousSibling() { List<Node> siblings = parentNode.childNodes; Integer index = siblingIndex(); Validate.notNull(index); if (index > 0) return siblings.get(index-1); else return null; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code void insert(Token.Character characterToken) { Node node; // characters in script and style go in as datanodes, not text nodes final String tagName = currentElement().tagName(); final String data = characterToken.getData(); if (characterToken.isCData()) node = new CDataNode(data); else if (tagName.equals("script") || tagName.equals("style")) node = new DataNode(data); else node = new TextNode(data); currentElement().appendChild(node); // doesn't use insertNode, because we don't foster these; and will always have a stack. } #location 4 #vulnerability type NULL_DEREFERENCE
#fixed code ParseSettings defaultSettings() { return ParseSettings.htmlDefault; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void testPreviousElementSiblings() { Document doc = Jsoup.parse("<li id='a'>a</li>" + "<li id='b'>b</li>" + "<li id='c'>c</li>"); Element element = doc.getElementById("b"); List<Element> elementSiblings = element.previousElementSiblings(); assertNotNull(elementSiblings); assertEquals(1, elementSiblings.size()); Element element1 = doc.getElementById("a"); List<Element> elementSiblings1 = element1.previousElementSiblings(); assertNull(elementSiblings1); } #location 9 #vulnerability type NULL_DEREFERENCE
#fixed code @Test public void testPreviousElementSiblings() { Document doc = Jsoup.parse("<ul id='ul'>" + "<li id='a'>a</li>" + "<li id='b'>b</li>" + "<li id='c'>c</li>" + "</ul>" + "<div id='div'>" + "<li id='d'>d</li>" + "</div>"); Element element = doc.getElementById("b"); List<Element> elementSiblings = element.previousElementSiblings(); assertNotNull(elementSiblings); assertEquals(1, elementSiblings.size()); assertEquals("a", elementSiblings.get(0).id()); Element element1 = doc.getElementById("a"); List<Element> elementSiblings1 = element1.previousElementSiblings(); assertEquals(0, elementSiblings1.size()); Element element2 = doc.getElementById("c"); List<Element> elementSiblings2 = element2.previousElementSiblings(); assertNotNull(elementSiblings2); assertEquals(2, elementSiblings2.size()); assertEquals("a", elementSiblings2.get(0).id()); assertEquals("b", elementSiblings2.get(1).id()); Element ul = doc.getElementById("ul"); List<Element> elementSiblings3 = ul.previousElementSiblings(); try { Element element3 = elementSiblings3.get(0); fail("This element should has no previous siblings"); } catch (IndexOutOfBoundsException e) { } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void forms() { Document doc = Jsoup.parse("<form id=1><input name=q></form><div /><form id=2><input name=f></form>"); Elements els = doc.select("*"); assertEquals(9, els.size()); List<FormElement> forms = els.forms(); assertEquals(2, forms.size()); assertTrue(forms.get(0) != null); assertTrue(forms.get(1) != null); assertEquals("1", forms.get(0).id()); assertEquals("2", forms.get(1).id()); } #location 10 #vulnerability type NULL_DEREFERENCE
#fixed code @Test public void forms() { Document doc = Jsoup.parse("<form id=1><input name=q></form><div /><form id=2><input name=f></form>"); Elements els = doc.select("*"); assertEquals(9, els.size()); List<FormElement> forms = els.forms(); assertEquals(2, forms.size()); assertNotNull(forms.get(0)); assertNotNull(forms.get(1)); assertEquals("1", forms.get(0).id()); assertEquals("2", forms.get(1).id()); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code static String load(File in, String charsetName) throws IOException { char[] buffer = new char[0x20000]; // ~ 130K StringBuilder data = new StringBuilder(0x20000); InputStream inStream = new FileInputStream(in); Reader inReader = new InputStreamReader(inStream, charsetName); int read; do { read = inReader.read(buffer, 0, buffer.length); if (read > 0) { data.append(buffer, 0, read); } } while (read >= 0); return data.toString(); } #location 15 #vulnerability type RESOURCE_LEAK
#fixed code static String load(File in, String charsetName) throws IOException { InputStream inStream = new FileInputStream(in); String data = readInputStream(inStream, charsetName); inStream.close(); return data; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public Node nextSibling() { if (parentNode == null) return null; // root List<Node> siblings = parentNode.childNodes; Integer index = indexInList(this, siblings); Validate.notNull(index); if (siblings.size() > index+1) return siblings.get(index+1); else return null; } #location 8 #vulnerability type NULL_DEREFERENCE
#fixed code public Node nextSibling() { if (parentNode == null) return null; // root List<Node> siblings = parentNode.childNodes; Integer index = siblingIndex(); Validate.notNull(index); if (siblings.size() > index+1) return siblings.get(index+1); else return null; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public Document normalise() { if (select("html").isEmpty()) appendElement("html"); if (head() == null) select("html").first().prependElement("head"); if (body() == null) select("html").first().appendElement("body"); // pull text nodes out of root, html, and head els, and push into body. non-text nodes are already taken care // of. do in inverse order to maintain text order. normalise(head()); normalise(select("html").first()); normalise(this); return this; } #location 11 #vulnerability type NULL_DEREFERENCE
#fixed code public Document normalise() { Element htmlEl = findFirstElementByTagName("html", this); if (htmlEl == null) htmlEl = appendElement("html"); if (head() == null) htmlEl.prependElement("head"); if (body() == null) htmlEl.appendElement("body"); // pull text nodes out of root, html, and head els, and push into body. non-text nodes are already taken care // of. do in inverse order to maintain text order. normalise(head()); normalise(htmlEl); normalise(this); return this; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code void insert(Token.Character characterToken) { Node node; // characters in script and style go in as datanodes, not text nodes final String tagName = currentElement().tagName(); final String data = characterToken.getData(); if (characterToken.isCData()) node = new CDataNode(data); else if (tagName.equals("script") || tagName.equals("style")) node = new DataNode(data); else node = new TextNode(data); currentElement().appendChild(node); // doesn't use insertNode, because we don't foster these; and will always have a stack. } #location 13 #vulnerability type NULL_DEREFERENCE
#fixed code ParseSettings defaultSettings() { return ParseSettings.htmlDefault; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public boolean matchesWhitespace() { return !isEmpty() && Character.isWhitespace(peek()); } #location 2 #vulnerability type NULL_DEREFERENCE
#fixed code public boolean matchesWhitespace() { return !isEmpty() && Character.isWhitespace(queue.charAt(pos)); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void testAppendTo() { String parentHtml = "<div class='a'></div>"; String childHtml = "<div class='b'></div>"; Element parentElement = Jsoup.parse(parentHtml).getElementsByClass("a").first(); Element childElement = Jsoup.parse(childHtml).getElementsByClass("b").first(); childElement.attr("class", "test-class").appendTo(parentElement).attr("id", "testId"); assertEquals("test-class", childElement.attr("class")); assertEquals("testId", childElement.attr("id")); assertThat(parentElement.attr("id"), not(equalTo("testId"))); assertThat(parentElement.attr("class"), not(equalTo("test-class"))); assertSame(childElement, parentElement.children().first()); assertSame(parentElement, childElement.parent()); } #location 9 #vulnerability type NULL_DEREFERENCE
#fixed code @Test public void testAppendTo() { String parentHtml = "<div class='a'></div>"; String childHtml = "<div class='b'></div><p>Two</p>"; Document parentDoc = Jsoup.parse(parentHtml); Element parent = parentDoc.body(); Document childDoc = Jsoup.parse(childHtml); Element div = childDoc.select("div").first(); Element p = childDoc.select("p").first(); Element appendTo1 = div.appendTo(parent); assertEquals(div, appendTo1); Element appendTo2 = p.appendTo(div); assertEquals(p, appendTo2); assertEquals("<div class=\"a\"></div>\n<div class=\"b\">\n <p>Two</p>\n</div>", parentDoc.body().html()); assertEquals("", childDoc.body().html()); // got moved out }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code Element pop() { // todo - dev, remove validation check if (stack.peekLast().nodeName().equals("td") && !state.name().equals("InCell")) Validate.isFalse(true, "pop td not in cell"); if (stack.peekLast().nodeName().equals("html")) Validate.isFalse(true, "popping html!"); return stack.pollLast(); } #location 5 #vulnerability type NULL_DEREFERENCE
#fixed code HtmlTreeBuilder() {}
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public Document normalise() { if (select("html").isEmpty()) appendElement("html"); if (head() == null) select("html").first().prependElement("head"); if (body() == null) select("html").first().appendElement("body"); // pull text nodes out of root, html, and head els, and push into body. non-text nodes are already taken care // of. do in inverse order to maintain text order. normalise(head()); normalise(select("html").first()); normalise(this); return this; } #location 5 #vulnerability type NULL_DEREFERENCE
#fixed code public Document normalise() { Element htmlEl = findFirstElementByTagName("html", this); if (htmlEl == null) htmlEl = appendElement("html"); if (head() == null) htmlEl.prependElement("head"); if (body() == null) htmlEl.appendElement("body"); // pull text nodes out of root, html, and head els, and push into body. non-text nodes are already taken care // of. do in inverse order to maintain text order. normalise(head()); normalise(htmlEl); normalise(this); return this; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code void outerHtmlHead(StringBuilder accum, int depth) { if (isBlock() || (parent() != null && parent().tag().canContainBlock() && siblingIndex() == 0)) indent(accum, depth); accum .append("<") .append(tagName()) .append(attributes.html()); if (childNodes.isEmpty() && tag.isEmpty()) accum.append(" />"); else accum.append(">"); } #location 2 #vulnerability type NULL_DEREFERENCE
#fixed code boolean preserveWhitespace() { return tag.preserveWhitespace() || parent() != null && parent().preserveWhitespace(); }
Below is the vulnerable code, please generate the patch based on the following information.