output
stringlengths 64
73.2k
| input
stringlengths 208
73.3k
| instruction
stringclasses 1
value |
---|---|---|
#fixed code
public void testHierarchicConfigRoundTrip() throws Exception
{
ConfigAlternate input = new ConfigAlternate(123, "Joe", 42);
String json = MAPPER.writeValueAsString(input);
ConfigAlternate root = MAPPER.readValue(json, ConfigAlternate.class);
assertEquals(123, root.id);
assertNotNull(root.general);
assertNotNull(root.general.names);
assertNotNull(root.misc);
assertEquals("Joe", root.general.names.name);
assertEquals(42, root.misc.value);
} | #vulnerable code
public void testHierarchicConfigRoundTrip() throws Exception
{
ConfigAlternate input = new ConfigAlternate(123, "Joe", 42);
String json = mapper.writeValueAsString(input);
ConfigAlternate root = mapper.readValue(json, ConfigAlternate.class);
assertEquals(123, root.id);
assertNotNull(root.general);
assertNotNull(root.general.names);
assertNotNull(root.misc);
assertEquals("Joe", root.general.names.name);
assertEquals(42, root.misc.value);
}
#location 7
#vulnerability type NULL_DEREFERENCE | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
public void testSimpleMapImitation() throws Exception
{
MapImitator mapHolder = MAPPER.readValue
("{ \"a\" : 3, \"b\" : true, \"c\":[1,2,3] }", MapImitator.class);
Map<String,Object> result = mapHolder._map;
assertEquals(3, result.size());
assertEquals(Integer.valueOf(3), result.get("a"));
assertEquals(Boolean.TRUE, result.get("b"));
Object ob = result.get("c");
assertTrue(ob instanceof List<?>);
List<?> l = (List<?>)ob;
assertEquals(3, l.size());
assertEquals(Integer.valueOf(3), l.get(2));
} | #vulnerable code
public void testSimpleMapImitation() throws Exception
{
MapImitator mapHolder = MAPPER.readValue
("{ \"a\" : 3, \"b\" : true }", MapImitator.class);
Map<String,Object> result = mapHolder._map;
assertEquals(2, result.size());
assertEquals(Integer.valueOf(3), result.get("a"));
assertEquals(Boolean.TRUE, result.get("b"));
}
#location 5
#vulnerability type NULL_DEREFERENCE | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
public void testHierarchicConfigDeserialize() throws Exception
{
ConfigRoot root = MAPPER.readValue("{\"general.names.name\":\"Bob\",\"misc.value\":3}",
ConfigRoot.class);
assertNotNull(root.general);
assertNotNull(root.general.names);
assertNotNull(root.misc);
assertEquals(3, root.misc.value);
assertEquals("Bob", root.general.names.name);
} | #vulnerable code
public void testHierarchicConfigDeserialize() throws Exception
{
ConfigRoot root = mapper.readValue("{\"general.names.name\":\"Bob\",\"misc.value\":3}",
ConfigRoot.class);
assertNotNull(root.general);
assertNotNull(root.general.names);
assertNotNull(root.misc);
assertEquals(3, root.misc.value);
assertEquals("Bob", root.general.names.name);
}
#location 5
#vulnerability type NULL_DEREFERENCE | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
public void testAtomicReference() throws Exception
{
AtomicReference<long[]> value = MAPPER.readValue("[1,2]",
new com.fasterxml.jackson.core.type.TypeReference<AtomicReference<long[]>>() { });
Object ob = value.get();
assertNotNull(ob);
assertEquals(long[].class, ob.getClass());
long[] longs = (long[]) ob;
assertNotNull(longs);
assertEquals(2, longs.length);
assertEquals(1, longs[0]);
assertEquals(2, longs[1]);
} | #vulnerable code
public void testAtomicReference() throws Exception
{
ObjectMapper mapper = new ObjectMapper();
AtomicReference<long[]> value = mapper.readValue("[1,2]",
new com.fasterxml.jackson.core.type.TypeReference<AtomicReference<long[]>>() { });
Object ob = value.get();
assertNotNull(ob);
assertEquals(long[].class, ob.getClass());
long[] longs = (long[]) ob;
assertNotNull(longs);
assertEquals(2, longs.length);
assertEquals(1, longs[0]);
assertEquals(2, longs[1]);
}
#location 6
#vulnerability type NULL_DEREFERENCE | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
public <T> MappingIterator<T> readValues(File src)
throws IOException, JsonProcessingException
{
if (_dataFormatReaders != null) {
return _detectBindAndReadValues(
_dataFormatReaders.findFormat(_inputStream(src)), false);
}
return _bindAndReadValues(_considerFilter(_parserFactory.createParser(src)));
} | #vulnerable code
public <T> MappingIterator<T> readValues(File src)
throws IOException, JsonProcessingException
{
if (_dataFormatReaders != null) {
return _detectBindAndReadValues(
_dataFormatReaders.findFormat(_inputStream(src)), false);
}
return _bindAndReadValues(considerFilter(_parserFactory.createParser(src)));
}
#location 8
#vulnerability type RESOURCE_LEAK | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@SuppressWarnings("resource")
public <T> MappingIterator<T> readValues(Reader src)
throws IOException, JsonProcessingException
{
if (_dataFormatReaders != null) {
_reportUndetectableSource(src);
}
JsonParser p = _considerFilter(_parserFactory.createParser(src));
_initForMultiRead(p);
p.nextToken();
DeserializationContext ctxt = createDeserializationContext(p);
return _newIterator(p, ctxt, _findRootDeserializer(ctxt), true);
} | #vulnerable code
@SuppressWarnings("resource")
public <T> MappingIterator<T> readValues(Reader src)
throws IOException, JsonProcessingException
{
if (_dataFormatReaders != null) {
_reportUndetectableSource(src);
}
JsonParser p = considerFilter(_parserFactory.createParser(src));
_initForMultiRead(p);
p.nextToken();
DeserializationContext ctxt = createDeserializationContext(p);
return _newIterator(p, ctxt, _findRootDeserializer(ctxt), true);
}
#location 12
#vulnerability type RESOURCE_LEAK | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
public void testAtomicBoolean() throws Exception
{
AtomicBoolean b = MAPPER.readValue("true", AtomicBoolean.class);
assertTrue(b.get());
} | #vulnerable code
public void testAtomicBoolean() throws Exception
{
ObjectMapper mapper = new ObjectMapper();
AtomicBoolean b = mapper.readValue("true", AtomicBoolean.class);
assertTrue(b.get());
}
#location 5
#vulnerability type NULL_DEREFERENCE | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Override
public PropertyMetadata getMetadata() {
final Boolean b = _findRequired();
final String desc = _findDescription();
final Integer idx = _findIndex();
final String def = _findDefaultValue();
if (b == null && idx == null && def == null) {
return (desc == null) ? PropertyMetadata.STD_REQUIRED_OR_OPTIONAL
: PropertyMetadata.STD_REQUIRED_OR_OPTIONAL.withDescription(desc);
}
return PropertyMetadata.construct(b, desc, idx, def);
} | #vulnerable code
@Override
public PropertyMetadata getMetadata() {
final Boolean b = _findRequired();
final String desc = _findDescription();
final Integer idx = _findIndex();
final String def = _findDefaultValue();
if (b == null && idx == null && def == null) {
return (desc == null) ? PropertyMetadata.STD_REQUIRED_OR_OPTIONAL
: PropertyMetadata.STD_REQUIRED_OR_OPTIONAL.withDescription(desc);
}
return PropertyMetadata.construct(b.booleanValue(), desc, idx, def);
}
#location 11
#vulnerability type NULL_DEREFERENCE | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Override
public String idFromValue(Object value)
{
return idFromClass(value.getClass());
} | #vulnerable code
@Override
public String idFromValue(Object value)
{
Class<?> cls = _typeFactory.constructType(value.getClass()).getRawClass();
final String key = cls.getName();
String name;
synchronized (_typeToId) {
name = _typeToId.get(key);
if (name == null) {
// 24-Feb-2011, tatu: As per [JACKSON-498], may need to dynamically look up name
// can either throw an exception, or use default name...
if (_config.isAnnotationProcessingEnabled()) {
BeanDescription beanDesc = _config.introspectClassAnnotations(cls);
name = _config.getAnnotationIntrospector().findTypeName(beanDesc.getClassInfo());
}
if (name == null) {
// And if still not found, let's choose default?
name = _defaultTypeId(cls);
}
_typeToId.put(key, name);
}
}
return name;
}
#location 4
#vulnerability type THREAD_SAFETY_VIOLATION | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
public void testMapUnwrapDeserialize() throws Exception
{
MapUnwrap root = MAPPER.readValue("{\"map.test\": 6}", MapUnwrap.class);
assertEquals(1, root.map.size());
assertEquals(6, ((Number)root.map.get("test")).intValue());
} | #vulnerable code
public void testMapUnwrapDeserialize() throws Exception
{
MapUnwrap root = mapper.readValue("{\"map.test\": 6}", MapUnwrap.class);
assertEquals(1, root.map.size());
assertEquals(6, ((Number)root.map.get("test")).intValue());
}
#location 5
#vulnerability type NULL_DEREFERENCE | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
public void withTree749() throws Exception
{
ObjectMapper mapper = new ObjectMapper().registerModule(new TestEnumModule());
Map<KeyEnum, Object> inputMap = new LinkedHashMap<KeyEnum, Object>();
Map<TestEnum, Map<String, String>> replacements = new LinkedHashMap<TestEnum, Map<String, String>>();
Map<String, String> reps = new LinkedHashMap<String, String>();
reps.put("1", "one");
replacements.put(TestEnum.GREEN, reps);
inputMap.put(KeyEnum.replacements, replacements);
JsonNode tree = mapper.valueToTree(inputMap);
ObjectNode ob = (ObjectNode) tree;
JsonNode inner = ob.get("replacements");
String firstFieldName = inner.fieldNames().next();
assertEquals("green", firstFieldName);
} | #vulnerable code
public void withTree749() throws Exception
{
Map<KeyEnum, Object> inputMap = new LinkedHashMap<KeyEnum, Object>();
Map<TestEnum, Map<String, String>> replacements = new LinkedHashMap<TestEnum, Map<String, String>>();
Map<String, String> reps = new LinkedHashMap<String, String>();
reps.put("1", "one");
replacements.put(TestEnum.GREEN, reps);
inputMap.put(KeyEnum.replacements, replacements);
ObjectMapper mapper = TestEnumModule.setupObjectMapper(new ObjectMapper());
JsonNode tree = mapper.valueToTree(inputMap);
ObjectNode ob = (ObjectNode) tree;
JsonNode inner = ob.get("replacements");
String firstFieldName = inner.fieldNames().next();
assertEquals("green", firstFieldName);
}
#location 12
#vulnerability type NULL_DEREFERENCE | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
public <T> MappingIterator<T> readValues(InputStream src)
throws IOException, JsonProcessingException
{
if (_dataFormatReaders != null) {
return _detectBindAndReadValues(_dataFormatReaders.findFormat(src), false);
}
return _bindAndReadValues(_considerFilter(_parserFactory.createParser(src)));
} | #vulnerable code
public <T> MappingIterator<T> readValues(InputStream src)
throws IOException, JsonProcessingException
{
if (_dataFormatReaders != null) {
return _detectBindAndReadValues(_dataFormatReaders.findFormat(src), false);
}
return _bindAndReadValues(considerFilter(_parserFactory.createParser(src)));
}
#location 8
#vulnerability type RESOURCE_LEAK | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
public void testAtomicInt() throws Exception
{
AtomicInteger value = MAPPER.readValue("13", AtomicInteger.class);
assertEquals(13, value.get());
} | #vulnerable code
public void testAtomicInt() throws Exception
{
ObjectMapper mapper = new ObjectMapper();
AtomicInteger value = mapper.readValue("13", AtomicInteger.class);
assertEquals(13, value.get());
}
#location 5
#vulnerability type NULL_DEREFERENCE | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
public <T> MappingIterator<T> readValues(URL src)
throws IOException, JsonProcessingException
{
if (_dataFormatReaders != null) {
return _detectBindAndReadValues(
_dataFormatReaders.findFormat(_inputStream(src)), true);
}
return _bindAndReadValues(_considerFilter(_parserFactory.createParser(src)));
} | #vulnerable code
public <T> MappingIterator<T> readValues(URL src)
throws IOException, JsonProcessingException
{
if (_dataFormatReaders != null) {
return _detectBindAndReadValues(
_dataFormatReaders.findFormat(_inputStream(src)), true);
}
return _bindAndReadValues(considerFilter(_parserFactory.createParser(src)));
}
#location 8
#vulnerability type RESOURCE_LEAK | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
public void testPrefixedUnwrapping() throws Exception
{
PrefixUnwrap bean = MAPPER.readValue("{\"name\":\"Axel\",\"_x\":4,\"_y\":7}", PrefixUnwrap.class);
assertNotNull(bean);
assertEquals("Axel", bean.name);
assertNotNull(bean.location);
assertEquals(4, bean.location.x);
assertEquals(7, bean.location.y);
} | #vulnerable code
public void testPrefixedUnwrapping() throws Exception
{
PrefixUnwrap bean = mapper.readValue("{\"name\":\"Axel\",\"_x\":4,\"_y\":7}", PrefixUnwrap.class);
assertNotNull(bean);
assertEquals("Axel", bean.name);
assertNotNull(bean.location);
assertEquals(4, bean.location.x);
assertEquals(7, bean.location.y);
}
#location 5
#vulnerability type NULL_DEREFERENCE | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
protected SiteMap processText(String sitemapUrl, byte[] content) throws IOException {
LOG.debug("Processing textual Sitemap");
SiteMap textSiteMap = new SiteMap(sitemapUrl);
textSiteMap.setType(SitemapType.TEXT);
BOMInputStream bomIs = new BOMInputStream(new ByteArrayInputStream(content));
@SuppressWarnings("resource")
BufferedReader reader = new BufferedReader(new InputStreamReader(bomIs, UTF_8));
String line;
int i = 1;
while ((line = reader.readLine()) != null) {
if (line.length() > 0 && i <= MAX_URLS) {
addUrlIntoSitemap(line, textSiteMap, null, null, null, i++);
}
}
textSiteMap.setProcessed(true);
return textSiteMap;
} | #vulnerable code
protected SiteMap processText(String sitemapUrl, byte[] content) throws IOException {
LOG.debug("Processing textual Sitemap");
SiteMap textSiteMap = new SiteMap(sitemapUrl);
textSiteMap.setType(SitemapType.TEXT);
BOMInputStream bomIs = new BOMInputStream(new ByteArrayInputStream(content));
@SuppressWarnings("resource")
BufferedReader reader = new BufferedReader(new InputStreamReader(bomIs, "UTF-8"));
String line;
int i = 1;
while ((line = reader.readLine()) != null) {
if (line.length() > 0 && i <= MAX_URLS) {
addUrlIntoSitemap(line, textSiteMap, null, null, null, i++);
}
}
textSiteMap.setProcessed(true);
return textSiteMap;
}
#location 20
#vulnerability type RESOURCE_LEAK | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Test
public void testVideosSitemap() throws UnknownFormatException, IOException {
SiteMapParser parser = new SiteMapParser();
parser.enableExtension(Extension.VIDEO);
String contentType = "text/xml";
byte[] content = SiteMapParserTest.getResourceAsBytes("src/test/resources/sitemaps/extension/sitemap-videos.xml");
URL url = new URL("http://www.example.com/sitemap-video.xml");
AbstractSiteMap asm = parser.parseSiteMap(contentType, content, url);
assertEquals(false, asm.isIndex());
assertEquals(true, asm instanceof SiteMap);
SiteMap sm = (SiteMap) asm;
assertEquals(2, sm.getSiteMapUrls().size());
Iterator<SiteMapURL> siter = sm.getSiteMapUrls().iterator();
// first <loc> element: nearly all video attributes
VideoAttributes expectedVideoAttributes = new VideoAttributes(new URL("http://www.example.com/thumbs/123.jpg"), "Grilling steaks for summer",
"Alkis shows you how to get perfectly done steaks every time", new URL("http://www.example.com/video123.flv"), new URL("http://www.example.com/videoplayer.swf?video=123"));
expectedVideoAttributes.setDuration(600);
ZonedDateTime dt = ZonedDateTime.parse("2009-11-05T19:20:30+08:00");
expectedVideoAttributes.setExpirationDate(dt);
dt = ZonedDateTime.parse("2007-11-05T19:20:30+08:00");
expectedVideoAttributes.setPublicationDate(dt);
expectedVideoAttributes.setRating(4.2f);
expectedVideoAttributes.setViewCount(12345);
expectedVideoAttributes.setFamilyFriendly(true);
expectedVideoAttributes.setTags(new String[] { "sample_tag1", "sample_tag2" });
expectedVideoAttributes.setAllowedCountries(new String[] { "IE", "GB", "US", "CA" });
expectedVideoAttributes.setGalleryLoc(new URL("http://cooking.example.com"));
expectedVideoAttributes.setGalleryTitle("Cooking Videos");
expectedVideoAttributes.setPrices(new VideoAttributes.VideoPrice[] { new VideoAttributes.VideoPrice("EUR", 1.99f, VideoAttributes.VideoPriceType.own) });
expectedVideoAttributes.setRequiresSubscription(true);
expectedVideoAttributes.setUploader("GrillyMcGrillerson");
expectedVideoAttributes.setUploaderInfo(new URL("http://www.example.com/users/grillymcgrillerson"));
expectedVideoAttributes.setLive(false);
VideoAttributes attr = (VideoAttributes) siter.next().getAttributesForExtension(Extension.VIDEO)[0];
assertNotNull(attr);
assertEquals(expectedVideoAttributes, attr);
// locale-specific number format in <video:price>, test #220
expectedVideoAttributes = new VideoAttributes(new URL("http://www.example.com/thumbs/123-2.jpg"), "Grilling steaks for summer, episode 2",
"Alkis shows you how to get perfectly done steaks every time", new URL("http://www.example.com/video123-2.flv"), null);
expectedVideoAttributes.setPrices(new VideoAttributes.VideoPrice[] { new VideoAttributes.VideoPrice("EUR", null, VideoAttributes.VideoPriceType.own) });
attr = (VideoAttributes) siter.next().getAttributesForExtension(Extension.VIDEO)[0];
assertNotNull(attr);
assertEquals(expectedVideoAttributes, attr);
} | #vulnerable code
@Test
public void testVideosSitemap() throws UnknownFormatException, IOException {
SiteMapParser parser = new SiteMapParser();
parser.enableExtension(Extension.VIDEO);
String contentType = "text/xml";
byte[] content = SiteMapParserTest.getResourceAsBytes("src/test/resources/sitemaps/extension/sitemap-videos.xml");
URL url = new URL("http://www.example.com/sitemap-video.xml");
AbstractSiteMap asm = parser.parseSiteMap(contentType, content, url);
assertEquals(false, asm.isIndex());
assertEquals(true, asm instanceof SiteMap);
SiteMap sm = (SiteMap) asm;
assertEquals(1, sm.getSiteMapUrls().size());
VideoAttributes expectedVideoAttributes = new VideoAttributes(new URL("http://www.example.com/thumbs/123.jpg"), "Grilling steaks for summer",
"Alkis shows you how to get perfectly done steaks every time", new URL("http://www.example.com/video123.flv"), new URL("http://www.example.com/videoplayer.swf?video=123"));
expectedVideoAttributes.setDuration(600);
ZonedDateTime dt = ZonedDateTime.parse("2009-11-05T19:20:30+08:00");
expectedVideoAttributes.setExpirationDate(dt);
dt = ZonedDateTime.parse("2007-11-05T19:20:30+08:00");
expectedVideoAttributes.setPublicationDate(dt);
expectedVideoAttributes.setRating(4.2f);
expectedVideoAttributes.setViewCount(12345);
expectedVideoAttributes.setFamilyFriendly(true);
expectedVideoAttributes.setTags(new String[] { "sample_tag1", "sample_tag2" });
expectedVideoAttributes.setAllowedCountries(new String[] { "IE", "GB", "US", "CA" });
expectedVideoAttributes.setGalleryLoc(new URL("http://cooking.example.com"));
expectedVideoAttributes.setGalleryTitle("Cooking Videos");
expectedVideoAttributes.setPrices(new VideoAttributes.VideoPrice[] { new VideoAttributes.VideoPrice("EUR", 1.99f, VideoAttributes.VideoPriceType.own) });
expectedVideoAttributes.setRequiresSubscription(true);
expectedVideoAttributes.setUploader("GrillyMcGrillerson");
expectedVideoAttributes.setUploaderInfo(new URL("http://www.example.com/users/grillymcgrillerson"));
expectedVideoAttributes.setLive(false);
for (SiteMapURL su : sm.getSiteMapUrls()) {
assertNotNull(su.getAttributesForExtension(Extension.VIDEO));
VideoAttributes attr = (VideoAttributes) su.getAttributesForExtension(Extension.VIDEO)[0];
assertEquals(expectedVideoAttributes, attr);
}
}
#location 37
#vulnerability type NULL_DEREFERENCE | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
protected AbstractSiteMap processXml(URL sitemapUrl, byte[] xmlContent) throws UnknownFormatException {
BOMInputStream bomIs = new BOMInputStream(new ByteArrayInputStream(xmlContent));
InputSource is = new InputSource();
is.setCharacterStream(new BufferedReader(new InputStreamReader(bomIs, UTF_8)));
return processXml(sitemapUrl, is);
} | #vulnerable code
protected AbstractSiteMap processXml(URL sitemapUrl, byte[] xmlContent) throws UnknownFormatException {
BOMInputStream bomIs = new BOMInputStream(new ByteArrayInputStream(xmlContent));
InputSource is = new InputSource();
try {
is.setCharacterStream(new BufferedReader(new InputStreamReader(bomIs, "UTF-8")));
} catch (UnsupportedEncodingException e) {
IOUtils.closeQuietly(bomIs);
throw new RuntimeException("Impossible exception", e);
}
return processXml(sitemapUrl, is);
}
#location 6
#vulnerability type RESOURCE_LEAK | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
public boolean validate(UserPersonalInfo info) {
validator.validate(info);
if(validator.hasErrors()){
return false;
}
if (info.getUser() == null) {
validator.add(new ValidationMessage("user.errors.wrong", "error"));
}
if (!info.getUser().getEmail().equals(info.getEmail())){
emailValidator.validate(info.getEmail());
}
if (info.getBirthDate() != null && info.getBirthDate().getYear() > DateTime.now().getYear()-12){
validator.add(new ValidationMessage("user.errors.invalid_birth_date.min_age", "error"));
}
if(!info.getUser().getName().equals(info.getName())){
DateTime nameLastTouchedAt = info.getUser().getNameLastTouchedAt();
if(nameLastTouchedAt.isAfter(new DateTime().minusDays(30))){
validator.add(new ValidationMessage("user.errors.name.min_time", "error", nameLastTouchedAt.plusDays(30).toString()));
}
}
return !validator.hasErrors();
} | #vulnerable code
public boolean validate(UserPersonalInfo info) {
validator.validate(info);
if(validator.hasErrors()){
return false;
}
if (info.getUser() == null) {
validator.add(new ValidationMessage("user.errors.wrong", "error"));
}
if(!info.getUser().getEmail().equals(info.getEmail())){
emailValidator.validate(info.getEmail());
}
if(info.getBirthDate().getYear() > DateTime.now().getYear()-12){
validator.add(new ValidationMessage("user.errors.invalid_birth_date.min_age", "error"));
}
if(!info.getUser().getName().equals(info.getName())){
DateTime nameLastTouchedAt = info.getUser().getNameLastTouchedAt();
if(nameLastTouchedAt.isAfter(new DateTime().minusDays(30))){
validator.add(new ValidationMessage("user.errors.name.min_time", "error", nameLastTouchedAt.plusDays(30).toString()));
}
}
return !validator.hasErrors();
}
#location 13
#vulnerability type NULL_DEREFERENCE | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Test
public void moderator_should_approve_question_information() throws Exception {
Information approvedInfo = new QuestionInformation("edited title", "edited desc",
new LoggedUser(otherUser, null), new ArrayList<Tag>(), "comment");
moderator.approve(myQuestion, approvedInfo);
assertEquals(approvedInfo, myQuestion.getInformation());
assertTrue(myQuestion.getInformation().isModerated());
} | #vulnerable code
@Test
public void moderator_should_approve_question_information() throws Exception {
Question question = question("question title", "question description", author);
Information approvedInfo = new QuestionInformation("edited title", "edited desc",
new LoggedUser(otherUser, null), new ArrayList<Tag>(), "comment");
moderator.approve(question, approvedInfo);
assertEquals(approvedInfo, question.getInformation());
assertTrue(question.getInformation().isModerated());
}
#location 10
#vulnerability type NULL_DEREFERENCE | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
public boolean validate(UserPersonalInfo info) {
validator.validate(info);
if (info.getUser() == null) {
validator.add(new ValidationMessage("user.errors.wrong", "error"));
}
if(!info.getUser().getName().equals(info.getName())){
userNameValidator.validate(info.getName());
}
if(!info.getUser().getEmail().equals(info.getEmail())){
emailValidator.validate(info.getEmail());
}
if(info.getUser().getNameLastTouchedAt() != null){
if(info.getUser().getNameLastTouchedAt().isAfter(new DateTime().minusDays(30))){
validator.add(new ValidationMessage("user.errors.name.min_time", "error"));
}
}
return !validator.hasErrors();
} | #vulnerable code
public boolean validate(UserPersonalInfo info) {
validator.validate(info);
if (info.getUser() == null) {
validator.add(new ValidationMessage("error","user.errors.wrong"));
}
if(!info.getUser().getName().equals(info.getName())){
userNameValidator.validate(info.getName());
}
if (!info.getUser().getEmail().equals(info.getEmail())){
emailValidator.validate(info.getEmail());
}
return !validator.hasErrors();
}
#location 9
#vulnerability type NULL_DEREFERENCE | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
public void testAlternateDefaultEncoding(final String cT, final String bomEnc, final String streamEnc, final String prologEnc, final String alternateEnc)
throws Exception {
XmlReader xmlReader = null;
try {
final InputStream is;
if (prologEnc == null) {
is = getXmlStream(bomEnc, XML1, streamEnc, prologEnc);
} else {
is = getXmlStream(bomEnc, XML3, streamEnc, prologEnc);
}
XmlReader.setDefaultEncoding(alternateEnc);
xmlReader = new XmlReader(is, cT, false);
if (!streamEnc.equals("UTF-16")) {
// we can not assert things here becuase UTF-8, US-ASCII and
// ISO-8859-1 look alike for the chars used for detection
} else {
assertEquals(xmlReader.getEncoding().substring(0, streamEnc.length()), streamEnc);
}
} finally {
XmlReader.setDefaultEncoding(null);
if (xmlReader != null) {
xmlReader.close();
}
}
} | #vulnerable code
public void testAlternateDefaultEncoding(final String cT, final String bomEnc, final String streamEnc, final String prologEnc, final String alternateEnc)
throws Exception {
try {
final InputStream is;
if (prologEnc == null) {
is = getXmlStream(bomEnc, XML1, streamEnc, prologEnc);
} else {
is = getXmlStream(bomEnc, XML3, streamEnc, prologEnc);
}
XmlReader.setDefaultEncoding(alternateEnc);
final XmlReader xmlReader = new XmlReader(is, cT, false);
if (!streamEnc.equals("UTF-16")) {
// we can not assert things here becuase UTF-8, US-ASCII and
// ISO-8859-1 look alike for the chars used for detection
} else {
final String enc;
if (alternateEnc != null) {
enc = alternateEnc;
} else {
enc = streamEnc;
}
assertEquals(xmlReader.getEncoding().substring(0, streamEnc.length()), streamEnc);
}
} finally {
XmlReader.setDefaultEncoding(null);
}
}
#location 22
#vulnerability type RESOURCE_LEAK | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
protected void testRawNoBomValid(final String encoding) throws Exception {
checkEncoding(XML1, encoding, "UTF-8");
checkEncoding(XML2, encoding, "UTF-8");
checkEncoding(XML3, encoding, encoding);
checkEncoding(XML4, encoding, encoding);
checkEncoding(XML5, encoding, encoding);
} | #vulnerable code
protected void testRawNoBomValid(final String encoding) throws Exception {
InputStream is = getXmlStream("no-bom", XML1, encoding, encoding);
XmlReader xmlReader = new XmlReader(is, false);
assertEquals(xmlReader.getEncoding(), "UTF-8");
is = getXmlStream("no-bom", XML2, encoding, encoding);
xmlReader = new XmlReader(is);
assertEquals(xmlReader.getEncoding(), "UTF-8");
is = getXmlStream("no-bom", XML3, encoding, encoding);
xmlReader = new XmlReader(is);
assertEquals(xmlReader.getEncoding(), encoding);
is = getXmlStream("no-bom", XML4, encoding, encoding);
xmlReader = new XmlReader(is);
assertEquals(xmlReader.getEncoding(), encoding);
is = getXmlStream("no-bom", XML5, encoding, encoding);
xmlReader = new XmlReader(is);
assertEquals(xmlReader.getEncoding(), encoding);
}
#location 12
#vulnerability type RESOURCE_LEAK | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
private static Date parseUsingMask(final String[] masks, String sDate) {
if (sDate != null) {
sDate = sDate.trim();
}
ParsePosition pp = null;
Date d = null;
for (int i = 0; d == null && i < masks.length; i++) {
final DateFormat df = new SimpleDateFormat(masks[i], Locale.US);
// df.setLenient(false);
df.setLenient(true);
try {
pp = new ParsePosition(0);
d = df.parse(sDate, pp);
if (pp.getIndex() != sDate.length()) {
d = null;
}
// System.out.println("pp["+pp.getIndex()+"] s["+sDate+" m["+masks[i]+"] d["+d+"]");
} catch (final Exception ex1) {
// System.out.println("s: "+sDate+" m: "+masks[i]+" d: "+null);
}
}
return d;
} | #vulnerable code
private static Date parseUsingMask(final String[] masks, String sDate) {
sDate = sDate != null ? sDate.trim() : null;
ParsePosition pp = null;
Date d = null;
for (int i = 0; d == null && i < masks.length; i++) {
final DateFormat df = new SimpleDateFormat(masks[i], Locale.US);
// df.setLenient(false);
df.setLenient(true);
try {
pp = new ParsePosition(0);
d = df.parse(sDate, pp);
if (pp.getIndex() != sDate.length()) {
d = null;
}
// System.out.println("pp["+pp.getIndex()+"] s["+sDate+" m["+masks[i]+"] d["+d+"]");
} catch (final Exception ex1) {
// System.out.println("s: "+sDate+" m: "+masks[i]+" d: "+null);
}
}
return d;
}
#location 12
#vulnerability type NULL_DEREFERENCE | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
public void testAlternateDefaultEncoding(final String cT, final String bomEnc, final String streamEnc, final String prologEnc, final String alternateEnc)
throws Exception {
XmlReader xmlReader = null;
try {
final InputStream is;
if (prologEnc == null) {
is = getXmlStream(bomEnc, XML1, streamEnc, prologEnc);
} else {
is = getXmlStream(bomEnc, XML3, streamEnc, prologEnc);
}
XmlReader.setDefaultEncoding(alternateEnc);
xmlReader = new XmlReader(is, cT, false);
if (!streamEnc.equals("UTF-16")) {
// we can not assert things here becuase UTF-8, US-ASCII and
// ISO-8859-1 look alike for the chars used for detection
} else {
assertEquals(xmlReader.getEncoding().substring(0, streamEnc.length()), streamEnc);
}
} finally {
XmlReader.setDefaultEncoding(null);
if (xmlReader != null) {
xmlReader.close();
}
}
} | #vulnerable code
public void testAlternateDefaultEncoding(final String cT, final String bomEnc, final String streamEnc, final String prologEnc, final String alternateEnc)
throws Exception {
try {
final InputStream is;
if (prologEnc == null) {
is = getXmlStream(bomEnc, XML1, streamEnc, prologEnc);
} else {
is = getXmlStream(bomEnc, XML3, streamEnc, prologEnc);
}
XmlReader.setDefaultEncoding(alternateEnc);
final XmlReader xmlReader = new XmlReader(is, cT, false);
if (!streamEnc.equals("UTF-16")) {
// we can not assert things here becuase UTF-8, US-ASCII and
// ISO-8859-1 look alike for the chars used for detection
} else {
final String enc;
if (alternateEnc != null) {
enc = alternateEnc;
} else {
enc = streamEnc;
}
assertEquals(xmlReader.getEncoding().substring(0, streamEnc.length()), streamEnc);
}
} finally {
XmlReader.setDefaultEncoding(null);
}
}
#location 12
#vulnerability type RESOURCE_LEAK | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
protected void testRawNoBomValid(final String encoding) throws Exception {
checkEncoding(XML1, encoding, "UTF-8");
checkEncoding(XML2, encoding, "UTF-8");
checkEncoding(XML3, encoding, encoding);
checkEncoding(XML4, encoding, encoding);
checkEncoding(XML5, encoding, encoding);
} | #vulnerable code
protected void testRawNoBomValid(final String encoding) throws Exception {
InputStream is = getXmlStream("no-bom", XML1, encoding, encoding);
XmlReader xmlReader = new XmlReader(is, false);
assertEquals(xmlReader.getEncoding(), "UTF-8");
is = getXmlStream("no-bom", XML2, encoding, encoding);
xmlReader = new XmlReader(is);
assertEquals(xmlReader.getEncoding(), "UTF-8");
is = getXmlStream("no-bom", XML3, encoding, encoding);
xmlReader = new XmlReader(is);
assertEquals(xmlReader.getEncoding(), encoding);
is = getXmlStream("no-bom", XML4, encoding, encoding);
xmlReader = new XmlReader(is);
assertEquals(xmlReader.getEncoding(), encoding);
is = getXmlStream("no-bom", XML5, encoding, encoding);
xmlReader = new XmlReader(is);
assertEquals(xmlReader.getEncoding(), encoding);
}
#location 12
#vulnerability type RESOURCE_LEAK | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
protected void testRawBomInvalid(final String bomEnc, final String streamEnc, final String prologEnc) throws Exception {
final InputStream is = getXmlStream(bomEnc, XML3, streamEnc, prologEnc);
try {
final XmlReader xmlReader = new XmlReader(is, false);
fail("It should have failed for BOM " + bomEnc + ", streamEnc " + streamEnc + " and prologEnc " + prologEnc);
xmlReader.close();
} catch (final IOException ex) {
assertTrue(ex.getMessage().indexOf("Invalid encoding,") > -1);
}
} | #vulnerable code
protected void testRawBomInvalid(final String bomEnc, final String streamEnc, final String prologEnc) throws Exception {
final InputStream is = getXmlStream(bomEnc, XML3, streamEnc, prologEnc);
try {
final XmlReader xmlReader = new XmlReader(is, false);
fail("It should have failed for BOM " + bomEnc + ", streamEnc " + streamEnc + " and prologEnc " + prologEnc);
} catch (final IOException ex) {
assertTrue(ex.getMessage().indexOf("Invalid encoding,") > -1);
}
}
#location 4
#vulnerability type RESOURCE_LEAK | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Override
public SyndFeedInfo remove(final URL url) {
SyndFeedInfo info = null;
final String fileName = cachePath + File.separator + "feed_" + replaceNonAlphanumeric(url.toString(), '_').trim();
FileInputStream fis = null;
ObjectInputStream ois = null;
try {
fis = new FileInputStream(fileName);
ois = new ObjectInputStream(fis);
info = (SyndFeedInfo) ois.readObject();
final File file = new File(fileName);
if (file.exists()) {
file.delete();
}
} catch (final FileNotFoundException fnfe) {
// That's OK, we'l return null
} catch (final ClassNotFoundException cnfe) {
// Error writing to cahce is fatal
throw new RuntimeException("Attempting to read from cache", cnfe);
} catch (final IOException fnfe) {
// Error writing to cahce is fatal
throw new RuntimeException("Attempting to read from cache", fnfe);
} finally {
if (fis != null) {
try {
fis.close();
} catch (final IOException e) {
}
}
if (ois != null) {
try {
ois.close();
} catch (final IOException e) {
}
}
}
return info;
} | #vulnerable code
@Override
public SyndFeedInfo remove(final URL url) {
SyndFeedInfo info = null;
final String fileName = cachePath + File.separator + "feed_" + replaceNonAlphanumeric(url.toString(), '_').trim();
FileInputStream fis;
try {
fis = new FileInputStream(fileName);
final ObjectInputStream ois = new ObjectInputStream(fis);
info = (SyndFeedInfo) ois.readObject();
fis.close();
final File file = new File(fileName);
if (file.exists()) {
file.delete();
}
} catch (final FileNotFoundException fnfe) {
// That's OK, we'l return null
} catch (final ClassNotFoundException cnfe) {
// Error writing to cahce is fatal
throw new RuntimeException("Attempting to read from cache", cnfe);
} catch (final IOException fnfe) {
// Error writing to cahce is fatal
throw new RuntimeException("Attempting to read from cache", fnfe);
}
return info;
}
#location 16
#vulnerability type RESOURCE_LEAK | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
public void testHttpValid(final String cT, final String bomEnc, final String streamEnc, final String prologEnc) throws Exception {
final InputStream is;
if (prologEnc == null) {
is = getXmlStream(bomEnc, XML1, streamEnc, prologEnc);
} else {
is = getXmlStream(bomEnc, XML3, streamEnc, prologEnc);
}
final XmlReader xmlReader = new XmlReader(is, cT, false);
if (!streamEnc.equals("UTF-16")) {
// we can not assert things here becuase UTF-8, US-ASCII and
// ISO-8859-1 look alike for the chars used for detection
} else {
assertEquals(xmlReader.getEncoding().substring(0, streamEnc.length()), streamEnc);
}
xmlReader.close();
} | #vulnerable code
public void testHttpValid(final String cT, final String bomEnc, final String streamEnc, final String prologEnc) throws Exception {
final InputStream is;
if (prologEnc == null) {
is = getXmlStream(bomEnc, XML1, streamEnc, prologEnc);
} else {
is = getXmlStream(bomEnc, XML3, streamEnc, prologEnc);
}
final XmlReader xmlReader = new XmlReader(is, cT, false);
if (!streamEnc.equals("UTF-16")) {
// we can not assert things here becuase UTF-8, US-ASCII and
// ISO-8859-1 look alike for the chars used for detection
} else {
assertEquals(xmlReader.getEncoding().substring(0, streamEnc.length()), streamEnc);
}
}
#location 9
#vulnerability type RESOURCE_LEAK | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
protected void testRawNoBomInvalid(final String encoding) throws Exception {
InputStream is = null;
XmlReader xmlReader = null;
try {
is = getXmlStream("no-bom", XML3, encoding, encoding);
xmlReader = new XmlReader(is, false);
fail("It should have failed");
} catch (final IOException ex) {
assertTrue(ex.getMessage().indexOf("Invalid encoding,") > -1);
} finally {
if (xmlReader != null) {
xmlReader.close();
}
if (is != null) {
is.close();
}
}
} | #vulnerable code
protected void testRawNoBomInvalid(final String encoding) throws Exception {
final InputStream is = getXmlStream("no-bom", XML3, encoding, encoding);
try {
final XmlReader xmlReader = new XmlReader(is, false);
fail("It should have failed");
} catch (final IOException ex) {
assertTrue(ex.getMessage().indexOf("Invalid encoding,") > -1);
}
}
#location 4
#vulnerability type RESOURCE_LEAK | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
public void testHttpValid(final String cT, final String bomEnc, final String streamEnc, final String prologEnc) throws Exception {
final InputStream is;
if (prologEnc == null) {
is = getXmlStream(bomEnc, XML1, streamEnc, prologEnc);
} else {
is = getXmlStream(bomEnc, XML3, streamEnc, prologEnc);
}
final XmlReader xmlReader = new XmlReader(is, cT, false);
if (!streamEnc.equals("UTF-16")) {
// we can not assert things here becuase UTF-8, US-ASCII and
// ISO-8859-1 look alike for the chars used for detection
} else {
assertEquals(xmlReader.getEncoding().substring(0, streamEnc.length()), streamEnc);
}
xmlReader.close();
} | #vulnerable code
public void testHttpValid(final String cT, final String bomEnc, final String streamEnc, final String prologEnc) throws Exception {
final InputStream is;
if (prologEnc == null) {
is = getXmlStream(bomEnc, XML1, streamEnc, prologEnc);
} else {
is = getXmlStream(bomEnc, XML3, streamEnc, prologEnc);
}
final XmlReader xmlReader = new XmlReader(is, cT, false);
if (!streamEnc.equals("UTF-16")) {
// we can not assert things here becuase UTF-8, US-ASCII and
// ISO-8859-1 look alike for the chars used for detection
} else {
assertEquals(xmlReader.getEncoding().substring(0, streamEnc.length()), streamEnc);
}
}
#location 13
#vulnerability type RESOURCE_LEAK | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Override
public SyndFeedInfo getFeedInfo(final URL url) {
SyndFeedInfo info = null;
final String fileName = cachePath + File.separator + "feed_" + replaceNonAlphanumeric(url.toString(), '_').trim();
FileInputStream fis = null;
ObjectInputStream ois = null;
try {
fis = new FileInputStream(fileName);
ois = new ObjectInputStream(fis);
info = (SyndFeedInfo) ois.readObject();
} catch (final FileNotFoundException e) {
// That's OK, we'l return null
} catch (final ClassNotFoundException e) {
// Error writing to cache is fatal
throw new RuntimeException("Attempting to read from cache", e);
} catch (final IOException e) {
// Error writing to cache is fatal
throw new RuntimeException("Attempting to read from cache", e);
} finally {
if (fis != null) {
try {
fis.close();
} catch (final IOException e) {
}
}
if (ois != null) {
try {
ois.close();
} catch (final IOException e) {
}
}
}
return info;
} | #vulnerable code
@Override
public SyndFeedInfo getFeedInfo(final URL url) {
SyndFeedInfo info = null;
final String fileName = cachePath + File.separator + "feed_" + replaceNonAlphanumeric(url.toString(), '_').trim();
FileInputStream fis;
try {
fis = new FileInputStream(fileName);
final ObjectInputStream ois = new ObjectInputStream(fis);
info = (SyndFeedInfo) ois.readObject();
fis.close();
} catch (final FileNotFoundException fnfe) {
// That's OK, we'l return null
} catch (final ClassNotFoundException cnfe) {
// Error writing to cache is fatal
throw new RuntimeException("Attempting to read from cache", cnfe);
} catch (final IOException fnfe) {
// Error writing to cache is fatal
throw new RuntimeException("Attempting to read from cache", fnfe);
}
return info;
}
#location 11
#vulnerability type RESOURCE_LEAK | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
protected void testRawBomValid(final String encoding) throws Exception {
final InputStream is = getXmlStream(encoding + "-bom", XML3, encoding, encoding);
final XmlReader xmlReader = new XmlReader(is, false);
if (!encoding.equals("UTF-16")) {
assertEquals(xmlReader.getEncoding(), encoding);
} else {
assertEquals(xmlReader.getEncoding().substring(0, encoding.length()), encoding);
}
xmlReader.close();
} | #vulnerable code
protected void testRawBomValid(final String encoding) throws Exception {
final InputStream is = getXmlStream(encoding + "-bom", XML3, encoding, encoding);
final XmlReader xmlReader = new XmlReader(is, false);
if (!encoding.equals("UTF-16")) {
assertEquals(xmlReader.getEncoding(), encoding);
} else {
assertEquals(xmlReader.getEncoding().substring(0, encoding.length()), encoding);
}
}
#location 7
#vulnerability type RESOURCE_LEAK | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
protected void testRawNoBomValid(final String encoding) throws Exception {
checkEncoding(XML1, encoding, "UTF-8");
checkEncoding(XML2, encoding, "UTF-8");
checkEncoding(XML3, encoding, encoding);
checkEncoding(XML4, encoding, encoding);
checkEncoding(XML5, encoding, encoding);
} | #vulnerable code
protected void testRawNoBomValid(final String encoding) throws Exception {
InputStream is = getXmlStream("no-bom", XML1, encoding, encoding);
XmlReader xmlReader = new XmlReader(is, false);
assertEquals(xmlReader.getEncoding(), "UTF-8");
is = getXmlStream("no-bom", XML2, encoding, encoding);
xmlReader = new XmlReader(is);
assertEquals(xmlReader.getEncoding(), "UTF-8");
is = getXmlStream("no-bom", XML3, encoding, encoding);
xmlReader = new XmlReader(is);
assertEquals(xmlReader.getEncoding(), encoding);
is = getXmlStream("no-bom", XML4, encoding, encoding);
xmlReader = new XmlReader(is);
assertEquals(xmlReader.getEncoding(), encoding);
is = getXmlStream("no-bom", XML5, encoding, encoding);
xmlReader = new XmlReader(is);
assertEquals(xmlReader.getEncoding(), encoding);
}
#location 12
#vulnerability type RESOURCE_LEAK | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
public void testParse() {
final Calendar cal = new GregorianCalendar();
cal.setTimeZone(TimeZone.getTimeZone("GMT"));
// four-digit year
String sDate = "Tue, 19 Jul 2005 23:00:51 GMT";
cal.setTime(DateParser.parseRFC822(sDate, Locale.US));
assertEquals(2005, cal.get(Calendar.YEAR));
assertEquals(6, cal.get(Calendar.MONTH)); // month is zero-indexed
assertEquals(19, cal.get(Calendar.DAY_OF_MONTH));
assertEquals(3, cal.get(Calendar.DAY_OF_WEEK));
assertEquals(23, cal.get(Calendar.HOUR_OF_DAY));
assertEquals(0, cal.get(Calendar.MINUTE));
assertEquals(51, cal.get(Calendar.SECOND));
// two-digit year
sDate = "Tue, 19 Jul 05 23:00:51 GMT";
cal.setTime(DateParser.parseRFC822(sDate, Locale.US));
assertEquals(2005, cal.get(Calendar.YEAR));
assertEquals(6, cal.get(Calendar.MONTH)); // month is zero-indexed
assertEquals(19, cal.get(Calendar.DAY_OF_MONTH));
assertEquals(3, cal.get(Calendar.DAY_OF_WEEK));
assertEquals(23, cal.get(Calendar.HOUR_OF_DAY));
assertEquals(0, cal.get(Calendar.MINUTE));
assertEquals(51, cal.get(Calendar.SECOND));
// four-digit year
sDate = "Tue, 19 Jul 2005 23:00:51 UT";
cal.setTime(DateParser.parseRFC822(sDate, Locale.US));
assertEquals(2005, cal.get(Calendar.YEAR));
assertEquals(6, cal.get(Calendar.MONTH)); // month is zero-indexed
assertEquals(19, cal.get(Calendar.DAY_OF_MONTH));
assertEquals(3, cal.get(Calendar.DAY_OF_WEEK));
assertEquals(23, cal.get(Calendar.HOUR_OF_DAY));
assertEquals(0, cal.get(Calendar.MINUTE));
assertEquals(51, cal.get(Calendar.SECOND));
// two-digit year
sDate = "Tue, 19 Jul 05 23:00:51 UT";
cal.setTime(DateParser.parseRFC822(sDate, Locale.US));
assertEquals(2005, cal.get(Calendar.YEAR));
assertEquals(6, cal.get(Calendar.MONTH)); // month is zero-indexed
assertEquals(19, cal.get(Calendar.DAY_OF_MONTH));
assertEquals(3, cal.get(Calendar.DAY_OF_WEEK));
assertEquals(23, cal.get(Calendar.HOUR_OF_DAY));
assertEquals(0, cal.get(Calendar.MINUTE));
assertEquals(51, cal.get(Calendar.SECOND));
// RFC822
sDate = "Tue, 19 Jul 2005 23:00:51 GMT";
assertNotNull(DateParser.parseDate(sDate, Locale.US));
// RFC822
sDate = "Tue, 19 Jul 05 23:00:51 GMT";
assertNotNull(DateParser.parseDate(sDate, Locale.US));
final Calendar c = Calendar.getInstance(TimeZone.getTimeZone("GMT"));
c.set(2000, Calendar.JANUARY, 01, 0, 0, 0);
final Date expectedDate = c.getTime();
// W3C
sDate = "2000-01-01T00:00:00Z";
assertEquals(expectedDate.getTime() / 1000, DateParser.parseDate(sDate, Locale.US).getTime() / 1000);
// W3C
sDate = "2000-01-01T00:00Z";
assertEquals(expectedDate.getTime() / 1000, DateParser.parseDate(sDate, Locale.US).getTime() / 1000);
// W3C
sDate = "2000-01-01";
assertEquals(expectedDate.getTime() / 1000, DateParser.parseDate(sDate, Locale.US).getTime() / 1000);
// W3C
sDate = "2000-01";
assertEquals(expectedDate.getTime() / 1000, DateParser.parseDate(sDate, Locale.US).getTime() / 1000);
// W3C
sDate = "2000";
assertEquals(expectedDate.getTime() / 1000, DateParser.parseDate(sDate, Locale.US).getTime() / 1000);
// EXTRA
sDate = "18:10 2000/10/10";
assertNotNull(DateParser.parseDate(sDate, Locale.US));
// INVALID
sDate = "X20:10 2000-10-10";
assertNull(DateParser.parseDate(sDate, Locale.US));
} | #vulnerable code
public void testParse() {
final Calendar cal = new GregorianCalendar();
cal.setTimeZone(TimeZone.getTimeZone("GMT"));
// four-digit year
String sDate = "Tue, 19 Jul 2005 23:00:51 GMT";
cal.setTime(DateParser.parseRFC822(sDate));
assertEquals(2005, cal.get(Calendar.YEAR));
assertEquals(6, cal.get(Calendar.MONTH)); // month is zero-indexed
assertEquals(19, cal.get(Calendar.DAY_OF_MONTH));
assertEquals(3, cal.get(Calendar.DAY_OF_WEEK));
assertEquals(23, cal.get(Calendar.HOUR_OF_DAY));
assertEquals(0, cal.get(Calendar.MINUTE));
assertEquals(51, cal.get(Calendar.SECOND));
// two-digit year
sDate = "Tue, 19 Jul 05 23:00:51 GMT";
cal.setTime(DateParser.parseRFC822(sDate));
assertEquals(2005, cal.get(Calendar.YEAR));
assertEquals(6, cal.get(Calendar.MONTH)); // month is zero-indexed
assertEquals(19, cal.get(Calendar.DAY_OF_MONTH));
assertEquals(3, cal.get(Calendar.DAY_OF_WEEK));
assertEquals(23, cal.get(Calendar.HOUR_OF_DAY));
assertEquals(0, cal.get(Calendar.MINUTE));
assertEquals(51, cal.get(Calendar.SECOND));
// four-digit year
sDate = "Tue, 19 Jul 2005 23:00:51 UT";
cal.setTime(DateParser.parseRFC822(sDate));
assertEquals(2005, cal.get(Calendar.YEAR));
assertEquals(6, cal.get(Calendar.MONTH)); // month is zero-indexed
assertEquals(19, cal.get(Calendar.DAY_OF_MONTH));
assertEquals(3, cal.get(Calendar.DAY_OF_WEEK));
assertEquals(23, cal.get(Calendar.HOUR_OF_DAY));
assertEquals(0, cal.get(Calendar.MINUTE));
assertEquals(51, cal.get(Calendar.SECOND));
// two-digit year
sDate = "Tue, 19 Jul 05 23:00:51 UT";
cal.setTime(DateParser.parseRFC822(sDate));
assertEquals(2005, cal.get(Calendar.YEAR));
assertEquals(6, cal.get(Calendar.MONTH)); // month is zero-indexed
assertEquals(19, cal.get(Calendar.DAY_OF_MONTH));
assertEquals(3, cal.get(Calendar.DAY_OF_WEEK));
assertEquals(23, cal.get(Calendar.HOUR_OF_DAY));
assertEquals(0, cal.get(Calendar.MINUTE));
assertEquals(51, cal.get(Calendar.SECOND));
// RFC822
sDate = "Tue, 19 Jul 2005 23:00:51 GMT";
assertNotNull(DateParser.parseDate(sDate));
// RFC822
sDate = "Tue, 19 Jul 05 23:00:51 GMT";
assertNotNull(DateParser.parseDate(sDate));
final Calendar c = Calendar.getInstance(TimeZone.getTimeZone("GMT"));
c.set(2000, Calendar.JANUARY, 01, 0, 0, 0);
final Date expectedDate = c.getTime();
// W3C
sDate = "2000-01-01T00:00:00Z";
assertEquals(expectedDate.getTime() / 1000, DateParser.parseDate(sDate).getTime() / 1000);
// W3C
sDate = "2000-01-01T00:00Z";
assertEquals(expectedDate.getTime() / 1000, DateParser.parseDate(sDate).getTime() / 1000);
// W3C
sDate = "2000-01-01";
assertEquals(expectedDate.getTime() / 1000, DateParser.parseDate(sDate).getTime() / 1000);
// W3C
sDate = "2000-01";
assertEquals(expectedDate.getTime() / 1000, DateParser.parseDate(sDate).getTime() / 1000);
// W3C
sDate = "2000";
assertEquals(expectedDate.getTime() / 1000, DateParser.parseDate(sDate).getTime() / 1000);
// EXTRA
sDate = "18:10 2000/10/10";
assertNotNull(DateParser.parseDate(sDate));
// INVALID
sDate = "X20:10 2000-10-10";
assertNull(DateParser.parseDate(sDate));
}
#location 67
#vulnerability type NULL_DEREFERENCE | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
protected void testHttpLenient(final String cT, final String bomEnc, final String streamEnc, final String prologEnc, final String shouldbe)
throws Exception {
final InputStream is;
if (prologEnc == null) {
is = getXmlStream(bomEnc, XML2, streamEnc, prologEnc);
} else {
is = getXmlStream(bomEnc, XML3, streamEnc, prologEnc);
}
final XmlReader xmlReader = new XmlReader(is, cT, true);
assertEquals(xmlReader.getEncoding(), shouldbe);
xmlReader.close();
} | #vulnerable code
protected void testHttpLenient(final String cT, final String bomEnc, final String streamEnc, final String prologEnc, final String shouldbe)
throws Exception {
final InputStream is;
if (prologEnc == null) {
is = getXmlStream(bomEnc, XML2, streamEnc, prologEnc);
} else {
is = getXmlStream(bomEnc, XML3, streamEnc, prologEnc);
}
final XmlReader xmlReader = new XmlReader(is, cT, true);
assertEquals(xmlReader.getEncoding(), shouldbe);
}
#location 10
#vulnerability type RESOURCE_LEAK | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
public void testParse() {
final Calendar cal = new GregorianCalendar();
cal.setTimeZone(TimeZone.getTimeZone("GMT"));
// four-digit year
String sDate = "Tue, 19 Jul 2005 23:00:51 GMT";
cal.setTime(DateParser.parseRFC822(sDate, Locale.US));
assertEquals(2005, cal.get(Calendar.YEAR));
assertEquals(6, cal.get(Calendar.MONTH)); // month is zero-indexed
assertEquals(19, cal.get(Calendar.DAY_OF_MONTH));
assertEquals(3, cal.get(Calendar.DAY_OF_WEEK));
assertEquals(23, cal.get(Calendar.HOUR_OF_DAY));
assertEquals(0, cal.get(Calendar.MINUTE));
assertEquals(51, cal.get(Calendar.SECOND));
// two-digit year
sDate = "Tue, 19 Jul 05 23:00:51 GMT";
cal.setTime(DateParser.parseRFC822(sDate, Locale.US));
assertEquals(2005, cal.get(Calendar.YEAR));
assertEquals(6, cal.get(Calendar.MONTH)); // month is zero-indexed
assertEquals(19, cal.get(Calendar.DAY_OF_MONTH));
assertEquals(3, cal.get(Calendar.DAY_OF_WEEK));
assertEquals(23, cal.get(Calendar.HOUR_OF_DAY));
assertEquals(0, cal.get(Calendar.MINUTE));
assertEquals(51, cal.get(Calendar.SECOND));
// four-digit year
sDate = "Tue, 19 Jul 2005 23:00:51 UT";
cal.setTime(DateParser.parseRFC822(sDate, Locale.US));
assertEquals(2005, cal.get(Calendar.YEAR));
assertEquals(6, cal.get(Calendar.MONTH)); // month is zero-indexed
assertEquals(19, cal.get(Calendar.DAY_OF_MONTH));
assertEquals(3, cal.get(Calendar.DAY_OF_WEEK));
assertEquals(23, cal.get(Calendar.HOUR_OF_DAY));
assertEquals(0, cal.get(Calendar.MINUTE));
assertEquals(51, cal.get(Calendar.SECOND));
// two-digit year
sDate = "Tue, 19 Jul 05 23:00:51 UT";
cal.setTime(DateParser.parseRFC822(sDate, Locale.US));
assertEquals(2005, cal.get(Calendar.YEAR));
assertEquals(6, cal.get(Calendar.MONTH)); // month is zero-indexed
assertEquals(19, cal.get(Calendar.DAY_OF_MONTH));
assertEquals(3, cal.get(Calendar.DAY_OF_WEEK));
assertEquals(23, cal.get(Calendar.HOUR_OF_DAY));
assertEquals(0, cal.get(Calendar.MINUTE));
assertEquals(51, cal.get(Calendar.SECOND));
// RFC822
sDate = "Tue, 19 Jul 2005 23:00:51 GMT";
assertNotNull(DateParser.parseDate(sDate, Locale.US));
// RFC822
sDate = "Tue, 19 Jul 05 23:00:51 GMT";
assertNotNull(DateParser.parseDate(sDate, Locale.US));
final Calendar c = Calendar.getInstance(TimeZone.getTimeZone("GMT"));
c.set(2000, Calendar.JANUARY, 01, 0, 0, 0);
final Date expectedDate = c.getTime();
// W3C
sDate = "2000-01-01T00:00:00Z";
assertEquals(expectedDate.getTime() / 1000, DateParser.parseDate(sDate, Locale.US).getTime() / 1000);
// W3C
sDate = "2000-01-01T00:00Z";
assertEquals(expectedDate.getTime() / 1000, DateParser.parseDate(sDate, Locale.US).getTime() / 1000);
// W3C
sDate = "2000-01-01";
assertEquals(expectedDate.getTime() / 1000, DateParser.parseDate(sDate, Locale.US).getTime() / 1000);
// W3C
sDate = "2000-01";
assertEquals(expectedDate.getTime() / 1000, DateParser.parseDate(sDate, Locale.US).getTime() / 1000);
// W3C
sDate = "2000";
assertEquals(expectedDate.getTime() / 1000, DateParser.parseDate(sDate, Locale.US).getTime() / 1000);
// EXTRA
sDate = "18:10 2000/10/10";
assertNotNull(DateParser.parseDate(sDate, Locale.US));
// INVALID
sDate = "X20:10 2000-10-10";
assertNull(DateParser.parseDate(sDate, Locale.US));
} | #vulnerable code
public void testParse() {
final Calendar cal = new GregorianCalendar();
cal.setTimeZone(TimeZone.getTimeZone("GMT"));
// four-digit year
String sDate = "Tue, 19 Jul 2005 23:00:51 GMT";
cal.setTime(DateParser.parseRFC822(sDate));
assertEquals(2005, cal.get(Calendar.YEAR));
assertEquals(6, cal.get(Calendar.MONTH)); // month is zero-indexed
assertEquals(19, cal.get(Calendar.DAY_OF_MONTH));
assertEquals(3, cal.get(Calendar.DAY_OF_WEEK));
assertEquals(23, cal.get(Calendar.HOUR_OF_DAY));
assertEquals(0, cal.get(Calendar.MINUTE));
assertEquals(51, cal.get(Calendar.SECOND));
// two-digit year
sDate = "Tue, 19 Jul 05 23:00:51 GMT";
cal.setTime(DateParser.parseRFC822(sDate));
assertEquals(2005, cal.get(Calendar.YEAR));
assertEquals(6, cal.get(Calendar.MONTH)); // month is zero-indexed
assertEquals(19, cal.get(Calendar.DAY_OF_MONTH));
assertEquals(3, cal.get(Calendar.DAY_OF_WEEK));
assertEquals(23, cal.get(Calendar.HOUR_OF_DAY));
assertEquals(0, cal.get(Calendar.MINUTE));
assertEquals(51, cal.get(Calendar.SECOND));
// four-digit year
sDate = "Tue, 19 Jul 2005 23:00:51 UT";
cal.setTime(DateParser.parseRFC822(sDate));
assertEquals(2005, cal.get(Calendar.YEAR));
assertEquals(6, cal.get(Calendar.MONTH)); // month is zero-indexed
assertEquals(19, cal.get(Calendar.DAY_OF_MONTH));
assertEquals(3, cal.get(Calendar.DAY_OF_WEEK));
assertEquals(23, cal.get(Calendar.HOUR_OF_DAY));
assertEquals(0, cal.get(Calendar.MINUTE));
assertEquals(51, cal.get(Calendar.SECOND));
// two-digit year
sDate = "Tue, 19 Jul 05 23:00:51 UT";
cal.setTime(DateParser.parseRFC822(sDate));
assertEquals(2005, cal.get(Calendar.YEAR));
assertEquals(6, cal.get(Calendar.MONTH)); // month is zero-indexed
assertEquals(19, cal.get(Calendar.DAY_OF_MONTH));
assertEquals(3, cal.get(Calendar.DAY_OF_WEEK));
assertEquals(23, cal.get(Calendar.HOUR_OF_DAY));
assertEquals(0, cal.get(Calendar.MINUTE));
assertEquals(51, cal.get(Calendar.SECOND));
// RFC822
sDate = "Tue, 19 Jul 2005 23:00:51 GMT";
assertNotNull(DateParser.parseDate(sDate));
// RFC822
sDate = "Tue, 19 Jul 05 23:00:51 GMT";
assertNotNull(DateParser.parseDate(sDate));
final Calendar c = Calendar.getInstance(TimeZone.getTimeZone("GMT"));
c.set(2000, Calendar.JANUARY, 01, 0, 0, 0);
final Date expectedDate = c.getTime();
// W3C
sDate = "2000-01-01T00:00:00Z";
assertEquals(expectedDate.getTime() / 1000, DateParser.parseDate(sDate).getTime() / 1000);
// W3C
sDate = "2000-01-01T00:00Z";
assertEquals(expectedDate.getTime() / 1000, DateParser.parseDate(sDate).getTime() / 1000);
// W3C
sDate = "2000-01-01";
assertEquals(expectedDate.getTime() / 1000, DateParser.parseDate(sDate).getTime() / 1000);
// W3C
sDate = "2000-01";
assertEquals(expectedDate.getTime() / 1000, DateParser.parseDate(sDate).getTime() / 1000);
// W3C
sDate = "2000";
assertEquals(expectedDate.getTime() / 1000, DateParser.parseDate(sDate).getTime() / 1000);
// EXTRA
sDate = "18:10 2000/10/10";
assertNotNull(DateParser.parseDate(sDate));
// INVALID
sDate = "X20:10 2000-10-10";
assertNull(DateParser.parseDate(sDate));
}
#location 67
#vulnerability type NULL_DEREFERENCE | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
protected void testRawNoBomValid(final String encoding) throws Exception {
checkEncoding(XML1, encoding, "UTF-8");
checkEncoding(XML2, encoding, "UTF-8");
checkEncoding(XML3, encoding, encoding);
checkEncoding(XML4, encoding, encoding);
checkEncoding(XML5, encoding, encoding);
} | #vulnerable code
protected void testRawNoBomValid(final String encoding) throws Exception {
InputStream is = getXmlStream("no-bom", XML1, encoding, encoding);
XmlReader xmlReader = new XmlReader(is, false);
assertEquals(xmlReader.getEncoding(), "UTF-8");
is = getXmlStream("no-bom", XML2, encoding, encoding);
xmlReader = new XmlReader(is);
assertEquals(xmlReader.getEncoding(), "UTF-8");
is = getXmlStream("no-bom", XML3, encoding, encoding);
xmlReader = new XmlReader(is);
assertEquals(xmlReader.getEncoding(), encoding);
is = getXmlStream("no-bom", XML4, encoding, encoding);
xmlReader = new XmlReader(is);
assertEquals(xmlReader.getEncoding(), encoding);
is = getXmlStream("no-bom", XML5, encoding, encoding);
xmlReader = new XmlReader(is);
assertEquals(xmlReader.getEncoding(), encoding);
}
#location 4
#vulnerability type RESOURCE_LEAK | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
HtmlTreeBuilder() {} | #vulnerable code
Element pop() {
// todo - dev, remove validation check
if (stack.peekLast().nodeName().equals("td") && !state.name().equals("InCell"))
Validate.isFalse(true, "pop td not in cell");
if (stack.peekLast().nodeName().equals("html"))
Validate.isFalse(true, "popping html!");
return stack.pollLast();
}
#location 3
#vulnerability type NULL_DEREFERENCE | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
private static String readInputStream(InputStream inStream, String charsetName) throws IOException {
byte[] buffer = new byte[bufferSize];
ByteArrayOutputStream outStream = new ByteArrayOutputStream(bufferSize);
int read;
while(true) {
read = inStream.read(buffer);
if (read == -1) break;
outStream.write(buffer, 0, read);
}
ByteBuffer byteData = ByteBuffer.wrap(outStream.toByteArray());
String docData;
if (charsetName == null) { // determine from http-equiv. safe parse as UTF-8
docData = Charset.forName(defaultCharset).decode(byteData).toString();
Document doc = Jsoup.parse(docData);
Element httpEquiv = doc.select("meta[http-equiv]").first();
if (httpEquiv != null) { // if not found, will keep utf-8 as best attempt
String foundCharset = getCharsetFromContentType(httpEquiv.attr("content"));
if (foundCharset != null && !foundCharset.equals(defaultCharset)) { // need to re-decode
byteData.rewind();
docData = Charset.forName(foundCharset).decode(byteData).toString();
}
}
} else { // specified by content type header (or by user on file load)
docData = Charset.forName(charsetName).decode(byteData).toString();
}
return docData;
} | #vulnerable code
private static String readInputStream(InputStream inStream, String charsetName) throws IOException {
char[] buffer = new char[0x20000]; // ~ 130K
StringBuilder data = new StringBuilder(0x20000);
Reader inReader = new InputStreamReader(inStream, charsetName);
int read;
do {
read = inReader.read(buffer, 0, buffer.length);
if (read > 0) {
data.append(buffer, 0, read);
}
} while (read >= 0);
return data.toString();
}
#location 14
#vulnerability type RESOURCE_LEAK | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
static String load(File in, String charsetName) throws IOException {
InputStream inStream = new FileInputStream(in);
String data = readInputStream(inStream, charsetName);
inStream.close();
return data;
} | #vulnerable code
static String load(File in, String charsetName) throws IOException {
char[] buffer = new char[0x20000]; // ~ 130K
StringBuilder data = new StringBuilder(0x20000);
InputStream inStream = new FileInputStream(in);
Reader inReader = new InputStreamReader(inStream, charsetName);
int read;
do {
read = inReader.read(buffer, 0, buffer.length);
if (read > 0) {
data.append(buffer, 0, read);
}
} while (read >= 0);
return data.toString();
}
#location 5
#vulnerability type RESOURCE_LEAK | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
public Document normalise() {
if (select("html").isEmpty())
appendElement("html");
if (head() == null)
select("html").first().prependElement("head");
if (body() == null)
select("html").first().appendElement("body");
// pull text nodes out of root, html, and head els, and push into body. non-text nodes are already taken care
// of. do in inverse order to maintain text order.
normalise(head());
normalise(select("html").first());
normalise(this);
return this;
} | #vulnerable code
public Document normalise() {
if (select("html").isEmpty())
appendElement("html");
if (head() == null)
select("html").first().prependElement("head");
if (body() == null)
select("html").first().appendElement("body");
normalise(this);
normalise(select("html").first());
normalise(head());
return this;
}
#location 10
#vulnerability type NULL_DEREFERENCE | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
public Document parse() {
// TODO: figure out implicit head & body elements
Document doc = new Document();
stack.add(doc);
StringBuilder commentAccum = null;
while (tokenStream.hasNext()) {
Token token = tokenStream.next();
if (token.isFullComment()) { // <!-- comment -->
Comment comment = new Comment(stack.peek(), token.getCommentData());
stack.getLast().addChild(comment);
} else if (token.isStartComment()) { // <!-- comment
commentAccum = new StringBuilder(token.getCommentData());
} else if (token.isEndComment() && commentAccum != null) { // comment -->
commentAccum.append(token.getCommentData());
Comment comment = new Comment(stack.peek(), commentAccum.toString());
stack.getLast().addChild(comment);
commentAccum = null;
} else if (commentAccum != null) { // within a comment
commentAccum.append(token.getData());
}
else if (token.isStartTag()) {
Attributes attributes = attributeParser.parse(token.getAttributeString());
Tag tag = Tag.valueOf(token.getTagName());
StartTag startTag = new StartTag(tag, attributes);
// if tag is "html", we already have it, so OK to ignore skip. todo: abstract this. and can there be attributes to set?
if (doc.getTag().equals(tag)) continue;
Element parent = popStackToSuitableContainer(tag);
Validate.notNull(parent, "Should always have a viable container");
Element node = new Element(parent, startTag);
parent.addChild(node);
stack.add(node);
}
if (token.isEndTag() && commentAccum == null) { // empty tags are both start and end tags
stack.removeLast();
}
// TODO[must] handle comments
else if (token.isTextNode()) {
String text = token.getData();
TextNode textNode = new TextNode(stack.peek(), text);
stack.getLast().addChild(textNode);
}
}
return doc;
} | #vulnerable code
public Document parse() {
// TODO: figure out implicit head & body elements
Document doc = new Document();
stack.add(doc);
while (tokenStream.hasNext()) {
Token token = tokenStream.next();
if (token.isStartTag()) {
Attributes attributes = attributeParser.parse(token.getAttributeString());
Tag tag = Tag.valueOf(token.getTagName());
StartTag startTag = new StartTag(tag, attributes);
// if tag is "html", we already have it, so OK to ignore skip. todo: abstract this. and can there be attributes to set?
if (doc.getTag().equals(tag)) continue;
Element parent = popStackToSuitableContainer(tag);
Validate.notNull(parent, "Should always have a viable container");
Element node = new Element(parent, startTag);
parent.addChild(node);
stack.add(node);
}
if (token.isEndTag()) { // empty tags are both start and end tags
stack.removeLast();
}
// TODO[must] handle comments
else if (token.isTextNode()) {
String text = token.getData();
TextNode textNode = new TextNode(stack.peek(), text);
stack.getLast().addChild(textNode);
}
}
return doc;
}
#location 20
#vulnerability type NULL_DEREFERENCE | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
public Node previousSibling() {
List<Node> siblings = parentNode.childNodes;
Integer index = siblingIndex();
Validate.notNull(index);
if (index > 0)
return siblings.get(index-1);
else
return null;
} | #vulnerable code
public Node previousSibling() {
List<Node> siblings = parentNode.childNodes;
Integer index = indexInList(this, siblings);
Validate.notNull(index);
if (index > 0)
return siblings.get(index-1);
else
return null;
}
#location 5
#vulnerability type NULL_DEREFERENCE | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
ParseSettings defaultSettings() {
return ParseSettings.htmlDefault;
} | #vulnerable code
void insert(Token.Character characterToken) {
Node node;
// characters in script and style go in as datanodes, not text nodes
final String tagName = currentElement().tagName();
final String data = characterToken.getData();
if (characterToken.isCData())
node = new CDataNode(data);
else if (tagName.equals("script") || tagName.equals("style"))
node = new DataNode(data);
else
node = new TextNode(data);
currentElement().appendChild(node); // doesn't use insertNode, because we don't foster these; and will always have a stack.
}
#location 4
#vulnerability type NULL_DEREFERENCE | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Test
public void testPreviousElementSiblings() {
Document doc = Jsoup.parse("<ul id='ul'>" +
"<li id='a'>a</li>" +
"<li id='b'>b</li>" +
"<li id='c'>c</li>" +
"</ul>" +
"<div id='div'>" +
"<li id='d'>d</li>" +
"</div>");
Element element = doc.getElementById("b");
List<Element> elementSiblings = element.previousElementSiblings();
assertNotNull(elementSiblings);
assertEquals(1, elementSiblings.size());
assertEquals("a", elementSiblings.get(0).id());
Element element1 = doc.getElementById("a");
List<Element> elementSiblings1 = element1.previousElementSiblings();
assertEquals(0, elementSiblings1.size());
Element element2 = doc.getElementById("c");
List<Element> elementSiblings2 = element2.previousElementSiblings();
assertNotNull(elementSiblings2);
assertEquals(2, elementSiblings2.size());
assertEquals("a", elementSiblings2.get(0).id());
assertEquals("b", elementSiblings2.get(1).id());
Element ul = doc.getElementById("ul");
List<Element> elementSiblings3 = ul.previousElementSiblings();
try {
Element element3 = elementSiblings3.get(0);
fail("This element should has no previous siblings");
} catch (IndexOutOfBoundsException e) {
}
} | #vulnerable code
@Test
public void testPreviousElementSiblings() {
Document doc = Jsoup.parse("<li id='a'>a</li>" +
"<li id='b'>b</li>" +
"<li id='c'>c</li>");
Element element = doc.getElementById("b");
List<Element> elementSiblings = element.previousElementSiblings();
assertNotNull(elementSiblings);
assertEquals(1, elementSiblings.size());
Element element1 = doc.getElementById("a");
List<Element> elementSiblings1 = element1.previousElementSiblings();
assertNull(elementSiblings1);
}
#location 9
#vulnerability type NULL_DEREFERENCE | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Test public void forms() {
Document doc = Jsoup.parse("<form id=1><input name=q></form><div /><form id=2><input name=f></form>");
Elements els = doc.select("*");
assertEquals(9, els.size());
List<FormElement> forms = els.forms();
assertEquals(2, forms.size());
assertNotNull(forms.get(0));
assertNotNull(forms.get(1));
assertEquals("1", forms.get(0).id());
assertEquals("2", forms.get(1).id());
} | #vulnerable code
@Test public void forms() {
Document doc = Jsoup.parse("<form id=1><input name=q></form><div /><form id=2><input name=f></form>");
Elements els = doc.select("*");
assertEquals(9, els.size());
List<FormElement> forms = els.forms();
assertEquals(2, forms.size());
assertTrue(forms.get(0) != null);
assertTrue(forms.get(1) != null);
assertEquals("1", forms.get(0).id());
assertEquals("2", forms.get(1).id());
}
#location 10
#vulnerability type NULL_DEREFERENCE | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
static String load(File in, String charsetName) throws IOException {
InputStream inStream = new FileInputStream(in);
String data = readInputStream(inStream, charsetName);
inStream.close();
return data;
} | #vulnerable code
static String load(File in, String charsetName) throws IOException {
char[] buffer = new char[0x20000]; // ~ 130K
StringBuilder data = new StringBuilder(0x20000);
InputStream inStream = new FileInputStream(in);
Reader inReader = new InputStreamReader(inStream, charsetName);
int read;
do {
read = inReader.read(buffer, 0, buffer.length);
if (read > 0) {
data.append(buffer, 0, read);
}
} while (read >= 0);
return data.toString();
}
#location 15
#vulnerability type RESOURCE_LEAK | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
public Node nextSibling() {
if (parentNode == null)
return null; // root
List<Node> siblings = parentNode.childNodes;
Integer index = siblingIndex();
Validate.notNull(index);
if (siblings.size() > index+1)
return siblings.get(index+1);
else
return null;
} | #vulnerable code
public Node nextSibling() {
if (parentNode == null)
return null; // root
List<Node> siblings = parentNode.childNodes;
Integer index = indexInList(this, siblings);
Validate.notNull(index);
if (siblings.size() > index+1)
return siblings.get(index+1);
else
return null;
}
#location 8
#vulnerability type NULL_DEREFERENCE | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
public Document normalise() {
Element htmlEl = findFirstElementByTagName("html", this);
if (htmlEl == null)
htmlEl = appendElement("html");
if (head() == null)
htmlEl.prependElement("head");
if (body() == null)
htmlEl.appendElement("body");
// pull text nodes out of root, html, and head els, and push into body. non-text nodes are already taken care
// of. do in inverse order to maintain text order.
normalise(head());
normalise(htmlEl);
normalise(this);
return this;
} | #vulnerable code
public Document normalise() {
if (select("html").isEmpty())
appendElement("html");
if (head() == null)
select("html").first().prependElement("head");
if (body() == null)
select("html").first().appendElement("body");
// pull text nodes out of root, html, and head els, and push into body. non-text nodes are already taken care
// of. do in inverse order to maintain text order.
normalise(head());
normalise(select("html").first());
normalise(this);
return this;
}
#location 11
#vulnerability type NULL_DEREFERENCE | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
ParseSettings defaultSettings() {
return ParseSettings.htmlDefault;
} | #vulnerable code
void insert(Token.Character characterToken) {
Node node;
// characters in script and style go in as datanodes, not text nodes
final String tagName = currentElement().tagName();
final String data = characterToken.getData();
if (characterToken.isCData())
node = new CDataNode(data);
else if (tagName.equals("script") || tagName.equals("style"))
node = new DataNode(data);
else
node = new TextNode(data);
currentElement().appendChild(node); // doesn't use insertNode, because we don't foster these; and will always have a stack.
}
#location 13
#vulnerability type NULL_DEREFERENCE | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
public boolean matchesWhitespace() {
return !isEmpty() && Character.isWhitespace(queue.charAt(pos));
} | #vulnerable code
public boolean matchesWhitespace() {
return !isEmpty() && Character.isWhitespace(peek());
}
#location 2
#vulnerability type NULL_DEREFERENCE | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Test
public void testAppendTo() {
String parentHtml = "<div class='a'></div>";
String childHtml = "<div class='b'></div><p>Two</p>";
Document parentDoc = Jsoup.parse(parentHtml);
Element parent = parentDoc.body();
Document childDoc = Jsoup.parse(childHtml);
Element div = childDoc.select("div").first();
Element p = childDoc.select("p").first();
Element appendTo1 = div.appendTo(parent);
assertEquals(div, appendTo1);
Element appendTo2 = p.appendTo(div);
assertEquals(p, appendTo2);
assertEquals("<div class=\"a\"></div>\n<div class=\"b\">\n <p>Two</p>\n</div>", parentDoc.body().html());
assertEquals("", childDoc.body().html()); // got moved out
} | #vulnerable code
@Test
public void testAppendTo() {
String parentHtml = "<div class='a'></div>";
String childHtml = "<div class='b'></div>";
Element parentElement = Jsoup.parse(parentHtml).getElementsByClass("a").first();
Element childElement = Jsoup.parse(childHtml).getElementsByClass("b").first();
childElement.attr("class", "test-class").appendTo(parentElement).attr("id", "testId");
assertEquals("test-class", childElement.attr("class"));
assertEquals("testId", childElement.attr("id"));
assertThat(parentElement.attr("id"), not(equalTo("testId")));
assertThat(parentElement.attr("class"), not(equalTo("test-class")));
assertSame(childElement, parentElement.children().first());
assertSame(parentElement, childElement.parent());
}
#location 9
#vulnerability type NULL_DEREFERENCE | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
HtmlTreeBuilder() {} | #vulnerable code
Element pop() {
// todo - dev, remove validation check
if (stack.peekLast().nodeName().equals("td") && !state.name().equals("InCell"))
Validate.isFalse(true, "pop td not in cell");
if (stack.peekLast().nodeName().equals("html"))
Validate.isFalse(true, "popping html!");
return stack.pollLast();
}
#location 5
#vulnerability type NULL_DEREFERENCE | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
private static void load(EscapeMode e, String file, int size) {
e.nameKeys = new String[size];
e.codeVals = new int[size];
e.codeKeys = new int[size];
e.nameVals = new String[size];
InputStream stream = Entities.class.getResourceAsStream(file);
if (stream == null)
throw new IllegalStateException("Could not read resource " + file + ". Make sure you copy resources for " + Entities.class.getCanonicalName());
int i = 0;
BufferedReader input = null;
try {
input = new BufferedReader(new InputStreamReader(stream, ASCII));
CharacterReader reader = new CharacterReader(input);
while (!reader.isEmpty()) {
// NotNestedLessLess=10913,824;1887
final String name = reader.consumeTo('=');
reader.advance();
final int cp1 = Integer.parseInt(reader.consumeToAny(codeDelims), codepointRadix);
final char codeDelim = reader.current();
reader.advance();
final int cp2;
if (codeDelim == ',') {
cp2 = Integer.parseInt(reader.consumeTo(';'), codepointRadix);
reader.advance();
} else {
cp2 = empty;
}
String indexS = reader.consumeTo('\n');
// default git checkout on windows will add a \r there, so remove
if (indexS.charAt(indexS.length() - 1) == '\r') {
indexS = indexS.substring(0, indexS.length() - 1);
}
final int index = Integer.parseInt(indexS, codepointRadix);
reader.advance();
e.nameKeys[i] = name;
e.codeVals[i] = cp1;
e.codeKeys[index] = cp1;
e.nameVals[index] = name;
if (cp2 != empty) {
multipoints.put(name, new String(new int[]{cp1, cp2}, 0, 2));
}
i++;
}
} finally {
try {
if (input != null) {
input.close();
}
} catch (IOException e1) {
//ignore exception
}
}
Validate.isTrue(i == size, "Unexpected count of entities loaded for " + file);
} | #vulnerable code
private static void load(EscapeMode e, String file, int size) {
e.nameKeys = new String[size];
e.codeVals = new int[size];
e.codeKeys = new int[size];
e.nameVals = new String[size];
InputStream stream = Entities.class.getResourceAsStream(file);
if (stream == null)
throw new IllegalStateException("Could not read resource " + file + ". Make sure you copy resources for " + Entities.class.getCanonicalName());
int i = 0;
BufferedReader input = new BufferedReader(new InputStreamReader(stream, ASCII));
CharacterReader reader = new CharacterReader(input);
while (!reader.isEmpty()) {
// NotNestedLessLess=10913,824;1887
final String name = reader.consumeTo('=');
reader.advance();
final int cp1 = Integer.parseInt(reader.consumeToAny(codeDelims), codepointRadix);
final char codeDelim = reader.current();
reader.advance();
final int cp2;
if (codeDelim == ',') {
cp2 = Integer.parseInt(reader.consumeTo(';'), codepointRadix);
reader.advance();
} else {
cp2 = empty;
}
String indexS = reader.consumeTo('\n');
// default git checkout on windows will add a \r there, so remove
if (indexS.charAt(indexS.length() - 1) == '\r') {
indexS = indexS.substring(0, indexS.length() - 1);
}
final int index = Integer.parseInt(indexS, codepointRadix);
reader.advance();
e.nameKeys[i] = name;
e.codeVals[i] = cp1;
e.codeKeys[index] = cp1;
e.nameVals[index] = name;
if (cp2 != empty) {
multipoints.put(name, new String(new int[]{cp1, cp2}, 0, 2));
}
i++;
}
Validate.isTrue(i == size, "Unexpected count of entities loaded for " + file);
}
#location 48
#vulnerability type RESOURCE_LEAK | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
protected void outerHtml(StringBuilder accum) {
new NodeTraversor(new OuterHtmlVisitor(accum, getOutputSettings())).traverse(this);
} | #vulnerable code
protected void outerHtml(StringBuilder accum) {
new NodeTraversor(new OuterHtmlVisitor(accum, ownerDocument().outputSettings())).traverse(this);
}
#location 2
#vulnerability type NULL_DEREFERENCE | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
public boolean matchesWord() {
return !isEmpty() && Character.isLetterOrDigit(queue.charAt(pos));
} | #vulnerable code
public boolean matchesWord() {
return !isEmpty() && Character.isLetterOrDigit(peek());
}
#location 2
#vulnerability type NULL_DEREFERENCE | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Test
public void testNextElementSiblings() {
Document doc = Jsoup.parse("<ul id='ul'>" +
"<li id='a'>a</li>" +
"<li id='b'>b</li>" +
"<li id='c'>c</li>" +
"</ul>" +
"<div id='div'>" +
"<li id='d'>d</li>" +
"</div>");
Element element = doc.getElementById("a");
List<Element> elementSiblings = element.nextElementSiblings();
assertNotNull(elementSiblings);
assertEquals(2, elementSiblings.size());
assertEquals("b", elementSiblings.get(0).id());
assertEquals("c", elementSiblings.get(1).id());
Element element1 = doc.getElementById("b");
List<Element> elementSiblings1 = element1.nextElementSiblings();
assertNotNull(elementSiblings1);
assertEquals(1, elementSiblings1.size());
assertEquals("c", elementSiblings1.get(0).id());
Element element2 = doc.getElementById("c");
List<Element> elementSiblings2 = element2.nextElementSiblings();
assertEquals(0, elementSiblings2.size());
Element ul = doc.getElementById("ul");
List<Element> elementSiblings3 = ul.nextElementSiblings();
assertNotNull(elementSiblings3);
assertEquals(1, elementSiblings3.size());
assertEquals("div", elementSiblings3.get(0).id());
Element div = doc.getElementById("div");
List<Element> elementSiblings4 = div.nextElementSiblings();
try {
Element elementSibling = elementSiblings4.get(0);
fail("This element should has no next siblings");
} catch (IndexOutOfBoundsException e) {
}
} | #vulnerable code
@Test
public void testNextElementSiblings() {
Document doc = Jsoup.parse("<li id='a'>a</li>" +
"<li id='b'>b</li>" +
"<li id='c'>c</li>");
Element element = doc.getElementById("a");
List<Element> elementSiblings = element.nextElementSiblings();
assertNotNull(elementSiblings);
assertEquals(2, elementSiblings.size());
Element element1 = doc.getElementById("c");
List<Element> elementSiblings1 = element1.nextElementSiblings();
assertNull(elementSiblings1);
}
#location 9
#vulnerability type NULL_DEREFERENCE | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Test
public void testNextElementSiblings() {
Document doc = Jsoup.parse("<ul id='ul'>" +
"<li id='a'>a</li>" +
"<li id='b'>b</li>" +
"<li id='c'>c</li>" +
"</ul>" +
"<div id='div'>" +
"<li id='d'>d</li>" +
"</div>");
Element element = doc.getElementById("a");
List<Element> elementSiblings = element.nextElementSiblings();
assertNotNull(elementSiblings);
assertEquals(2, elementSiblings.size());
assertEquals("b", elementSiblings.get(0).id());
assertEquals("c", elementSiblings.get(1).id());
Element element1 = doc.getElementById("b");
List<Element> elementSiblings1 = element1.nextElementSiblings();
assertNotNull(elementSiblings1);
assertEquals(1, elementSiblings1.size());
assertEquals("c", elementSiblings1.get(0).id());
Element element2 = doc.getElementById("c");
List<Element> elementSiblings2 = element2.nextElementSiblings();
assertEquals(0, elementSiblings2.size());
Element ul = doc.getElementById("ul");
List<Element> elementSiblings3 = ul.nextElementSiblings();
assertNotNull(elementSiblings3);
assertEquals(1, elementSiblings3.size());
assertEquals("div", elementSiblings3.get(0).id());
Element div = doc.getElementById("div");
List<Element> elementSiblings4 = div.nextElementSiblings();
try {
Element elementSibling = elementSiblings4.get(0);
fail("This element should has no next siblings");
} catch (IndexOutOfBoundsException e) {
}
} | #vulnerable code
@Test
public void testNextElementSiblings() {
Document doc = Jsoup.parse("<li id='a'>a</li>" +
"<li id='b'>b</li>" +
"<li id='c'>c</li>");
Element element = doc.getElementById("a");
List<Element> elementSiblings = element.nextElementSiblings();
assertNotNull(elementSiblings);
assertEquals(2, elementSiblings.size());
Element element1 = doc.getElementById("c");
List<Element> elementSiblings1 = element1.nextElementSiblings();
assertNull(elementSiblings1);
}
#location 12
#vulnerability type NULL_DEREFERENCE | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
private static void load(EscapeMode e, String file, int size) {
e.nameKeys = new String[size];
e.codeVals = new int[size];
e.codeKeys = new int[size];
e.nameVals = new String[size];
InputStream stream = Entities.class.getResourceAsStream(file);
if (stream == null)
throw new IllegalStateException("Could not read resource " + file + ". Make sure you copy resources for " + Entities.class.getCanonicalName());
int i = 0;
BufferedReader input = null;
try {
input = new BufferedReader(new InputStreamReader(stream, ASCII));
CharacterReader reader = new CharacterReader(input);
while (!reader.isEmpty()) {
// NotNestedLessLess=10913,824;1887
final String name = reader.consumeTo('=');
reader.advance();
final int cp1 = Integer.parseInt(reader.consumeToAny(codeDelims), codepointRadix);
final char codeDelim = reader.current();
reader.advance();
final int cp2;
if (codeDelim == ',') {
cp2 = Integer.parseInt(reader.consumeTo(';'), codepointRadix);
reader.advance();
} else {
cp2 = empty;
}
String indexS = reader.consumeTo('\n');
// default git checkout on windows will add a \r there, so remove
if (indexS.charAt(indexS.length() - 1) == '\r') {
indexS = indexS.substring(0, indexS.length() - 1);
}
final int index = Integer.parseInt(indexS, codepointRadix);
reader.advance();
e.nameKeys[i] = name;
e.codeVals[i] = cp1;
e.codeKeys[index] = cp1;
e.nameVals[index] = name;
if (cp2 != empty) {
multipoints.put(name, new String(new int[]{cp1, cp2}, 0, 2));
}
i++;
}
} finally {
try {
if (input != null) {
input.close();
}
} catch (IOException e1) {
//ignore exception
}
}
Validate.isTrue(i == size, "Unexpected count of entities loaded for " + file);
} | #vulnerable code
private static void load(EscapeMode e, String file, int size) {
e.nameKeys = new String[size];
e.codeVals = new int[size];
e.codeKeys = new int[size];
e.nameVals = new String[size];
InputStream stream = Entities.class.getResourceAsStream(file);
if (stream == null)
throw new IllegalStateException("Could not read resource " + file + ". Make sure you copy resources for " + Entities.class.getCanonicalName());
int i = 0;
BufferedReader input = new BufferedReader(new InputStreamReader(stream, ASCII));
CharacterReader reader = new CharacterReader(input);
while (!reader.isEmpty()) {
// NotNestedLessLess=10913,824;1887
final String name = reader.consumeTo('=');
reader.advance();
final int cp1 = Integer.parseInt(reader.consumeToAny(codeDelims), codepointRadix);
final char codeDelim = reader.current();
reader.advance();
final int cp2;
if (codeDelim == ',') {
cp2 = Integer.parseInt(reader.consumeTo(';'), codepointRadix);
reader.advance();
} else {
cp2 = empty;
}
String indexS = reader.consumeTo('\n');
// default git checkout on windows will add a \r there, so remove
if (indexS.charAt(indexS.length() - 1) == '\r') {
indexS = indexS.substring(0, indexS.length() - 1);
}
final int index = Integer.parseInt(indexS, codepointRadix);
reader.advance();
e.nameKeys[i] = name;
e.codeVals[i] = cp1;
e.codeKeys[index] = cp1;
e.nameVals[index] = name;
if (cp2 != empty) {
multipoints.put(name, new String(new int[]{cp1, cp2}, 0, 2));
}
i++;
}
Validate.isTrue(i == size, "Unexpected count of entities loaded for " + file);
}
#location 13
#vulnerability type RESOURCE_LEAK | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
void outerHtmlHead(StringBuilder accum, int depth) {
String html = StringEscapeUtils.escapeHtml(getWholeText());
if (parent() instanceof Element && !((Element) parent()).preserveWhitespace()) {
html = normaliseWhitespace(html);
}
if (siblingIndex() == 0 && parentNode instanceof Element && ((Element) parentNode).tag().canContainBlock() && !isBlank())
indent(accum, depth);
accum.append(html);
} | #vulnerable code
void outerHtml(StringBuilder accum) {
String html = StringEscapeUtils.escapeHtml(getWholeText());
if (parent() instanceof Element && !((Element) parent()).preserveWhitespace()) {
html = normaliseWhitespace(html);
}
if (siblingIndex() == 0 && parentNode instanceof Element && ((Element) parentNode).tag().canContainBlock() && !isBlank())
indent(accum);
accum.append(html);
}
#location 7
#vulnerability type NULL_DEREFERENCE | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
public static Document load(File in, String charsetName, String baseUri) throws IOException {
InputStream inStream = null;
try {
inStream = new FileInputStream(in);
ByteBuffer byteData = readToByteBuffer(inStream);
return parseByteData(byteData, charsetName, baseUri);
} finally {
if (inStream != null)
inStream.close();
}
} | #vulnerable code
public static Document load(File in, String charsetName, String baseUri) throws IOException {
InputStream inStream = new FileInputStream(in);
ByteBuffer byteData = readToByteBuffer(inStream);
Document doc = parseByteData(byteData, charsetName, baseUri);
inStream.close();
return doc;
}
#location 6
#vulnerability type RESOURCE_LEAK | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
public String consumeCssIdentifier() {
int start = pos;
while (!isEmpty() && (matchesWord() || matchesAny('-', '_')))
pos++;
return queue.substring(start, pos);
} | #vulnerable code
public String consumeCssIdentifier() {
StringBuilder accum = new StringBuilder();
Character c = peek();
while (!isEmpty() && (Character.isLetterOrDigit(c) || c.equals('-') || c.equals('_'))) {
accum.append(consume());
c = peek();
}
return accum.toString();
}
#location 4
#vulnerability type NULL_DEREFERENCE | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
protected void addChildren(int index, Node... children) {
Validate.notNull(children);
if (children.length == 0) {
return;
}
final List<Node> nodes = ensureChildNodes();
// fast path - if used as a wrap (index=0, children = child[0].parent.children - do inplace
final Node firstParent = children[0].parent();
if (firstParent != null && firstParent.childNodeSize() == children.length) {
boolean sameList = true;
final List<Node> firstParentNodes = firstParent.childNodes();
// identity check contents to see if same
int i = children.length;
while (i-- > 0) {
if (children[i] != firstParentNodes.get(i)) {
sameList = false;
break;
}
}
firstParent.empty();
nodes.addAll(index, Arrays.asList(children));
i = children.length;
while (i-- > 0) {
children[i].parentNode = this;
}
reindexChildren(index);
return;
}
Validate.noNullElements(children);
for (Node child : children) {
reparentChild(child);
}
nodes.addAll(index, Arrays.asList(children));
reindexChildren(index);
} | #vulnerable code
protected void addChildren(int index, Node... children) {
Validate.noNullElements(children);
final List<Node> nodes = ensureChildNodes();
for (Node child : children) {
reparentChild(child);
}
nodes.addAll(index, Arrays.asList(children));
reindexChildren(index);
}
#location 6
#vulnerability type NULL_DEREFERENCE | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
static String unescape(String string) {
if (!string.contains("&"))
return string;
Matcher m = unescapePattern.matcher(string); // &(#(x|X)?([0-9a-fA-F]+)|[a-zA-Z]+);?
StringBuffer accum = new StringBuffer(string.length()); // pity matcher can't use stringbuilder, avoid syncs
while (m.find()) {
int charval = -1;
String num = m.group(3);
if (num != null) {
try {
int base = m.group(2) != null ? 16 : 10; // 2 is hex indicator
charval = Integer.valueOf(num, base);
} catch (NumberFormatException e) {
} // skip
} else {
String name = m.group(1);
if (full.containsKey(name))
charval = full.get(name);
}
if (charval != -1 || charval > 0xFFFF) { // out of range
String c = Character.toString((char) charval);
m.appendReplacement(accum, c);
} else {
m.appendReplacement(accum, m.group(0)); // replace with original string
}
}
m.appendTail(accum);
return accum.toString();
} | #vulnerable code
static String unescape(String string) {
if (!string.contains("&"))
return string;
Matcher m = unescapePattern.matcher(string); // &(#(x|X)?([0-9a-fA-F]+)|[a-zA-Z]+);?
StringBuffer accum = new StringBuffer(string.length()); // pity matcher can't use stringbuilder, avoid syncs
while (m.find()) {
int charval = -1;
String num = m.group(3);
if (num != null) {
try {
int base = m.group(2) != null ? 16 : 10; // 2 is hex indicator
charval = Integer.valueOf(num, base);
} catch (NumberFormatException e) {
} // skip
} else {
String name = m.group(1).toLowerCase();
if (full.containsKey(name))
charval = full.get(name);
}
if (charval != -1 || charval > 0xFFFF) { // out of range
String c = Character.toString((char) charval);
m.appendReplacement(accum, c);
} else {
m.appendReplacement(accum, m.group(0)); // replace with original string
}
}
m.appendTail(accum);
return accum.toString();
}
#location 18
#vulnerability type NULL_DEREFERENCE | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
private static void load(EscapeMode e, String file, int size) {
e.nameKeys = new String[size];
e.codeVals = new int[size];
e.codeKeys = new int[size];
e.nameVals = new String[size];
InputStream stream = Entities.class.getResourceAsStream(file);
if (stream == null)
throw new IllegalStateException("Could not read resource " + file + ". Make sure you copy resources for " + Entities.class.getCanonicalName());
int i = 0;
try {
ByteBuffer bytes = DataUtil.readToByteBuffer(stream, 0);
String contents = Charset.forName("ascii").decode(bytes).toString();
CharacterReader reader = new CharacterReader(contents);
while (!reader.isEmpty()) {
// NotNestedLessLess=10913,824;1887
final String name = reader.consumeTo('=');
reader.advance();
final int cp1 = Integer.parseInt(reader.consumeToAny(codeDelims), codepointRadix);
final char codeDelim = reader.current();
reader.advance();
final int cp2;
if (codeDelim == ',') {
cp2 = Integer.parseInt(reader.consumeTo(';'), codepointRadix);
reader.advance();
} else {
cp2 = empty;
}
final int index = Integer.parseInt(reader.consumeTo('\n'), codepointRadix);
reader.advance();
e.nameKeys[i] = name;
e.codeVals[i] = cp1;
e.codeKeys[index] = cp1;
e.nameVals[index] = name;
if (cp2 != empty) {
multipoints.put(name, new String(new int[]{cp1, cp2}, 0, 2));
}
i++;
}
} catch (IOException err) {
throw new IllegalStateException("Error reading resource " + file);
}
} | #vulnerable code
private static void load(EscapeMode e, String file, int size) {
e.nameKeys = new String[size];
e.codeVals = new int[size];
e.codeKeys = new int[size];
e.nameVals = new String[size];
InputStream stream = Entities.class.getResourceAsStream(file);
if (stream == null)
throw new IllegalStateException("Could not read resource " + file + ". Make sure you copy resources for " + Entities.class.getCanonicalName());
BufferedReader reader = new BufferedReader(new InputStreamReader(stream));
String entry;
int i = 0;
try {
while ((entry = reader.readLine()) != null) {
// NotNestedLessLess=10913,824;1887
final Matcher match = entityPattern.matcher(entry);
if (match.find()) {
final String name = match.group(1);
final int cp1 = Integer.parseInt(match.group(2), codepointRadix);
final int cp2 = match.group(3) != null ? Integer.parseInt(match.group(3), codepointRadix) : empty;
final int index = Integer.parseInt(match.group(4), codepointRadix);
e.nameKeys[i] = name;
e.codeVals[i] = cp1;
e.codeKeys[index] = cp1;
e.nameVals[index] = name;
if (cp2 != empty) {
multipoints.put(name, new String(new int[]{cp1, cp2}, 0, 2));
}
i++;
}
}
reader.close();
} catch (IOException err) {
throw new IllegalStateException("Error reading resource " + file);
}
}
#location 36
#vulnerability type RESOURCE_LEAK | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
private void parseStartTag() {
tq.consume("<");
Attributes attributes = new Attributes();
String tagName = tq.consumeWord();
while (!tq.matchesAny("<", "/>", ">") && !tq.isEmpty()) {
Attribute attribute = parseAttribute();
if (attribute != null)
attributes.put(attribute);
}
Tag tag = Tag.valueOf(tagName);
StartTag startTag = new StartTag(tag, attributes);
Element child = new Element(startTag);
boolean emptyTag;
if (tq.matchChomp("/>")) { // empty tag, don't add to stack
emptyTag = true;
} else {
tq.matchChomp(">"); // safe because checked above (or ran out of data)
emptyTag = false;
}
// pc data only tags (textarea, script): chomp to end tag, add content as text node
if (tag.isData()) {
String data = tq.chompTo("</" + tagName);
tq.chompTo(">");
TextNode textNode = TextNode.createFromEncoded(data); // TODO: maybe have this be another data type? So doesn't come back in text()?
child.addChild(textNode);
if (tag.equals(titleTag))
doc.setTitle(child.text());
}
// switch between html, head, body, to preserve doc structure
if (tag.equals(htmlTag)) {
doc.getAttributes().mergeAttributes(attributes);
} else if (tag.equals(headTag)) {
doc.getHead().getAttributes().mergeAttributes(attributes);
// head is on stack from start, no action required
} else if (last().getTag().equals(headTag) && !headTag.canContain(tag)) {
// switch to body
stack.removeLast();
stack.addLast(doc.getBody());
last().addChild(child);
if (!emptyTag)
stack.addLast(child);
} else if (tag.equals(bodyTag) && last().getTag().equals(htmlTag)) {
doc.getBody().getAttributes().mergeAttributes(attributes);
stack.removeLast();
stack.addLast(doc.getBody());
} else {
Element parent = popStackToSuitableContainer(tag);
parent.addChild(child);
if (!emptyTag && !tag.isData()) // TODO: only check for data here because last() == head is wrong; should be ancestor is head
stack.addLast(child);
}
} | #vulnerable code
private void parseStartTag() {
tq.consume("<");
Attributes attributes = new Attributes();
String tagName = tq.consumeWord();
while (!tq.matches("<") && !tq.matches("/>") && !tq.matches(">") && !tq.isEmpty()) {
Attribute attribute = parseAttribute();
if (attribute != null)
attributes.put(attribute);
}
Tag tag = Tag.valueOf(tagName);
StartTag startTag = new StartTag(tag, attributes);
Element child = new Element(startTag);
boolean emptyTag;
if (tq.matchChomp("/>")) { // empty tag, don't add to stack
emptyTag = true;
} else {
tq.matchChomp(">"); // safe because checked above (or ran out of data)
emptyTag = false;
}
// pc data only tags (textarea, script): chomp to end tag, add content as text node
if (tag.isData()) {
String data = tq.chompTo("</" + tagName);
tq.chompTo(">");
TextNode textNode = TextNode.createFromEncoded(data);
child.addChild(textNode);
if (tag.equals(titleTag))
doc.setTitle(child.text());
}
// switch between html, head, body, to preserve doc structure
if (tag.equals(htmlTag)) {
doc.getAttributes().mergeAttributes(attributes);
} else if (tag.equals(headTag)) {
doc.getHead().getAttributes().mergeAttributes(attributes);
// head is on stack from start, no action required
} else if (last().getTag().equals(headTag) && !headTag.canContain(tag)) {
// switch to body
stack.removeLast();
stack.addLast(doc.getBody());
last().addChild(child);
if (!emptyTag)
stack.addLast(child);
} else if (tag.equals(bodyTag) && last().getTag().equals(htmlTag)) {
doc.getBody().getAttributes().mergeAttributes(attributes);
stack.removeLast();
stack.addLast(doc.getBody());
} else {
Element parent = popStackToSuitableContainer(tag);
parent.addChild(child);
if (!emptyTag && !tag.isData()) // TODO: only check for data here because last() == head is wrong; should be ancestor is head
stack.addLast(child);
}
}
#location 54
#vulnerability type NULL_DEREFERENCE | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
private static String ihVal(String key, Document doc) {
final Element first = doc.select("th:contains(" + key + ") + td").first();
return first != null ? first.text() : null;
} | #vulnerable code
private static String ihVal(String key, Document doc) {
return doc.select("th:contains(" + key + ") + td").first().text();
}
#location 2
#vulnerability type NULL_DEREFERENCE | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
void outerHtmlHead(Appendable accum, int depth, Document.OutputSettings out) throws IOException {
final boolean prettyPrint = out.prettyPrint();
if (prettyPrint && ((siblingIndex() == 0 && parentNode instanceof Element && ((Element) parentNode).tag().formatAsBlock() && !isBlank()) || (out.outline() && siblingNodes().size()>0 && !isBlank()) ))
indent(accum, depth, out);
final boolean normaliseWhite = prettyPrint && !Element.preserveWhitespace(parentNode);
final boolean stripWhite = prettyPrint && parentNode instanceof Document;
Entities.escape(accum, coreValue(), out, false, normaliseWhite, stripWhite);
} | #vulnerable code
void outerHtmlHead(Appendable accum, int depth, Document.OutputSettings out) throws IOException {
if (out.prettyPrint() && ((siblingIndex() == 0 && parentNode instanceof Element && ((Element) parentNode).tag().formatAsBlock() && !isBlank()) || (out.outline() && siblingNodes().size()>0 && !isBlank()) ))
indent(accum, depth, out);
boolean normaliseWhite = out.prettyPrint() && !Element.preserveWhitespace(parent());
Entities.escape(accum, coreValue(), out, false, normaliseWhite, false);
}
#location 5
#vulnerability type NULL_DEREFERENCE | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Test
public void testNamespace() throws Exception
{
final String namespace = "TestNamespace";
CuratorFrameworkFactory.Builder builder = CuratorFrameworkFactory.builder();
CuratorFramework client = builder.connectString(server.getConnectString()).retryPolicy(new RetryOneTime(1)).namespace(namespace).build();
client.start();
try
{
String actualPath = client.create().forPath("/test");
Assert.assertEquals(actualPath, "/test");
Assert.assertNotNull(client.getZookeeperClient().getZooKeeper().exists("/" + namespace + "/test", false));
Assert.assertNull(client.getZookeeperClient().getZooKeeper().exists("/test", false));
actualPath = client.nonNamespaceView().create().forPath("/non");
Assert.assertEquals(actualPath, "/non");
Assert.assertNotNull(client.getZookeeperClient().getZooKeeper().exists("/non", false));
client.create().forPath("/test/child", "hey".getBytes());
byte[] bytes = client.getData().forPath("/test/child");
Assert.assertEquals(bytes, "hey".getBytes());
bytes = client.nonNamespaceView().getData().forPath("/" + namespace + "/test/child");
Assert.assertEquals(bytes, "hey".getBytes());
}
finally
{
client.close();
}
} | #vulnerable code
@Test
public void testNamespace() throws Exception
{
final String namespace = "TestNamespace";
CuratorFrameworkFactory.Builder builder = CuratorFrameworkFactory.builder();
CuratorFramework client = builder.connectString(server.getConnectString()).retryPolicy(new RetryOneTime(1)).namespace(namespace).build();
client.start();
try
{
String actualPath = client.create().forPath("/test", new byte[0]);
Assert.assertEquals(actualPath, "/test");
Assert.assertNotNull(client.getZookeeperClient().getZooKeeper().exists("/" + namespace + "/test", false));
Assert.assertNull(client.getZookeeperClient().getZooKeeper().exists("/test", false));
actualPath = client.nonNamespaceView().create().forPath("/non", new byte[0]);
Assert.assertEquals(actualPath, "/non");
Assert.assertNotNull(client.getZookeeperClient().getZooKeeper().exists("/non", false));
client.create().forPath("/test/child", "hey".getBytes());
byte[] bytes = client.getData().forPath("/test/child");
Assert.assertEquals(bytes, "hey".getBytes());
bytes = client.nonNamespaceView().getData().forPath("/" + namespace + "/test/child");
Assert.assertEquals(bytes, "hey".getBytes());
}
finally
{
client.close();
}
}
#location 26
#vulnerability type RESOURCE_LEAK | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Test
public void testNamespaceInBackground() throws Exception
{
CuratorFrameworkFactory.Builder builder = CuratorFrameworkFactory.builder();
CuratorFramework client = builder.connectString(server.getConnectString()).namespace("aisa").retryPolicy(new RetryOneTime(1)).build();
client.start();
try
{
final SynchronousQueue<String> queue = new SynchronousQueue<String>();
CuratorListener listener = new CuratorListener()
{
@Override
public void eventReceived(CuratorFramework client, CuratorEvent event) throws Exception
{
if ( event.getType() == CuratorEventType.EXISTS )
{
queue.put(event.getPath());
}
}
};
client.getCuratorListenable().addListener(listener);
client.create().forPath("/base");
client.checkExists().inBackground().forPath("/base");
String path = queue.poll(10, TimeUnit.SECONDS);
Assert.assertEquals(path, "/base");
client.getCuratorListenable().removeListener(listener);
BackgroundCallback callback = new BackgroundCallback()
{
@Override
public void processResult(CuratorFramework client, CuratorEvent event) throws Exception
{
queue.put(event.getPath());
}
};
client.getChildren().inBackground(callback).forPath("/base");
path = queue.poll(10, TimeUnit.SECONDS);
Assert.assertEquals(path, "/base");
}
finally
{
client.close();
}
} | #vulnerable code
@Test
public void testNamespaceInBackground() throws Exception
{
CuratorFrameworkFactory.Builder builder = CuratorFrameworkFactory.builder();
CuratorFramework client = builder.connectString(server.getConnectString()).namespace("aisa").retryPolicy(new RetryOneTime(1)).build();
client.start();
try
{
final SynchronousQueue<String> queue = new SynchronousQueue<String>();
CuratorListener listener = new CuratorListener()
{
@Override
public void eventReceived(CuratorFramework client, CuratorEvent event) throws Exception
{
if ( event.getType() == CuratorEventType.EXISTS )
{
queue.put(event.getPath());
}
}
};
client.getCuratorListenable().addListener(listener);
client.create().forPath("/base", new byte[0]);
client.checkExists().inBackground().forPath("/base");
String path = queue.poll(10, TimeUnit.SECONDS);
Assert.assertEquals(path, "/base");
client.getCuratorListenable().removeListener(listener);
BackgroundCallback callback = new BackgroundCallback()
{
@Override
public void processResult(CuratorFramework client, CuratorEvent event) throws Exception
{
queue.put(event.getPath());
}
};
client.getChildren().inBackground(callback).forPath("/base");
path = queue.poll(10, TimeUnit.SECONDS);
Assert.assertEquals(path, "/base");
}
finally
{
client.close();
}
}
#location 18
#vulnerability type RESOURCE_LEAK | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Test
public void testNamespaceWithWatcher() throws Exception
{
CuratorFrameworkFactory.Builder builder = CuratorFrameworkFactory.builder();
CuratorFramework client = builder.connectString(server.getConnectString()).namespace("aisa").retryPolicy(new RetryOneTime(1)).build();
client.start();
try
{
final SynchronousQueue<String> queue = new SynchronousQueue<String>();
Watcher watcher = new Watcher()
{
@Override
public void process(WatchedEvent event)
{
try
{
queue.put(event.getPath());
}
catch ( InterruptedException e )
{
throw new Error(e);
}
}
};
client.create().forPath("/base");
client.getChildren().usingWatcher(watcher).forPath("/base");
client.create().forPath("/base/child");
String path = queue.take();
Assert.assertEquals(path, "/base");
}
finally
{
client.close();
}
} | #vulnerable code
@Test
public void testNamespaceWithWatcher() throws Exception
{
CuratorFrameworkFactory.Builder builder = CuratorFrameworkFactory.builder();
CuratorFramework client = builder.connectString(server.getConnectString()).namespace("aisa").retryPolicy(new RetryOneTime(1)).build();
client.start();
try
{
final SynchronousQueue<String> queue = new SynchronousQueue<String>();
Watcher watcher = new Watcher()
{
@Override
public void process(WatchedEvent event)
{
try
{
queue.put(event.getPath());
}
catch ( InterruptedException e )
{
throw new Error(e);
}
}
};
client.create().forPath("/base", new byte[0]);
client.getChildren().usingWatcher(watcher).forPath("/base");
client.create().forPath("/base/child", new byte[0]);
String path = queue.take();
Assert.assertEquals(path, "/base");
}
finally
{
client.close();
}
}
#location 18
#vulnerability type RESOURCE_LEAK | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
public void transactionObject(final String trytes) {
if (StringUtils.isEmpty(trytes)) {
log.warn("Warning: empty trytes in input for transactionObject");
return;
}
// validity check
for (int i = 2279; i < 2295; i++) {
if (trytes.charAt(i) != '9') {
log.warn("Trytes {} does not seem a valid tryte", trytes);
return;
}
}
int[] transactionTrits = Converter.trits(trytes);
int[] hash = new int[243];
ICurl curl = SpongeFactory.create(SpongeFactory.Mode.CURLP81);
// generate the correct transaction hash
curl.reset();
curl.absorb(transactionTrits, 0, transactionTrits.length);
curl.squeeze(hash, 0, hash.length);
this.setHash(Converter.trytes(hash));
this.setSignatureFragments(trytes.substring(0, 2187));
this.setAddress(trytes.substring(2187, 2268));
this.setValue(Converter.longValue(Arrays.copyOfRange(transactionTrits, 6804, 6837)));
this.setObsoleteTag(trytes.substring(2295, 2322));
this.setTimestamp(Converter.longValue(Arrays.copyOfRange(transactionTrits, 6966, 6993)));
this.setCurrentIndex(Converter.longValue(Arrays.copyOfRange(transactionTrits, 6993, 7020)));
this.setLastIndex(Converter.longValue(Arrays.copyOfRange(transactionTrits, 7020, 7047)));
this.setBundle(trytes.substring(2349, 2430));
this.setTrunkTransaction(trytes.substring(2430, 2511));
this.setBranchTransaction(trytes.substring(2511, 2592));
this.setTag(trytes.substring(2592, 2619));
this.setAttachmentTimestamp(Converter.longValue(Arrays.copyOfRange(transactionTrits, 7857, 7884)) / 1000);
this.setAttachmentTimestampLowerBound(Converter.longValue(Arrays.copyOfRange(transactionTrits, 7884, 7911)));
this.setAttachmentTimestampUpperBound(Converter.longValue(Arrays.copyOfRange(transactionTrits, 7911, 7938)));
this.setNonce(trytes.substring(2646, 2673));
} | #vulnerable code
public void transactionObject(final String trytes) {
if (StringUtils.isEmpty(trytes)) {
log.warn("Warning: empty trytes in input for transactionObject");
return;
}
// validity check
for (int i = 2279; i < 2295; i++) {
if (trytes.charAt(i) != '9') {
log.warn("Trytes {} does not seem a valid tryte", trytes);
return;
}
}
int[] transactionTrits = Converter.trits(trytes);
int[] hash = new int[243];
ICurl curl = SpongeFactory.create(SpongeFactory.Mode.CURL);
// generate the correct transaction hash
curl.reset();
curl.absorb(transactionTrits, 0, transactionTrits.length);
curl.squeeze(hash, 0, hash.length);
this.setHash(Converter.trytes(hash));
this.setSignatureFragments(trytes.substring(0, 2187));
this.setAddress(trytes.substring(2187, 2268));
this.setValue(Converter.longValue(Arrays.copyOfRange(transactionTrits, 6804, 6837)));
this.setTag(trytes.substring(2295, 2322));
this.setTimestamp(Converter.longValue(Arrays.copyOfRange(transactionTrits, 6966, 6993)));
this.setCurrentIndex(Converter.longValue(Arrays.copyOfRange(transactionTrits, 6993, 7020)));
this.setLastIndex(Converter.longValue(Arrays.copyOfRange(transactionTrits, 7020, 7047)));
this.setBundle(trytes.substring(2349, 2430));
this.setTrunkTransaction(trytes.substring(2430, 2511));
this.setBranchTransaction(trytes.substring(2511, 2592));
this.setNonce(trytes.substring(2592, 2673));
}
#location 21
#vulnerability type NULL_DEREFERENCE | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
public void transactionObject(final String trytes) {
if (StringUtils.isEmpty(trytes)) {
log.warn("Warning: empty trytes in input for transactionObject");
return;
}
// validity check
for (int i = 2279; i < 2295; i++) {
if (trytes.charAt(i) != '9') {
log.warn("Trytes {} does not seem a valid tryte", trytes);
return;
}
}
int[] transactionTrits = Converter.trits(trytes);
int[] hash = new int[243];
ICurl curl = SpongeFactory.create(SpongeFactory.Mode.CURLP81);
// generate the correct transaction hash
curl.reset();
curl.absorb(transactionTrits, 0, transactionTrits.length);
curl.squeeze(hash, 0, hash.length);
this.setHash(Converter.trytes(hash));
this.setSignatureFragments(trytes.substring(0, 2187));
this.setAddress(trytes.substring(2187, 2268));
this.setValue(Converter.longValue(Arrays.copyOfRange(transactionTrits, 6804, 6837)));
this.setObsoleteTag(trytes.substring(2295, 2322));
this.setTimestamp(Converter.longValue(Arrays.copyOfRange(transactionTrits, 6966, 6993)));
this.setCurrentIndex(Converter.longValue(Arrays.copyOfRange(transactionTrits, 6993, 7020)));
this.setLastIndex(Converter.longValue(Arrays.copyOfRange(transactionTrits, 7020, 7047)));
this.setBundle(trytes.substring(2349, 2430));
this.setTrunkTransaction(trytes.substring(2430, 2511));
this.setBranchTransaction(trytes.substring(2511, 2592));
this.setTag(trytes.substring(2592, 2619));
this.setAttachmentTimestamp(Converter.longValue(Arrays.copyOfRange(transactionTrits, 7857, 7884)) / 1000);
this.setAttachmentTimestampLowerBound(Converter.longValue(Arrays.copyOfRange(transactionTrits, 7884, 7911)));
this.setAttachmentTimestampUpperBound(Converter.longValue(Arrays.copyOfRange(transactionTrits, 7911, 7938)));
this.setNonce(trytes.substring(2646, 2673));
} | #vulnerable code
public void transactionObject(final String trytes) {
if (StringUtils.isEmpty(trytes)) {
log.warn("Warning: empty trytes in input for transactionObject");
return;
}
// validity check
for (int i = 2279; i < 2295; i++) {
if (trytes.charAt(i) != '9') {
log.warn("Trytes {} does not seem a valid tryte", trytes);
return;
}
}
int[] transactionTrits = Converter.trits(trytes);
int[] hash = new int[243];
ICurl curl = SpongeFactory.create(SpongeFactory.Mode.CURL);
// generate the correct transaction hash
curl.reset();
curl.absorb(transactionTrits, 0, transactionTrits.length);
curl.squeeze(hash, 0, hash.length);
this.setHash(Converter.trytes(hash));
this.setSignatureFragments(trytes.substring(0, 2187));
this.setAddress(trytes.substring(2187, 2268));
this.setValue(Converter.longValue(Arrays.copyOfRange(transactionTrits, 6804, 6837)));
this.setTag(trytes.substring(2295, 2322));
this.setTimestamp(Converter.longValue(Arrays.copyOfRange(transactionTrits, 6966, 6993)));
this.setCurrentIndex(Converter.longValue(Arrays.copyOfRange(transactionTrits, 6993, 7020)));
this.setLastIndex(Converter.longValue(Arrays.copyOfRange(transactionTrits, 7020, 7047)));
this.setBundle(trytes.substring(2349, 2430));
this.setTrunkTransaction(trytes.substring(2430, 2511));
this.setBranchTransaction(trytes.substring(2511, 2592));
this.setNonce(trytes.substring(2592, 2673));
}
#location 21
#vulnerability type NULL_DEREFERENCE | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
public GetTransferResponse getTransfers(String seed, Integer start, Integer end, Boolean inclusionStates) throws ArgumentException, InvalidBundleException, InvalidSignatureException {
// validate & if needed pad seed
if ( (seed = InputValidator.validateSeed(seed)) == null) {
throw new IllegalStateException("Invalid Seed");
}
start = start != null ? 0 : start;
end = end == null ? null : end;
inclusionStates = inclusionStates != null ? inclusionStates : null;
if (start > end || end > (start + 500)) {
throw new ArgumentException();
}
StopWatch sw = new StopWatch();
sw.start();
System.out.println("GetTransfer started");
GetNewAddressResponse gnr = getNewAddress(seed, start, false, end == null ? end - start : end, true);
if (gnr != null && gnr.getAddresses() != null) {
System.out.println("GetTransfers after getNewAddresses " + sw.getTime() + " ms");
Bundle[] bundles = bundlesFromAddresses(gnr.getAddresses().toArray(new String[gnr.getAddresses().size()]), inclusionStates);
System.out.println("GetTransfers after bundlesFromAddresses " + sw.getTime() + " ms");
sw.stop();
return GetTransferResponse.create(bundles);
}
sw.stop();
return null;
} | #vulnerable code
public GetTransferResponse getTransfers(String seed, Integer start, Integer end, Boolean inclusionStates) throws ArgumentException, InvalidBundleException, InvalidSignatureException {
start = start != null ? 0 : start;
end = end == null ? null : end;
inclusionStates = inclusionStates != null ? inclusionStates : null;
if (start > end || end > (start + 500)) {
throw new ArgumentException();
}
GetNewAddressResponse gnr = getNewAddress(seed, start, false, end == null ? end - start : end, true);
if (gnr != null && gnr.getAddresses() != null) {
Bundle[] bundles = bundlesFromAddresses(gnr.getAddresses().toArray(new String[gnr.getAddresses().size()]), inclusionStates);
return GetTransferResponse.create(bundles);
}
return null;
}
#location 12
#vulnerability type NULL_DEREFERENCE | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
private synchronized boolean send(byte[] bytes) {
// buffering
if (pendings.position() + bytes.length > pendings.capacity()) {
LOG.severe("Cannot send logs to " + server.toString());
return false;
}
pendings.put(bytes);
try {
// suppress reconnection burst
if (!reconnector.enableReconnection(System.currentTimeMillis())) {
return true;
}
// send pending data
flush();
} catch (IOException e) {
// close socket
close();
}
return true;
} | #vulnerable code
private synchronized boolean send(byte[] bytes) {
// buffering
if (pendings.position() + bytes.length > pendings.capacity()) {
LOG.severe("Cannot send logs to " + server.toString());
return false;
}
pendings.put(bytes);
try {
// suppress reconnection burst
if (!reconnector.enableReconnection(System.currentTimeMillis())) {
return true;
}
// check whether connection is established or not
reconnect();
// write data
out.write(getBuffer());
out.flush();
clearBuffer();
} catch (IOException e) {
// close socket
close();
}
return true;
}
#location 25
#vulnerability type RESOURCE_LEAK | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Test
public void testClose() throws Exception {
// use NullSender
Properties props = System.getProperties();
props.setProperty(Config.FLUENT_SENDER_CLASS, NullSender.class.getName());
// create logger objects
FluentLogger.getLogger("tag1");
FluentLogger.getLogger("tag2");
FluentLogger.getLogger("tag3");
Map<String, FluentLogger> loggers;
{
loggers = FluentLogger.getLoggers();
assertEquals(3, loggers.size());
}
// close and delete
FluentLogger.close();
{
loggers = FluentLogger.getLoggers();
assertEquals(0, loggers.size());
}
props.remove(Config.FLUENT_SENDER_CLASS);
} | #vulnerable code
@Test
public void testClose() throws Exception {
// use NullSender
Properties props = System.getProperties();
props.setProperty(Config.FLUENT_SENDER_CLASS, NullSender.class.getName());
// create logger objects
FluentLogger.getLogger("tag1");
FluentLogger.getLogger("tag2");
FluentLogger.getLogger("tag3");
Map<String, FluentLogger> loggers;
{
loggers = FluentLogger.getLoggers();
assertEquals(3, loggers.size());
}
// close and delete
FluentLogger.close();
{
loggers = FluentLogger.getLoggers();
assertEquals(0, loggers.size());
}
}
#location 9
#vulnerability type RESOURCE_LEAK | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
public void run() {
try {
final Socket socket = serverSocket.accept();
Thread th = new Thread() {
public void run() {
try {
process.process(msgpack, socket);
} catch (IOException e) { // ignore
}
}
};
th.start();
} catch (IOException e) {
e.printStackTrace();
}
} | #vulnerable code
public void run() throws IOException {
Socket socket = serverSock.accept();
BufferedInputStream in = new BufferedInputStream(socket.getInputStream());
// TODO
}
#location 3
#vulnerability type RESOURCE_LEAK | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Test
public void testClose() throws Exception {
// use NullSender
Properties props = System.getProperties();
props.setProperty(Config.FLUENT_SENDER_CLASS, NullSender.class.getName());
// create logger objects
FluentLogger.getLogger("tag1");
FluentLogger.getLogger("tag2");
FluentLogger.getLogger("tag3");
Map<String, FluentLogger> loggers;
{
loggers = FluentLogger.getLoggers();
assertEquals(3, loggers.size());
}
// close and delete
FluentLogger.close();
{
loggers = FluentLogger.getLoggers();
assertEquals(0, loggers.size());
}
props.remove(Config.FLUENT_SENDER_CLASS);
} | #vulnerable code
@Test
public void testClose() throws Exception {
// use NullSender
Properties props = System.getProperties();
props.setProperty(Config.FLUENT_SENDER_CLASS, NullSender.class.getName());
// create logger objects
FluentLogger.getLogger("tag1");
FluentLogger.getLogger("tag2");
FluentLogger.getLogger("tag3");
Map<String, FluentLogger> loggers;
{
loggers = FluentLogger.getLoggers();
assertEquals(3, loggers.size());
}
// close and delete
FluentLogger.close();
{
loggers = FluentLogger.getLoggers();
assertEquals(0, loggers.size());
}
}
#location 8
#vulnerability type RESOURCE_LEAK | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
private synchronized boolean send(byte[] bytes) {
// buffering
if (pendings.position() + bytes.length > pendings.capacity()) {
LOG.severe("Cannot send logs to " + server.toString());
return false;
}
pendings.put(bytes);
// suppress reconnection burst
if (!reconnector.enableReconnection(System.currentTimeMillis())) {
return true;
}
// send pending data
flush();
return true;
} | #vulnerable code
private synchronized boolean send(byte[] bytes) {
// buffering
if (pendings.position() + bytes.length > pendings.capacity()) {
LOG.severe("Cannot send logs to " + server.toString());
return false;
}
pendings.put(bytes);
try {
// suppress reconnection burst
if (!reconnector.enableReconnection(System.currentTimeMillis())) {
return true;
}
// send pending data
flush();
} catch (IOException e) {
// close socket
close();
}
return true;
}
#location 19
#vulnerability type RESOURCE_LEAK | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Test
public void testClose() throws Exception {
// use NullSender
Properties props = System.getProperties();
props.setProperty(Config.FLUENT_SENDER_CLASS, NullSender.class.getName());
// create logger objects
FluentLogger.getLogger("tag1");
FluentLogger.getLogger("tag2");
FluentLogger.getLogger("tag3");
Map<String, FluentLogger> loggers;
{
loggers = FluentLogger.getLoggers();
assertEquals(3, loggers.size());
}
// close and delete
FluentLogger.close();
{
loggers = FluentLogger.getLoggers();
assertEquals(0, loggers.size());
}
props.remove(Config.FLUENT_SENDER_CLASS);
} | #vulnerable code
@Test
public void testClose() throws Exception {
// use NullSender
Properties props = System.getProperties();
props.setProperty(Config.FLUENT_SENDER_CLASS, NullSender.class.getName());
// create logger objects
FluentLogger.getLogger("tag1");
FluentLogger.getLogger("tag2");
FluentLogger.getLogger("tag3");
Map<String, FluentLogger> loggers;
{
loggers = FluentLogger.getLoggers();
assertEquals(3, loggers.size());
}
// close and delete
FluentLogger.close();
{
loggers = FluentLogger.getLoggers();
assertEquals(0, loggers.size());
}
}
#location 10
#vulnerability type RESOURCE_LEAK | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
public void run() {
try {
final Socket socket = serverSocket.accept();
Thread th = new Thread() {
public void run() {
try {
process.process(msgpack, socket);
} catch (IOException e) { // ignore
}
}
};
th.start();
} catch (IOException e) {
e.printStackTrace();
}
} | #vulnerable code
public void run() throws IOException {
Socket socket = serverSock.accept();
BufferedInputStream in = new BufferedInputStream(socket.getInputStream());
// TODO
}
#location 3
#vulnerability type RESOURCE_LEAK | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Test
public void testRenderMultipleObjects() {
TestObject testObject = new TestObject();
// step 1: add one object.
Result result = new Result(200);
result.render(testObject);
assertEquals(testObject, result.getRenderable());
// step 2: add a second object (string is just a dummy)
// => we expect to get a map from the result now...
String string = new String("test");
result.render(string);
assertTrue(result.getRenderable() instanceof Map);
Map<String, Object> resultMap = (Map) result.getRenderable();
assertEquals(string, resultMap.get("string"));
assertEquals(testObject, resultMap.get("testObject"));
// step 3: add same object => we expect an illegal argument exception as the map
// cannot handle that case:
TestObject anotherObject = new TestObject();
boolean gotException = false;
try {
result.render(anotherObject);
} catch (IllegalArgumentException e) {
gotException = true;
}
assertTrue(gotException);
// step 4: add an entry
Entry<String, Object> entry = new AbstractMap.SimpleImmutableEntry<String, Object>("anotherObject", anotherObject);
result.render(entry);
resultMap = (Map) result.getRenderable();
assertEquals(3, resultMap.size());
assertEquals(anotherObject, resultMap.get("anotherObject"));
// step 5: add another map and check that conversion works:
Map<String, Object> mapToRender = Maps.newHashMap();
String anotherString = new String("anotherString");
TestObject anotherTestObject = new TestObject();
mapToRender.put("anotherString", anotherString);
mapToRender.put("anotherTestObject", anotherTestObject);
result.render(mapToRender);
resultMap = (Map) result.getRenderable();
assertEquals(2, resultMap.size());
assertEquals(anotherString, resultMap.get("anotherString"));
assertEquals(anotherTestObject, resultMap.get("anotherTestObject"));
} | #vulnerable code
@Test
public void testRenderMultipleObjects() {
TestObject testObject = new TestObject();
// step 1: add one object.
Result result = new Result(200);
result.render(testObject);
assertEquals(testObject, result.getRenderable());
// step 2: add a second object (string is just a dummy)
// => we expect to get a map from the result now...
String string = new String("test");
result.render(string);
assertTrue(result.getRenderable() instanceof Map);
Map<String, Object> resultMap = (Map) result.getRenderable();
assertEquals(string, resultMap.get("string"));
assertEquals(testObject, resultMap.get("testObject"));
// step 3: add same object => we expect an illegal argument exception as the map
// cannot handle that case:
TestObject anotherObject = new TestObject();
boolean gotException = false;
try {
result.render(anotherObject);
} catch (IllegalArgumentException e) {
gotException = true;
}
assertTrue(gotException);
// step 4: add an entry
Entry<String, Object> entry = new AbstractMap.SimpleImmutableEntry<String, Object>("anotherObject", anotherObject);
result.render(entry);
resultMap = (Map) result.getRenderable();
assertEquals(3, resultMap.size());
assertEquals(anotherObject, resultMap.get("anotherObject"));
// step 5: add another map and check that conversion works:
Map<String, Object> mapToRender = Maps.newHashMap();
String anotherString = new String("anotherString");
TestObject anotherTestObject = new TestObject();
mapToRender.put("anotherString", anotherString);
mapToRender.put("anotherTestObject", anotherTestObject);
result.render(mapToRender);
resultMap = (Map) result.getRenderable();
assertEquals(5, resultMap.size());
assertEquals(anotherString, resultMap.get("anotherString"));
assertEquals(anotherTestObject, resultMap.get("anotherTestObject"));
}
#location 21
#vulnerability type NULL_DEREFERENCE | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Test
public void testRenderingOfStringObjectPairsWorks() {
String object1 = new String("stringy1");
String object2 = new String("stringy2");
// step 1: add one object.
Result result = new Result(200);
result.render("object1", object1);
result.render("object2", object2);
Map<String, Object> resultMap = (Map) result.getRenderable();
assertEquals(object1, resultMap.get("object1"));
assertEquals(object2, resultMap.get("object2"));
} | #vulnerable code
@Test
public void testRenderingOfStringObjectPairsWorks() {
String object1 = new String("stringy1");
String object2 = new String("stringy2");
// step 1: add one object.
Result result = new Result(200);
result.render("object1", object1);
result.render("object2", object2);
Map<String, Object> resultMap = (Map) result.getRenderable();
assertEquals(object1, resultMap.get("object1"));
assertEquals(object2, resultMap.get("object2"));
///////////////////////////////////////////////////////////////////////
// check that empty render throws exception
///////////////////////////////////////////////////////////////////////
boolean gotException = false;
try {
// will throw exception
result.render();
} catch (IllegalArgumentException e) {
gotException = true;
}
assertTrue(gotException);
///////////////////////////////////////////////////////////////////////
// check that too many arguments in render(...) throws exception
///////////////////////////////////////////////////////////////////////
gotException = false;
try {
// will throw exception
result.render(object1, object2, new String("three"));
} catch (IllegalArgumentException e) {
gotException = true;
}
assertTrue(gotException);
///////////////////////////////////////////////////////////////////////
// check that "correct" two string render throws exception
// when first parameter is not a string
///////////////////////////////////////////////////////////////////////
gotException = false;
try {
// will throw exception
result.render(new TestObject(), object2);
} catch (IllegalArgumentException e) {
gotException = true;
}
assertTrue(gotException);
}
#location 12
#vulnerability type NULL_DEREFERENCE | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
public static String makeJsonRequest(String url) {
Map<String, String> headers = Maps.newHashMap();
headers.put("accept", "application/json");
return makeRequest(url, headers);
} | #vulnerable code
public static String makeJsonRequest(String url) {
StringBuffer sb = new StringBuffer();
try {
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpGet getRequest = new HttpGet(url);
getRequest.addHeader("accept", "application/json");
HttpResponse response;
response = httpClient.execute(getRequest);
if (response.getStatusLine().getStatusCode() != 200) {
throw new RuntimeException("Failed : HTTP error code : "
+ response.getStatusLine().getStatusCode());
}
BufferedReader br = new BufferedReader(new InputStreamReader(
(response.getEntity().getContent())));
String output;
while ((output = br.readLine()) != null) {
sb.append(output);
}
httpClient.getConnectionManager().shutdown();
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return sb.toString();
}
#location 28
#vulnerability type RESOURCE_LEAK | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Test
public void testRenderEntryAndMakeSureMapIsCreated() {
String stringy = new String("stringy");
// step 1: add one object.
Result result = new Result(200);
result.render("stringy", stringy);
Map<String, Object> resultMap = (Map) result.getRenderable();
assertEquals(stringy, resultMap.get("stringy"));
} | #vulnerable code
@Test
public void testRenderEntryAndMakeSureMapIsCreated() {
String stringy = new String("stringy");
Entry<String, Object> entry
= new SimpleImmutableEntry("stringy", stringy);
// step 1: add one object.
Result result = new Result(200);
result.render(entry);
Map<String, Object> resultMap = (Map) result.getRenderable();
assertEquals(stringy, resultMap.get("stringy"));
}
#location 13
#vulnerability type NULL_DEREFERENCE | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
static private SourceSnippet readFromInputStream(InputStream is,
URI source,
int lineFrom,
int lineTo) throws IOException {
// did the user provide a strange range (e.g. negative values)?
// this sometimes may happen when a range is provided like an error
// on line 3 and you want 5 before and 5 after
if (lineFrom < 1 && lineTo > 0) {
// calculate intended range
int intendedRange = lineTo - lineFrom;
lineFrom = 1;
lineTo = lineFrom + intendedRange;
}
else if (lineFrom < 0 && lineTo < 0) {
if (lineFrom < lineTo) {
int intendedRange = -1 * (lineFrom - lineTo);
lineFrom = 1;
lineTo = lineFrom + intendedRange;
}
else {
// giving up
return null;
}
}
BufferedReader in = new BufferedReader(
new InputStreamReader(is));
List<String> lines = new ArrayList<>();
int i = 0;
String line;
while ((line = in.readLine()) != null) {
i++; // lines index are 1-based
if (i >= lineFrom) {
if (i <= lineTo) {
lines.add(line);
} else {
break;
}
}
}
if (lines.isEmpty()) {
return null;
}
// since file may not contain enough lines for requested lineTo --
// we caclulate the actual range here by number read "from" line
// since we are inclusive and not zero based we adjust the "from" by 1
return new SourceSnippet(source, lines, lineFrom, lineFrom + lines.size() - 1);
} | #vulnerable code
static private SourceSnippet readFromInputStream(InputStream is,
URI source,
int lineFrom,
int lineTo) throws IOException {
if (lineTo <= 0) {
throw new IllegalArgumentException("lineTo was <= 0");
}
// just zero this out
if (lineFrom < 0) {
lineFrom = 0;
}
if (lineTo < lineFrom) {
throw new IllegalArgumentException("lineTo was < lineFrom");
}
BufferedReader in = new BufferedReader(
new InputStreamReader(is));
List<String> lines = new ArrayList<>();
int i = 0;
String line;
while ((line = in.readLine()) != null) {
i++; // lines index are 1-based
if (i >= lineFrom) {
if (i <= lineTo) {
lines.add(line);
} else {
break;
}
}
}
if (lines.isEmpty()) {
return null;
}
// since file may not contain enough lines for requested lineTo --
// we caclulate the actual range here by number read "from" line.
return new SourceSnippet(source, lines, lineFrom, lineFrom + lines.size());
}
#location 42
#vulnerability type RESOURCE_LEAK | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
public String makeRequest(String url, Map<String, String> headers) {
StringBuffer sb = new StringBuffer();
BufferedReader br = null;
try {
HttpGet getRequest = new HttpGet(url);
if (headers != null) {
// add all headers
for (Entry<String, String> header : headers.entrySet()) {
getRequest.addHeader(header.getKey(), header.getValue());
}
}
HttpResponse response;
response = httpClient.execute(getRequest);
br = new BufferedReader(new InputStreamReader(response.getEntity().getContent(), "UTF-8"));
String output;
while ((output = br.readLine()) != null) {
sb.append(output);
}
getRequest.releaseConnection();
} catch (Exception e) {
throw new RuntimeException(e);
} finally {
if (br != null) {
try {
br.close();
} catch (IOException e) {
LOG.error("Failed to close resource", e);
}
}
}
return sb.toString();
} | #vulnerable code
public String makeRequest(String url, Map<String, String> headers) {
StringBuffer sb = new StringBuffer();
try {
HttpGet getRequest = new HttpGet(url);
if (headers != null) {
// add all headers
for (Entry<String, String> header : headers.entrySet()) {
getRequest.addHeader(header.getKey(), header.getValue());
}
}
HttpResponse response;
response = httpClient.execute(getRequest);
BufferedReader br = new BufferedReader(new InputStreamReader(
response.getEntity().getContent(), "UTF-8"));
String output;
while ((output = br.readLine()) != null) {
sb.append(output);
}
getRequest.releaseConnection();
} catch (Exception e) {
throw new RuntimeException(e);
}
return sb.toString();
}
#location 29
#vulnerability type RESOURCE_LEAK | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
public void handleTemplateException(TemplateException te,
Environment env,
Writer out) throws TemplateException {
if (!ninjaProperties.isProd()) {
// print out full stacktrace if we are in test or dev mode
PrintWriter pw = (out instanceof PrintWriter) ? (PrintWriter) out
: new PrintWriter(out);
pw.println("<!-- FREEMARKER ERROR MESSAGE STARTS HERE -->"
+ "<script language=javascript>//\"></script>"
+ "<script language=javascript>//\'></script>"
+ "<script language=javascript>//\"></script>"
+ "<script language=javascript>//\'></script>"
+ "</title></xmp></script></noscript></style></object>"
+ "</head></pre></table>"
+ "</form></table></table></table></a></u></i></b>"
+ "<div align=left "
+ "style='background-color:#FFFF00; color:#FF0000; "
+ "display:block; border-top:double; padding:2pt; "
+ "font-size:medium; font-family:Arial,sans-serif; "
+ "font-style: normal; font-variant: normal; "
+ "font-weight: normal; text-decoration: none; "
+ "text-transform: none'>"
+ "<b style='font-size:medium'>FreeMarker template error!</b>"
+ "<pre><xmp>");
te.printStackTrace(pw);
pw.println("</xmp></pre></div></html>");
pw.flush();
pw.close();
logger.error("Templating error.", te);
}
// Let the exception bubble up to the central handlers
// so the application can return the correct error page
// or perform some other application specific action.
throw te;
} | #vulnerable code
public void handleTemplateException(TemplateException te,
Environment env,
Writer out) {
if (ninjaProperties.isProd()) {
PrintWriter pw = (out instanceof PrintWriter) ? (PrintWriter) out
: new PrintWriter(out);
pw.println(
"<script language=javascript>//\"></script>"
+ "<script language=javascript>//\'></script>"
+ "<script language=javascript>//\"></script>"
+ "<script language=javascript>//\'></script>"
+ "</title></xmp></script></noscript></style></object>"
+ "</head></pre></table>"
+ "</form></table></table></table></a></u></i></b>"
+ "<div align=left "
+ "style='background-color:#FFFF00; color:#FF0000; "
+ "display:block; border-top:double; padding:2pt; "
+ "font-size:medium; font-family:Arial,sans-serif; "
+ "font-style: normal; font-variant: normal; "
+ "font-weight: normal; text-decoration: none; "
+ "text-transform: none'>");
pw.println("<b style='font-size:medium'>Ooops. A really strange error occurred. Please contact admin if error persists.</b>");
pw.println("</div></html>");
pw.flush();
pw.close();
logger.log(Level.SEVERE, "Templating error. This should not happen in production", te);
} else {
// print out full stacktrace if we are in test or dev mode
PrintWriter pw = (out instanceof PrintWriter) ? (PrintWriter) out
: new PrintWriter(out);
pw.println("<!-- FREEMARKER ERROR MESSAGE STARTS HERE -->"
+ "<script language=javascript>//\"></script>"
+ "<script language=javascript>//\'></script>"
+ "<script language=javascript>//\"></script>"
+ "<script language=javascript>//\'></script>"
+ "</title></xmp></script></noscript></style></object>"
+ "</head></pre></table>"
+ "</form></table></table></table></a></u></i></b>"
+ "<div align=left "
+ "style='background-color:#FFFF00; color:#FF0000; "
+ "display:block; border-top:double; padding:2pt; "
+ "font-size:medium; font-family:Arial,sans-serif; "
+ "font-style: normal; font-variant: normal; "
+ "font-weight: normal; text-decoration: none; "
+ "text-transform: none'>"
+ "<b style='font-size:medium'>FreeMarker template error!</b>"
+ "<pre><xmp>");
te.printStackTrace(pw);
pw.println("</xmp></pre></div></html>");
pw.flush();
pw.close();
logger.log(Level.SEVERE, "Templating error.", te);
}
}
#location 62
#vulnerability type RESOURCE_LEAK | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Override
public Object invoke(MethodInvocation invocation) throws Throwable {
if (null == didWeStartWork.get()) {
unitOfWork.begin();
didWeStartWork.set(Boolean.TRUE);
} else {
// If unit of work already started we don't do anything here...
// another UnitOfWorkInterceptor point point will take care...
// This happens if you are nesting your calls.
return invocation.proceed();
}
try {
return invocation.proceed();
} finally {
if (null != didWeStartWork.get()) {
didWeStartWork.remove();
unitOfWork.end();
}
}
} | #vulnerable code
@Override
public Object invoke(MethodInvocation invocation) throws Throwable {
final UnitOfWork unitOfWork;
// Only start a new unit of work if the entitymanager is empty
// otherwise someone else has started the unit of work already
// and we do nothing
// Please compare to com.google.inject.persist.jpa.JpaLocalTxnInterceptor
// we just mimick that interceptor
//
// IMPORTANT:
// Nesting of begin() end() of unitOfWork is NOT allowed. Contrary to
// the documentation of Google Guice as of March 2014.
// Related Ninja issue: https://github.com/ninjaframework/ninja/issues/157
if (entityManagerProvider.get() == null) {
unitOfWork = unitOfWorkProvider.get();
unitOfWork.begin();
didWeStartWork.set(Boolean.TRUE);
} else {
// If unit of work already started we don't do anything here...
// another UnitOfWorkInterceptor point point will take care...
// This happens if you are nesting your calls.
return invocation.proceed();
}
try {
return invocation.proceed();
} finally {
if (null != didWeStartWork.get()) {
didWeStartWork.remove();
unitOfWork.end();
}
}
}
#location 19
#vulnerability type NULL_DEREFERENCE | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
public String makePostRequestWithFormParameters(String url,
Map<String, String> headers,
Map<String, String> formParameters) {
StringBuffer sb = new StringBuffer();
BufferedReader br = null;
try {
HttpPost postRequest = new HttpPost(url);
if (headers != null) {
// add all headers
for (Entry<String, String> header : headers.entrySet()) {
postRequest.addHeader(header.getKey(), header.getValue());
}
}
// add form parameters:
List<BasicNameValuePair> formparams = new ArrayList<BasicNameValuePair>();
if (formParameters != null) {
for (Entry<String, String> parameter : formParameters
.entrySet()) {
formparams.add(new BasicNameValuePair(parameter.getKey(),
parameter.getValue()));
}
}
// encode form parameters and add
UrlEncodedFormEntity entity = new UrlEncodedFormEntity(formparams);
postRequest.setEntity(entity);
HttpResponse response;
response = httpClient.execute(postRequest);
br = new BufferedReader(new InputStreamReader(response.getEntity().getContent(), "UTF-8"));
String output;
while ((output = br.readLine()) != null) {
sb.append(output);
}
postRequest.releaseConnection();
} catch (Exception e) {
throw new RuntimeException(e);
} finally {
if (br != null) {
try {
br.close();
} catch (IOException e) {
LOG.error("Failed to close resource", e);
}
}
}
return sb.toString();
} | #vulnerable code
public String makePostRequestWithFormParameters(String url,
Map<String, String> headers,
Map<String, String> formParameters) {
StringBuffer sb = new StringBuffer();
try {
HttpPost postRequest = new HttpPost(url);
if (headers != null) {
// add all headers
for (Entry<String, String> header : headers.entrySet()) {
postRequest.addHeader(header.getKey(), header.getValue());
}
}
// add form parameters:
List<BasicNameValuePair> formparams = new ArrayList<BasicNameValuePair>();
if (formParameters != null) {
for (Entry<String, String> parameter : formParameters
.entrySet()) {
formparams.add(new BasicNameValuePair(parameter.getKey(),
parameter.getValue()));
}
}
// encode form parameters and add
UrlEncodedFormEntity entity = new UrlEncodedFormEntity(formparams);
postRequest.setEntity(entity);
HttpResponse response;
response = httpClient.execute(postRequest);
BufferedReader br = new BufferedReader(new InputStreamReader(
response.getEntity().getContent(), "UTF-8"));
String output;
while ((output = br.readLine()) != null) {
sb.append(output);
}
postRequest.releaseConnection();
} catch (Exception e) {
throw new RuntimeException(e);
}
return sb.toString();
}
#location 49
#vulnerability type RESOURCE_LEAK | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Test
public void testAllConstants() {
Configuration configuration =
SwissKnife.loadConfigurationInUtf8("conf/all_constants.conf");
assertEquals("LANGUAGES", configuration.getString(NinjaConstant.applicationLanguages));
assertEquals("PREFIX", configuration.getString(NinjaConstant.applicationCookiePrefix));
assertEquals("NAME", configuration.getString(NinjaConstant.applicationName));
assertEquals("SECRET", configuration.getString(NinjaConstant.applicationSecret));
assertEquals("SERVER_NAME", configuration.getString(NinjaConstant.serverName));
assertEquals(9999, configuration.getInt(NinjaConstant.sessionExpireTimeInSeconds));
assertEquals(false, configuration.getBoolean(NinjaConstant.sessionSendOnlyIfChanged));
assertEquals(false, configuration.getBoolean(NinjaConstant.sessionTransferredOverHttpsOnly));
} | #vulnerable code
@Test
public void testAllConstants() {
Configuration configuration =
SwissKnife.loadConfigurationFromClasspathInUtf8("conf/all_constants.conf", this
.getClass());
assertEquals("LANGUAGES", configuration.getString(NinjaConstant.applicationLanguages));
assertEquals("PREFIX", configuration.getString(NinjaConstant.applicationCookiePrefix));
assertEquals("NAME", configuration.getString(NinjaConstant.applicationName));
assertEquals("SECRET", configuration.getString(NinjaConstant.applicationSecret));
assertEquals("SERVER_NAME", configuration.getString(NinjaConstant.serverName));
assertEquals(9999, configuration.getInt(NinjaConstant.sessionExpireTimeInSeconds));
assertEquals(false, configuration.getBoolean(NinjaConstant.sessionSendOnlyIfChanged));
assertEquals(false, configuration.getBoolean(NinjaConstant.sessionTransferredOverHttpsOnly));
}
#location 9
#vulnerability type NULL_DEREFERENCE | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Override
public boolean runSteps(FlowSpec scenario, FlowStepStatusNotifier flowStepStatusNotifier) {
LOGGER.info("\n-------------------------- Scenario:{} -------------------------\n", scenario.getFlowName());
ScenarioExecutionState scenarioExecutionState = new ScenarioExecutionState();
for(Step thisStep : scenario.getSteps()){
// Another way to get the String
// String requestJson = objectMapper.valueToTree(thisStep.getRequest()).toString();
final String requestJsonAsString = thisStep.getRequest().toString();
StepExecutionState stepExecutionState = new StepExecutionState();
stepExecutionState.addStep(thisStep.getName());
String resolvedRequestJson = jsonTestProcesor.resolveStringJson(
requestJsonAsString,
scenarioExecutionState.getResolvedScenarioState()
);
stepExecutionState.addRequest(resolvedRequestJson);
String executionResult;
final String logPrefixRelationshipId = createRelationshipId();
try{
String serviceName = thisStep.getUrl();
String operationName = thisStep.getOperation();
// Resolve the URL patterns if any
serviceName = jsonTestProcesor.resolveStringJson(
serviceName,
scenarioExecutionState.getResolvedScenarioState()
);
//
logCorelationshipPrinter.aRequestBuilder()
.relationshipId(logPrefixRelationshipId)
.requestTimeStamp(LocalDateTime.now())
.step(thisStep.getName())
.url(serviceName)
.method(operationName)
.request(SmartUtils.prettyPrintJson(resolvedRequestJson));
//
// REST call execution
Boolean isRESTCall = false;
if( serviceName != null && serviceName.contains("/")) {
isRESTCall = true;
}
if(isRESTCall) {
serviceName = getFullyQualifiedRestUrl(serviceName);
executionResult = serviceExecutor.executeRESTService(serviceName, operationName, resolvedRequestJson);
}
else {
executionResult = serviceExecutor.executeJavaService(serviceName, operationName, resolvedRequestJson);
}
//
logCorelationshipPrinter.aResponseBuilder()
.relationshipId(logPrefixRelationshipId)
.responseTimeStamp(LocalDateTime.now())
.response(executionResult);
//
stepExecutionState.addResponse(executionResult);
scenarioExecutionState.addStepState(stepExecutionState.getResolvedStep());
// Handle assertion section
String resolvedAssertionJson = jsonTestProcesor.resolveStringJson(
thisStep.getAssertions().toString(),
scenarioExecutionState.getResolvedScenarioState()
);
LOGGER.info("\n---------> Assertion: <----------\n{}", prettyPrintJson(resolvedAssertionJson));
List<JsonAsserter> asserters = jsonTestProcesor.createAssertersFrom(resolvedAssertionJson);
List<AssertionReport> failureResults = jsonTestProcesor.assertAllAndReturnFailed(asserters, executionResult); //<-- write code
// TODO: During this step: if assertion failed
if (!failureResults.isEmpty()) {
return flowStepStatusNotifier.notifyFlowStepAssertionFailed(scenario.getFlowName(), thisStep.getName(), failureResults);
}
// TODO: Otherwise test passed
flowStepStatusNotifier.notifyFlowStepExecutionPassed(scenario.getFlowName(), thisStep.getName());
} catch(Exception ex){
logCorelationshipPrinter.aResponseBuilder()
.relationshipId(logPrefixRelationshipId)
.responseTimeStamp(LocalDateTime.now())
.response(ex.getMessage());
// During this step: if any exception occurred
return flowStepStatusNotifier.notifyFlowStepExecutionException(
scenario.getFlowName(),
thisStep.getName(),
new RuntimeException("Smart Step execution failed. Details:" + ex)
);
}
finally {
logCorelationshipPrinter.print();
}
}
/*
* There were no steps to execute and the framework will display the test status as Green than Red.
* Red symbolises failure, but nothing has failed here.
*/
return true;
} | #vulnerable code
@Override
public boolean runSteps(FlowSpec scenario, FlowStepStatusNotifier flowStepStatusNotifier) {
ScenarioExecutionState scenarioExecutionState = new ScenarioExecutionState();
for(Step thisStep : scenario.getSteps()){
// Another way to get the String
// String requestJson = objectMapper.valueToTree(thisStep.getRequest()).toString();
final String requestJsonAsString = thisStep.getRequest().toString();
LOGGER.info(String.format("\n###RAW: Journey:%s, Step:%s", scenario.getFlowName(), thisStep.getName()));
StepExecutionState stepExecutionState = new StepExecutionState();
stepExecutionState.addStep(thisStep.getName());
String resolvedRequestJson = jsonTestProcesor.resolveRequestJson(
requestJsonAsString,
scenarioExecutionState.getResolvedScenarioState()
);
stepExecutionState.addRequest(resolvedRequestJson);
String executionResult;
try{
String serviceName = thisStep.getUrl();
String operationName = thisStep.getOperation();
// REST call execution
Boolean isRESTCall = false;
if( serviceName != null && serviceName.contains("/")) {
isRESTCall = true;
}
if(isRESTCall) {
serviceName = getFullyQualifiedRestUrl(serviceName);
executionResult = serviceExecutor.executeRESTService(serviceName, operationName, resolvedRequestJson);
}
else {
executionResult = serviceExecutor.executeJavaService(serviceName, operationName, resolvedRequestJson);
}
stepExecutionState.addResponse(executionResult);
scenarioExecutionState.addStepState(stepExecutionState.getResolvedStep());
// Handle assertion section
String resolvedAssertionJson = jsonTestProcesor.resolveRequestJson(
thisStep.getAssertions().toString(),
scenarioExecutionState.getResolvedScenarioState()
);
LOGGER.info("\n---------> Assertion: <----------\n"
+ prettyPrintJson(resolvedAssertionJson));
// TODO: Collect the assertion result into this list, say field by field
List<JsonAsserter> asserters = jsonTestProcesor.createAssertersFrom(resolvedAssertionJson);
List<AssertionReport> failureResults = new ArrayList<>(); //<-- write code
// TODO: During this step: if assertion failed
if (!failureResults.isEmpty()) {
return flowStepStatusNotifier.notifyFlowStepAssertionFailed(scenario.getFlowName(), thisStep.getName(), failureResults);
}
// TODO: Otherwise test passed
//return flowStepStatusNotifier.notifyFlowStepExecutionPassed(scenario.getFlowName(), thisStep.getName());
} catch(Exception ex){
// During this step: if any exception occurred
return flowStepStatusNotifier.notifyFlowStepExecutionException(
scenario.getFlowName(),
thisStep.getName(),
new RuntimeException("Smart Step execution failed. Details:" + ex)
);
}
}
/*
* There were no steps to execute and the framework will display the test status as Green than Red.
* Red symbolises failure, but nothing has failed here.
*/
return true;
}
#location 33
#vulnerability type NULL_DEREFERENCE | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Test
public void testRawRecordingSpeed() throws Exception {
testRawRecordingSpeedAtExpectedInterval(1000000000);
testRawRecordingSpeedAtExpectedInterval(10000);
} | #vulnerable code
@Test
public void testRawRecordingSpeed() throws Exception {
Histogram histogram = new Histogram(highestTrackableValue, numberOfSignificantValueDigits);
// Warm up:
long startTime = System.nanoTime();
recordLoop(histogram, warmupLoopLength);
long endTime = System.nanoTime();
long deltaUsec = (endTime - startTime) / 1000L;
long rate = 1000000 * warmupLoopLength / deltaUsec;
System.out.println("Warmup:\n" + warmupLoopLength + " value recordings completed in " +
deltaUsec + " usec, rate = " + rate + " value recording calls per sec.");
histogram.reset();
// Wait a bit to make sure compiler had a cache to do it's stuff:
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
}
startTime = System.nanoTime();
recordLoop(histogram, timingLoopCount);
endTime = System.nanoTime();
deltaUsec = (endTime - startTime) / 1000L;
rate = 1000000 * timingLoopCount / deltaUsec;
System.out.println("Timing:");
System.out.println(timingLoopCount + " value recordings completed in " +
deltaUsec + " usec, rate = " + rate + " value recording calls per sec.");
rate = 1000000 * histogram.getHistogramData().getTotalCount() / deltaUsec;
System.out.println(histogram.getHistogramData().getTotalCount() + " raw recorded entries completed in " +
deltaUsec + " usec, rate = " + rate + " recorded values per sec.");
}
#location 26
#vulnerability type NULL_DEREFERENCE | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
private static synchronized List<Menu> loadJson() throws IOException {
InputStream inStream = MenuJsonUtils.class.getResourceAsStream(config);
BufferedReader reader = new BufferedReader(new InputStreamReader(inStream, Charset.forName("UTF-8")));
StringBuilder json = new StringBuilder();
String tmp;
try {
while ((tmp = reader.readLine()) != null) {
json.append(tmp);
}
} catch (IOException e) {
throw e;
} finally {
reader.close();
inStream.close();
}
List<Menu> menus = JSONArray.parseArray(json.toString(), Menu.class);
return menus;
} | #vulnerable code
private static synchronized List<Menu> loadJson() throws IOException {
InputStream inStream = MenuJsonUtils.class.getResourceAsStream(config);
BufferedReader reader = new BufferedReader(new InputStreamReader(inStream, Charset.forName("UTF-8")));
StringBuilder json = new StringBuilder();
String tmp;
while ((tmp = reader.readLine()) != null) {
json.append(tmp);
}
List<Menu> menus = JSONArray.parseArray(json.toString(), Menu.class);
return menus;
}
#location 12
#vulnerability type RESOURCE_LEAK | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, HandlerMethod handler, ModelAndView modelAndView) throws Exception {
PostVO ret = (PostVO) modelAndView.getModelMap().get("view");
Object editing = modelAndView.getModel().get("editing");
if (null == editing && ret != null) {
PostVO post = new PostVO();
BeanUtils.copyProperties(ret, post);
if (check(ret.getId(), ret.getAuthor().getId())) {
String c = post.getContent().replaceAll("\\[hide\\]([\\s\\S]*)\\[\\/hide\\]", SHOW);
post.setContent(c);
} else {
String c = post.getContent().replaceAll("\\[hide\\]([\\s\\S]*)\\[\\/hide\\]", "$1");
post.setContent(c);
}
modelAndView.getModelMap().put("view", post);
}
} | #vulnerable code
@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, HandlerMethod handler, ModelAndView modelAndView) throws Exception {
PostVO ret = (PostVO) modelAndView.getModelMap().get("view");
Object editing = modelAndView.getModel().get("editing");
if (null == editing && ret != null) {
PostVO post = new PostVO();
BeanUtils.copyProperties(ret, post);
if (check(ret.getId(), ret.getAuthor().getId())) {
post.setContent(replace(post.getContent()));
} else {
String c = post.getContent().replaceAll("<hide>", "<hide>");
c = c.replaceAll("</hide>", "</hide>");
post.setContent(c);
}
modelAndView.getModelMap().put("view", post);
}
}
#location 9
#vulnerability type NULL_DEREFERENCE | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
public static void main(String[] args) throws Exception {
// STEP-1: read input parameters and validate them
if (args.length < 2) {
System.err.println("Usage: SecondarySortUsingGroupByKey <input> <output>");
System.exit(1);
}
String inputPath = args[0];
System.out.println("inputPath=" + inputPath);
String outputPath = args[1];
System.out.println("outputPath=" + outputPath);
// STEP-2: Connect to the Spark master by creating JavaSparkContext object
final JavaSparkContext ctx = SparkUtil.createJavaSparkContext("SecondarySorting");
// STEP-3: Use ctx to create JavaRDD<String>
// input record format: <name><,><time><,><value>
JavaRDD<String> lines = ctx.textFile(inputPath, 1);
// STEP-4: create (key, value) pairs from JavaRDD<String> where
// key is the {name} and value is a pair of (time, value).
// The resulting RDD will be JavaPairRDD<String, Tuple2<Integer, Integer>>.
// convert each record into Tuple2(name, time, value)
// PairFunction<T, K, V> T => Tuple2(K, V) where K=String and V=Tuple2<Integer, Integer>
// input K V
System.out.println("=== DEBUG STEP-4 ===");
JavaPairRDD<String, Tuple2<Integer, Integer>> pairs = lines.mapToPair(new PairFunction<String, String, Tuple2<Integer, Integer>>() {
@Override
public Tuple2<String, Tuple2<Integer, Integer>> call(String s) {
String[] tokens = s.split(","); // x,2,5
System.out.println(tokens[0] + "," + tokens[1] + "," + tokens[2]);
Tuple2<Integer, Integer> timevalue = new Tuple2<Integer, Integer>(Integer.parseInt(tokens[1]), Integer.parseInt(tokens[2]));
return new Tuple2<String, Tuple2<Integer, Integer>>(tokens[0], timevalue);
}
});
// STEP-5: validate STEP-4, we collect all values from JavaPairRDD<> and print it.
List<Tuple2<String, Tuple2<Integer, Integer>>> output = pairs.collect();
for (Tuple2 t : output) {
Tuple2<Integer, Integer> timevalue = (Tuple2<Integer, Integer>) t._2;
System.out.println(t._1 + "," + timevalue._1 + "," + timevalue._2);
}
// STEP-6: We group JavaPairRDD<> elements by the key ({name}).
JavaPairRDD<String, Iterable<Tuple2<Integer, Integer>>> groups = pairs.groupByKey();
// STEP-7: validate STEP-6, we collect all values from JavaPairRDD<> and print it.
System.out.println("=== DEBUG STEP-6 ===");
List<Tuple2<String, Iterable<Tuple2<Integer, Integer>>>> output2 = groups.collect();
for (Tuple2<String, Iterable<Tuple2<Integer, Integer>>> t : output2) {
Iterable<Tuple2<Integer, Integer>> list = t._2;
System.out.println(t._1);
for (Tuple2<Integer, Integer> t2 : list) {
System.out.println(t2._1 + "," + t2._2);
}
System.out.println("=====");
}
//STEP-8: Sort the reducer's values and this will give us the final output.
// OPTION-1: worked
// mapValues[U](f: (V) ⇒ U): JavaPairRDD[K, U]
// Pass each value in the key-value pair RDD through a map function without changing the keys;
// this also retains the original RDD's partitioning.
JavaPairRDD<String, Iterable<Tuple2<Integer, Integer>>> sorted = groups.mapValues(new Function<Iterable<Tuple2<Integer, Integer>>, // input
Iterable<Tuple2<Integer, Integer>> // output
>() {
@Override
public Iterable<Tuple2<Integer, Integer>> call(Iterable<Tuple2<Integer, Integer>> s) {
List<Tuple2<Integer, Integer>> newList = new ArrayList<Tuple2<Integer, Integer>>(iterableToList(s));
Collections.sort(newList, SparkTupleComparator.INSTANCE);
return newList;
}
});
// STEP-9: validate STEP-8, we collect all values from JavaPairRDD<> and print it.
System.out.println("=== DEBUG STEP-8 ===");
List<Tuple2<String, Iterable<Tuple2<Integer, Integer>>>> output3 = sorted.collect();
for (Tuple2<String, Iterable<Tuple2<Integer, Integer>>> t : output3) {
Iterable<Tuple2<Integer, Integer>> list = t._2;
System.out.println(t._1);
for (Tuple2<Integer, Integer> t2 : list) {
System.out.println(t2._1 + "," + t2._2);
}
System.out.println("=====");
}
sorted.saveAsTextFile(outputPath);
System.exit(0);
} | #vulnerable code
public static void main(String[] args) throws Exception {
// STEP-1: read input parameters and validate them
if (args.length < 2) {
System.err.println("Usage: SecondarySortUsingGroupByKey <input> <output>");
System.exit(1);
}
String inputPath = args[0];
System.out.println("inputPath=" + inputPath);
String outputPath = args[1];
System.out.println("outputPath=" + outputPath);
// STEP-2: Connect to the Sark master by creating JavaSparkContext object
final JavaSparkContext ctx = SparkUtil.createJavaSparkContext();
// STEP-3: Use ctx to create JavaRDD<String>
// input record format: <name><,><time><,><value>
JavaRDD<String> lines = ctx.textFile(inputPath, 1);
// STEP-4: create (key, value) pairs from JavaRDD<String> where
// key is the {name} and value is a pair of (time, value).
// The resulting RDD will be JavaPairRDD<String, Tuple2<Integer, Integer>>.
// convert each record into Tuple2(name, time, value)
// PairFunction<T, K, V> T => Tuple2(K, V) where K=String and V=Tuple2<Integer, Integer>
// input K V
System.out.println("=== DEBUG STEP-4 ===");
JavaPairRDD<String, Tuple2<Integer, Integer>> pairs = lines.mapToPair(new PairFunction<String, String, Tuple2<Integer, Integer>>() {
@Override
public Tuple2<String, Tuple2<Integer, Integer>> call(String s) {
String[] tokens = s.split(","); // x,2,5
System.out.println(tokens[0] + "," + tokens[1] + "," + tokens[2]);
Tuple2<Integer, Integer> timevalue = new Tuple2<Integer, Integer>(Integer.parseInt(tokens[1]), Integer.parseInt(tokens[2]));
return new Tuple2<String, Tuple2<Integer, Integer>>(tokens[0], timevalue);
}
});
// STEP-5: validate STEP-4, we collect all values from JavaPairRDD<> and print it.
List<Tuple2<String, Tuple2<Integer, Integer>>> output = pairs.collect();
for (Tuple2 t : output) {
Tuple2<Integer, Integer> timevalue = (Tuple2<Integer, Integer>) t._2;
System.out.println(t._1 + "," + timevalue._1 + "," + timevalue._1);
}
// STEP-6: We group JavaPairRDD<> elements by the key ({name}).
JavaPairRDD<String, Iterable<Tuple2<Integer, Integer>>> groups = pairs.groupByKey();
// STEP-7: validate STEP-6, we collect all values from JavaPairRDD<> and print it.
System.out.println("=== DEBUG STEP-6 ===");
List<Tuple2<String, Iterable<Tuple2<Integer, Integer>>>> output2 = groups.collect();
for (Tuple2<String, Iterable<Tuple2<Integer, Integer>>> t : output2) {
Iterable<Tuple2<Integer, Integer>> list = t._2;
System.out.println(t._1);
for (Tuple2<Integer, Integer> t2 : list) {
System.out.println(t2._1 + "," + t2._2);
}
System.out.println("=====");
}
//STEP-8: Sort the reducer's values and this will give us the final output.
// OPTION-1: worked
// mapValues[U](f: (V) ⇒ U): JavaPairRDD[K, U]
// Pass each value in the key-value pair RDD through a map function without changing the keys;
// this also retains the original RDD's partitioning.
JavaPairRDD<String, Iterable<Tuple2<Integer, Integer>>> sorted = groups.mapValues(new Function<Iterable<Tuple2<Integer, Integer>>, // input
Iterable<Tuple2<Integer, Integer>> // output
>() {
@Override
public Iterable<Tuple2<Integer, Integer>> call(Iterable<Tuple2<Integer, Integer>> s) {
List<Tuple2<Integer, Integer>> newList = new ArrayList<Tuple2<Integer, Integer>>(iterableToList(s));
Collections.sort(newList, SparkTupleComparator.INSTANCE);
return newList;
}
});
// STEP-9: validate STEP-8, we collect all values from JavaPairRDD<> and print it.
System.out.println("=== DEBUG STEP-8 ===");
List<Tuple2<String, Iterable<Tuple2<Integer, Integer>>>> output3 = sorted.collect();
for (Tuple2<String, Iterable<Tuple2<Integer, Integer>>> t : output3) {
Iterable<Tuple2<Integer, Integer>> list = t._2;
System.out.println(t._1);
for (Tuple2<Integer, Integer> t2 : list) {
System.out.println(t2._1 + "," + t2._2);
}
System.out.println("=====");
}
sorted.saveAsTextFile(outputPath);
System.exit(0);
}
#location 18
#vulnerability type RESOURCE_LEAK | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
public static CacheManager get() {
return get(defaultCacheManager);
} | #vulnerable code
public static CacheManager get() {
if (instance == null) {
synchronized (log) {
if (instance == null) {
instance = new CacheManager();
}
}
}
return instance;
}
#location 9
#vulnerability type THREAD_SAFETY_VIOLATION | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@SuppressWarnings({"unchecked", "rawtypes"})
public void onReceive(ServiceContext serviceContext) throws Throwable {
FlowMessage fm = serviceContext.getFlowMessage();
if (serviceContext.isSync() && !syncActors.containsKey(serviceContext.getId())) {
syncActors.putIfAbsent(serviceContext.getId(), getSender());
}
// TODO 没有必要设置默认值,下面执行异常就会抛出异常
Object result = null;// DefaultMessage.getMessage();// set default
try {
this.service = ServiceFactory.getService(serviceName);
result = ((Service) service).process(fm.getMessage(), serviceContext);
} catch (Throwable e) {
Web web = serviceContext.getWeb();
if (web != null) {
web.complete();
}
throw new FlowerException("fail to invoke service " + serviceName + " : " + service + ", param : " + fm.getMessage(), e);
}
logger.info("同步处理 : {}, hasChild : {}", serviceContext.isSync(), hasChildActor());
if (serviceContext.isSync() && !hasChildActor()) {
logger.info("返回响应 {}", result);
ActorRef actor = syncActors.get(serviceContext.getId());
if(actor !=null) {
actor.tell(result, getSelf());
syncActors.remove(serviceContext.getId());
}
return;
}
Web web = serviceContext.getWeb();
if (service instanceof Complete) {
// FlowContext.removeServiceContext(fm.getTransactionId());
}
if (web != null) {
if (service instanceof Flush) {
web.flush();
}
if (service instanceof HttpComplete || service instanceof Complete) {
web.complete();
}
}
if (result == null)// for joint service
return;
if (hasChildActor()) {
for (RefType refType : nextServiceActors) {
ServiceContext context = serviceContext.newInstance();
context.getFlowMessage().setMessage(result);
// if (refType.isJoint()) {
// FlowMessage flowMessage1 = CloneUtil.clone(fm);
// flowMessage1.setMessage(result);
// context.setFlowMessage(flowMessage1);
// }
// condition fork for one-service to multi-service
if (refType.getMessageType().isInstance(result)) {
if (!(result instanceof Condition) || !(((Condition) result).getCondition() instanceof String)
|| stringInStrings(refType.getServiceName(), ((Condition) result).getCondition().toString())) {
refType.getActorRef().tell(context, getSelf());
}
}
}
} else {
}
} | #vulnerable code
@SuppressWarnings({"unchecked", "rawtypes"})
public void onReceive(ServiceContext serviceContext) throws Throwable {
FlowMessage fm = serviceContext.getFlowMessage();
if (serviceContext.isSync() && !syncActors.containsKey(serviceContext.getId())) {
syncActors.putIfAbsent(serviceContext.getId(), getSender());
}
// TODO 没有必要设置默认值,下面执行异常就会抛出异常
Object result = null;// DefaultMessage.getMessage();// set default
try {
this.service = ServiceFactory.getService(serviceName);
result = ((Service) service).process(fm.getMessage(), serviceContext);
} catch (Throwable e) {
Web web = serviceContext.getWeb();
if (web != null) {
web.complete();
}
throw new FlowerException("fail to invoke service " + serviceName + " : " + service + ", param : " + fm.getMessage(), e);
}
if (serviceContext.isSync() && !hasChildActor()) {
syncActors.get(serviceContext.getId()).tell(result, getSelf());
syncActors.remove(serviceContext.getId());
return;
}
Web web = serviceContext.getWeb();
if (service instanceof Complete) {
// FlowContext.removeServiceContext(fm.getTransactionId());
}
if (web != null) {
if (service instanceof Flush) {
web.flush();
}
if (service instanceof HttpComplete || service instanceof Complete) {
web.complete();
}
}
if (result == null)// for joint service
return;
if (hasChildActor()) {
for (RefType refType : nextServiceActors) {
ServiceContext context = serviceContext.newInstance();
context.getFlowMessage().setMessage(result);
// if (refType.isJoint()) {
// FlowMessage flowMessage1 = CloneUtil.clone(fm);
// flowMessage1.setMessage(result);
// context.setFlowMessage(flowMessage1);
// }
// condition fork for one-service to multi-service
if (refType.getMessageType().isInstance(result)) {
if (!(result instanceof Condition) || !(((Condition) result).getCondition() instanceof String)
|| stringInStrings(refType.getServiceName(), ((Condition) result).getCondition().toString())) {
refType.getActorRef().tell(context, getSelf());
}
}
}
} else {
}
}
#location 45
#vulnerability type NULL_DEREFERENCE | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Override
public String toString() {
StringBuilder builder = new StringBuilder();
builder.append("ServiceFlow [ flowName = ");
builder.append(flowName);
builder.append("\r\n\t");
ServiceConfig hh = header;
buildString(hh, builder);
builder.append("\n]");
return builder.toString();
} | #vulnerable code
@Override
public String toString() {
StringBuilder builder = new StringBuilder();
builder.append("ServiceFlow [\r\n\tflowName = ");
builder.append(flowName);
builder.append("\r\n\t");
Set<ServiceConfig> nextServices = servicesOfFlow.get(getHeadServiceConfig().getServiceName());
builder.append(getHeadServiceConfig().getSimpleDesc());
builder.append(" --> ");
getHeadServiceConfig().getNextServiceConfigs().forEach(item -> {
builder.append(item.getSimpleDesc()).append(",");
});
if (nextServices != null) {
for (Map.Entry<String, Set<ServiceConfig>> entry : servicesOfFlow.entrySet()) {
if (getHeadServiceConfig().getServiceName().equals(entry.getKey())) {
continue;
}
builder.append("\r\n\t");
builder.append(getServiceConfig(entry.getKey()).getSimpleDesc());
builder.append(" -- > ");
entry.getValue().forEach(item -> {
builder.append(item.getSimpleDesc()).append(", ");
});
}
}
builder.append("\n]");
return builder.toString();
}
#location 11
#vulnerability type NULL_DEREFERENCE | 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.