input
stringlengths 205
73.3k
| output
stringlengths 64
73.2k
| instruction
stringclasses 1
value |
---|---|---|
#vulnerable code
public void testSimpleObjectWrite()
throws Exception
{
StringWriter sw = new StringWriter();
JsonGenerator gen = new JsonFactory().createJsonGenerator(sw);
gen.writeStartObject();
gen.writeFieldName("first");
gen.writeNumber(-901);
gen.writeFieldName("sec");
gen.writeBoolean(false);
gen.writeFieldName("3rd!"); // json field names are just strings, not ids with restrictions
gen.writeString("yee-haw");
gen.writeEndObject();
gen.close();
String docStr = sw.toString();
JsonParser jp = createParserUsingReader(docStr);
assertEquals(JsonToken.START_OBJECT, jp.nextToken());
assertEquals(JsonToken.FIELD_NAME, jp.nextToken());
assertEquals("first", jp.getText());
assertEquals(JsonToken.VALUE_NUMBER_INT, jp.nextToken());
assertEquals(-901, jp.getIntValue());
assertEquals(JsonToken.FIELD_NAME, jp.nextToken());
assertEquals("sec", jp.getText());
assertEquals(JsonToken.VALUE_FALSE, jp.nextToken());
assertEquals(JsonToken.FIELD_NAME, jp.nextToken());
assertEquals("3rd!", jp.getText());
assertEquals(JsonToken.VALUE_STRING, jp.nextToken());
assertEquals("yee-haw", jp.getText());
assertEquals(JsonToken.END_OBJECT, jp.nextToken());
assertEquals(null, jp.nextToken());
jp.close();
}
#location 32
#vulnerability type RESOURCE_LEAK | #fixed code
public void testSimpleObjectWrite()
throws Exception
{
StringWriter sw = new StringWriter();
JsonGenerator gen = new JsonFactory().createGenerator(sw);
gen.writeStartObject();
gen.writeFieldName("first");
gen.writeNumber(-901);
gen.writeFieldName("sec");
gen.writeBoolean(false);
gen.writeFieldName("3rd!"); // json field names are just strings, not ids with restrictions
gen.writeString("yee-haw");
gen.writeEndObject();
gen.close();
String docStr = sw.toString();
JsonParser jp = createParserUsingReader(docStr);
assertEquals(JsonToken.START_OBJECT, jp.nextToken());
assertEquals(JsonToken.FIELD_NAME, jp.nextToken());
assertEquals("first", jp.getText());
assertEquals(JsonToken.VALUE_NUMBER_INT, jp.nextToken());
assertEquals(-901, jp.getIntValue());
assertEquals(JsonToken.FIELD_NAME, jp.nextToken());
assertEquals("sec", jp.getText());
assertEquals(JsonToken.VALUE_FALSE, jp.nextToken());
assertEquals(JsonToken.FIELD_NAME, jp.nextToken());
assertEquals("3rd!", jp.getText());
assertEquals(JsonToken.VALUE_STRING, jp.nextToken());
assertEquals("yee-haw", jp.getText());
assertEquals(JsonToken.END_OBJECT, jp.nextToken());
assertEquals(null, jp.nextToken());
jp.close();
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
public void testSimpleArrayWrite()
throws Exception
{
StringWriter sw = new StringWriter();
JsonGenerator gen = new JsonFactory().createJsonGenerator(sw);
gen.writeStartArray();
gen.writeNumber(13);
gen.writeBoolean(true);
gen.writeString("foobar");
gen.writeEndArray();
gen.close();
String docStr = sw.toString();
JsonParser jp = createParserUsingReader(docStr);
assertEquals(JsonToken.START_ARRAY, jp.nextToken());
assertEquals(JsonToken.VALUE_NUMBER_INT, jp.nextToken());
assertEquals(13, jp.getIntValue());
assertEquals(JsonToken.VALUE_TRUE, jp.nextToken());
assertEquals(JsonToken.VALUE_STRING, jp.nextToken());
assertEquals("foobar", jp.getText());
assertEquals(JsonToken.END_ARRAY, jp.nextToken());
assertEquals(null, jp.nextToken());
jp.close();
}
#location 23
#vulnerability type RESOURCE_LEAK | #fixed code
public void testSimpleArrayWrite()
throws Exception
{
StringWriter sw = new StringWriter();
JsonGenerator gen = new JsonFactory().createGenerator(sw);
gen.writeStartArray();
gen.writeNumber(13);
gen.writeBoolean(true);
gen.writeString("foobar");
gen.writeEndArray();
gen.close();
String docStr = sw.toString();
JsonParser jp = createParserUsingReader(docStr);
assertEquals(JsonToken.START_ARRAY, jp.nextToken());
assertEquals(JsonToken.VALUE_NUMBER_INT, jp.nextToken());
assertEquals(13, jp.getIntValue());
assertEquals(JsonToken.VALUE_TRUE, jp.nextToken());
assertEquals(JsonToken.VALUE_STRING, jp.nextToken());
assertEquals("foobar", jp.getText());
assertEquals(JsonToken.END_ARRAY, jp.nextToken());
assertEquals(null, jp.nextToken());
jp.close();
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Deprecated
protected JsonParser _createJsonParser(Reader r, IOContext ctxt) throws IOException, JsonParseException {
return new ReaderBasedJsonParser(ctxt, _parserFeatures, r, _objectCodec,
_rootCharSymbols.makeChild(isEnabled(JsonFactory.Feature.CANONICALIZE_FIELD_NAMES),
isEnabled(JsonFactory.Feature.INTERN_FIELD_NAMES)));
}
#location 4
#vulnerability type RESOURCE_LEAK | #fixed code
@Deprecated
protected JsonParser _createJsonParser(Reader r, IOContext ctxt) throws IOException, JsonParseException {
return _createParser(r, ctxt);
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Deprecated
protected JsonGenerator _createUTF8JsonGenerator(OutputStream out, IOContext ctxt)
throws IOException
{
UTF8JsonGenerator gen = new UTF8JsonGenerator(ctxt,
_generatorFeatures, _objectCodec, out);
if (_characterEscapes != null) {
gen.setCharacterEscapes(_characterEscapes);
}
SerializableString rootSep = _rootValueSeparator;
if (rootSep != DEFAULT_ROOT_VALUE_SEPARATOR) {
gen.setRootValueSeparator(rootSep);
}
return gen;
}
#location 5
#vulnerability type RESOURCE_LEAK | #fixed code
@Deprecated
protected JsonGenerator _createUTF8JsonGenerator(OutputStream out, IOContext ctxt)
throws IOException
{
return _createUTF8Generator(out, ctxt);
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
public static Version versionFor(Class<?> cls)
{
InputStream in;
Version version = null;
try {
in = cls.getResourceAsStream(VERSION_FILE);
if (in != null) {
try {
BufferedReader br = new BufferedReader(new InputStreamReader(in, "UTF-8"));
String groupStr = null, artifactStr = null;
String versionStr = br.readLine();
if (versionStr != null) {
groupStr = br.readLine();
if (groupStr != null) {
groupStr = groupStr.trim();
artifactStr = br.readLine();
if (artifactStr != null) {
artifactStr = artifactStr.trim();
}
}
}
version = parseVersion(versionStr, groupStr, artifactStr);
} finally {
try {
in.close();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}
} catch (IOException e) { }
return (version == null) ? Version.unknownVersion() : version;
}
#location 17
#vulnerability type RESOURCE_LEAK | #fixed code
public static Version versionFor(Class<?> cls)
{
final InputStream in = cls.getResourceAsStream(VERSION_FILE);
if (in == null)
return Version.unknownVersion();
try {
InputStreamReader reader = new InputStreamReader(in, "UTF-8");
try {
return doReadVersion(reader);
} finally {
try {
reader.close();
} catch (IOException ignored) {
}
}
} catch (UnsupportedEncodingException e) {
return Version.unknownVersion();
} finally {
try {
in.close();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
public void testInvalidArrayWrite()
throws Exception
{
StringWriter sw = new StringWriter();
JsonGenerator gen = new JsonFactory().createJsonGenerator(sw);
gen.writeStartArray();
// Mismatch:
try {
gen.writeEndObject();
fail("Expected an exception for mismatched array/object write");
} catch (JsonGenerationException e) {
verifyException(e, "Current context not an object");
}
}
#location 9
#vulnerability type RESOURCE_LEAK | #fixed code
public void testInvalidArrayWrite()
throws Exception
{
StringWriter sw = new StringWriter();
JsonGenerator gen = new JsonFactory().createGenerator(sw);
gen.writeStartArray();
// Mismatch:
try {
gen.writeEndObject();
fail("Expected an exception for mismatched array/object write");
} catch (JsonGenerationException e) {
verifyException(e, "Current context not an object");
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
protected String _generateRoot(JsonFactory jf, PrettyPrinter pp) throws IOException
{
StringWriter sw = new StringWriter();
JsonGenerator gen = new JsonFactory().createJsonGenerator(sw);
gen.setPrettyPrinter(pp);
gen.writeStartObject();
gen.writeEndObject();
gen.writeStartObject();
gen.writeEndObject();
gen.writeStartArray();
gen.writeEndArray();
gen.close();
return sw.toString();
}
#location 13
#vulnerability type RESOURCE_LEAK | #fixed code
protected String _generateRoot(JsonFactory jf, PrettyPrinter pp) throws IOException
{
StringWriter sw = new StringWriter();
JsonGenerator gen = new JsonFactory().createGenerator(sw);
gen.setPrettyPrinter(pp);
gen.writeStartObject();
gen.writeEndObject();
gen.writeStartObject();
gen.writeEndObject();
gen.writeStartArray();
gen.writeEndArray();
gen.close();
return sw.toString();
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
public void testArrayCount() throws Exception
{
final String EXP = "[6,[1,2,9(3)](2)]";
final JsonFactory jf = new JsonFactory();
for (int i = 0; i < 2; ++i) {
boolean useBytes = (i > 0);
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
StringWriter sw = new StringWriter();
JsonGenerator gen = useBytes ? jf.createJsonGenerator(bytes)
: jf.createJsonGenerator(sw);
gen.setPrettyPrinter(new CountPrinter());
gen.writeStartArray();
gen.writeNumber(6);
gen.writeStartArray();
gen.writeNumber(1);
gen.writeNumber(2);
gen.writeNumber(9);
gen.writeEndArray();
gen.writeEndArray();
gen.close();
String json = useBytes ? bytes.toString("UTF-8") : sw.toString();
assertEquals(EXP, json);
}
}
#location 26
#vulnerability type RESOURCE_LEAK | #fixed code
public void testArrayCount() throws Exception
{
final String EXP = "[6,[1,2,9(3)](2)]";
final JsonFactory jf = new JsonFactory();
for (int i = 0; i < 2; ++i) {
boolean useBytes = (i > 0);
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
StringWriter sw = new StringWriter();
JsonGenerator gen = useBytes ? jf.createGenerator(bytes)
: jf.createGenerator(sw);
gen.setPrettyPrinter(new CountPrinter());
gen.writeStartArray();
gen.writeNumber(6);
gen.writeStartArray();
gen.writeNumber(1);
gen.writeNumber(2);
gen.writeNumber(9);
gen.writeEndArray();
gen.writeEndArray();
gen.close();
String json = useBytes ? bytes.toString("UTF-8") : sw.toString();
assertEquals(EXP, json);
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Deprecated
protected JsonGenerator _createJsonGenerator(Writer out, IOContext ctxt)
throws IOException
{
WriterBasedJsonGenerator gen = new WriterBasedJsonGenerator(ctxt,
_generatorFeatures, _objectCodec, out);
if (_characterEscapes != null) {
gen.setCharacterEscapes(_characterEscapes);
}
SerializableString rootSep = _rootValueSeparator;
if (rootSep != DEFAULT_ROOT_VALUE_SEPARATOR) {
gen.setRootValueSeparator(rootSep);
}
return gen;
}
#location 5
#vulnerability type RESOURCE_LEAK | #fixed code
@Deprecated
protected JsonGenerator _createJsonGenerator(Writer out, IOContext ctxt)
throws IOException
{
/* NOTE: MUST call the deprecated method until it is deleted, just so
* that override still works as expected, for now.
*/
return _createGenerator(out, ctxt);
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
public void testWriteLongCustomEscapes() throws Exception
{
JsonFactory jf = new JsonFactory();
jf.setCharacterEscapes(ESC_627); // must set to trigger bug
StringBuilder longString = new StringBuilder();
while (longString.length() < 2000) {
longString.append("\u65e5\u672c\u8a9e");
}
StringWriter writer = new StringWriter();
// must call #createJsonGenerator(Writer), #createJsonGenerator(OutputStream) doesn't trigger bug
JsonGenerator jgen = jf.createJsonGenerator(writer);
jgen.setHighestNonEscapedChar(127); // must set to trigger bug
jgen.writeString(longString.toString());
}
#location 14
#vulnerability type RESOURCE_LEAK | #fixed code
public void testWriteLongCustomEscapes() throws Exception
{
JsonFactory jf = new JsonFactory();
jf.setCharacterEscapes(ESC_627); // must set to trigger bug
StringBuilder longString = new StringBuilder();
while (longString.length() < 2000) {
longString.append("\u65e5\u672c\u8a9e");
}
StringWriter writer = new StringWriter();
// must call #createGenerator(Writer), #createGenerator(OutputStream) doesn't trigger bug
JsonGenerator jgen = jf.createGenerator(writer);
jgen.setHighestNonEscapedChar(127); // must set to trigger bug
jgen.writeString(longString.toString());
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
public void testRaw() throws IOException
{
JsonFactory jf = new JsonFactory();
StringWriter sw = new StringWriter();
JsonGenerator gen = jf.createJsonGenerator(sw);
gen.writeStartArray();
gen.writeRaw("-123, true");
gen.writeRaw(", \"x\" ");
gen.writeEndArray();
gen.close();
JsonParser jp = createParserUsingReader(sw.toString());
assertToken(JsonToken.START_ARRAY, jp.nextToken());
assertToken(JsonToken.VALUE_NUMBER_INT, jp.nextToken());
assertEquals(-123, jp.getIntValue());
assertToken(JsonToken.VALUE_TRUE, jp.nextToken());
assertToken(JsonToken.VALUE_STRING, jp.nextToken());
assertEquals("x", jp.getText());
assertToken(JsonToken.END_ARRAY, jp.nextToken());
jp.close();
}
#location 22
#vulnerability type RESOURCE_LEAK | #fixed code
public void testRaw() throws IOException
{
JsonFactory jf = new JsonFactory();
StringWriter sw = new StringWriter();
JsonGenerator gen = jf.createGenerator(sw);
gen.writeStartArray();
gen.writeRaw("-123, true");
gen.writeRaw(", \"x\" ");
gen.writeEndArray();
gen.close();
JsonParser jp = createParserUsingReader(sw.toString());
assertToken(JsonToken.START_ARRAY, jp.nextToken());
assertToken(JsonToken.VALUE_NUMBER_INT, jp.nextToken());
assertEquals(-123, jp.getIntValue());
assertToken(JsonToken.VALUE_TRUE, jp.nextToken());
assertToken(JsonToken.VALUE_STRING, jp.nextToken());
assertEquals("x", jp.getText());
assertToken(JsonToken.END_ARRAY, jp.nextToken());
jp.close();
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
private void doTestBasicEscaping(boolean charArray)
throws Exception
{
for (int i = 0; i < SAMPLES.length; ++i) {
String VALUE = SAMPLES[i];
StringWriter sw = new StringWriter();
JsonGenerator gen = new JsonFactory().createJsonGenerator(sw);
gen.writeStartArray();
if (charArray) {
char[] buf = new char[VALUE.length() + i];
VALUE.getChars(0, VALUE.length(), buf, i);
gen.writeString(buf, i, VALUE.length());
} else {
gen.writeString(VALUE);
}
gen.writeEndArray();
gen.close();
String docStr = sw.toString();
JsonParser jp = createParserUsingReader(docStr);
assertEquals(JsonToken.START_ARRAY, jp.nextToken());
JsonToken t = jp.nextToken();
assertEquals(JsonToken.VALUE_STRING, t);
assertEquals(VALUE, jp.getText());
assertEquals(JsonToken.END_ARRAY, jp.nextToken());
assertEquals(null, jp.nextToken());
jp.close();
}
}
#location 15
#vulnerability type RESOURCE_LEAK | #fixed code
private void doTestBasicEscaping(boolean charArray)
throws Exception
{
for (int i = 0; i < SAMPLES.length; ++i) {
String VALUE = SAMPLES[i];
StringWriter sw = new StringWriter();
JsonGenerator gen = new JsonFactory().createGenerator(sw);
gen.writeStartArray();
if (charArray) {
char[] buf = new char[VALUE.length() + i];
VALUE.getChars(0, VALUE.length(), buf, i);
gen.writeString(buf, i, VALUE.length());
} else {
gen.writeString(VALUE);
}
gen.writeEndArray();
gen.close();
String docStr = sw.toString();
JsonParser jp = createParserUsingReader(docStr);
assertEquals(JsonToken.START_ARRAY, jp.nextToken());
JsonToken t = jp.nextToken();
assertEquals(JsonToken.VALUE_STRING, t);
assertEquals(VALUE, jp.getText());
assertEquals(JsonToken.END_ARRAY, jp.nextToken());
assertEquals(null, jp.nextToken());
jp.close();
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
public void testAutoFlushOrNot() throws Exception
{
JsonFactory f = new JsonFactory();
assertTrue(f.isEnabled(JsonGenerator.Feature.FLUSH_PASSED_TO_STREAM));
MyChars sw = new MyChars();
JsonGenerator jg = f.createJsonGenerator(sw);
jg.writeStartArray();
jg.writeEndArray();
assertEquals(0, sw.flushed);
jg.flush();
assertEquals(1, sw.flushed);
jg.close();
// ditto with stream
MyBytes bytes = new MyBytes();
jg = f.createJsonGenerator(bytes, JsonEncoding.UTF8);
jg.writeStartArray();
jg.writeEndArray();
assertEquals(0, bytes.flushed);
jg.flush();
assertEquals(1, bytes.flushed);
assertEquals(2, bytes.toByteArray().length);
jg.close();
// then disable and we should not see flushing again...
f.disable(JsonGenerator.Feature.FLUSH_PASSED_TO_STREAM);
// first with a Writer
sw = new MyChars();
jg = f.createJsonGenerator(sw);
jg.writeStartArray();
jg.writeEndArray();
assertEquals(0, sw.flushed);
jg.flush();
assertEquals(0, sw.flushed);
jg.close();
assertEquals("[]", sw.toString());
// and then with OutputStream
bytes = new MyBytes();
jg = f.createJsonGenerator(bytes, JsonEncoding.UTF8);
jg.writeStartArray();
jg.writeEndArray();
assertEquals(0, bytes.flushed);
jg.flush();
assertEquals(0, bytes.flushed);
jg.close();
assertEquals(2, bytes.toByteArray().length);
}
#location 48
#vulnerability type RESOURCE_LEAK | #fixed code
public void testAutoFlushOrNot() throws Exception
{
JsonFactory f = new JsonFactory();
assertTrue(f.isEnabled(JsonGenerator.Feature.FLUSH_PASSED_TO_STREAM));
MyChars sw = new MyChars();
JsonGenerator jg = f.createGenerator(sw);
jg.writeStartArray();
jg.writeEndArray();
assertEquals(0, sw.flushed);
jg.flush();
assertEquals(1, sw.flushed);
jg.close();
// ditto with stream
MyBytes bytes = new MyBytes();
jg = f.createGenerator(bytes, JsonEncoding.UTF8);
jg.writeStartArray();
jg.writeEndArray();
assertEquals(0, bytes.flushed);
jg.flush();
assertEquals(1, bytes.flushed);
assertEquals(2, bytes.toByteArray().length);
jg.close();
// then disable and we should not see flushing again...
f.disable(JsonGenerator.Feature.FLUSH_PASSED_TO_STREAM);
// first with a Writer
sw = new MyChars();
jg = f.createGenerator(sw);
jg.writeStartArray();
jg.writeEndArray();
assertEquals(0, sw.flushed);
jg.flush();
assertEquals(0, sw.flushed);
jg.close();
assertEquals("[]", sw.toString());
// and then with OutputStream
bytes = new MyBytes();
jg = f.createGenerator(bytes, JsonEncoding.UTF8);
jg.writeStartArray();
jg.writeEndArray();
assertEquals(0, bytes.flushed);
jg.flush();
assertEquals(0, bytes.flushed);
jg.close();
assertEquals(2, bytes.toByteArray().length);
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
public void testFieldValueWrites()
throws Exception
{
StringWriter sw = new StringWriter();
JsonGenerator gen = new JsonFactory().createJsonGenerator(sw);
gen.writeStartObject();
gen.writeNumberField("long", 3L);
gen.writeNumberField("double", 0.25);
gen.writeNumberField("float", -0.25f);
gen.writeEndObject();
gen.close();
assertEquals("{\"long\":3,\"double\":0.25,\"float\":-0.25}", sw.toString().trim());
}
#location 14
#vulnerability type RESOURCE_LEAK | #fixed code
public void testFieldValueWrites()
throws Exception
{
StringWriter sw = new StringWriter();
JsonGenerator gen = new JsonFactory().createGenerator(sw);
gen.writeStartObject();
gen.writeNumberField("long", 3L);
gen.writeNumberField("double", 0.25);
gen.writeNumberField("float", -0.25f);
gen.writeEndObject();
gen.close();
assertEquals("{\"long\":3,\"double\":0.25,\"float\":-0.25}", sw.toString().trim());
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
public void testConvenienceMethods()
throws Exception
{
StringWriter sw = new StringWriter();
JsonGenerator gen = new JsonFactory().createJsonGenerator(sw);
gen.writeStartObject();
final BigDecimal dec = new BigDecimal("0.1");
final String TEXT = "\"some\nString!\"";
gen.writeNullField("null");
gen.writeBooleanField("bt", true);
gen.writeBooleanField("bf", false);
gen.writeNumberField("int", -1289);
gen.writeNumberField("dec", dec);
gen.writeObjectFieldStart("ob");
gen.writeStringField("str", TEXT);
gen.writeEndObject();
gen.writeArrayFieldStart("arr");
gen.writeEndArray();
gen.writeEndObject();
gen.close();
String docStr = sw.toString();
JsonParser jp = createParserUsingReader(docStr);
assertEquals(JsonToken.START_OBJECT, jp.nextToken());
assertEquals(JsonToken.FIELD_NAME, jp.nextToken());
assertEquals("null", jp.getText());
assertEquals(JsonToken.VALUE_NULL, jp.nextToken());
assertEquals(JsonToken.FIELD_NAME, jp.nextToken());
assertEquals("bt", jp.getText());
assertEquals(JsonToken.VALUE_TRUE, jp.nextToken());
assertEquals(JsonToken.FIELD_NAME, jp.nextToken());
assertEquals("bf", jp.getText());
assertEquals(JsonToken.VALUE_FALSE, jp.nextToken());
assertEquals(JsonToken.FIELD_NAME, jp.nextToken());
assertEquals("int", jp.getText());
assertEquals(JsonToken.VALUE_NUMBER_INT, jp.nextToken());
assertEquals(JsonToken.FIELD_NAME, jp.nextToken());
assertEquals("dec", jp.getText());
assertEquals(JsonToken.VALUE_NUMBER_FLOAT, jp.nextToken());
assertEquals(JsonToken.FIELD_NAME, jp.nextToken());
assertEquals("ob", jp.getText());
assertEquals(JsonToken.START_OBJECT, jp.nextToken());
assertEquals(JsonToken.FIELD_NAME, jp.nextToken());
assertEquals("str", jp.getText());
assertEquals(JsonToken.VALUE_STRING, jp.nextToken());
assertEquals(TEXT, getAndVerifyText(jp));
assertEquals(JsonToken.END_OBJECT, jp.nextToken());
assertEquals(JsonToken.FIELD_NAME, jp.nextToken());
assertEquals("arr", jp.getText());
assertEquals(JsonToken.START_ARRAY, jp.nextToken());
assertEquals(JsonToken.END_ARRAY, jp.nextToken());
assertEquals(JsonToken.END_OBJECT, jp.nextToken());
assertEquals(null, jp.nextToken());
jp.close();
}
#location 64
#vulnerability type RESOURCE_LEAK | #fixed code
public void testConvenienceMethods()
throws Exception
{
StringWriter sw = new StringWriter();
JsonGenerator gen = new JsonFactory().createGenerator(sw);
gen.writeStartObject();
final BigDecimal dec = new BigDecimal("0.1");
final String TEXT = "\"some\nString!\"";
gen.writeNullField("null");
gen.writeBooleanField("bt", true);
gen.writeBooleanField("bf", false);
gen.writeNumberField("int", -1289);
gen.writeNumberField("dec", dec);
gen.writeObjectFieldStart("ob");
gen.writeStringField("str", TEXT);
gen.writeEndObject();
gen.writeArrayFieldStart("arr");
gen.writeEndArray();
gen.writeEndObject();
gen.close();
String docStr = sw.toString();
JsonParser jp = createParserUsingReader(docStr);
assertEquals(JsonToken.START_OBJECT, jp.nextToken());
assertEquals(JsonToken.FIELD_NAME, jp.nextToken());
assertEquals("null", jp.getText());
assertEquals(JsonToken.VALUE_NULL, jp.nextToken());
assertEquals(JsonToken.FIELD_NAME, jp.nextToken());
assertEquals("bt", jp.getText());
assertEquals(JsonToken.VALUE_TRUE, jp.nextToken());
assertEquals(JsonToken.FIELD_NAME, jp.nextToken());
assertEquals("bf", jp.getText());
assertEquals(JsonToken.VALUE_FALSE, jp.nextToken());
assertEquals(JsonToken.FIELD_NAME, jp.nextToken());
assertEquals("int", jp.getText());
assertEquals(JsonToken.VALUE_NUMBER_INT, jp.nextToken());
assertEquals(JsonToken.FIELD_NAME, jp.nextToken());
assertEquals("dec", jp.getText());
assertEquals(JsonToken.VALUE_NUMBER_FLOAT, jp.nextToken());
assertEquals(JsonToken.FIELD_NAME, jp.nextToken());
assertEquals("ob", jp.getText());
assertEquals(JsonToken.START_OBJECT, jp.nextToken());
assertEquals(JsonToken.FIELD_NAME, jp.nextToken());
assertEquals("str", jp.getText());
assertEquals(JsonToken.VALUE_STRING, jp.nextToken());
assertEquals(TEXT, getAndVerifyText(jp));
assertEquals(JsonToken.END_OBJECT, jp.nextToken());
assertEquals(JsonToken.FIELD_NAME, jp.nextToken());
assertEquals("arr", jp.getText());
assertEquals(JsonToken.START_ARRAY, jp.nextToken());
assertEquals(JsonToken.END_ARRAY, jp.nextToken());
assertEquals(JsonToken.END_OBJECT, jp.nextToken());
assertEquals(null, jp.nextToken());
jp.close();
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
public void testCopyObjectTokens()
throws IOException
{
JsonFactory jf = new JsonFactory();
final String DOC = "{ \"a\":1, \"b\":[{ \"c\" : null }] }";
JsonParser jp = jf.createJsonParser(new StringReader(DOC));
StringWriter sw = new StringWriter();
JsonGenerator gen = jf.createJsonGenerator(sw);
assertToken(JsonToken.START_OBJECT, jp.nextToken());
gen.copyCurrentStructure(jp);
// which will advance parser to matching end Object
assertToken(JsonToken.END_OBJECT, jp.getCurrentToken());
jp.close();
gen.close();
assertEquals("{\"a\":1,\"b\":[{\"c\":null}]}", sw.toString());
}
#location 18
#vulnerability type RESOURCE_LEAK | #fixed code
public void testCopyObjectTokens()
throws IOException
{
JsonFactory jf = new JsonFactory();
final String DOC = "{ \"a\":1, \"b\":[{ \"c\" : null }] }";
JsonParser jp = jf.createParser(new StringReader(DOC));
StringWriter sw = new StringWriter();
JsonGenerator gen = jf.createGenerator(sw);
assertToken(JsonToken.START_OBJECT, jp.nextToken());
gen.copyCurrentStructure(jp);
// which will advance parser to matching end Object
assertToken(JsonToken.END_OBJECT, jp.getCurrentToken());
jp.close();
gen.close();
assertEquals("{\"a\":1,\"b\":[{\"c\":null}]}", sw.toString());
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@SuppressWarnings("resource")
private void _testEscapeAboveAscii(boolean useStream) throws Exception
{
JsonFactory f = new JsonFactory();
final String VALUE = "chars: [\u00A0]/[\u1234]";
final String KEY = "fun:\u0088:\u3456";
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
JsonGenerator jgen;
// First: output normally; should not add escaping
if (useStream) {
jgen = f.createJsonGenerator(bytes, JsonEncoding.UTF8);
} else {
jgen = f.createJsonGenerator(new OutputStreamWriter(bytes, "UTF-8"));
}
jgen.writeStartArray();
jgen.writeString(VALUE);
jgen.writeEndArray();
jgen.close();
String json = bytes.toString("UTF-8");
assertEquals("["+quote(VALUE)+"]", json);
// And then with forced ASCII; first, values
bytes = new ByteArrayOutputStream();
if (useStream) {
jgen = f.createJsonGenerator(bytes, JsonEncoding.UTF8);
} else {
jgen = f.createJsonGenerator(new OutputStreamWriter(bytes, "UTF-8"));
}
jgen.enable(JsonGenerator.Feature.ESCAPE_NON_ASCII);
jgen.writeStartArray();
jgen.writeString(VALUE);
jgen.writeEndArray();
jgen.close();
json = bytes.toString("UTF-8");
assertEquals("["+quote("chars: [\\u00A0]/[\\u1234]")+"]", json);
// and then keys
bytes = new ByteArrayOutputStream();
if (useStream) {
jgen = f.createJsonGenerator(bytes, JsonEncoding.UTF8);
} else {
jgen = f.createJsonGenerator(new OutputStreamWriter(bytes, "UTF-8"));
}
jgen.enable(JsonGenerator.Feature.ESCAPE_NON_ASCII);
jgen.writeStartObject();
jgen.writeFieldName(KEY);
jgen.writeBoolean(true);
jgen.writeEndObject();
jgen.close();
json = bytes.toString("UTF-8");
assertEquals("{"+quote("fun:\\u0088:\\u3456")+":true}", json);
}
#location 15
#vulnerability type RESOURCE_LEAK | #fixed code
@SuppressWarnings("resource")
private void _testEscapeAboveAscii(boolean useStream) throws Exception
{
JsonFactory f = new JsonFactory();
final String VALUE = "chars: [\u00A0]/[\u1234]";
final String KEY = "fun:\u0088:\u3456";
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
JsonGenerator jgen;
// First: output normally; should not add escaping
if (useStream) {
jgen = f.createGenerator(bytes, JsonEncoding.UTF8);
} else {
jgen = f.createGenerator(new OutputStreamWriter(bytes, "UTF-8"));
}
jgen.writeStartArray();
jgen.writeString(VALUE);
jgen.writeEndArray();
jgen.close();
String json = bytes.toString("UTF-8");
assertEquals("["+quote(VALUE)+"]", json);
// And then with forced ASCII; first, values
bytes = new ByteArrayOutputStream();
if (useStream) {
jgen = f.createGenerator(bytes, JsonEncoding.UTF8);
} else {
jgen = f.createGenerator(new OutputStreamWriter(bytes, "UTF-8"));
}
jgen.enable(JsonGenerator.Feature.ESCAPE_NON_ASCII);
jgen.writeStartArray();
jgen.writeString(VALUE);
jgen.writeEndArray();
jgen.close();
json = bytes.toString("UTF-8");
assertEquals("["+quote("chars: [\\u00A0]/[\\u1234]")+"]", json);
// and then keys
bytes = new ByteArrayOutputStream();
if (useStream) {
jgen = f.createGenerator(bytes, JsonEncoding.UTF8);
} else {
jgen = f.createGenerator(new OutputStreamWriter(bytes, "UTF-8"));
}
jgen.enable(JsonGenerator.Feature.ESCAPE_NON_ASCII);
jgen.writeStartObject();
jgen.writeFieldName(KEY);
jgen.writeBoolean(true);
jgen.writeEndObject();
jgen.close();
json = bytes.toString("UTF-8");
assertEquals("{"+quote("fun:\\u0088:\\u3456")+":true}", json);
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
private String _writeNumbers(JsonFactory jf) throws IOException
{
StringWriter sw = new StringWriter();
JsonGenerator jg = jf.createJsonGenerator(sw);
jg.writeStartArray();
jg.writeNumber(1);
jg.writeNumber(2L);
jg.writeNumber(1.25);
jg.writeNumber(2.25f);
jg.writeNumber(BigInteger.valueOf(3001));
jg.writeNumber(BigDecimal.valueOf(0.5));
jg.writeNumber("-1");
jg.writeEndArray();
jg.close();
return sw.toString();
}
#location 17
#vulnerability type RESOURCE_LEAK | #fixed code
private String _writeNumbers(JsonFactory jf) throws IOException
{
StringWriter sw = new StringWriter();
JsonGenerator jg = jf.createGenerator(sw);
jg.writeStartArray();
jg.writeNumber(1);
jg.writeNumber(2L);
jg.writeNumber(1.25);
jg.writeNumber(2.25f);
jg.writeNumber(BigInteger.valueOf(3001));
jg.writeNumber(BigDecimal.valueOf(0.5));
jg.writeNumber("-1");
jg.writeEndArray();
jg.close();
return sw.toString();
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
public void testInvalidObjectWrite()
throws Exception
{
StringWriter sw = new StringWriter();
JsonGenerator gen = new JsonFactory().createJsonGenerator(sw);
gen.writeStartObject();
// Mismatch:
try {
gen.writeEndArray();
fail("Expected an exception for mismatched array/object write");
} catch (JsonGenerationException e) {
verifyException(e, "Current context not an array");
}
}
#location 9
#vulnerability type RESOURCE_LEAK | #fixed code
public void testInvalidObjectWrite()
throws Exception
{
StringWriter sw = new StringWriter();
JsonGenerator gen = new JsonFactory().createGenerator(sw);
gen.writeStartObject();
// Mismatch:
try {
gen.writeEndArray();
fail("Expected an exception for mismatched array/object write");
} catch (JsonGenerationException e) {
verifyException(e, "Current context not an array");
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
public void testCopyRootTokens()
throws IOException
{
JsonFactory jf = new JsonFactory();
final String DOC = "\"text\\non two lines\" true false 2.0";
JsonParser jp = jf.createJsonParser(new StringReader(DOC));
StringWriter sw = new StringWriter();
JsonGenerator gen = jf.createJsonGenerator(sw);
JsonToken t;
while ((t = jp.nextToken()) != null) {
gen.copyCurrentEvent(jp);
// should not change parser state:
assertToken(t, jp.getCurrentToken());
}
jp.close();
gen.close();
assertEquals("\"text\\non two lines\" true false 2.0", sw.toString());
}
#location 16
#vulnerability type RESOURCE_LEAK | #fixed code
public void testCopyRootTokens()
throws IOException
{
JsonFactory jf = new JsonFactory();
final String DOC = "\"text\\non two lines\" true false 2.0";
JsonParser jp = jf.createParser(new StringReader(DOC));
StringWriter sw = new StringWriter();
JsonGenerator gen = jf.createGenerator(sw);
JsonToken t;
while ((t = jp.nextToken()) != null) {
gen.copyCurrentEvent(jp);
// should not change parser state:
assertToken(t, jp.getCurrentToken());
}
jp.close();
gen.close();
assertEquals("\"text\\non two lines\" true false 2.0", sw.toString());
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
private void _testNonNumericQuoting(JsonFactory jf, boolean quoted)
throws IOException
{
StringWriter sw = new StringWriter();
JsonGenerator jg = jf.createJsonGenerator(sw);
jg.writeStartObject();
jg.writeFieldName("double");
jg.writeNumber(Double.NaN);
jg.writeEndObject();
jg.writeStartObject();
jg.writeFieldName("float");
jg.writeNumber(Float.NaN);
jg.writeEndObject();
jg.close();
String result = sw.toString();
if (quoted) {
assertEquals("{\"double\":\"NaN\"} {\"float\":\"NaN\"}", result);
} else {
assertEquals("{\"double\":NaN} {\"float\":NaN}", result);
}
}
#location 21
#vulnerability type RESOURCE_LEAK | #fixed code
private void _testNonNumericQuoting(JsonFactory jf, boolean quoted)
throws IOException
{
StringWriter sw = new StringWriter();
JsonGenerator jg = jf.createGenerator(sw);
jg.writeStartObject();
jg.writeFieldName("double");
jg.writeNumber(Double.NaN);
jg.writeEndObject();
jg.writeStartObject();
jg.writeFieldName("float");
jg.writeNumber(Float.NaN);
jg.writeEndObject();
jg.close();
String result = sw.toString();
if (quoted) {
assertEquals("{\"double\":\"NaN\"} {\"float\":\"NaN\"}", result);
} else {
assertEquals("{\"double\":NaN} {\"float\":NaN}", result);
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
public void testIsClosed()
throws IOException
{
JsonFactory jf = new JsonFactory();
for (int i = 0; i < 2; ++i) {
boolean stream = ((i & 1) == 0);
JsonGenerator jg = stream ?
jf.createJsonGenerator(new StringWriter())
: jf.createJsonGenerator(new ByteArrayOutputStream(), JsonEncoding.UTF8)
;
assertFalse(jg.isClosed());
jg.writeStartArray();
jg.writeNumber(-1);
jg.writeEndArray();
assertFalse(jg.isClosed());
jg.close();
assertTrue(jg.isClosed());
jg.close();
assertTrue(jg.isClosed());
}
}
#location 20
#vulnerability type RESOURCE_LEAK | #fixed code
public void testIsClosed()
throws IOException
{
JsonFactory jf = new JsonFactory();
for (int i = 0; i < 2; ++i) {
boolean stream = ((i & 1) == 0);
JsonGenerator jg = stream ?
jf.createGenerator(new StringWriter())
: jf.createGenerator(new ByteArrayOutputStream(), JsonEncoding.UTF8)
;
assertFalse(jg.isClosed());
jg.writeStartArray();
jg.writeNumber(-1);
jg.writeEndArray();
assertFalse(jg.isClosed());
jg.close();
assertTrue(jg.isClosed());
jg.close();
assertTrue(jg.isClosed());
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
public void testLongText() throws Exception
{
final int LEN = 96000;
StringBuilder sb = new StringBuilder(LEN + 100);
Random r = new Random(99);
while (sb.length() < LEN) {
sb.append(r.nextInt());
sb.append(" xyz foo");
if (r.nextBoolean()) {
sb.append(" and \"bar\"");
} else if (r.nextBoolean()) {
sb.append(" [whatever].... ");
} else {
// Let's try some more 'exotic' chars
sb.append(" UTF-8-fu: try this {\u00E2/\u0BF8/\uA123!} (look funny?)");
}
if (r.nextBoolean()) {
if (r.nextBoolean()) {
sb.append('\n');
} else if (r.nextBoolean()) {
sb.append('\r');
} else {
sb.append("\r\n");
}
}
}
final String VALUE = sb.toString();
JsonFactory jf = new JsonFactory();
// Let's use real generator to get json done right
StringWriter sw = new StringWriter(LEN + (LEN >> 2));
JsonGenerator jg = jf.createJsonGenerator(sw);
jg.writeStartObject();
jg.writeFieldName("doc");
jg.writeString(VALUE);
jg.writeEndObject();
jg.close();
final String DOC = sw.toString();
for (int type = 0; type < 3; ++type) {
JsonParser jp;
switch (type) {
default:
jp = jf.createJsonParser(DOC.getBytes("UTF-8"));
break;
case 1:
jp = jf.createJsonParser(DOC);
break;
case 2: // NEW: let's also exercise UTF-32...
jp = jf.createJsonParser(encodeInUTF32BE(DOC));
break;
}
assertToken(JsonToken.START_OBJECT, jp.nextToken());
assertToken(JsonToken.FIELD_NAME, jp.nextToken());
assertEquals("doc", jp.getCurrentName());
assertToken(JsonToken.VALUE_STRING, jp.nextToken());
String act = getAndVerifyText(jp);
if (act.length() != VALUE.length()) {
fail("Expected length "+VALUE.length()+", got "+act.length());
}
if (!act.equals(VALUE)) {
fail("Long text differs");
}
// should still know the field name
assertEquals("doc", jp.getCurrentName());
assertToken(JsonToken.END_OBJECT, jp.nextToken());
assertNull(jp.nextToken());
jp.close();
}
}
#location 16
#vulnerability type RESOURCE_LEAK | #fixed code
public void testLongText() throws Exception
{
final int LEN = 96000;
StringBuilder sb = new StringBuilder(LEN + 100);
Random r = new Random(99);
while (sb.length() < LEN) {
sb.append(r.nextInt());
sb.append(" xyz foo");
if (r.nextBoolean()) {
sb.append(" and \"bar\"");
} else if (r.nextBoolean()) {
sb.append(" [whatever].... ");
} else {
// Let's try some more 'exotic' chars
sb.append(" UTF-8-fu: try this {\u00E2/\u0BF8/\uA123!} (look funny?)");
}
if (r.nextBoolean()) {
if (r.nextBoolean()) {
sb.append('\n');
} else if (r.nextBoolean()) {
sb.append('\r');
} else {
sb.append("\r\n");
}
}
}
final String VALUE = sb.toString();
JsonFactory jf = new JsonFactory();
// Let's use real generator to get json done right
StringWriter sw = new StringWriter(LEN + (LEN >> 2));
JsonGenerator jg = jf.createGenerator(sw);
jg.writeStartObject();
jg.writeFieldName("doc");
jg.writeString(VALUE);
jg.writeEndObject();
jg.close();
final String DOC = sw.toString();
for (int type = 0; type < 3; ++type) {
JsonParser jp;
switch (type) {
default:
jp = jf.createParser(DOC.getBytes("UTF-8"));
break;
case 1:
jp = jf.createParser(DOC);
break;
case 2: // NEW: let's also exercise UTF-32...
jp = jf.createParser(encodeInUTF32BE(DOC));
break;
}
assertToken(JsonToken.START_OBJECT, jp.nextToken());
assertToken(JsonToken.FIELD_NAME, jp.nextToken());
assertEquals("doc", jp.getCurrentName());
assertToken(JsonToken.VALUE_STRING, jp.nextToken());
String act = getAndVerifyText(jp);
if (act.length() != VALUE.length()) {
fail("Expected length "+VALUE.length()+", got "+act.length());
}
if (!act.equals(VALUE)) {
fail("Long text differs");
}
// should still know the field name
assertEquals("doc", jp.getCurrentName());
assertToken(JsonToken.END_OBJECT, jp.nextToken());
assertNull(jp.nextToken());
jp.close();
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
public void testObjectCount() throws Exception
{
final String EXP = "{\"x\":{\"a\":1,\"b\":2(2)}(1)}";
final JsonFactory jf = new JsonFactory();
for (int i = 0; i < 2; ++i) {
boolean useBytes = (i > 0);
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
StringWriter sw = new StringWriter();
JsonGenerator gen = useBytes ? jf.createJsonGenerator(bytes)
: jf.createJsonGenerator(sw);
gen.setPrettyPrinter(new CountPrinter());
gen.writeStartObject();
gen.writeFieldName("x");
gen.writeStartObject();
gen.writeNumberField("a", 1);
gen.writeNumberField("b", 2);
gen.writeEndObject();
gen.writeEndObject();
gen.close();
String json = useBytes ? bytes.toString("UTF-8") : sw.toString();
assertEquals(EXP, json);
}
}
#location 24
#vulnerability type RESOURCE_LEAK | #fixed code
public void testObjectCount() throws Exception
{
final String EXP = "{\"x\":{\"a\":1,\"b\":2(2)}(1)}";
final JsonFactory jf = new JsonFactory();
for (int i = 0; i < 2; ++i) {
boolean useBytes = (i > 0);
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
StringWriter sw = new StringWriter();
JsonGenerator gen = useBytes ? jf.createGenerator(bytes)
: jf.createGenerator(sw);
gen.setPrettyPrinter(new CountPrinter());
gen.writeStartObject();
gen.writeFieldName("x");
gen.writeStartObject();
gen.writeNumberField("a", 1);
gen.writeNumberField("b", 2);
gen.writeEndObject();
gen.writeEndObject();
gen.close();
String json = useBytes ? bytes.toString("UTF-8") : sw.toString();
assertEquals(EXP, json);
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
public void testConfigDefaults() throws IOException
{
JsonFactory jf = new JsonFactory();
JsonGenerator jg = jf.createJsonGenerator(new StringWriter());
assertFalse(jg.isEnabled(JsonGenerator.Feature.WRITE_NUMBERS_AS_STRINGS));
}
#location 5
#vulnerability type RESOURCE_LEAK | #fixed code
public void testConfigDefaults() throws IOException
{
JsonFactory jf = new JsonFactory();
JsonGenerator jg = jf.createGenerator(new StringWriter());
assertFalse(jg.isEnabled(JsonGenerator.Feature.WRITE_NUMBERS_AS_STRINGS));
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
private void _testStreaming(boolean useBytes) throws IOException
{
final int[] SIZES = new int[] {
1, 2, 3, 4, 5, 6,
7, 8, 12,
100, 350, 1900, 6000, 19000, 65000,
139000
};
JsonFactory jsonFactory = new JsonFactory();
final ByteArrayOutputStream bytes = new ByteArrayOutputStream();
StringWriter chars = null;
for (int size : SIZES) {
byte[] data = _generateData(size);
JsonGenerator g;
if (useBytes) {
bytes.reset();
g = jsonFactory.createJsonGenerator(bytes, JsonEncoding.UTF8);
} else {
chars = new StringWriter();
g = jsonFactory.createJsonGenerator(chars);
}
g.writeStartObject();
g.writeFieldName("b");
g.writeBinary(data);
g.writeEndObject();
g.close();
// and verify
JsonParser p;
if (useBytes) {
p = jsonFactory.createJsonParser(bytes.toByteArray());
} else {
p = jsonFactory.createJsonParser(chars.toString());
}
assertToken(JsonToken.START_OBJECT, p.nextToken());
assertToken(JsonToken.FIELD_NAME, p.nextToken());
assertEquals("b", p.getCurrentName());
assertToken(JsonToken.VALUE_STRING, p.nextToken());
ByteArrayOutputStream result = new ByteArrayOutputStream(size);
int gotten = p.readBinaryValue(result);
assertEquals(size, gotten);
assertArrayEquals(data, result.toByteArray());
assertToken(JsonToken.END_OBJECT, p.nextToken());
assertNull(p.nextToken());
p.close();
}
}
#location 23
#vulnerability type RESOURCE_LEAK | #fixed code
private void _testStreaming(boolean useBytes) throws IOException
{
final int[] SIZES = new int[] {
1, 2, 3, 4, 5, 6,
7, 8, 12,
100, 350, 1900, 6000, 19000, 65000,
139000
};
JsonFactory jsonFactory = new JsonFactory();
final ByteArrayOutputStream bytes = new ByteArrayOutputStream();
StringWriter chars = null;
for (int size : SIZES) {
byte[] data = _generateData(size);
JsonGenerator g;
if (useBytes) {
bytes.reset();
g = jsonFactory.createGenerator(bytes, JsonEncoding.UTF8);
} else {
chars = new StringWriter();
g = jsonFactory.createGenerator(chars);
}
g.writeStartObject();
g.writeFieldName("b");
g.writeBinary(data);
g.writeEndObject();
g.close();
// and verify
JsonParser p;
if (useBytes) {
p = jsonFactory.createParser(bytes.toByteArray());
} else {
p = jsonFactory.createParser(chars.toString());
}
assertToken(JsonToken.START_OBJECT, p.nextToken());
assertToken(JsonToken.FIELD_NAME, p.nextToken());
assertEquals("b", p.getCurrentName());
assertToken(JsonToken.VALUE_STRING, p.nextToken());
ByteArrayOutputStream result = new ByteArrayOutputStream(size);
int gotten = p.readBinaryValue(result);
assertEquals(size, gotten);
assertArrayEquals(data, result.toByteArray());
assertToken(JsonToken.END_OBJECT, p.nextToken());
assertNull(p.nextToken());
p.close();
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
public void testLongerObjects() throws Exception
{
JsonFactory jf = new JsonFactory();
for (int i = 0; i < 2; ++i) {
boolean useChars = (i == 0);
JsonGenerator jgen;
ByteArrayOutputStream bout = new ByteArrayOutputStream(200);
if (useChars) {
jgen = jf.createJsonGenerator(new OutputStreamWriter(bout, "UTF-8"));
} else {
jgen = jf.createJsonGenerator(bout, JsonEncoding.UTF8);
}
jgen.writeStartObject();
for (int rounds = 0; rounds < 1500; ++rounds) {
for (int letter = 'a'; letter <= 'z'; ++letter) {
for (int index = 0; index < 20; ++index) {
String name;
if (letter > 'f') {
name = "X"+letter+index;
} else if (letter > 'p') {
name = ""+letter+index;
} else {
name = "__"+index+letter;
}
jgen.writeFieldName(name);
jgen.writeNumber(index-1);
}
jgen.writeRaw('\n');
}
}
jgen.writeEndObject();
jgen.close();
byte[] json = bout.toByteArray();
JsonParser jp = jf.createJsonParser(json);
assertToken(JsonToken.START_OBJECT, jp.nextToken());
for (int rounds = 0; rounds < 1500; ++rounds) {
for (int letter = 'a'; letter <= 'z'; ++letter) {
for (int index = 0; index < 20; ++index) {
assertToken(JsonToken.FIELD_NAME, jp.nextToken());
String name;
if (letter > 'f') {
name = "X"+letter+index;
} else if (letter > 'p') {
name = ""+letter+index;
} else {
name = "__"+index+letter;
}
assertEquals(name, jp.getCurrentName());
assertToken(JsonToken.VALUE_NUMBER_INT, jp.nextToken());
assertEquals(index-1, jp.getIntValue());
}
}
}
assertToken(JsonToken.END_OBJECT, jp.nextToken());
}
}
#location 12
#vulnerability type RESOURCE_LEAK | #fixed code
public void testLongerObjects() throws Exception
{
JsonFactory jf = new JsonFactory();
for (int i = 0; i < 2; ++i) {
boolean useChars = (i == 0);
JsonGenerator jgen;
ByteArrayOutputStream bout = new ByteArrayOutputStream(200);
if (useChars) {
jgen = jf.createGenerator(new OutputStreamWriter(bout, "UTF-8"));
} else {
jgen = jf.createGenerator(bout, JsonEncoding.UTF8);
}
jgen.writeStartObject();
for (int rounds = 0; rounds < 1500; ++rounds) {
for (int letter = 'a'; letter <= 'z'; ++letter) {
for (int index = 0; index < 20; ++index) {
String name;
if (letter > 'f') {
name = "X"+letter+index;
} else if (letter > 'p') {
name = ""+letter+index;
} else {
name = "__"+index+letter;
}
jgen.writeFieldName(name);
jgen.writeNumber(index-1);
}
jgen.writeRaw('\n');
}
}
jgen.writeEndObject();
jgen.close();
byte[] json = bout.toByteArray();
JsonParser jp = jf.createParser(json);
assertToken(JsonToken.START_OBJECT, jp.nextToken());
for (int rounds = 0; rounds < 1500; ++rounds) {
for (int letter = 'a'; letter <= 'z'; ++letter) {
for (int index = 0; index < 20; ++index) {
assertToken(JsonToken.FIELD_NAME, jp.nextToken());
String name;
if (letter > 'f') {
name = "X"+letter+index;
} else if (letter > 'p') {
name = ""+letter+index;
} else {
name = "__"+index+letter;
}
assertEquals(name, jp.getCurrentName());
assertToken(JsonToken.VALUE_NUMBER_INT, jp.nextToken());
assertEquals(index-1, jp.getIntValue());
}
}
}
assertToken(JsonToken.END_OBJECT, jp.nextToken());
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
public void testCopyArrayTokens()
throws IOException
{
JsonFactory jf = new JsonFactory();
final String DOC = "123 [ 1, null, [ false ] ]";
JsonParser jp = jf.createJsonParser(new StringReader(DOC));
StringWriter sw = new StringWriter();
JsonGenerator gen = jf.createJsonGenerator(sw);
assertToken(JsonToken.VALUE_NUMBER_INT, jp.nextToken());
gen.copyCurrentEvent(jp);
// should not change parser state:
assertToken(JsonToken.VALUE_NUMBER_INT, jp.getCurrentToken());
assertEquals(123, jp.getIntValue());
// And then let's copy the array
assertToken(JsonToken.START_ARRAY, jp.nextToken());
gen.copyCurrentStructure(jp);
// which will advance parser to matching close Array
assertToken(JsonToken.END_ARRAY, jp.getCurrentToken());
jp.close();
gen.close();
assertEquals("123 [1,null,[false]]", sw.toString());
}
#location 25
#vulnerability type RESOURCE_LEAK | #fixed code
public void testCopyArrayTokens()
throws IOException
{
JsonFactory jf = new JsonFactory();
final String DOC = "123 [ 1, null, [ false ] ]";
JsonParser jp = jf.createParser(new StringReader(DOC));
StringWriter sw = new StringWriter();
JsonGenerator gen = jf.createGenerator(sw);
assertToken(JsonToken.VALUE_NUMBER_INT, jp.nextToken());
gen.copyCurrentEvent(jp);
// should not change parser state:
assertToken(JsonToken.VALUE_NUMBER_INT, jp.getCurrentToken());
assertEquals(123, jp.getIntValue());
// And then let's copy the array
assertToken(JsonToken.START_ARRAY, jp.nextToken());
gen.copyCurrentStructure(jp);
// which will advance parser to matching close Array
assertToken(JsonToken.END_ARRAY, jp.getCurrentToken());
jp.close();
gen.close();
assertEquals("123 [1,null,[false]]", sw.toString());
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
private void _testEscapeCustom(boolean useStream) throws Exception
{
JsonFactory f = new JsonFactory().setCharacterEscapes(new MyEscapes());
final String STR_IN = "[abcd/"+((char) TWO_BYTE_ESCAPED)+"/"+((char) THREE_BYTE_ESCAPED)+"]";
final String STR_OUT = "[\\A\\u0062c[D]/"+TWO_BYTE_ESCAPED_STRING+"/"+THREE_BYTE_ESCAPED_STRING+"]";
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
JsonGenerator jgen;
// First: output normally; should not add escaping
if (useStream) {
jgen = f.createJsonGenerator(bytes, JsonEncoding.UTF8);
} else {
jgen = f.createJsonGenerator(new OutputStreamWriter(bytes, "UTF-8"));
}
jgen.writeStartObject();
jgen.writeStringField(STR_IN, STR_IN);
jgen.writeEndObject();
jgen.close();
String json = bytes.toString("UTF-8");
assertEquals("{"+quote(STR_OUT)+":"+quote(STR_OUT)+"}", json);
}
#location 14
#vulnerability type RESOURCE_LEAK | #fixed code
private void _testEscapeCustom(boolean useStream) throws Exception
{
JsonFactory f = new JsonFactory().setCharacterEscapes(new MyEscapes());
final String STR_IN = "[abcd/"+((char) TWO_BYTE_ESCAPED)+"/"+((char) THREE_BYTE_ESCAPED)+"]";
final String STR_OUT = "[\\A\\u0062c[D]/"+TWO_BYTE_ESCAPED_STRING+"/"+THREE_BYTE_ESCAPED_STRING+"]";
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
JsonGenerator jgen;
// First: output normally; should not add escaping
if (useStream) {
jgen = f.createGenerator(bytes, JsonEncoding.UTF8);
} else {
jgen = f.createGenerator(new OutputStreamWriter(bytes, "UTF-8"));
}
jgen.writeStartObject();
jgen.writeStringField(STR_IN, STR_IN);
jgen.writeEndObject();
jgen.close();
String json = bytes.toString("UTF-8");
assertEquals("{"+quote(STR_OUT)+":"+quote(STR_OUT)+"}", json);
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
private void _testSurrogates(JsonFactory f, boolean checkText) throws IOException
{
byte[] json = "{\"text\":\"\uD83D\uDE03\"}".getBytes("UTF-8");
// first
JsonParser jp = f.createJsonParser(json);
assertToken(JsonToken.START_OBJECT, jp.nextToken());
assertToken(JsonToken.FIELD_NAME, jp.nextToken());
if (checkText) {
assertEquals("text", jp.getText());
}
assertToken(JsonToken.VALUE_STRING, jp.nextToken());
if (checkText) {
assertEquals("\uD83D\uDE03", jp.getText());
}
assertToken(JsonToken.END_OBJECT, jp.nextToken());
}
#location 15
#vulnerability type RESOURCE_LEAK | #fixed code
private void _testSurrogates(JsonFactory f, boolean checkText) throws IOException
{
byte[] json = "{\"text\":\"\uD83D\uDE03\"}".getBytes("UTF-8");
// first
JsonParser jp = f.createParser(json);
assertToken(JsonToken.START_OBJECT, jp.nextToken());
assertToken(JsonToken.FIELD_NAME, jp.nextToken());
if (checkText) {
assertEquals("text", jp.getText());
}
assertToken(JsonToken.VALUE_STRING, jp.nextToken());
if (checkText) {
assertEquals("\uD83D\uDE03", jp.getText());
}
assertToken(JsonToken.END_OBJECT, jp.nextToken());
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
public void testRawValue() throws IOException
{
JsonFactory jf = new JsonFactory();
StringWriter sw = new StringWriter();
JsonGenerator gen = jf.createJsonGenerator(sw);
gen.writeStartArray();
gen.writeRawValue("7");
gen.writeRawValue("[ null ]");
gen.writeRawValue("false");
gen.writeEndArray();
gen.close();
JsonParser jp = createParserUsingReader(sw.toString());
assertToken(JsonToken.START_ARRAY, jp.nextToken());
assertToken(JsonToken.VALUE_NUMBER_INT, jp.nextToken());
assertEquals(7, jp.getIntValue());
assertToken(JsonToken.START_ARRAY, jp.nextToken());
assertToken(JsonToken.VALUE_NULL, jp.nextToken());
assertToken(JsonToken.END_ARRAY, jp.nextToken());
assertToken(JsonToken.VALUE_FALSE, jp.nextToken());
assertToken(JsonToken.END_ARRAY, jp.nextToken());
jp.close();
}
#location 25
#vulnerability type RESOURCE_LEAK | #fixed code
public void testRawValue() throws IOException
{
JsonFactory jf = new JsonFactory();
StringWriter sw = new StringWriter();
JsonGenerator gen = jf.createGenerator(sw);
gen.writeStartArray();
gen.writeRawValue("7");
gen.writeRawValue("[ null ]");
gen.writeRawValue("false");
gen.writeEndArray();
gen.close();
JsonParser jp = createParserUsingReader(sw.toString());
assertToken(JsonToken.START_ARRAY, jp.nextToken());
assertToken(JsonToken.VALUE_NUMBER_INT, jp.nextToken());
assertEquals(7, jp.getIntValue());
assertToken(JsonToken.START_ARRAY, jp.nextToken());
assertToken(JsonToken.VALUE_NULL, jp.nextToken());
assertToken(JsonToken.END_ARRAY, jp.nextToken());
assertToken(JsonToken.VALUE_FALSE, jp.nextToken());
assertToken(JsonToken.END_ARRAY, jp.nextToken());
jp.close();
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
public void testConvenienceMethodsWithNulls()
throws Exception
{
StringWriter sw = new StringWriter();
JsonGenerator gen = new JsonFactory().createJsonGenerator(sw);
gen.writeStartObject();
gen.writeStringField("str", null);
gen.writeNumberField("num", null);
gen.writeObjectField("obj", null);
gen.writeEndObject();
gen.close();
String docStr = sw.toString();
JsonParser jp = createParserUsingReader(docStr);
assertEquals(JsonToken.START_OBJECT, jp.nextToken());
assertEquals(JsonToken.FIELD_NAME, jp.nextToken());
assertEquals("str", jp.getCurrentName());
assertEquals(JsonToken.VALUE_NULL, jp.nextToken());
assertEquals(JsonToken.FIELD_NAME, jp.nextToken());
assertEquals("num", jp.getCurrentName());
assertEquals(JsonToken.VALUE_NULL, jp.nextToken());
assertEquals(JsonToken.FIELD_NAME, jp.nextToken());
assertEquals("obj", jp.getCurrentName());
assertEquals(JsonToken.VALUE_NULL, jp.nextToken());
assertEquals(JsonToken.END_OBJECT, jp.nextToken());
}
#location 32
#vulnerability type RESOURCE_LEAK | #fixed code
public void testConvenienceMethodsWithNulls()
throws Exception
{
StringWriter sw = new StringWriter();
JsonGenerator gen = new JsonFactory().createGenerator(sw);
gen.writeStartObject();
gen.writeStringField("str", null);
gen.writeNumberField("num", null);
gen.writeObjectField("obj", null);
gen.writeEndObject();
gen.close();
String docStr = sw.toString();
JsonParser jp = createParserUsingReader(docStr);
assertEquals(JsonToken.START_OBJECT, jp.nextToken());
assertEquals(JsonToken.FIELD_NAME, jp.nextToken());
assertEquals("str", jp.getCurrentName());
assertEquals(JsonToken.VALUE_NULL, jp.nextToken());
assertEquals(JsonToken.FIELD_NAME, jp.nextToken());
assertEquals("num", jp.getCurrentName());
assertEquals(JsonToken.VALUE_NULL, jp.nextToken());
assertEquals(JsonToken.FIELD_NAME, jp.nextToken());
assertEquals("obj", jp.getCurrentName());
assertEquals(JsonToken.VALUE_NULL, jp.nextToken());
assertEquals(JsonToken.END_OBJECT, jp.nextToken());
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
public static Version versionFor(Class<?> cls)
{
InputStream in;
Version version = null;
try {
in = cls.getResourceAsStream(VERSION_FILE);
if (in != null) {
try {
BufferedReader br = new BufferedReader(new InputStreamReader(in, "UTF-8"));
String groupStr = null, artifactStr = null;
String versionStr = br.readLine();
if (versionStr != null) {
groupStr = br.readLine();
if (groupStr != null) {
groupStr = groupStr.trim();
artifactStr = br.readLine();
if (artifactStr != null) {
artifactStr = artifactStr.trim();
}
}
}
version = parseVersion(versionStr, groupStr, artifactStr);
} finally {
try {
in.close();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}
} catch (IOException e) { }
return (version == null) ? Version.unknownVersion() : version;
}
#location 6
#vulnerability type RESOURCE_LEAK | #fixed code
public static Version versionFor(Class<?> cls)
{
final InputStream in = cls.getResourceAsStream(VERSION_FILE);
if (in == null)
return Version.unknownVersion();
try {
InputStreamReader reader = new InputStreamReader(in, "UTF-8");
try {
return doReadVersion(reader);
} finally {
try {
reader.close();
} catch (IOException ignored) {
}
}
} catch (UnsupportedEncodingException e) {
return Version.unknownVersion();
} finally {
try {
in.close();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
private void _testFieldNameQuoting(JsonFactory jf, boolean quoted)
throws IOException
{
StringWriter sw = new StringWriter();
JsonGenerator jg = jf.createJsonGenerator(sw);
jg.writeStartObject();
jg.writeFieldName("foo");
jg.writeNumber(1);
jg.writeEndObject();
jg.close();
String result = sw.toString();
if (quoted) {
assertEquals("{\"foo\":1}", result);
} else {
assertEquals("{foo:1}", result);
}
}
#location 17
#vulnerability type RESOURCE_LEAK | #fixed code
private void _testFieldNameQuoting(JsonFactory jf, boolean quoted)
throws IOException
{
StringWriter sw = new StringWriter();
JsonGenerator jg = jf.createGenerator(sw);
jg.writeStartObject();
jg.writeFieldName("foo");
jg.writeNumber(1);
jg.writeEndObject();
jg.close();
String result = sw.toString();
if (quoted) {
assertEquals("{\"foo\":1}", result);
} else {
assertEquals("{foo:1}", result);
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
private void updateGC() {
if (perfDataSupport) {
ygcCount.update((Long) ygcCountCounter.getValue());
ygcTimeMills.update(perfData.tickToMills(ygcTimeCounter));
fullgcCount.update((Long) fullGcCountCounter.getValue());
fullgcTimeMills.update(perfData.tickToMills(fullgcTimeCounter));
} else if (isJmxStateOk()) {
try {
ygcCount.update(jmxClient.getYoungCollector().getCollectionCount());
ygcTimeMills.update(jmxClient.getYoungCollector().getCollectionTime());
fullgcCount.update(jmxClient.getFullCollector().getCollectionCount());
fullgcTimeMills.update(jmxClient.getFullCollector().getCollectionTime());
} catch (Exception e) {
handleJmxFetchDataError(e);
}
}
}
#location 11
#vulnerability type NULL_DEREFERENCE | #fixed code
private void updateGC() {
if (perfDataSupport) {
ygcCount.update((Long) ygcCountCounter.getValue());
ygcTimeMills.update(perfData.tickToMills(ygcTimeCounter));
fullgcCount.update((Long) fullGcCountCounter.getValue());
fullgcTimeMills.update(perfData.tickToMills(fullgcTimeCounter));
} else if (isJmxStateOk()) {
try {
ygcCount.update(jmxClient.getGarbageCollectorManager().getYoungCollector().getCollectionCount());
ygcTimeMills.update(jmxClient.getGarbageCollectorManager().getYoungCollector().getCollectionTime());
fullgcCount.update(jmxClient.getGarbageCollectorManager().getFullCollector().getCollectionCount());
fullgcTimeMills.update(jmxClient.getGarbageCollectorManager().getFullCollector().getCollectionTime());
} catch (Exception e) {
handleJmxFetchDataError(e);
}
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
public void run() {
log.info("ProactiveGcTask starting, oldGenOccupancyFraction:" + oldGenOccupancyFraction + ", datetime: "
+ new Date());
try {
oldMemoryPool = getOldMemoryPool();
long maxOldBytes = getMemoryPoolMaxOrCommitted(oldMemoryPool);
long oldUsedBytes = oldMemoryPool.getUsage().getUsed();
log.info(String.format("max old gen: %.2f MB, used old gen: %.2f MB, available old gen: %.2f MB.",
SizeUnit.BYTES.toMegaBytes(maxOldBytes), SizeUnit.BYTES.toMegaBytes(oldUsedBytes),
SizeUnit.BYTES.toMegaBytes(maxOldBytes - oldUsedBytes)));
if (needTriggerGc(maxOldBytes, oldUsedBytes, oldGenOccupancyFraction)) {
preGc();
doGc();
postGc();
}
} catch (Exception e) {
log.error(e.getMessage(), e);
} finally {
if (!scheduler.isShutdown()) { // reschedule this task
try {
scheduler.reschedule(this);
} catch (Exception e) {
log.error(e.getMessage(), e);
}
}
}
}
#location 6
#vulnerability type NULL_DEREFERENCE | #fixed code
public void run() {
logger.info("ProactiveGcTask starting, oldGenOccupancyFraction:" + oldGenOccupancyFraction);
try {
long usedOldBytes = logOldGenStatus();
if (needTriggerGc(maxOldBytes, usedOldBytes, oldGenOccupancyFraction)) {
preGc();
doGc();
postGc();
}
} catch (Exception e) {
logger.error(e.getMessage(), e);
} finally {
scheduler.reschedule(this);
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
private void init() throws IOException {
try {
perfData = PerfData.connect(Integer.parseInt(pid));
perfDataSupport = true;
} catch (Exception e) {
System.err.println("PerfData not support");
}
vmArgs = Utils.join(jmxClient.getRuntimeMXBean().getInputArguments(), " ");
Map<String, String> systemProperties_ = jmxClient.getRuntimeMXBean().getSystemProperties();
osUser = systemProperties_.get("user.name");
jvmVersion = systemProperties_.get("java.version");
jvmMajorVersion = getJavaMajorVersion();
permGenName = jmxClient.getMemoryPoolManager().getPermMemoryPool().getName().toLowerCase();
threadCpuTimeSupported = jmxClient.getThreadMXBean().isThreadCpuTimeSupported();
threadMemoryAllocatedSupported = jmxClient.getThreadMXBean().isThreadAllocatedMemorySupported();
processors = jmxClient.getOperatingSystemMXBean().getAvailableProcessors();
isLinux = jmxClient.getOperatingSystemMXBean().getName().toLowerCase(Locale.US).contains("linux");
}
#location 16
#vulnerability type NULL_DEREFERENCE | #fixed code
private void init() throws IOException {
try {
perfData = PerfData.connect(Integer.parseInt(pid));
perfDataSupport = true;
} catch (Exception e) {
System.err.println("PerfData not support");
}
if (perfDataSupport) {
vmArgs = (String) perfData.findCounter("java.rt.vmArgs").getValue();
} else {
vmArgs = Utils.join(jmxClient.getRuntimeMXBean().getInputArguments(), " ");
}
Map<String, String> systemProperties_ = jmxClient.getRuntimeMXBean().getSystemProperties();
osUser = systemProperties_.get("user.name");
jvmVersion = systemProperties_.get("java.version");
jvmMajorVersion = getJavaMajorVersion();
permGenName = jvmMajorVersion >= 8 ? "metaspace" : "perm";
threadCpuTimeSupported = jmxClient.getThreadMXBean().isThreadCpuTimeSupported();
threadMemoryAllocatedSupported = jmxClient.getThreadMXBean().isThreadAllocatedMemorySupported();
processors = jmxClient.getOperatingSystemMXBean().getAvailableProcessors();
isLinux = jmxClient.getOperatingSystemMXBean().getName().toLowerCase(Locale.US).contains("linux");
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
public void run() {
while (true) {
try {
String command = new BufferedReader(new InputStreamReader(System.in)).readLine().trim();
if (command.equals("t")) {
vjtop.setNeedForFurtherInput(true);
System.err.print(" Input TID for stack:");
String pidStr = new BufferedReader(new InputStreamReader(System.in)).readLine();
try {
long pid = Long.parseLong(pidStr);
view.printStack(pid);
} catch (NumberFormatException e) {
System.err.println(" Wrong number format");
}
//block the flush to let user see the result
Utils.sleep(10000);
vjtop.setNeedForFurtherInput(false);
} else if (command.equals("d")) {
vjtop.setNeedForFurtherInput(true);
System.err.print(
" Input number of Display Mode(1.cpu, 2.syscpu 3.total cpu 4.total syscpu 5.memory 6.total memory): ");
String mode = new BufferedReader(new InputStreamReader(System.in)).readLine();
switch (mode) {
case "1":
view.setMode(DetailMode.cpu);
break;
case "2":
view.setMode(DetailMode.syscpu);
break;
case "3":
view.setMode(DetailMode.totalcpu);
break;
case "4":
view.setMode(DetailMode.totalsyscpu);
break;
case "5":
view.setMode(DetailMode.memory);
break;
case "6":
view.setMode(DetailMode.totalmemory);
break;
default:
System.err.println(" Wrong option for display mode");
break;
}
System.err.println(" Display mode changed to " + view.getMode() + " for next flush");
vjtop.setNeedForFurtherInput(false);
} else if (command.equals("q")) {
view.exit();
mainThread.interrupt();
System.err.println(" Quit.");
return;
} else if (command.equals("h")) {
System.err.println(" t : print stack trace for the thread you choose");
System.err.println(" d : change threads display mode and ordering");
System.err.println(" q : quit");
System.err.println(" h : print help");
} else if (command.equals("")) {
} else {
System.err.println("Unkown command: " + command);
}
view.waitForCommand();
} catch (Exception e) {
}
}
}
#location 4
#vulnerability type RESOURCE_LEAK | #fixed code
public void run() {
while (true) {
try {
String command = reader.readLine().trim().toLowerCase();
if (command.equals("t")) {
printStacktrace();
} else if (command.equals("d")) {
changeDisplayMode();
} else if (command.equals("q")) {
app.exit();
return;
} else if (command.equalsIgnoreCase("h") || command.equalsIgnoreCase("help")) {
printHelp();
} else if (command.equals("")) {
} else {
tty.println("Unkown command: " + command);
printHelp();
}
tty.print(" Input command (h for help):");
} catch (Exception e) {
e.printStackTrace(tty);
}
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
private void updateGC() {
if (perfDataSupport) {
ygcCount.update((Long) ygcCountCounter.getValue());
ygcTimeMills.update(perfData.tickToMills(ygcTimeCounter));
fullgcCount.update((Long) fullGcCountCounter.getValue());
fullgcTimeMills.update(perfData.tickToMills(fullgcTimeCounter));
} else if (isJmxStateOk()) {
try {
ygcCount.update(jmxClient.getYoungCollector().getCollectionCount());
ygcTimeMills.update(jmxClient.getYoungCollector().getCollectionTime());
fullgcCount.update(jmxClient.getFullCollector().getCollectionCount());
fullgcTimeMills.update(jmxClient.getFullCollector().getCollectionTime());
} catch (Exception e) {
handleJmxFetchDataError(e);
}
}
}
#location 9
#vulnerability type NULL_DEREFERENCE | #fixed code
private void updateGC() {
if (perfDataSupport) {
ygcCount.update((Long) ygcCountCounter.getValue());
ygcTimeMills.update(perfData.tickToMills(ygcTimeCounter));
fullgcCount.update((Long) fullGcCountCounter.getValue());
fullgcTimeMills.update(perfData.tickToMills(fullgcTimeCounter));
} else if (isJmxStateOk()) {
try {
ygcCount.update(jmxClient.getGarbageCollectorManager().getYoungCollector().getCollectionCount());
ygcTimeMills.update(jmxClient.getGarbageCollectorManager().getYoungCollector().getCollectionTime());
fullgcCount.update(jmxClient.getGarbageCollectorManager().getFullCollector().getCollectionCount());
fullgcTimeMills.update(jmxClient.getGarbageCollectorManager().getFullCollector().getCollectionTime());
} catch (Exception e) {
handleJmxFetchDataError(e);
}
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
private void updateMemoryPool() throws IOException {
MemoryPoolMXBean survivorMemoryPool = jmxClient.getMemoryPoolManager().getSurvivorMemoryPool();
if (survivorMemoryPool != null) {
surUsedBytes = survivorMemoryPool.getUsage().getUsed();
surMaxBytes = getMemoryPoolMaxOrCommited(survivorMemoryPool);
}
edenUsedBytes = jmxClient.getMemoryPoolManager().getEdenMemoryPool().getUsage().getUsed();
edenMaxBytes = getMemoryPoolMaxOrCommited(jmxClient.getMemoryPoolManager().getEdenMemoryPool());
oldUsedBytes = jmxClient.getMemoryPoolManager().getOldMemoryPool().getUsage().getUsed();
oldMaxBytes = getMemoryPoolMaxOrCommited(jmxClient.getMemoryPoolManager().getOldMemoryPool());
permUsedBytes = jmxClient.getMemoryPoolManager().getPermMemoryPool().getUsage().getUsed();
permMaxBytes = getMemoryPoolMaxOrCommited(jmxClient.getMemoryPoolManager().getPermMemoryPool());
if (jvmMajorVersion >= 8) {
ccsUsedBytes = jmxClient.getMemoryPoolManager().getCompressedClassSpaceMemoryPool().getUsage().getUsed();
ccsMaxBytes = getMemoryPoolMaxOrCommited(jmxClient.getMemoryPoolManager()
.getCompressedClassSpaceMemoryPool());
}
codeCacheUsedBytes = jmxClient.getMemoryPoolManager().getCodeCacheMemoryPool().getUsage().getUsed();
codeCacheMaxBytes = getMemoryPoolMaxOrCommited(jmxClient.getMemoryPoolManager().getCodeCacheMemoryPool());
directUsedBytes = jmxClient.getBufferPoolManager().getDirectBufferPool().getMemoryUsed();
directMaxBytes = jmxClient.getBufferPoolManager().getDirectBufferPool().getTotalCapacity();
mapUsedBytes = jmxClient.getBufferPoolManager().getMappedBufferPool().getMemoryUsed();
mapMaxBytes = jmxClient.getBufferPoolManager().getMappedBufferPool().getTotalCapacity();
}
#location 8
#vulnerability type NULL_DEREFERENCE | #fixed code
private void updateMemoryPool() throws IOException {
JmxMemoryPoolManager memoryPoolManager = jmxClient.getMemoryPoolManager();
edenUsedBytes = memoryPoolManager.getEdenMemoryPool().getUsage().getUsed();
edenMaxBytes = getMemoryPoolMaxOrCommited(memoryPoolManager.getEdenMemoryPool());
MemoryPoolMXBean survivorMemoryPool = memoryPoolManager.getSurvivorMemoryPool();
if (survivorMemoryPool != null) {
surUsedBytes = survivorMemoryPool.getUsage().getUsed();
surMaxBytes = getMemoryPoolMaxOrCommited(survivorMemoryPool);
}
oldUsedBytes = memoryPoolManager.getOldMemoryPool().getUsage().getUsed();
oldMaxBytes = getMemoryPoolMaxOrCommited(memoryPoolManager.getOldMemoryPool());
permUsedBytes = memoryPoolManager.getPermMemoryPool().getUsage().getUsed();
permMaxBytes = getMemoryPoolMaxOrCommited(memoryPoolManager.getPermMemoryPool());
if (jvmMajorVersion >= 8) {
MemoryPoolMXBean compressedClassSpaceMemoryPool = memoryPoolManager.getCompressedClassSpaceMemoryPool();
if (compressedClassSpaceMemoryPool != null) {
ccsUsedBytes = compressedClassSpaceMemoryPool.getUsage().getUsed();
ccsMaxBytes = getMemoryPoolMaxOrCommited(compressedClassSpaceMemoryPool);
}
}
codeCacheUsedBytes = memoryPoolManager.getCodeCacheMemoryPool().getUsage().getUsed();
codeCacheMaxBytes = getMemoryPoolMaxOrCommited(memoryPoolManager.getCodeCacheMemoryPool());
directUsedBytes = jmxClient.getBufferPoolManager().getDirectBufferPool().getMemoryUsed();
directMaxBytes = jmxClient.getBufferPoolManager().getDirectBufferPool().getTotalCapacity();
mapUsedBytes = jmxClient.getBufferPoolManager().getMappedBufferPool().getMemoryUsed();
mapMaxBytes = jmxClient.getBufferPoolManager().getMappedBufferPool().getTotalCapacity();
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
private void printHelp() throws Exception {
tty.println(" t [tid]: print stack trace for the thread you choose");
tty.println(" a : list all thread's id and name");
tty.println(" m : change threads display mode and ordering");
tty.println(" i : change flush interval seconds");
tty.println(" l : change number of display threads");
tty.println(" q : quit");
tty.println(" h : print help");
app.preventFlush();
String command = waitForEnter();
app.continueFlush();
if (command.length() > 0) {
handleCommand(command);
}
}
#location 12
#vulnerability type NULL_DEREFERENCE | #fixed code
private void printHelp() throws Exception {
tty.println(" t [tid]: print stack trace for the thread you choose");
tty.println(" a : list all thread's id and name");
tty.println(" m : change threads display mode and ordering");
tty.println(" i [num]: change flush interval seconds");
tty.println(" l [num]: change number of display threads");
tty.println(" f [name]: set thread name filter");
tty.println(" q : quit");
tty.println(" h : print help");
app.preventFlush();
waitForEnter();
app.continueFlush();
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
private void init() throws IOException {
Map<String, Counter> perfCounters = null;
try {
perfData = PerfData.connect(Integer.parseInt(pid));
perfCounters = perfData.getCounters();
initPerfCounters(perfCounters);
perfDataSupport = true;
} catch (Throwable ignored) {
}
if (perfDataSupport) {
vmArgs = (String) perfCounters.get("java.rt.vmArgs").getValue();
} else {
vmArgs = Formats.join(jmxClient.getRuntimeMXBean().getInputArguments(), " ");
}
startTime = jmxClient.getRuntimeMXBean().getStartTime();
Map<String, String> taregetVMSystemProperties = jmxClient.getRuntimeMXBean().getSystemProperties();
osUser = taregetVMSystemProperties.get("user.name");
jvmVersion = taregetVMSystemProperties.get("java.version");
jvmMajorVersion = getJavaMajorVersion(jvmVersion);
permGenName = jvmMajorVersion >= 8 ? "metaspace" : "perm";
threadStackSize = 1024
* Long.parseLong(jmxClient.getHotSpotDiagnosticMXBean().getVMOption("ThreadStackSize").getValue());
maxDirectMemorySize = Long
.parseLong(jmxClient.getHotSpotDiagnosticMXBean().getVMOption("MaxDirectMemorySize").getValue());
maxDirectMemorySize = maxDirectMemorySize == 0 ? -1 : maxDirectMemorySize;
threadCpuTimeSupported = jmxClient.getThreadMXBean().isThreadCpuTimeSupported();
threadMemoryAllocatedSupported = jmxClient.getThreadMXBean().isThreadAllocatedMemorySupported();
processors = jmxClient.getOperatingSystemMXBean().getAvailableProcessors();
warningRule.updateProcessor(processors);
isLinux = System.getProperty("os.name").toLowerCase(Locale.US).contains("linux");
}
#location 6
#vulnerability type NULL_DEREFERENCE | #fixed code
private void init() throws IOException {
Map<String, Counter> perfCounters = null;
try {
perfData = PerfData.connect(Integer.parseInt(pid));
perfCounters = perfData.getAllCounters();
initPerfCounters(perfCounters);
perfDataSupport = true;
} catch (Throwable ignored) {
}
if (perfDataSupport) {
vmArgs = (String) perfCounters.get("java.rt.vmArgs").getValue();
} else {
vmArgs = Formats.join(jmxClient.getRuntimeMXBean().getInputArguments(), " ");
}
startTime = jmxClient.getRuntimeMXBean().getStartTime();
Map<String, String> taregetVMSystemProperties = jmxClient.getRuntimeMXBean().getSystemProperties();
osUser = taregetVMSystemProperties.get("user.name");
jvmVersion = taregetVMSystemProperties.get("java.version");
jvmMajorVersion = getJavaMajorVersion(jvmVersion);
permGenName = jvmMajorVersion >= 8 ? "metaspace" : "perm";
threadStackSize = 1024
* Long.parseLong(jmxClient.getHotSpotDiagnosticMXBean().getVMOption("ThreadStackSize").getValue());
maxDirectMemorySize = Long
.parseLong(jmxClient.getHotSpotDiagnosticMXBean().getVMOption("MaxDirectMemorySize").getValue());
maxDirectMemorySize = maxDirectMemorySize == 0 ? -1 : maxDirectMemorySize;
threadCpuTimeSupported = jmxClient.getThreadMXBean().isThreadCpuTimeSupported();
threadMemoryAllocatedSupported = jmxClient.getThreadMXBean().isThreadAllocatedMemorySupported();
processors = jmxClient.getOperatingSystemMXBean().getAvailableProcessors();
warningRule.updateProcessor(processors);
isLinux = System.getProperty("os.name").toLowerCase(Locale.US).contains("linux");
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
private void updateGC() {
if (perfDataSupport) {
ygcCount.update(ygcCountCounter.longValue());
ygcTimeMills.update(perfData.tickToMills(ygcTimeCounter));
if (fullGcCountCounter != null) {
fullgcCount.update(fullGcCountCounter.longValue());
fullgcTimeMills.update(perfData.tickToMills(fullgcTimeCounter));
}
} else if (isJmxStateOk()) {
try {
ygcCount.update(jmxClient.getGarbageCollectorManager().getYoungCollector().getCollectionCount());
ygcTimeMills.update(jmxClient.getGarbageCollectorManager().getYoungCollector().getCollectionTime());
if (jmxClient.getGarbageCollectorManager().getFullCollector() != null) {
fullgcCount.update(jmxClient.getGarbageCollectorManager().getFullCollector().getCollectionCount());
fullgcTimeMills
.update(jmxClient.getGarbageCollectorManager().getFullCollector().getCollectionTime());
}
} catch (Exception e) {
handleJmxFetchDataError(e);
}
}
}
#location 11
#vulnerability type NULL_DEREFERENCE | #fixed code
private void updateGC() {
if (perfDataSupport) {
ygcCount.update(ygcCountCounter.longValue());
ygcTimeMills.update(perfData.tickToMills(ygcTimeCounter));
if (fullGcCountCounter != null) {
fullgcCount.update(fullGcCountCounter.longValue());
fullgcTimeMills.update(perfData.tickToMills(fullgcTimeCounter));
}
} else if (isJmxStateOk()) {
try {
JmxGarbageCollectorManager gcManager = jmxClient.getGarbageCollectorManager();
GarbageCollectorMXBean ygcMXBean = gcManager.getYoungCollector();
ygcStrategy = gcManager.getYgcStrategy();
ygcCount.update(ygcMXBean.getCollectionCount());
ygcTimeMills.update(ygcMXBean.getCollectionTime());
GarbageCollectorMXBean fullgcMXBean = gcManager.getFullCollector();
if (fullgcMXBean != null) {
fullgcStrategy = gcManager.getFgcStrategy();
fullgcCount.update(fullgcMXBean.getCollectionCount());
fullgcTimeMills.update(fullgcMXBean.getCollectionTime());
}
} catch (Exception e) {
handleJmxFetchDataError(e);
}
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
public static void main(String[] args) {
try {
// 1. create option parser
OptionParser parser = createOptionParser();
OptionSet optionSet = parser.parse(args);
if (optionSet.has("help")) {
printHelper(parser);
System.exit(0);
}
// 2. create vminfo
String pid = parsePid(parser, optionSet);
VMInfo vminfo = VMInfo.processNewVM(pid);
if (vminfo.state != VMInfoState.ATTACHED) {
System.out.println("\nERROR: Could not attach to process, please find reason in README\n");
return;
}
// 3. create view
VMDetailView.DetailMode displayMode = parseDisplayMode(optionSet);
Integer width = null;
if (optionSet.hasArgument("width")) {
width = (Integer) optionSet.valueOf("width");
}
VMDetailView view = new VMDetailView(vminfo, displayMode, width);
if (optionSet.hasArgument("limit")) {
Integer limit = (Integer) optionSet.valueOf("limit");
view.threadLimit = limit;
}
// 4. create main application
VJTop app = new VJTop();
app.mainThread = Thread.currentThread();
app.view = view;
Integer interval = DEFAULT_INTERVAL;
if (optionSet.hasArgument("interval")) {
interval = (Integer) (optionSet.valueOf("interval"));
if (interval < 1) {
throw new IllegalArgumentException("Interval cannot be set below 1.0");
}
}
app.interval = interval;
if (optionSet.hasArgument("n")) {
Integer iterations = (Integer) optionSet.valueOf("n");
app.maxIterations = iterations;
}
// 5. start thread to get user input
Thread interactiveThread = new Thread(new InteractiveTask(app), "InteractiveThread");
interactiveThread.setDaemon(true);
interactiveThread.start();
// 6. run app
app.run(view);
} catch (Exception e) {
e.printStackTrace(System.out);
System.out.flush();
}
}
#location 56
#vulnerability type RESOURCE_LEAK | #fixed code
public static void main(String[] args) {
try {
// 1. create option parser
OptionParser parser = createOptionParser();
OptionSet optionSet = parser.parse(args);
if (optionSet.has("help")) {
printHelper(parser);
System.exit(0);
}
// 2. create vminfo
String pid = parsePid(parser, optionSet);
VMInfo vminfo = VMInfo.processNewVM(pid);
if (vminfo.state != VMInfoState.ATTACHED) {
System.out.println("\nERROR: Could not attach to process, please find reason in README\n");
return;
}
// 3. create view
VMDetailView.DetailMode displayMode = parseDisplayMode(optionSet);
Integer width = null;
if (optionSet.hasArgument("width")) {
width = (Integer) optionSet.valueOf("width");
}
VMDetailView view = new VMDetailView(vminfo, displayMode, width);
if (optionSet.hasArgument("limit")) {
Integer limit = (Integer) optionSet.valueOf("limit");
view.threadLimit = limit;
}
// 4. create main application
VJTop app = new VJTop();
app.mainThread = Thread.currentThread();
app.view = view;
Integer interval = DEFAULT_INTERVAL;
if (optionSet.hasArgument("interval")) {
interval = (Integer) (optionSet.valueOf("interval"));
if (interval < 1) {
throw new IllegalArgumentException("Interval cannot be set below 1.0");
}
}
app.interval = interval;
if (optionSet.hasArgument("n")) {
Integer iterations = (Integer) optionSet.valueOf("n");
app.maxIterations = iterations;
}
// 5. start thread to get user input
if (app.maxIterations == -1) {
InteractiveTask task = new InteractiveTask(app);
if (task.inputEnabled()) {
view.displayCommandHints = true;
Thread interactiveThread = new Thread(task, "InteractiveThread");
interactiveThread.setDaemon(true);
interactiveThread.start();
}
}
// 6. run app
app.run(view);
} catch (Exception e) {
e.printStackTrace(System.out);
System.out.flush();
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
private void changeDisplayMode() {
app.preventFlush();
String mode = readLine(
" Input number of Display Mode(1.cpu, 2.syscpu 3.total cpu 4.total syscpu 5.memory 6.total memory, current "
+ app.view.threadInfoMode + "): ");
ThreadInfoMode detailMode = ThreadInfoMode.parse(mode);
if (detailMode == null) {
tty.println(" Wrong option for display mode(1-6)");
} else if (detailMode == app.view.threadInfoMode) {
tty.println(" Nothing be changed");
} else {
if (app.view.threadInfoMode.isCpuMode != detailMode.isCpuMode) {
app.view.switchCpuAndMemory();
app.view.threadInfoMode = detailMode;
tty.println(" Display mode changed to " + app.view.threadInfoMode + " for next flush");
app.interruptSleep();
} else {
app.view.threadInfoMode = detailMode;
tty.println(" Display mode changed to " + app.view.threadInfoMode + " for next flush("
+ app.nextFlushTime() + "s later)");
}
}
app.continueFlush();
}
#location 7
#vulnerability type NULL_DEREFERENCE | #fixed code
private void changeDisplayMode() {
app.preventFlush();
String mode = readLine(" Input Display Mode(cpu, syscpu, totalcpu, totalsyscpu, memory, totalmemory, current "
+ app.view.threadInfoMode + "): ");
ThreadInfoMode detailMode = ThreadInfoMode.valueOf(mode);
if (detailMode == null) {
tty.println(" Wrong option for display mode");
} else if (detailMode == app.view.threadInfoMode) {
tty.println(" Nothing be changed");
} else {
if (app.view.threadInfoMode.isCpuMode != detailMode.isCpuMode) {
app.view.switchCpuAndMemory();
app.view.threadInfoMode = detailMode;
tty.println(" Display mode changed to " + app.view.threadInfoMode + " for next flush");
app.interruptSleep();
} else {
app.view.threadInfoMode = detailMode;
tty.println(" Display mode changed to " + app.view.threadInfoMode + " for next flush("
+ app.nextFlushTime() + "s later)");
}
}
app.continueFlush();
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
public Double getFGCT() throws Exception {
return Double.parseDouble(getAttribute(fgcCollector, COLLECTION_TIME_ATTRIBUTE).toString()) / 1000;
}
#location 2
#vulnerability type NULL_DEREFERENCE | #fixed code
public Double getFGCT() throws Exception {
if (fgcCollector == null) {
return 0.0;
}
return Double.parseDouble(getAttribute(fgcCollector, COLLECTION_TIME_ATTRIBUTE).toString()) / 1000;
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
private void updateMemoryPool() throws IOException {
JmxMemoryPoolManager memoryPoolManager = jmxClient.getMemoryPoolManager();
eden = new Usage(memoryPoolManager.getEdenMemoryPool().getUsage());
old = new Usage(memoryPoolManager.getOldMemoryPool().getUsage());
warning.updateOld(old.max);
MemoryPoolMXBean survivorMemoryPool = memoryPoolManager.getSurvivorMemoryPool();
if (survivorMemoryPool != null) {
sur = new Usage(survivorMemoryPool.getUsage());
} else {
sur = new Usage();
}
perm = new Usage(memoryPoolManager.getPermMemoryPool().getUsage());
warning.updatePerm(perm.max);
if (jvmMajorVersion >= 8) {
MemoryPoolMXBean compressedClassSpaceMemoryPool = memoryPoolManager.getCompressedClassSpaceMemoryPool();
if (compressedClassSpaceMemoryPool != null) {
ccs = new Usage(compressedClassSpaceMemoryPool.getUsage());
}
}
codeCache = new Usage(memoryPoolManager.getCodeCacheMemoryPool().getUsage());
direct = new Usage(jmxClient.getBufferPoolManager().getDirectBufferPool());
map = new Usage(jmxClient.getBufferPoolManager().getMappedBufferPool());
}
#location 27
#vulnerability type NULL_DEREFERENCE | #fixed code
private void updateMemoryPool() throws IOException {
JmxMemoryPoolManager memoryPoolManager = jmxClient.getMemoryPoolManager();
eden = new Usage(memoryPoolManager.getEdenMemoryPool().getUsage());
old = new Usage(memoryPoolManager.getOldMemoryPool().getUsage());
warning.updateOld(old.max);
MemoryPoolMXBean survivorMemoryPool = memoryPoolManager.getSurvivorMemoryPool();
if (survivorMemoryPool != null) {
sur = new Usage(survivorMemoryPool.getUsage());
} else {
sur = new Usage();
}
perm = new Usage(memoryPoolManager.getPermMemoryPool().getUsage());
warning.updatePerm(perm.max);
if (jvmMajorVersion >= 8) {
MemoryPoolMXBean compressedClassSpaceMemoryPool = memoryPoolManager.getCompressedClassSpaceMemoryPool();
if (compressedClassSpaceMemoryPool != null) {
ccs = new Usage(compressedClassSpaceMemoryPool.getUsage());
}
}
codeCache = new Usage(memoryPoolManager.getCodeCacheMemoryPool().getUsage());
direct = new Usage(jmxClient.getBufferPoolManager().getDirectBufferPool().getMemoryUsed(),
jmxClient.getBufferPoolManager().getDirectBufferPool().getTotalCapacity(), maxDirectMemorySize);
// 取巧用法,将count 放入无用的max中。
map = new Usage(jmxClient.getBufferPoolManager().getMappedBufferPool().getMemoryUsed(),
jmxClient.getBufferPoolManager().getMappedBufferPool().getTotalCapacity(),
jmxClient.getBufferPoolManager().getMappedBufferPool().getCount());
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Override
public void run() {
while (true) {
try {
String command = readLine();
handleCommand(command);
if (!app.view.shouldExit()) {
tty.print(" Input command (h for help):");
}
} catch (Exception e) {
e.printStackTrace(tty);
}
}
}
#location 6
#vulnerability type NULL_DEREFERENCE | #fixed code
@Override
public void run() {
// background执行时,console为Null
if (console == null) {
return;
}
while (true) {
try {
String command = readLine("");
if (command == null) {
break;
}
handleCommand(command);
if (!app.view.shouldExit()) {
tty.print(" Input command (h for help):");
}
} catch (Exception e) {
e.printStackTrace(tty);
}
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
private void updateMemoryPool() {
if (!isJmxStateOk()) {
return;
}
try {
JmxMemoryPoolManager memoryPoolManager = jmxClient.getMemoryPoolManager();
eden = new Usage(memoryPoolManager.getEdenMemoryPool().getUsage());
old = new Usage(memoryPoolManager.getOldMemoryPool().getUsage());
warningRule.updateOld(old.max);
MemoryPoolMXBean survivorMemoryPool = memoryPoolManager.getSurvivorMemoryPool();
if (survivorMemoryPool != null) {
sur = new Usage(survivorMemoryPool.getUsage());
} else {
sur = new Usage();
}
perm = new Usage(memoryPoolManager.getPermMemoryPool().getUsage());
warningRule.updatePerm(perm.max);
if (jvmMajorVersion >= 8) {
MemoryPoolMXBean compressedClassSpaceMemoryPool = memoryPoolManager.getCompressedClassSpaceMemoryPool();
if (compressedClassSpaceMemoryPool != null) {
ccs = new Usage(compressedClassSpaceMemoryPool.getUsage());
} else {
ccs = new Usage();
}
}
codeCache = new Usage(memoryPoolManager.getCodeCacheMemoryPool().getUsage());
direct = new Usage(jmxClient.getBufferPoolManager().getDirectBufferPoolUsed(),
jmxClient.getBufferPoolManager().getDirectBufferPoolCapacity(), maxDirectMemorySize);
// 取巧用法,将count 放入无用的max中。
long mapUsed = jmxClient.getBufferPoolManager().getMappedBufferPoolUsed();
map = new Usage(mapUsed, jmxClient.getBufferPoolManager().getMappedBufferPoolCapacity(),
mapUsed == 0 ? 0 : jmxClient.getBufferPoolManager().getMappedBufferPoolCount());
} catch (Exception e) {
handleJmxFetchDataError(e);
}
}
#location 8
#vulnerability type NULL_DEREFERENCE | #fixed code
private void updateMemoryPool() {
if (!isJmxStateOk()) {
return;
}
try {
JmxMemoryPoolManager memoryPoolManager = jmxClient.getMemoryPoolManager();
MemoryPoolMXBean edenMXBean = memoryPoolManager.getEdenMemoryPool();
if (edenMXBean != null) {
eden = new Usage(edenMXBean.getUsage());
} else {
eden = new Usage();
}
MemoryPoolMXBean oldMXBean = memoryPoolManager.getOldMemoryPool();
if (oldMXBean != null) {
old = new Usage(oldMXBean.getUsage());
warningRule.updateOld(old.max);
} else {
old = new Usage();
}
MemoryPoolMXBean survivorMemoryPool = memoryPoolManager.getSurvivorMemoryPool();
if (survivorMemoryPool != null) {
sur = new Usage(survivorMemoryPool.getUsage());
} else {
sur = new Usage();
}
MemoryPoolMXBean permMXBean = memoryPoolManager.getPermMemoryPool();
if (permMXBean != null) {
perm = new Usage(permMXBean.getUsage());
warningRule.updatePerm(perm.max);
} else {
perm = new Usage();
}
if (jvmMajorVersion >= 8) {
MemoryPoolMXBean compressedClassSpaceMemoryPool = memoryPoolManager.getCompressedClassSpaceMemoryPool();
if (compressedClassSpaceMemoryPool != null) {
ccs = new Usage(compressedClassSpaceMemoryPool.getUsage());
} else {
ccs = new Usage();
}
}
MemoryPoolMXBean memoryPoolMXBean = memoryPoolManager.getCodeCacheMemoryPool();
if (memoryPoolMXBean != null) {
codeCache = new Usage(memoryPoolMXBean.getUsage());
} else {
codeCache = new Usage();
}
direct = new Usage(jmxClient.getBufferPoolManager().getDirectBufferPoolUsed(),
jmxClient.getBufferPoolManager().getDirectBufferPoolCapacity(), maxDirectMemorySize);
// 取巧用法,将count 放入无用的max中。
long mapUsed = jmxClient.getBufferPoolManager().getMappedBufferPoolUsed();
map = new Usage(mapUsed, jmxClient.getBufferPoolManager().getMappedBufferPoolCapacity(),
mapUsed == 0 ? 0 : jmxClient.getBufferPoolManager().getMappedBufferPoolCount());
} catch (Exception e) {
handleJmxFetchDataError(e);
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
private static void clearTerminal() {
if (System.getProperty("os.name").contains("Windows")) {
// hack
System.out.printf("%n%n%n%n%n%n%n%n%n%n%n%n%n%n%n%n%n%n%n%n%n%n%n%n%n%n%n%n%n%n%n");
} else if (System.getProperty("vjtop.altClear") != null) {
System.out.print('\f');
} else {
System.out.print(CLEAR_TERMINAL_ANSI_CMD);
}
}
#location 2
#vulnerability type NULL_DEREFERENCE | #fixed code
private static void clearTerminal() {
if (Utils.isWindows) {
System.out.printf("%n%n%n%n%n%n%n%n%n%n%n%n%n%n%n%n%n%n%n%n%n%n%n%n%n%n%n%n%n%n%n");
} else {
System.out.print(CLEAR_TERMINAL_ANSI_CMD);
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
public void run() {
while (true) {
try {
String command = new BufferedReader(new InputStreamReader(System.in)).readLine().trim();
if (command.equals("t")) {
vjtop.setNeedForFurtherInput(true);
System.err.print(" Input TID for stack:");
String pidStr = new BufferedReader(new InputStreamReader(System.in)).readLine();
try {
long pid = Long.parseLong(pidStr);
view.printStack(pid);
} catch (NumberFormatException e) {
System.err.println(" Wrong number format");
}
//block the flush to let user see the result
Utils.sleep(10000);
vjtop.setNeedForFurtherInput(false);
} else if (command.equals("d")) {
vjtop.setNeedForFurtherInput(true);
System.err.print(
" Input number of Display Mode(1.cpu, 2.syscpu 3.total cpu 4.total syscpu 5.memory 6.total memory): ");
String mode = new BufferedReader(new InputStreamReader(System.in)).readLine();
switch (mode) {
case "1":
view.setMode(DetailMode.cpu);
break;
case "2":
view.setMode(DetailMode.syscpu);
break;
case "3":
view.setMode(DetailMode.totalcpu);
break;
case "4":
view.setMode(DetailMode.totalsyscpu);
break;
case "5":
view.setMode(DetailMode.memory);
break;
case "6":
view.setMode(DetailMode.totalmemory);
break;
default:
System.err.println(" Wrong option for display mode");
break;
}
System.err.println(" Display mode changed to " + view.getMode() + " for next flush");
vjtop.setNeedForFurtherInput(false);
} else if (command.equals("q")) {
view.exit();
mainThread.interrupt();
System.err.println(" Quit.");
return;
} else if (command.equals("h")) {
System.err.println(" t : print stack trace for the thread you choose");
System.err.println(" d : change threads display mode and ordering");
System.err.println(" q : quit");
System.err.println(" h : print help");
} else if (command.equals("")) {
} else {
System.err.println("Unkown command: " + command);
}
view.waitForCommand();
} catch (Exception e) {
}
}
}
#location 22
#vulnerability type RESOURCE_LEAK | #fixed code
public void run() {
while (true) {
try {
String command = reader.readLine().trim().toLowerCase();
if (command.equals("t")) {
printStacktrace();
} else if (command.equals("d")) {
changeDisplayMode();
} else if (command.equals("q")) {
app.exit();
return;
} else if (command.equalsIgnoreCase("h") || command.equalsIgnoreCase("help")) {
printHelp();
} else if (command.equals("")) {
} else {
tty.println("Unkown command: " + command);
printHelp();
}
tty.print(" Input command (h for help):");
} catch (Exception e) {
e.printStackTrace(tty);
}
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
public static void main(String[] args) throws Exception {
String path = "E:/btdata/bt_cumulation.txt";
BufferedReader br = new BufferedReader(new FileReader(path));
String line = null;
br.readLine();
PrintWriter pw = new PrintWriter("E:/btdata/bt_cumulation2.txt");
int i = 0;
while ((line = br.readLine()) != null) {
//System.out.println("'" + line + "',");
String[] ss = line.split(",");
String pin = ss[1];
pw.println(pin);
if (i++ % 10 == 0) {
pw.flush();
System.out.println(i);
}
}
br.close();
pw.close();
}
#location 17
#vulnerability type RESOURCE_LEAK | #fixed code
public static void main(String[] args) throws Exception {
BitSet bitSet = new BitSet(Integer.MAX_VALUE);//hashcode的值域
String url = "http://baidu.com/a";
int hashcode = url.hashCode() & 0x7FFFFFFF;
bitSet.set(hashcode);
System.out.println(bitSet.cardinality());//着色位的个数
System.out.println(bitSet.get(hashcode));//检测存在性
bitSet.clear(hashcode);//清除位数据
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
public static void main(String[] args) {
new ClassPathXmlApplicationContext("spring/rocketmq-consumer.xml");
}
#location 2
#vulnerability type RESOURCE_LEAK | #fixed code
public static void main(String[] args) {
ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("spring/rocketmq-consumer.xml");
context.registerShutdownHook();
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
public void process(Socket socket) {
SocketInputStream input = null;
OutputStream output = null;
try {
input = new SocketInputStream(socket.getInputStream(), 2048); // 1.读取套接字的输入流
output = socket.getOutputStream();
// create HttpRequest object and parse
request = new HttpRequest(input);
response = new HttpResponse(output);
response.setRequest(request);
response.setHeader("Server", "Mars Servlet Container");
parseRequest(input, output); // 解析请求行,即HTTP请求的第一行内容
parseHeaders(input); // 解析请求头
// request.addHeader(name, value); // 将请求头的名/值添加到request对象的HashMap请求头中
if (request.getUri().startsWith("/servlet/")) {
ServletProcessor processor = new ServletProcessor();
//processor.process(request, response);
} else {
StaticResourceProcessor processor = new StaticResourceProcessor();
//processor.process(request, response);
}
socket.close();
} catch (Exception e) {
e.printStackTrace();
}
}
#location 18
#vulnerability type NULL_DEREFERENCE | #fixed code
public void process(Socket socket) {
SocketInputStream input = null;
OutputStream output = null;
try {
input = new SocketInputStream(socket.getInputStream(), 2048); // 1.读取套接字的输入流
output = socket.getOutputStream();
// create HttpRequest object and parse
request = new HttpRequest(input);
response = new HttpResponse(output);
response.setRequest(request);
response.setHeader("Server", "Mars Servlet Container");
parseRequest(input, output); // 解析请求行,即HTTP请求的第一行内容
parseHeaders(input); // 解析请求头
if (request.getRequestURI().startsWith("/servlet/")) {
ServletProcessor processor = new ServletProcessor();
//processor.process(request, response);
} else {
StaticResourceProcessor processor = new StaticResourceProcessor();
//processor.process(request, response);
}
socket.close();
} catch (Exception e) {
e.printStackTrace();
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
public static void main(String[] args) {
ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext(new String[]{"META-INF/spring/dubbo-demo-consumer.xml"});
context.start();
// dubbo protocol
DemoService demoService = (DemoService) context.getBean("demoService"); // 获取远程服务代理
String hello = demoService.sayHello("dubbo"); // 执行远程方法
System.out.println(hello); // 显示调用结果
// hessian protocol 直连
DemoService demoService2 = (DemoService) context.getBean("demoService2");
String hello2 = demoService2.sayHello("hessian直连");
System.out.println(hello2);
// hessian protocol
DemoService demoService3 = (DemoService) context.getBean("demoService3");
String hello3 = demoService3.sayHello("hessian");
System.out.println(hello3);
// service group
DemoService demoService4 = (DemoService) context.getBean("demoService4");
String hello4 = demoService4.sayHello("group:new");
System.out.println(hello4);
// 回声测试可用性
EchoService echoService = (EchoService) demoService;
Object status = echoService.$echo("OK");
System.out.println("回声测试:" + status.equals("OK"));
}
#location 22
#vulnerability type RESOURCE_LEAK | #fixed code
public static void main(String[] args) throws Exception {
ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext(new String[]{"META-INF/spring/dubbo-demo-consumer.xml"});
context.start();
// 异步调用
async(context);
// dubbo protocol
DemoService demoService = (DemoService) context.getBean("demoService"); // 获取远程服务代理
String hello = demoService.sayHello("dubbo"); // 执行远程方法
System.out.println(hello); // 显示调用结果
// hessian protocol 直连
DemoService demoService2 = (DemoService) context.getBean("demoService2");
String hello2 = demoService2.sayHello("hessian直连");
System.out.println(hello2);
// hessian protocol
DemoService demoService3 = (DemoService) context.getBean("demoService3");
String hello3 = demoService3.sayHello("hessian");
System.out.println(hello3);
// service group
DemoService demoService4 = (DemoService) context.getBean("demoService4");
String hello4 = demoService4.sayHello("group:new");
System.out.println(hello4);
// 回声测试可用性
EchoService echoService = (EchoService) demoService;
Object status = echoService.$echo("OK");
System.out.println("回声测试:" + status.equals("OK"));
System.out.println("#######################ALL SUCCESSFUL##########################");
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
public static void main(String[] args) throws Exception {
String path = "E:/btdata/bt_cumulation.txt";
BufferedReader br = new BufferedReader(new FileReader(path));
String line = null;
br.readLine();
PrintWriter pw = new PrintWriter("E:/btdata/bt_cumulation2.txt");
int i = 0;
while ((line = br.readLine()) != null) {
//System.out.println("'" + line + "',");
String[] ss = line.split(",");
String pin = ss[1];
pw.println(pin);
if (i++ % 10 == 0) {
pw.flush();
System.out.println(i);
}
}
br.close();
pw.close();
}
#location 17
#vulnerability type RESOURCE_LEAK | #fixed code
public static void main(String[] args) throws Exception {
BitSet bitSet = new BitSet(Integer.MAX_VALUE);//hashcode的值域
String url = "http://baidu.com/a";
int hashcode = url.hashCode() & 0x7FFFFFFF;
bitSet.set(hashcode);
System.out.println(bitSet.cardinality());//着色位的个数
System.out.println(bitSet.get(hashcode));//检测存在性
bitSet.clear(hashcode);//清除位数据
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
public Vector4fc toImmutable() {
if (Proxy.DISABLE_PROXIES)
return this;
if (proxy != null)
return proxy;
synchronized (this) {
if (proxy != null)
return proxy;
proxy = Proxy.createVector4fc(this);
}
return proxy;
}
#location 5
#vulnerability type THREAD_SAFETY_VIOLATION | #fixed code
public Vector4fc toImmutable() {
if (Proxy.DISABLE_PROXIES)
return this;
return Proxy.createVector4fc(this);
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
public Quaternionfc toImmutable() {
if (Proxy.DISABLE_PROXIES)
return this;
if (proxy != null)
return proxy;
synchronized (this) {
if (proxy != null)
return proxy;
proxy = Proxy.createQuaternionfc(this);
}
return proxy;
}
#location 5
#vulnerability type THREAD_SAFETY_VIOLATION | #fixed code
public Quaternionfc toImmutable() {
if (Proxy.DISABLE_PROXIES)
return this;
return Proxy.createQuaternionfc(this);
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
public Vector3fc toImmutable() {
if (Proxy.DISABLE_PROXIES)
return this;
if (proxy != null)
return proxy;
synchronized (this) {
if (proxy != null)
return proxy;
proxy = Proxy.createVector3fc(this);
}
return proxy;
}
#location 5
#vulnerability type THREAD_SAFETY_VIOLATION | #fixed code
public Vector3fc toImmutable() {
if (Proxy.DISABLE_PROXIES)
return this;
return Proxy.createVector3fc(this);
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Override
public void handle(String target, HttpServletRequest request, HttpServletResponse response, boolean[] isHandled) {
long start = System.currentTimeMillis();
REQUEST_START_TIME.set(start);
String url = WebTools.getHomeUrl(request);
request.setAttribute("basePath", url);
request.setAttribute("baseWithHostPath", WebTools.getHomeUrlWithHostNotProtocol(request));
request.setAttribute("pageEndTag", PAGE_END_TAG);
String ext = null;
if (target.contains("/")) {
String name = target.substring(target.lastIndexOf('/'));
if (name.contains(".")) {
ext = name.substring(name.lastIndexOf('.'));
}
}
try {
AdminTokenVO adminTokenVO = new AdminTokenService().getAdminTokenVO(request);
final ResponseRenderPrintWriter responseRenderPrintWriter = new ResponseRenderPrintWriter(response.getOutputStream(), url, PAGE_END_TAG, request, response, adminTokenVO);
response = new HttpServletResponseWrapper(response) {
@Override
public PrintWriter getWriter() {
return responseRenderPrintWriter;
}
};
if (ext != null) {
if (!FORBIDDEN_URI_EXT_SET.contains(ext)) {
// 处理静态化文件,仅仅缓存文章页(变化较小)
if (target.endsWith(".html") && target.startsWith("/" + Constants.getArticleUri())) {
target = target.substring(0, target.lastIndexOf("."));
if (Constants.isStaticHtmlStatus() && adminTokenVO == null) {
String path = new String(request.getServletPath().getBytes(StandardCharsets.ISO_8859_1), StandardCharsets.UTF_8);
responseHtmlFile(target, request, response, isHandled, responseRenderPrintWriter, new File(CACHE_HTML_PATH + I18nUtil.getAcceptLanguage(request) + path));
} else {
this.next.handle(target, request, response, isHandled);
}
} else {
this.next.handle(target, request, response, isHandled);
}
} else {
//非法请求, 返回403
response.sendError(403);
}
} else {
//首页静态化
if ("/".equals(target) && Constants.isStaticHtmlStatus() && adminTokenVO == null) {
responseHtmlFile(target, request, response, isHandled, responseRenderPrintWriter, new File(CACHE_HTML_PATH + I18nUtil.getAcceptLanguage(request) + "/index.html"));
} else {
this.next.handle(target, request, response, isHandled);
}
}
} catch (Exception e) {
LOGGER.error("", e);
} finally {
I18nUtil.removeI18n();
//开发环境下面打印整个请求的耗时,便于优化代码
if (BlogBuildInfoUtil.isDev()) {
LOGGER.info("{} used time {}", request.getServletPath(), System.currentTimeMillis() - start);
}
//仅保留非静态资源请求或者是以 .html结尾的
if (ZrLogConfig.isInstalled() && !target.contains(".") || target.endsWith(".html")) {
RequestInfo requestInfo = new RequestInfo();
requestInfo.setIp(WebTools.getRealIp(request));
requestInfo.setUrl(url);
requestInfo.setUserAgent(request.getHeader("User-Agent"));
requestInfo.setRequestTime(System.currentTimeMillis());
requestInfo.setRequestUri(target);
RequestStatisticsPlugin.record(requestInfo);
}
}
REQUEST_START_TIME.remove();
}
#location 34
#vulnerability type RESOURCE_LEAK | #fixed code
@Override
public void handle(String target, HttpServletRequest request, HttpServletResponse response, boolean[] isHandled) {
long start = System.currentTimeMillis();
REQUEST_START_TIME.set(start);
String url = WebTools.getHomeUrl(request);
request.setAttribute("basePath", url);
request.setAttribute("baseWithHostPath", WebTools.getHomeUrlWithHostNotProtocol(request));
request.setAttribute("pageEndTag", PAGE_END_TAG);
String ext = null;
if (target.contains("/")) {
String name = target.substring(target.lastIndexOf('/'));
if (name.contains(".")) {
ext = name.substring(name.lastIndexOf('.'));
}
}
try {
AdminTokenVO adminTokenVO = new AdminTokenService().getAdminTokenVO(request);
final ResponseRenderPrintWriter responseRenderPrintWriter = new ResponseRenderPrintWriter(response.getOutputStream(), url, PAGE_END_TAG, request, response, adminTokenVO);
response = new MyHttpServletResponseWrapper(response,responseRenderPrintWriter);
if (ext != null) {
if (!FORBIDDEN_URI_EXT_SET.contains(ext)) {
// 处理静态化文件,仅仅缓存文章页(变化较小)
if (target.endsWith(".html") && target.startsWith("/" + Constants.getArticleUri())) {
target = target.substring(0, target.lastIndexOf("."));
if (Constants.isStaticHtmlStatus() && adminTokenVO == null) {
String path = new String(request.getServletPath().getBytes(StandardCharsets.ISO_8859_1), StandardCharsets.UTF_8);
responseHtmlFile(target, request, response, isHandled, responseRenderPrintWriter, new File(CACHE_HTML_PATH + I18nUtil.getAcceptLanguage(request) + path));
} else {
this.next.handle(target, request, response, isHandled);
}
} else {
this.next.handle(target, request, response, isHandled);
}
} else {
//非法请求, 返回403
response.sendError(403);
}
} else {
//首页静态化
if ("/".equals(target) && Constants.isStaticHtmlStatus() && adminTokenVO == null) {
responseHtmlFile(target, request, response, isHandled, responseRenderPrintWriter, new File(CACHE_HTML_PATH + I18nUtil.getAcceptLanguage(request) + "/index.html"));
} else {
this.next.handle(target, request, response, isHandled);
//JFinal, JsonRender 移除了 flush(),需要手动 flush,针对JFinal3.3 以后版本
response.getWriter().flush();
}
}
} catch (Exception e) {
LOGGER.error("", e);
} finally {
I18nUtil.removeI18n();
//开发环境下面打印整个请求的耗时,便于优化代码
if (BlogBuildInfoUtil.isDev()) {
LOGGER.info("{} used time {}", request.getServletPath(), System.currentTimeMillis() - start);
}
//仅保留非静态资源请求或者是以 .html结尾的
if (ZrLogConfig.isInstalled() && !target.contains(".") || target.endsWith(".html")) {
RequestInfo requestInfo = new RequestInfo();
requestInfo.setIp(WebTools.getRealIp(request));
requestInfo.setUrl(url);
requestInfo.setUserAgent(request.getHeader("User-Agent"));
requestInfo.setRequestTime(System.currentTimeMillis());
requestInfo.setRequestUri(target);
RequestStatisticsPlugin.record(requestInfo);
}
}
REQUEST_START_TIME.remove();
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Override
public void handle(String target, HttpServletRequest request, HttpServletResponse response, boolean[] isHandled) {
long start = System.currentTimeMillis();
REQUEST_START_TIME.set(start);
String url = WebTools.getHomeUrl(request);
request.setAttribute("basePath", url);
request.setAttribute("baseWithHostPath", WebTools.getHomeUrlWithHostNotProtocol(request));
request.setAttribute("pageEndTag", PAGE_END_TAG);
String ext = null;
if (target.contains("/")) {
String name = target.substring(target.lastIndexOf('/'));
if (name.contains(".")) {
ext = name.substring(name.lastIndexOf('.'));
}
}
try {
AdminTokenVO adminTokenVO = new AdminTokenService().getAdminTokenVO(request);
final ResponseRenderPrintWriter responseRenderPrintWriter = new ResponseRenderPrintWriter(response.getOutputStream(), url, PAGE_END_TAG, request, response, adminTokenVO);
response = new MyHttpServletResponseWrapper(response,responseRenderPrintWriter);
if (ext != null) {
if (!FORBIDDEN_URI_EXT_SET.contains(ext)) {
// 处理静态化文件,仅仅缓存文章页(变化较小)
if (target.endsWith(".html") && target.startsWith("/" + Constants.getArticleUri())) {
target = target.substring(0, target.lastIndexOf("."));
if (Constants.isStaticHtmlStatus() && adminTokenVO == null) {
String path = new String(request.getServletPath().getBytes(StandardCharsets.ISO_8859_1), StandardCharsets.UTF_8);
responseHtmlFile(target, request, response, isHandled, responseRenderPrintWriter, new File(CACHE_HTML_PATH + I18nUtil.getAcceptLanguage(request) + path));
} else {
this.next.handle(target, request, response, isHandled);
}
} else {
this.next.handle(target, request, response, isHandled);
}
} else {
//非法请求, 返回403
response.sendError(403);
}
} else {
//首页静态化
if ("/".equals(target) && Constants.isStaticHtmlStatus() && adminTokenVO == null) {
responseHtmlFile(target, request, response, isHandled, responseRenderPrintWriter, new File(CACHE_HTML_PATH + I18nUtil.getAcceptLanguage(request) + "/index.html"));
} else {
this.next.handle(target, request, response, isHandled);
//JFinal, JsonRender 移除了 flush(),需要手动 flush,针对JFinal3.3 以后版本
response.getWriter().flush();
}
}
} catch (Exception e) {
LOGGER.error("", e);
} finally {
I18nUtil.removeI18n();
//开发环境下面打印整个请求的耗时,便于优化代码
if (BlogBuildInfoUtil.isDev()) {
LOGGER.info("{} used time {}", request.getServletPath(), System.currentTimeMillis() - start);
}
//仅保留非静态资源请求或者是以 .html结尾的
if (ZrLogConfig.isInstalled() && !target.contains(".") || target.endsWith(".html")) {
RequestInfo requestInfo = new RequestInfo();
requestInfo.setIp(WebTools.getRealIp(request));
requestInfo.setUrl(url);
requestInfo.setUserAgent(request.getHeader("User-Agent"));
requestInfo.setRequestTime(System.currentTimeMillis());
requestInfo.setRequestUri(target);
RequestStatisticsPlugin.record(requestInfo);
}
}
REQUEST_START_TIME.remove();
}
#location 41
#vulnerability type RESOURCE_LEAK | #fixed code
@Override
public void handle(String target, HttpServletRequest request, HttpServletResponse response, boolean[] isHandled) {
long start = System.currentTimeMillis();
REQUEST_START_TIME.set(start);
String url = WebTools.getHomeUrl(request);
request.setAttribute("basePath", url);
request.setAttribute("baseWithHostPath", WebTools.getHomeUrlWithHostNotProtocol(request));
request.setAttribute("pageEndTag", PAGE_END_TAG);
String ext = null;
if (target.contains("/")) {
String name = target.substring(target.lastIndexOf('/'));
if (name.contains(".")) {
ext = name.substring(name.lastIndexOf('.'));
}
}
try {
AdminTokenVO adminTokenVO = new AdminTokenService().getAdminTokenVO(request);
final ResponseRenderPrintWriter responseRenderPrintWriter = new ResponseRenderPrintWriter(response.getOutputStream(), url, PAGE_END_TAG, request, response, adminTokenVO);
response = new MyHttpServletResponseWrapper(response, responseRenderPrintWriter);
if (ext != null) {
if (!FORBIDDEN_URI_EXT_SET.contains(ext)) {
if (catGeneratorHtml(target)) {
target = target.substring(0, target.lastIndexOf("."));
if (Constants.isStaticHtmlStatus() && adminTokenVO == null) {
String path = new String(request.getServletPath().getBytes(StandardCharsets.ISO_8859_1), StandardCharsets.UTF_8);
if ("/".equals(path)) {
path = INDEX_PAGE_HTML;
}
responseHtmlFile(target, request, response, isHandled, responseRenderPrintWriter, new File(CACHE_HTML_PATH + I18nUtil.getAcceptLanguage(request) + path));
} else {
this.next.handle(target, request, response, isHandled);
}
} else {
this.next.handle(target, request, response, isHandled);
}
} else {
//非法请求, 返回403
response.sendError(403);
}
} else {
//首页静态化
if ("/".equals(target) && Constants.isStaticHtmlStatus()) {
responseHtmlFile(target, request, response, isHandled, responseRenderPrintWriter, new File(CACHE_HTML_PATH + I18nUtil.getAcceptLanguage(request) + INDEX_PAGE_HTML));
} else {
this.next.handle(target, request, response, isHandled);
//JFinal, JsonRender 移除了 flush(),需要手动 flush,针对JFinal3.3 以后版本
response.getWriter().flush();
}
}
} catch (Exception e) {
LOGGER.error("", e);
} finally {
I18nUtil.removeI18n();
//开发环境下面打印整个请求的耗时,便于优化代码
if (BlogBuildInfoUtil.isDev()) {
LOGGER.info("{} used time {}", request.getServletPath(), System.currentTimeMillis() - start);
}
//仅保留非静态资源请求或者是以 .html结尾的
if (ZrLogConfig.isInstalled() && !target.contains(".") || target.endsWith(".html")) {
RequestInfo requestInfo = new RequestInfo();
requestInfo.setIp(WebTools.getRealIp(request));
requestInfo.setUrl(url);
requestInfo.setUserAgent(request.getHeader("User-Agent"));
requestInfo.setRequestTime(System.currentTimeMillis());
requestInfo.setRequestUri(target);
RequestStatisticsPlugin.record(requestInfo);
}
}
REQUEST_START_TIME.remove();
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Override
public void executeTask(IConversationMemory memory) {
IData<String> expressionsData = memory.getCurrentStep().getLatestData(EXPRESSIONS_PARSED_IDENTIFIER);
List<IData<Context>> contextDataList = memory.getCurrentStep().getAllData(CONTEXT_IDENTIFIER);
if (expressionsData == null && contextDataList == null) {
return;
}
List<Expression> aggregatedExpressions = new LinkedList<>();
if (contextDataList != null) {
aggregatedExpressions.addAll(extractContextProperties(contextDataList));
}
if (expressionsData != null) {
aggregatedExpressions.addAll(expressionProvider.parseExpressions(expressionsData.getResult()));
}
List<PropertyEntry> properties = propertyDisposer.extractProperties(aggregatedExpressions);
// see if action "CATCH_ANY_INPUT_AS_PROPERTY" was in the last step, so we take last user input into account
IConversationStepStack previousSteps = memory.getPreviousSteps();
if (previousSteps.size() > 0) {
IData<List<String>> actionsData = previousSteps.get(0).getLatestData(ACTIONS_IDENTIFIER);
List<String> actions = actionsData.getResult();
if (actions != null && actions.contains(CATCH_ANY_INPUT_AS_PROPERTY_ACTION)) {
IData<String> initialInputData = memory.getCurrentStep().getLatestData(INPUT_INITIAL_IDENTIFIER);
String initialInput = initialInputData.getResult();
if (!initialInput.isEmpty()) {
properties.add(new PropertyEntry(Collections.singletonList(EXPRESSION_MEANING_USER_INPUT), initialInput));
}
}
}
if (!properties.isEmpty()) {
memory.getCurrentStep().storeData(dataFactory.createData(PROPERTIES_EXTRACTED_IDENTIFIER, properties, true));
}
}
#location 26
#vulnerability type NULL_DEREFERENCE | #fixed code
@Override
public void executeTask(IConversationMemory memory) {
IData<String> expressionsData = memory.getCurrentStep().getLatestData(EXPRESSIONS_PARSED_IDENTIFIER);
List<IData<Context>> contextDataList = memory.getCurrentStep().getAllData(CONTEXT_IDENTIFIER);
if (expressionsData == null && contextDataList == null) {
return;
}
List<Expression> aggregatedExpressions = new LinkedList<>();
if (contextDataList != null) {
aggregatedExpressions.addAll(extractContextProperties(contextDataList));
}
if (expressionsData != null) {
aggregatedExpressions.addAll(expressionProvider.parseExpressions(expressionsData.getResult()));
}
List<PropertyEntry> properties = propertyDisposer.extractProperties(aggregatedExpressions);
// see if action "CATCH_ANY_INPUT_AS_PROPERTY" was in the last step, so we take last user input into account
IConversationStepStack previousSteps = memory.getPreviousSteps();
if (previousSteps.size() > 0) {
IData<List<String>> actionsData = previousSteps.get(0).getLatestData(ACTIONS_IDENTIFIER);
if (actionsData != null) {
List<String> actions = actionsData.getResult();
if (actions != null && actions.contains(CATCH_ANY_INPUT_AS_PROPERTY_ACTION)) {
IData<String> initialInputData = memory.getCurrentStep().getLatestData(INPUT_INITIAL_IDENTIFIER);
String initialInput = initialInputData.getResult();
if (!initialInput.isEmpty()) {
properties.add(new PropertyEntry(
Collections.singletonList(EXPRESSION_MEANING_USER_INPUT), initialInput));
}
}
}
}
if (!properties.isEmpty()) {
memory.getCurrentStep().storeData(dataFactory.createData(PROPERTIES_EXTRACTED_IDENTIFIER, properties, true));
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Test
public void serializeToJsonIteratorWithEmbeddedMap() throws Exception {
final Graph g = new TinkerGraph();
final Vertex v = g.addVertex();
final Map<String, Object> map = new HashMap<>();
map.put("x", 500);
map.put("y", "some");
final ArrayList friends = new ArrayList();
friends.add("x");
friends.add(5);
friends.add(map);
v.setProperty("friends", friends);
final Iterator iterable = g.query().vertices().iterator();
final String results = ResultSerializer.JSON_RESULT_SERIALIZER.serialize(iterable, new Context(msg, null, null, null));
final JSONObject json = new JSONObject(results);
assertNotNull(json);
assertEquals(msg.requestId.toString(), json.getString(ResultSerializer.JsonResultSerializer.TOKEN_REQUEST));
final JSONArray converted = json.getJSONArray(ResultSerializer.JsonResultSerializer.TOKEN_RESULT);
assertNotNull(converted);
assertEquals(1, converted.length());
final JSONObject vertexAsJson = converted.optJSONObject(0);
assertNotNull(vertexAsJson);
final JSONObject properties = vertexAsJson.optJSONObject(ResultSerializer.JsonResultSerializer.TOKEN_PROPERTIES);
assertNotNull(properties);
final JSONArray friendsProperty = properties.optJSONArray("friends");
assertNotNull(friendsProperty);
assertEquals(3, friends.size());
final String object1 = friendsProperty.getString(0);
assertEquals("x", object1);
final int object2 = friendsProperty.getInt(1);
assertEquals(5, object2);
final JSONObject object3 = friendsProperty.getJSONObject(2);
assertEquals(500, object3.getInt("x"));
assertEquals("some", object3.getString("y"));
}
#location 16
#vulnerability type RESOURCE_LEAK | #fixed code
@Test
public void serializeToJsonIteratorWithEmbeddedMap() throws Exception {
Graph g = TinkerGraph.open(null);
final Vertex v = g.addVertex();
final Map<String, Object> map = new HashMap<>();
map.put("x", 500);
map.put("y", "some");
final ArrayList friends = new ArrayList();
friends.add("x");
friends.add(5);
friends.add(map);
v.setProperty("friends", friends);
final Iterator iterable = g.query().vertices().iterator();
final String results = ResultSerializer.JSON_RESULT_SERIALIZER.serialize(iterable, new Context(msg, null, null, null));
final JSONObject json = new JSONObject(results);
assertNotNull(json);
assertEquals(msg.requestId.toString(), json.getString(ResultSerializer.JsonResultSerializer.TOKEN_REQUEST));
final JSONArray converted = json.getJSONArray(ResultSerializer.JsonResultSerializer.TOKEN_RESULT);
assertNotNull(converted);
assertEquals(1, converted.length());
final JSONObject vertexAsJson = converted.optJSONObject(0);
assertNotNull(vertexAsJson);
final JSONObject properties = vertexAsJson.optJSONObject(ResultSerializer.JsonResultSerializer.TOKEN_PROPERTIES);
assertNotNull(properties);
final JSONArray friendsProperty = properties.optJSONArray("friends");
assertNotNull(friendsProperty);
assertEquals(3, friends.size());
final String object1 = friendsProperty.getString(0);
assertEquals("x", object1);
final int object2 = friendsProperty.getInt(1);
assertEquals(5, object2);
final JSONObject object3 = friendsProperty.getJSONObject(2);
assertEquals(500, object3.getInt("x"));
assertEquals("some", object3.getString("y"));
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Test
public void testGremlinOLAP() throws Exception {
Graph g = TinkerFactory.createClassic();
ComputeResult result =
g.compute().program(GremlinVertexProgram.create().gremlin(() -> (Gremlin)
//Gremlin.of().out("created").in("created").property("name"))
Gremlin.of().as("x").outE().inV().loop("x", o -> o.getLoops() < 2).value("name").map(s -> s.toString().length()).path())
.build())
.submit().get();
/////////// GREMLIN REPL LOOK
System.out.println("gremlin> " + result.getGraphMemory().<Supplier>get("gremlinPipeline").get());
StreamFactory.stream(g.query().vertices()).forEach(v -> {
final GremlinTracker tracker = result.getVertexMemory().<GremlinTracker>getProperty(v, GremlinVertexProgram.GREMLIN_TRACKER).get();
tracker.getDoneGraphHolders().forEach((a, b) -> Stream.generate(() -> 1).limit(b.size()).forEach(t -> System.out.println("==>" + a)));
tracker.getDoneObjectHolders().forEach((a, b) -> Stream.generate(() -> 1).limit(b.size()).forEach(t -> System.out.println("==>" + a)));
});
}
#location 14
#vulnerability type RESOURCE_LEAK | #fixed code
@Test
public void testGremlinOLAP() throws Exception {
Graph g = TinkerFactory.createClassic();
ComputeResult result =
g.compute().program(GremlinVertexProgram.create().gremlin(() -> (Gremlin)
//Gremlin.of().out("created").in("created").value("name").map(o -> o.toString().length()))
Gremlin.of().out().out().property("name").value().path())
//Gremlin.of().as("x").outE().inV().loop("x", o -> o.getLoops() < 2).value("name").map(s -> s.toString().length()).path())
.build())
.submit().get();
/////////// GREMLIN REPL LOOK
if (result.getGraphMemory().get(GremlinVertexProgram.TRACK_PATHS)) {
System.out.println("gremlin> " + result.getGraphMemory().<Supplier>get("gremlinPipeline").get());
StreamFactory.stream(g.query().vertices()).forEach(v -> {
final GremlinPaths tracker = result.getVertexMemory().<GremlinPaths>getProperty(v, GremlinVertexProgram.GREMLIN_TRACKER).get();
tracker.getDoneGraphTracks().forEach((a, b) -> Stream.generate(() -> 1).limit(((List) b).size()).forEach(t -> System.out.println("==>" + a)));
tracker.getDoneObjectTracks().forEach((a, b) -> Stream.generate(() -> 1).limit(((List) b).size()).forEach(t -> System.out.println("==>" + a)));
});
} else {
System.out.println("gremlin> " + result.getGraphMemory().<Supplier>get("gremlinPipeline").get());
StreamFactory.stream(g.query().vertices()).forEach(v -> {
final GremlinCounter tracker = result.getVertexMemory().<GremlinCounter>getProperty(v, GremlinVertexProgram.GREMLIN_TRACKER).get();
tracker.getDoneGraphTracks().forEach((a, b) -> Stream.generate(() -> 1).limit(b).forEach(t -> System.out.println("==>" + a)));
tracker.getDoneObjectTracks().forEach((a, b) -> Stream.generate(() -> 1).limit(b).forEach(t -> System.out.println("==>" + a)));
});
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
public void testTinkerGraph() {
TinkerGraph g = new TinkerGraph();
g.createIndex("name", Vertex.class);
Vertex marko = g.addVertex(TinkerProperty.make("name", "marko", "age", 33));
Vertex stephen = g.addVertex(TinkerProperty.make("name", "stephen", "id", 12));
marko.addEdge("knows", stephen);
System.out.println(g.query().has("name", Compare.EQUAL, "marko").vertices());
System.out.println(marko.query().direction(Direction.OUT).labels("knows", "workedWith").vertices());
}
#location 9
#vulnerability type RESOURCE_LEAK | #fixed code
public void testTinkerGraph() {
TinkerGraph g = new TinkerGraph();
g.createIndex("name", Vertex.class);
Vertex marko = g.addVertex(TinkerProperty.make("name", "marko", "age", 33, "blah", "bloop"));
Vertex stephen = g.addVertex(TinkerProperty.make("name", "stephen", "id", 12, "blah", "bloop"));
Random r = new Random();
Stream.generate(()->g.addVertex(TinkerProperty.make("blah",r.nextInt()))).limit(100000).count();
assertEquals(g.vertices.size(), 100002);
marko.addEdge("knows", stephen);
System.out.println(g.query().has("name", Compare.EQUAL, "marko").vertices());
System.out.println(marko.query().direction(Direction.OUT).labels("knows", "workedWith").vertices());
g.createIndex("blah", Vertex.class);
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Test
public void serializeToJsonIteratorWithEmbeddedMap() throws Exception {
Graph g = TinkerGraph.open(Optional.empty());
final Vertex v = g.addVertex();
final Map<String, Object> map = new HashMap<>();
map.put("x", 500);
map.put("y", "some");
final ArrayList friends = new ArrayList();
friends.add("x");
friends.add(5);
friends.add(map);
v.setProperty("friends", friends);
final Iterator iterable = g.query().vertices().iterator();
final String results = ResultSerializer.JSON_RESULT_SERIALIZER.serialize(iterable, new Context(msg, null, null, null, null));
final JSONObject json = new JSONObject(results);
assertNotNull(json);
assertEquals(msg.requestId.toString(), json.getString(ResultSerializer.JsonResultSerializer.TOKEN_REQUEST));
final JSONArray converted = json.getJSONArray(ResultSerializer.JsonResultSerializer.TOKEN_RESULT);
assertNotNull(converted);
assertEquals(1, converted.length());
final JSONObject vertexAsJson = converted.optJSONObject(0);
assertNotNull(vertexAsJson);
final JSONObject properties = vertexAsJson.optJSONObject(ResultSerializer.JsonResultSerializer.TOKEN_PROPERTIES);
assertNotNull(properties);
final JSONArray friendsProperty = properties.optJSONArray("friends");
assertNotNull(friendsProperty);
assertEquals(3, friends.size());
final String object1 = friendsProperty.getString(0);
assertEquals("x", object1);
final int object2 = friendsProperty.getInt(1);
assertEquals(5, object2);
final JSONObject object3 = friendsProperty.getJSONObject(2);
assertEquals(500, object3.getInt("x"));
assertEquals("some", object3.getString("y"));
}
#location 16
#vulnerability type RESOURCE_LEAK | #fixed code
@Test
public void serializeToJsonIteratorWithEmbeddedMap() throws Exception {
final Graph g = TinkerGraph.open();
final Vertex v = g.addVertex();
final Map<String, Object> map = new HashMap<>();
map.put("x", 500);
map.put("y", "some");
final ArrayList friends = new ArrayList();
friends.add("x");
friends.add(5);
friends.add(map);
v.setProperty("friends", friends);
final Iterator iterable = g.query().vertices().iterator();
final String results = ResultSerializer.JSON_RESULT_SERIALIZER.serialize(iterable, new Context(msg, null, null, null, null));
final JSONObject json = new JSONObject(results);
assertNotNull(json);
assertEquals(msg.requestId.toString(), json.getString(ResultSerializer.JsonResultSerializer.TOKEN_REQUEST));
final JSONArray converted = json.getJSONArray(ResultSerializer.JsonResultSerializer.TOKEN_RESULT);
assertNotNull(converted);
assertEquals(1, converted.length());
final JSONObject vertexAsJson = converted.optJSONObject(0);
assertNotNull(vertexAsJson);
final JSONObject properties = vertexAsJson.optJSONObject(ResultSerializer.JsonResultSerializer.TOKEN_PROPERTIES);
assertNotNull(properties);
final JSONArray friendsProperty = properties.optJSONObject("friends").optJSONArray(ResultSerializer.JsonResultSerializer.TOKEN_VALUE);
assertNotNull(friendsProperty);
assertEquals(3, friends.size());
final String object1 = friendsProperty.getString(0);
assertEquals("x", object1);
final int object2 = friendsProperty.getInt(1);
assertEquals(5, object2);
final JSONObject object3 = friendsProperty.getJSONObject(2);
assertEquals(500, object3.getInt("x"));
assertEquals("some", object3.getString("y"));
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
private FunctionThatThrows<RequestMessage, Object> select(final RequestMessage message, final GremlinServer.Graphs graphs) {
final Bindings bindings = new SimpleBindings();
bindings.putAll(extractBindingsFromMessage(message));
if (message.optionalSessionId().isPresent()) {
// an in session request...throw in a dummy graph instance for now..............................
final Graph g = TinkerFactory.createClassic();
bindings.put("g", g);
final GremlinSession session = getGremlinSession(message.sessionId, bindings);
if (logger.isDebugEnabled()) logger.debug("Using session {} ScriptEngine to process {}", message.sessionId, message);
return s -> session.eval(message.<String>optionalArgs(RequestMessage.FIELD_GREMLIN).get(), bindings);
} else {
// a sessionless request
if (logger.isDebugEnabled()) logger.debug("Using shared ScriptEngine to process {}", message);
return s -> {
// put all the preconfigured graphs on the bindings
bindings.putAll(graphs.getGraphs());
try {
// do a safety cleanup of previous transaction...if any
graphs.rollbackAll();
final Object o = sharedScriptEngine.eval(message.<String>optionalArgs(RequestMessage.FIELD_GREMLIN).get(), bindings);
graphs.commitAll();
return o;
} catch (ScriptException ex) {
// todo: gotta work on error handling for failed scripts..........
graphs.rollbackAll();
throw ex;
}
};
}
}
#location 12
#vulnerability type RESOURCE_LEAK | #fixed code
private FunctionThatThrows<RequestMessage, Object> select(final RequestMessage message, final GremlinServer.Graphs graphs) {
final Bindings bindings = new SimpleBindings();
bindings.putAll(extractBindingsFromMessage(message));
final String language = message.<String>optionalArgs("language").orElse("gremlin-groovy");
if (message.optionalSessionId().isPresent()) {
// an in session request...throw in a dummy graph instance for now..............................
final Graph g = TinkerFactory.createClassic();
bindings.put("g", g);
final GremlinSession session = getGremlinSession(message.sessionId, bindings);
if (logger.isDebugEnabled()) logger.debug("Using session {} ScriptEngine to process {}", message.sessionId, message);
return s -> session.eval(message.<String>optionalArgs(RequestMessage.FIELD_GREMLIN).get(), bindings, language);
} else {
// a sessionless request
if (logger.isDebugEnabled()) logger.debug("Using shared ScriptEngine to process {}", message);
return s -> {
// put all the preconfigured graphs on the bindings
bindings.putAll(graphs.getGraphs());
try {
// do a safety cleanup of previous transaction...if any
graphs.rollbackAll();
final Object o = sharedScriptEngines.eval(message.<String>optionalArgs(RequestMessage.FIELD_GREMLIN).get(), bindings, language);
graphs.commitAll();
return o;
} catch (ScriptException ex) {
// todo: gotta work on error handling for failed scripts..........
graphs.rollbackAll();
throw ex;
}
};
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Override
public TableEvaluationRequest readFrom(Class<TableEvaluationRequest> type, Type genericType, Annotation[] annotations, MediaType mediaType, MultivaluedMap<String, String> httpHeaders, InputStream entityStream) throws IOException {
String charset = getCharset(mediaType);
MultivaluedMap<String, String> queryParameters = this.uriInfo.getQueryParameters();
String delimiterChar = queryParameters.getFirst("delimiterChar");
String quoteChar = queryParameters.getFirst("quoteChar");
BufferedReader reader = new BufferedReader(new InputStreamReader(entityStream, charset)){
@Override
public void close(){
// The closing of the underlying java.io.InputStream is handled elsewhere
}
};
TableEvaluationRequest tableRequest;
try {
CsvPreference format;
if(delimiterChar != null){
format = CsvUtil.getFormat(delimiterChar, quoteChar);
} else
{
format = CsvUtil.getFormat(reader);
}
tableRequest = CsvUtil.readTable(reader, format);
} catch(Exception e){
logger.error("Failed to load CSV document", e);
throw new BadRequestException(e);
} finally {
reader.close();
}
tableRequest.setCharset(charset);
return tableRequest;
}
#location 37
#vulnerability type RESOURCE_LEAK | #fixed code
@Override
public TableEvaluationRequest readFrom(Class<TableEvaluationRequest> type, Type genericType, Annotation[] annotations, MediaType mediaType, MultivaluedMap<String, String> httpHeaders, InputStream entityStream) throws IOException {
String charset = getCharset(mediaType);
MultivaluedMap<String, String> queryParameters = this.uriInfo.getQueryParameters();
String delimiterChar = queryParameters.getFirst("delimiterChar");
String quoteChar = queryParameters.getFirst("quoteChar");
BufferedReader reader = new BufferedReader(new InputStreamReader(entityStream, charset)){
@Override
public void close(){
// The closing of the underlying java.io.InputStream is handled elsewhere
}
};
TableEvaluationRequest tableRequest;
try {
CsvPreference format;
if(delimiterChar != null){
format = CsvUtil.getFormat(delimiterChar, quoteChar);
} else
{
format = CsvUtil.getFormat(reader);
}
tableRequest = CsvUtil.readTable(reader, format);
TableFormat tableFormat = new TableFormat()
.setCharset(charset)
.setDelimiterChar((char)format.getDelimiterChar())
.setQuoteChar(format.getQuoteChar());
tableRequest.setFormat(tableFormat);
} catch(Exception e){
logger.error("Failed to load CSV document", e);
throw new BadRequestException(e);
} finally {
reader.close();
}
return tableRequest;
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
static
private boolean checkFormat(BufferedReader reader, CsvPreference format) throws IOException {
CsvListReader parser = new CsvListReader(reader, format);
int columns = 0;
// Check the header line and the first ten lines
for(int line = 0; line < (1 + 10); line++){
List<String> row = parser.read();
if(row == null){
break;
} // End if
if(columns == 0 || columns == row.size()){
columns = row.size();
} else
{
columns = -1;
break;
}
}
return (columns > 1);
}
#location 25
#vulnerability type RESOURCE_LEAK | #fixed code
static
private boolean checkFormat(BufferedReader reader, CsvPreference format) throws IOException {
CsvListReader parser = new CsvListReader(reader, format);
int columns = 0;
// Check the header line and the first ten lines
for(int line = 0; line < (1 + 10); line++){
List<String> row = parser.read();
if(row == null){
break;
} // End if
if(columns == 0 || columns == row.size()){
columns = row.size();
} else
{
return false;
}
}
return (columns > 1);
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
static
private boolean checkFormat(BufferedReader reader, CsvPreference format) throws IOException {
CsvListReader parser = new CsvListReader(reader, format);
int columns = 0;
// Check the header line and the first ten lines
for(int line = 0; line < (1 + 10); line++){
List<String> row = parser.read();
if(row == null){
break;
} // End if
if(columns == 0 || columns == row.size()){
columns = row.size();
} else
{
return false;
}
}
return (columns > 1);
}
#location 23
#vulnerability type RESOURCE_LEAK | #fixed code
static
private boolean checkFormat(BufferedReader reader, CsvPreference format) throws IOException {
CsvListReader parser = new CsvListReader(reader, format){
@Override
public void close(){
}
};
int columns = 0;
// Check the header line and the first ten lines
for(int line = 0; line < (1 + 10); line++){
List<String> row = parser.read();
if(row == null){
break;
} // End if
if(columns == 0 || columns == row.size()){
columns = row.size();
} else
{
return false;
}
}
parser.close();
return (columns > 1);
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
public static void premain(final String args, final Instrumentation instrumentation) {
Map<String, String> argMap = parseArgs(args);
String statsdServer = argMap.get("server");
int statsdPort = Integer.valueOf(argMap.get("port"));
String prefix = argMap.get("prefix");
List<String> filterPackages = Arrays.asList(argMap.get("filterPackages").split(":"));
StatsDClient client = new NonBlockingStatsDClient(prefix, statsdServer, statsdPort);
Profiler memoryProfiler = new MemoryProfiler(client);
Profiler cpuProfiler = new CPUProfiler(client, filterPackages);
Collection<Profiler> profilers = Arrays.asList(memoryProfiler, cpuProfiler);
scheduleProfilers(profilers);
registerShutdownHook(profilers);
}
#location 6
#vulnerability type NULL_DEREFERENCE | #fixed code
public static void premain(final String args, final Instrumentation instrumentation) {
Arguments arguments = Arguments.parseArgs(args);
String statsdServer = arguments.statsdServer;
int statsdPort = arguments.statsdPort;
String prefix = arguments.metricsPrefix.or("statsd-jvm-profiler");
List<String> filterPackages = arguments.filterPackages.or(new ArrayList<String>());
StatsDClient client = new NonBlockingStatsDClient(prefix, statsdServer, statsdPort);
Profiler memoryProfiler = new MemoryProfiler(client);
Profiler cpuProfiler = new CPUProfiler(client, filterPackages);
Collection<Profiler> profilers = Arrays.asList(memoryProfiler, cpuProfiler);
scheduleProfilers(profilers);
registerShutdownHook(profilers);
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
private List<String> readContractList() {
return ResourceLoader
.getBufferedReader(getClass(), SLA_CONTRACTS_LIST)
.lines()
.filter(l -> !l.startsWith("#"))
.filter(l -> !l.trim().isEmpty())
.collect(toList());
}
#location 4
#vulnerability type RESOURCE_LEAK | #fixed code
private List<String> readContractList() {
return ResourceLoader
.newBufferedReader(SLA_CONTRACTS_LIST, getClass())
.lines()
.filter(l -> !l.startsWith("#"))
.filter(l -> !l.trim().isEmpty())
.collect(toList());
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Override
public void addLink(final long srcId, final long destId, final double bandwidth, final double latency) {
if (getTopologycalGraph() == null) {
graph = new TopologicalGraph();
}
if (map == null) {
map = new HashMap<>();
}
// maybe add the nodes
addNodeMapping(srcId);
addNodeMapping(destId);
// generate a new link
getTopologycalGraph().addLink(new TopologicalLink(map.get(srcId), map.get(destId), (float) latency, (float) bandwidth));
generateMatrices();
}
#location 16
#vulnerability type NULL_DEREFERENCE | #fixed code
@Override
public void addLink(final long srcId, final long destId, final double bandwidth, final double latency) {
if (getTopologycalGraph() == null) {
graph = new TopologicalGraph();
}
if (entitiesMap == null) {
entitiesMap = new HashMap<>();
}
// maybe add the nodes
addNodeMapping(srcId);
addNodeMapping(destId);
// generate a new link
getTopologycalGraph().addLink(new TopologicalLink(entitiesMap.get(srcId), entitiesMap.get(destId), (float) latency, (float) bandwidth));
generateMatrices();
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
private void onUpdateCloudletProcessingListener(CloudletVmEventInfo eventInfo) {
Cloudlet c = eventInfo.getCloudlet();
double cpuUsage = c.getUtilizationModelCpu().getUtilization(eventInfo.getTime())*100;
double ramUsage = c.getUtilizationModelRam().getUtilization(eventInfo.getTime())*100;
double bwUsage = c.getUtilizationModelBw().getUtilization(eventInfo.getTime())*100;
System.out.printf(
"\t#EventListener: Time %.0f: Updated Cloudlet %d execution inside Vm %d",
eventInfo.getTime(), c.getId(), eventInfo.getVm().getId());
System.out.printf(
"\tCurrent Cloudlet resource usage: CPU %3.0f%%, RAM %3.0f%%, BW %3.0f%%\n",
cpuUsage, ramUsage, bwUsage);
}
#location 6
#vulnerability type CHECKERS_PRINTF_ARGS | #fixed code
private void onUpdateCloudletProcessingListener(CloudletVmEventInfo eventInfo) {
Cloudlet c = eventInfo.getCloudlet();
double cpuUsage = c.getUtilizationModelCpu().getUtilization(eventInfo.getTime())*100;
double ramUsage = c.getUtilizationModelRam().getUtilization(eventInfo.getTime())*100;
double bwUsage = c.getUtilizationModelBw().getUtilization(eventInfo.getTime())*100;
System.out.printf(
"\t#EventListener: Time %.0f: Updated Cloudlet %d execution inside Vm %d",
eventInfo.getTime(), c.getId(), eventInfo.getVm().getId());
System.out.printf(
"\tCurrent Cloudlet resource usage: CPU %3.0f%%, RAM %3.0f%%, BW %3.0f%%%n",
cpuUsage, ramUsage, bwUsage);
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
protected void updateExecutionTask(ResCloudlet rcl, double currentTime, Processor p) {
NetworkCloudlet netcl = (NetworkCloudlet)rcl.getCloudlet();
/**
* @todo @author manoelcampos updates the execution
* length of the task, considering the NetworkCloudlet
* has only one execution task.
*/
CloudletExecutionTask task = (CloudletExecutionTask)netcl.getCurrentTask();
task.process(netcl.getCloudletFinishedSoFar());
if (task.isFinished()) {
netcl.getCurrentTask().computeExecutionTime(currentTime);
startNextTask(netcl);
}
}
#location 9
#vulnerability type NULL_DEREFERENCE | #fixed code
protected void updateExecutionTask(ResCloudlet rcl, double currentTime, Processor p) {
NetworkCloudlet netcl = (NetworkCloudlet)rcl.getCloudlet();
if(!(netcl.getCurrentTask() instanceof CloudletExecutionTask))
throw new RuntimeException(
"This method has to be called only when the current task of the NetworkCloudlet, inside the given ResCloudlet, is a CloudletExecutionTask");
/**
* @todo @author manoelcampos The method updates the execution
* length of the task, considering the NetworkCloudlet
* has only 1 execution task.
*/
CloudletExecutionTask task = (CloudletExecutionTask)netcl.getCurrentTask();
task.process(netcl.getCloudletFinishedSoFar());
if (task.isFinished()) {
netcl.getCurrentTask().computeExecutionTime(currentTime);
startNextTask(netcl);
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
private List<String> readContractList() {
return ResourceLoader
.getBufferedReader(getClass(), SLA_CONTRACTS_LIST)
.lines()
.filter(l -> !l.startsWith("#"))
.filter(l -> !l.trim().isEmpty())
.collect(toList());
}
#location 4
#vulnerability type RESOURCE_LEAK | #fixed code
private List<String> readContractList() {
return ResourceLoader
.newBufferedReader(SLA_CONTRACTS_LIST, getClass())
.lines()
.filter(l -> !l.startsWith("#"))
.filter(l -> !l.trim().isEmpty())
.collect(toList());
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
private void vmProcessingUpdateListener(VmHostEventInfo info) {
final Vm vm = info.getVm();
//Destroys VM 1 when its CPU usage reaches 90%
if(vm.getCpuPercentUtilization() > 0.9 && vm.isCreated()){
System.out.printf(
"\n# %.2f: Intentionally destroying %s due to CPU overload. Current VM CPU usage is %.2f%%\n",
info.getTime(), vm, vm.getCpuPercentUtilization()*100);
vm.getHost().destroyVm(vm);
}
datacenter0.getHostList().forEach(h -> System.out.printf("# %.2f: %s CPU Utilization %.2f%%\n", info.getTime(), h, h.getCpuPercentUtilization()*100));
}
#location 5
#vulnerability type CHECKERS_PRINTF_ARGS | #fixed code
private void vmProcessingUpdateListener(VmHostEventInfo info) {
final Vm vm = info.getVm();
//Destroys VM 1 when its CPU usage reaches 90%
if(vm.getCpuPercentUtilization() > 0.9 && vm.isCreated()){
System.out.printf(
"%n# %.2f: Intentionally destroying %s due to CPU overload. Current VM CPU usage is %.2f%%%n",
info.getTime(), vm, vm.getCpuPercentUtilization()*100);
vm.getHost().destroyVm(vm);
}
datacenter0.getHostList().forEach(h -> System.out.printf("# %.2f: %s CPU Utilization %.2f%%%n", info.getTime(), h, h.getCpuPercentUtilization()*100));
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
public static void main(String[] args) {
final CloudletTaskCompletionTimeMinimizationExperiment exp = new CloudletTaskCompletionTimeMinimizationExperiment(344L);
exp.setVerbose(true);
exp.run();
System.out.println();
System.out.printf("Average Task Completion Time (TCT): %.2f seconds\n", exp.getTaskCompletionTimeAverage());
for (DatacenterBroker broker : exp.getBrokerList()) {
System.out.printf("%s SLA's TCT: %.2f seconds\n", broker, exp.getTaskCompletionTimeFromContract(broker));
}
System.out.printf("Percentage of cloudlet that met TCT (i.e, the execution time was less or equal to the TCT defined in the SLA): %.2f%%\n", exp.getPercentageOfCloudletsMeetingTaskCompletionTime());
System.out.printf("Ratio of existing total VM PEs to required Cloudlets PEs: %.2f\n", exp.getRatioOfExistingVmPesToRequiredCloudletPes());
}
#location 11
#vulnerability type CHECKERS_PRINTF_ARGS | #fixed code
public static void main(String[] args) {
final CloudletTaskCompletionTimeMinimizationExperiment exp = new CloudletTaskCompletionTimeMinimizationExperiment(344L);
exp.setVerbose(true);
exp.run();
System.out.println();
System.out.printf("Average Task Completion Time (TCT): %.2f seconds%n", exp.getTaskCompletionTimeAverage());
for (DatacenterBroker broker : exp.getBrokerList()) {
System.out.printf("%s SLA's TCT: %.2f seconds%n", broker, exp.getTaskCompletionTimeFromContract(broker));
}
System.out.printf("Percentage of cloudlet that met TCT (i.e, the execution time was less or equal to the TCT defined in the SLA): %.2f%%%n", exp.getPercentageOfCloudletsMeetingTaskCompletionTime());
System.out.printf("Ratio of existing total VM PEs to required Cloudlets PEs: %.2f%n", exp.getRatioOfExistingVmPesToRequiredCloudletPes());
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
public static GoogleTaskEventsTraceReader getInstance(
final CloudSim simulation,
final String filePath,
final Function<TaskEvent, Cloudlet> cloudletCreationFunction)
{
final InputStream reader = ResourceLoader.getInputStream(filePath, GoogleTaskEventsTraceReader.class);
return new GoogleTaskEventsTraceReader(simulation, filePath, reader, cloudletCreationFunction);
}
#location 7
#vulnerability type RESOURCE_LEAK | #fixed code
public static GoogleTaskEventsTraceReader getInstance(
final CloudSim simulation,
final String filePath,
final Function<TaskEvent, Cloudlet> cloudletCreationFunction)
{
final InputStream reader = ResourceLoader.newInputStream(filePath, GoogleTaskEventsTraceReader.class);
return new GoogleTaskEventsTraceReader(simulation, filePath, reader, cloudletCreationFunction);
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
private List<String> readContractList() {
return ResourceLoader
.getBufferedReader(getClass(), SLA_CONTRACTS_LIST)
.lines()
.map(String::trim)
.filter(line -> !line.isEmpty())
.filter(line -> !line.startsWith("#"))
.collect(toList());
}
#location 4
#vulnerability type RESOURCE_LEAK | #fixed code
private List<String> readContractList() {
return ResourceLoader
.newBufferedReader(SLA_CONTRACTS_LIST, getClass())
.lines()
.map(String::trim)
.filter(line -> !line.isEmpty())
.filter(line -> !line.startsWith("#"))
.collect(toList());
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
public static SlaContract getInstance(final String jsonFilePath) {
return getInstanceInternal(ResourceLoader.getInputStream(jsonFilePath, SlaContract.class));
}
#location 2
#vulnerability type RESOURCE_LEAK | #fixed code
public static SlaContract getInstance(final String jsonFilePath) {
return getInstanceInternal(ResourceLoader.newInputStream(jsonFilePath, SlaContract.class));
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
private void onClockTick(final EventInfo info) {
for (Host host : datacenter0.getHostList()) {
System.out.printf("Host %-2d Time: %.0f\n", host.getId(), info.getTime());
for (Vm vm : host.getVmList()) {
System.out.printf(
"\tVm %2d: Host's CPU utilization: %5.0f%% | Host's RAM utilization: %5.0f%% | Host's BW utilization: %5.0f%%\n",
vm.getId(), vm.getHostCpuUtilization()*100, vm.getHostRamUtilization()*100, vm.getHostBwUtilization()*100);
}
System.out.printf(
"Host %-2d Total Utilization: %5.0f%% | %5.0f%% | %5.0f%%\n\n",
host.getId(),host.getCpuPercentUtilization()*100,
host.getRam().getPercentUtilization()*100,
host.getBw().getPercentUtilization()*100);
}
}
#location 5
#vulnerability type CHECKERS_PRINTF_ARGS | #fixed code
private void onClockTick(final EventInfo info) {
for (Host host : datacenter0.getHostList()) {
System.out.printf("Host %-2d Time: %.0f%n", host.getId(), info.getTime());
for (Vm vm : host.getVmList()) {
System.out.printf(
"\tVm %2d: Host's CPU utilization: %5.0f%% | Host's RAM utilization: %5.0f%% | Host's BW utilization: %5.0f%%%n",
vm.getId(), vm.getHostCpuUtilization()*100, vm.getHostRamUtilization()*100, vm.getHostBwUtilization()*100);
}
System.out.printf(
"Host %-2d Total Utilization: %5.0f%% | %5.0f%% | %5.0f%%%n%n",
host.getId(),host.getCpuPercentUtilization()*100,
host.getRam().getPercentUtilization()*100,
host.getBw().getPercentUtilization()*100);
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Override
public final Host setActive(final boolean activate) {
if(isFailed() && activate){
throw new IllegalStateException("The Host is failed and cannot be activated.");
}
notifyStartupOrShutdown(activate);
if(activate && !this.active) {
setStartTime(getSimulation().clock());
} else if(!activate && this.active){
setShutdownTime(getSimulation().clock());
}
this.active = activate;
return this;
}
#location 12
#vulnerability type NULL_DEREFERENCE | #fixed code
@Override
public final Host setActive(final boolean activate) {
if(isFailed() && activate){
throw new IllegalStateException("The Host is failed and cannot be activated.");
}
final boolean wasActive = this.active;
if(activate && !this.active) {
setStartTime(getSimulation().clock());
} else if(!activate && this.active){
setShutdownTime(getSimulation().clock());
}
this.active = activate;
notifyStartupOrShutdown(activate, wasActive);
return this;
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
public static BriteNetworkTopology getInstance(final String fileName){
final InputStreamReader reader = new InputStreamReader(ResourceLoader.getInputStream(fileName, BriteNetworkTopology.class));
return new BriteNetworkTopology(reader);
}
#location 3
#vulnerability type RESOURCE_LEAK | #fixed code
public static BriteNetworkTopology getInstance(final String fileName){
final InputStreamReader reader = ResourceLoader.newInputStreamReader(fileName, BriteNetworkTopology.class);
return new BriteNetworkTopology(reader);
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
public static GoogleMachineEventsTraceReader getInstance(
final String filePath,
final Function<MachineEvent, Host> hostCreationFunction)
{
final InputStream reader = ResourceLoader.getInputStream(filePath, GoogleMachineEventsTraceReader.class);
return new GoogleMachineEventsTraceReader(filePath, reader, hostCreationFunction);
}
#location 6
#vulnerability type RESOURCE_LEAK | #fixed code
public static GoogleMachineEventsTraceReader getInstance(
final String filePath,
final Function<MachineEvent, Host> hostCreationFunction)
{
final InputStream reader = ResourceLoader.newInputStream(filePath, GoogleMachineEventsTraceReader.class);
return new GoogleMachineEventsTraceReader(filePath, reader, hostCreationFunction);
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
private void printVmUtilizationHistory(Vm vm) {
System.out.println(vm + " RAM and BW utilization history");
System.out.println("----------------------------------------------------------------------------------");
//A set containing all resource utilization collected times
final Set<Double> timeSet = allVmsRamUtilizationHistory.get(vm).keySet();
final Map<Double, Double> vmRamUtilization = allVmsRamUtilizationHistory.get(vm);
final Map<Double, Double> vmBwUtilization = allVmsBwUtilizationHistory.get(vm);
for (final double time : timeSet) {
System.out.printf(
"Time: %10.1f secs | RAM Utilization: %10.2f%% | BW Utilization: %10.2f%%\n",
time, vmRamUtilization.get(time) * 100, vmBwUtilization.get(time) * 100);
}
System.out.println("----------------------------------------------------------------------------------\n");
}
#location 12
#vulnerability type CHECKERS_PRINTF_ARGS | #fixed code
private void printVmUtilizationHistory(Vm vm) {
System.out.println(vm + " RAM and BW utilization history");
System.out.println("----------------------------------------------------------------------------------");
//A set containing all resource utilization collected times
final Set<Double> timeSet = allVmsRamUtilizationHistory.get(vm).keySet();
final Map<Double, Double> vmRamUtilization = allVmsRamUtilizationHistory.get(vm);
final Map<Double, Double> vmBwUtilization = allVmsBwUtilizationHistory.get(vm);
for (final double time : timeSet) {
System.out.printf(
"Time: %10.1f secs | RAM Utilization: %10.2f%% | BW Utilization: %10.2f%%%n",
time, vmRamUtilization.get(time) * 100, vmBwUtilization.get(time) * 100);
}
System.out.printf("----------------------------------------------------------------------------------%n%n");
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
private void showCpuUtilizationForAllHosts() {
System.out.println("\nHosts CPU utilization history for the entire simulation period");
int numberOfUsageHistoryEntries = 0;
for (Host host : hostList) {
double mipsByPe = host.getTotalMipsCapacity() / (double)host.getNumberOfPes();
System.out.printf("Host %d: Number of PEs %2d, MIPS by PE %.0f\n", host.getId(), host.getNumberOfPes(), mipsByPe);
for (Map.Entry<Double, Double> entry : host.getUtilizationHistorySum().entrySet()) {
final double time = entry.getKey();
final double cpuUsage = entry.getValue()*100;
numberOfUsageHistoryEntries++;
System.out.printf("\tTime: %4.1f CPU Utilization: %6.2f%%\n", time, cpuUsage);
}
System.out.println("--------------------------------------------------");
}
if(numberOfUsageHistoryEntries == 0) {
System.out.println("No CPU usage history was found");
}
}
#location 11
#vulnerability type CHECKERS_PRINTF_ARGS | #fixed code
private void showCpuUtilizationForAllHosts() {
System.out.printf("%nHosts CPU utilization history for the entire simulation period%n");
int numberOfUsageHistoryEntries = 0;
for (Host host : hostList) {
double mipsByPe = host.getTotalMipsCapacity() / (double)host.getNumberOfPes();
System.out.printf("Host %d: Number of PEs %2d, MIPS by PE %.0f%n", host.getId(), host.getNumberOfPes(), mipsByPe);
for (Map.Entry<Double, Double> entry : host.getUtilizationHistorySum().entrySet()) {
final double time = entry.getKey();
final double cpuUsage = entry.getValue()*100;
numberOfUsageHistoryEntries++;
System.out.printf("\tTime: %4.1f CPU Utilization: %6.2f%%%n", time, cpuUsage);
}
System.out.println("--------------------------------------------------");
}
if(numberOfUsageHistoryEntries == 0) {
System.out.println("No CPU usage history was found");
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Override
public final Host setActive(final boolean activate) {
if(isFailed() && activate){
throw new IllegalStateException("The Host is failed and cannot be activated.");
}
notifyStartupOrShutdown(activate);
if(activate && !this.active) {
setStartTime(getSimulation().clock());
} else if(!activate && this.active){
setShutdownTime(getSimulation().clock());
}
this.active = activate;
return this;
}
#location 10
#vulnerability type NULL_DEREFERENCE | #fixed code
@Override
public final Host setActive(final boolean activate) {
if(isFailed() && activate){
throw new IllegalStateException("The Host is failed and cannot be activated.");
}
final boolean wasActive = this.active;
if(activate && !this.active) {
setStartTime(getSimulation().clock());
} else if(!activate && this.active){
setShutdownTime(getSimulation().clock());
}
this.active = activate;
notifyStartupOrShutdown(activate, wasActive);
return this;
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
public static SwfWorkloadFileReader getInstance(final String fileName, final int mips) {
final InputStream reader = ResourceLoader.getInputStream(fileName, SwfWorkloadFileReader.class);
return new SwfWorkloadFileReader(fileName, reader, mips);
}
#location 3
#vulnerability type RESOURCE_LEAK | #fixed code
public static SwfWorkloadFileReader getInstance(final String fileName, final int mips) {
final InputStream reader = ResourceLoader.newInputStream(fileName, SwfWorkloadFileReader.class);
return new SwfWorkloadFileReader(fileName, reader, mips);
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
private void showCpuUtilizationForAllVms(final double simulationFinishTime) {
System.out.println("\nHosts CPU utilization history for the entire simulation period\n");
int numberOfUsageHistoryEntries = 0;
for (Vm vm : vmlist) {
System.out.printf("VM %d\n", vm.getId());
if (vm.getUtilizationHistory().getHistory().isEmpty()) {
System.out.println("\tThere isn't any usage history");
continue;
}
for (Map.Entry<Double, Double> entry : vm.getUtilizationHistory().getHistory().entrySet()) {
final double time = entry.getKey();
final double vmCpuUsage = entry.getValue()*100;
if (vmCpuUsage > 0) {
numberOfUsageHistoryEntries++;
System.out.printf("\tTime: %2.0f CPU Utilization: %6.2f%%\n", time, vmCpuUsage);
}
}
}
if (numberOfUsageHistoryEntries == 0) {
System.out.println("No CPU usage history was found");
}
}
#location 16
#vulnerability type CHECKERS_PRINTF_ARGS | #fixed code
private void showCpuUtilizationForAllVms(final double simulationFinishTime) {
System.out.printf("%nHosts CPU utilization history for the entire simulation period%n%n");
int numberOfUsageHistoryEntries = 0;
for (Vm vm : vmlist) {
System.out.printf("VM %d%n", vm.getId());
if (vm.getUtilizationHistory().getHistory().isEmpty()) {
System.out.println("\tThere isn't any usage history");
continue;
}
for (Map.Entry<Double, Double> entry : vm.getUtilizationHistory().getHistory().entrySet()) {
final double time = entry.getKey();
final double vmCpuUsage = entry.getValue()*100;
if (vmCpuUsage > 0) {
numberOfUsageHistoryEntries++;
System.out.printf("\tTime: %2.0f CPU Utilization: %6.2f%%%n", time, vmCpuUsage);
}
}
}
if (numberOfUsageHistoryEntries == 0) {
System.out.println("No CPU usage history was found");
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
public static GoogleTaskUsageTraceReader getInstance(
final List<DatacenterBroker> brokers,
final String filePath)
{
final InputStream reader = ResourceLoader.getInputStream(filePath, GoogleTaskUsageTraceReader.class);
return new GoogleTaskUsageTraceReader(brokers, filePath, reader);
}
#location 6
#vulnerability type RESOURCE_LEAK | #fixed code
public static GoogleTaskUsageTraceReader getInstance(
final List<DatacenterBroker> brokers,
final String filePath)
{
final InputStream reader = ResourceLoader.newInputStream(filePath, GoogleTaskUsageTraceReader.class);
return new GoogleTaskUsageTraceReader(brokers, filePath, reader);
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
public final boolean generateFailure() {
final int numberOfFailedPes = setFailedHostPes();
final long hostWorkingPes = host.getNumberOfWorkingPes();
final long vmsRequiredPes = getPesSumOfWorkingVms();
Log.printFormattedLine("\t%.2f: Generated %d PEs failures for Host %d", getSimulation().clock(), numberOfFailedPes, host.getId());
if(vmsRequiredPes == 0){
System.out.printf("\t Number of VMs: %d\n", host.getId(), host.getVmList().size());
}
System.out.printf("\t Working PEs: %d | VMs required PEs: %d\n", hostWorkingPes, vmsRequiredPes);
if(hostWorkingPes == 0){
setAllVmsToFailed();
} else if (hostWorkingPes >= vmsRequiredPes) {
logNoVmFailure();
} else {
deallocateFailedHostPesFromVms();
}
return numberOfFailedPes > 0;
}
#location 7
#vulnerability type CHECKERS_PRINTF_ARGS | #fixed code
public final boolean generateFailure() {
final int numberOfFailedPes = setFailedHostPes();
final long hostWorkingPes = host.getNumberOfWorkingPes();
final long vmsRequiredPes = getPesSumOfWorkingVms();
Log.printFormattedLine("\t%.2f: Generated %d PEs failures for %s", getSimulation().clock(), numberOfFailedPes, host);
if(vmsRequiredPes == 0){
System.out.printf("\t Number of VMs: %d\n", host.getVmList().size());
}
System.out.printf("\t Working PEs: %d | VMs required PEs: %d\n", hostWorkingPes, vmsRequiredPes);
if(hostWorkingPes == 0){
setAllVmsToFailed();
} else if (hostWorkingPes >= vmsRequiredPes) {
logNoVmFailure();
} else {
deallocateFailedHostPesFromVms();
}
return numberOfFailedPes > 0;
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
private static Properties loadWithNormalMode(final String propertyFilePath)
throws Exception {
Properties props = new Properties();
props.load(new FileInputStream(propertyFilePath));
return props;
}
#location 5
#vulnerability type RESOURCE_LEAK | #fixed code
private static Properties loadWithNormalMode(final String propertyFilePath)
throws Exception {
Properties props = new Properties();
props.load(new InputStreamReader(new FileInputStream(propertyFilePath), "utf-8"));
return props;
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
public static WatchMgr getWatchMgr(FetcherMgr fetcherMgr) throws Exception {
if (!ConfigMgr.isInit()) {
throw new Exception(
"ConfigMgr should be init before WatchFactory.getWatchMgr");
}
if (hosts == null) {
synchronized (hostsSync) {
if (hosts == null) {
// 获取 Zoo Hosts
try {
hosts = fetcherMgr.getValueFromServer(DisconfWebPathMgr
.getZooHostsUrl(DisClientSysConfig
.getInstance().CONF_SERVER_ZOO_ACTION));
} catch (Exception e) {
throw new Exception("cannot get zoo hosts", e);
}
}
}
}
WatchMgr watchMgr = new WatchMgrImpl();
watchMgr.init(hosts,
DisClientSysConfig.getInstance().ZOOKEEPER_URL_PREFIX);
return watchMgr;
}
#location 25
#vulnerability type THREAD_SAFETY_VIOLATION | #fixed code
public static WatchMgr getWatchMgr(FetcherMgr fetcherMgr) throws Exception {
if (!ConfigMgr.isInit()) {
throw new Exception(
"ConfigMgr should be init before WatchFactory.getWatchMgr");
}
if (hosts == null) {
synchronized (hostsSync) {
if (hosts == null) {
// 获取 Zoo Hosts
try {
hosts = fetcherMgr.getValueFromServer(DisconfWebPathMgr
.getZooHostsUrl(DisClientSysConfig
.getInstance().CONF_SERVER_ZOO_ACTION));
WatchMgr watchMgr = new WatchMgrImpl();
watchMgr.init(
hosts,
DisClientSysConfig.getInstance().ZOOKEEPER_URL_PREFIX);
return watchMgr;
} catch (Exception e) {
LOGGER.error("cannot get watch module", e);
}
}
}
}
return null;
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Override
public String downloadFromServer(RemoteUrl remoteUrl, String fileName, String localFileDir, String localFileDirTemp,
String copy2TargetDirPath, boolean enableLocalDownloadDirInClassPath,
int retryTimes, int retrySleepSeconds)
throws Exception {
// 目标地址文件
File localFile = null;
//
// 进行下载、mv、copy
//
try {
// 可重试的下载
File tmpFilePathUniqueFile = retryDownload(localFileDirTemp, fileName, remoteUrl, retryTimes,
retrySleepSeconds);
// 将 tmp file copy localFileDir
localFile = transfer2SpecifyDir(tmpFilePathUniqueFile, localFileDir, fileName, false);
// mv 到指定目录
if (copy2TargetDirPath != null) {
//
if (enableLocalDownloadDirInClassPath || !copy2TargetDirPath.equals(ClassLoaderUtil.getClassPath
())) {
localFile = transfer2SpecifyDir(tmpFilePathUniqueFile, copy2TargetDirPath, fileName, true);
}
}
LOGGER.debug("Move to: " + localFile.getAbsolutePath());
} catch (Exception e) {
LOGGER.warn("download file failed, using previous download file.", e);
}
//
// 判断是否下载失败
//
if (!localFile.exists()) {
throw new Exception("target file cannot be found! " + fileName);
}
//
// 下面为下载成功
//
// 返回相对路径
if (localFileDir != null) {
String relativePathString = OsUtil.getRelativePath(localFile, new File(localFileDir));
if (relativePathString != null) {
if (new File(relativePathString).isFile()) {
return relativePathString;
}
}
}
// 否则, 返回全路径
return localFile.getAbsolutePath();
}
#location 44
#vulnerability type NULL_DEREFERENCE | #fixed code
@Override
public String downloadFromServer(RemoteUrl remoteUrl, String fileName, String localFileDir, String localFileDirTemp,
String copy2TargetDirPath, boolean enableLocalDownloadDirInClassPath,
int retryTimes, int retrySleepSeconds)
throws Exception {
// 目标地址文件
File localFile = null;
//
// 进行下载、mv、copy
//
try {
// 可重试的下载
File tmpFilePathUniqueFile = retryDownload(localFileDirTemp, fileName, remoteUrl, retryTimes,
retrySleepSeconds);
// 将 tmp file copy localFileDir
localFile = transfer2SpecifyDir(tmpFilePathUniqueFile, localFileDir, fileName, false);
// mv 到指定目录
if (copy2TargetDirPath != null) {
//
if (enableLocalDownloadDirInClassPath || !copy2TargetDirPath.equals(ClassLoaderUtil.getClassPath
())) {
localFile = transfer2SpecifyDir(tmpFilePathUniqueFile, copy2TargetDirPath, fileName, true);
}
}
LOGGER.debug("Move to: " + localFile.getAbsolutePath());
} catch (Exception e) {
LOGGER.warn("download file failed, using previous download file.", e);
}
//
// 判断是否下载失败
//
if (localFile == null || !localFile.exists()) {
throw new Exception("target file cannot be found! " + fileName);
}
//
// 下面为下载成功
//
// 返回相对路径
String relativePathString = OsUtil.getRelativePath(localFile, new File(localFileDir));
if (relativePathString != null) {
if (new File(relativePathString).isFile()) {
return relativePathString;
}
}
// 否则, 返回全路径
return localFile.getAbsolutePath();
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
private static Properties loadWithTomcatMode(final String propertyFilePath)
throws Exception {
Properties props = new Properties();
try {
// 先用TOMCAT模式进行导入
// http://blog.csdn.net/minfree/article/details/1800311
// http://stackoverflow.com/questions/3263560/sysloader-getresource-problem-in-java
URL url = ClassLoaderUtil.getLoader().getResource(propertyFilePath);
URI uri = new URI(url.toString());
props.load(new FileInputStream(uri.getPath()));
} catch (Exception e) {
// http://stackoverflow.com/questions/574809/load-a-resource-contained-in-a-jar
props.load(ClassLoaderUtil.getLoader().getResourceAsStream(propertyFilePath));
}
return props;
}
#location 13
#vulnerability type RESOURCE_LEAK | #fixed code
private static Properties loadWithTomcatMode(final String propertyFilePath)
throws Exception {
Properties props = new Properties();
try {
// 先用TOMCAT模式进行导入
// http://blog.csdn.net/minfree/article/details/1800311
// http://stackoverflow.com/questions/3263560/sysloader-getresource-problem-in-java
URL url = ClassLoaderUtil.getLoader().getResource(propertyFilePath);
URI uri = new URI(url.toString());
props.load(new InputStreamReader(new FileInputStream(uri.getPath()), "utf-8"));
} catch (Exception e) {
// http://stackoverflow.com/questions/574809/load-a-resource-contained-in-a-jar
props.load(new InputStreamReader(ClassLoaderUtil.getLoader().getResourceAsStream(propertyFilePath),
"utf-8"));
}
return props;
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@ManagedMetric(description = "Total Disk Space assigned")
public long getTotalDiskAssigned() {
return (Long) parseStorageTotals().get("hdd").get("total");
}
#location 3
#vulnerability type NULL_DEREFERENCE | #fixed code
@ManagedMetric(description = "Total Disk Space assigned")
public long getTotalDiskAssigned() {
return convertPotentialLong(parseStorageTotals().get("hdd").get("total"));
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@ManagedMetric(description = "Total Disk Space free")
public long getTotalDiskFree() {
return (Long) parseStorageTotals().get("hdd").get("free");
}
#location 3
#vulnerability type NULL_DEREFERENCE | #fixed code
@ManagedMetric(description = "Total Disk Space free")
public long getTotalDiskFree() {
return convertPotentialLong(parseStorageTotals().get("hdd").get("free"));
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@ManagedMetric(description = "Total RAM assigned")
public long getTotalRAMAssigned() {
return (Long) parseStorageTotals().get("ram").get("total");
}
#location 3
#vulnerability type NULL_DEREFERENCE | #fixed code
@ManagedMetric(description = "Total RAM assigned")
public long getTotalRAMAssigned() {
return convertPotentialLong(parseStorageTotals().get("ram").get("total"));
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@ManagedMetric(description = "Total Disk Space used")
public long getTotalDiskUsed() {
return (Long) parseStorageTotals().get("hdd").get("used");
}
#location 3
#vulnerability type NULL_DEREFERENCE | #fixed code
@ManagedMetric(description = "Total Disk Space used")
public long getTotalDiskUsed() {
return convertPotentialLong(parseStorageTotals().get("hdd").get("used"));
} | Below is the vulnerable code, please generate the patch based on the following information. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.