input
stringlengths
205
73.3k
output
stringlengths
64
73.2k
instruction
stringclasses
1 value
#vulnerable code private static void show(final String msg, final Stats s, final long start) { final long elapsed = System.currentTimeMillis() - start; System.out.printf("%-20s: %5dms " + s.count + " lines "+ s.fields + " fields%n",msg,elapsed); elapsedTimes[num++]=elapsed; } #location 3 #vulnerability type CHECKERS_PRINTF_ARGS
#fixed code private static void show(final String msg, final Stats s, final long start) { final long elapsed = System.currentTimeMillis() - start; System.out.printf("%-20s: %5dms %d lines %d fields%n", msg, elapsed, s.count, s.fields); elapsedTimes[num] = elapsed; num++; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void testEmptyLineBehaviourCSV() throws Exception { String[] codes = { "hello,\r\n\r\n\r\n", "hello,\n\n\n", "hello,\"\"\r\n\r\n\r\n", "hello,\"\"\n\n\n" }; String[][] res = { {"hello", ""} // CSV format ignores empty lines }; for (String code : codes) { CSVParser parser = new CSVParser(new StringReader(code)); String[][] tmp = parser.getRecords(); assertEquals(res.length, tmp.length); assertTrue(tmp.length > 0); for (int i = 0; i < res.length; i++) { assertTrue(Arrays.equals(res[i], tmp[i])); } } } #location 15 #vulnerability type NULL_DEREFERENCE
#fixed code @Test public void testEmptyLineBehaviourCSV() throws Exception { String[] codes = { "hello,\r\n\r\n\r\n", "hello,\n\n\n", "hello,\"\"\r\n\r\n\r\n", "hello,\"\"\n\n\n" }; String[][] res = { {"hello", ""} // CSV format ignores empty lines }; for (String code : codes) { CSVParser parser = new CSVParser(new StringReader(code)); List<CSVRecord> records = parser.getRecords(); assertEquals(res.length, records.size()); assertTrue(records.size() > 0); for (int i = 0; i < res.length; i++) { assertTrue(Arrays.equals(res[i], records.get(i).values())); } } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void testNextToken3Escaping() throws IOException { /* file: a,\,,b * \,, */ final String code = "a,\\,,b\\\\\n\\,,\\\nc,d\\\r\ne"; final CSVFormat format = CSVFormat.newBuilder().withEscape('\\').withIgnoreEmptyLines(false).build(); assertTrue(format.isEscaping()); final Lexer parser = getLexer(code, format); assertTokenEquals(TOKEN, "a", parser.nextToken(new Token())); assertTokenEquals(TOKEN, ",", parser.nextToken(new Token())); assertTokenEquals(EORECORD, "b\\", parser.nextToken(new Token())); assertTokenEquals(TOKEN, ",", parser.nextToken(new Token())); assertTokenEquals(TOKEN, "\nc", parser.nextToken(new Token())); assertTokenEquals(EORECORD, "d\r", parser.nextToken(new Token())); assertTokenEquals(EOF, "e", parser.nextToken(new Token())); } #location 17 #vulnerability type RESOURCE_LEAK
#fixed code @Test public void testNextToken3Escaping() throws IOException { /* file: a,\,,b * \,, */ final String code = "a,\\,,b\\\\\n\\,,\\\nc,d\\\r\ne"; final CSVFormat format = formatWithEscaping.toBuilder().withIgnoreEmptyLines(false).build(); assertTrue(format.isEscaping()); final Lexer parser = getLexer(code, format); assertTokenEquals(TOKEN, "a", parser.nextToken(new Token())); assertTokenEquals(TOKEN, ",", parser.nextToken(new Token())); assertTokenEquals(EORECORD, "b\\", parser.nextToken(new Token())); assertTokenEquals(TOKEN, ",", parser.nextToken(new Token())); assertTokenEquals(TOKEN, "\nc", parser.nextToken(new Token())); assertTokenEquals(EORECORD, "d\r", parser.nextToken(new Token())); assertTokenEquals(EOF, "e", parser.nextToken(new Token())); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void testExcelFormat1() throws IOException { final String code = "value1,value2,value3,value4\r\na,b,c,d\r\n x,,," + "\r\n\r\n\"\"\"hello\"\"\",\" \"\"world\"\"\",\"abc\ndef\",\r\n"; final String[][] res = { {"value1", "value2", "value3", "value4"}, {"a", "b", "c", "d"}, {" x", "", "", ""}, {""}, {"\"hello\"", " \"world\"", "abc\ndef", ""} }; final CSVParser parser = CSVParser.parseString(code, CSVFormat.EXCEL); final List<CSVRecord> records = parser.getRecords(); assertEquals(res.length, records.size()); assertTrue(records.size() > 0); for (int i = 0; i < res.length; i++) { assertArrayEquals(res[i], records.get(i).values()); } } #location 14 #vulnerability type RESOURCE_LEAK
#fixed code @Test public void testExcelFormat1() throws IOException { final String code = "value1,value2,value3,value4\r\na,b,c,d\r\n x,,," + "\r\n\r\n\"\"\"hello\"\"\",\" \"\"world\"\"\",\"abc\ndef\",\r\n"; final String[][] res = { {"value1", "value2", "value3", "value4"}, {"a", "b", "c", "d"}, {" x", "", "", ""}, {""}, {"\"hello\"", " \"world\"", "abc\ndef", ""} }; final CSVParser parser = CSVParser.parse(code, CSVFormat.EXCEL); final List<CSVRecord> records = parser.getRecords(); assertEquals(res.length, records.size()); assertTrue(records.size() > 0); for (int i = 0; i < res.length; i++) { assertArrayEquals(res[i], records.get(i).values()); } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void testIgnoreEmptyLines() throws IOException { final String code = "\nfoo,baar\n\r\n,\n\n,world\r\n\n"; //String code = "world\r\n\n"; //String code = "foo;baar\r\n\r\nhello;\r\n\r\nworld;\r\n"; final CSVParser parser = CSVParser.parseString(code, CSVFormat.DEFAULT); final List<CSVRecord> records = parser.getRecords(); assertEquals(3, records.size()); } #location 7 #vulnerability type RESOURCE_LEAK
#fixed code @Test public void testIgnoreEmptyLines() throws IOException { final String code = "\nfoo,baar\n\r\n,\n\n,world\r\n\n"; //String code = "world\r\n\n"; //String code = "foo;baar\r\n\r\nhello;\r\n\r\nworld;\r\n"; final CSVParser parser = CSVParser.parse(code, CSVFormat.DEFAULT); final List<CSVRecord> records = parser.getRecords(); assertEquals(3, records.size()); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test @Ignore public void testBackslashEscapingOld() throws IOException { final String code = "one,two,three\n" + "on\\\"e,two\n" + "on\"e,two\n" + "one,\"tw\\\"o\"\n" + "one,\"t\\,wo\"\n" + "one,two,\"th,ree\"\n" + "\"a\\\\\"\n" + "a\\,b\n" + "\"a\\\\,b\""; final String[][] res = { {"one", "two", "three"}, {"on\\\"e", "two"}, {"on\"e", "two"}, {"one", "tw\"o"}, {"one", "t\\,wo"}, // backslash in quotes only escapes a delimiter (",") {"one", "two", "th,ree"}, {"a\\\\"}, // backslash in quotes only escapes a delimiter (",") {"a\\", "b"}, // a backslash must be returnd {"a\\\\,b"} // backslash in quotes only escapes a delimiter (",") }; final CSVParser parser = CSVParser.parse(code, CSVFormat.DEFAULT); final List<CSVRecord> records = parser.getRecords(); assertEquals(res.length, records.size()); assertTrue(records.size() > 0); for (int i = 0; i < res.length; i++) { assertArrayEquals(res[i], records.get(i).values()); } } #location 26 #vulnerability type RESOURCE_LEAK
#fixed code @Test @Ignore public void testBackslashEscapingOld() throws IOException { final String code = "one,two,three\n" + "on\\\"e,two\n" + "on\"e,two\n" + "one,\"tw\\\"o\"\n" + "one,\"t\\,wo\"\n" + "one,two,\"th,ree\"\n" + "\"a\\\\\"\n" + "a\\,b\n" + "\"a\\\\,b\""; final String[][] res = { {"one", "two", "three"}, {"on\\\"e", "two"}, {"on\"e", "two"}, {"one", "tw\"o"}, {"one", "t\\,wo"}, // backslash in quotes only escapes a delimiter (",") {"one", "two", "th,ree"}, {"a\\\\"}, // backslash in quotes only escapes a delimiter (",") {"a\\", "b"}, // a backslash must be returnd {"a\\\\,b"} // backslash in quotes only escapes a delimiter (",") }; final CSVParser parser = CSVParser.parse(code, CSVFormat.DEFAULT); final List<CSVRecord> records = parser.getRecords(); assertEquals(res.length, records.size()); assertTrue(records.size() > 0); for (int i = 0; i < res.length; i++) { assertArrayEquals(res[i], records.get(i).values()); } parser.close(); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void testRemoveAndAddColumns() throws IOException { // do: final CSVPrinter printer = new CSVPrinter(new StringBuilder(), CSVFormat.DEFAULT); final Map<String, String> map = recordWithHeader.toMap(); map.remove("OldColumn"); map.put("ZColumn", "NewValue"); // check: final ArrayList<String> list = new ArrayList<String>(map.values()); Collections.sort(list); printer.printRecord(list); Assert.assertEquals("A,B,C,NewValue" + CSVFormat.DEFAULT.getRecordSeparator(), printer.getOut().toString()); } #location 12 #vulnerability type RESOURCE_LEAK
#fixed code @Test public void testRemoveAndAddColumns() throws IOException { // do: final CSVPrinter printer = new CSVPrinter(new StringBuilder(), CSVFormat.DEFAULT); final Map<String, String> map = recordWithHeader.toMap(); map.remove("OldColumn"); map.put("ZColumn", "NewValue"); // check: final ArrayList<String> list = new ArrayList<String>(map.values()); Collections.sort(list); printer.printRecord(list); Assert.assertEquals("A,B,C,NewValue" + CSVFormat.DEFAULT.getRecordSeparator(), printer.getOut().toString()); printer.close(); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void testBackslashEscaping2() throws IOException { // To avoid confusion over the need for escaping chars in java code, // We will test with a forward slash as the escape char, and a single // quote as the encapsulator. final String code = "" + " , , \n" // 1) + " \t , , \n" // 2) + " // , /, , /,\n" // 3) + ""; final String[][] res = { {" ", " ", " "}, // 1 {" \t ", " ", " "}, // 2 {" / ", " , ", " ,"}, // 3 }; final CSVFormat format = CSVFormat.newFormat(',') .withRecordSeparator(CRLF).withEscape('/').withIgnoreEmptyLines(true); final CSVParser parser = CSVParser.parseString(code, format); final List<CSVRecord> records = parser.getRecords(); assertTrue(records.size() > 0); Utils.compare("", res, records); } #location 24 #vulnerability type RESOURCE_LEAK
#fixed code @Test public void testBackslashEscaping2() throws IOException { // To avoid confusion over the need for escaping chars in java code, // We will test with a forward slash as the escape char, and a single // quote as the encapsulator. final String code = "" + " , , \n" // 1) + " \t , , \n" // 2) + " // , /, , /,\n" // 3) + ""; final String[][] res = { {" ", " ", " "}, // 1 {" \t ", " ", " "}, // 2 {" / ", " , ", " ,"}, // 3 }; final CSVFormat format = CSVFormat.newFormat(',') .withRecordSeparator(CRLF).withEscape('/').withIgnoreEmptyLines(true); final CSVParser parser = CSVParser.parse(code, format); final List<CSVRecord> records = parser.getRecords(); assertTrue(records.size() > 0); Utils.compare("", res, records); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void testExcelFormat2() throws Exception { String code = "foo,baar\r\n\r\nhello,\r\n\r\nworld,\r\n"; String[][] res = { {"foo", "baar"}, {""}, {"hello", ""}, {""}, {"world", ""} }; CSVParser parser = new CSVParser(code, CSVFormat.EXCEL); String[][] tmp = parser.getRecords(); assertEquals(res.length, tmp.length); assertTrue(tmp.length > 0); for (int i = 0; i < res.length; i++) { assertTrue(Arrays.equals(res[i], tmp[i])); } } #location 13 #vulnerability type NULL_DEREFERENCE
#fixed code @Test public void testExcelFormat2() throws Exception { String code = "foo,baar\r\n\r\nhello,\r\n\r\nworld,\r\n"; String[][] res = { {"foo", "baar"}, {""}, {"hello", ""}, {""}, {"world", ""} }; CSVParser parser = new CSVParser(code, CSVFormat.EXCEL); List<CSVRecord> records = parser.getRecords(); assertEquals(res.length, records.size()); assertTrue(records.size() > 0); for (int i = 0; i < res.length; i++) { assertTrue(Arrays.equals(res[i], records.get(i).values())); } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void testCarriageReturnEndings() throws IOException { String code = "foo\rbaar,\rhello,world\r,kanu"; CSVParser parser = new CSVParser(new StringReader(code)); String[][] data = parser.getRecords(); assertEquals(4, data.length); } #location 6 #vulnerability type NULL_DEREFERENCE
#fixed code @Test public void testCarriageReturnEndings() throws IOException { String code = "foo\rbaar,\rhello,world\r,kanu"; CSVParser parser = new CSVParser(new StringReader(code)); List<CSVRecord> records = parser.getRecords(); assertEquals(4, records.size()); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public void testReadLine() throws Exception { br = getEBR(""); assertTrue(br.readLine() == null); br = getEBR("\n"); assertTrue(br.readLine().equals("")); assertTrue(br.readLine() == null); br = getEBR("foo\n\nhello"); assertEquals(0, br.getLineNumber()); assertTrue(br.readLine().equals("foo")); assertEquals(1, br.getLineNumber()); assertTrue(br.readLine().equals("")); assertEquals(2, br.getLineNumber()); assertTrue(br.readLine().equals("hello")); assertEquals(3, br.getLineNumber()); assertTrue(br.readLine() == null); assertEquals(3, br.getLineNumber()); br = getEBR("foo\n\nhello"); assertEquals('f', br.read()); assertEquals('o', br.lookAhead()); assertTrue(br.readLine().equals("oo")); assertEquals(1, br.getLineNumber()); assertEquals('\n', br.lookAhead()); assertTrue(br.readLine().equals("")); assertEquals(2, br.getLineNumber()); assertEquals('h', br.lookAhead()); assertTrue(br.readLine().equals("hello")); assertTrue(br.readLine() == null); assertEquals(3, br.getLineNumber()); br = getEBR("foo\rbaar\r\nfoo"); assertTrue(br.readLine().equals("foo")); assertEquals('b', br.lookAhead()); assertTrue(br.readLine().equals("baar")); assertEquals('f', br.lookAhead()); assertTrue(br.readLine().equals("foo")); assertTrue(br.readLine() == null); } #location 11 #vulnerability type NULL_DEREFERENCE
#fixed code public void testReadLine() throws Exception { ExtendedBufferedReader br = getEBR(""); assertTrue(br.readLine() == null); br = getEBR("\n"); assertTrue(br.readLine().equals("")); assertTrue(br.readLine() == null); br = getEBR("foo\n\nhello"); assertEquals(0, br.getLineNumber()); assertTrue(br.readLine().equals("foo")); assertEquals(1, br.getLineNumber()); assertTrue(br.readLine().equals("")); assertEquals(2, br.getLineNumber()); assertTrue(br.readLine().equals("hello")); assertEquals(3, br.getLineNumber()); assertTrue(br.readLine() == null); assertEquals(3, br.getLineNumber()); br = getEBR("foo\n\nhello"); assertEquals('f', br.read()); assertEquals('o', br.lookAhead()); assertTrue(br.readLine().equals("oo")); assertEquals(1, br.getLineNumber()); assertEquals('\n', br.lookAhead()); assertTrue(br.readLine().equals("")); assertEquals(2, br.getLineNumber()); assertEquals('h', br.lookAhead()); assertTrue(br.readLine().equals("hello")); assertTrue(br.readLine() == null); assertEquals(3, br.getLineNumber()); br = getEBR("foo\rbaar\r\nfoo"); assertTrue(br.readLine().equals("foo")); assertEquals('b', br.lookAhead()); assertTrue(br.readLine().equals("baar")); assertEquals('f', br.lookAhead()); assertTrue(br.readLine().equals("foo")); assertTrue(br.readLine() == null); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void testCSVResource() throws Exception { String line = readTestData(); assertNotNull("file must contain config line", line); final String[] split = line.split(" "); assertTrue(testName + " require 1 param", split.length >= 1); // first line starts with csv data file name CSVFormat format = CSVFormat.newFormat(',').withQuoteChar('"'); boolean checkComments = false; for (int i = 1; i < split.length; i++) { final String option = split[i]; final String[] option_parts = option.split("=", 2); if ("IgnoreEmpty".equalsIgnoreCase(option_parts[0])) { format = format.withIgnoreEmptyLines(Boolean.parseBoolean(option_parts[1])); } else if ("IgnoreSpaces".equalsIgnoreCase(option_parts[0])) { format = format.withIgnoreSurroundingSpaces(Boolean.parseBoolean(option_parts[1])); } else if ("CommentStart".equalsIgnoreCase(option_parts[0])) { format = format.withCommentStart(option_parts[1].charAt(0)); } else if ("CheckComments".equalsIgnoreCase(option_parts[0])) { checkComments = true; } else { fail(testName + " unexpected option: " + option); } } line = readTestData(); // get string version of format assertEquals(testName + " Expected format ", line, format.toString()); // Now parse the file and compare against the expected results final CSVParser parser = CSVParser.parseResource("CSVFileParser/" + split[0], Charset.forName("UTF-8"), this.getClass().getClassLoader(), format); for (final CSVRecord record : parser) { String parsed = record.toString(); if (checkComments) { final String comment = record.getComment().replace("\n", "\\n"); if (comment != null) { parsed += "#" + comment; } } final int count = record.size(); assertEquals(testName, readTestData(), count + ":" + parsed); } } #location 23 #vulnerability type RESOURCE_LEAK
#fixed code @Test public void testCSVResource() throws Exception { String line = readTestData(); assertNotNull("file must contain config line", line); final String[] split = line.split(" "); assertTrue(testName + " require 1 param", split.length >= 1); // first line starts with csv data file name CSVFormat format = CSVFormat.newFormat(',').withQuoteChar('"'); boolean checkComments = false; for (int i = 1; i < split.length; i++) { final String option = split[i]; final String[] option_parts = option.split("=", 2); if ("IgnoreEmpty".equalsIgnoreCase(option_parts[0])) { format = format.withIgnoreEmptyLines(Boolean.parseBoolean(option_parts[1])); } else if ("IgnoreSpaces".equalsIgnoreCase(option_parts[0])) { format = format.withIgnoreSurroundingSpaces(Boolean.parseBoolean(option_parts[1])); } else if ("CommentStart".equalsIgnoreCase(option_parts[0])) { format = format.withCommentStart(option_parts[1].charAt(0)); } else if ("CheckComments".equalsIgnoreCase(option_parts[0])) { checkComments = true; } else { fail(testName + " unexpected option: " + option); } } line = readTestData(); // get string version of format assertEquals(testName + " Expected format ", line, format.toString()); // Now parse the file and compare against the expected results final CSVParser parser = CSVParser.parse("CSVFileParser/" + split[0], Charset.forName("UTF-8"), this.getClass().getClassLoader(), format); for (final CSVRecord record : parser) { String parsed = record.toString(); if (checkComments) { final String comment = record.getComment().replace("\n", "\\n"); if (comment != null) { parsed += "#" + comment; } } final int count = record.size(); assertEquals(testName, readTestData(), count + ":" + parsed); } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public void testReadLookahead2() throws Exception { char[] ref = new char[5]; char[] res = new char[5]; ExtendedBufferedReader br = getEBR(""); assertEquals(0, br.read(res, 0, 0)); assertTrue(Arrays.equals(res, ref)); br = getEBR("abcdefg"); ref[0] = 'a'; ref[1] = 'b'; ref[2] = 'c'; assertEquals(3, br.read(res, 0, 3)); assertTrue(Arrays.equals(res, ref)); assertEquals('c', br.readAgain()); assertEquals('d', br.lookAhead()); ref[4] = 'd'; assertEquals(1, br.read(res, 4, 1)); assertTrue(Arrays.equals(res, ref)); assertEquals('d', br.readAgain()); } #location 23 #vulnerability type RESOURCE_LEAK
#fixed code public void testReadLookahead2() throws Exception { char[] ref = new char[5]; char[] res = new char[5]; ExtendedBufferedReader br = getBufferedReader("abcdefg"); ref[0] = 'a'; ref[1] = 'b'; ref[2] = 'c'; assertEquals(3, br.read(res, 0, 3)); assertTrue(Arrays.equals(res, ref)); assertEquals('c', br.readAgain()); assertEquals('d', br.lookAhead()); ref[4] = 'd'; assertEquals(1, br.read(res, 4, 1)); assertTrue(Arrays.equals(res, ref)); assertEquals('d', br.readAgain()); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void testReadLookahead2() throws Exception { final char[] ref = new char[5]; final char[] res = new char[5]; final ExtendedBufferedReader br = getBufferedReader("abcdefg"); ref[0] = 'a'; ref[1] = 'b'; ref[2] = 'c'; assertEquals(3, br.read(res, 0, 3)); assertArrayEquals(ref, res); assertEquals('c', br.getLastChar()); assertEquals('d', br.lookAhead()); ref[4] = 'd'; assertEquals(1, br.read(res, 4, 1)); assertArrayEquals(ref, res); assertEquals('d', br.getLastChar()); } #location 18 #vulnerability type RESOURCE_LEAK
#fixed code @Test public void testReadLookahead2() throws Exception { final char[] ref = new char[5]; final char[] res = new char[5]; final ExtendedBufferedReader br = getBufferedReader("abcdefg"); ref[0] = 'a'; ref[1] = 'b'; ref[2] = 'c'; assertEquals(3, br.read(res, 0, 3)); assertArrayEquals(ref, res); assertEquals('c', br.getLastChar()); assertEquals('d', br.lookAhead()); ref[4] = 'd'; assertEquals(1, br.read(res, 4, 1)); assertArrayEquals(ref, res); assertEquals('d', br.getLastChar()); br.close(); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public void testForEach() { List<String[]> records = new ArrayList<String[]>(); String code = "a,b,c\n1,2,3\nx,y,z"; Reader in = new StringReader(code); for (String[] record : new CSVParser(in)) { records.add(record); } assertEquals(3, records.size()); assertTrue(Arrays.equals(new String[] {"a", "b", "c"}, records.get(0))); assertTrue(Arrays.equals(new String[]{"1", "2", "3"}, records.get(1))); assertTrue(Arrays.equals(new String[] {"x", "y", "z"}, records.get(2))); } #location 11 #vulnerability type RESOURCE_LEAK
#fixed code public void testForEach() { List<String[]> records = new ArrayList<String[]>(); Reader in = new StringReader("a,b,c\n1,2,3\nx,y,z"); for (String[] record : CSVFormat.DEFAULT.parse(in)) { records.add(record); } assertEquals(3, records.size()); assertTrue(Arrays.equals(new String[]{"a", "b", "c"}, records.get(0))); assertTrue(Arrays.equals(new String[]{"1", "2", "3"}, records.get(1))); assertTrue(Arrays.equals(new String[]{"x", "y", "z"}, records.get(2))); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void testEmptyInput() throws Exception { final ExtendedBufferedReader br = getBufferedReader(""); assertEquals(END_OF_STREAM, br.read()); assertEquals(END_OF_STREAM, br.lookAhead()); assertEquals(END_OF_STREAM, br.getLastChar()); assertNull(br.readLine()); assertEquals(0, br.read(new char[10], 0, 0)); } #location 8 #vulnerability type RESOURCE_LEAK
#fixed code @Test public void testEmptyInput() throws Exception { final ExtendedBufferedReader br = getBufferedReader(""); assertEquals(END_OF_STREAM, br.read()); assertEquals(END_OF_STREAM, br.lookAhead()); assertEquals(END_OF_STREAM, br.getLastChar()); assertNull(br.readLine()); assertEquals(0, br.read(new char[10], 0, 0)); br.close(); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void testReadLine() throws Exception { ExtendedBufferedReader br = getBufferedReader(""); assertNull(br.readLine()); br = getBufferedReader("\n"); assertEquals("",br.readLine()); assertNull(br.readLine()); br = getBufferedReader("foo\n\nhello"); assertEquals(0, br.getCurrentLineNumber()); assertEquals("foo",br.readLine()); assertEquals(1, br.getCurrentLineNumber()); assertEquals("",br.readLine()); assertEquals(2, br.getCurrentLineNumber()); assertEquals("hello",br.readLine()); assertEquals(3, br.getCurrentLineNumber()); assertNull(br.readLine()); assertEquals(3, br.getCurrentLineNumber()); br = getBufferedReader("foo\n\nhello"); assertEquals('f', br.read()); assertEquals('o', br.lookAhead()); assertEquals("oo",br.readLine()); assertEquals(1, br.getCurrentLineNumber()); assertEquals('\n', br.lookAhead()); assertEquals("",br.readLine()); assertEquals(2, br.getCurrentLineNumber()); assertEquals('h', br.lookAhead()); assertEquals("hello",br.readLine()); assertNull(br.readLine()); assertEquals(3, br.getCurrentLineNumber()); br = getBufferedReader("foo\rbaar\r\nfoo"); assertEquals("foo",br.readLine()); assertEquals('b', br.lookAhead()); assertEquals("baar",br.readLine()); assertEquals('f', br.lookAhead()); assertEquals("foo",br.readLine()); assertNull(br.readLine()); } #location 4 #vulnerability type RESOURCE_LEAK
#fixed code @Test public void testReadLine() throws Exception { ExtendedBufferedReader br = getBufferedReader(""); assertNull(br.readLine()); br.close(); br = getBufferedReader("\n"); assertEquals("",br.readLine()); assertNull(br.readLine()); br.close(); br = getBufferedReader("foo\n\nhello"); assertEquals(0, br.getCurrentLineNumber()); assertEquals("foo",br.readLine()); assertEquals(1, br.getCurrentLineNumber()); assertEquals("",br.readLine()); assertEquals(2, br.getCurrentLineNumber()); assertEquals("hello",br.readLine()); assertEquals(3, br.getCurrentLineNumber()); assertNull(br.readLine()); assertEquals(3, br.getCurrentLineNumber()); br.close(); br = getBufferedReader("foo\n\nhello"); assertEquals('f', br.read()); assertEquals('o', br.lookAhead()); assertEquals("oo",br.readLine()); assertEquals(1, br.getCurrentLineNumber()); assertEquals('\n', br.lookAhead()); assertEquals("",br.readLine()); assertEquals(2, br.getCurrentLineNumber()); assertEquals('h', br.lookAhead()); assertEquals("hello",br.readLine()); assertNull(br.readLine()); assertEquals(3, br.getCurrentLineNumber()); br.close(); br = getBufferedReader("foo\rbaar\r\nfoo"); assertEquals("foo",br.readLine()); assertEquals('b', br.lookAhead()); assertEquals("baar",br.readLine()); assertEquals('f', br.lookAhead()); assertEquals("foo",br.readLine()); assertNull(br.readLine()); br.close(); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void testEndOfFileBehaviourExcel() throws Exception { final String[] codes = { "hello,\r\n\r\nworld,\r\n", "hello,\r\n\r\nworld,", "hello,\r\n\r\nworld,\"\"\r\n", "hello,\r\n\r\nworld,\"\"", "hello,\r\n\r\nworld,\n", "hello,\r\n\r\nworld,", "hello,\r\n\r\nworld,\"\"\n", "hello,\r\n\r\nworld,\"\"" }; final String[][] res = { {"hello", ""}, {""}, // Excel format does not ignore empty lines {"world", ""} }; for (final String code : codes) { final CSVParser parser = new CSVParser(code, CSVFormat.EXCEL); final List<CSVRecord> records = parser.getRecords(); assertEquals(res.length, records.size()); assertTrue(records.size() > 0); for (int i = 0; i < res.length; i++) { assertArrayEquals(res[i], records.get(i).values()); } } } #location 21 #vulnerability type RESOURCE_LEAK
#fixed code @Test public void testEndOfFileBehaviourExcel() throws Exception { final String[] codes = { "hello,\r\n\r\nworld,\r\n", "hello,\r\n\r\nworld,", "hello,\r\n\r\nworld,\"\"\r\n", "hello,\r\n\r\nworld,\"\"", "hello,\r\n\r\nworld,\n", "hello,\r\n\r\nworld,", "hello,\r\n\r\nworld,\"\"\n", "hello,\r\n\r\nworld,\"\"" }; final String[][] res = { {"hello", ""}, {""}, // Excel format does not ignore empty lines {"world", ""} }; for (final String code : codes) { final CSVParser parser = CSVParser.parseString(code, CSVFormat.EXCEL); final List<CSVRecord> records = parser.getRecords(); assertEquals(res.length, records.size()); assertTrue(records.size() > 0); for (int i = 0; i < res.length; i++) { assertArrayEquals(res[i], records.get(i).values()); } } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void testCSVFile() throws Exception { String line = readTestData(); assertNotNull("file must contain config line", line); final String[] split = line.split(" "); assertTrue(testName+" require 1 param", split.length >= 1); // first line starts with csv data file name CSVFormat format = CSVFormat.newFormat(',').withQuoteChar('"'); boolean checkComments = false; for(int i=1; i < split.length; i++) { final String option = split[i]; final String[] option_parts = option.split("=",2); if ("IgnoreEmpty".equalsIgnoreCase(option_parts[0])){ format = format.withIgnoreEmptyLines(Boolean.parseBoolean(option_parts[1])); } else if ("IgnoreSpaces".equalsIgnoreCase(option_parts[0])) { format = format.withIgnoreSurroundingSpaces(Boolean.parseBoolean(option_parts[1])); } else if ("CommentStart".equalsIgnoreCase(option_parts[0])) { format = format.withCommentStart(option_parts[1].charAt(0)); } else if ("CheckComments".equalsIgnoreCase(option_parts[0])) { checkComments = true; } else { fail(testName+" unexpected option: "+option); } } line = readTestData(); // get string version of format assertEquals(testName+" Expected format ", line, format.toString()); // Now parse the file and compare against the expected results // We use a buffered reader internally so no need to create one here. final CSVParser parser = CSVParser.parse(new File(BASE, split[0]), format); for(final CSVRecord record : parser) { String parsed = record.toString(); if (checkComments) { final String comment = record.getComment().replace("\n", "\\n"); if (comment != null) { parsed += "#" + comment; } } final int count = record.size(); assertEquals(testName, readTestData(), count+":"+parsed); } } #location 23 #vulnerability type RESOURCE_LEAK
#fixed code @Test public void testCSVFile() throws Exception { String line = readTestData(); assertNotNull("file must contain config line", line); final String[] split = line.split(" "); assertTrue(testName+" require 1 param", split.length >= 1); // first line starts with csv data file name CSVFormat format = CSVFormat.newFormat(',').withQuoteChar('"'); boolean checkComments = false; for(int i=1; i < split.length; i++) { final String option = split[i]; final String[] option_parts = option.split("=",2); if ("IgnoreEmpty".equalsIgnoreCase(option_parts[0])){ format = format.withIgnoreEmptyLines(Boolean.parseBoolean(option_parts[1])); } else if ("IgnoreSpaces".equalsIgnoreCase(option_parts[0])) { format = format.withIgnoreSurroundingSpaces(Boolean.parseBoolean(option_parts[1])); } else if ("CommentStart".equalsIgnoreCase(option_parts[0])) { format = format.withCommentStart(option_parts[1].charAt(0)); } else if ("CheckComments".equalsIgnoreCase(option_parts[0])) { checkComments = true; } else { fail(testName+" unexpected option: "+option); } } line = readTestData(); // get string version of format assertEquals(testName+" Expected format ", line, format.toString()); // Now parse the file and compare against the expected results // We use a buffered reader internally so no need to create one here. final CSVParser parser = CSVParser.parse(new File(BASE, split[0]), format); for(final CSVRecord record : parser) { String parsed = record.toString(); if (checkComments) { final String comment = record.getComment().replace("\n", "\\n"); if (comment != null) { parsed += "#" + comment; } } final int count = record.size(); assertEquals(testName, readTestData(), count+":"+parsed); } parser.close(); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public void testSkip0() throws Exception { br = getEBR(""); assertEquals(0, br.skip(0)); assertEquals(0, br.skip(1)); br = getEBR(""); assertEquals(0, br.skip(1)); br = getEBR("abcdefg"); assertEquals(0, br.skip(0)); assertEquals('a', br.lookAhead()); assertEquals(0, br.skip(0)); assertEquals('a', br.lookAhead()); assertEquals(1, br.skip(1)); assertEquals('b', br.lookAhead()); assertEquals('b', br.read()); assertEquals(3, br.skip(3)); assertEquals('f', br.lookAhead()); assertEquals(2, br.skip(5)); assertTrue(br.readLine() == null); br = getEBR("12345"); assertEquals(5, br.skip(5)); assertTrue (br.lookAhead() == ExtendedBufferedReader.END_OF_STREAM); } #location 10 #vulnerability type RESOURCE_LEAK
#fixed code public void testSkip0() throws Exception { ExtendedBufferedReader br = getEBR(""); assertEquals(0, br.skip(0)); assertEquals(0, br.skip(1)); br = getEBR(""); assertEquals(0, br.skip(1)); br = getEBR("abcdefg"); assertEquals(0, br.skip(0)); assertEquals('a', br.lookAhead()); assertEquals(0, br.skip(0)); assertEquals('a', br.lookAhead()); assertEquals(1, br.skip(1)); assertEquals('b', br.lookAhead()); assertEquals('b', br.read()); assertEquals(3, br.skip(3)); assertEquals('f', br.lookAhead()); assertEquals(2, br.skip(5)); assertTrue(br.readLine() == null); br = getEBR("12345"); assertEquals(5, br.skip(5)); assertTrue (br.lookAhead() == ExtendedBufferedReader.END_OF_STREAM); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void testReadLine() throws Exception { ExtendedBufferedReader br = getBufferedReader(""); assertTrue(br.readLine() == null); br = getBufferedReader("\n"); assertEquals("",br.readLine()); assertTrue(br.readLine() == null); br = getBufferedReader("foo\n\nhello"); assertEquals(0, br.getLineNumber()); assertEquals("foo",br.readLine()); assertEquals(1, br.getLineNumber()); assertEquals("",br.readLine()); assertEquals(2, br.getLineNumber()); assertEquals("hello",br.readLine()); assertEquals(3, br.getLineNumber()); assertTrue(br.readLine() == null); assertEquals(3, br.getLineNumber()); br = getBufferedReader("foo\n\nhello"); assertEquals('f', br.read()); assertEquals('o', br.lookAhead()); assertEquals("oo",br.readLine()); assertEquals(1, br.getLineNumber()); assertEquals('\n', br.lookAhead()); assertEquals("",br.readLine()); assertEquals(2, br.getLineNumber()); assertEquals('h', br.lookAhead()); assertEquals("hello",br.readLine()); assertTrue(br.readLine() == null); assertEquals(3, br.getLineNumber()); br = getBufferedReader("foo\rbaar\r\nfoo"); assertEquals("foo",br.readLine()); assertEquals('b', br.lookAhead()); assertEquals("baar",br.readLine()); assertEquals('f', br.lookAhead()); assertEquals("foo",br.readLine()); assertTrue(br.readLine() == null); } #location 4 #vulnerability type RESOURCE_LEAK
#fixed code @Test public void testReadLine() throws Exception { ExtendedBufferedReader br = getBufferedReader(""); assertNull(br.readLine()); br = getBufferedReader("\n"); assertEquals("",br.readLine()); assertNull(br.readLine()); br = getBufferedReader("foo\n\nhello"); assertEquals(0, br.getLineNumber()); assertEquals("foo",br.readLine()); assertEquals(1, br.getLineNumber()); assertEquals("",br.readLine()); assertEquals(2, br.getLineNumber()); assertEquals("hello",br.readLine()); assertEquals(3, br.getLineNumber()); assertNull(br.readLine()); assertEquals(3, br.getLineNumber()); br = getBufferedReader("foo\n\nhello"); assertEquals('f', br.read()); assertEquals('o', br.lookAhead()); assertEquals("oo",br.readLine()); assertEquals(1, br.getLineNumber()); assertEquals('\n', br.lookAhead()); assertEquals("",br.readLine()); assertEquals(2, br.getLineNumber()); assertEquals('h', br.lookAhead()); assertEquals("hello",br.readLine()); assertNull(br.readLine()); assertEquals(3, br.getLineNumber()); br = getBufferedReader("foo\rbaar\r\nfoo"); assertEquals("foo",br.readLine()); assertEquals('b', br.lookAhead()); assertEquals("baar",br.readLine()); assertEquals('f', br.lookAhead()); assertEquals("foo",br.readLine()); assertNull(br.readLine()); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void testExcelPrintAllIterableOfLists() throws IOException { final StringWriter sw = new StringWriter(); final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.EXCEL); printer.printRecords(Arrays.asList(new List[] { Arrays.asList(new String[] { "r1c1", "r1c2" }), Arrays.asList(new String[] { "r2c1", "r2c2" }) })); assertEquals("r1c1,r1c2" + recordSeparator + "r2c1,r2c2" + recordSeparator, sw.toString()); } #location 5 #vulnerability type RESOURCE_LEAK
#fixed code @Test public void testExcelPrintAllIterableOfLists() throws IOException { final StringWriter sw = new StringWriter(); final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.EXCEL); printer.printRecords(Arrays.asList(new List[] { Arrays.asList(new String[] { "r1c1", "r1c2" }), Arrays.asList(new String[] { "r2c1", "r2c2" }) })); assertEquals("r1c1,r1c2" + recordSeparator + "r2c1,r2c2" + recordSeparator, sw.toString()); printer.close(); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void testEmptyFile() throws Exception { final CSVParser parser = CSVParser.parseString("", CSVFormat.DEFAULT); assertNull(parser.nextRecord()); } #location 4 #vulnerability type RESOURCE_LEAK
#fixed code @Test public void testEmptyFile() throws Exception { final CSVParser parser = CSVParser.parse("", CSVFormat.DEFAULT); assertNull(parser.nextRecord()); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code private static void testCSVLexer(final boolean newToken, String test) throws Exception { Token token = new Token(); for (int i = 0; i < max; i++) { final BufferedReader reader = getReader(); Lexer lexer = new CSVLexer(format, new ExtendedBufferedReader(reader)); int count = 0; int fields = 0; long t0 = System.currentTimeMillis(); do { if (newToken) { token = new Token(); } else { token.reset(); } lexer.nextToken(token); switch(token.type) { case EOF: break; case EORECORD: fields++; count++; break; case INVALID: throw new IOException("invalid parse sequence"); case TOKEN: fields++; break; } } while (!token.type.equals(Token.Type.EOF)); Stats s = new Stats(count, fields); reader.close(); show(test, s, t0); } show(); } #location 31 #vulnerability type RESOURCE_LEAK
#fixed code private static void testCSVLexer(final boolean newToken, String test) throws Exception { Token token = new Token(); String dynamic = ""; for (int i = 0; i < max; i++) { final ExtendedBufferedReader input = new ExtendedBufferedReader(getReader()); Lexer lexer = null; if (test.startsWith("CSVLexer")) { dynamic="!"; lexer = getLexerCtor(test).newInstance(new Object[]{format, input}); } else { lexer = new CSVLexer(format, input); } int count = 0; int fields = 0; long t0 = System.currentTimeMillis(); do { if (newToken) { token = new Token(); } else { token.reset(); } lexer.nextToken(token); switch(token.type) { case EOF: break; case EORECORD: fields++; count++; break; case INVALID: throw new IOException("invalid parse sequence"); case TOKEN: fields++; break; } } while (!token.type.equals(Token.Type.EOF)); Stats s = new Stats(count, fields); input.close(); show(lexer.getClass().getSimpleName()+dynamic+" "+(newToken ? "new" : "reset"), s, t0); } show(); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void testDelimiterIsWhitespace() throws IOException { final String code = "one\ttwo\t\tfour \t five\t six"; final Lexer parser = getLexer(code, CSVFormat.TDF); assertTokenEquals(TOKEN, "one", parser.nextToken(new Token())); assertTokenEquals(TOKEN, "two", parser.nextToken(new Token())); assertTokenEquals(TOKEN, "", parser.nextToken(new Token())); assertTokenEquals(TOKEN, "four", parser.nextToken(new Token())); assertTokenEquals(TOKEN, "five", parser.nextToken(new Token())); assertTokenEquals(EOF, "six", parser.nextToken(new Token())); } #location 10 #vulnerability type RESOURCE_LEAK
#fixed code @Test public void testDelimiterIsWhitespace() throws IOException { final String code = "one\ttwo\t\tfour \t five\t six"; final Lexer parser = getLexer(code, CSVFormat.TDF); assertThat(parser.nextToken(new Token()), matches(TOKEN, "one")); assertThat(parser.nextToken(new Token()), matches(TOKEN, "two")); assertThat(parser.nextToken(new Token()), matches(TOKEN, "")); assertThat(parser.nextToken(new Token()), matches(TOKEN, "four")); assertThat(parser.nextToken(new Token()), matches(TOKEN, "five")); assertThat(parser.nextToken(new Token()), matches(EOF, "six")); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void testPrinter4() throws IOException { final StringWriter sw = new StringWriter(); final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.DEFAULT); printer.printRecord("a", "b\"c"); assertEquals("a,\"b\"\"c\"" + recordSeparator, sw.toString()); } #location 5 #vulnerability type RESOURCE_LEAK
#fixed code @Test public void testPrinter4() throws IOException { final StringWriter sw = new StringWriter(); final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.DEFAULT); printer.printRecord("a", "b\"c"); assertEquals("a,\"b\"\"c\"" + recordSeparator, sw.toString()); printer.close(); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void testExcelPrintAllArrayOfLists() throws IOException { final StringWriter sw = new StringWriter(); final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.EXCEL); printer.printRecords(new List[] { Arrays.asList(new String[] { "r1c1", "r1c2" }), Arrays.asList(new String[] { "r2c1", "r2c2" }) }); assertEquals("r1c1,r1c2" + recordSeparator + "r2c1,r2c2" + recordSeparator, sw.toString()); } #location 5 #vulnerability type RESOURCE_LEAK
#fixed code @Test public void testExcelPrintAllArrayOfLists() throws IOException { final StringWriter sw = new StringWriter(); final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.EXCEL); printer.printRecords(new List[] { Arrays.asList(new String[] { "r1c1", "r1c2" }), Arrays.asList(new String[] { "r2c1", "r2c2" }) }); assertEquals("r1c1,r1c2" + recordSeparator + "r2c1,r2c2" + recordSeparator, sw.toString()); printer.close(); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void testEmptyLineBehaviourExcel() throws Exception { final String[] codes = { "hello,\r\n\r\n\r\n", "hello,\n\n\n", "hello,\"\"\r\n\r\n\r\n", "hello,\"\"\n\n\n" }; final String[][] res = { {"hello", ""}, {""}, // Excel format does not ignore empty lines {""} }; for (final String code : codes) { final CSVParser parser = new CSVParser(code, CSVFormat.EXCEL); final List<CSVRecord> records = parser.getRecords(); assertEquals(res.length, records.size()); assertTrue(records.size() > 0); for (int i = 0; i < res.length; i++) { assertArrayEquals(res[i], records.get(i).values()); } } } #location 16 #vulnerability type RESOURCE_LEAK
#fixed code @Test public void testEmptyLineBehaviourExcel() throws Exception { final String[] codes = { "hello,\r\n\r\n\r\n", "hello,\n\n\n", "hello,\"\"\r\n\r\n\r\n", "hello,\"\"\n\n\n" }; final String[][] res = { {"hello", ""}, {""}, // Excel format does not ignore empty lines {""} }; for (final String code : codes) { final CSVParser parser = CSVParser.parseString(code, CSVFormat.EXCEL); final List<CSVRecord> records = parser.getRecords(); assertEquals(res.length, records.size()); assertTrue(records.size() > 0); for (int i = 0; i < res.length; i++) { assertArrayEquals(res[i], records.get(i).values()); } } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void testNextToken3Escaping() throws IOException { /* file: a,\,,b * \,, */ String code = "a,\\,,b\\\\\n\\,,\\\nc,d\\\n"; CSVFormat format = CSVFormat.DEFAULT.withEscape('\\'); assertTrue(format.isEscaping()); Lexer parser = getLexer(code, format); assertTokenEquals(TOKEN, "a", parser.nextToken(new Token())); assertTokenEquals(TOKEN, ",", parser.nextToken(new Token())); assertTokenEquals(EORECORD, "b\\", parser.nextToken(new Token())); assertTokenEquals(TOKEN, ",", parser.nextToken(new Token())); assertTokenEquals(TOKEN, "\nc", parser.nextToken(new Token())); assertTokenEquals(EOF, "d\n", parser.nextToken(new Token())); assertTokenEquals(EOF, "", parser.nextToken(new Token())); } #location 17 #vulnerability type RESOURCE_LEAK
#fixed code @Test public void testNextToken3Escaping() throws IOException { /* file: a,\,,b * \,, */ String code = "a,\\,,b\\\\\n\\,,\\\nc,d\\\r\ne"; CSVFormat format = CSVFormat.DEFAULT.withEscape('\\').withEmptyLinesIgnored(false); assertTrue(format.isEscaping()); Lexer parser = getLexer(code, format); assertTokenEquals(TOKEN, "a", parser.nextToken(new Token())); assertTokenEquals(TOKEN, ",", parser.nextToken(new Token())); assertTokenEquals(EORECORD, "b\\", parser.nextToken(new Token())); assertTokenEquals(TOKEN, ",", parser.nextToken(new Token())); assertTokenEquals(TOKEN, "\nc", parser.nextToken(new Token())); assertTokenEquals(EORECORD, "d\r", parser.nextToken(new Token())); assertTokenEquals(EOF, "e", parser.nextToken(new Token())); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void testEndOfFileBehaviorCSV() throws Exception { final String[] codes = { "hello,\r\n\r\nworld,\r\n", "hello,\r\n\r\nworld,", "hello,\r\n\r\nworld,\"\"\r\n", "hello,\r\n\r\nworld,\"\"", "hello,\r\n\r\nworld,\n", "hello,\r\n\r\nworld,", "hello,\r\n\r\nworld,\"\"\n", "hello,\r\n\r\nworld,\"\"" }; final String[][] res = { {"hello", ""}, // CSV format ignores empty lines {"world", ""} }; for (final String code : codes) { final CSVParser parser = CSVParser.parse(code, CSVFormat.DEFAULT); final List<CSVRecord> records = parser.getRecords(); assertEquals(res.length, records.size()); assertTrue(records.size() > 0); for (int i = 0; i < res.length; i++) { assertArrayEquals(res[i], records.get(i).values()); } } } #location 19 #vulnerability type RESOURCE_LEAK
#fixed code @Test public void testEndOfFileBehaviorCSV() throws Exception { final String[] codes = { "hello,\r\n\r\nworld,\r\n", "hello,\r\n\r\nworld,", "hello,\r\n\r\nworld,\"\"\r\n", "hello,\r\n\r\nworld,\"\"", "hello,\r\n\r\nworld,\n", "hello,\r\n\r\nworld,", "hello,\r\n\r\nworld,\"\"\n", "hello,\r\n\r\nworld,\"\"" }; final String[][] res = { {"hello", ""}, // CSV format ignores empty lines {"world", ""} }; for (final String code : codes) { final CSVParser parser = CSVParser.parse(code, CSVFormat.DEFAULT); final List<CSVRecord> records = parser.getRecords(); assertEquals(res.length, records.size()); assertTrue(records.size() > 0); for (int i = 0; i < res.length; i++) { assertArrayEquals(res[i], records.get(i).values()); } parser.close(); } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void testGetRecords() throws IOException { final CSVParser parser = CSVParser.parseString(CSVINPUT, CSVFormat.DEFAULT.withIgnoreSurroundingSpaces(true)); final List<CSVRecord> records = parser.getRecords(); assertEquals(RESULT.length, records.size()); assertTrue(records.size() > 0); for (int i = 0; i < RESULT.length; i++) { assertArrayEquals(RESULT[i], records.get(i).values()); } } #location 4 #vulnerability type RESOURCE_LEAK
#fixed code @Test public void testGetRecords() throws IOException { final CSVParser parser = CSVParser.parse(CSVINPUT, CSVFormat.DEFAULT.withIgnoreSurroundingSpaces(true)); final List<CSVRecord> records = parser.getRecords(); assertEquals(RESULT.length, records.size()); assertTrue(records.size() > 0); for (int i = 0; i < RESULT.length; i++) { assertArrayEquals(RESULT[i], records.get(i).values()); } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code private static void testParseCommonsCSV() throws Exception { for (int i = 0; i < max; i++) { final BufferedReader reader = getReader(); final CSVParser parser = new CSVParser(reader, format); final long t0 = System.currentTimeMillis(); final Stats s = iterate(parser); reader.close(); show("CSV", s, t0); } show(); } #location 6 #vulnerability type RESOURCE_LEAK
#fixed code private static void testParseCommonsCSV() throws Exception { for (int i = 0; i < max; i++) { final BufferedReader reader = getReader(); final CSVParser parser = new CSVParser(reader, format); final long t0 = System.currentTimeMillis(); final Stats s = iterate(parser); reader.close(); show("CSV", s, t0); parser.close(); } show(); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void testDefaultFormat() throws IOException { String code = "" + "a,b\n" // 1) + "\"\n\",\" \"\n" // 2) + "\"\",#\n" // 2) ; String[][] res = { {"a", "b"}, {"\n", " "}, {"", "#"}, }; CSVFormat format = CSVFormat.DEFAULT; assertEquals(CSVFormat.DISABLED, format.getCommentStart()); CSVParser parser = new CSVParser(code, format); String[][] tmp = parser.getRecords(); assertTrue(tmp.length > 0); if (!CSVPrinterTest.equals(res, tmp)) { assertTrue(false); } String[][] res_comments = { {"a", "b"}, {"\n", " "}, {""}, }; format = CSVFormat.DEFAULT.withCommentStart('#'); parser = new CSVParser(code, format); tmp = parser.getRecords(); if (!CSVPrinterTest.equals(res_comments, tmp)) { assertTrue(false); } } #location 20 #vulnerability type NULL_DEREFERENCE
#fixed code @Test public void testDefaultFormat() throws IOException { String code = "" + "a,b\n" // 1) + "\"\n\",\" \"\n" // 2) + "\"\",#\n" // 2) ; String[][] res = { {"a", "b"}, {"\n", " "}, {"", "#"}, }; CSVFormat format = CSVFormat.DEFAULT; assertEquals(CSVFormat.DISABLED, format.getCommentStart()); CSVParser parser = new CSVParser(code, format); List<CSVRecord> records = parser.getRecords(); assertTrue(records.size() > 0); assertTrue(CSVPrinterTest.equals(res, records)); String[][] res_comments = { {"a", "b"}, {"\n", " "}, {""}, }; format = CSVFormat.DEFAULT.withCommentStart('#'); parser = new CSVParser(code, format); records = parser.getRecords(); assertTrue(CSVPrinterTest.equals(res_comments, records)); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test // TODO this may lead to strange behavior, throw an exception if iterator() has already been called? public void testMultipleIterators() throws Exception { final CSVParser parser = CSVParser.parse("a,b,c" + CR + "d,e,f", CSVFormat.DEFAULT); final Iterator<CSVRecord> itr1 = parser.iterator(); final Iterator<CSVRecord> itr2 = parser.iterator(); final CSVRecord first = itr1.next(); assertEquals("a", first.get(0)); assertEquals("b", first.get(1)); assertEquals("c", first.get(2)); final CSVRecord second = itr2.next(); assertEquals("d", second.get(0)); assertEquals("e", second.get(1)); assertEquals("f", second.get(2)); } #location 13 #vulnerability type RESOURCE_LEAK
#fixed code @Test // TODO this may lead to strange behavior, throw an exception if iterator() has already been called? public void testMultipleIterators() throws Exception { final CSVParser parser = CSVParser.parse("a,b,c" + CR + "d,e,f", CSVFormat.DEFAULT); final Iterator<CSVRecord> itr1 = parser.iterator(); final Iterator<CSVRecord> itr2 = parser.iterator(); final CSVRecord first = itr1.next(); assertEquals("a", first.get(0)); assertEquals("b", first.get(1)); assertEquals("c", first.get(2)); final CSVRecord second = itr2.next(); assertEquals("d", second.get(0)); assertEquals("e", second.get(1)); assertEquals("f", second.get(2)); parser.close(); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void testExcelFormat2() throws Exception { final String code = "foo,baar\r\n\r\nhello,\r\n\r\nworld,\r\n"; final String[][] res = { {"foo", "baar"}, {""}, {"hello", ""}, {""}, {"world", ""} }; final CSVParser parser = new CSVParser(code, CSVFormat.EXCEL); final List<CSVRecord> records = parser.getRecords(); assertEquals(res.length, records.size()); assertTrue(records.size() > 0); for (int i = 0; i < res.length; i++) { assertArrayEquals(res[i], records.get(i).values()); } } #location 12 #vulnerability type RESOURCE_LEAK
#fixed code @Test public void testExcelFormat2() throws Exception { final String code = "foo,baar\r\n\r\nhello,\r\n\r\nworld,\r\n"; final String[][] res = { {"foo", "baar"}, {""}, {"hello", ""}, {""}, {"world", ""} }; final CSVParser parser = CSVParser.parseString(code, CSVFormat.EXCEL); final List<CSVRecord> records = parser.getRecords(); assertEquals(res.length, records.size()); assertTrue(records.size() > 0); for (int i = 0; i < res.length; i++) { assertArrayEquals(res[i], records.get(i).values()); } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void testBackslashEscaping2() throws IOException { // To avoid confusion over the need for escaping chars in java code, // We will test with a forward slash as the escape char, and a single // quote as the encapsulator. String code = "" + " , , \n" // 1) + " \t , , \n" // 2) + " // , /, , /,\n" // 3) + ""; String[][] res = { {" ", " ", " "}, // 1 {" \t ", " ", " "}, // 2 {" / ", " , ", " ,"}, // 3 }; CSVFormat format = new CSVFormat(',', CSVFormat.DISABLED, CSVFormat.DISABLED, '/', false, false, true, true, "\r\n", null); CSVParser parser = new CSVParser(code, format); List<CSVRecord> records = parser.getRecords(); assertTrue(records.size() > 0); assertTrue(CSVPrinterTest.equals(res, records)); } #location 23 #vulnerability type RESOURCE_LEAK
#fixed code @Test public void testBackslashEscaping2() throws IOException { // To avoid confusion over the need for escaping chars in java code, // We will test with a forward slash as the escape char, and a single // quote as the encapsulator. String code = "" + " , , \n" // 1) + " \t , , \n" // 2) + " // , /, , /,\n" // 3) + ""; String[][] res = { {" ", " ", " "}, // 1 {" \t ", " ", " "}, // 2 {" / ", " , ", " ,"}, // 3 }; CSVFormat format = new CSVFormat(',', CSVFormat.DISABLED, CSVFormat.DISABLED, '/', false, false, true, "\r\n", null); CSVParser parser = new CSVParser(code, format); List<CSVRecord> records = parser.getRecords(); assertTrue(records.size() > 0); assertTrue(CSVPrinterTest.equals(res, records)); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void parse() throws IOException { final File csvData = new File("src/test/resources/csv-167/sample1.csv"); final BufferedReader br = new BufferedReader(new FileReader(csvData)); String s = null; int totcomment = 0; int totrecs = 0; boolean lastWasComment = false; while((s=br.readLine()) != null) { if (s.startsWith("#")) { if (!lastWasComment) { // comments are merged totcomment++; } lastWasComment = true; } else { totrecs++; lastWasComment = false; } } br.close(); CSVFormat format = CSVFormat.DEFAULT; // format = format.withAllowMissingColumnNames(false); format = format.withCommentMarker('#'); format = format.withDelimiter(','); format = format.withEscape('\\'); format = format.withHeader("author", "title", "publishDate"); format = format.withHeaderComments("headerComment"); format = format.withNullString("NULL"); format = format.withIgnoreEmptyLines(true); format = format.withIgnoreSurroundingSpaces(true); format = format.withQuote('"'); format = format.withQuoteMode(QuoteMode.ALL); format = format.withRecordSeparator('\n'); format = format.withSkipHeaderRecord(false); // final CSVParser parser = CSVParser.parse(csvData, Charset.defaultCharset(), format); int comments = 0; int records = 0; for (final CSVRecord csvRecord : parser) { // System.out.println(csvRecord.isComment() + "[" + csvRecord.toString() + "]"); records++; if (csvRecord.hasComment()) { comments++; } } // Comment lines are concatenated, in this example 4 lines become 2 comments. Assert.assertEquals(totcomment, comments); Assert.assertEquals(totrecs, records); // records includes the header } #location 13 #vulnerability type RESOURCE_LEAK
#fixed code @Test public void parse() throws IOException { final BufferedReader br = new BufferedReader(getTestInput()); String s = null; int totcomment = 0; int totrecs = 0; boolean lastWasComment = false; while((s=br.readLine()) != null) { if (s.startsWith("#")) { if (!lastWasComment) { // comments are merged totcomment++; } lastWasComment = true; } else { totrecs++; lastWasComment = false; } } br.close(); CSVFormat format = CSVFormat.DEFAULT; // format = format.withAllowMissingColumnNames(false); format = format.withCommentMarker('#'); format = format.withDelimiter(','); format = format.withEscape('\\'); format = format.withHeader("author", "title", "publishDate"); format = format.withHeaderComments("headerComment"); format = format.withNullString("NULL"); format = format.withIgnoreEmptyLines(true); format = format.withIgnoreSurroundingSpaces(true); format = format.withQuote('"'); format = format.withQuoteMode(QuoteMode.ALL); format = format.withRecordSeparator('\n'); format = format.withSkipHeaderRecord(false); // final CSVParser parser = format.parse(getTestInput()); int comments = 0; int records = 0; for (final CSVRecord csvRecord : parser) { records++; if (csvRecord.hasComment()) { comments++; } } // Comment lines are concatenated, in this example 4 lines become 2 comments. Assert.assertEquals(totcomment, comments); Assert.assertEquals(totrecs, records); // records includes the header }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void testLineFeedEndings() throws IOException { final String code = "foo\nbaar,\nhello,world\n,kanu"; final CSVParser parser = new CSVParser(new StringReader(code)); final List<CSVRecord> records = parser.getRecords(); assertEquals(4, records.size()); } #location 5 #vulnerability type RESOURCE_LEAK
#fixed code @Test public void testLineFeedEndings() throws IOException { final String code = "foo\nbaar,\nhello,world\n,kanu"; final CSVParser parser = CSVParser.parseString(code); final List<CSVRecord> records = parser.getRecords(); assertEquals(4, records.size()); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void testExcelFormat2() throws Exception { final String code = "foo,baar\r\n\r\nhello,\r\n\r\nworld,\r\n"; final String[][] res = { {"foo", "baar"}, {""}, {"hello", ""}, {""}, {"world", ""} }; final CSVParser parser = CSVParser.parse(code, CSVFormat.EXCEL); final List<CSVRecord> records = parser.getRecords(); assertEquals(res.length, records.size()); assertTrue(records.size() > 0); for (int i = 0; i < res.length; i++) { assertArrayEquals(res[i], records.get(i).values()); } } #location 12 #vulnerability type RESOURCE_LEAK
#fixed code @Test public void testExcelFormat2() throws Exception { final String code = "foo,baar\r\n\r\nhello,\r\n\r\nworld,\r\n"; final String[][] res = { {"foo", "baar"}, {""}, {"hello", ""}, {""}, {"world", ""} }; final CSVParser parser = CSVParser.parse(code, CSVFormat.EXCEL); final List<CSVRecord> records = parser.getRecords(); assertEquals(res.length, records.size()); assertTrue(records.size() > 0); for (int i = 0; i < res.length; i++) { assertArrayEquals(res[i], records.get(i).values()); } parser.close(); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void testGetLine() throws IOException { final CSVParser parser = CSVParser.parse(CSVINPUT, CSVFormat.DEFAULT.withIgnoreSurroundingSpaces(true)); for (final String[] re : RESULT) { assertArrayEquals(re, parser.nextRecord().values()); } assertNull(parser.nextRecord()); } #location 8 #vulnerability type RESOURCE_LEAK
#fixed code @Test public void testGetLine() throws IOException { final CSVParser parser = CSVParser.parse(CSVINPUT, CSVFormat.DEFAULT.withIgnoreSurroundingSpaces(true)); for (final String[] re : RESULT) { assertArrayEquals(re, parser.nextRecord().values()); } assertNull(parser.nextRecord()); parser.close(); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void testParseCustomNullValues() throws IOException { final StringWriter sw = new StringWriter(); final CSVFormat format = CSVFormat.DEFAULT.withNullString("NULL"); final CSVPrinter printer = new CSVPrinter(sw, format); printer.printRecord("a", null, "b"); printer.close(); final String csvString = sw.toString(); assertEquals("a,NULL,b" + recordSeparator, csvString); final Iterable<CSVRecord> iterable = format.parse(new StringReader(csvString)); final Iterator<CSVRecord> iterator = iterable.iterator(); final CSVRecord record = iterator.next(); assertEquals("a", record.get(0)); assertEquals(null, record.get(1)); assertEquals("b", record.get(2)); assertFalse(iterator.hasNext()); } #location 16 #vulnerability type RESOURCE_LEAK
#fixed code @Test public void testParseCustomNullValues() throws IOException { final StringWriter sw = new StringWriter(); final CSVFormat format = CSVFormat.DEFAULT.withNullString("NULL"); final CSVPrinter printer = new CSVPrinter(sw, format); printer.printRecord("a", null, "b"); printer.close(); final String csvString = sw.toString(); assertEquals("a,NULL,b" + recordSeparator, csvString); final Iterable<CSVRecord> iterable = format.parse(new StringReader(csvString)); final Iterator<CSVRecord> iterator = iterable.iterator(); final CSVRecord record = iterator.next(); assertEquals("a", record.get(0)); assertEquals(null, record.get(1)); assertEquals("b", record.get(2)); assertFalse(iterator.hasNext()); ((CSVParser) iterable).close(); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void testPrinter2() throws IOException { final StringWriter sw = new StringWriter(); final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.DEFAULT); printer.printRecord("a,b", "b"); assertEquals("\"a,b\",b" + recordSeparator, sw.toString()); } #location 5 #vulnerability type RESOURCE_LEAK
#fixed code @Test public void testPrinter2() throws IOException { final StringWriter sw = new StringWriter(); final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.DEFAULT); printer.printRecord("a,b", "b"); assertEquals("\"a,b\",b" + recordSeparator, sw.toString()); printer.close(); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public void testReadLookahead2() throws Exception { char[] ref = new char[5]; char[] res = new char[5]; ExtendedBufferedReader br = getEBR(""); assertEquals(0, br.read(res, 0, 0)); assertTrue(Arrays.equals(res, ref)); br = getEBR("abcdefg"); ref[0] = 'a'; ref[1] = 'b'; ref[2] = 'c'; assertEquals(3, br.read(res, 0, 3)); assertTrue(Arrays.equals(res, ref)); assertEquals('c', br.readAgain()); assertEquals('d', br.lookAhead()); ref[4] = 'd'; assertEquals(1, br.read(res, 4, 1)); assertTrue(Arrays.equals(res, ref)); assertEquals('d', br.readAgain()); } #location 21 #vulnerability type RESOURCE_LEAK
#fixed code public void testReadLookahead2() throws Exception { char[] ref = new char[5]; char[] res = new char[5]; ExtendedBufferedReader br = getBufferedReader("abcdefg"); ref[0] = 'a'; ref[1] = 'b'; ref[2] = 'c'; assertEquals(3, br.read(res, 0, 3)); assertTrue(Arrays.equals(res, ref)); assertEquals('c', br.readAgain()); assertEquals('d', br.lookAhead()); ref[4] = 'd'; assertEquals(1, br.read(res, 4, 1)); assertTrue(Arrays.equals(res, ref)); assertEquals('d', br.readAgain()); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void testGetRecords() throws IOException { CSVParser parser = new CSVParser(new StringReader(code)); String[][] tmp = parser.getRecords(); assertEquals(res.length, tmp.length); assertTrue(tmp.length > 0); for (int i = 0; i < res.length; i++) { assertTrue(Arrays.equals(res[i], tmp[i])); } } #location 5 #vulnerability type NULL_DEREFERENCE
#fixed code @Test public void testGetRecords() throws IOException { CSVParser parser = new CSVParser(new StringReader(code)); List<CSVRecord> records = parser.getRecords(); assertEquals(res.length, records.size()); assertTrue(records.size() > 0); for (int i = 0; i < res.length; i++) { assertTrue(Arrays.equals(res[i], records.get(i).values())); } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void testReadLine() throws Exception { ExtendedBufferedReader br = getBufferedReader(""); assertNull(br.readLine()); br = getBufferedReader("\n"); assertEquals("",br.readLine()); assertNull(br.readLine()); br = getBufferedReader("foo\n\nhello"); assertEquals(0, br.getCurrentLineNumber()); assertEquals("foo",br.readLine()); assertEquals(1, br.getCurrentLineNumber()); assertEquals("",br.readLine()); assertEquals(2, br.getCurrentLineNumber()); assertEquals("hello",br.readLine()); assertEquals(3, br.getCurrentLineNumber()); assertNull(br.readLine()); assertEquals(3, br.getCurrentLineNumber()); br = getBufferedReader("foo\n\nhello"); assertEquals('f', br.read()); assertEquals('o', br.lookAhead()); assertEquals("oo",br.readLine()); assertEquals(1, br.getCurrentLineNumber()); assertEquals('\n', br.lookAhead()); assertEquals("",br.readLine()); assertEquals(2, br.getCurrentLineNumber()); assertEquals('h', br.lookAhead()); assertEquals("hello",br.readLine()); assertNull(br.readLine()); assertEquals(3, br.getCurrentLineNumber()); br = getBufferedReader("foo\rbaar\r\nfoo"); assertEquals("foo",br.readLine()); assertEquals('b', br.lookAhead()); assertEquals("baar",br.readLine()); assertEquals('f', br.lookAhead()); assertEquals("foo",br.readLine()); assertNull(br.readLine()); } #location 17 #vulnerability type RESOURCE_LEAK
#fixed code @Test public void testReadLine() throws Exception { ExtendedBufferedReader br = getBufferedReader(""); assertNull(br.readLine()); br.close(); br = getBufferedReader("\n"); assertEquals("",br.readLine()); assertNull(br.readLine()); br.close(); br = getBufferedReader("foo\n\nhello"); assertEquals(0, br.getCurrentLineNumber()); assertEquals("foo",br.readLine()); assertEquals(1, br.getCurrentLineNumber()); assertEquals("",br.readLine()); assertEquals(2, br.getCurrentLineNumber()); assertEquals("hello",br.readLine()); assertEquals(3, br.getCurrentLineNumber()); assertNull(br.readLine()); assertEquals(3, br.getCurrentLineNumber()); br.close(); br = getBufferedReader("foo\n\nhello"); assertEquals('f', br.read()); assertEquals('o', br.lookAhead()); assertEquals("oo",br.readLine()); assertEquals(1, br.getCurrentLineNumber()); assertEquals('\n', br.lookAhead()); assertEquals("",br.readLine()); assertEquals(2, br.getCurrentLineNumber()); assertEquals('h', br.lookAhead()); assertEquals("hello",br.readLine()); assertNull(br.readLine()); assertEquals(3, br.getCurrentLineNumber()); br.close(); br = getBufferedReader("foo\rbaar\r\nfoo"); assertEquals("foo",br.readLine()); assertEquals('b', br.lookAhead()); assertEquals("baar",br.readLine()); assertEquals('f', br.lookAhead()); assertEquals("foo",br.readLine()); assertNull(br.readLine()); br.close(); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public void testReadLookahead2() throws Exception { char[] ref = new char[5]; char[] res = new char[5]; br = getEBR(""); assertEquals(0, br.read(res, 0, 0)); assertTrue(Arrays.equals(res, ref)); br = getEBR("abcdefg"); ref[0] = 'a'; ref[1] = 'b'; ref[2] = 'c'; assertEquals(3, br.read(res, 0, 3)); assertTrue(Arrays.equals(res, ref)); assertEquals('c', br.readAgain()); assertEquals('d', br.lookAhead()); ref[4] = 'd'; assertEquals(1, br.read(res, 4, 1)); assertTrue(Arrays.equals(res, ref)); assertEquals('d', br.readAgain()); } #location 9 #vulnerability type RESOURCE_LEAK
#fixed code public void testReadLookahead2() throws Exception { char[] ref = new char[5]; char[] res = new char[5]; ExtendedBufferedReader br = getEBR(""); assertEquals(0, br.read(res, 0, 0)); assertTrue(Arrays.equals(res, ref)); br = getEBR("abcdefg"); ref[0] = 'a'; ref[1] = 'b'; ref[2] = 'c'; assertEquals(3, br.read(res, 0, 3)); assertTrue(Arrays.equals(res, ref)); assertEquals('c', br.readAgain()); assertEquals('d', br.lookAhead()); ref[4] = 'd'; assertEquals(1, br.read(res, 4, 1)); assertTrue(Arrays.equals(res, ref)); assertEquals('d', br.readAgain()); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void testCarriageReturnLineFeedEndings() throws IOException { final String code = "foo\r\nbaar,\r\nhello,world\r\n,kanu"; final CSVParser parser = CSVParser.parse(code, CSVFormat.DEFAULT); final List<CSVRecord> records = parser.getRecords(); assertEquals(4, records.size()); } #location 5 #vulnerability type RESOURCE_LEAK
#fixed code @Test public void testCarriageReturnLineFeedEndings() throws IOException { final String code = "foo\r\nbaar,\r\nhello,world\r\n,kanu"; final CSVParser parser = CSVParser.parse(code, CSVFormat.DEFAULT); final List<CSVRecord> records = parser.getRecords(); assertEquals(4, records.size()); parser.close(); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void testEmptyLineBehaviourCSV() throws Exception { final String[] codes = { "hello,\r\n\r\n\r\n", "hello,\n\n\n", "hello,\"\"\r\n\r\n\r\n", "hello,\"\"\n\n\n" }; final String[][] res = { {"hello", ""} // CSV format ignores empty lines }; for (final String code : codes) { final CSVParser parser = CSVParser.parseString(code, CSVFormat.DEFAULT); final List<CSVRecord> records = parser.getRecords(); assertEquals(res.length, records.size()); assertTrue(records.size() > 0); for (int i = 0; i < res.length; i++) { assertArrayEquals(res[i], records.get(i).values()); } } } #location 14 #vulnerability type RESOURCE_LEAK
#fixed code @Test public void testEmptyLineBehaviourCSV() throws Exception { final String[] codes = { "hello,\r\n\r\n\r\n", "hello,\n\n\n", "hello,\"\"\r\n\r\n\r\n", "hello,\"\"\n\n\n" }; final String[][] res = { {"hello", ""} // CSV format ignores empty lines }; for (final String code : codes) { final CSVParser parser = CSVParser.parse(code, CSVFormat.DEFAULT); final List<CSVRecord> records = parser.getRecords(); assertEquals(res.length, records.size()); assertTrue(records.size() > 0); for (int i = 0; i < res.length; i++) { assertArrayEquals(res[i], records.get(i).values()); } } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public void doOneRandom(final CSVFormat format) throws Exception { final Random r = new Random(); final int nLines = r.nextInt(4) + 1; final int nCol = r.nextInt(3) + 1; // nLines=1;nCol=2; final String[][] lines = new String[nLines][]; for (int i = 0; i < nLines; i++) { final String[] line = new String[nCol]; lines[i] = line; for (int j = 0; j < nCol; j++) { line[j] = randStr(); } } final StringWriter sw = new StringWriter(); final CSVPrinter printer = new CSVPrinter(sw, format); for (int i = 0; i < nLines; i++) { // for (int j=0; j<lines[i].length; j++) System.out.println("### VALUE=:" + printable(lines[i][j])); printer.printRecord((Object[])lines[i]); } printer.flush(); printer.close(); final String result = sw.toString(); // System.out.println("### :" + printable(result)); final CSVParser parser = new CSVParser(result, format); final List<CSVRecord> parseResult = parser.getRecords(); Utils.compare("Printer output :" + printable(result), lines, parseResult); } #location 30 #vulnerability type RESOURCE_LEAK
#fixed code public void doOneRandom(final CSVFormat format) throws Exception { final Random r = new Random(); final int nLines = r.nextInt(4) + 1; final int nCol = r.nextInt(3) + 1; // nLines=1;nCol=2; final String[][] lines = new String[nLines][]; for (int i = 0; i < nLines; i++) { final String[] line = new String[nCol]; lines[i] = line; for (int j = 0; j < nCol; j++) { line[j] = randStr(); } } final StringWriter sw = new StringWriter(); final CSVPrinter printer = new CSVPrinter(sw, format); for (int i = 0; i < nLines; i++) { // for (int j=0; j<lines[i].length; j++) System.out.println("### VALUE=:" + printable(lines[i][j])); printer.printRecord((Object[])lines[i]); } printer.flush(); printer.close(); final String result = sw.toString(); // System.out.println("### :" + printable(result)); final CSVParser parser = CSVParser.parseString(result, format); final List<CSVRecord> parseResult = parser.getRecords(); Utils.compare("Printer output :" + printable(result), lines, parseResult); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void testEndOfFileBehaviorCSV() throws Exception { String[] codes = { "hello,\r\n\r\nworld,\r\n", "hello,\r\n\r\nworld,", "hello,\r\n\r\nworld,\"\"\r\n", "hello,\r\n\r\nworld,\"\"", "hello,\r\n\r\nworld,\n", "hello,\r\n\r\nworld,", "hello,\r\n\r\nworld,\"\"\n", "hello,\r\n\r\nworld,\"\"" }; String[][] res = { {"hello", ""}, // CSV format ignores empty lines {"world", ""} }; for (String code : codes) { CSVParser parser = new CSVParser(new StringReader(code)); String[][] tmp = parser.getRecords(); assertEquals(res.length, tmp.length); assertTrue(tmp.length > 0); for (int i = 0; i < res.length; i++) { assertTrue(Arrays.equals(res[i], tmp[i])); } } } #location 20 #vulnerability type NULL_DEREFERENCE
#fixed code @Test public void testEndOfFileBehaviorCSV() throws Exception { String[] codes = { "hello,\r\n\r\nworld,\r\n", "hello,\r\n\r\nworld,", "hello,\r\n\r\nworld,\"\"\r\n", "hello,\r\n\r\nworld,\"\"", "hello,\r\n\r\nworld,\n", "hello,\r\n\r\nworld,", "hello,\r\n\r\nworld,\"\"\n", "hello,\r\n\r\nworld,\"\"" }; String[][] res = { {"hello", ""}, // CSV format ignores empty lines {"world", ""} }; for (String code : codes) { CSVParser parser = new CSVParser(new StringReader(code)); List<CSVRecord> records = parser.getRecords(); assertEquals(res.length, records.size()); assertTrue(records.size() > 0); for (int i = 0; i < res.length; i++) { assertTrue(Arrays.equals(res[i], records.get(i).values())); } } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void testCarriageReturnLineFeedEndings() throws IOException { String code = "foo\r\nbaar,\r\nhello,world\r\n,kanu"; CSVParser parser = new CSVParser(new StringReader(code)); String[][] data = parser.getRecords(); assertEquals(4, data.length); } #location 6 #vulnerability type NULL_DEREFERENCE
#fixed code @Test public void testCarriageReturnLineFeedEndings() throws IOException { String code = "foo\r\nbaar,\r\nhello,world\r\n,kanu"; CSVParser parser = new CSVParser(new StringReader(code)); List<CSVRecord> records = parser.getRecords(); assertEquals(4, records.size()); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void testGetLine() throws IOException { final CSVParser parser = CSVParser.parseString(CSVINPUT, CSVFormat.DEFAULT.withIgnoreSurroundingSpaces(true)); for (final String[] re : RESULT) { assertArrayEquals(re, parser.nextRecord().values()); } assertNull(parser.nextRecord()); } #location 8 #vulnerability type RESOURCE_LEAK
#fixed code @Test public void testGetLine() throws IOException { final CSVParser parser = CSVParser.parse(CSVINPUT, CSVFormat.DEFAULT.withIgnoreSurroundingSpaces(true)); for (final String[] re : RESULT) { assertArrayEquals(re, parser.nextRecord().values()); } assertNull(parser.nextRecord()); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void testCarriageReturnEndings() throws IOException { final String code = "foo\rbaar,\rhello,world\r,kanu"; final CSVParser parser = new CSVParser(new StringReader(code)); final List<CSVRecord> records = parser.getRecords(); assertEquals(4, records.size()); } #location 5 #vulnerability type RESOURCE_LEAK
#fixed code @Test public void testCarriageReturnEndings() throws IOException { final String code = "foo\rbaar,\rhello,world\r,kanu"; final CSVParser parser = CSVParser.parseString(code); final List<CSVRecord> records = parser.getRecords(); assertEquals(4, records.size()); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void testExcelFormat1() throws IOException { final String code = "value1,value2,value3,value4\r\na,b,c,d\r\n x,,," + "\r\n\r\n\"\"\"hello\"\"\",\" \"\"world\"\"\",\"abc\ndef\",\r\n"; final String[][] res = { {"value1", "value2", "value3", "value4"}, {"a", "b", "c", "d"}, {" x", "", "", ""}, {""}, {"\"hello\"", " \"world\"", "abc\ndef", ""} }; final CSVParser parser = new CSVParser(code, CSVFormat.EXCEL); final List<CSVRecord> records = parser.getRecords(); assertEquals(res.length, records.size()); assertTrue(records.size() > 0); for (int i = 0; i < res.length; i++) { assertArrayEquals(res[i], records.get(i).values()); } } #location 14 #vulnerability type RESOURCE_LEAK
#fixed code @Test public void testExcelFormat1() throws IOException { final String code = "value1,value2,value3,value4\r\na,b,c,d\r\n x,,," + "\r\n\r\n\"\"\"hello\"\"\",\" \"\"world\"\"\",\"abc\ndef\",\r\n"; final String[][] res = { {"value1", "value2", "value3", "value4"}, {"a", "b", "c", "d"}, {" x", "", "", ""}, {""}, {"\"hello\"", " \"world\"", "abc\ndef", ""} }; final CSVParser parser = CSVParser.parseString(code, CSVFormat.EXCEL); final List<CSVRecord> records = parser.getRecords(); assertEquals(res.length, records.size()); assertTrue(records.size() > 0); for (int i = 0; i < res.length; i++) { assertArrayEquals(res[i], records.get(i).values()); } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code private static void parseAlterColumn(final Parser parser, final PgTable table) { parser.expectOptional("COLUMN"); final String columnName = parser.parseIdentifier(); if (parser.expectOptional("SET")) { if (parser.expectOptional("STATISTICS")) { final PgColumn col = table.getColumn(columnName); col.setStatistics(parser.parseInteger()); } else if (parser.expectOptional("DEFAULT")) { final String defaultValue = parser.getExpression(); if (table.containsColumn(columnName)) { final PgColumn column = table.getColumn(columnName); column.setDefaultValue(defaultValue); } else { throw new ParserException("Cannot find column '" + columnName + " 'in table '" + table.getName() + "'"); } } else { parser.throwUnsupportedCommand(); } } else { parser.throwUnsupportedCommand(); } } #location 10 #vulnerability type NULL_DEREFERENCE
#fixed code private static void parseAlterColumn(final Parser parser, final PgTable table) { parser.expectOptional("COLUMN"); final String columnName = parser.parseIdentifier(); if (parser.expectOptional("SET")) { if (parser.expectOptional("STATISTICS")) { final PgColumn column = table.getColumn(columnName); column.setStatistics(parser.parseInteger()); } else if (parser.expectOptional("DEFAULT")) { final String defaultValue = parser.getExpression(); if (table.containsColumn(columnName)) { final PgColumn column = table.getColumn(columnName); column.setDefaultValue(defaultValue); } else { throw new ParserException("Cannot find column '" + columnName + " 'in table '" + table.getName() + "'"); } } else if (parser.expectOptional("STORAGE")) { final PgColumn column = table.getColumn(columnName); if (parser.expectOptional("PLAIN")) { column.setStorage("PLAIN"); } else if (parser.expectOptional("EXTERNAL")) { column.setStorage("EXTERNAL"); } else if (parser.expectOptional("EXTENDED")) { column.setStorage("EXTENDED"); } else if (parser.expectOptional("MAIN")) { column.setStorage("MAIN"); } else { parser.throwUnsupportedCommand(); } } else { parser.throwUnsupportedCommand(); } } else { parser.throwUnsupportedCommand(); } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public static void parse(final PgDatabase database, final String command) { final Parser parser = new Parser(command); parser.expect("ALTER", "VIEW"); final String viewName = parser.parseIdentifier(); final PgView view = database.getSchema( ParserUtils.getSchemaName(viewName, database)).getView( ParserUtils.getObjectName(viewName)); while (!parser.expectOptional(";")) { if (parser.expectOptional("ALTER")) { parser.expectOptional("COLUMN"); final String columnName = ParserUtils.getObjectName(parser.parseIdentifier()); if (parser.expectOptional("SET", "DEFAULT")) { final String expression = parser.getExpression(); view.addColumnDefaultValue(columnName, expression); } else if (parser.expectOptional("DROP", "DEFAULT")) { view.removeColumnDefaultValue(columnName); } else { parser.throwUnsupportedCommand(); } } else if (parser.expectOptional("OWNER", "TO")) { // we do not support OWNER TO so just consume the output parser.getExpression(); } else { parser.throwUnsupportedCommand(); } } } #location 7 #vulnerability type NULL_DEREFERENCE
#fixed code public static void parse(final PgDatabase database, final String command) { final Parser parser = new Parser(command); parser.expect("ALTER", "VIEW"); final String viewName = parser.parseIdentifier(); final String schemaName = ParserUtils.getSchemaName(viewName, database); final String objectName = ParserUtils.getObjectName(viewName); final PgView view = database.getSchema(schemaName).getView(objectName); while (!parser.expectOptional(";")) { if (parser.expectOptional("ALTER")) { parser.expectOptional("COLUMN"); final String columnName = ParserUtils.getObjectName(parser.parseIdentifier()); if (parser.expectOptional("SET", "DEFAULT")) { final String expression = parser.getExpression(); view.addColumnDefaultValue(columnName, expression); } else if (parser.expectOptional("DROP", "DEFAULT")) { view.removeColumnDefaultValue(columnName); } else { parser.throwUnsupportedCommand(); } } else if (parser.expectOptional("OWNER", "TO")) { // we do not support OWNER TO so just consume the output parser.getExpression(); } else { parser.throwUnsupportedCommand(); } } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public static void parse(final PgDatabase database, final String command) { String line = command; final Matcher matcher = PATTERN_TABLE_NAME.matcher(line); final String tableName; if (matcher.find()) { tableName = matcher.group(1).trim(); line = ParserUtils.removeSubString( line, matcher.start(), matcher.end()); } else { throw new ParserException( ParserException.CANNOT_PARSE_COMMAND + line); } final PgTable table = new PgTable(ParserUtils.getObjectName(tableName)); database.getSchema(ParserUtils.getSchemaName(tableName, database)).addTable( table); parseRows(table, ParserUtils.removeLastSemicolon(line)); } #location 19 #vulnerability type NULL_DEREFERENCE
#fixed code public static void parse(final PgDatabase database, final String command) { String line = command; final Matcher matcher = PATTERN_TABLE_NAME.matcher(line); final String tableName; if (matcher.find()) { tableName = matcher.group(1).trim(); line = ParserUtils.removeSubString( line, matcher.start(), matcher.end()); } else { throw new ParserException( ParserException.CANNOT_PARSE_COMMAND + line); } final PgTable table = new PgTable(ParserUtils.getObjectName(tableName)); final String schemaName = ParserUtils.getSchemaName(tableName, database); final PgSchema schema = database.getSchema(schemaName); if (schema == null) { throw new RuntimeException( "Cannot get schema '" + schemaName + "'. Need to issue 'CREATE SCHEMA " + schemaName + ";' before 'CREATE TABLE " + tableName + "...;'?"); } schema.addTable(table); parseRows(table, ParserUtils.removeLastSemicolon(line)); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public static void parse(final PgDatabase database, final String command) { final Parser parser = new Parser(command); parser.expect("ALTER", "TABLE"); parser.expectOptional("ONLY"); final String tableName = parser.parseIdentifier(); final PgTable table = database.getSchema( ParserUtils.getSchemaName(tableName, database)).getTable( ParserUtils.getObjectName(tableName)); while (!parser.expectOptional(";")) { if (parser.expectOptional("ALTER")) { parseAlterColumn(parser, table); } else if (parser.expectOptional("CLUSTER", "ON")) { table.setClusterIndexName(parser.parseIdentifier()); } else if (parser.expectOptional("OWNER", "TO")) { // we do not parse this one so we just consume the expression parser.getExpression(); } else if (parser.expectOptional("ADD")) { if (parser.expectOptional("FOREIGN", "KEY")) { parseAddForeignKey(parser, table); } else if (parser.expectOptional("CONSTRAINT")) { parseAddConstraint(parser, table); } else { parser.throwUnsupportedCommand(); } } else if (parser.expectOptional("ENABLE")) { parseEnable(parser); } else if (parser.expectOptional("DISABLE")) { parseDisable(parser); } else { parser.throwUnsupportedCommand(); } if (parser.expectOptional(";")) { break; } else { parser.expect(","); } } } #location 9 #vulnerability type NULL_DEREFERENCE
#fixed code public static void parse(final PgDatabase database, final String command) { final Parser parser = new Parser(command); parser.expect("ALTER", "TABLE"); parser.expectOptional("ONLY"); final String tableName = parser.parseIdentifier(); final String schemaName = ParserUtils.getSchemaName(tableName, database); final PgSchema schema = database.getSchema(schemaName); final String objectName = ParserUtils.getObjectName(tableName); final PgTable table = schema.getTable(objectName); if (table == null) { final PgView view = schema.getView(objectName); if (view != null) { parseView(parser, view); return; } } while (!parser.expectOptional(";")) { if (parser.expectOptional("ALTER")) { parseAlterColumn(parser, table); } else if (parser.expectOptional("CLUSTER", "ON")) { table.setClusterIndexName(parser.parseIdentifier()); } else if (parser.expectOptional("OWNER", "TO")) { // we do not parse this one so we just consume the expression parser.getExpression(); } else if (parser.expectOptional("ADD")) { if (parser.expectOptional("FOREIGN", "KEY")) { parseAddForeignKey(parser, table); } else if (parser.expectOptional("CONSTRAINT")) { parseAddConstraint(parser, table); } else { parser.throwUnsupportedCommand(); } } else if (parser.expectOptional("ENABLE")) { parseEnable(parser); } else if (parser.expectOptional("DISABLE")) { parseDisable(parser); } else { parser.throwUnsupportedCommand(); } if (parser.expectOptional(";")) { break; } else { parser.expect(","); } } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public static void parse(final PgDatabase database, final String command) { final Parser parser = new Parser(command); parser.expect("CREATE", "SEQUENCE"); final String sequenceName = parser.parseIdentifier(); final PgSequence sequence = new PgSequence(ParserUtils.getObjectName(sequenceName)); database.getSchema(ParserUtils.getSchemaName( sequenceName, database)).addSequence(sequence); while (!parser.expectOptional(";")) { if (parser.expectOptional("INCREMENT")) { parser.expectOptional("BY"); sequence.setIncrement(parser.parseString()); } else if (parser.expectOptional("MINVALUE")) { sequence.setMinValue(parser.parseString()); } else if (parser.expectOptional("MAXVALUE")) { sequence.setMaxValue(parser.parseString()); } else if (parser.expectOptional("START")) { parser.expectOptional("WITH"); sequence.setStartWith(parser.parseString()); } else if (parser.expectOptional("CACHE")) { sequence.setCache(parser.parseString()); } else if (parser.expectOptional("CYCLE")) { sequence.setCycle(true); } else if (parser.expectOptional("OWNED", "BY")) { if (parser.expectOptional("NONE")) { sequence.setOwnedBy(null); } else { sequence.setOwnedBy(parser.parseIdentifier()); } } else if (parser.expectOptional("NO")) { if (parser.expectOptional("MINVALUE")) { sequence.setMinValue(null); } else if (parser.expectOptional("MAXVALUE")) { sequence.setMaxValue(null); } else if (parser.expectOptional("CYCLE")) { sequence.setCycle(false); } else { parser.throwUnsupportedCommand(); } } else { parser.throwUnsupportedCommand(); } } } #location 9 #vulnerability type NULL_DEREFERENCE
#fixed code public static void parse(final PgDatabase database, final String command) { final Parser parser = new Parser(command); parser.expect("CREATE", "SEQUENCE"); final String sequenceName = parser.parseIdentifier(); final PgSequence sequence = new PgSequence(ParserUtils.getObjectName(sequenceName)); final String schemaName = ParserUtils.getSchemaName(sequenceName, database); database.getSchema(schemaName).addSequence(sequence); while (!parser.expectOptional(";")) { if (parser.expectOptional("INCREMENT")) { parser.expectOptional("BY"); sequence.setIncrement(parser.parseString()); } else if (parser.expectOptional("MINVALUE")) { sequence.setMinValue(parser.parseString()); } else if (parser.expectOptional("MAXVALUE")) { sequence.setMaxValue(parser.parseString()); } else if (parser.expectOptional("START")) { parser.expectOptional("WITH"); sequence.setStartWith(parser.parseString()); } else if (parser.expectOptional("CACHE")) { sequence.setCache(parser.parseString()); } else if (parser.expectOptional("CYCLE")) { sequence.setCycle(true); } else if (parser.expectOptional("OWNED", "BY")) { if (parser.expectOptional("NONE")) { sequence.setOwnedBy(null); } else { sequence.setOwnedBy(parser.parseIdentifier()); } } else if (parser.expectOptional("NO")) { if (parser.expectOptional("MINVALUE")) { sequence.setMinValue(null); } else if (parser.expectOptional("MAXVALUE")) { sequence.setMaxValue(null); } else if (parser.expectOptional("CYCLE")) { sequence.setCycle(false); } else { parser.throwUnsupportedCommand(); } } else { parser.throwUnsupportedCommand(); } } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public static void parse(final PgDatabase database, final String command) { final Parser parser = new Parser(command); parser.expect("CREATE"); parser.expectOptional("OR", "REPLACE"); parser.expect("FUNCTION"); final String functionName = parser.parseIdentifier(); final PgFunction function = new PgFunction(); function.setName(ParserUtils.getObjectName(functionName)); database.getSchema(ParserUtils.getSchemaName( functionName, database)).addFunction(function); parser.expect("("); while (!parser.expectOptional(")")) { final String mode; if (parser.expectOptional("IN")) { mode = "IN"; } else if (parser.expectOptional("OUT")) { mode = "OUT"; } else if (parser.expectOptional("INOUT")) { mode = "INOUT"; } else if (parser.expectOptional("VARIADIC")) { mode = "VARIADIC"; } else { mode = null; } final int position = parser.getPosition(); String argumentName = null; String dataType = parser.parseDataType(); final int position2 = parser.getPosition(); if (!parser.expectOptional(")") && !parser.expectOptional(",") && !parser.expectOptional("=") && !parser.expectOptional("DEFAULT")) { parser.setPosition(position); argumentName = parser.parseIdentifier(); dataType = parser.parseDataType(); } else { parser.setPosition(position2); } final String defaultExpression; if (parser.expectOptional("=") || parser.expectOptional("DEFAULT")) { defaultExpression = parser.getExpression(); } else { defaultExpression = null; } final PgFunction.Argument argument = new PgFunction.Argument(); argument.setDataType(dataType); argument.setDefaultExpression(defaultExpression); argument.setMode(mode); argument.setName(argumentName); function.addArgument(argument); if (parser.expectOptional(")")) { break; } else { parser.expect(","); } } function.setBody(parser.getRest()); } #location 11 #vulnerability type NULL_DEREFERENCE
#fixed code public static void parse(final PgDatabase database, final String command) { final Parser parser = new Parser(command); parser.expect("CREATE"); parser.expectOptional("OR", "REPLACE"); parser.expect("FUNCTION"); final String functionName = parser.parseIdentifier(); final String schemaName = ParserUtils.getSchemaName(functionName, database); final PgFunction function = new PgFunction(); function.setName(ParserUtils.getObjectName(functionName)); database.getSchema(schemaName).addFunction(function); parser.expect("("); while (!parser.expectOptional(")")) { final String mode; if (parser.expectOptional("IN")) { mode = "IN"; } else if (parser.expectOptional("OUT")) { mode = "OUT"; } else if (parser.expectOptional("INOUT")) { mode = "INOUT"; } else if (parser.expectOptional("VARIADIC")) { mode = "VARIADIC"; } else { mode = null; } final int position = parser.getPosition(); String argumentName = null; String dataType = parser.parseDataType(); final int position2 = parser.getPosition(); if (!parser.expectOptional(")") && !parser.expectOptional(",") && !parser.expectOptional("=") && !parser.expectOptional("DEFAULT")) { parser.setPosition(position); argumentName = parser.parseIdentifier(); dataType = parser.parseDataType(); } else { parser.setPosition(position2); } final String defaultExpression; if (parser.expectOptional("=") || parser.expectOptional("DEFAULT")) { defaultExpression = parser.getExpression(); } else { defaultExpression = null; } final PgFunction.Argument argument = new PgFunction.Argument(); argument.setDataType(dataType); argument.setDefaultExpression(defaultExpression); argument.setMode(mode); argument.setName(argumentName); function.addArgument(argument); if (parser.expectOptional(")")) { break; } else { parser.expect(","); } } function.setBody(parser.getRest()); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public static void parse(final PgDatabase database, final String command) { final Matcher matcher = PATTERN.matcher(command.trim()); if (matcher.matches()) { final String triggerName = matcher.group(1); final String when = matcher.group(2); final String[] events = new String[3]; events[0] = matcher.group(3); events[1] = matcher.group(4); events[2] = matcher.group(5); final String tableName = matcher.group(6); final String fireOn = matcher.group(7); final String procedure = matcher.group(8); final PgTrigger trigger = new PgTrigger(); trigger.setBefore("BEFORE".equalsIgnoreCase(when)); trigger.setForEachRow( (fireOn != null) && "ROW".equalsIgnoreCase(fireOn)); trigger.setFunction(procedure.trim()); trigger.setName(triggerName.trim()); trigger.setOnDelete(isEventPresent(events, "DELETE")); trigger.setOnInsert(isEventPresent(events, "INSERT")); trigger.setOnUpdate(isEventPresent(events, "UPDATE")); trigger.setTableName(tableName.trim()); database.getDefaultSchema().getTable( trigger.getTableName()).addTrigger(trigger); } else { throw new ParserException( ParserException.CANNOT_PARSE_COMMAND + command); } } #location 20 #vulnerability type NULL_DEREFERENCE
#fixed code public static void parse(final PgDatabase database, final String command) { final Parser parser = new Parser(command); parser.expect("CREATE", "TRIGGER"); final PgTrigger trigger = new PgTrigger(); trigger.setName(parser.parseIdentifier()); if (parser.expectOptional("BEFORE")) { trigger.setBefore(true); } else if (parser.expectOptional("AFTER")) { trigger.setBefore(false); } boolean first = true; while (true) { if (!first && !parser.expectOptional("OR")) { break; } if (parser.expectOptional("INSERT")) { trigger.setOnInsert(true); } else if (parser.expectOptional("UPDATE")) { trigger.setOnUpdate(true); } else if (parser.expectOptional("DELETE")) { trigger.setOnDelete(true); } else if (parser.expectOptional("TRUNCATE")) { trigger.setOnTruncate(true); } else if (first) { break; } else { parser.throwUnsupportedCommand(); } first = false; } parser.expect("ON"); trigger.setTableName(parser.parseIdentifier()); if (parser.expectOptional("FOR")) { parser.expectOptional("EACH"); if (parser.expectOptional("ROW")) { trigger.setForEachRow(true); } else if (parser.expectOptional("STATEMENT")) { trigger.setForEachRow(false); } else { parser.throwUnsupportedCommand(); } } if (parser.expectOptional("WHEN")) { parser.expect("("); trigger.setWhen(parser.getExpression()); parser.expect(")"); } parser.expect("EXECUTE", "PROCEDURE"); trigger.setFunction(parser.getRest()); database.getDefaultSchema().getTable( trigger.getTableName()).addTrigger(trigger); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code private String loadText(String path) throws IOException { StringBuilder sbText = new StringBuilder(); BufferedReader br = new BufferedReader(new InputStreamReader(Thread.currentThread().getContextClassLoader().getResourceAsStream(path))); String line; while ((line = br.readLine()) != null) { sbText.append(line).append("\n"); } br.close(); return sbText.toString(); } #location 12 #vulnerability type RESOURCE_LEAK
#fixed code private String loadText(String path) throws IOException { StringBuilder sbText = new StringBuilder(); BufferedReader br = new BufferedReader(new InputStreamReader(Thread.currentThread().getContextClassLoader().getResourceAsStream(path), "UTF-8")); String line; while ((line = br.readLine()) != null) { sbText.append(line).append("\n"); } br.close(); return sbText.toString(); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code private Set<String> loadDictionary(String path) throws IOException { Set<String> dictionary = new TreeSet<String>(); BufferedReader br = new BufferedReader(new InputStreamReader(Thread.currentThread().getContextClassLoader().getResourceAsStream(path))); String line; while ((line = br.readLine()) != null) { dictionary.add(line); } br.close(); return dictionary; } #location 12 #vulnerability type RESOURCE_LEAK
#fixed code private Set<String> loadDictionary(String path) throws IOException { Set<String> dictionary = new TreeSet<String>(); BufferedReader br = new BufferedReader(new InputStreamReader(Thread.currentThread().getContextClassLoader().getResourceAsStream(path), "UTF-8")); String line; while ((line = br.readLine()) != null) { dictionary.add(line); } br.close(); return dictionary; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code protected Function<Publisher<?>, Publisher<?>> lookup(String name) { Function<Publisher<?>, Publisher<?>> function = this.function; if (name != null && this.catalog != null) { Function<Publisher<?>, Publisher<?>> preferred = this.catalog .lookup(Function.class, name); if (preferred != null) { function = preferred; } } if (function != null) { return function; } throw new IllegalStateException("No function defined"); } #location 2 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code protected Function<Publisher<?>, Publisher<?>> lookup(String name) { Function<Publisher<?>, Publisher<?>> function = this.function; if (name != null && this.catalog != null) { @SuppressWarnings("unchecked") Function<Publisher<?>, Publisher<?>> preferred = this.catalog .lookup(Function.class, name); if (preferred != null) { function = preferred; } } if (function != null) { return function; } throw new IllegalStateException("No function defined with name=" + name); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Override public boolean isRetainOuputAsMessage(Message<?> message) { if (message.getHeaders().containsKey("message-type") && message.getHeaders().get("message-type").equals("cloudevent")) { return true; } return false; } #location 3 #vulnerability type NULL_DEREFERENCE
#fixed code @Override public boolean isRetainOuputAsMessage(Message<?> message) { if (message.getHeaders().containsKey(MessageUtils.MESSAGE_TYPE) && message.getHeaders().get(MessageUtils.MESSAGE_TYPE).equals(CloudEventMessageUtils.CLOUDEVENT_VALUE)) { return true; } return false; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void deployAndExtractFunctions() throws Exception { // This one can only work if you change the boot classpath to contain reactor-core // and reactive-streams expected.expect(ClassCastException.class); @SuppressWarnings("unchecked") Flux<String> result = (Flux<String>) deployer.lookupFunction("uppercase") .apply(Flux.just("foo")); assertThat(result.blockFirst()).isEqualTo("FOO"); } #location 8 #vulnerability type NULL_DEREFERENCE
#fixed code @Test public void deployAndExtractFunctions() throws Exception { // This one can only work if you change the boot classpath to contain reactor-core // and reactive-streams expected.expect(ClassCastException.class); @SuppressWarnings("unchecked") Flux<String> result = (Flux<String>) deployer.lookupFunction("pojos/uppercase") .apply(Flux.just("foo")); assertThat(result.blockFirst()).isEqualTo("FOO"); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @SuppressWarnings("unchecked") public static Message<?> toBinary(Message<?> inputMessage, MessageConverter messageConverter) { Map<String, Object> headers = inputMessage.getHeaders(); CloudEventAttributes attributes = new CloudEventAttributes(headers); // first check the obvious and see if content-type is `cloudevents` if (!attributes.isValidCloudEvent() && headers.containsKey(MessageHeaders.CONTENT_TYPE)) { MimeType contentType = contentTypeResolver.resolve(inputMessage.getHeaders()); if (contentType.getType().equals(CloudEventMessageUtils.APPLICATION_CLOUDEVENTS.getType()) && contentType.getSubtype().startsWith(CloudEventMessageUtils.APPLICATION_CLOUDEVENTS.getSubtype())) { String dataContentType = StringUtils.hasText(attributes.getDataContentType()) ? attributes.getDataContentType() : MimeTypeUtils.APPLICATION_JSON_VALUE; String suffix = contentType.getSubtypeSuffix(); Assert.hasText(suffix, "Content-type 'suffix' can not be determined from " + contentType); MimeType cloudEventDeserializationContentType = MimeTypeUtils .parseMimeType(contentType.getType() + "/" + suffix); Message<?> cloudEventMessage = MessageBuilder.fromMessage(inputMessage) .setHeader(MessageHeaders.CONTENT_TYPE, cloudEventDeserializationContentType) .setHeader(CloudEventMessageUtils.CANONICAL_DATACONTENTTYPE, dataContentType) .build(); Map<String, Object> structuredCloudEvent = (Map<String, Object>) messageConverter.fromMessage(cloudEventMessage, Map.class); Message<?> binaryCeMessage = buildCeMessageFromStructured(structuredCloudEvent, inputMessage.getHeaders()); return binaryCeMessage; } } else if (StringUtils.hasText(attributes.getDataContentType())) { return MessageBuilder.fromMessage(inputMessage) .setHeader(MessageHeaders.CONTENT_TYPE, attributes.getDataContentType()) .build(); } return inputMessage; } #location 10 #vulnerability type NULL_DEREFERENCE
#fixed code @SuppressWarnings("unchecked") public static Message<?> toBinary(Message<?> inputMessage, MessageConverter messageConverter) { Map<String, Object> headers = inputMessage.getHeaders(); CloudEventAttributes attributes = new CloudEventAttributes(headers); // first check the obvious and see if content-type is `cloudevents` if (!attributes.isValidCloudEvent() && headers.containsKey(MessageHeaders.CONTENT_TYPE)) { MimeType contentType = resolveContentType(inputMessage.getHeaders()); if (contentType != null && contentType.getType().equals(CloudEventMessageUtils.APPLICATION_CLOUDEVENTS.getType()) && contentType.getSubtype().startsWith(CloudEventMessageUtils.APPLICATION_CLOUDEVENTS.getSubtype())) { String dataContentType = StringUtils.hasText(attributes.getDataContentType()) ? attributes.getDataContentType() : MimeTypeUtils.APPLICATION_JSON_VALUE; String suffix = contentType.getSubtypeSuffix(); Assert.hasText(suffix, "Content-type 'suffix' can not be determined from " + contentType); MimeType cloudEventDeserializationContentType = MimeTypeUtils .parseMimeType(contentType.getType() + "/" + suffix); Message<?> cloudEventMessage = MessageBuilder.fromMessage(inputMessage) .setHeader(MessageHeaders.CONTENT_TYPE, cloudEventDeserializationContentType) .setHeader(CloudEventMessageUtils.CANONICAL_DATACONTENTTYPE, dataContentType) .build(); Map<String, Object> structuredCloudEvent = (Map<String, Object>) messageConverter.fromMessage(cloudEventMessage, Map.class); Message<?> binaryCeMessage = buildCeMessageFromStructured(structuredCloudEvent, inputMessage.getHeaders()); return binaryCeMessage; } } else if (StringUtils.hasText(attributes.getDataContentType())) { return MessageBuilder.fromMessage(inputMessage) .setHeader(MessageHeaders.CONTENT_TYPE, attributes.getDataContentType()) .build(); } return inputMessage; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Override public boolean isRetainOuputAsMessage(Message<?> message) { return message.getHeaders().containsKey(MessageUtils.MESSAGE_TYPE) && message.getHeaders().get(MessageUtils.MESSAGE_TYPE).equals(CloudEventMessageUtils.CLOUDEVENT_VALUE); } #location 4 #vulnerability type NULL_DEREFERENCE
#fixed code @Override public boolean isRetainOuputAsMessage(Message<?> message) { return message.getHeaders().containsKey(MessageUtils.TARGET_PROTOCOL) || (message.getHeaders().containsKey(MessageUtils.MESSAGE_TYPE) && message.getHeaders().get(MessageUtils.MESSAGE_TYPE).equals(CloudEventMessageUtils.CLOUDEVENT_VALUE)); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @SuppressWarnings("unchecked") protected void initialize(ExecutionContext ctxt) { ConfigurableApplicationContext context = AzureSpringFunctionInitializer.context; if (!this.initialized.compareAndSet(false, true)) { return; } if (ctxt != null) { ctxt.getLogger().info("Initializing functions"); } if (context == null) { synchronized (AzureSpringFunctionInitializer.class) { if (context == null) { SpringApplicationBuilder builder = new SpringApplicationBuilder( configurationClass); ClassUtils.overrideThreadContextClassLoader( AzureSpringFunctionInitializer.class.getClassLoader()); context = builder.web(WebApplicationType.NONE).run(); AzureSpringFunctionInitializer.context = context; } } } context.getAutowireCapableBeanFactory().autowireBean(this); String name = context.getEnvironment().getProperty("function.name"); if (name == null) { name = "function"; } if (this.catalog == null) { this.function = context.getBean(name, Function.class); } else { Set<String> functionNames = this.catalog.getNames(Function.class); if (functionNames.size() == 1) { this.function = this.catalog.lookup(Function.class, functionNames.iterator().next()); } else { this.function = this.catalog.lookup(Function.class, name); } } } #location 44 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code @SuppressWarnings("unchecked") protected void initialize(ExecutionContext ctxt) { ConfigurableApplicationContext context = AzureSpringFunctionInitializer.context; if (!this.initialized.compareAndSet(false, true)) { return; } if (ctxt != null) { ctxt.getLogger().info("Initializing functions"); } if (context == null) { synchronized (AzureSpringFunctionInitializer.class) { if (context == null) { SpringApplicationBuilder builder = new SpringApplicationBuilder( configurationClass); ClassUtils.overrideThreadContextClassLoader( AzureSpringFunctionInitializer.class.getClassLoader()); context = builder.web(WebApplicationType.NONE).run(); AzureSpringFunctionInitializer.context = context; } } } context.getAutowireCapableBeanFactory().autowireBean(this); if (ctxt != null) { ctxt.getLogger().info("Initialized context: catalog=" + this.catalog); } String name = context.getEnvironment().getProperty("function.name"); if (name == null) { name = "function"; } if (this.catalog == null) { if (context.containsBean(name)) { if (ctxt != null) { ctxt.getLogger() .info("No catalog. Looking for Function bean name=" + name); } this.function = context.getBean(name, Function.class); } } else { Set<String> functionNames = this.catalog.getNames(Function.class); if (functionNames.size() == 1) { this.function = this.catalog.lookup(Function.class, functionNames.iterator().next()); } else { this.function = this.catalog.lookup(Function.class, name); } } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code private X509Certificate retrieveAndVerifyCertificateChain( final String signingCertificateChainUrl) throws CertificateException { try (InputStream in = getAndVerifySigningCertificateChainUrl(signingCertificateChainUrl).openConnection(proxy).getInputStream()) { CertificateFactory certificateFactory = CertificateFactory.getInstance(ServletConstants.SIGNATURE_CERTIFICATE_TYPE); @SuppressWarnings("unchecked") Collection<X509Certificate> certificateChain = (Collection<X509Certificate>) certificateFactory.generateCertificates(in); /* * check the before/after dates on the certificate date to confirm that it is valid on * the current date */ X509Certificate signingCertificate = certificateChain.iterator().next(); signingCertificate.checkValidity(); // check the certificate chain TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm()); trustManagerFactory.init((KeyStore) null); X509TrustManager x509TrustManager = null; for (TrustManager trustManager : trustManagerFactory.getTrustManagers()) { if (trustManager instanceof X509TrustManager) { x509TrustManager = (X509TrustManager) trustManager; } } if (x509TrustManager == null) { throw new IllegalStateException( "No X509 TrustManager available. Unable to check certificate chain"); } else { x509TrustManager.checkServerTrusted( certificateChain.toArray(new X509Certificate[certificateChain.size()]), ServletConstants.SIGNATURE_TYPE); } /* * verify Echo API's hostname is specified as one of subject alternative names on the * signing certificate */ if (!subjectAlernativeNameListContainsEchoSdkDomainName(signingCertificate .getSubjectAlternativeNames())) { throw new CertificateException( "The provided certificate is not valid for the Echo SDK"); } return signingCertificate; } catch (KeyStoreException | IOException | NoSuchAlgorithmException ex) { throw new CertificateException("Unable to verify certificate at URL: " + signingCertificateChainUrl, ex); } } #location 4 #vulnerability type RESOURCE_LEAK
#fixed code private X509Certificate retrieveAndVerifyCertificateChain( final String signingCertificateChainUrl) throws CertificateException { try (InputStream in = proxy != null ? getAndVerifySigningCertificateChainUrl(signingCertificateChainUrl).openConnection(proxy).getInputStream() : getAndVerifySigningCertificateChainUrl(signingCertificateChainUrl).openConnection().getInputStream()) { CertificateFactory certificateFactory = CertificateFactory.getInstance(ServletConstants.SIGNATURE_CERTIFICATE_TYPE); @SuppressWarnings("unchecked") Collection<X509Certificate> certificateChain = (Collection<X509Certificate>) certificateFactory.generateCertificates(in); /* * check the before/after dates on the certificate date to confirm that it is valid on * the current date */ X509Certificate signingCertificate = certificateChain.iterator().next(); signingCertificate.checkValidity(); // check the certificate chain TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm()); trustManagerFactory.init((KeyStore) null); X509TrustManager x509TrustManager = null; for (TrustManager trustManager : trustManagerFactory.getTrustManagers()) { if (trustManager instanceof X509TrustManager) { x509TrustManager = (X509TrustManager) trustManager; } } if (x509TrustManager == null) { throw new IllegalStateException( "No X509 TrustManager available. Unable to check certificate chain"); } else { x509TrustManager.checkServerTrusted( certificateChain.toArray(new X509Certificate[certificateChain.size()]), ServletConstants.SIGNATURE_TYPE); } /* * verify Echo API's hostname is specified as one of subject alternative names on the * signing certificate */ if (!subjectAlernativeNameListContainsEchoSdkDomainName(signingCertificate .getSubjectAlternativeNames())) { throw new CertificateException( "The provided certificate is not valid for the Echo SDK"); } return signingCertificate; } catch (KeyStoreException | IOException | NoSuchAlgorithmException ex) { throw new CertificateException("Unable to verify certificate at URL: " + signingCertificateChainUrl, ex); } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code private X509Certificate retrieveAndVerifyCertificateChain( final String signingCertificateChainUrl) throws CertificateException { try (InputStream in = proxy != null ? getAndVerifySigningCertificateChainUrl(signingCertificateChainUrl).openConnection(proxy).getInputStream() : getAndVerifySigningCertificateChainUrl(signingCertificateChainUrl).openConnection().getInputStream()) { CertificateFactory certificateFactory = CertificateFactory.getInstance(ServletConstants.SIGNATURE_CERTIFICATE_TYPE); @SuppressWarnings("unchecked") Collection<X509Certificate> certificateChain = (Collection<X509Certificate>) certificateFactory.generateCertificates(in); /* * check the before/after dates on the certificate date to confirm that it is valid on * the current date */ X509Certificate signingCertificate = certificateChain.iterator().next(); signingCertificate.checkValidity(); // check the certificate chain TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm()); trustManagerFactory.init((KeyStore) null); X509TrustManager x509TrustManager = null; for (TrustManager trustManager : trustManagerFactory.getTrustManagers()) { if (trustManager instanceof X509TrustManager) { x509TrustManager = (X509TrustManager) trustManager; } } if (x509TrustManager == null) { throw new IllegalStateException( "No X509 TrustManager available. Unable to check certificate chain"); } else { x509TrustManager.checkServerTrusted( certificateChain.toArray(new X509Certificate[certificateChain.size()]), ServletConstants.SIGNATURE_TYPE); } /* * verify Echo API's hostname is specified as one of subject alternative names on the * signing certificate */ if (!subjectAlernativeNameListContainsEchoSdkDomainName(signingCertificate .getSubjectAlternativeNames())) { throw new CertificateException( "The provided certificate is not valid for the Echo SDK"); } return signingCertificate; } catch (KeyStoreException | IOException | NoSuchAlgorithmException ex) { throw new CertificateException("Unable to verify certificate at URL: " + signingCertificateChainUrl, ex); } } #location 5 #vulnerability type RESOURCE_LEAK
#fixed code private X509Certificate retrieveAndVerifyCertificateChain( final String signingCertificateChainUrl) throws CertificateException { for (int attempt = 0; attempt <= CERT_RETRIEVAL_RETRY_COUNT; attempt++) { InputStream in = null; try { HttpURLConnection connection = proxy != null ? (HttpURLConnection)getAndVerifySigningCertificateChainUrl(signingCertificateChainUrl).openConnection(proxy) : (HttpURLConnection)getAndVerifySigningCertificateChainUrl(signingCertificateChainUrl).openConnection(); if (connection.getResponseCode() != 200) { if (waitForRetry(attempt)) { continue; } else { throw new CertificateException("Got a non-200 status code when retrieving certificate at URL: " + signingCertificateChainUrl); } } in = connection.getInputStream(); CertificateFactory certificateFactory = CertificateFactory.getInstance(ServletConstants.SIGNATURE_CERTIFICATE_TYPE); @SuppressWarnings("unchecked") Collection<X509Certificate> certificateChain = (Collection<X509Certificate>) certificateFactory.generateCertificates(in); /* * check the before/after dates on the certificate date to confirm that it is valid on * the current date */ X509Certificate signingCertificate = certificateChain.iterator().next(); signingCertificate.checkValidity(); // check the certificate chain TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm()); trustManagerFactory.init((KeyStore) null); X509TrustManager x509TrustManager = null; for (TrustManager trustManager : trustManagerFactory.getTrustManagers()) { if (trustManager instanceof X509TrustManager) { x509TrustManager = (X509TrustManager) trustManager; } } if (x509TrustManager == null) { throw new IllegalStateException( "No X509 TrustManager available. Unable to check certificate chain"); } else { x509TrustManager.checkServerTrusted( certificateChain.toArray(new X509Certificate[certificateChain.size()]), ServletConstants.SIGNATURE_TYPE); } /* * verify Echo API's hostname is specified as one of subject alternative names on the * signing certificate */ if (!subjectAlernativeNameListContainsEchoSdkDomainName(signingCertificate .getSubjectAlternativeNames())) { throw new CertificateException( "The provided certificate is not valid for the ASK SDK"); } return signingCertificate; } catch (IOException e) { if (!waitForRetry(attempt)) { throw new CertificateException("Unable to retrieve certificate from URL: " + signingCertificateChainUrl, e); } } catch (Exception e) { throw new CertificateException("Unable to verify certificate at URL: " + signingCertificateChainUrl, e); } finally { if (in != null) { IOUtils.closeQuietly(in); } } } throw new RuntimeException("Unable to retrieve signing certificate due to an unhandled exception"); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public void load() { configuration = Configuration.load("core.yml"); registerCoreModules(); // check for upgrade before everything else new ConfigPost300().run(); plugin.loadDatabase(); Performance.init(); physicalDatabase = new PhysDB(); memoryDatabase = new MemDB(); updateThread = new UpdateThread(this); // Permissions init permissions = new NoPermissions(); if (resolvePlugin("PermissionsBukkit") != null) { permissions = new BukkitPermissions(); } else if (resolvePlugin("PermissionsEx") != null) { permissions = new PEXPermissions(); } else { // Default to Permissions over SuperPermissions, except with SuperpermsBridge Plugin legacy = resolvePlugin("Permissions"); try { // super perms bridge if (((com.nijikokun.bukkit.Permissions.Permissions)legacy).getHandler() instanceof com.platymuus.bukkit.permcompat.PermissionHandler) { permissions = new SuperPermsPermissions(); } else { permissions = new NijiPermissions(); } } catch (NoClassDefFoundError e) { } // attempt super perms if we still have nothing if (permissions.getClass() == NoPermissions.class) { try { Method method = CraftHumanEntity.class.getDeclaredMethod("hasPermission", String.class); if (method != null) { permissions = new SuperPermsPermissions(); } } catch(NoSuchMethodException e) { // server does not support SuperPerms } } } // Currency init currency = new NoCurrency(); if (resolvePlugin("iConomy") != null) { // We need to figure out which iConomy plugin we have... Plugin plugin = resolvePlugin("iConomy"); // get the class name String className = plugin.getClass().getName(); // check for the iConomy5 package try { if (className.startsWith("com.iConomy")) { currency = new iConomy5Currency(); } else { // iConomy 6! currency = new iConomy6Currency(); } } catch (NoClassDefFoundError e) { } } else if (resolvePlugin("BOSEconomy") != null) { currency = new BOSECurrency(); } else if (resolvePlugin("Essentials") != null) { currency = new EssentialsCurrency(); } log("Permissions API: " + Colors.Red + permissions.getClass().getSimpleName()); log("Currency API: " + Colors.Red + currency.getClass().getSimpleName()); log("Loading " + Database.DefaultType); try { physicalDatabase.connect(); memoryDatabase.connect(); physicalDatabase.load(); memoryDatabase.load(); log("Using: " + StringUtils.capitalizeFirstLetter(physicalDatabase.getConnection().getMetaData().getDriverVersion())); } catch (Exception e) { e.printStackTrace(); } // check any major conversions new MySQLPost200().run(); // precache lots of protections physicalDatabase.precache(); // tell all modules we're loaded moduleLoader.loadAll(); } #location 28 #vulnerability type NULL_DEREFERENCE
#fixed code public void load() { configuration = Configuration.load("core.yml"); registerCoreModules(); // check for upgrade before everything else new ConfigPost300().run(); plugin.loadDatabase(); Performance.init(); physicalDatabase = new PhysDB(); memoryDatabase = new MemDB(); updateThread = new UpdateThread(this); // Permissions init permissions = new NoPermissions(); if (resolvePlugin("PermissionsBukkit") != null) { permissions = new BukkitPermissions(); } else if (resolvePlugin("PermissionsEx") != null) { permissions = new PEXPermissions(); } else { // Default to Permissions over SuperPermissions, except with SuperpermsBridge Plugin legacy = resolvePlugin("Permissions"); try { // super perms bridge, will throw exception if it's not it if (legacy != null) { if (((com.nijikokun.bukkit.Permissions.Permissions)legacy).getHandler() instanceof com.platymuus.bukkit.permcompat.PermissionHandler) { permissions = new SuperPermsPermissions(); } } } catch (NoClassDefFoundError e) { // Permissions 2/3 or some other bridge if (legacy != null) { permissions = new NijiPermissions(); } } // attempt super perms if we still have nothing if (permissions.getClass() == NoPermissions.class) { try { Method method = CraftHumanEntity.class.getDeclaredMethod("hasPermission", String.class); if (method != null) { permissions = new SuperPermsPermissions(); } } catch(NoSuchMethodException e) { // server does not support SuperPerms } } } // Currency init currency = new NoCurrency(); if (resolvePlugin("iConomy") != null) { // We need to figure out which iConomy plugin we have... Plugin plugin = resolvePlugin("iConomy"); // get the class name String className = plugin.getClass().getName(); // check for the iConomy5 package try { if (className.startsWith("com.iConomy")) { currency = new iConomy5Currency(); } else { // iConomy 6! currency = new iConomy6Currency(); } } catch (NoClassDefFoundError e) { } } else if (resolvePlugin("BOSEconomy") != null) { currency = new BOSECurrency(); } else if (resolvePlugin("Essentials") != null) { currency = new EssentialsCurrency(); } log("Permissions API: " + Colors.Red + permissions.getClass().getSimpleName()); log("Currency API: " + Colors.Red + currency.getClass().getSimpleName()); log("Loading " + Database.DefaultType); try { physicalDatabase.connect(); memoryDatabase.connect(); physicalDatabase.load(); memoryDatabase.load(); log("Using: " + StringUtils.capitalizeFirstLetter(physicalDatabase.getConnection().getMetaData().getDriverVersion())); } catch (Exception e) { e.printStackTrace(); } // check any major conversions new MySQLPost200().run(); // precache lots of protections physicalDatabase.precache(); // tell all modules we're loaded moduleLoader.loadAll(); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public boolean tryLoadProtection(Block block) { Protection protection = lwc.getPhysicalDatabase().loadProtection(block.getWorld().getName(), block.getX(), block.getY(), block.getZ()); if (protection != null) { // ensure it's the right block if (protection.getBlockId() > 0) { if (protection.getBlockId() == protection.getBlock().getTypeId()) { this.matchedProtection = protection; } else { // Corrupted protection System.out.println("Removing corrupted protection: " + protection); protection.remove(); } } } return this.matchedProtection != null; } #location 7 #vulnerability type NULL_DEREFERENCE
#fixed code public boolean tryLoadProtection(Block block) { Protection protection = lwc.getPhysicalDatabase().loadProtection(block.getWorld().getName(), block.getX(), block.getY(), block.getZ()); if (protection != null) { // ensure it's the right block if (protection.getBlockId() > 0) { if (protection.isBlockInWorld()) { this.matchedProtection = protection; } else { // Corrupted protection System.out.println("Removing corrupted protection: " + protection); protection.remove(); } } } return this.matchedProtection != null; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code private int getPlayerDropTransferTarget(LWCPlayer player) { Mode mode = player.getMode("dropTransfer"); String target = mode.getData(); try { return Integer.parseInt(target); } catch (NumberFormatException e) { } return -1; } #location 3 #vulnerability type NULL_DEREFERENCE
#fixed code private int getPlayerDropTransferTarget(LWCPlayer player) { Mode mode = player.getMode("dropTransfer"); if (mode == null) { return -1; } String target = mode.getData(); try { return Integer.parseInt(target); } catch (NumberFormatException e) { } return -1; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public void run() { LWC lwc = LWC.getInstance(); PhysDB physicalDatabase = lwc.getPhysicalDatabase(); // this patcher only does something exciting if you have mysql enabled // :-) if (physicalDatabase.getType() != Type.MySQL) { return; } // this patcher only does something exciting if the old SQLite database // still exists :-) String database = lwc.getConfiguration().getString("database.path"); if (database == null || database.trim().equals("")) { database = "plugins/LWC/lwc.db"; } File file = new File(database); if (!file.exists()) { return; } logger.info("######################################################"); logger.info("######################################################"); logger.info("SQLite to MySQL conversion required"); logger.info("Loading SQLite"); // rev up those sqlite databases because I sure am hungry for some // data... PhysDB sqliteDatabase = new PhysDB(Type.SQLite); try { sqliteDatabase.connect(); sqliteDatabase.load(); logger.info("SQLite is good to go"); physicalDatabase.getConnection().setAutoCommit(false); logger.info("Preliminary scan..............."); int startProtections = physicalDatabase.getProtectionCount(); int protectionCount = sqliteDatabase.getProtectionCount(); int historyCount = sqliteDatabase.getHistoryCount(); int expectedProtections = protectionCount + startProtections; logger.info("TO CONVERT:"); logger.info("Protections:\t" + protectionCount); logger.info("History:\t" + historyCount); logger.info(""); if (protectionCount > 0) { logger.info("Converting: PROTECTIONS"); List<Protection> tmp = sqliteDatabase.loadProtections(); for (Protection protection : tmp) { // sync it to the live database protection.saveNow(); } logger.info("COMMITTING"); physicalDatabase.getConnection().commit(); logger.info("OK , expecting: " + expectedProtections); if (expectedProtections == (protectionCount = physicalDatabase.getProtectionCount())) { logger.info("OK."); } else { logger.info("Weird, only " + protectionCount + " protections are in the database? Continuing..."); } } if (historyCount > 0) { logger.info("Converting: HISTORY"); List<History> tmp = sqliteDatabase.loadHistory(); for (History history : tmp) { // make sure it's assumed it does not exist in the database history.setExists(false); // sync the history object with the active database (ala MySQL) history.sync(); } logger.info("OK"); } logger.info("Closing SQLite"); sqliteDatabase.getConnection().close(); logger.info("Renaming \"" + database + "\" to \"" + database + ".old\""); if (!file.renameTo(new File(database + ".old"))) { logger.info("NOTICE: FAILED TO RENAME lwc.db!! Please rename this manually!"); } logger.info("SQLite to MySQL conversion is now complete!\n"); logger.info("Thank you!"); } catch (Exception e) { logger.info("#### SEVERE ERROR: Something bad happened when converting the database (Oops!)"); e.printStackTrace(); } try { physicalDatabase.getConnection().setAutoCommit(true); } catch (SQLException e) { e.printStackTrace(); } logger.info("######################################################"); logger.info("######################################################"); } #location 91 #vulnerability type NULL_DEREFERENCE
#fixed code public void run() { LWC lwc = LWC.getInstance(); PhysDB physicalDatabase = lwc.getPhysicalDatabase(); // this patcher only does something exciting if you have mysql enabled // :-) if (physicalDatabase.getType() != Type.MySQL) { return; } // this patcher only does something exciting if the old SQLite database // still exists :-) String database = lwc.getConfiguration().getString("database.path"); if (database == null || database.trim().equals("")) { database = "plugins/LWC/lwc.db"; } File file = new File(database); if (!file.exists()) { return; } logger.info("######################################################"); logger.info("######################################################"); logger.info("SQLite to MySQL conversion required"); // rev up those sqlite databases because I sure am hungry for some data... DatabaseMigrator migrator = new DatabaseMigrator(); if (migrator.convertFrom(Type.SQLite)) { logger.info("Successfully converted."); logger.info("Renaming \"" + database + "\" to \"" + database + ".old\""); if (!file.renameTo(new File(database + ".old"))) { logger.info("NOTICE: FAILED TO RENAME lwc.db!! Please rename this manually!"); } logger.info("SQLite to MySQL conversion is now complete!\n"); logger.info("Thank you!"); } else { logger.info("#### SEVERE ERROR: Something bad happened when converting the database (Oops!)"); } logger.info("######################################################"); logger.info("######################################################"); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code private void postPlugin(Plugin plugin, boolean isPing) throws IOException { // Construct the post data String response = "ERR No response"; String data = encode("guid") + "=" + encode(guid) + "&" + encode("version") + "=" + encode(plugin.getDescription().getVersion()) + "&" + encode("server") + "=" + encode(Bukkit.getVersion()) + "&" + encode("players") + "=" + encode(Bukkit.getServer().getOnlinePlayers().length + "") + "&" + encode("revision") + "=" + encode(REVISION + ""); // If we're pinging, append it if (isPing) { data += "&" + encode("ping") + "=" + encode("true"); } // Create the url URL url = new URL(BASE_URL + String.format(REPORT_URL, plugin.getDescription().getName())); // Connect to the website URLConnection connection = url.openConnection(); connection.setDoOutput(true); // Write the data OutputStreamWriter writer = new OutputStreamWriter(connection.getOutputStream()); writer.write(data); writer.flush(); // Now read the response BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream())); response = reader.readLine(); // close resources writer.close(); reader.close(); if (response.startsWith("OK")) { // Useless return, but it documents that we should be receiving OK followed by an optional description return; } else if (response.startsWith("ERR")) { // Throw it to whoever is catching us throw new IOException(response); } } #location 13 #vulnerability type RESOURCE_LEAK
#fixed code private void postPlugin(Plugin plugin, boolean isPing) throws IOException { // Construct the post data String response = "ERR No response"; String data = encode("guid") + "=" + encode(guid) + "&" + encode("version") + "=" + encode(plugin.getDescription().getVersion()) + "&" + encode("server") + "=" + encode(Bukkit.getVersion()) + "&" + encode("players") + "=" + encode(Bukkit.getServer().getOnlinePlayers().length + "") + "&" + encode("revision") + "=" + encode(REVISION + ""); // If we're pinging, append it if (isPing) { data += "&" + encode("ping") + "=" + encode("true"); } // Add any custom data (if applicable) Set<Plotter> plotters = customData.get(plugin); if (plotters != null) { for (Plotter plotter : plotters) { data += "&" + encode ("Custom" + plotter.getColumnName()) + "=" + encode(Integer.toString(plotter.getValue())); } } // Create the url URL url = new URL(BASE_URL + String.format(REPORT_URL, plugin.getDescription().getName())); // Connect to the website URLConnection connection = url.openConnection(); connection.setDoOutput(true); // Write the data OutputStreamWriter writer = new OutputStreamWriter(connection.getOutputStream()); writer.write(data); writer.flush(); // Now read the response BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream())); response = reader.readLine(); // close resources writer.close(); reader.close(); if (response.startsWith("OK")) { // Useless return, but it documents that we should be receiving OK followed by an optional description return; } else if (response.startsWith("ERR")) { // Throw it to whoever is catching us throw new IOException(response); } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public void load() { configuration = Configuration.load("core.yml"); registerCoreModules(); // check for upgrade before everything else new ConfigPost300().run(); plugin.loadDatabase(); Statistics.init(); physicalDatabase = new PhysDB(); databaseThread = new DatabaseThread(this); // Permissions init permissions = new NoPermissions(); if(permissions.getClass() == NoPermissions.class) { if (resolvePlugin("PermissionsBukkit") != null) { permissions = new BukkitPermissions(); } else if (resolvePlugin("PermissionsEx") != null) { permissions = new PEXPermissions(); } else if (resolvePlugin("bPermissions") != null) { permissions = new bPermissions(); } else { try { Method method = CraftHumanEntity.class.getDeclaredMethod("hasPermission", String.class); if (method != null) { permissions = new SuperPermsPermissions(); } } catch(NoSuchMethodException e) { // server does not support SuperPerms } } } // Currency init currency = new NoCurrency(); if (resolvePlugin("iConomy") != null) { // We need to figure out which iConomy plugin we have... Plugin plugin = resolvePlugin("iConomy"); // get the class name String className = plugin.getClass().getName(); // check for the iConomy5 package try { if (className.startsWith("com.iConomy")) { currency = new iConomy5Currency(); } else { // iConomy 6! currency = new iConomy6Currency(); } } catch (NoClassDefFoundError e) { } } else if (resolvePlugin("BOSEconomy") != null) { currency = new BOSECurrency(); } else if (resolvePlugin("Essentials") != null) { currency = new EssentialsCurrency(); } log("Permissions API: " + Colors.Red + permissions.getClass().getSimpleName()); log("Currency API: " + Colors.Red + currency.getClass().getSimpleName()); log("Connecting to " + Database.DefaultType); try { physicalDatabase.connect(); // We're connected, perform any necessary database changes log("Performing any necessary database updates"); physicalDatabase.load(); log("Using database: " + StringUtil.capitalizeFirstLetter(physicalDatabase.getConnection().getMetaData().getDriverVersion())); } catch (Exception e) { e.printStackTrace(); } // check any major conversions new MySQLPost200().run(); // precache protections physicalDatabase.precache(); // We are now done loading! moduleLoader.loadAll(); // Should we try metrics? if (!configuration.getBoolean("optional.optOut", false)) { try { Metrics metrics = new Metrics(); // Create a line graph Metrics.Graph lineGraph = metrics.createGraph(plugin, Metrics.Graph.Type.Line, "Protections"); // Add the total protections plotter lineGraph.addPlotter(new Metrics.Plotter("Total") { @Override public int getValue() { return physicalDatabase.getProtectionCount(); } }); // Create a pie graph for individual protections Metrics.Graph pieGraph = metrics.createGraph(plugin, Metrics.Graph.Type.Pie, "Protection percentages"); for (final Protection.Type type : Protection.Type.values()) { if (type == Protection.Type.RESERVED1 || type == Protection.Type.RESERVED2) { continue; } // Create the plotter Metrics.Plotter plotter = new Metrics.Plotter(StringUtil.capitalizeFirstLetter(type.toString()) + " Protections") { @Override public int getValue() { return physicalDatabase.getProtectionCount(type); } }; // Add it to both graphs lineGraph.addPlotter(plotter); pieGraph.addPlotter(plotter); } metrics.beginMeasuringPlugin(plugin); } catch (IOException e) { log(e.getMessage()); } } } #location 74 #vulnerability type NULL_DEREFERENCE
#fixed code public void load() { configuration = Configuration.load("core.yml"); registerCoreModules(); // check for upgrade before everything else new ConfigPost300().run(); plugin.loadDatabase(); Statistics.init(); physicalDatabase = new PhysDB(); databaseThread = new DatabaseThread(this); // Permissions init permissions = new SuperPermsPermissions(); if (resolvePlugin("PermissionsBukkit") != null) { permissions = new BukkitPermissions(); } else if (resolvePlugin("PermissionsEx") != null) { permissions = new PEXPermissions(); } else if (resolvePlugin("bPermissions") != null) { permissions = new bPermissions(); } // Currency init currency = new NoCurrency(); if (resolvePlugin("iConomy") != null) { // We need to figure out which iConomy plugin we have... Plugin plugin = resolvePlugin("iConomy"); // get the class name String className = plugin.getClass().getName(); // check for the iConomy5 package try { if (className.startsWith("com.iConomy")) { currency = new iConomy5Currency(); } else { // iConomy 6! currency = new iConomy6Currency(); } } catch (NoClassDefFoundError e) { } } else if (resolvePlugin("BOSEconomy") != null) { currency = new BOSECurrency(); } else if (resolvePlugin("Essentials") != null) { currency = new EssentialsCurrency(); } log("Permissions API: " + Colors.Red + permissions.getClass().getSimpleName()); log("Currency API: " + Colors.Red + currency.getClass().getSimpleName()); log("Connecting to " + Database.DefaultType); try { physicalDatabase.connect(); // We're connected, perform any necessary database changes log("Performing any necessary database updates"); physicalDatabase.load(); log("Using database: " + StringUtil.capitalizeFirstLetter(physicalDatabase.getConnection().getMetaData().getDriverVersion())); } catch (Exception e) { e.printStackTrace(); } // check any major conversions new MySQLPost200().run(); // precache protections physicalDatabase.precache(); // We are now done loading! moduleLoader.loadAll(); // Should we try metrics? if (!configuration.getBoolean("optional.optOut", false)) { try { Metrics metrics = new Metrics(); // Create a line graph Metrics.Graph lineGraph = metrics.createGraph(plugin, Metrics.Graph.Type.Line, "Protections"); // Add the total protections plotter lineGraph.addPlotter(new Metrics.Plotter("Total") { @Override public int getValue() { return physicalDatabase.getProtectionCount(); } }); // Create a pie graph for individual protections Metrics.Graph pieGraph = metrics.createGraph(plugin, Metrics.Graph.Type.Pie, "Protection percentages"); for (final Protection.Type type : Protection.Type.values()) { if (type == Protection.Type.RESERVED1 || type == Protection.Type.RESERVED2) { continue; } // Create the plotter Metrics.Plotter plotter = new Metrics.Plotter(StringUtil.capitalizeFirstLetter(type.toString()) + " Protections") { @Override public int getValue() { return physicalDatabase.getProtectionCount(type); } }; // Add it to both graphs lineGraph.addPlotter(plotter); pieGraph.addPlotter(plotter); } metrics.beginMeasuringPlugin(plugin); } catch (IOException e) { log(e.getMessage()); } } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public static Permission decodeJSON(JSONObject node) { Permission permission = new Permission(); // The values are stored as longs internally, despite us passing an int permission.setName((String) node.get("name")); permission.setType(Type.values()[((Long) node.get("type")).intValue()]); permission.setAccess(Access.values()[((Long) node.get("rights")).intValue()]); return permission; } #location 6 #vulnerability type NULL_DEREFERENCE
#fixed code public static Permission decodeJSON(JSONObject node) { Permission permission = new Permission(); Access access = Access.values()[((Long) node.get("rights")).intValue()]; if (access.ordinal() == 0) { access = Access.PLAYER; } // The values are stored as longs internally, despite us passing an int permission.setName((String) node.get("name")); permission.setType(Type.values()[((Long) node.get("type")).intValue()]); permission.setAccess(access); return permission; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code private void postPlugin(Plugin plugin, boolean isPing) throws IOException { // Construct the post data String response = "ERR No response"; String data = encode("guid") + "=" + encode(guid) + "&" + encode("version") + "=" + encode(plugin.getDescription().getVersion()) + "&" + encode("server") + "=" + encode(Bukkit.getVersion()) + "&" + encode("players") + "=" + encode(Bukkit.getServer().getOnlinePlayers().length + "") + "&" + encode("revision") + "=" + encode(REVISION + ""); // If we're pinging, append it if (isPing) { data += "&" + encode("ping") + "=" + encode("true"); } // Create the url URL url = new URL(BASE_URL + String.format(REPORT_URL, plugin.getDescription().getName())); // Connect to the website URLConnection connection = url.openConnection(); connection.setDoOutput(true); // Write the data OutputStreamWriter writer = new OutputStreamWriter(connection.getOutputStream()); writer.write(data); writer.flush(); // Now read the response BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream())); response = reader.readLine(); // close resources writer.close(); reader.close(); if (response.startsWith("OK")) { // Useless return, but it documents that we should be receiving OK followed by an optional description return; } else if (response.startsWith("ERR")) { // Throw it to whoever is catching us throw new IOException(response); } } #location 13 #vulnerability type RESOURCE_LEAK
#fixed code private void postPlugin(Plugin plugin, boolean isPing) throws IOException { // Construct the post data String response = "ERR No response"; String data = encode("guid") + "=" + encode(guid) + "&" + encode("version") + "=" + encode(plugin.getDescription().getVersion()) + "&" + encode("server") + "=" + encode(Bukkit.getVersion()) + "&" + encode("players") + "=" + encode(Bukkit.getServer().getOnlinePlayers().length + "") + "&" + encode("revision") + "=" + encode(REVISION + ""); // If we're pinging, append it if (isPing) { data += "&" + encode("ping") + "=" + encode("true"); } // Add any custom data (if applicable) Set<Plotter> plotters = customData.get(plugin); if (plotters != null) { for (Plotter plotter : plotters) { data += "&" + encode ("Custom" + plotter.getColumnName()) + "=" + encode(Integer.toString(plotter.getValue())); } } // Create the url URL url = new URL(BASE_URL + String.format(REPORT_URL, plugin.getDescription().getName())); // Connect to the website URLConnection connection = url.openConnection(); connection.setDoOutput(true); // Write the data OutputStreamWriter writer = new OutputStreamWriter(connection.getOutputStream()); writer.write(data); writer.flush(); // Now read the response BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream())); response = reader.readLine(); // close resources writer.close(); reader.close(); if (response.startsWith("OK")) { // Useless return, but it documents that we should be receiving OK followed by an optional description return; } else if (response.startsWith("ERR")) { // Throw it to whoever is catching us throw new IOException(response); } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public static AccessRight decodeJSON(JSONObject node) { AccessRight right = new AccessRight(); // The values are stored as longs internally, despite us passing an int right.setProtectionId(((Long) node.get("protection")).intValue()); right.setType(((Long) node.get("type")).intValue()); right.setName((String) node.get("name")); right.setRights(((Long) node.get("rights")).intValue()); return right; } #location 5 #vulnerability type NULL_DEREFERENCE
#fixed code public static AccessRight decodeJSON(JSONObject node) { AccessRight right = new AccessRight(); // The values are stored as longs internally, despite us passing an int // right.setProtectionId(((Long) node.get("protection")).intValue()); right.setType(((Long) node.get("type")).intValue()); right.setName((String) node.get("name")); right.setRights(((Long) node.get("rights")).intValue()); return right; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code protected void initialize(final int cachePercent) throws IOException { final long fileBytes = file.length(); final long cacheSize = (fileBytes / 100) * cachePercent; final long cacheModulus = cacheSize == 0 ? fileBytes : cacheSize > fileBytes ? 1 : fileBytes / cacheSize; if (cache == null) { throw new IllegalStateException("Cannot initialize after close has been called."); } FileWord a; FileWord b = null; synchronized (cache) { position = 0; seek(0); cache.clear(); while ((a = nextWord()) != null) { if (b != null && comparator.compare(a.word, b.word) < 0) { throw new IllegalArgumentException("File is not sorted correctly for this comparator"); } b = a; if (cacheSize > 0 && size % cacheModulus == 0) { cache.put(size, a.offset); } size++; } } } #location 10 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code protected void initialize(final int cachePercent) throws IOException { cache = new Cache(file.length(), cachePercent); FileWord a; FileWord b = null; synchronized (cache) { position = 0; seek(position); while ((a = nextWord()) != null) { if (b != null && comparator.compare(a.word, b.word) < 0) { throw new IllegalArgumentException("File is not sorted correctly for this comparator"); } b = a; cache.put(size++, position); } } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code protected String readWord(final int index) throws IOException { int i = 0; if (!cache.isEmpty() && cache.firstKey() <= index) { i = cache.floorKey(index); } FileWord w; synchronized (cache) { position = i > 0 ? cache.get(i) : 0L; seek(position); do { w = nextWord(); } while (i++ < index && w != null); return w != null ? w.word : null; } } #location 15 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code protected String readWord(final int index) throws IOException { FileWord w; int i; synchronized (cache) { final Cache.Entry entry = cache.get(index); i = entry.index; seek(entry.position); do { w = nextWord(); } while (i++ < index && w != null); return w != null ? w.word : null; } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public HttpConfig files(String[] filePaths, String inputName, boolean forceRemoveContentTypeChraset) { synchronized (getClass()) { if(this.map==null){ this.map= new HashMap<String, Object>(); } } map.put(Utils.ENTITY_MULTIPART, filePaths); map.put(Utils.ENTITY_MULTIPART+".name", inputName); map.put(Utils.ENTITY_MULTIPART+".rmCharset", forceRemoveContentTypeChraset); return this; } #location 9 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code public HttpConfig files(String[] filePaths, String inputName, boolean forceRemoveContentTypeChraset) { // synchronized (getClass()) { // if(this.map==null){ // this.map= new HashMap<String, Object>(); // } // } // map.put(Utils.ENTITY_MULTIPART, filePaths); // map.put(Utils.ENTITY_MULTIPART+".name", inputName); // map.put(Utils.ENTITY_MULTIPART+".rmCharset", forceRemoveContentTypeChraset); Map<String, Object> m = maps.get(); if(m==null || m==null){ m = new HashMap<String, Object>(); } m.put(Utils.ENTITY_MULTIPART, filePaths); m.put(Utils.ENTITY_MULTIPART+".name", inputName); m.put(Utils.ENTITY_MULTIPART+".rmCharset", forceRemoveContentTypeChraset); maps.set(m); return this; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public HttpConfig json(String json) { this.json = json; map = new HashMap<String, Object>(); map.put(Utils.ENTITY_STRING, json); return this; } #location 3 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code public HttpConfig json(String json) { this.json = json; Map<String, Object> map = new HashMap<String, Object>(); map.put(Utils.ENTITY_STRING, json); maps.set(map); return this; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public Map<String, Object> map() { return map; } #location 2 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code public Map<String, Object> map() { // return map; return maps.get(); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public HttpConfig json(String json) { this.json = json; map = new HashMap<String, Object>(); map.put(Utils.ENTITY_STRING, json); return this; } #location 4 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code public HttpConfig json(String json) { this.json = json; Map<String, Object> map = new HashMap<String, Object>(); map.put(Utils.ENTITY_STRING, json); maps.set(map); return this; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code private static String usageString(CommandLine commandLine, Help.Ansi ansi) throws UnsupportedEncodingException { ByteArrayOutputStream baos = new ByteArrayOutputStream(); commandLine.usage(new PrintStream(baos, true, "UTF8"), ansi); String result = baos.toString("UTF8"); return result; } #location 3 #vulnerability type RESOURCE_LEAK
#fixed code private static String usageString(CommandLine commandLine, Help.Ansi ansi) throws UnsupportedEncodingException { ByteArrayOutputStream baos = new ByteArrayOutputStream(); commandLine.usage(new PrintStream(baos, true, "UTF8"), ansi); String result = baos.toString("UTF8"); if (ansi == Help.Ansi.AUTO) { baos.reset(); commandLine.usage(new PrintStream(baos, true, "UTF8")); assertEquals(result, baos.toString("UTF8")); } else if (ansi == Help.Ansi.ON) { baos.reset(); commandLine.usage(new PrintStream(baos, true, "UTF8"), Help.defaultColorScheme(Help.Ansi.ON)); assertEquals(result, baos.toString("UTF8")); } return result; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Override public void verify(final UChannel channel,String extension, final ISDKVerifyListener callback) { try{ JSONObject json = JSONObject.fromObject(extension); final String ts = json.getString("ts"); final String playerId = json.getString("playerId"); final String accessToken = json.getString("accessToken"); final String nickname = json.getString("nickName"); StringBuilder sb = new StringBuilder(); sb.append(channel.getCpAppID()).append(ts).append(playerId); boolean ok = RSAUtil.verify(sb.toString().getBytes("UTF-8"), LOGIN_RSA_PUBLIC, accessToken); if(ok){ SDKVerifyResult vResult = new SDKVerifyResult(true, playerId, "", nickname); callback.onSuccess(vResult); }else{ callback.onFailed(channel.getMaster().getSdkName() + " verify failed."); } }catch (Exception e){ e.printStackTrace(); callback.onFailed(channel.getMaster().getSdkName() + " verify execute failed. the exception is "+e.getMessage()); } } #location 22 #vulnerability type NULL_DEREFERENCE
#fixed code @Override public void verify(final UChannel channel,String extension, final ISDKVerifyListener callback) { try{ JSONObject json = JSONObject.fromObject(extension); final String ts = json.getString("ts"); final String playerId = json.getString("playerId"); final String accessToken = json.getString("accessToken"); final String nickname = json.getString("nickName"); SDKVerifyResult vResult = new SDKVerifyResult(true, playerId, "", ""); callback.onSuccess(vResult); ///2016-10-27 华为这版本流程这里,分为两步,这里不便服务器端做验证,注释下面这些 // StringBuilder sb = new StringBuilder(); // sb.append(channel.getCpAppID()).append(ts).append(playerId); // boolean ok = RSAUtil.verify(sb.toString().getBytes("UTF-8"), LOGIN_RSA_PUBLIC, accessToken); // if(ok){ // // SDKVerifyResult vResult = new SDKVerifyResult(true, playerId, "", nickname); // // callback.onSuccess(vResult); // }else{ // callback.onFailed(channel.getMaster().getSdkName() + " verify failed."); // } }catch (Exception e){ e.printStackTrace(); callback.onFailed(channel.getMaster().getSdkName() + " verify execute failed. the exception is "+e.getMessage()); } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void testOverridenFields() throws Exception { MappingFileReader fileReader = new MappingFileReader("overridemapping.xml"); MappingFileData mappingFileData = fileReader.read(); MappingsParser mappingsParser = MappingsParser.getInstance(); mappingsParser.processMappings(mappingFileData.getClassMaps(), mappingFileData.getConfiguration()); // validate class mappings Iterator<?> iter = mappingFileData.getClassMaps().iterator(); while (iter.hasNext()) { ClassMap classMap = (ClassMap) iter.next(); if (classMap.getSrcClassToMap().getName().equals("net.sf.dozer.util.mapping.vo.FurtherTestObject")) { assertTrue(classMap.isStopOnErrors()); } if (classMap.getSrcClassToMap().getName().equals("net.sf.dozer.util.mapping.vo.SuperSuperSuperClass")) { assertTrue(classMap.isWildcard()); } if (classMap.getSrcClassToMap().getName().equals("net.sf.dozer.util.mapping.vo.TestObject")) { assertTrue(!(classMap.getFieldMaps().get(0)).isCopyByReference()); } } } #location 4 #vulnerability type NULL_DEREFERENCE
#fixed code @Test public void testOverridenFields() throws Exception { MappingFileReader fileReader = new MappingFileReader(XMLParserFactory.getInstance()); MappingFileData mappingFileData = fileReader.read("overridemapping.xml"); MappingsParser mappingsParser = MappingsParser.getInstance(); mappingsParser.processMappings(mappingFileData.getClassMaps(), mappingFileData.getConfiguration()); // validate class mappings for (ClassMap classMap : mappingFileData.getClassMaps()) { if (classMap.getSrcClassToMap().getName().equals("net.sf.dozer.util.mapping.vo.FurtherTestObject")) { assertTrue(classMap.isStopOnErrors()); } if (classMap.getSrcClassToMap().getName().equals("net.sf.dozer.util.mapping.vo.SuperSuperSuperClass")) { assertTrue(classMap.isWildcard()); } if (classMap.getSrcClassToMap().getName().equals("net.sf.dozer.util.mapping.vo.TestObject")) { assertTrue(!(classMap.getFieldMaps().get(0)).isCopyByReference()); } } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void testDetectDuplicateMapping() throws Exception { MappingFileReader fileReader = new MappingFileReader("duplicateMapping.xml"); MappingFileData mappingFileData = fileReader.read(); try { parser.processMappings(mappingFileData.getClassMaps(), new Configuration()); fail("should have thrown exception"); } catch (Exception e) { assertTrue("invalid exception", e.getMessage().indexOf("Duplicate Class Mapping Found") != -1); } } #location 4 #vulnerability type NULL_DEREFERENCE
#fixed code @Test public void testDetectDuplicateMapping() throws Exception { MappingFileReader fileReader = new MappingFileReader(XMLParserFactory.getInstance()); MappingFileData mappingFileData = fileReader.read("duplicateMapping.xml"); try { parser.processMappings(mappingFileData.getClassMaps(), new Configuration()); fail("should have thrown exception"); } catch (Exception e) { assertTrue("invalid exception", e.getMessage().indexOf("Duplicate Class Mapping Found") != -1); } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code protected void writeDeepDestinationValue(Object destObj, Object destFieldValue, FieldMap fieldMap) { // follow deep field hierarchy. If any values are null along the way, then create a new instance DeepHierarchyElement[] hierarchy = getDeepFieldHierarchy(destObj, fieldMap.getDestDeepIndexHintContainer()); // first, iteratate through hierarchy and instantiate any objects that are null Object parentObj = destObj; int hierarchyLength = hierarchy.length - 1; int hintIndex = 0; for (int i = 0; i < hierarchyLength; i++) { DeepHierarchyElement hierarchyElement = hierarchy[i]; PropertyDescriptor pd = hierarchyElement.getPropDescriptor(); Object value = ReflectionUtils.invoke(pd.getReadMethod(), parentObj, null); Class clazz; if (value == null) { clazz = pd.getPropertyType(); if (clazz.isInterface() && (i + 1) == hierarchyLength && fieldMap.getDestHintContainer() != null) { // before setting the property on the destination object we should check for a destination hint. need to know // that we are at the end of the line determine the property type clazz = fieldMap.getDestHintContainer().getHint(); } Object o = null; if (clazz.isArray()) { o = MappingUtils.prepareIndexedCollection(clazz, value, DestBeanCreator.create(clazz.getComponentType()), hierarchyElement.getIndex()); } else if (Collection.class.isAssignableFrom(clazz)) { Class collectionEntryType; Class genericType = ReflectionUtils.determineGenericsType(pd); if (genericType != null) { collectionEntryType = genericType; } else { collectionEntryType = fieldMap.getDestDeepIndexHintContainer().getHint(hintIndex); //hint index is used to handle multiple hints hintIndex += 1; } o = MappingUtils.prepareIndexedCollection(clazz, value, DestBeanCreator.create(collectionEntryType), hierarchyElement .getIndex()); } else { try { o = DestBeanCreator.create(clazz); } catch (Exception e) { //lets see if they have a factory we can try as a last ditch. If not...throw the exception: if (fieldMap.getClassMap().getDestClassBeanFactory() != null) { o = DestBeanCreator.create(null, fieldMap.getClassMap().getSrcClassToMap(), clazz, clazz, fieldMap.getClassMap() .getDestClassBeanFactory(), fieldMap.getClassMap().getDestClassBeanFactoryId(), null); } else { MappingUtils.throwMappingException(e); } } } ReflectionUtils.invoke(pd.getWriteMethod(), parentObj, new Object[] { o }); value = ReflectionUtils.invoke(pd.getReadMethod(), parentObj, null); } //Check to see if collection needs to be resized if (MappingUtils.isSupportedCollection(value.getClass())) { int currentSize = CollectionUtils.getLengthOfCollection(value); if (currentSize < hierarchyElement.getIndex() + 1) { value = MappingUtils.prepareIndexedCollection(pd.getPropertyType(), value, DestBeanCreator.create(pd.getPropertyType().getComponentType()), hierarchyElement.getIndex()); ReflectionUtils.invoke(pd.getWriteMethod(), parentObj, new Object[] { value }); } } if (value != null && value.getClass().isArray()) { parentObj = Array.get(value, hierarchyElement.getIndex()); } else if (value != null && Collection.class.isAssignableFrom(value.getClass())) { parentObj = MappingUtils.getIndexedValue(value, hierarchyElement.getIndex()); } else { parentObj = value; } } // second, set the very last field in the deep hierarchy PropertyDescriptor pd = hierarchy[hierarchy.length - 1].getPropDescriptor(); Class type; // For one-way mappings there could be no read method if (pd.getReadMethod() != null) { type = pd.getReadMethod().getReturnType(); } else { type = pd.getWriteMethod().getParameterTypes()[0]; } if (!type.isPrimitive() || destFieldValue != null) { if (!isIndexed) { Method method = pd.getWriteMethod(); try { if (method == null && getSetMethodName() != null) { // lets see if we can find a custom method method = ReflectionUtils.findAMethod(parentObj.getClass(), getSetMethodName()); } } catch (NoSuchMethodException e) { MappingUtils.throwMappingException(e); } ReflectionUtils.invoke(method, parentObj, new Object[] { destFieldValue }); } else { writeIndexedValue(parentObj, destFieldValue); } } } #location 96 #vulnerability type NULL_DEREFERENCE
#fixed code protected void writeDeepDestinationValue(Object destObj, Object destFieldValue, FieldMap fieldMap) { // follow deep field hierarchy. If any values are null along the way, then create a new instance DeepHierarchyElement[] hierarchy = getDeepFieldHierarchy(destObj, fieldMap.getDestDeepIndexHintContainer()); // first, iteratate through hierarchy and instantiate any objects that are null Object parentObj = destObj; int hierarchyLength = hierarchy.length - 1; int hintIndex = 0; for (int i = 0; i < hierarchyLength; i++) { DeepHierarchyElement hierarchyElement = hierarchy[i]; PropertyDescriptor pd = hierarchyElement.getPropDescriptor(); Object value = ReflectionUtils.invoke(pd.getReadMethod(), parentObj, null); Class clazz; if (value == null) { clazz = pd.getPropertyType(); if (clazz.isInterface() && (i + 1) == hierarchyLength && fieldMap.getDestHintContainer() != null) { // before setting the property on the destination object we should check for a destination hint. need to know // that we are at the end of the line determine the property type clazz = fieldMap.getDestHintContainer().getHint(); } Object o = null; if (clazz.isArray()) { o = MappingUtils.prepareIndexedCollection(clazz, value, DestBeanCreator.create(clazz.getComponentType()), hierarchyElement.getIndex()); } else if (Collection.class.isAssignableFrom(clazz)) { Class collectionEntryType; Class genericType = ReflectionUtils.determineGenericsType(pd); if (genericType != null) { collectionEntryType = genericType; } else { collectionEntryType = fieldMap.getDestDeepIndexHintContainer().getHint(hintIndex); //hint index is used to handle multiple hints hintIndex += 1; } o = MappingUtils.prepareIndexedCollection(clazz, value, DestBeanCreator.create(collectionEntryType), hierarchyElement .getIndex()); } else { try { o = DestBeanCreator.create(clazz); } catch (Exception e) { //lets see if they have a factory we can try as a last ditch. If not...throw the exception: if (fieldMap.getClassMap().getDestClassBeanFactory() != null) { o = DestBeanCreator.create(null, fieldMap.getClassMap().getSrcClassToMap(), clazz, clazz, fieldMap.getClassMap() .getDestClassBeanFactory(), fieldMap.getClassMap().getDestClassBeanFactoryId(), null); } else { MappingUtils.throwMappingException(e); } } } ReflectionUtils.invoke(pd.getWriteMethod(), parentObj, new Object[] { o }); value = ReflectionUtils.invoke(pd.getReadMethod(), parentObj, null); } //Check to see if collection needs to be resized if (MappingUtils.isSupportedCollection(value.getClass())) { int currentSize = CollectionUtils.getLengthOfCollection(value); if (currentSize < hierarchyElement.getIndex() + 1) { value = MappingUtils.prepareIndexedCollection(pd.getPropertyType(), value, DestBeanCreator.create(pd.getPropertyType() .getComponentType()), hierarchyElement.getIndex()); ReflectionUtils.invoke(pd.getWriteMethod(), parentObj, new Object[] { value }); } } if (value != null && value.getClass().isArray()) { parentObj = Array.get(value, hierarchyElement.getIndex()); } else if (value != null && Collection.class.isAssignableFrom(value.getClass())) { parentObj = MappingUtils.getIndexedValue(value, hierarchyElement.getIndex()); } else { parentObj = value; } } // second, set the very last field in the deep hierarchy PropertyDescriptor pd = hierarchy[hierarchy.length - 1].getPropDescriptor(); Class type; // For one-way mappings there could be no read method if (pd.getReadMethod() != null) { type = pd.getReadMethod().getReturnType(); } else { type = pd.getWriteMethod().getParameterTypes()[0]; } if (!type.isPrimitive() || destFieldValue != null) { if (!isIndexed) { Method method = null; if (!isCustomSetMethod()) { method = pd.getWriteMethod(); } else { try { method = ReflectionUtils.findAMethod(parentObj.getClass(), getSetMethodName()); } catch (NoSuchMethodException e) { MappingUtils.throwMappingException(e); } } ReflectionUtils.invoke(method, parentObj, new Object[] { destFieldValue }); } else { writeIndexedValue(parentObj, destFieldValue); } } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void testDuplicateMapIds() throws Exception { MappingFileReader fileReader = new MappingFileReader("duplicateMapIdsMapping.xml"); MappingFileData mappingFileData = fileReader.read(); try { parser.processMappings(mappingFileData.getClassMaps(), new Configuration()); fail("should have thrown exception"); } catch (Exception e) { assertTrue("invalid exception thrown", e.getMessage().indexOf("Duplicate Map Id") != -1); } } #location 4 #vulnerability type NULL_DEREFERENCE
#fixed code @Test public void testDuplicateMapIds() throws Exception { MappingFileReader fileReader = new MappingFileReader(XMLParserFactory.getInstance()); MappingFileData mappingFileData = fileReader.read("duplicateMapIdsMapping.xml"); try { parser.processMappings(mappingFileData.getClassMaps(), new Configuration()); fail("should have thrown exception"); } catch (Exception e) { assertTrue("invalid exception thrown", e.getMessage().indexOf("Duplicate Map Id") != -1); } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code void initialize(GlobalSettings globalSettings, ClassLoader classLoader) { if (globalSettings.isAutoregisterJMXBeans()) { // Register JMX MBeans. If an error occurs, don't propagate exception try { registerJMXBeans(new JMXPlatformImpl()); } catch (Throwable t) { log.warn("Unable to register Dozer JMX MBeans with the PlatformMBeanServer. Dozer will still function " + "normally, but management via JMX may not be available", t); } } String classLoaderName = globalSettings.getClassLoaderName(); String proxyResolverName = globalSettings.getProxyResolverName(); DefaultClassLoader defaultClassLoader = new DefaultClassLoader(classLoader); BeanContainer beanContainer = BeanContainer.getInstance(); Class<? extends DozerClassLoader> classLoaderType = loadBeanType(classLoaderName, defaultClassLoader, DozerClassLoader.class); Class<? extends DozerProxyResolver> proxyResolverType = loadBeanType(proxyResolverName, defaultClassLoader, DozerProxyResolver.class); // TODO Chicken-egg problem - investigate // DozerClassLoader classLoaderBean = ReflectionUtils.newInstance(classLoaderType); DozerClassLoader classLoaderBean = defaultClassLoader; DozerProxyResolver proxyResolverBean = ReflectionUtils.newInstance(proxyResolverType); beanContainer.setClassLoader(classLoaderBean); beanContainer.setProxyResolver(proxyResolverBean); if (globalSettings.isElEnabled()) { ELEngine engine = new ELEngine(); engine.init(); beanContainer.setElEngine(engine); beanContainer.setElementReader(new ExpressionElementReader(engine)); } for (DozerModule module : ServiceLoader.load(DozerModule.class)) { module.init(); } } #location 24 #vulnerability type NULL_DEREFERENCE
#fixed code void initialize(GlobalSettings globalSettings, ClassLoader classLoader) { if (globalSettings.isAutoregisterJMXBeans()) { // Register JMX MBeans. If an error occurs, don't propagate exception try { registerJMXBeans(new JMXPlatformImpl()); } catch (Throwable t) { log.warn("Unable to register Dozer JMX MBeans with the PlatformMBeanServer. Dozer will still function " + "normally, but management via JMX may not be available", t); } } BeanContainer beanContainer = BeanContainer.getInstance(); registerClassLoader(globalSettings, classLoader, beanContainer); registerProxyResolver(globalSettings, beanContainer); if (globalSettings.isElEnabled()) { ELEngine engine = new ELEngine(); engine.init(); beanContainer.setElEngine(engine); beanContainer.setElementReader(new ExpressionElementReader(engine)); } for (DozerModule module : ServiceLoader.load(DozerModule.class)) { module.init(); } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public String getBeanId() { Class<?> factoryClass = objectFactory(destObjClass).getClass(); Class<?> destClass = null; String methodName = "create" + destObjClass.substring(destObjClass.lastIndexOf(".") + 1) + StringUtils.capitalize(destFieldName); try { Method method = ReflectionUtils.findAMethod(factoryClass, methodName); Class<?>[] parameterTypes = method.getParameterTypes(); for (Class<?> parameterClass : parameterTypes) { destClass = parameterClass; break; } } catch (NoSuchMethodException e) { MappingUtils.throwMappingException(e); } return destClass.getCanonicalName(); } #location 17 #vulnerability type NULL_DEREFERENCE
#fixed code public String getBeanId() { Class<?> factoryClass = objectFactory(destObjClass).getClass(); Class<?> destClass = null; String methodName = "create" + destObjClass.substring(destObjClass.lastIndexOf(".") + 1) + StringUtils.capitalize(destFieldName); try { Method method = ReflectionUtils.findAMethod(factoryClass, methodName); Class<?>[] parameterTypes = method.getParameterTypes(); for (Class<?> parameterClass : parameterTypes) { destClass = parameterClass; break; } } catch (NoSuchMethodException e) { MappingUtils.throwMappingException(e); } return (destClass != null) ? destClass.getCanonicalName() : null; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public long getValue() { return value; } #location 2 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code public long getValue() { return value.get(); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code void initialize(GlobalSettings globalSettings, ClassLoader classLoader) { if (globalSettings.isAutoregisterJMXBeans()) { // Register JMX MBeans. If an error occurs, don't propagate exception try { registerJMXBeans(new JMXPlatformImpl()); } catch (Throwable t) { log.warn("Unable to register Dozer JMX MBeans with the PlatformMBeanServer. Dozer will still function " + "normally, but management via JMX may not be available", t); } } String classLoaderName = globalSettings.getClassLoaderName(); String proxyResolverName = globalSettings.getProxyResolverName(); DefaultClassLoader defaultClassLoader = new DefaultClassLoader(classLoader); BeanContainer beanContainer = BeanContainer.getInstance(); Class<? extends DozerClassLoader> classLoaderType = loadBeanType(classLoaderName, defaultClassLoader, DozerClassLoader.class); Class<? extends DozerProxyResolver> proxyResolverType = loadBeanType(proxyResolverName, defaultClassLoader, DozerProxyResolver.class); // TODO Chicken-egg problem - investigate // DozerClassLoader classLoaderBean = ReflectionUtils.newInstance(classLoaderType); DozerClassLoader classLoaderBean = defaultClassLoader; DozerProxyResolver proxyResolverBean = ReflectionUtils.newInstance(proxyResolverType); beanContainer.setClassLoader(classLoaderBean); beanContainer.setProxyResolver(proxyResolverBean); if (globalSettings.isElEnabled()) { ELEngine engine = new ELEngine(); engine.init(); beanContainer.setElEngine(engine); beanContainer.setElementReader(new ExpressionElementReader(engine)); } for (DozerModule module : ServiceLoader.load(DozerModule.class)) { module.init(); } } #location 27 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code void initialize(GlobalSettings globalSettings, ClassLoader classLoader) { if (globalSettings.isAutoregisterJMXBeans()) { // Register JMX MBeans. If an error occurs, don't propagate exception try { registerJMXBeans(new JMXPlatformImpl()); } catch (Throwable t) { log.warn("Unable to register Dozer JMX MBeans with the PlatformMBeanServer. Dozer will still function " + "normally, but management via JMX may not be available", t); } } BeanContainer beanContainer = BeanContainer.getInstance(); registerClassLoader(globalSettings, classLoader, beanContainer); registerProxyResolver(globalSettings, beanContainer); if (globalSettings.isElEnabled()) { ELEngine engine = new ELEngine(); engine.init(); beanContainer.setElEngine(engine); beanContainer.setElementReader(new ExpressionElementReader(engine)); } for (DozerModule module : ServiceLoader.load(DozerModule.class)) { module.init(); } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public static boolean isEnumType(Class srcFieldClass, Class destFieldType){ if (GlobalSettings.getInstance().isJava5()){//Verify if running JRE is 1.5 or above if (srcFieldClass.isAnonymousClass()){ //If srcFieldClass is anonymous class, replace srcFieldClass with its enclosing class. //This is used to ensure Dozer can get correct Enum type. srcFieldClass = srcFieldClass.getEnclosingClass(); } if (destFieldType.isAnonymousClass()){ //Just like srcFieldClass, if destFieldType is anonymous class, replace destFieldType with //its enclosing class. This is used to ensure Dozer can get correct Enum type. destFieldType = destFieldType.getEnclosingClass(); } return ((Boolean) ReflectionUtils .invoke(Jdk5Methods.getInstance().getClassIsEnumMethod(), srcFieldClass, null)) .booleanValue() && ((Boolean) ReflectionUtils .invoke(Jdk5Methods.getInstance().getClassIsEnumMethod(), destFieldType, null)) .booleanValue(); } return false; } #location 15 #vulnerability type NULL_DEREFERENCE
#fixed code public static boolean isEnumType(Class srcFieldClass, Class destFieldType){ if (GlobalSettings.getInstance().isJava5()){//Verify if running JRE is 1.5 or above if ( ((Boolean) ReflectionUtils.invoke(Jdk5Methods.getInstance().getIsAnonymousClassMethod(), srcFieldClass, null)).booleanValue()) { //If srcFieldClass is anonymous class, replace srcFieldClass with its enclosing class. //This is used to ensure Dozer can get correct Enum type. srcFieldClass = (Class) ReflectionUtils.invoke(Jdk5Methods.getInstance().getGetEnclosingClassMethod(), srcFieldClass, null); } if ( ((Boolean) ReflectionUtils.invoke(Jdk5Methods.getInstance().getIsAnonymousClassMethod(), destFieldType, null)).booleanValue()) { //Just like srcFieldClass, if destFieldType is anonymous class, replace destFieldType with //its enclosing class. This is used to ensure Dozer can get correct Enum type. destFieldType = (Class) ReflectionUtils.invoke(Jdk5Methods.getInstance().getGetEnclosingClassMethod(), destFieldType, null); } return ((Boolean) ReflectionUtils .invoke(Jdk5Methods.getInstance().getClassIsEnumMethod(), srcFieldClass, null)) .booleanValue() && ((Boolean) ReflectionUtils .invoke(Jdk5Methods.getInstance().getClassIsEnumMethod(), destFieldType, null)) .booleanValue(); } return false; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public static String getScript(String path) { StringBuilder sb = new StringBuilder(); InputStream stream = ScriptUtil.class.getClassLoader().getResourceAsStream(path); BufferedReader br = new BufferedReader(new InputStreamReader(stream)); try { String str = ""; while ((str = br.readLine()) != null) { sb.append(str).append(System.lineSeparator()); } } catch (IOException e) { System.err.println(e.getStackTrace()); } return sb.toString(); } #location 13 #vulnerability type RESOURCE_LEAK
#fixed code public static String getScript(String path) { StringBuilder sb = new StringBuilder(); InputStream stream = ScriptUtil.class.getClassLoader().getResourceAsStream(path); try (BufferedReader br = new BufferedReader(new InputStreamReader(stream))){ String str; while ((str = br.readLine()) != null) { sb.append(str).append(System.lineSeparator()); } } catch (IOException e) { System.err.println(e.getStackTrace()); } return sb.toString(); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public boolean limit() { String key = String.valueOf(System.currentTimeMillis() / 1000); Object result = null; RedisClusterConnection clusterConnection = jedis.getClusterConnection(); if (clusterConnection != null){ JedisCluster jedisCluster = (JedisCluster) clusterConnection.getNativeConnection(); result = jedisCluster.eval(script, Collections.singletonList(key), Collections.singletonList(String.valueOf(limit))); }else { Jedis jedis = (Jedis) clusterConnection.getNativeConnection(); result = jedis.eval(script, Collections.singletonList(key), Collections.singletonList(String.valueOf(limit))); } if (FAIL_CODE != (Long) result) { return true; } else { return false; } } #location 9 #vulnerability type NULL_DEREFERENCE
#fixed code public boolean limit() { String key = String.valueOf(System.currentTimeMillis() / 1000); Object result = null; try { RedisClusterConnection clusterConnection = jedis.getClusterConnection(); JedisCluster jedisCluster = (JedisCluster) clusterConnection.getNativeConnection(); result = jedisCluster.eval(script, Collections.singletonList(key), Collections.singletonList(String.valueOf(limit))); if (FAIL_CODE != (Long) result) { return true; } else { return false; } }catch (InvalidDataAccessApiUsageException e){ } Jedis jedisConn = (Jedis)jedis.getConnection().getNativeConnection() ; result = jedisConn.eval(script, Collections.singletonList(key), Collections.singletonList(String.valueOf(limit))); if (FAIL_CODE != (Long) result) { return true; } else { return false; } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code private void init() { HostAndPort hostAndPort = new HostAndPort("10.19.13.51", 7000); JedisCluster jedisCluster = new JedisCluster(hostAndPort); //redisLimit = new RedisLimit.Builder(jedisCluster) // .limit(100) // .build(); } #location 3 #vulnerability type RESOURCE_LEAK
#fixed code private void init() { HostAndPort hostAndPort = new HostAndPort("10.19.13.51", 7000); JedisCluster jedisCluster = new JedisCluster(hostAndPort); redisLimit = new RedisLimit.Builder<>(jedisCluster) .limit(100) .build(); }
Below is the vulnerable code, please generate the patch based on the following information.