instruction
stringclasses 1
value | output
stringlengths 64
69.4k
| input
stringlengths 205
32.4k
|
---|---|---|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
@Test
public void testExcelFormat1() throws IOException {
String code =
"value1,value2,value3,value4\r\na,b,c,d\r\n x,,,"
+ "\r\n\r\n\"\"\"hello\"\"\",\" \"\"world\"\"\",\"abc\ndef\",\r\n";
String[][] res = {
{"value1", "value2", "value3", "value4"},
{"a", "b", "c", "d"},
{" x", "", "", ""},
{""},
{"\"hello\"", " \"world\"", "abc\ndef", ""}
};
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()));
}
}
|
#vulnerable code
@Test
public void testExcelFormat1() throws IOException {
String code =
"value1,value2,value3,value4\r\na,b,c,d\r\n x,,,"
+ "\r\n\r\n\"\"\"hello\"\"\",\" \"\"world\"\"\",\"abc\ndef\",\r\n";
String[][] res = {
{"value1", "value2", "value3", "value4"},
{"a", "b", "c", "d"},
{" x", "", "", ""},
{""},
{"\"hello\"", " \"world\"", "abc\ndef", ""}
};
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 15
#vulnerability type NULL_DEREFERENCE
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
public void testIterator() {
Reader in = new StringReader("a,b,c\n1,2,3\nx,y,z");
Iterator<String[]> iterator = CSVFormat.DEFAULT.parse(in).iterator();
assertTrue(iterator.hasNext());
try {
iterator.remove();
fail("expected UnsupportedOperationException");
} catch (UnsupportedOperationException expected) {
}
assertTrue(Arrays.equals(new String[]{"a", "b", "c"}, iterator.next()));
assertTrue(Arrays.equals(new String[]{"1", "2", "3"}, iterator.next()));
assertTrue(iterator.hasNext());
assertTrue(iterator.hasNext());
assertTrue(iterator.hasNext());
assertTrue(Arrays.equals(new String[]{"x", "y", "z"}, iterator.next()));
assertFalse(iterator.hasNext());
try {
iterator.next();
fail("NoSuchElementException expected");
} catch (NoSuchElementException e) {
// expected
}
}
|
#vulnerable code
public void testIterator() {
Reader in = new StringReader("a,b,c\n1,2,3\nx,y,z");
Iterator<String[]> iterator = CSVFormat.DEFAULT.parse(in).iterator();
assertTrue(iterator.hasNext());
iterator.remove();
assertTrue(Arrays.equals(new String[]{"a", "b", "c"}, iterator.next()));
assertTrue(Arrays.equals(new String[]{"1", "2", "3"}, iterator.next()));
assertTrue(iterator.hasNext());
assertTrue(iterator.hasNext());
assertTrue(iterator.hasNext());
assertTrue(Arrays.equals(new String[]{"x", "y", "z"}, iterator.next()));
assertFalse(iterator.hasNext());
try {
iterator.next();
fail("NoSuchElementException expected");
} catch (NoSuchElementException e) {
// expected
}
}
#location 21
#vulnerability type RESOURCE_LEAK
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
@Test
public void testQuoteAll() throws IOException {
final StringWriter sw = new StringWriter();
final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.newBuilder().withQuotePolicy(Quote.ALL).build());
printer.printRecord("a", "b\nc", "d");
assertEquals("\"a\",\"b\nc\",\"d\"" + recordSeparator, sw.toString());
printer.close();
}
|
#vulnerable code
@Test
public void testQuoteAll() throws IOException {
final StringWriter sw = new StringWriter();
final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.newBuilder().withQuotePolicy(Quote.ALL).build());
printer.printRecord("a", "b\nc", "d");
assertEquals("\"a\",\"b\nc\",\"d\"" + recordSeparator, sw.toString());
}
#location 5
#vulnerability type RESOURCE_LEAK
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
private 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.parse(result, format);
final List<CSVRecord> parseResult = parser.getRecords();
Utils.compare("Printer output :" + printable(result), lines, parseResult);
parser.close();
}
|
#vulnerable code
private 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.parse(result, format);
final List<CSVRecord> parseResult = parser.getRecords();
Utils.compare("Printer output :" + printable(result), lines, parseResult);
}
#location 30
#vulnerability type RESOURCE_LEAK
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#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 = new CSVFormat(',').withEscape('/')
.withIgnoreEmptyLines(true).withLineSeparator(CRLF);
final CSVParser parser = new CSVParser(code, format);
final List<CSVRecord> records = parser.getRecords();
assertTrue(records.size() > 0);
Utils.compare("", res, records);
}
|
#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.PRISTINE.withDelimiter(',').withEscape('/')
.withIgnoreEmptyLines(true).withLineSeparator(CRLF);
final CSVParser parser = new CSVParser(code, format);
final List<CSVRecord> records = parser.getRecords();
assertTrue(records.size() > 0);
Utils.compare("", res, records);
}
#location 24
#vulnerability type RESOURCE_LEAK
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
public void testIterator() {
Reader in = new StringReader("a,b,c\n1,2,3\nx,y,z");
Iterator<String[]> iterator = CSVFormat.DEFAULT.parse(in).iterator();
assertTrue(iterator.hasNext());
iterator.remove();
assertTrue(Arrays.equals(new String[]{"a", "b", "c"}, iterator.next()));
assertTrue(Arrays.equals(new String[]{"1", "2", "3"}, iterator.next()));
assertTrue(iterator.hasNext());
assertTrue(iterator.hasNext());
assertTrue(iterator.hasNext());
assertTrue(Arrays.equals(new String[]{"x", "y", "z"}, iterator.next()));
assertFalse(iterator.hasNext());
try {
iterator.next();
fail("NoSuchElementException expected");
} catch (NoSuchElementException e) {
// expected
}
}
|
#vulnerable code
public void testIterator() {
String code = "a,b,c\n1,2,3\nx,y,z";
Iterator<String[]> iterator = new CSVParser(new StringReader(code)).iterator();
assertTrue(iterator.hasNext());
iterator.remove();
assertTrue(Arrays.equals(new String[]{"a", "b", "c"}, iterator.next()));
assertTrue(Arrays.equals(new String[]{"1", "2", "3"}, iterator.next()));
assertTrue(iterator.hasNext());
assertTrue(iterator.hasNext());
assertTrue(iterator.hasNext());
assertTrue(Arrays.equals(new String[]{"x", "y", "z"}, iterator.next()));
assertFalse(iterator.hasNext());
try {
iterator.next();
fail("NoSuchElementException expected");
} catch (NoSuchElementException e) {
// expected
}
}
#location 20
#vulnerability type RESOURCE_LEAK
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
@Test
public void testLineFeedEndings() throws IOException {
final String code = "foo\nbaar,\nhello,world\n,kanu";
final CSVParser parser = CSVParser.parse(code, CSVFormat.DEFAULT);
final List<CSVRecord> records = parser.getRecords();
assertEquals(4, records.size());
parser.close();
}
|
#vulnerable code
@Test
public void testLineFeedEndings() throws IOException {
final String code = "foo\nbaar,\nhello,world\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
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#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);
}
|
#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 3
#vulnerability type RESOURCE_LEAK
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
@Test
public void testEndOfFileBehaviourExcel() 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", ""},
{""}, // Excel format does not ignore empty lines
{"world", ""}
};
for (String code : codes) {
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()));
}
}
}
|
#vulnerable code
@Test
public void testEndOfFileBehaviourExcel() 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", ""},
{""}, // Excel format does not ignore empty lines
{"world", ""}
};
for (String code : codes) {
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 22
#vulnerability type NULL_DEREFERENCE
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
@Test
public void testCSV57() throws Exception {
final CSVParser parser = CSVParser.parse("", CSVFormat.DEFAULT);
final List<CSVRecord> list = parser.getRecords();
assertNotNull(list);
assertEquals(0, list.size());
}
|
#vulnerable code
@Test
public void testCSV57() throws Exception {
final CSVParser parser = CSVParser.parseString("", CSVFormat.DEFAULT);
final List<CSVRecord> list = parser.getRecords();
assertNotNull(list);
assertEquals(0, list.size());
}
#location 4
#vulnerability type RESOURCE_LEAK
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
@Test
public void testDefaultFormat() throws IOException {
final String code = ""
+ "a,b#\n" // 1)
+ "\"\n\",\" \",#\n" // 2)
+ "#,\"\"\n" // 3)
+ "# Final comment\n"// 4)
;
final String[][] res = {
{"a", "b#"},
{"\n", " ", "#"},
{"#", ""},
{"# Final comment"}
};
CSVFormat format = CSVFormat.DEFAULT;
assertFalse(format.isCommentingEnabled());
CSVParser parser = CSVParser.parse(code, format);
List<CSVRecord> records = parser.getRecords();
assertTrue(records.size() > 0);
Utils.compare("Failed to parse without comments", res, records);
final String[][] res_comments = {
{"a", "b#"},
{"\n", " ", "#"},
};
format = CSVFormat.DEFAULT.withCommentStart('#');
parser = CSVParser.parse(code, format);
records = parser.getRecords();
Utils.compare("Failed to parse with comments", res_comments, records);
}
|
#vulnerable code
@Test
public void testDefaultFormat() throws IOException {
final String code = ""
+ "a,b#\n" // 1)
+ "\"\n\",\" \",#\n" // 2)
+ "#,\"\"\n" // 3)
+ "# Final comment\n"// 4)
;
final String[][] res = {
{"a", "b#"},
{"\n", " ", "#"},
{"#", ""},
{"# Final comment"}
};
CSVFormat format = CSVFormat.DEFAULT;
assertFalse(format.isCommentingEnabled());
CSVParser parser = CSVParser.parseString(code, format);
List<CSVRecord> records = parser.getRecords();
assertTrue(records.size() > 0);
Utils.compare("Failed to parse without comments", res, records);
final String[][] res_comments = {
{"a", "b#"},
{"\n", " ", "#"},
};
format = CSVFormat.DEFAULT.withCommentStart('#');
parser = CSVParser.parseString(code, format);
records = parser.getRecords();
Utils.compare("Failed to parse with comments", res_comments, records);
}
#location 32
#vulnerability type RESOURCE_LEAK
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#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();
}
|
#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 17
#vulnerability type RESOURCE_LEAK
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#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());
}
|
#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
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
public void testReadLine() throws Exception {
ExtendedBufferedReader br = getBufferedReader("");
assertTrue(br.readLine() == null);
br = getBufferedReader("\n");
assertTrue(br.readLine().equals(""));
assertTrue(br.readLine() == null);
br = getBufferedReader("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 = getBufferedReader("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 = getBufferedReader("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);
}
|
#vulnerable 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);
}
#location 3
#vulnerability type RESOURCE_LEAK
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
@Test
public void testDisabledComment() throws IOException {
final StringWriter sw = new StringWriter();
final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.DEFAULT);
printer.printComment("This is a comment");
assertEquals("", sw.toString());
printer.close();
}
|
#vulnerable code
@Test
public void testDisabledComment() throws IOException {
final StringWriter sw = new StringWriter();
final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.DEFAULT);
printer.printComment("This is a comment");
assertEquals("", sw.toString());
}
#location 5
#vulnerability type RESOURCE_LEAK
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#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.parseString(code);
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());
}
}
|
#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 = new CSVParser(new StringReader(code));
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
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
@Test
public void testCarriageReturnEndings() throws IOException {
final String code = "foo\rbaar,\rhello,world\r,kanu";
final CSVParser parser = CSVParser.parse(code, CSVFormat.DEFAULT);
final List<CSVRecord> records = parser.getRecords();
assertEquals(4, records.size());
}
|
#vulnerable code
@Test
public void testCarriageReturnEndings() throws IOException {
final String code = "foo\rbaar,\rhello,world\r,kanu";
final CSVParser parser = CSVParser.parseString(code, CSVFormat.DEFAULT);
final List<CSVRecord> records = parser.getRecords();
assertEquals(4, records.size());
}
#location 5
#vulnerability type RESOURCE_LEAK
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
@Test
public void testBackslashEscaping() 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 =
"one,two,three\n" // 0
+ "'',''\n" // 1) empty encapsulators
+ "/',/'\n" // 2) single encapsulators
+ "'/'','/''\n" // 3) single encapsulators encapsulated via escape
+ "'''',''''\n" // 4) single encapsulators encapsulated via doubling
+ "/,,/,\n" // 5) separator escaped
+ "//,//\n" // 6) escape escaped
+ "'//','//'\n" // 7) escape escaped in encapsulation
+ " 8 , \"quoted \"\" /\" // string\" \n" // don't eat spaces
+ "9, /\n \n" // escaped newline
+ "";
String[][] res = {
{"one", "two", "three"}, // 0
{"", ""}, // 1
{"'", "'"}, // 2
{"'", "'"}, // 3
{"'", "'"}, // 4
{",", ","}, // 5
{"/", "/"}, // 6
{"/", "/"}, // 7
{" 8 ", " \"quoted \"\" \" / string\" "},
{"9", " \n "},
};
CSVFormat format = new CSVFormat(',', '\'', CSVFormat.DISABLED, '/', false, false, true, "\r\n", null);
CSVParser parser = new CSVParser(code, format);
List<CSVRecord> records = parser.getRecords();
assertTrue(records.size() > 0);
for (int i = 0; i < res.length; i++) {
assertTrue(Arrays.equals(res[i], records.get(i).values()));
}
}
|
#vulnerable code
@Test
public void testBackslashEscaping() 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 =
"one,two,three\n" // 0
+ "'',''\n" // 1) empty encapsulators
+ "/',/'\n" // 2) single encapsulators
+ "'/'','/''\n" // 3) single encapsulators encapsulated via escape
+ "'''',''''\n" // 4) single encapsulators encapsulated via doubling
+ "/,,/,\n" // 5) separator escaped
+ "//,//\n" // 6) escape escaped
+ "'//','//'\n" // 7) escape escaped in encapsulation
+ " 8 , \"quoted \"\" /\" // string\" \n" // don't eat spaces
+ "9, /\n \n" // escaped newline
+ "";
String[][] res = {
{"one", "two", "three"}, // 0
{"", ""}, // 1
{"'", "'"}, // 2
{"'", "'"}, // 3
{"'", "'"}, // 4
{",", ","}, // 5
{"/", "/"}, // 6
{"/", "/"}, // 7
{" 8 ", " \"quoted \"\" \" / string\" "},
{"9", " \n "},
};
CSVFormat format = new CSVFormat(',', '\'', CSVFormat.DISABLED, '/', false, false, true, true, "\r\n", null);
CSVParser parser = new CSVParser(code, format);
List<CSVRecord> records = parser.getRecords();
assertTrue(records.size() > 0);
for (int i = 0; i < res.length; i++) {
assertTrue(Arrays.equals(res[i], records.get(i).values()));
}
}
#location 37
#vulnerability type RESOURCE_LEAK
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed 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());
}
}
|
#vulnerable code
@Test
public void testGetRecords() throws IOException {
final CSVParser parser = new CSVParser(new StringReader(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
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#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.parseString(code);
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());
}
}
}
|
#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 = new CSVParser(new StringReader(code));
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
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
@Test
public void testExcelPrintAllArrayOfArrays() throws IOException {
final StringWriter sw = new StringWriter();
final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.EXCEL);
printer.printRecords(new String[][] { { "r1c1", "r1c2" }, { "r2c1", "r2c2" } });
assertEquals("r1c1,r1c2" + recordSeparator + "r2c1,r2c2" + recordSeparator, sw.toString());
printer.close();
}
|
#vulnerable code
@Test
public void testExcelPrintAllArrayOfArrays() throws IOException {
final StringWriter sw = new StringWriter();
final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.EXCEL);
printer.printRecords(new String[][] { { "r1c1", "r1c2" }, { "r2c1", "r2c2" } });
assertEquals("r1c1,r1c2" + recordSeparator + "r2c1,r2c2" + recordSeparator, sw.toString());
}
#location 5
#vulnerability type RESOURCE_LEAK
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
@Test
public void testQuoteNonNumeric() throws IOException {
final StringWriter sw = new StringWriter();
final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.newBuilder().withQuotePolicy(Quote.NON_NUMERIC).build());
printer.printRecord("a", "b\nc", Integer.valueOf(1));
assertEquals("\"a\",\"b\nc\",1" + recordSeparator, sw.toString());
printer.close();
}
|
#vulnerable code
@Test
public void testQuoteNonNumeric() throws IOException {
final StringWriter sw = new StringWriter();
final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.newBuilder().withQuotePolicy(Quote.NON_NUMERIC).build());
printer.printRecord("a", "b\nc", Integer.valueOf(1));
assertEquals("\"a\",\"b\nc\",1" + recordSeparator, sw.toString());
}
#location 5
#vulnerability type RESOURCE_LEAK
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
public void testReadLookahead1() throws Exception {
ExtendedBufferedReader br = getBufferedReader("1\n2\r3\n");
assertEquals('1', br.lookAhead());
assertEquals(ExtendedBufferedReader.UNDEFINED, br.readAgain());
assertEquals('1', br.read());
assertEquals('1', br.readAgain());
assertEquals(0, br.getLineNumber());
assertEquals('\n', br.lookAhead());
assertEquals(0, br.getLineNumber());
assertEquals('1', br.readAgain());
assertEquals('\n', br.read());
assertEquals(1, br.getLineNumber());
assertEquals('\n', br.readAgain());
assertEquals(1, br.getLineNumber());
assertEquals('2', br.lookAhead());
assertEquals(1, br.getLineNumber());
assertEquals('\n', br.readAgain());
assertEquals(1, br.getLineNumber());
assertEquals('2', br.read());
assertEquals('2', br.readAgain());
assertEquals('\r', br.lookAhead());
assertEquals('2', br.readAgain());
assertEquals('\r', br.read());
assertEquals('\r', br.readAgain());
assertEquals('3', br.lookAhead());
assertEquals('\r', br.readAgain());
assertEquals('3', br.read());
assertEquals('3', br.readAgain());
assertEquals('\n', br.lookAhead());
assertEquals(1, br.getLineNumber());
assertEquals('3', br.readAgain());
assertEquals('\n', br.read());
assertEquals(2, br.getLineNumber());
assertEquals('\n', br.readAgain());
assertEquals(2, br.getLineNumber());
assertEquals(ExtendedBufferedReader.END_OF_STREAM, br.lookAhead());
assertEquals('\n', br.readAgain());
assertEquals(ExtendedBufferedReader.END_OF_STREAM, br.read());
assertEquals(ExtendedBufferedReader.END_OF_STREAM, br.readAgain());
assertEquals(ExtendedBufferedReader.END_OF_STREAM, br.read());
assertEquals(ExtendedBufferedReader.END_OF_STREAM, br.lookAhead());
}
|
#vulnerable code
public void testReadLookahead1() throws Exception {
assertEquals(ExtendedBufferedReader.END_OF_STREAM, getEBR("").read());
ExtendedBufferedReader br = getEBR("1\n2\r3\n");
assertEquals('1', br.lookAhead());
assertEquals(ExtendedBufferedReader.UNDEFINED, br.readAgain());
assertEquals('1', br.read());
assertEquals('1', br.readAgain());
assertEquals(0, br.getLineNumber());
assertEquals('\n', br.lookAhead());
assertEquals(0, br.getLineNumber());
assertEquals('1', br.readAgain());
assertEquals('\n', br.read());
assertEquals(1, br.getLineNumber());
assertEquals('\n', br.readAgain());
assertEquals(1, br.getLineNumber());
assertEquals('2', br.lookAhead());
assertEquals(1, br.getLineNumber());
assertEquals('\n', br.readAgain());
assertEquals(1, br.getLineNumber());
assertEquals('2', br.read());
assertEquals('2', br.readAgain());
assertEquals('\r', br.lookAhead());
assertEquals('2', br.readAgain());
assertEquals('\r', br.read());
assertEquals('\r', br.readAgain());
assertEquals('3', br.lookAhead());
assertEquals('\r', br.readAgain());
assertEquals('3', br.read());
assertEquals('3', br.readAgain());
assertEquals('\n', br.lookAhead());
assertEquals(1, br.getLineNumber());
assertEquals('3', br.readAgain());
assertEquals('\n', br.read());
assertEquals(2, br.getLineNumber());
assertEquals('\n', br.readAgain());
assertEquals(2, br.getLineNumber());
assertEquals(ExtendedBufferedReader.END_OF_STREAM, br.lookAhead());
assertEquals('\n', br.readAgain());
assertEquals(ExtendedBufferedReader.END_OF_STREAM, br.read());
assertEquals(ExtendedBufferedReader.END_OF_STREAM, br.readAgain());
assertEquals(ExtendedBufferedReader.END_OF_STREAM, br.read());
assertEquals(ExtendedBufferedReader.END_OF_STREAM, br.lookAhead());
}
#location 3
#vulnerability type RESOURCE_LEAK
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
public void testSkipUntil() throws Exception {
ExtendedBufferedReader br = getEBR("");
assertEquals(0, br.skipUntil(';'));
br = getEBR("ABCDEF,GHL,,MN");
assertEquals(6, br.skipUntil(','));
assertEquals(0, br.skipUntil(','));
br.skip(1);
assertEquals(3, br.skipUntil(','));
br.skip(1);
assertEquals(0, br.skipUntil(','));
br.skip(1);
assertEquals(2, br.skipUntil(','));
}
|
#vulnerable code
public void testSkipUntil() throws Exception {
br = getEBR("");
assertEquals(0, br.skipUntil(';'));
br = getEBR("ABCDEF,GHL,,MN");
assertEquals(6, br.skipUntil(','));
assertEquals(0, br.skipUntil(','));
br.skip(1);
assertEquals(3, br.skipUntil(','));
br.skip(1);
assertEquals(0, br.skipUntil(','));
br.skip(1);
assertEquals(2, br.skipUntil(','));
}
#location 4
#vulnerability type RESOURCE_LEAK
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
@Test
public void 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());
}
parser.close();
}
|
#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.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 14
#vulnerability type RESOURCE_LEAK
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
@Test
public void testPrintNullValues() throws IOException {
final StringWriter sw = new StringWriter();
final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.DEFAULT);
printer.printRecord("a", null, "b");
assertEquals("a,,b" + recordSeparator, sw.toString());
printer.close();
}
|
#vulnerable code
@Test
public void testPrintNullValues() throws IOException {
final StringWriter sw = new StringWriter();
final CSVPrinter printer = new CSVPrinter(sw, CSVFormat.DEFAULT);
printer.printRecord("a", null, "b");
assertEquals("a,,b" + recordSeparator, sw.toString());
}
#location 5
#vulnerability type RESOURCE_LEAK
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
@Test
public void 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());
}
|
#vulnerable code
@Test
public void testCarriageReturnLineFeedEndings() throws IOException {
final String code = "foo\r\nbaar,\r\nhello,world\r\n,kanu";
final CSVParser parser = CSVParser.parseString(code, CSVFormat.DEFAULT);
final List<CSVRecord> records = parser.getRecords();
assertEquals(4, records.size());
}
#location 5
#vulnerability type RESOURCE_LEAK
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
@Test
public void testDefaultFormat() throws IOException {
final String code = ""
+ "a,b#\n" // 1)
+ "\"\n\",\" \",#\n" // 2)
+ "#,\"\"\n" // 3)
+ "# Final comment\n"// 4)
;
final String[][] res = {
{"a", "b#"},
{"\n", " ", "#"},
{"#", ""},
{"# Final comment"}
};
CSVFormat format = CSVFormat.DEFAULT;
assertFalse(format.isCommentingEnabled());
CSVParser parser = CSVParser.parse(code, format);
List<CSVRecord> records = parser.getRecords();
assertTrue(records.size() > 0);
Utils.compare("Failed to parse without comments", res, records);
final String[][] res_comments = {
{"a", "b#"},
{"\n", " ", "#"},
};
format = CSVFormat.DEFAULT.withCommentStart('#');
parser.close();
parser = CSVParser.parse(code, format);
records = parser.getRecords();
Utils.compare("Failed to parse with comments", res_comments, records);
parser.close();
}
|
#vulnerable code
@Test
public void testDefaultFormat() throws IOException {
final String code = ""
+ "a,b#\n" // 1)
+ "\"\n\",\" \",#\n" // 2)
+ "#,\"\"\n" // 3)
+ "# Final comment\n"// 4)
;
final String[][] res = {
{"a", "b#"},
{"\n", " ", "#"},
{"#", ""},
{"# Final comment"}
};
CSVFormat format = CSVFormat.DEFAULT;
assertFalse(format.isCommentingEnabled());
CSVParser parser = CSVParser.parse(code, format);
List<CSVRecord> records = parser.getRecords();
assertTrue(records.size() > 0);
Utils.compare("Failed to parse without comments", res, records);
final String[][] res_comments = {
{"a", "b#"},
{"\n", " ", "#"},
};
format = CSVFormat.DEFAULT.withCommentStart('#');
parser = CSVParser.parse(code, format);
records = parser.getRecords();
Utils.compare("Failed to parse with comments", res_comments, records);
}
#location 20
#vulnerability type RESOURCE_LEAK
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#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++;
}
|
#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
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#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()));
}
|
#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
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#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());
}
|
#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
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#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);
}
|
#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
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#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);
}
|
#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
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#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();
}
|
#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
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#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();
}
|
#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
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#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();
}
|
#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
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#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();
}
|
#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
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#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()));
}
|
#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
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#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();
}
}
|
#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
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#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));
}
|
#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
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#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();
}
|
#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
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#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();
}
|
#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
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#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()));
}
}
|
#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
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#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();
}
|
#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
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#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());
}
|
#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
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#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);
}
|
#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
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#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());
}
|
#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
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#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();
}
}
|
#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
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#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();
}
}
}
|
#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
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#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();
}
}
}
|
#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
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#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());
}
|
#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
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#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);
}
|
#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
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#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);
}
|
#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
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#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;
}
|
#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
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#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;
}
|
#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
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#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);
}
}
}
|
#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
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#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");
}
|
#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
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#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();
}
|
#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
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#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;
}
|
#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
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#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;
}
|
#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
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#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);
}
}
|
#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
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#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;
}
}
|
#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
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#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;
}
|
#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
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
public Map<String, Object> map() {
// return map;
return maps.get();
}
|
#vulnerable code
public Map<String, Object> map() {
return map;
}
#location 2
#vulnerability type THREAD_SAFETY_VIOLATION
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#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;
}
|
#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
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#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);
}
}
}
|
#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
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#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;
}
|
#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
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
public long getValue() {
return value.get();
}
|
#vulnerable code
public long getValue() {
return value;
}
#location 2
#vulnerability type THREAD_SAFETY_VIOLATION
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#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();
}
}
|
#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
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#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();
}
|
#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
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#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;
}
}
|
#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
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#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();
}
|
#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
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
public boolean within(Date date, String lower, String upper) throws ParseException {
LOGGER.debug("within({},{},{})", date, lower, upper);
Date lowerDate = date(lower);
Date upperDate = date(upper);
boolean result = date != null && date.getTime() >= lowerDate.getTime() && date.getTime() <= upperDate.getTime();
LOGGER.debug("within({},{},{})={}", date, lower, upper, result);
return result;
}
|
#vulnerable code
public boolean within(Date date, String lower, String upper) throws ParseException {
Date lowerDate = date(lower);
Date upperDate = date(upper);
return date != null && date.getTime() >= lowerDate.getTime() && date.getTime() <= upperDate.getTime();
}
#location 4
#vulnerability type NULL_DEREFERENCE
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
public static void main(String[] args) throws Exception {
ApplicationContext appContext = ApplicationContextFactory.getContext();
Main main = appContext.getBean("main", Main.class);
if (!main.procesPreLoadOptions(args)) {
LOGGER.debug("Exiting");
return;
}
main.loadData();
main.processPostLoadOptions(args);
main.run();
LOGGER.debug("Exiting");
}
|
#vulnerable code
public static void main(String[] args) throws Exception {
ApplicationContext appContext = ApplicationContextFactory.create();
Main main = appContext.getBean("main", Main.class);
if (!main.procesPreLoadOptions(args)) {
LOGGER.debug("Exiting");
return;
}
main.loadData();
main.processPostLoadOptions(args);
main.run();
LOGGER.debug("Exiting");
}
#location 5
#vulnerability type RESOURCE_LEAK
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
private void writeToLog(String type, String content) {
writerThread.execute(()->{
String t = ServerTimeUtil.accurateToLogName();
File f = new File(logs, t + ".klog");
FileWriter fw = null;
if (f.exists()) {
try {
fw = new FileWriter(f, true);
fw.write("\r\n\r\nTIME:\r\n" + ServerTimeUtil.accurateToSecond() + "\r\nTYPE:\r\n" + type
+ "\r\nCONTENT:\r\n" + content);
fw.close();
} catch (Exception e1) {
if (Printer.instance != null) {
Printer.instance.print("KohgylwIFT:[Log]Cannt write to file,message:" + e1.getMessage());
} else {
System.out.println("KohgylwIFT:[Log]Cannt write to file,message:" + e1.getMessage());
}
}
} else {
try {
fw = new FileWriter(f, false);
fw.write("TIME:\r\n" + ServerTimeUtil.accurateToSecond() + "\r\nTYPE:\r\n" + type + "\r\nCONTENT:\r\n"
+ content);
fw.close();
} catch (IOException e1) {
if (Printer.instance != null) {
Printer.instance.print("KohgylwIFT:[Log]Cannt write to file,message:" + e1.getMessage());
} else {
System.out.println("KohgylwIFT:[Log]Cannt write to file,message:" + e1.getMessage());
}
}
}
});
}
|
#vulnerable code
private void writeToLog(String type, String content) {
String t = ServerTimeUtil.accurateToLogName();
File f = new File(logs, t + ".klog");
FileWriter fw = null;
if (f.exists()) {
try {
fw = new FileWriter(f, true);
fw.write("\r\n\r\nTIME:\r\n" + ServerTimeUtil.accurateToSecond() + "\r\nTYPE:\r\n" + type
+ "\r\nCONTENT:\r\n" + content);
fw.close();
} catch (Exception e1) {
System.out.println("KohgylwIFT:[Log]Cannt write to file,message:" + e1.getMessage());
}
} else {
try {
fw = new FileWriter(f, false);
fw.write("TIME:\r\n" + ServerTimeUtil.accurateToSecond() + "\r\nTYPE:\r\n" + type + "\r\nCONTENT:\r\n"
+ content);
fw.close();
} catch (IOException e1) {
System.out.println("KohgylwIFT:[Log]Cannt write to file,message:" + e1.getMessage());
}
}
}
#location 20
#vulnerability type RESOURCE_LEAK
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
private void getFolderView(String folderId) throws Exception {
try {
currentView = FileSystemManager.getInstance().getFolderView(folderId);
if(currentView!=null && currentView.getCurrent()!=null) {
filesTable.updateValues(currentView.getFolders(), currentView.getFiles());
window.setTitle("kiftd-" + currentView.getCurrent().getFolderName());
}else {
//浏览一个不存在的文件夹时自动返回根目录
getFolderView("root");
}
} catch (Exception e) {
throw e;
}
}
|
#vulnerable code
private void getFolderView(String folderId) throws Exception {
try {
currentView = FileSystemManager.getInstance().getFolderView(folderId);
filesTable.updateValues(currentView.getFolders(), currentView.getFiles());
window.setTitle("kiftd-" + currentView.getCurrent().getFolderName());
} catch (Exception e) {
throw e;
}
}
#location 5
#vulnerability type NULL_DEREFERENCE
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
public void doDownloadFile(final HttpServletRequest request, final HttpServletResponse response) {
final String account = (String) request.getSession().getAttribute("ACCOUNT");
if (ConfigureReader.instance().authorized(account, AccountAuth.DOWNLOAD_FILES)) {
final String fileId = request.getParameter("fileId");
if (fileId != null) {
final Node f = this.fm.queryById(fileId);
if (f != null) {
final String fileBlocks = ConfigureReader.instance().getFileBlockPath();
final File fo = this.fbu.getFileFromBlocks(fileBlocks, f.getFilePath());
downloadRangeFile(request, response, fo, f.getFileName());// 使用断点续传执行下载
this.lu.writeDownloadFileEvent(request, f);
}
}
}
}
|
#vulnerable code
public void doDownloadFile(final HttpServletRequest request, final HttpServletResponse response) {
final String account = (String) request.getSession().getAttribute("ACCOUNT");
if (ConfigureReader.instance().authorized(account, AccountAuth.DOWNLOAD_FILES)) {
final String fileId = request.getParameter("fileId");
if (fileId != null) {
final Node f = this.fm.queryById(fileId);
if (f != null) {
final String fileBlocks = ConfigureReader.instance().getFileBlockPath();
final File fo = this.fbu.getFileFromBlocks(fileBlocks, f.getFilePath());
try {
final FileInputStream fis = new FileInputStream(fo);
response.setContentType("application/force-download");
response.setHeader("Content-Length", "" + fo.length());
response.addHeader("Content-Disposition",
"attachment;fileName=" + URLEncoder.encode(f.getFileName(), "UTF-8"));
final int buffersize = ConfigureReader.instance().getBuffSize();
final byte[] buffer = new byte[buffersize];
final BufferedInputStream bis = new BufferedInputStream(fis);
final OutputStream os = (OutputStream) response.getOutputStream();
int index = 0;
while ((index = bis.read(buffer)) != -1) {
os.write(buffer, 0, index);
}
bis.close();
fis.close();
this.lu.writeDownloadFileEvent(request, f);
} catch (Exception ex) {
}
}
}
}
}
#location 13
#vulnerability type NULL_DEREFERENCE
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
public String doUploadFile(final HttpServletRequest request, final HttpServletResponse response,
final MultipartFile file) {
String account = (String) request.getSession().getAttribute("ACCOUNT");
final String folderId = request.getParameter("folderId");
final String fname = request.getParameter("fname");
final String originalFileName = fname != null ? fname : file.getOriginalFilename();
String fileName = originalFileName;
final String repeType = request.getParameter("repeType");
// 再次检查上传文件名与目标目录ID
if (folderId == null || folderId.length() <= 0 || originalFileName == null || originalFileName.length() <= 0) {
return UPLOADERROR;
}
Folder folder = flm.queryById(folderId);
if (folder == null) {
return UPLOADERROR;
}
// 检查上传权限
if (!ConfigureReader.instance().authorized(account, AccountAuth.UPLOAD_FILES, fu.getAllFoldersId(folderId))
|| !ConfigureReader.instance().accessFolder(folder, account)) {
return UPLOADERROR;
}
// 检查上传文件体积是否超限
long mufs = ConfigureReader.instance().getUploadFileSize(account);
if (mufs >= 0 && file.getSize() > mufs) {
return UPLOADERROR;
}
// 检查是否存在同名文件。不存在:直接存入新节点;存在:检查repeType代表的上传类型:覆盖、跳过、保留两者。
final List<Node> nodes = this.fm.queryByParentFolderId(folderId);
if (nodes.parallelStream().anyMatch((e) -> e.getFileName().equals(originalFileName))) {
// 针对存在同名文件的操作
if (repeType != null) {
switch (repeType) {
// 跳过则忽略上传请求并直接返回上传成功(跳过不应上传)
case "skip":
return UPLOADSUCCESS;
// 如果要覆盖的文件不存在与其他节点共享文件块的情况,则找到该文件块并将新内容写入其中,同时更新原节点信息(除了文件名、父目录和ID之外的全部信息)。
// 如果要覆盖的文件是某个文件块的众多副本之一,那么“覆盖”就是新存入一个文件块,然后再更新原节点信息(除了文件名、父目录和ID之外的全部信息)。
case "cover":
// 特殊操作权限检查,“覆盖”操作同时还要求用户必须具备删除权限,否则不能执行
if (!ConfigureReader.instance().authorized(account, AccountAuth.DELETE_FILE_OR_FOLDER,
fu.getAllFoldersId(folderId))) {
return UPLOADERROR;
}
for (Node f : nodes) {
// 找到要覆盖的节点
if (f.getFileName().equals(originalFileName)) {
try {
// 首先先将该节点中必须覆盖的信息更新
f.setFileSize(fbu.getFileSize(file));
f.setFileCreationDate(ServerTimeUtil.accurateToDay());
if (account != null) {
f.setFileCreator(account);
} else {
f.setFileCreator("\u533f\u540d\u7528\u6237");
}
// 该节点对应的文件块是否独享?
Map<String, String> map = new HashMap<>();
map.put("path", f.getFilePath());
map.put("fileId", f.getFileId());
List<Node> nodesHasSomeBlock = fm.queryByPathExcludeById(map);
if (nodesHasSomeBlock == null || nodesHasSomeBlock.isEmpty()) {
// 如果该节点的文件块仅由该节点引用,那么直接重写此文件块
if (fm.update(f) > 0) {
if (fbu.isValidNode(f)) {
File block = fbu.getFileFromBlocks(f);
file.transferTo(block);
this.lu.writeUploadFileEvent(request, f, account);
return UPLOADSUCCESS;
}
}
} else {
// 如果此文件块还被其他节点引用,那么为此节点新建一个文件块
File block = fbu.saveToFileBlocks(file);
// 并将该节点的文件块索引更新为新的文件块
f.setFilePath(block.getName());
if (fm.update(f) > 0) {
if (fbu.isValidNode(f)) {
this.lu.writeUploadFileEvent(request, f, account);
return UPLOADSUCCESS;
} else {
block.delete();
}
}
}
return UPLOADERROR;
} catch (Exception e) {
return UPLOADERROR;
}
}
}
return UPLOADERROR;
// 保留两者,使用型如“xxxxx (n).xx”的形式命名新文件。其中n为计数,例如已经存在2个文件,则新文件的n记为2
case "both":
// 设置新文件名为标号形式
fileName = FileNodeUtil.getNewNodeName(originalFileName, nodes);
break;
default:
// 其他声明,容错,暂无效果
return UPLOADERROR;
}
} else {
// 如果既有重复文件、同时又没声明如何操作,则直接上传失败。
return UPLOADERROR;
}
}
// 判断该文件夹内的文件数量是否超限
if (fm.countByParentFolderId(folderId) >= FileNodeUtil.MAXIMUM_NUM_OF_SINGLE_FOLDER) {
return FILES_TOTAL_OUT_OF_LIMIT;
}
// 将文件存入节点并获取其存入生成路径,型如“UUID.block”形式。
final File block = this.fbu.saveToFileBlocks(file);
if (block == null) {
return UPLOADERROR;
}
final String fsize = this.fbu.getFileSize(file);
Node newNode = fbu.insertNewNode(fileName, account, block.getName(), fsize, folderId);
if (newNode != null) {
// 存入成功,则写入日志并返回成功提示
this.lu.writeUploadFileEvent(request, newNode, account);
return UPLOADSUCCESS;
} else {
// 存入失败则删除残余文件块,并返回失败提示
block.delete();
return UPLOADERROR;
}
}
|
#vulnerable code
public String doUploadFile(final HttpServletRequest request, final HttpServletResponse response,
final MultipartFile file) {
String account = (String) request.getSession().getAttribute("ACCOUNT");
final String folderId = request.getParameter("folderId");
final String originalFileName = new String(file.getOriginalFilename().getBytes(Charset.forName("UTF-8")),
Charset.forName("UTF-8"));
String fileName = originalFileName;
final String repeType = request.getParameter("repeType");
// 再次检查上传文件名与目标目录ID
if (folderId == null || folderId.length() <= 0 || originalFileName == null || originalFileName.length() <= 0) {
return UPLOADERROR;
}
Folder folder = flm.queryById(folderId);
if (folder == null) {
return UPLOADERROR;
}
// 检查上传权限
if (!ConfigureReader.instance().authorized(account, AccountAuth.UPLOAD_FILES, fu.getAllFoldersId(folderId))
|| !ConfigureReader.instance().accessFolder(folder, account)) {
return UPLOADERROR;
}
// 检查上传文件体积是否超限
long mufs = ConfigureReader.instance().getUploadFileSize(account);
if (mufs >= 0 && file.getSize() > mufs) {
return UPLOADERROR;
}
// 检查是否存在同名文件。不存在:直接存入新节点;存在:检查repeType代表的上传类型:覆盖、跳过、保留两者。
final List<Node> nodes = this.fm.queryByParentFolderId(folderId);
if (nodes.parallelStream().anyMatch((e) -> e.getFileName().equals(originalFileName))) {
// 针对存在同名文件的操作
if (repeType != null) {
switch (repeType) {
// 跳过则忽略上传请求并直接返回上传成功(跳过不应上传)
case "skip":
return UPLOADSUCCESS;
// 如果要覆盖的文件不存在与其他节点共享文件块的情况,则找到该文件块并将新内容写入其中,同时更新原节点信息(除了文件名、父目录和ID之外的全部信息)。
// 如果要覆盖的文件是某个文件块的众多副本之一,那么“覆盖”就是新存入一个文件块,然后再更新原节点信息(除了文件名、父目录和ID之外的全部信息)。
case "cover":
// 特殊操作权限检查,“覆盖”操作同时还要求用户必须具备删除权限,否则不能执行
if (!ConfigureReader.instance().authorized(account, AccountAuth.DELETE_FILE_OR_FOLDER,
fu.getAllFoldersId(folderId))) {
return UPLOADERROR;
}
for (Node f : nodes) {
// 找到要覆盖的节点
if (f.getFileName().equals(originalFileName)) {
try {
// 首先先将该节点中必须覆盖的信息更新
f.setFileSize(fbu.getFileSize(file));
f.setFileCreationDate(ServerTimeUtil.accurateToDay());
if (account != null) {
f.setFileCreator(account);
} else {
f.setFileCreator("\u533f\u540d\u7528\u6237");
}
// 该节点对应的文件块是否独享?
Map<String, String> map = new HashMap<>();
map.put("path", f.getFilePath());
map.put("fileId", f.getFileId());
List<Node> nodesHasSomeBlock = fm.queryByPathExcludeById(map);
if (nodesHasSomeBlock == null || nodesHasSomeBlock.isEmpty()) {
// 如果该节点的文件块仅由该节点引用,那么直接重写此文件块
if (fm.update(f) > 0) {
if (fbu.isValidNode(f)) {
File block = fbu.getFileFromBlocks(f);
file.transferTo(block);
this.lu.writeUploadFileEvent(request, f, account);
return UPLOADSUCCESS;
}
}
} else {
// 如果此文件块还被其他节点引用,那么为此节点新建一个文件块
File block = fbu.saveToFileBlocks(file);
// 并将该节点的文件块索引更新为新的文件块
f.setFilePath(block.getName());
if (fm.update(f) > 0) {
if (fbu.isValidNode(f)) {
this.lu.writeUploadFileEvent(request, f, account);
return UPLOADSUCCESS;
} else {
block.delete();
}
}
}
return UPLOADERROR;
} catch (Exception e) {
return UPLOADERROR;
}
}
}
return UPLOADERROR;
// 保留两者,使用型如“xxxxx (n).xx”的形式命名新文件。其中n为计数,例如已经存在2个文件,则新文件的n记为2
case "both":
// 设置新文件名为标号形式
fileName = FileNodeUtil.getNewNodeName(originalFileName, nodes);
break;
default:
// 其他声明,容错,暂无效果
return UPLOADERROR;
}
} else {
// 如果既有重复文件、同时又没声明如何操作,则直接上传失败。
return UPLOADERROR;
}
}
// 判断该文件夹内的文件数量是否超限
if (fm.countByParentFolderId(folderId) >= FileNodeUtil.MAXIMUM_NUM_OF_SINGLE_FOLDER) {
return FILES_TOTAL_OUT_OF_LIMIT;
}
// 将文件存入节点并获取其存入生成路径,型如“UUID.block”形式。
final File block = this.fbu.saveToFileBlocks(file);
if (block == null) {
return UPLOADERROR;
}
final String fsize = this.fbu.getFileSize(file);
Node newNode = fbu.insertNewNode(fileName, account, block.getName(), fsize, folderId);
if (newNode != null) {
// 存入成功,则写入日志并返回成功提示
this.lu.writeUploadFileEvent(request, newNode, account);
return UPLOADSUCCESS;
} else {
// 存入失败则删除残余文件块,并返回失败提示
block.delete();
return UPLOADERROR;
}
}
#location 5
#vulnerability type NULL_DEREFERENCE
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
@Override
public void getCondensedPicture(final HttpServletRequest request, final HttpServletResponse response) {
// TODO 自动生成的方法存根
if (ConfigureReader.instance().authorized((String) request.getSession().getAttribute("ACCOUNT"),
AccountAuth.DOWNLOAD_FILES)) {
String fileId = request.getParameter("fileId");
if (fileId != null) {
Node node = fm.queryById(fileId);
if (node != null) {
File pBlock = fbu.getFileFromBlocks(node);
if (pBlock != null && pBlock.exists()) {
try {
int pSize = Integer.parseInt(node.getFileSize());
if (pSize < 3) {
Thumbnails.of(pBlock).size(1024, 1024).outputFormat("JPG")
.toOutputStream(response.getOutputStream());
} else if (pSize < 5) {
Thumbnails.of(pBlock).size(1440, 1440).outputFormat("JPG")
.toOutputStream(response.getOutputStream());
} else {
Thumbnails.of(pBlock).size(1680, 1680).outputFormat("JPG")
.toOutputStream(response.getOutputStream());
}
} catch (IOException e) {
// TODO 自动生成的 catch 块
// 压缩失败时,尝试以源文件进行预览
try {
Files.copy(pBlock.toPath(), response.getOutputStream());
} catch (IOException e1) {
// TODO 自动生成的 catch 块
}
}
}
}
}
}
}
|
#vulnerable code
@Override
public void getCondensedPicture(final HttpServletRequest request, final HttpServletResponse response) {
// TODO 自动生成的方法存根
if (ConfigureReader.instance().authorized((String) request.getSession().getAttribute("ACCOUNT"),
AccountAuth.DOWNLOAD_FILES)) {
String fileId = request.getParameter("fileId");
if (fileId != null) {
Node node = fm.queryById(fileId);
if (node != null) {
File pBlock = fbu.getFileFromBlocks(node);
if (pBlock.exists()) {
try {
int pSize = Integer.parseInt(node.getFileSize());
if (pSize < 3) {
Thumbnails.of(pBlock).size(1024, 1024).outputFormat("JPG")
.toOutputStream(response.getOutputStream());
} else if (pSize < 5) {
Thumbnails.of(pBlock).size(1440, 1440).outputFormat("JPG")
.toOutputStream(response.getOutputStream());
} else {
Thumbnails.of(pBlock).size(1680, 1680).outputFormat("JPG")
.toOutputStream(response.getOutputStream());
}
} catch (IOException e) {
// TODO 自动生成的 catch 块
// 压缩失败时,尝试以源文件进行预览
try {
Files.copy(pBlock.toPath(), response.getOutputStream());
} catch (IOException e1) {
// TODO 自动生成的 catch 块
}
}
}
}
}
}
}
#location 11
#vulnerability type NULL_DEREFERENCE
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
@Override
public String checkImportFolder(HttpServletRequest request) {
final String account = (String) request.getSession().getAttribute("ACCOUNT");
final String folderId = request.getParameter("folderId");
final String folderName = request.getParameter("folderName");
final String maxUploadFileSize = request.getParameter("maxSize");
CheckImportFolderRespons cifr = new CheckImportFolderRespons();
// 先行权限检查
if (!ConfigureReader.instance().authorized(account, AccountAuth.UPLOAD_FILES)) {
cifr.setResult(NO_AUTHORIZED);
return gson.toJson(cifr);
}
// 开始文件上传体积限制检查
try {
// 获取最大文件体积(以Byte为单位)
long mufs = Long.parseLong(maxUploadFileSize);
long pMaxUploadSize = ConfigureReader.instance().getUploadFileSize(account);
if (pMaxUploadSize >= 0) {
if (mufs > pMaxUploadSize) {
cifr.setResult("fileOverSize");
cifr.setMaxSize(formatMaxUploadFileSize(ConfigureReader.instance().getUploadFileSize(account)));
return gson.toJson(cifr);
}
}
} catch (Exception e) {
cifr.setResult(ERROR_PARAMETER);
return gson.toJson(cifr);
}
// 开始文件夹命名冲突检查,若无重名则允许上传。
final List<Folder> folders = flm.queryByParentId(folderId);
try {
folders.stream().parallel()
.filter((n) -> n.getFolderName().equals(
new String(folderName.getBytes(Charset.forName("UTF-8")), Charset.forName("UTF-8"))))
.findAny().get();
cifr.setResult("repeatFolder");
return gson.toJson(cifr);
} catch (NoSuchElementException e) {
// 通过所有检查,允许上传
cifr.setResult("permitUpload");
return gson.toJson(cifr);
}
}
|
#vulnerable code
@Override
public String checkImportFolder(HttpServletRequest request) {
final String account = (String) request.getSession().getAttribute("ACCOUNT");
final String folderId = request.getParameter("folderId");
final String folderName = request.getParameter("folderName");
final String maxUploadFileSize = request.getParameter("maxSize");
CheckImportFolderRespons cifr = new CheckImportFolderRespons();
// 先行权限检查
if (!ConfigureReader.instance().authorized(account, AccountAuth.UPLOAD_FILES)) {
cifr.setResult(NO_AUTHORIZED);
return gson.toJson(cifr);
}
// 开始文件上传体积限制检查
try {
// 获取最大文件体积(以Byte为单位)
long mufs = Long.parseLong(maxUploadFileSize);
long pMaxUploadSize = ConfigureReader.instance().getUploadFileSize(account);
if (pMaxUploadSize >= 0) {
if (mufs > pMaxUploadSize) {
cifr.setResult("fileOverSize");
cifr.setMaxSize(formatMaxUploadFileSize(ConfigureReader.instance().getUploadFileSize(account)));
return gson.toJson(cifr);
}
}
} catch (Exception e) {
cifr.setResult(ERROR_PARAMETER);
return gson.toJson(cifr);
}
// 开始文件夹命名冲突检查,若无重名则允许上传。
final List<Folder> folders = flm.queryByParentId(folderId);
try {
Folder testfolder = folders.stream().parallel()
.filter((n) -> n.getFolderName().equals(
new String(folderName.getBytes(Charset.forName("UTF-8")), Charset.forName("UTF-8"))))
.findAny().get();
// 若有重名,则判定该用户是否具备删除权限,这是能够覆盖的第一步
if (ConfigureReader.instance().authorized(account, AccountAuth.DELETE_FILE_OR_FOLDER)) {
// 接下来判断其是否具备冲突文件夹的访问权限,这是能够覆盖的第二步
if (ConfigureReader.instance().accessFolder(testfolder, account)) {
cifr.setResult("coverOrBoth");
return gson.toJson(cifr);
}
}
// 如果上述条件不满足,则只能允许保留两者
cifr.setResult("onlyBoth");
return gson.toJson(cifr);
} catch (NoSuchElementException e) {
// 通过所有检查,允许上传
cifr.setResult("permitUpload");
return gson.toJson(cifr);
}
}
#location 39
#vulnerability type THREAD_SAFETY_VIOLATION
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
public boolean removeAddedAuthByFolderId(List<String> fIds) {
if (fIds == null || fIds.size() == 0) {
return false;
}
Set<String> configs = accountp.stringPropertieNames();
List<String> invalidConfigs = new ArrayList<>();
for (String fId : fIds) {
for (String config : configs) {
if (config.endsWith(".auth." + fId)) {
invalidConfigs.add(config);
}
}
}
for (String config : invalidConfigs) {
accountp.removeProperty(config);
}
try (FileOutputStream accountSettingOut = new FileOutputStream(this.confdir + ACCOUNT_PROPERTIES_FILE)) {
FileLock lock = accountSettingOut.getChannel().lock();
accountp.store(accountSettingOut, null);
lock.release();
return true;
} catch (Exception e) {
Printer.instance.print("错误:更新账户配置文件时出现错误,请立即检查账户配置文件。");
return false;
}
}
|
#vulnerable code
public boolean removeAddedAuthByFolderId(List<String> fIds) {
if(fIds == null || fIds.size() == 0) {
return false;
}
Set<String> configs=accountp.stringPropertieNames();
List<String> invalidConfigs = new ArrayList<>();
for(String fId:fIds) {
for (String config:configs) {
if(config.endsWith(".auth."+fId)) {
invalidConfigs.add(config);
}
}
}
for(String config:invalidConfigs) {
accountp.removeProperty(config);
}
try {
accountp.store(new FileOutputStream(this.confdir + ACCOUNT_PROPERTIES_FILE), null);
return true;
} catch (Exception e) {
Printer.instance.print("错误:更新账户配置文件时出现错误,请立即检查账户配置文件。");
return false;
}
}
#location 18
#vulnerability type RESOURCE_LEAK
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
@Override
public String doImportFolder(HttpServletRequest request, MultipartFile file) {
final String account = (String) request.getSession().getAttribute("ACCOUNT");
String folderId = request.getParameter("folderId");
final String originalFileName = new String(file.getOriginalFilename().getBytes(Charset.forName("UTF-8")),
Charset.forName("UTF-8"));
String folderConstraint = request.getParameter("folderConstraint");
// 再次检查上传文件名与目标目录ID
if (folderId == null || folderId.length() <= 0 || originalFileName == null || originalFileName.length() <= 0) {
return UPLOADERROR;
}
Folder folder = flm.queryById(folderId);
if (folder == null) {
return UPLOADERROR;
}
// 检查上传权限
if (!ConfigureReader.instance().authorized(account, AccountAuth.UPLOAD_FILES)
|| !ConfigureReader.instance().accessFolder(folder, account)) {
return UPLOADERROR;
}
// 检查上传文件体积是否超限
long mufs = ConfigureReader.instance().getUploadFileSize(account);
if (mufs >= 0 && file.getSize() > mufs) {
return UPLOADERROR;
}
// 检查是否具备创建文件夹权限,若有则使用请求中提供的文件夹访问级别,否则使用默认访问级别
int pc = folder.getFolderConstraint();
if (ConfigureReader.instance().authorized(account, AccountAuth.CREATE_NEW_FOLDER)) {
try {
int ifc = Integer.parseInt(folderConstraint);
if (ifc > 0 && account == null) {
return UPLOADERROR;
}
if (ifc < pc) {
return UPLOADERROR;
}
} catch (Exception e) {
return UPLOADERROR;
}
} else {
folderConstraint = pc + "";
}
// 计算相对路径的文件夹ID(即真正要保存的文件夹目标)
String[] paths = getParentPath(originalFileName);
// 将当前操作的文件夹路径加入到安全锁中,确保同一时间内无法对该文件夹进行重复导入,避免发生文件冲突的问题。
String result = protectImportFolder(paths, folderId, account, folderConstraint, originalFileName, file);
return result;
}
|
#vulnerable code
@Override
public String doImportFolder(HttpServletRequest request, MultipartFile file) {
String account = (String) request.getSession().getAttribute("ACCOUNT");
String folderId = request.getParameter("folderId");
final String originalFileName = new String(file.getOriginalFilename().getBytes(Charset.forName("UTF-8")),
Charset.forName("UTF-8"));
final String folderConstraint = request.getParameter("folderConstraint");
// 再次检查上传文件名与目标目录ID
if (folderId == null || folderId.length() <= 0 || originalFileName == null || originalFileName.length() <= 0) {
return UPLOADERROR;
}
Folder folder = flm.queryById(folderId);
if (folder == null) {
return UPLOADERROR;
}
// 检查上传权限
if (!ConfigureReader.instance().authorized(account, AccountAuth.UPLOAD_FILES)
|| !ConfigureReader.instance().accessFolder(folder, account)) {
return UPLOADERROR;
}
// 检查上传文件体积是否超限
long mufs = ConfigureReader.instance().getUploadFileSize(account);
if (mufs >= 0 && file.getSize() > mufs) {
return UPLOADERROR;
}
// 计算相对路径的文件夹ID(即真正要保存的文件夹目标)
String[] paths = getParentPath(originalFileName);
//将当前操作的文件夹路径加入到安全锁中,确保同一时间内无法对该文件夹进行重复导入,避免发生文件冲突的问题。
String pathskey = Arrays.toString(paths);
synchronized (pathsKeys) {
if(pathsKeys.contains(pathskey)) {
return UPLOADERROR;
}else {
pathsKeys.add(pathskey);
}
}
String result = protectImportFolder(paths, folderId, account, folderConstraint, originalFileName, file);
synchronized (pathsKeys) {
pathsKeys.remove(pathskey);
}
return result;
}
#location 30
#vulnerability type THREAD_SAFETY_VIOLATION
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
@Override
public String checkImportFolder(HttpServletRequest request) {
final String account = (String) request.getSession().getAttribute("ACCOUNT");
final String folderId = request.getParameter("folderId");
final String folderName = request.getParameter("folderName");
final String maxUploadFileSize = request.getParameter("maxSize");
CheckImportFolderRespons cifr = new CheckImportFolderRespons();
// 先行权限检查
if (!ConfigureReader.instance().authorized(account, AccountAuth.UPLOAD_FILES)) {
cifr.setResult(NO_AUTHORIZED);
return gson.toJson(cifr);
}
// 开始文件上传体积限制检查
try {
// 获取最大文件体积(以Byte为单位)
long mufs = Long.parseLong(maxUploadFileSize);
long pMaxUploadSize = ConfigureReader.instance().getUploadFileSize(account);
if (pMaxUploadSize >= 0) {
if (mufs > pMaxUploadSize) {
cifr.setResult("fileOverSize");
cifr.setMaxSize(formatMaxUploadFileSize(ConfigureReader.instance().getUploadFileSize(account)));
return gson.toJson(cifr);
}
}
} catch (Exception e) {
cifr.setResult(ERROR_PARAMETER);
return gson.toJson(cifr);
}
// 开始文件夹命名冲突检查,若无重名则允许上传。
final List<Folder> folders = flm.queryByParentId(folderId);
try {
folders.stream().parallel()
.filter((n) -> n.getFolderName().equals(
new String(folderName.getBytes(Charset.forName("UTF-8")), Charset.forName("UTF-8"))))
.findAny().get();
cifr.setResult("repeatFolder");
return gson.toJson(cifr);
} catch (NoSuchElementException e) {
// 通过所有检查,允许上传
cifr.setResult("permitUpload");
return gson.toJson(cifr);
}
}
|
#vulnerable code
@Override
public String checkImportFolder(HttpServletRequest request) {
final String account = (String) request.getSession().getAttribute("ACCOUNT");
final String folderId = request.getParameter("folderId");
final String folderName = request.getParameter("folderName");
final String maxUploadFileSize = request.getParameter("maxSize");
CheckImportFolderRespons cifr = new CheckImportFolderRespons();
// 先行权限检查
if (!ConfigureReader.instance().authorized(account, AccountAuth.UPLOAD_FILES)) {
cifr.setResult(NO_AUTHORIZED);
return gson.toJson(cifr);
}
// 开始文件上传体积限制检查
try {
// 获取最大文件体积(以Byte为单位)
long mufs = Long.parseLong(maxUploadFileSize);
long pMaxUploadSize = ConfigureReader.instance().getUploadFileSize(account);
if (pMaxUploadSize >= 0) {
if (mufs > pMaxUploadSize) {
cifr.setResult("fileOverSize");
cifr.setMaxSize(formatMaxUploadFileSize(ConfigureReader.instance().getUploadFileSize(account)));
return gson.toJson(cifr);
}
}
} catch (Exception e) {
cifr.setResult(ERROR_PARAMETER);
return gson.toJson(cifr);
}
// 开始文件夹命名冲突检查,若无重名则允许上传。
final List<Folder> folders = flm.queryByParentId(folderId);
try {
Folder testfolder = folders.stream().parallel()
.filter((n) -> n.getFolderName().equals(
new String(folderName.getBytes(Charset.forName("UTF-8")), Charset.forName("UTF-8"))))
.findAny().get();
// 若有重名,则判定该用户是否具备删除权限,这是能够覆盖的第一步
if (ConfigureReader.instance().authorized(account, AccountAuth.DELETE_FILE_OR_FOLDER)) {
// 接下来判断其是否具备冲突文件夹的访问权限,这是能够覆盖的第二步
if (ConfigureReader.instance().accessFolder(testfolder, account)) {
cifr.setResult("coverOrBoth");
return gson.toJson(cifr);
}
}
// 如果上述条件不满足,则只能允许保留两者
cifr.setResult("onlyBoth");
return gson.toJson(cifr);
} catch (NoSuchElementException e) {
// 通过所有检查,允许上传
cifr.setResult("permitUpload");
return gson.toJson(cifr);
}
}
#location 21
#vulnerability type THREAD_SAFETY_VIOLATION
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
@Override
public String doImportFolder(HttpServletRequest request, MultipartFile file) {
final String account = (String) request.getSession().getAttribute("ACCOUNT");
String folderId = request.getParameter("folderId");
final String originalFileName = new String(file.getOriginalFilename().getBytes(Charset.forName("UTF-8")),
Charset.forName("UTF-8"));
String folderConstraint = request.getParameter("folderConstraint");
// 再次检查上传文件名与目标目录ID
if (folderId == null || folderId.length() <= 0 || originalFileName == null || originalFileName.length() <= 0) {
return UPLOADERROR;
}
Folder folder = flm.queryById(folderId);
if (folder == null) {
return UPLOADERROR;
}
// 检查上传权限
if (!ConfigureReader.instance().authorized(account, AccountAuth.UPLOAD_FILES)
|| !ConfigureReader.instance().accessFolder(folder, account)) {
return UPLOADERROR;
}
// 检查上传文件体积是否超限
long mufs = ConfigureReader.instance().getUploadFileSize(account);
if (mufs >= 0 && file.getSize() > mufs) {
return UPLOADERROR;
}
// 检查是否具备创建文件夹权限,若有则使用请求中提供的文件夹访问级别,否则使用默认访问级别
int pc = folder.getFolderConstraint();
if (ConfigureReader.instance().authorized(account, AccountAuth.CREATE_NEW_FOLDER)) {
try {
int ifc = Integer.parseInt(folderConstraint);
if (ifc > 0 && account == null) {
return UPLOADERROR;
}
if (ifc < pc) {
return UPLOADERROR;
}
} catch (Exception e) {
return UPLOADERROR;
}
} else {
folderConstraint = pc + "";
}
// 计算相对路径的文件夹ID(即真正要保存的文件夹目标)
String[] paths = getParentPath(originalFileName);
// 将当前操作的文件夹路径加入到安全锁中,确保同一时间内无法对该文件夹进行重复导入,避免发生文件冲突的问题。
String result = protectImportFolder(paths, folderId, account, folderConstraint, originalFileName, file);
return result;
}
|
#vulnerable code
@Override
public String doImportFolder(HttpServletRequest request, MultipartFile file) {
String account = (String) request.getSession().getAttribute("ACCOUNT");
String folderId = request.getParameter("folderId");
final String originalFileName = new String(file.getOriginalFilename().getBytes(Charset.forName("UTF-8")),
Charset.forName("UTF-8"));
final String folderConstraint = request.getParameter("folderConstraint");
// 再次检查上传文件名与目标目录ID
if (folderId == null || folderId.length() <= 0 || originalFileName == null || originalFileName.length() <= 0) {
return UPLOADERROR;
}
Folder folder = flm.queryById(folderId);
if (folder == null) {
return UPLOADERROR;
}
// 检查上传权限
if (!ConfigureReader.instance().authorized(account, AccountAuth.UPLOAD_FILES)
|| !ConfigureReader.instance().accessFolder(folder, account)) {
return UPLOADERROR;
}
// 检查上传文件体积是否超限
long mufs = ConfigureReader.instance().getUploadFileSize(account);
if (mufs >= 0 && file.getSize() > mufs) {
return UPLOADERROR;
}
// 计算相对路径的文件夹ID(即真正要保存的文件夹目标)
String[] paths = getParentPath(originalFileName);
//将当前操作的文件夹路径加入到安全锁中,确保同一时间内无法对该文件夹进行重复导入,避免发生文件冲突的问题。
String pathskey = Arrays.toString(paths);
synchronized (pathsKeys) {
if(pathsKeys.contains(pathskey)) {
return UPLOADERROR;
}else {
pathsKeys.add(pathskey);
}
}
String result = protectImportFolder(paths, folderId, account, folderConstraint, originalFileName, file);
synchronized (pathsKeys) {
pathsKeys.remove(pathskey);
}
return result;
}
#location 22
#vulnerability type THREAD_SAFETY_VIOLATION
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
@Override
public String doImportFolder(HttpServletRequest request, MultipartFile file) {
String account = (String) request.getSession().getAttribute("ACCOUNT");
String folderId = request.getParameter("folderId");
final String originalFileName = new String(file.getOriginalFilename().getBytes(Charset.forName("UTF-8")),
Charset.forName("UTF-8"));
final String folderConstraint = request.getParameter("folderConstraint");
// 再次检查上传文件名与目标目录ID
if (folderId == null || folderId.length() <= 0 || originalFileName == null || originalFileName.length() <= 0) {
return UPLOADERROR;
}
Folder folder = flm.queryById(folderId);
if (folder == null) {
return UPLOADERROR;
}
// 检查上传权限
if (!ConfigureReader.instance().authorized(account, AccountAuth.UPLOAD_FILES)
|| !ConfigureReader.instance().accessFolder(folder, account)) {
return UPLOADERROR;
}
// 检查上传文件体积是否超限
long mufs = ConfigureReader.instance().getUploadFileSize(account);
if (mufs >= 0 && file.getSize() > mufs) {
return UPLOADERROR;
}
// 计算相对路径的文件夹ID(即真正要保存的文件夹目标)
String[] paths = getParentPath(originalFileName);
//将当前操作的文件夹路径加入到安全锁中,确保同一时间内无法对该文件夹进行重复导入,避免发生文件冲突的问题。
String pathskey = Arrays.toString(paths);
synchronized (pathsKeys) {
if(pathsKeys.contains(pathskey)) {
return UPLOADERROR;
}else {
pathsKeys.add(pathskey);
}
}
String result = protectImportFolder(paths, folderId, account, folderConstraint, originalFileName, file);
synchronized (pathsKeys) {
pathsKeys.remove(pathskey);
}
return result;
}
|
#vulnerable code
@Override
public String doImportFolder(HttpServletRequest request, MultipartFile file) {
String account = (String) request.getSession().getAttribute("ACCOUNT");
String folderId = request.getParameter("folderId");
final String originalFileName = new String(file.getOriginalFilename().getBytes(Charset.forName("UTF-8")),
Charset.forName("UTF-8"));
final String folderConstraint = request.getParameter("folderConstraint");
// 再次检查上传文件名与目标目录ID
if (folderId == null || folderId.length() <= 0 || originalFileName == null || originalFileName.length() <= 0) {
return UPLOADERROR;
}
Folder folder = flm.queryById(folderId);
if (folder == null) {
return UPLOADERROR;
}
// 检查上传权限
if (!ConfigureReader.instance().authorized(account, AccountAuth.UPLOAD_FILES)
|| !ConfigureReader.instance().accessFolder(folder, account)) {
return UPLOADERROR;
}
// 检查上传文件体积是否超限
long mufs = ConfigureReader.instance().getUploadFileSize(account);
if (mufs >= 0 && file.getSize() > mufs) {
return UPLOADERROR;
}
// 计算相对路径的文件夹ID(即真正要保存的文件夹目标)
String[] paths = getParentPath(originalFileName);
//将当前操作的文件夹路径加入到安全锁中,确保同一时间内无法对该文件夹进行重复导入,避免发生文件冲突的问题。
String pathskey = Arrays.toString(paths);
synchronized (pathsKeys) {
if(pathsKeys.contains(pathskey)) {
return UPLOADERROR;
}else {
pathsKeys.add(pathskey);
}
}
for (String pName : paths) {
try {
Folder target = flm.queryByParentId(folderId).parallelStream()
.filter((e) -> e.getFolderName().equals(pName)).findAny().get();
if (ConfigureReader.instance().accessFolder(target, account)) {
folderId = target.getFolderId();// 向下迭代直至将父路径全部迭代完毕并找到最终路径
} else {
synchronized (pathsKeys) {
pathsKeys.remove(pathskey);//解除安全锁,便于下一次上传
}
return UPLOADERROR;
}
} catch (NoSuchElementException e) {
Folder newFolder = fu.createNewFolder(flm.queryById(folderId), account, pName, folderConstraint);
if (newFolder != null) {
folderId = newFolder.getFolderId();
} else {
synchronized (pathsKeys) {
pathsKeys.remove(pathskey);//解除安全锁,便于下一次上传
}
return UPLOADERROR;
}
}
}
String fileName = getFileNameFormPath(originalFileName);
// 检查是否存在同名文件。存在则直接失败(确保上传的文件夹内容的原始性)
final List<Node> files = this.fm.queryByParentFolderId(folderId);
if (files.parallelStream().anyMatch((e) -> e.getFileName().equals(fileName))) {
synchronized (pathsKeys) {
pathsKeys.remove(pathskey);//解除安全锁,便于下一次上传
}
return UPLOADERROR;
}
// 将文件存入节点并获取其存入生成路径,型如“UUID.block”形式。
final String path = this.fbu.saveToFileBlocks(file);
if (path.equals("ERROR")) {
synchronized (pathsKeys) {
pathsKeys.remove(pathskey);//解除安全锁,便于下一次上传
}
return UPLOADERROR;
}
final String fsize = this.fbu.getFileSize(file);
final Node f2 = new Node();
f2.setFileId(UUID.randomUUID().toString());
if (account != null) {
f2.setFileCreator(account);
} else {
f2.setFileCreator("\u533f\u540d\u7528\u6237");
}
f2.setFileCreationDate(ServerTimeUtil.accurateToDay());
f2.setFileName(fileName);
f2.setFileParentFolder(folderId);
f2.setFilePath(path);
f2.setFileSize(fsize);
int i = 0;
// 尽可能避免UUID重复的情况发生,重试10次
while (true) {
try {
if (this.fm.insert(f2) > 0) {
this.lu.writeUploadFileEvent(f2, account);
synchronized (pathsKeys) {
pathsKeys.remove(pathskey);//解除安全锁,便于下一次上传
}
return UPLOADSUCCESS;
}
break;
} catch (Exception e) {
f2.setFileId(UUID.randomUUID().toString());
i++;
}
if (i >= 10) {
break;
}
}
synchronized (pathsKeys) {
pathsKeys.remove(pathskey);
}
return UPLOADERROR;
}
#location 41
#vulnerability type THREAD_SAFETY_VIOLATION
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
@Override
public String checkImportFolder(HttpServletRequest request) {
final String account = (String) request.getSession().getAttribute("ACCOUNT");
final String folderId = request.getParameter("folderId");
final String folderName = request.getParameter("folderName");
final String maxUploadFileSize = request.getParameter("maxSize");
CheckImportFolderRespons cifr = new CheckImportFolderRespons();
// 先行权限检查
if (!ConfigureReader.instance().authorized(account, AccountAuth.UPLOAD_FILES)) {
cifr.setResult(NO_AUTHORIZED);
return gson.toJson(cifr);
}
// 开始文件上传体积限制检查
try {
// 获取最大文件体积(以Byte为单位)
long mufs = Long.parseLong(maxUploadFileSize);
long pMaxUploadSize = ConfigureReader.instance().getUploadFileSize(account);
if (pMaxUploadSize >= 0) {
if (mufs > pMaxUploadSize) {
cifr.setResult("fileOverSize");
cifr.setMaxSize(formatMaxUploadFileSize(ConfigureReader.instance().getUploadFileSize(account)));
return gson.toJson(cifr);
}
}
} catch (Exception e) {
cifr.setResult(ERROR_PARAMETER);
return gson.toJson(cifr);
}
// 开始文件夹命名冲突检查,若无重名则允许上传。
final List<Folder> folders = flm.queryByParentId(folderId);
try {
folders.stream().parallel()
.filter((n) -> n.getFolderName().equals(
new String(folderName.getBytes(Charset.forName("UTF-8")), Charset.forName("UTF-8"))))
.findAny().get();
cifr.setResult("repeatFolder");
return gson.toJson(cifr);
} catch (NoSuchElementException e) {
// 通过所有检查,允许上传
cifr.setResult("permitUpload");
return gson.toJson(cifr);
}
}
|
#vulnerable code
@Override
public String checkImportFolder(HttpServletRequest request) {
final String account = (String) request.getSession().getAttribute("ACCOUNT");
final String folderId = request.getParameter("folderId");
final String folderName = request.getParameter("folderName");
final String maxUploadFileSize = request.getParameter("maxSize");
CheckImportFolderRespons cifr = new CheckImportFolderRespons();
// 先行权限检查
if (!ConfigureReader.instance().authorized(account, AccountAuth.UPLOAD_FILES)) {
cifr.setResult(NO_AUTHORIZED);
return gson.toJson(cifr);
}
// 开始文件上传体积限制检查
try {
// 获取最大文件体积(以Byte为单位)
long mufs = Long.parseLong(maxUploadFileSize);
long pMaxUploadSize = ConfigureReader.instance().getUploadFileSize(account);
if (pMaxUploadSize >= 0) {
if (mufs > pMaxUploadSize) {
cifr.setResult("fileOverSize");
cifr.setMaxSize(formatMaxUploadFileSize(ConfigureReader.instance().getUploadFileSize(account)));
return gson.toJson(cifr);
}
}
} catch (Exception e) {
cifr.setResult(ERROR_PARAMETER);
return gson.toJson(cifr);
}
// 开始文件夹命名冲突检查,若无重名则允许上传。
final List<Folder> folders = flm.queryByParentId(folderId);
try {
Folder testfolder = folders.stream().parallel()
.filter((n) -> n.getFolderName().equals(
new String(folderName.getBytes(Charset.forName("UTF-8")), Charset.forName("UTF-8"))))
.findAny().get();
// 若有重名,则判定该用户是否具备删除权限,这是能够覆盖的第一步
if (ConfigureReader.instance().authorized(account, AccountAuth.DELETE_FILE_OR_FOLDER)) {
// 接下来判断其是否具备冲突文件夹的访问权限,这是能够覆盖的第二步
if (ConfigureReader.instance().accessFolder(testfolder, account)) {
cifr.setResult("coverOrBoth");
return gson.toJson(cifr);
}
}
// 如果上述条件不满足,则只能允许保留两者
cifr.setResult("onlyBoth");
return gson.toJson(cifr);
} catch (NoSuchElementException e) {
// 通过所有检查,允许上传
cifr.setResult("permitUpload");
return gson.toJson(cifr);
}
}
#location 37
#vulnerability type THREAD_SAFETY_VIOLATION
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
public String checkLoginRequest(final HttpServletRequest request, final HttpSession session) {
final String encrypted = request.getParameter("encrypted");
try {
final String loginInfoStr = DecryptionUtil.dncryption(encrypted, ku.getPrivateKey());
final LoginInfoPojo info = gson.fromJson(loginInfoStr, LoginInfoPojo.class);
if (System.currentTimeMillis() - Long.parseLong(info.getTime()) > TIME_OUT) {
return "error";
}
final String accountId = info.getAccountId();
if (!ConfigureReader.instance().foundAccount(accountId)) {
return "accountnotfound";
}
// 如果验证码开启且该账户已被关注,则要求提供验证码
if(!ConfigureReader.instance().getVCLevel().equals(VCLevel.Close)) {
synchronized (focusAccount) {
if (focusAccount.contains(accountId)) {
String reqVerCode = request.getParameter("vercode");
String trueVerCode = (String) session.getAttribute("VERCODE");
session.removeAttribute("VERCODE");// 确保一个验证码只会生效一次,无论对错
if (reqVerCode == null || trueVerCode == null || !trueVerCode.equals(reqVerCode.toLowerCase())) {
return "needsubmitvercode";
}
}
}
}
if (ConfigureReader.instance().checkAccountPwd(accountId, info.getAccountPwd())) {
session.setAttribute("ACCOUNT", (Object) accountId);
// 如果该账户输入正确且是一个被关注的账户,则解除该账户的关注,释放空间
if(!ConfigureReader.instance().getVCLevel().equals(VCLevel.Close)) {
synchronized (focusAccount) {
focusAccount.remove(accountId);
}
}
return "permitlogin";
}
// 如果账户密码不匹配,则将该账户加入到关注账户集合,避免对方进一步破解
synchronized (focusAccount) {
if(!ConfigureReader.instance().getVCLevel().equals(VCLevel.Close)) {
focusAccount.add(accountId);
}
}
return "accountpwderror";
} catch (Exception e) {
return "error";
}
}
|
#vulnerable code
public String checkLoginRequest(final HttpServletRequest request, final HttpSession session) {
final String encrypted = request.getParameter("encrypted");
final String loginInfoStr = DecryptionUtil.dncryption(encrypted, ku.getPrivateKey());
try {
final LoginInfoPojo info = gson.fromJson(loginInfoStr, LoginInfoPojo.class);
if (System.currentTimeMillis() - Long.parseLong(info.getTime()) > TIME_OUT) {
return "error";
}
final String accountId = info.getAccountId();
if (!ConfigureReader.instance().foundAccount(accountId)) {
return "accountnotfound";
}
// 如果验证码开启且该账户已被关注,则要求提供验证码
if(!ConfigureReader.instance().getVCLevel().equals(VCLevel.Close)) {
synchronized (focusAccount) {
if (focusAccount.contains(accountId)) {
String reqVerCode = request.getParameter("vercode");
String trueVerCode = (String) session.getAttribute("VERCODE");
session.removeAttribute("VERCODE");// 确保一个验证码只会生效一次,无论对错
if (reqVerCode == null || trueVerCode == null || !trueVerCode.equals(reqVerCode.toLowerCase())) {
return "needsubmitvercode";
}
}
}
}
if (ConfigureReader.instance().checkAccountPwd(accountId, info.getAccountPwd())) {
session.setAttribute("ACCOUNT", (Object) accountId);
// 如果该账户输入正确且是一个被关注的账户,则解除该账户的关注,释放空间
if(!ConfigureReader.instance().getVCLevel().equals(VCLevel.Close)) {
synchronized (focusAccount) {
focusAccount.remove(accountId);
}
}
return "permitlogin";
}
// 如果账户密码不匹配,则将该账户加入到关注账户集合,避免对方进一步破解
synchronized (focusAccount) {
if(!ConfigureReader.instance().getVCLevel().equals(VCLevel.Close)) {
focusAccount.add(accountId);
}
}
return "accountpwderror";
} catch (Exception e) {
return "error";
}
}
#location 14
#vulnerability type THREAD_SAFETY_VIOLATION
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
@Override
public String doImportFolder(HttpServletRequest request, MultipartFile file) {
final String account = (String) request.getSession().getAttribute("ACCOUNT");
String folderId = request.getParameter("folderId");
final String originalFileName = new String(file.getOriginalFilename().getBytes(Charset.forName("UTF-8")),
Charset.forName("UTF-8"));
String folderConstraint = request.getParameter("folderConstraint");
// 再次检查上传文件名与目标目录ID
if (folderId == null || folderId.length() <= 0 || originalFileName == null || originalFileName.length() <= 0) {
return UPLOADERROR;
}
Folder folder = flm.queryById(folderId);
if (folder == null) {
return UPLOADERROR;
}
// 检查上传权限
if (!ConfigureReader.instance().authorized(account, AccountAuth.UPLOAD_FILES)
|| !ConfigureReader.instance().accessFolder(folder, account)) {
return UPLOADERROR;
}
// 检查上传文件体积是否超限
long mufs = ConfigureReader.instance().getUploadFileSize(account);
if (mufs >= 0 && file.getSize() > mufs) {
return UPLOADERROR;
}
// 检查是否具备创建文件夹权限,若有则使用请求中提供的文件夹访问级别,否则使用默认访问级别
int pc = folder.getFolderConstraint();
if (ConfigureReader.instance().authorized(account, AccountAuth.CREATE_NEW_FOLDER)) {
try {
int ifc = Integer.parseInt(folderConstraint);
if (ifc > 0 && account == null) {
return UPLOADERROR;
}
if (ifc < pc) {
return UPLOADERROR;
}
} catch (Exception e) {
return UPLOADERROR;
}
} else {
folderConstraint = pc + "";
}
// 计算相对路径的文件夹ID(即真正要保存的文件夹目标)
String[] paths = getParentPath(originalFileName);
// 将当前操作的文件夹路径加入到安全锁中,确保同一时间内无法对该文件夹进行重复导入,避免发生文件冲突的问题。
String result = protectImportFolder(paths, folderId, account, folderConstraint, originalFileName, file);
return result;
}
|
#vulnerable code
@Override
public String doImportFolder(HttpServletRequest request, MultipartFile file) {
String account = (String) request.getSession().getAttribute("ACCOUNT");
String folderId = request.getParameter("folderId");
final String originalFileName = new String(file.getOriginalFilename().getBytes(Charset.forName("UTF-8")),
Charset.forName("UTF-8"));
final String folderConstraint = request.getParameter("folderConstraint");
// 再次检查上传文件名与目标目录ID
if (folderId == null || folderId.length() <= 0 || originalFileName == null || originalFileName.length() <= 0) {
return UPLOADERROR;
}
Folder folder = flm.queryById(folderId);
if (folder == null) {
return UPLOADERROR;
}
// 检查上传权限
if (!ConfigureReader.instance().authorized(account, AccountAuth.UPLOAD_FILES)
|| !ConfigureReader.instance().accessFolder(folder, account)) {
return UPLOADERROR;
}
// 检查上传文件体积是否超限
long mufs = ConfigureReader.instance().getUploadFileSize(account);
if (mufs >= 0 && file.getSize() > mufs) {
return UPLOADERROR;
}
// 计算相对路径的文件夹ID(即真正要保存的文件夹目标)
String[] paths = getParentPath(originalFileName);
//将当前操作的文件夹路径加入到安全锁中,确保同一时间内无法对该文件夹进行重复导入,避免发生文件冲突的问题。
String pathskey = Arrays.toString(paths);
synchronized (pathsKeys) {
if(pathsKeys.contains(pathskey)) {
return UPLOADERROR;
}else {
pathsKeys.add(pathskey);
}
}
String result = protectImportFolder(paths, folderId, account, folderConstraint, originalFileName, file);
synchronized (pathsKeys) {
pathsKeys.remove(pathskey);
}
return result;
}
#location 18
#vulnerability type THREAD_SAFETY_VIOLATION
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
@Override
public String doImportFolder(HttpServletRequest request, MultipartFile file) {
final String account = (String) request.getSession().getAttribute("ACCOUNT");
String folderId = request.getParameter("folderId");
final String originalFileName = new String(file.getOriginalFilename().getBytes(Charset.forName("UTF-8")),
Charset.forName("UTF-8"));
String folderConstraint = request.getParameter("folderConstraint");
// 再次检查上传文件名与目标目录ID
if (folderId == null || folderId.length() <= 0 || originalFileName == null || originalFileName.length() <= 0) {
return UPLOADERROR;
}
Folder folder = flm.queryById(folderId);
if (folder == null) {
return UPLOADERROR;
}
// 检查上传权限
if (!ConfigureReader.instance().authorized(account, AccountAuth.UPLOAD_FILES)
|| !ConfigureReader.instance().accessFolder(folder, account)) {
return UPLOADERROR;
}
// 检查上传文件体积是否超限
long mufs = ConfigureReader.instance().getUploadFileSize(account);
if (mufs >= 0 && file.getSize() > mufs) {
return UPLOADERROR;
}
// 检查是否具备创建文件夹权限,若有则使用请求中提供的文件夹访问级别,否则使用默认访问级别
int pc = folder.getFolderConstraint();
if (ConfigureReader.instance().authorized(account, AccountAuth.CREATE_NEW_FOLDER)) {
try {
int ifc = Integer.parseInt(folderConstraint);
if (ifc > 0 && account == null) {
return UPLOADERROR;
}
if (ifc < pc) {
return UPLOADERROR;
}
} catch (Exception e) {
return UPLOADERROR;
}
} else {
folderConstraint = pc + "";
}
// 计算相对路径的文件夹ID(即真正要保存的文件夹目标)
String[] paths = getParentPath(originalFileName);
// 将当前操作的文件夹路径加入到安全锁中,确保同一时间内无法对该文件夹进行重复导入,避免发生文件冲突的问题。
String result = protectImportFolder(paths, folderId, account, folderConstraint, originalFileName, file);
return result;
}
|
#vulnerable code
@Override
public String doImportFolder(HttpServletRequest request, MultipartFile file) {
String account = (String) request.getSession().getAttribute("ACCOUNT");
String folderId = request.getParameter("folderId");
final String originalFileName = new String(file.getOriginalFilename().getBytes(Charset.forName("UTF-8")),
Charset.forName("UTF-8"));
final String folderConstraint = request.getParameter("folderConstraint");
// 再次检查上传文件名与目标目录ID
if (folderId == null || folderId.length() <= 0 || originalFileName == null || originalFileName.length() <= 0) {
return UPLOADERROR;
}
Folder folder = flm.queryById(folderId);
if (folder == null) {
return UPLOADERROR;
}
// 检查上传权限
if (!ConfigureReader.instance().authorized(account, AccountAuth.UPLOAD_FILES)
|| !ConfigureReader.instance().accessFolder(folder, account)) {
return UPLOADERROR;
}
// 检查上传文件体积是否超限
long mufs = ConfigureReader.instance().getUploadFileSize(account);
if (mufs >= 0 && file.getSize() > mufs) {
return UPLOADERROR;
}
// 计算相对路径的文件夹ID(即真正要保存的文件夹目标)
String[] paths = getParentPath(originalFileName);
//将当前操作的文件夹路径加入到安全锁中,确保同一时间内无法对该文件夹进行重复导入,避免发生文件冲突的问题。
String pathskey = Arrays.toString(paths);
synchronized (pathsKeys) {
if(pathsKeys.contains(pathskey)) {
return UPLOADERROR;
}else {
pathsKeys.add(pathskey);
}
}
String result = protectImportFolder(paths, folderId, account, folderConstraint, originalFileName, file);
synchronized (pathsKeys) {
pathsKeys.remove(pathskey);
}
return result;
}
#location 17
#vulnerability type THREAD_SAFETY_VIOLATION
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
@Override
public void clear() {
Map<String, String> savedHash = nest.hgetAll();
for (Map.Entry<String, String> entry : savedHash.entrySet()) {
nest.hdel(entry.getKey());
}
nest.del();
}
|
#vulnerable code
@Override
public void clear() {
Map<String, String> savedHash = nest.hgetAll();
for (Map.Entry<String, String> entry : savedHash.entrySet()) {
V value = JOhm.get(valueClazz, Integer.parseInt(entry.getValue()));
value.delete();
nest.hdel(entry.getKey());
}
nest.del();
refreshStorage(true);
}
#location 3
#vulnerability type THREAD_SAFETY_VIOLATION
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
@Override
public boolean addAll(Collection<? extends T> c) {
boolean success = true;
for (T element : c) {
success &= internalAdd(element);
}
return success;
}
|
#vulnerable code
@Override
public boolean addAll(Collection<? extends T> c) {
boolean success = true;
for (T element : c) {
success &= internalAdd(element, false);
}
refreshStorage(true);
return success;
}
#location 5
#vulnerability type THREAD_SAFETY_VIOLATION
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
@Override
public int size() {
int repoSize = nest.llen();
return repoSize;
}
|
#vulnerable code
@Override
public int size() {
int repoSize = nest.llen();
if (repoSize != elements.size()) {
refreshStorage(true);
}
return repoSize;
}
#location 3
#vulnerability type THREAD_SAFETY_VIOLATION
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
@Override
public T set(int index, T element) {
T previousElement = this.get(index);
internalIndexedAdd(index, element);
return previousElement;
}
|
#vulnerable code
@Override
public T set(int index, T element) {
T previousElement = this.get(index);
internalIndexedAdd(index, element, true);
return previousElement;
}
#location 4
#vulnerability type THREAD_SAFETY_VIOLATION
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
@Override
public void clear() {
Map<String, String> savedHash = nest.hgetAll();
for (Map.Entry<String, String> entry : savedHash.entrySet()) {
nest.hdel(entry.getKey());
}
nest.del();
}
|
#vulnerable code
@Override
public void clear() {
Map<String, String> savedHash = nest.hgetAll();
for (Map.Entry<String, String> entry : savedHash.entrySet()) {
V value = JOhm.get(valueClazz, Integer.parseInt(entry.getValue()));
value.delete();
nest.hdel(entry.getKey());
}
nest.del();
refreshStorage(true);
}
#location 7
#vulnerability type THREAD_SAFETY_VIOLATION
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
@Override
@SuppressWarnings("unchecked")
public boolean removeAll(Collection<?> c) {
Iterator<? extends Model> iterator = (Iterator<? extends Model>) c
.iterator();
boolean success = true;
while (iterator.hasNext()) {
T element = (T) iterator.next();
success &= internalRemove(element);
}
return success;
}
|
#vulnerable code
@Override
@SuppressWarnings("unchecked")
public boolean removeAll(Collection<?> c) {
Iterator<? extends Model> iterator = (Iterator<? extends Model>) c
.iterator();
boolean success = true;
while (iterator.hasNext()) {
T element = (T) iterator.next();
success &= internalRemove(element, false);
}
refreshStorage(true);
return success;
}
#location 9
#vulnerability type THREAD_SAFETY_VIOLATION
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
@Override
@SuppressWarnings("unchecked")
public boolean retainAll(Collection<?> c) {
this.clear();
Iterator<? extends Model> iterator = (Iterator<? extends Model>) c
.iterator();
boolean success = true;
while (iterator.hasNext()) {
T element = (T) iterator.next();
success &= internalAdd(element);
}
return success;
}
|
#vulnerable code
@Override
@SuppressWarnings("unchecked")
public boolean retainAll(Collection<?> c) {
this.clear();
Iterator<? extends Model> iterator = (Iterator<? extends Model>) c
.iterator();
boolean success = true;
while (iterator.hasNext()) {
T element = (T) iterator.next();
success &= internalAdd(element, false);
}
refreshStorage(true);
return success;
}
#location 4
#vulnerability type THREAD_SAFETY_VIOLATION
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
@Test
public void shouldSetCollectionAutomatically() {
User user = new User();
assertNotNull(user.getLikes());
assertTrue(user.getLikes().getClass().equals(RedisList.class));
assertTrue(user.getPurchases().getClass().equals(RedisSet.class));
assertTrue(user.getFavoritePurchases().getClass()
.equals(RedisMap.class));
assertTrue(user.getOrderedPurchases().getClass().equals(
RedisSortedSet.class));
}
|
#vulnerable code
@Test
public void shouldSetCollectionAutomatically() {
User user = new User();
assertNotNull(user.getLikes());
assertTrue(user.getLikes().getClass().equals(RedisList.class));
assertTrue(user.getPurchases().getClass().equals(RedisSet.class));
assertTrue(user.getFavoritePurchases().getClass()
.equals(RedisMap.class));
}
#location 5
#vulnerability type NULL_DEREFERENCE
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
@SuppressWarnings("unchecked")
@Override
public boolean retainAll(Collection<?> c) {
this.clear();
Iterator<? extends Model> iterator = (Iterator<? extends Model>) c
.iterator();
boolean success = true;
while (iterator.hasNext()) {
T element = (T) iterator.next();
success &= internalAdd(element);
}
return success;
}
|
#vulnerable code
@SuppressWarnings("unchecked")
@Override
public boolean retainAll(Collection<?> c) {
this.clear();
Iterator<? extends Model> iterator = (Iterator<? extends Model>) c
.iterator();
boolean success = true;
while (iterator.hasNext()) {
T element = (T) iterator.next();
success &= internalAdd(element, false);
}
refreshStorage(true);
return success;
}
#location 10
#vulnerability type THREAD_SAFETY_VIOLATION
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
@Override
public boolean remove(Object o) {
return internalRemove(o);
}
|
#vulnerable code
@Override
public boolean remove(Object o) {
return internalRemove(o, true);
}
#location 3
#vulnerability type THREAD_SAFETY_VIOLATION
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
@Override
public boolean add(T element) {
return internalAdd(element);
}
|
#vulnerable code
@Override
public boolean add(T element) {
return internalAdd(element, true);
}
#location 3
#vulnerability type THREAD_SAFETY_VIOLATION
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.