output
stringlengths 64
73.2k
| input
stringlengths 208
73.3k
| instruction
stringclasses 1
value |
---|---|---|
#fixed code
@SuppressWarnings("unchecked")
protected void _addMapping(K key, final FieldMapperColumnDefinition<K, S> columnDefinition) {
final FieldMapperColumnDefinition<K, S> composedDefinition = FieldMapperColumnDefinition.compose(columnDefinition, columnDefinitions.getColumnDefinition(key));
final K mappedColumnKey = composedDefinition.rename(key);
if (columnDefinition.getCustomFieldMapper() != null) {
_addMapper((FieldMapper<S, T>) columnDefinition.getCustomFieldMapper());
} else {
final PropertyMeta<T, ?> property = propertyMappingsBuilder.addProperty(mappedColumnKey, composedDefinition);
if (property != null && composedDefinition.isKey() && !property.isSubProperty()) {
mappingContextFactoryBuilder.addKey(key);
}
}
} | #vulnerable code
@SuppressWarnings("unchecked")
protected void _addMapping(K key, final FieldMapperColumnDefinition<K, S> columnDefinition) {
final FieldMapperColumnDefinition<K, S> composedDefinition = FieldMapperColumnDefinition.compose(columnDefinition, columnDefinitions.getColumnDefinition(key));
final K mappedColumnKey = composedDefinition.rename(key);
if (columnDefinition.getCustomFieldMapper() != null) {
_addMapper((FieldMapper<S, T>) columnDefinition.getCustomFieldMapper());
} else {
final PropertyMeta<T, ?> property = propertyMappingsBuilder.addProperty(mappedColumnKey, composedDefinition);
if (composedDefinition.isKey() && !property.isSubProperty()) {
mappingContextFactoryBuilder.addKey(key);
}
}
}
#location 10
#vulnerability type NULL_DEREFERENCE | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Test
public void testFindElementOnArray() {
ClassMeta<DbObject[]> classMeta = ReflectionService.newInstance().getRootClassMeta(DbObject[].class);
PropertyFinder<DbObject[]> propertyFinder = classMeta.newPropertyFinder();
PropertyMeta<DbObject[], ?> propEltId = propertyFinder.findProperty(matcher("elt0_id"));
assertNotNull(propEltId);
propEltId = propertyFinder.findProperty(matcher("2_id"));
assertNotNull(propEltId);
propEltId = propertyFinder.findProperty(matcher("id"));
assertNotNull(propEltId);
assertEquals(1, ((ArrayElementPropertyMeta<?, ?>) ((SubPropertyMeta<?, ?>) propEltId).getOwnerProperty()).getIndex());
propEltId = propertyFinder.findProperty(matcher("id"));
assertNotNull(propEltId);
assertEquals(3, ((ArrayElementPropertyMeta<?, ?>) ((SubPropertyMeta<?, ?>) propEltId).getOwnerProperty()).getIndex());
propEltId = propertyFinder.findProperty(matcher("name"));
assertNotNull(propEltId);
assertEquals(0, ((ArrayElementPropertyMeta<?, ?>) ((SubPropertyMeta<?, ?>) propEltId).getOwnerProperty()).getIndex());
propEltId = propertyFinder.findProperty(matcher("2_notid"));
assertNull(propEltId);
propEltId = propertyFinder.findProperty(matcher("notid"));
assertNull(propEltId);
} | #vulnerable code
@Test
public void testFindElementOnArray() {
ClassMeta<DbObject[]> classMeta = ReflectionService.newInstance().getClassMeta(DbObject[].class);
PropertyFinder<DbObject[]> propertyFinder = classMeta.newPropertyFinder();
PropertyMeta<DbObject[], ?> propEltId = propertyFinder.findProperty(matcher("elt0_id"));
assertNotNull(propEltId);
propEltId = propertyFinder.findProperty(matcher("2_id"));
assertNotNull(propEltId);
propEltId = propertyFinder.findProperty(matcher("id"));
assertNotNull(propEltId);
assertEquals(1, ((ArrayElementPropertyMeta<?, ?>) ((SubPropertyMeta<?, ?>) propEltId).getOwnerProperty()).getIndex());
propEltId = propertyFinder.findProperty(matcher("id"));
assertNotNull(propEltId);
assertEquals(3, ((ArrayElementPropertyMeta<?, ?>) ((SubPropertyMeta<?, ?>) propEltId).getOwnerProperty()).getIndex());
propEltId = propertyFinder.findProperty(matcher("name"));
assertNotNull(propEltId);
assertEquals(0, ((ArrayElementPropertyMeta<?, ?>) ((SubPropertyMeta<?, ?>) propEltId).getOwnerProperty()).getIndex());
propEltId = propertyFinder.findProperty(matcher("2_notid"));
assertNull(propEltId);
propEltId = propertyFinder.findProperty(matcher("notid"));
assertNull(propEltId);
}
#location 6
#vulnerability type NULL_DEREFERENCE | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Test
public void testArrayElementConstructorInjectionWithIncompatibleConstructorUseCompatibleOutlay() {
ClassMeta<ObjectWithIncompatibleConstructor[]> classMeta = ReflectionService.newInstance().getRootClassMeta(ObjectWithIncompatibleConstructor[].class);
PropertyFinder<ObjectWithIncompatibleConstructor[]> propertyFinder = classMeta.newPropertyFinder();
assertNotNull(propertyFinder.findProperty(matcher("1_arg1")));
assertNotNull(propertyFinder.findProperty(matcher("1_arg3")));
assertNotNull(propertyFinder.findProperty(matcher("2_arg1")));
assertNotNull(propertyFinder.findProperty(matcher("2_arg2")));
} | #vulnerable code
@Test
public void testArrayElementConstructorInjectionWithIncompatibleConstructorUseCompatibleOutlay() {
ClassMeta<ObjectWithIncompatibleConstructor[]> classMeta = ReflectionService.newInstance().getClassMeta(ObjectWithIncompatibleConstructor[].class);
PropertyFinder<ObjectWithIncompatibleConstructor[]> propertyFinder = classMeta.newPropertyFinder();
assertNotNull(propertyFinder.findProperty(matcher("1_arg1")));
assertNotNull(propertyFinder.findProperty(matcher("1_arg3")));
assertNotNull(propertyFinder.findProperty(matcher("2_arg1")));
assertNotNull(propertyFinder.findProperty(matcher("2_arg2")));
}
#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 testPrimitiveField() {
ClassMeta<DbObject> classMeta = ReflectionService.newInstance(true, false).getRootClassMeta(DbObject.class);
PropertyMeta<DbObject, Long> id = classMeta.newPropertyFinder().<Long>findProperty(new DefaultPropertyNameMatcher("id"));
FieldMapperColumnDefinition<JdbcColumnKey, ResultSet> identity = FieldMapperColumnDefinition.identity();
PropertyMapping<DbObject, Long, JdbcColumnKey, FieldMapperColumnDefinition<JdbcColumnKey, ResultSet>> propertyMapping = new PropertyMapping<DbObject, Long, JdbcColumnKey, FieldMapperColumnDefinition<JdbcColumnKey, ResultSet>>(id, new JdbcColumnKey("id", 1), identity);
FieldMapper<ResultSet, DbObject> fieldMapper = factory.newFieldMapper(
propertyMapping, errorHandler, new RethrowMapperBuilderErrorHandler());
assertTrue(fieldMapper instanceof LongFieldMapper);
PropertyMapping<DbObject, Long, JdbcColumnKey, FieldMapperColumnDefinition<JdbcColumnKey, ResultSet>> propertyMapping1 = new PropertyMapping<DbObject, Long, JdbcColumnKey, FieldMapperColumnDefinition<JdbcColumnKey, ResultSet>>(id, new JdbcColumnKey("id", 0), identity);
fieldMapper = factory.newFieldMapper(propertyMapping1, errorHandler, new RethrowMapperBuilderErrorHandler());
assertTrue(fieldMapper instanceof LongFieldMapper);
} | #vulnerable code
@Test
public void testPrimitiveField() {
ClassMeta<DbObject> classMeta = ReflectionService.newInstance(true, false).getClassMeta(DbObject.class);
PropertyMeta<DbObject, Long> id = classMeta.newPropertyFinder().<Long>findProperty(new DefaultPropertyNameMatcher("id"));
FieldMapperColumnDefinition<JdbcColumnKey, ResultSet> identity = FieldMapperColumnDefinition.identity();
PropertyMapping<DbObject, Long, JdbcColumnKey, FieldMapperColumnDefinition<JdbcColumnKey, ResultSet>> propertyMapping = new PropertyMapping<DbObject, Long, JdbcColumnKey, FieldMapperColumnDefinition<JdbcColumnKey, ResultSet>>(id, new JdbcColumnKey("id", 1), identity);
FieldMapper<ResultSet, DbObject> fieldMapper = factory.newFieldMapper(
propertyMapping, errorHandler, new RethrowMapperBuilderErrorHandler());
assertTrue(fieldMapper instanceof LongFieldMapper);
PropertyMapping<DbObject, Long, JdbcColumnKey, FieldMapperColumnDefinition<JdbcColumnKey, ResultSet>> propertyMapping1 = new PropertyMapping<DbObject, Long, JdbcColumnKey, FieldMapperColumnDefinition<JdbcColumnKey, ResultSet>>(id, new JdbcColumnKey("id", 0), identity);
fieldMapper = factory.newFieldMapper(propertyMapping1, errorHandler, new RethrowMapperBuilderErrorHandler());
assertTrue(fieldMapper instanceof LongFieldMapper);
}
#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 testFindElementOnTuple() {
ClassMeta<DbObject[]> classMeta = ReflectionService.newInstance().getRootClassMeta(Tuples.typeDef(String.class, DbObject.class, DbObject.class));
PropertyFinder<DbObject[]> propertyFinder = classMeta.newPropertyFinder();
PropertyMeta<DbObject[], ?> propEltId = propertyFinder.findProperty(matcher("element2_id"));
assertNotNull(propEltId);
propEltId = propertyFinder.findProperty(matcher("element1"));
assertNotNull(propEltId);
propEltId = propertyFinder.findProperty(matcher("elt1"));
assertNotNull(propEltId);
propEltId = propertyFinder.findProperty(matcher("1"));
assertNotNull(propEltId);
propEltId = propertyFinder.findProperty(matcher("id"));
assertNotNull(propEltId);
propEltId = propertyFinder.findProperty(matcher("4_id"));
assertNull(propEltId);
propEltId = propertyFinder.findProperty(matcher("2_notid"));
assertNull(propEltId);
propEltId = propertyFinder.findProperty(matcher("notid"));
assertNull(propEltId);
} | #vulnerable code
@Test
public void testFindElementOnTuple() {
ClassMeta<DbObject[]> classMeta = ReflectionService.newInstance().getClassMeta(Tuples.typeDef(String.class, DbObject.class, DbObject.class));
PropertyFinder<DbObject[]> propertyFinder = classMeta.newPropertyFinder();
PropertyMeta<DbObject[], ?> propEltId = propertyFinder.findProperty(matcher("element2_id"));
assertNotNull(propEltId);
propEltId = propertyFinder.findProperty(matcher("element1"));
assertNotNull(propEltId);
propEltId = propertyFinder.findProperty(matcher("elt1"));
assertNotNull(propEltId);
propEltId = propertyFinder.findProperty(matcher("1"));
assertNotNull(propEltId);
propEltId = propertyFinder.findProperty(matcher("id"));
assertNotNull(propEltId);
propEltId = propertyFinder.findProperty(matcher("4_id"));
assertNull(propEltId);
propEltId = propertyFinder.findProperty(matcher("2_notid"));
assertNull(propEltId);
propEltId = propertyFinder.findProperty(matcher("notid"));
assertNull(propEltId);
}
#location 5
#vulnerability type NULL_DEREFERENCE | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
public ResultSetMapperBuilder<T> addMapping(String property, int column) {
Setter<T, Object> setter = setterFactory.getSetter(target, property);
addMapping(setter, column);
return this;
} | #vulnerable code
public ResultSetMapperBuilder<T> addMapping(String property, int column) {
Setter<T, Object> setter = setterFactory.getSetter(target, property);
Mapper<ResultSet, T> fieldMapper;
if (setter.getPropertyType().isPrimitive()) {
fieldMapper = primitiveFieldMapper(column, setter);
} else {
fieldMapper = objectFieldMapper(column, setter);
}
fields.add(fieldMapper);
return this;
}
#location 6
#vulnerability type NULL_DEREFERENCE | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
public void threadDumpIfNeed(String reasonMsg) {
if (!enable) {
return;
}
synchronized (this) {
if (System.currentTimeMillis() - lastThreadDumpTime < leastIntervalMills) {
return;
} else {
lastThreadDumpTime = System.currentTimeMillis();
}
}
logger.info("Thread dump by ThreadDumpper" + (reasonMsg != null ? (" for " + reasonMsg) : ""));
Map<Thread, StackTraceElement[]> threads = Thread.getAllStackTraces();
// 两条日志间的时间间隔,是VM被thread dump堵塞的时间.
logger.info("Finish the threads snapshot");
StringBuilder sb = new StringBuilder(8192 * 20).append("\n");
for (Entry<Thread, StackTraceElement[]> entry : threads.entrySet()) {
dumpThreadInfo(entry.getKey(), entry.getValue(), sb);
}
logger.info(sb.toString());
} | #vulnerable code
public void threadDumpIfNeed(String reasonMsg) {
if (!enable) {
return;
}
synchronized (this) {
if (System.currentTimeMillis() - lastThreadDumpTime < leastIntervalMills) {
return;
} else {
lastThreadDumpTime = System.currentTimeMillis();
}
}
logger.info("Thread dump by ThreadDumpper" + reasonMsg != null ? (" for " + reasonMsg) : "");
// 参数均为false, 避免输出lockedMonitors和lockedSynchronizers导致的JVM缓慢
ThreadInfo[] threadInfos = threadMBean.dumpAllThreads(false, false);
StringBuilder b = new StringBuilder(8192);
b.append('[');
for (int i = 0; i < threadInfos.length; i++) {
b.append(dumpThreadInfo(threadInfos[i])).append(", ");
}
// 两条日志间的时间间隔,是VM被thread dump堵塞的时间.
logger.info(b.toString());
}
#location 22
#vulnerability type THREAD_SAFETY_VIOLATION | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
private void printExecution(ExecutionMetric execution) {
output.printf(" count = %d%n", execution.counter.count);
output.printf(" last rate = %2.2f/s%n", execution.counter.lastRate);
output.printf(" mean rate = %2.2f/s%n", execution.counter.meanRate);
output.printf(" min = %d ms%n", execution.histogram.min);
output.printf(" max = %d ms%n", execution.histogram.max);
output.printf(" mean = %2.2f ms%n", execution.histogram.mean);
for (Entry<Double, Long> pct : execution.histogram.pcts.entrySet()) {
output.printf(" %2.2f%% <= %d ms%n", pct.getKey(), pct.getValue());
}
} | #vulnerable code
private void printExecution(ExecutionMetric execution) {
output.printf(" count = %d%n", execution.counter.count);
output.printf(" last rate = %2.2f/s%n", execution.counter.lastRate);
output.printf(" mean rate = %2.2f/s%n", execution.counter.meanRate);
output.printf(" min = %d ms%n", execution.histogram.min);
output.printf(" max = %d ms%n", execution.histogram.max);
output.printf(" mean = %2.2f ms%n", execution.histogram.mean);
for (Entry<Double, Long> pct : execution.histogram.pcts.entrySet()) {
output.printf(" %2.2f%% <= %d ms%n", pct.getKey() * 100, pct.getValue());
}
}
#location 9
#vulnerability type CHECKERS_PRINTF_ARGS | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Test
public void nullAndEmpty() {
// toJson测试 //
// Null Bean
TestBean nullBean = null;
String nullBeanString = binder.toJson(nullBean);
assertThat(nullBeanString).isEqualTo("null");
// Empty List
List<String> emptyList = Lists.newArrayList();
String emptyListString = binder.toJson(emptyList);
assertThat(emptyListString).isEqualTo("[]");
// fromJson测试 //
// Null String for Bean
TestBean nullBeanResult = binder.fromJson(null, TestBean.class);
assertThat(nullBeanResult).isNull();
nullBeanResult = binder.fromJson("null", TestBean.class);
assertThat(nullBeanResult).isNull();
// Null/Empty String for List
List nullListResult = binder.fromJson(null, List.class);
assertThat(nullListResult).isNull();
nullListResult = binder.fromJson("null", List.class);
assertThat(nullListResult).isNull();
nullListResult = binder.fromJson("[]", List.class);
assertThat(nullListResult).isEmpty();
} | #vulnerable code
@Test
public void nullAndEmpty() {
// toJson测试 //
// Null Bean
TestBean nullBean = null;
String nullBeanString = binder.toJson(nullBean);
assertEquals("null", nullBeanString);
// Empty List
List<String> emptyList = Lists.newArrayList();
String emptyListString = binder.toJson(emptyList);
assertEquals("[]", emptyListString);
// fromJson测试 //
// Null String for Bean
TestBean nullBeanResult = binder.fromJson(null, TestBean.class);
assertNull(nullBeanResult);
nullBeanResult = binder.fromJson("null", TestBean.class);
assertNull(nullBeanResult);
// Null/Empty String for List
List nullListResult = binder.fromJson(null, List.class);
assertNull(nullListResult);
nullListResult = binder.fromJson("null", List.class);
assertNull(nullListResult);
nullListResult = binder.fromJson("[]", List.class);
assertEquals(0, nullListResult.size());
}
#location 32
#vulnerability type NULL_DEREFERENCE | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@RequestMapping(value = "/{id}", method = RequestMethod.GET)
@ResponseBody
public UserDTO getUser(@PathVariable("id") Long id) {
User user = accountService.getUser(id);
if (user == null) {
String message = "用户不存在(id:" + id + ")";
logger.warn(message);
throw new RestException(HttpStatus.NOT_FOUND, message);
}
// 使用Dozer转换DTO类,并补充Dozer不能自动绑定的属性
UserDTO dto = BeanMapper.map(user, UserDTO.class);
dto.setTeamId(user.getTeam().getId());
return dto;
} | #vulnerable code
@RequestMapping(value = "/{id}", method = RequestMethod.GET)
@ResponseBody
public UserDTO getUser(@PathVariable("id") Long id) {
User user = accountService.getUser(id);
// 使用Dozer转换DTO类,并补充Dozer不能自动绑定的属性
UserDTO dto = BeanMapper.map(user, UserDTO.class);
dto.setTeamId(user.getTeam().getId());
return dto;
}
#location 8
#vulnerability type NULL_DEREFERENCE | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
public void threadDumpIfNeed(String reasonMsg) {
if (!enable) {
return;
}
synchronized (this) {
if (System.currentTimeMillis() - lastThreadDumpTime < leastIntervalMills) {
return;
} else {
lastThreadDumpTime = System.currentTimeMillis();
}
}
logger.info("Thread dump by ThreadDumpper" + (reasonMsg != null ? (" for " + reasonMsg) : ""));
Map<Thread, StackTraceElement[]> threads = Thread.getAllStackTraces();
// 两条日志间的时间间隔,是VM被thread dump堵塞的时间.
logger.info("Finish the threads snapshot");
StringBuilder sb = new StringBuilder(8192 * 20).append("\n");
for (Entry<Thread, StackTraceElement[]> entry : threads.entrySet()) {
dumpThreadInfo(entry.getKey(), entry.getValue(), sb);
}
logger.info(sb.toString());
} | #vulnerable code
public void threadDumpIfNeed(String reasonMsg) {
if (!enable) {
return;
}
synchronized (this) {
if (System.currentTimeMillis() - lastThreadDumpTime < leastIntervalMills) {
return;
} else {
lastThreadDumpTime = System.currentTimeMillis();
}
}
logger.info("Thread dump by ThreadDumpper" + reasonMsg != null ? (" for " + reasonMsg) : "");
// 参数均为false, 避免输出lockedMonitors和lockedSynchronizers导致的JVM缓慢
ThreadInfo[] threadInfos = threadMBean.dumpAllThreads(false, false);
StringBuilder b = new StringBuilder(8192);
b.append('[');
for (int i = 0; i < threadInfos.length; i++) {
b.append(dumpThreadInfo(threadInfos[i])).append(", ");
}
// 两条日志间的时间间隔,是VM被thread dump堵塞的时间.
logger.info(b.toString());
}
#location 2
#vulnerability type THREAD_SAFETY_VIOLATION | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
private void reportExecution(String name, ExecutionMetric execution, long timestamp) throws IOException {
send(MetricRegistry.name(prefix, name, "count"), format(execution.counterMetric.lastCount), timestamp);
send(MetricRegistry.name(prefix, name, "min"), format(execution.histogramMetric.min), timestamp);
send(MetricRegistry.name(prefix, name, "max"), format(execution.histogramMetric.max), timestamp);
send(MetricRegistry.name(prefix, name, "mean"), format(execution.histogramMetric.mean), timestamp);
for (Entry<Double, Long> pct : execution.histogramMetric.pcts.entrySet()) {
send(MetricRegistry.name(prefix, name, format(pct.getKey()).replace('.', '_')), format(pct.getValue()),
timestamp);
}
} | #vulnerable code
private void reportExecution(String name, ExecutionMetric execution, long timestamp) throws IOException {
send(MetricRegistry.name(prefix, name, "count"), format(execution.counter.count), timestamp);
send(MetricRegistry.name(prefix, name, "min"), format(execution.histogram.min), timestamp);
send(MetricRegistry.name(prefix, name, "max"), format(execution.histogram.max), timestamp);
send(MetricRegistry.name(prefix, name, "mean"), format(execution.histogram.mean), timestamp);
for (Entry<Double, Long> pct : execution.histogram.pcts.entrySet()) {
send(MetricRegistry.name(prefix, name, format(pct.getKey()).replace('.', '_')), format(pct.getValue()),
timestamp);
}
}
#location 8
#vulnerability type NULL_DEREFERENCE | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
public HistogramMetric calculateMetric() {
// 快照当前的数据,在计算时不阻塞新的metrics update.
List<Long> snapshotList = measurements;
measurements = new LinkedList();
if (snapshotList.isEmpty()) {
return createEmptyMetric();
}
// 按数值大小排序,以快速支持百分比过滤
Collections.sort(snapshotList);
int count = snapshotList.size();
HistogramMetric metric = new HistogramMetric();
metric.min = snapshotList.get(0);
metric.max = snapshotList.get(count - 1);
double sum = 0;
for (long value : snapshotList) {
sum += value;
}
metric.mean = sum / count;
for (Double pct : pcts) {
metric.pcts.put(pct, getPercent(snapshotList, count, pct));
}
latestMetric = metric;
return metric;
} | #vulnerable code
public HistogramMetric calculateMetric() {
// 快照当前的数据,在计算时不阻塞新的metrics update.
List<Long> snapshotList = null;
synchronized (lock) {
snapshotList = measurements;
measurements = new LinkedList();
}
if (snapshotList.isEmpty()) {
return createEmptyMetric();
}
// 按数值大小排序,以快速支持百分比过滤
Collections.sort(snapshotList);
int count = snapshotList.size();
HistogramMetric metric = new HistogramMetric();
metric.min = snapshotList.get(0);
metric.max = snapshotList.get(count - 1);
double sum = 0;
for (long value : snapshotList) {
sum += value;
}
metric.mean = sum / count;
for (Double pct : pcts) {
metric.pcts.put(pct, getPercent(snapshotList, count, pct));
}
snapshot = metric;
return metric;
}
#location 33
#vulnerability type THREAD_SAFETY_VIOLATION | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
private static InetAddress findLocalAddressViaNetworkInterface() {
// 如果hostname +/etc/hosts 得到的是127.0.0.1, 则首选这块网卡
String preferNamePrefix = SystemPropertiesUtil.getString("localhost.prefer.nic.prefix",
"LOCALHOST_PREFER_NIC_PREFIX", "bond0.");
// 如果hostname +/etc/hosts 得到的是127.0.0.1, 和首选网卡都不符合要求,则按顺序遍历下面的网卡
String defaultNicList = SystemPropertiesUtil.getString("localhost.default.nic.list",
"LOCALHOST_DEFAULT_NIC_LIST", "bond0,eth0,em0,br0");
InetAddress resultAddress = null;
Map<String, NetworkInterface> candidateInterfaces = MapUtil.newHashMap();
// 遍历所有网卡,找出所有可用网卡,尝试找出符合prefer前缀的网卡
try {
for (Enumeration<NetworkInterface> allInterfaces = NetworkInterface.getNetworkInterfaces(); allInterfaces
.hasMoreElements();) {
NetworkInterface nic = allInterfaces.nextElement();
// 检查网卡可用并支持广播
try {
if (!nic.isUp() || !nic.supportsMulticast()) {
continue;
}
} catch (SocketException e) {
continue;
}
// 检查是否符合prefer前缀
String name = nic.getName();
if (name.startsWith(preferNamePrefix)) {
// 检查有否非ipv6 非127.0.0.1的inetaddress
resultAddress = findAvailableInetAddress(nic);
if (resultAddress != null) {
return resultAddress;
}
} else {
// 不是Prefer前缀,先放入可选列表
candidateInterfaces.put(name, nic);
}
}
for (String nifName : defaultNicList.split(",")) {
NetworkInterface nic = candidateInterfaces.get(nifName);
if (nic != null) {
resultAddress = findAvailableInetAddress(nic);
if (resultAddress != null) {
return resultAddress;
}
}
}
} catch (SocketException e) {
return null;
}
return null;
} | #vulnerable code
private static InetAddress findLocalAddressViaNetworkInterface() {
// 如果hostname +/etc/hosts 得到的是127.0.0.1, 则首选这块网卡
String preferNamePrefix = SystemPropertiesUtil.getString("localhost.prefer.nic.prefix",
"LOCALHOST_PREFER_NIC_PREFIX", "bond0.");
// 如果hostname +/etc/hosts 得到的是127.0.0.1, 和首选网卡都不符合要求,则按顺序遍历下面的网卡
String defaultNicList = SystemPropertiesUtil.getString("localhost.default.nic.list", "LOCALHOST_DEFAULT_NIC_LIST",
"bond0,eth0,em0,br0");
InetAddress resultAddress = null;
Map<String, NetworkInterface> candidateInterfaces = MapUtil.newHashMap();
// 遍历所有网卡,找出所有可用网卡,尝试找出符合prefer前缀的网卡
try {
for (Enumeration<NetworkInterface> allInterfaces = NetworkInterface.getNetworkInterfaces(); allInterfaces
.hasMoreElements();) {
NetworkInterface nic = allInterfaces.nextElement();
// 检查网卡可用并支持广播
try {
if (!nic.isUp() || !nic.supportsMulticast()) {
continue;
}
} catch (SocketException e) {
continue;
}
// 检查是否符合prefer前缀
String name = nic.getName();
if (name.startsWith(preferNamePrefix)) {
// 检查有否非ipv6 非127.0.0.1的inetaddress
resultAddress = findAvailableInetAddress(nic);
if (resultAddress != null) {
return resultAddress;
}
} else {
// 不是Prefer前缀,先放入可选列表
candidateInterfaces.put(name, nic);
}
}
for (String nifName : defaultNicList.split(",")) {
NetworkInterface nic = candidateInterfaces.get(nifName);
resultAddress = findAvailableInetAddress(nic);
if (resultAddress != null) {
return resultAddress;
}
}
} catch (SocketException e) {
return null;
}
return null;
}
#location 30
#vulnerability type NULL_DEREFERENCE | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
private void printCounter(CounterMetric counter) {
output.printf(" last count = %d%n", counter.lastCount);
output.printf(" total count = %d%n", counter.totalCount);
output.printf(" last rate = %d%n", counter.lastRate);
output.printf(" mean rate = %d%n", counter.meanRate);
} | #vulnerable code
private void printCounter(CounterMetric counter) {
output.printf(" last count = %d%n", counter.lastCount);
output.printf(" total count = %d%n", counter.totalCount);
output.printf(" last rate = %2.2f/s%n", counter.lastRate);
output.printf(" mean rate = %2.2f/s%n", counter.meanRate);
}
#location 5
#vulnerability type CHECKERS_PRINTF_ARGS | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
private void printTimer(TimerMetric timer) {
output.printf(" count = %d%n", timer.counterMetric.totalCount);
output.printf(" last rate = %d%n", timer.counterMetric.lastRate);
output.printf(" mean rate = %d%n", timer.counterMetric.meanRate);
output.printf(" min = %d ms%n", timer.histogramMetric.min);
output.printf(" max = %d ms%n", timer.histogramMetric.max);
output.printf(" mean = %2.2f ms%n", timer.histogramMetric.mean);
for (Entry<Double, Long> pct : timer.histogramMetric.pcts.entrySet()) {
output.printf(" %2.2f%% <= %d ms%n", pct.getKey(), pct.getValue());
}
} | #vulnerable code
private void printTimer(TimerMetric timer) {
output.printf(" count = %d%n", timer.counterMetric.totalCount);
output.printf(" last rate = %2.2f/s%n", timer.counterMetric.lastRate);
output.printf(" mean rate = %2.2f/s%n", timer.counterMetric.meanRate);
output.printf(" min = %d ms%n", timer.histogramMetric.min);
output.printf(" max = %d ms%n", timer.histogramMetric.max);
output.printf(" mean = %2.2f ms%n", timer.histogramMetric.mean);
for (Entry<Double, Long> pct : timer.histogramMetric.pcts.entrySet()) {
output.printf(" %2.2f%% <= %d ms%n", pct.getKey(), pct.getValue());
}
}
#location 4
#vulnerability type CHECKERS_PRINTF_ARGS | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
private void printCounter(CounterMetric counter) {
output.printf(" last count = %d%n", counter.lastCount);
output.printf(" total count = %d%n", counter.totalCount);
output.printf(" last rate = %d%n", counter.lastRate);
output.printf(" mean rate = %d%n", counter.meanRate);
} | #vulnerable code
private void printCounter(CounterMetric counter) {
output.printf(" last count = %d%n", counter.lastCount);
output.printf(" total count = %d%n", counter.totalCount);
output.printf(" last rate = %2.2f/s%n", counter.lastRate);
output.printf(" mean rate = %2.2f/s%n", counter.meanRate);
}
#location 4
#vulnerability type CHECKERS_PRINTF_ARGS | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
private void printTimer(TimerMetric timer) {
output.printf(" count = %d%n", timer.counterMetric.totalCount);
output.printf(" last rate = %d%n", timer.counterMetric.lastRate);
output.printf(" mean rate = %d%n", timer.counterMetric.meanRate);
output.printf(" min = %d ms%n", timer.histogramMetric.min);
output.printf(" max = %d ms%n", timer.histogramMetric.max);
output.printf(" mean = %2.2f ms%n", timer.histogramMetric.mean);
for (Entry<Double, Long> pct : timer.histogramMetric.pcts.entrySet()) {
output.printf(" %2.2f%% <= %d ms%n", pct.getKey(), pct.getValue());
}
} | #vulnerable code
private void printTimer(TimerMetric timer) {
output.printf(" count = %d%n", timer.counterMetric.totalCount);
output.printf(" last rate = %2.2f/s%n", timer.counterMetric.lastRate);
output.printf(" mean rate = %2.2f/s%n", timer.counterMetric.meanRate);
output.printf(" min = %d ms%n", timer.histogramMetric.min);
output.printf(" max = %d ms%n", timer.histogramMetric.max);
output.printf(" mean = %2.2f ms%n", timer.histogramMetric.mean);
for (Entry<Double, Long> pct : timer.histogramMetric.pcts.entrySet()) {
output.printf(" %2.2f%% <= %d ms%n", pct.getKey(), pct.getValue());
}
}
#location 3
#vulnerability type CHECKERS_PRINTF_ARGS | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
private void printHistogram(HistogramMetric histogram) {
output.printf(" min = %d%n", histogram.min);
output.printf(" max = %d%n", histogram.max);
output.printf(" mean = %2.2f%n", histogram.mean);
for (Entry<Double, Long> pct : histogram.pcts.entrySet()) {
output.printf(" %2.2f%% <= %d %n", pct.getKey(), pct.getValue());
}
} | #vulnerable code
private void printHistogram(HistogramMetric histogram) {
output.printf(" min = %d%n", histogram.min);
output.printf(" max = %d%n", histogram.max);
output.printf(" mean = %2.2f%n", histogram.mean);
for (Entry<Double, Long> pct : histogram.pcts.entrySet()) {
output.printf(" %2.2f%% <= %d %n", pct.getKey() * 100, pct.getValue());
}
}
#location 6
#vulnerability type CHECKERS_PRINTF_ARGS | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
public static VideoInfo getVideoInfo(File input) {
VideoInfo vi = new VideoInfo();
if (input != null && input.exists()) {
List<String> commands = Lists.newArrayList(BaseCommandOption.getFFprobeBinary());
commands.add(input.getAbsolutePath());
vi.setSize(FileUtils.getFineSize(input));
if (vi.getSize() > 0) {
return FFmpegUtils.regInfo(runProcess(commands), vi);
}
} else {
if (log.isErrorEnabled())
log.error("video '{}' is not fount! ", input.getAbsolutePath());
}
return vi;
} | #vulnerable code
public static VideoInfo getVideoInfo(File input) {
if (input != null && input.exists()) {
List<String> commands = Lists.newArrayList(BaseCommandOption.getFFprobeBinary());
commands.add(input.getAbsolutePath());
// if (log.isInfoEnabled())
// log.info("get video info commands : '{}'", FFmpegUtils.ffmpegCmdLine(commands));
try {
VideoInfo vi = new VideoInfo(new FileInputStream(input).available());
// pb = new ProcessBuilder();
// pb.command(commands);
//
// pb.redirectErrorStream(true);
//
//
// pro = pb.start();
// BufferedReader buf = null;
// buf = new BufferedReader(new InputStreamReader(pro.getInputStream()));
// StringBuffer sb = new StringBuffer();
// String line = null;
// while ((line = buf.readLine()) != null) {
// sb.append(line);
// continue;
// }
//
// int ret = pro.waitFor();
// if (log.isInfoEnabled())
// log.info("get video info process run status:'{}'", ret);
FFmpegUtils.regInfo(runProcess(commands, null), vi);
return vi;
} catch (IOException e) {
if (log.isErrorEnabled())
log.error("video '{}' get info IOException :'{} '", input.getAbsoluteFile(), e.getCause().getMessage());
e.printStackTrace();
} catch (InterruptedException e) {
if (log.isErrorEnabled())
log.error("video '{}' get info InterruptedException :'{} '", input.getAbsoluteFile(), e.getCause().getMessage());
e.printStackTrace();
} catch (Exception e) {
if (log.isErrorEnabled())
log.error("video '{}' get info Exception :'{} '", input.getAbsoluteFile(), e.getCause().getMessage());
e.printStackTrace();
}
} else {
if (log.isErrorEnabled())
log.error("video '{}' is not fount! ", input.getAbsolutePath());
}
return null;
}
#location 9
#vulnerability type RESOURCE_LEAK | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
public static VideoInfo getVideoInfo(File input) {
if (input != null && input.exists()) {
List<String> commands = Lists.newArrayList(BaseCommandOption.getFFprobeBinary());
commands.add(input.getAbsolutePath());
// if (log.isInfoEnabled())
// log.info("get video info commands : '{}'", FFmpegUtils.ffmpegCmdLine(commands));
try {
// pb = new ProcessBuilder();
// pb.command(commands);
//
// pb.redirectErrorStream(true);
//
//
// pro = pb.start();
// BufferedReader buf = null;
// buf = new BufferedReader(new InputStreamReader(pro.getInputStream()));
// StringBuffer sb = new StringBuffer();
// String line = null;
// while ((line = buf.readLine()) != null) {
// sb.append(line);
// continue;
// }
//
// int ret = pro.waitFor();
// if (log.isInfoEnabled())
// log.info("get video info process run status:'{}'", ret);
VideoInfo mi = FFmpegUtils.regInfo(runProcess(commands, null));
mi.setSize(new FileInputStream(input).available());
return mi;
} catch (IOException e) {
if (log.isErrorEnabled())
log.error("video '{}' get info IOException :'{} '", input.getAbsoluteFile(), e.getCause().getMessage());
e.printStackTrace();
} catch (InterruptedException e) {
if (log.isErrorEnabled())
log.error("video '{}' get info InterruptedException :'{} '", input.getAbsoluteFile(), e.getCause().getMessage());
e.printStackTrace();
} catch (Exception e) {
if (log.isErrorEnabled())
log.error("video '{}' get info Exception :'{} '", input.getAbsoluteFile(), e.getCause().getMessage());
e.printStackTrace();
}
} else {
if (log.isErrorEnabled())
log.error("video '{}' is not fount! ", input.getAbsolutePath());
}
return null;
} | #vulnerable code
public static VideoInfo getVideoInfo(File input) {
if (input != null && input.exists()) {
List<String> commands = Lists.newArrayList(BaseCommandOption.getFfmpegBinary());
commands.addAll(BaseCommandOption.toInputCommonsCmdArrays(input.getAbsolutePath()));
if (log.isInfoEnabled())
log.info("get video info commands : '{}'", FFmpegUtils.ffmpegCmdLine(commands));
try {
pb = new ProcessBuilder();
pb.command(commands);
pb.redirectErrorStream(true);
pro = pb.start();
BufferedReader buf = null;
buf = new BufferedReader(new InputStreamReader(pro.getInputStream()));
StringBuffer sb = new StringBuffer();
String line = null;
while ((line = buf.readLine()) != null) {
sb.append(line);
continue;
}
int ret = pro.waitFor();
if (log.isInfoEnabled())
log.info("get video info process run status:'{}'", ret);
VideoInfo mi = FFmpegUtils.regInfo(sb.toString());
mi.setSize(new FileInputStream(input).available());
return mi;
} catch (IOException e) {
if (log.isErrorEnabled())
log.error("video '{}' get info IOException :'{} '", input.getAbsoluteFile(), e.getCause().getMessage());
e.printStackTrace();
} catch (InterruptedException e) {
if (log.isErrorEnabled())
log.error("video '{}' get info InterruptedException :'{} '", input.getAbsoluteFile(), e.getCause().getMessage());
e.printStackTrace();
}
} else {
if (log.isErrorEnabled())
log.error("video '{}' is not fount! ", input.getAbsolutePath());
}
return null;
}
#location 30
#vulnerability type RESOURCE_LEAK | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
public String handler(InputStream errorStream) throws IOException {
FileChannel inputChannel =null;
if (errorStream instanceof FileInputStream) {
inputChannel = ((FileInputStream) errorStream).getChannel();
} else{
return "";
}
ByteArrayOutputStream byteArrayStream = new ByteArrayOutputStream(4096);
ByteBuffer buffer = ByteBuffer.allocate(4096);
StringBuffer sb = new StringBuffer();
try {
while (inputChannel.read(buffer) > -1) {
buffer.flip();
sb.append(buffer.get());
buffer.clear();
}
} catch (IOException e) {
// 当脚本执行超时,由于channel的关闭必然会抛出异常
log.error("read from process error : '{}'",e);
throw e;
}
finally {
if(inputChannel!=null)
inputChannel.close();
}
setResult(sb.toString());
return getResult();
} | #vulnerable code
public String handler(InputStream errorStream) throws IOException {
BufferedReader reader = new BufferedReader(new InputStreamReader(errorStream,BaseCommandOption.UTF8));
StringBuffer sb = new StringBuffer();
String line;
try {
while ((line = reader.readLine()) != null){
sb.append(line).append("\n");
// if(log.isDebugEnabled())
// log.debug(line);
}
}catch (IOException e){
log.error("read from process error : '{}'",e);
throw e;
}finally {
try {
errorStream.close();
}catch (IOException e){
log.error("close errorStream error: '{}'",e);
}
}
setResult(sb.toString());
return getResult();
}
#location 11
#vulnerability type RESOURCE_LEAK | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
public static VideoInfo getVideoInfo(File input) {
if (input != null && input.exists()) {
List<String> commands = Lists.newArrayList(BaseCommandOption.getFFprobeBinary());
commands.add(input.getAbsolutePath());
// if (log.isInfoEnabled())
// log.info("get video info commands : '{}'", FFmpegUtils.ffmpegCmdLine(commands));
try {
VideoInfo vi = new VideoInfo(new FileInputStream(input).available());
// pb = new ProcessBuilder();
// pb.command(commands);
//
// pb.redirectErrorStream(true);
//
//
// pro = pb.start();
// BufferedReader buf = null;
// buf = new BufferedReader(new InputStreamReader(pro.getInputStream()));
// StringBuffer sb = new StringBuffer();
// String line = null;
// while ((line = buf.readLine()) != null) {
// sb.append(line);
// continue;
// }
//
// int ret = pro.waitFor();
// if (log.isInfoEnabled())
// log.info("get video info process run status:'{}'", ret);
FFmpegUtils.regInfo(runProcess(commands, null), vi);
return vi;
} catch (IOException e) {
if (log.isErrorEnabled())
log.error("video '{}' get info IOException :'{} '", input.getAbsoluteFile(), e.getCause().getMessage());
e.printStackTrace();
} catch (InterruptedException e) {
if (log.isErrorEnabled())
log.error("video '{}' get info InterruptedException :'{} '", input.getAbsoluteFile(), e.getCause().getMessage());
e.printStackTrace();
} catch (Exception e) {
if (log.isErrorEnabled())
log.error("video '{}' get info Exception :'{} '", input.getAbsoluteFile(), e.getCause().getMessage());
e.printStackTrace();
}
} else {
if (log.isErrorEnabled())
log.error("video '{}' is not fount! ", input.getAbsolutePath());
}
return null;
} | #vulnerable code
public static VideoInfo getVideoInfo(File input) {
if (input != null && input.exists()) {
List<String> commands = Lists.newArrayList(BaseCommandOption.getFFprobeBinary());
commands.add(input.getAbsolutePath());
// if (log.isInfoEnabled())
// log.info("get video info commands : '{}'", FFmpegUtils.ffmpegCmdLine(commands));
try {
// pb = new ProcessBuilder();
// pb.command(commands);
//
// pb.redirectErrorStream(true);
//
//
// pro = pb.start();
// BufferedReader buf = null;
// buf = new BufferedReader(new InputStreamReader(pro.getInputStream()));
// StringBuffer sb = new StringBuffer();
// String line = null;
// while ((line = buf.readLine()) != null) {
// sb.append(line);
// continue;
// }
//
// int ret = pro.waitFor();
// if (log.isInfoEnabled())
// log.info("get video info process run status:'{}'", ret);
VideoInfo mi = FFmpegUtils.regInfo(runProcess(commands, null));
mi.setSize(new FileInputStream(input).available());
return mi;
} catch (IOException e) {
if (log.isErrorEnabled())
log.error("video '{}' get info IOException :'{} '", input.getAbsoluteFile(), e.getCause().getMessage());
e.printStackTrace();
} catch (InterruptedException e) {
if (log.isErrorEnabled())
log.error("video '{}' get info InterruptedException :'{} '", input.getAbsoluteFile(), e.getCause().getMessage());
e.printStackTrace();
} catch (Exception e) {
if (log.isErrorEnabled())
log.error("video '{}' get info Exception :'{} '", input.getAbsoluteFile(), e.getCause().getMessage());
e.printStackTrace();
}
} else {
if (log.isErrorEnabled())
log.error("video '{}' is not fount! ", input.getAbsolutePath());
}
return null;
}
#location 29
#vulnerability type RESOURCE_LEAK | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
public void agglomerate(LinkageStrategy linkageStrategy) {
Collections.sort(distances);
if (distances.size() > 0) {
ClusterPair minDistLink = distances.remove(0);
clusters.remove(minDistLink.getrCluster());
clusters.remove(minDistLink.getlCluster());
Cluster oldClusterL = minDistLink.getlCluster();
Cluster oldClusterR = minDistLink.getrCluster();
Cluster newCluster = minDistLink.agglomerate(null);
for (Cluster iClust : clusters) {
ClusterPair link1 = findByClusters(iClust, oldClusterL);
ClusterPair link2 = findByClusters(iClust, oldClusterR);
ClusterPair newLinkage = new ClusterPair();
newLinkage.setlCluster(iClust);
newLinkage.setrCluster(newCluster);
Collection<Double> distanceValues = new ArrayList<Double>();
if (link1 != null) {
distanceValues.add(link1.getLinkageDistance());
distances.remove(link1);
}
if (link2 != null) {
distanceValues.add(link2.getLinkageDistance());
distances.remove(link2);
}
Double newDistance = linkageStrategy
.calculateDistance(distanceValues);
newLinkage.setLinkageDistance(newDistance);
distances.add(newLinkage);
}
clusters.add(newCluster);
}
} | #vulnerable code
public void agglomerate(LinkageStrategy linkageStrategy) {
Collections.sort(distances);
if (distances.size() > 0) {
ClusterPair minDistLink = distances.remove(0);
clusters.remove(minDistLink.getrCluster());
clusters.remove(minDistLink.getlCluster());
Cluster oldClusterL = minDistLink.getlCluster();
Cluster oldClusterR = minDistLink.getrCluster();
Cluster newCluster = minDistLink.agglomerate(null);
for (Cluster iClust : clusters) {
ClusterPair link1 = findByClusters(iClust, oldClusterL);
ClusterPair link2 = findByClusters(iClust, oldClusterR);
ClusterPair newLinkage = new ClusterPair();
newLinkage.setlCluster(iClust);
newLinkage.setrCluster(newCluster);
Collection<Double> distanceValues = new ArrayList<Double>();
if (link1 != null) {
distanceValues.add(link1.getLinkageDistance());
distances.remove(link1);
}
if (link1 != null) {
distanceValues.add(link2.getLinkageDistance());
distances.remove(link2);
}
Double newDistance = linkageStrategy
.calculateDistance(distanceValues);
newLinkage.setLinkageDistance(newDistance);
distances.add(newLinkage);
}
clusters.add(newCluster);
}
}
#location 24
#vulnerability type NULL_DEREFERENCE | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Test
public void imageTest06() throws IOException, InterruptedException {
String outFileName = destinationFolder + "imageTest06.pdf";
String cmpFileName = sourceFolder + "cmp_imageTest06.pdf";
FileOutputStream file = new FileOutputStream(outFileName);
PdfWriter writer = new PdfWriter(file);
PdfDocument pdfDoc = new PdfDocument(writer);
Document doc = new Document(pdfDoc);
PdfImageXObject xObject = new PdfImageXObject(pdfDoc, ImageFactory.getJpegImage(new File(sourceFolder+"Desert.jpg").toURI().toURL()));
Image image = new Image(xObject, 100);
doc.add(new Paragraph(new Text("First Line")));
Paragraph p = new Paragraph();
p.add(image);
image.setTranslationDistance(100, -100);
doc.add(p);
doc.add(new Paragraph(new Text("Second Line")));
doc.close();
Assert.assertNull(new CompareTool().compareByContent(outFileName, cmpFileName, destinationFolder, "diff"));
} | #vulnerable code
@Test
public void imageTest06() throws IOException, InterruptedException {
String outFileName = destinationFolder + "imageTest06.pdf";
String cmpFileName = sourceFolder + "cmp_imageTest06.pdf";
FileOutputStream file = new FileOutputStream(outFileName);
PdfWriter writer = new PdfWriter(file);
PdfDocument pdfDoc = new PdfDocument(writer);
Document doc = new Document(pdfDoc);
ByteArrayOutputStream buffer = new ByteArrayOutputStream();
int nRead;
FileInputStream is = new FileInputStream(sourceFolder+"Desert.jpg");
nRead = is.read();
while (nRead != -1){
buffer.write(nRead);
nRead = is.read();
}
PdfImageXObject xObject = new PdfImageXObject(pdfDoc, ImageFactory.getJpegImage(buffer.toByteArray()));
Image image = new Image(xObject, 100);
doc.add(new Paragraph(new Text("First Line")));
Paragraph p = new Paragraph();
p.add(image);
image.setTranslationDistance(100, -100);
doc.add(p);
doc.add(new Paragraph(new Text("Second Line")));
doc.close();
Assert.assertNull(new CompareTool().compareByContent(outFileName, cmpFileName, destinationFolder, "diff"));
}
#location 25
#vulnerability type RESOURCE_LEAK | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Override
public PdfObject getDestinationPage(final HashMap<Object, PdfObject> names) throws PdfException {
PdfArray array = (PdfArray) names.get(getPdfObject());
return array != null ? array.get(0, false) : null;
} | #vulnerable code
@Override
public PdfObject getDestinationPage(final HashMap<Object, PdfObject> names) throws PdfException {
PdfArray array = (PdfArray) names.get(getPdfObject());
return array.get(0, false);
}
#location 5
#vulnerability type NULL_DEREFERENCE | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
public OutputStream writeFloat(float value) throws IOException {
int intPart = (int) value;
int fractalPart = (int) (value - (int) value) * 1000;
writeInteger(intPart, 8).writeByte((byte) '.').writeInteger(fractalPart, 4);
return this;
} | #vulnerable code
public OutputStream writeFloat(float value) throws IOException {
write(getIsoBytes(String.valueOf(value)));
return this;
}
#location 2
#vulnerability type NULL_DEREFERENCE | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
public OutputStream writeBoolean(boolean value) throws IOException {
write(value ? booleanTrue : booleanFalse);
return this;
} | #vulnerable code
public OutputStream writeBoolean(boolean value) throws IOException {
write(getIsoBytes(String.valueOf(value)));
return this;
}
#location 2
#vulnerability type NULL_DEREFERENCE | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
protected int writeXRefTable() throws IOException, PdfException {
int strtxref = currentPos;
if (fullCompression) {
PdfStream stream = new PdfStream(pdfDocument);
stream.put(PdfName.Type, PdfName.XRef);
stream.put(PdfName.Size, new PdfNumber(pdfDocument.getIndirects().size() + 1));
stream.put(PdfName.W, new PdfArray(new ArrayList<PdfObject>() {{
add(new PdfNumber(1));
add(new PdfNumber(4));
add(new PdfNumber(2));
}}));
stream.put(PdfName.Info, pdfDocument.trailer.getDocumentInfo());
stream.put(PdfName.Root, pdfDocument.trailer.getCatalog());
stream.getOutputStream().write(0);
stream.getOutputStream().write(intToBytes(0));
stream.getOutputStream().write(shortToBytes(0xFFFF));
for (PdfIndirectReference indirect : pdfDocument.getIndirects()) {
PdfObject refersTo = indirect.getRefersTo();
if (refersTo.getObjectStream() != null) {
stream.getOutputStream().write(2);
stream.getOutputStream().write(intToBytes(refersTo.getObjectStream().getIndirectReference().getObjNr()));
stream.getOutputStream().write(shortToBytes(refersTo.getOffset()));
} else {
stream.getOutputStream().write(1);
stream.getOutputStream().write(intToBytes(refersTo.getOffset()));
stream.getOutputStream().write(shortToBytes(0));
}
}
stream.flush();
} else {
writeString("xref\n").
writeString("0 ").
writeInteger(pdfDocument.getIndirects().size() + 1).
writeString("\n0000000000 65535 f \n");
for (PdfIndirectReference indirect : pdfDocument.getIndirects()) {
writeString(objectOffsetFormatter.format(indirect.getRefersTo().getOffset())).
writeBytes(endXRefEntry);
}
}
return strtxref;
} | #vulnerable code
protected int writeXRefTable() throws IOException, PdfException {
int strtxref = currentPos;
if (fullCompression) {
PdfStream stream = new PdfStream(pdfDocument);
stream.put(PdfName.Type, PdfName.XRef);
stream.put(PdfName.Size, new PdfNumber(pdfDocument.getIndirects().size() + 1));
stream.put(PdfName.W, new PdfArray(new ArrayList<PdfObject>() {{
add(new PdfNumber(1));
add(new PdfNumber(4));
add(new PdfNumber(2));
}}));
stream.put(PdfName.Info, pdfDocument.trailer.getDocumentInfo());
stream.put(PdfName.Root, pdfDocument.trailer.getCatalog());
stream.getOutputStream().write(0);
stream.getOutputStream().write(intToBytes(0));
stream.getOutputStream().write(shortToBytes(0xFFFF));
for (PdfIndirectReference indirect : pdfDocument.getIndirects()) {
PdfObject refersTo = indirect.getRefersTo();
if (refersTo.getObjectStream() != null) {
stream.getOutputStream().write(2);
stream.getOutputStream().write(intToBytes(refersTo.getObjectStream().getIndirectReference().getObjNr()));
stream.getOutputStream().write(shortToBytes(refersTo.getOffset()));
} else {
stream.getOutputStream().write(1);
stream.getOutputStream().write(intToBytes(refersTo.getOffset()));
stream.getOutputStream().write(shortToBytes(0));
}
}
stream.flush();
} else {
writeString("xref\n").
writeString("0 ").
writeInteger(pdfDocument.getIndirects().size() + 1).
writeString("\n0000000000 65535 f \n");
for (PdfIndirectReference indirect : pdfDocument.getIndirects()) {
writeString(objectOffsetFormatter.format(indirect.getRefersTo().getOffset())).
writeString(" 00000 n \n");
}
}
return strtxref;
}
#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 outlinesTest() throws IOException, PdfException {
PdfReader reader = new PdfReader(new FileInputStream(sourceFolder+"iphone_user_guide.pdf"));
PdfDocument pdfDoc = new PdfDocument(reader);
PdfOutline outlines = pdfDoc.getOutlines(false);
List<PdfOutline> children = outlines.getAllChildren().get(0).getAllChildren();
Assert.assertEquals(outlines.getTitle(), "Outlines");
Assert.assertEquals(children.size(), 13);
Assert.assertTrue(children.get(0).getDestination() instanceof PdfStringDestination);
} | #vulnerable code
@Test
public void outlinesTest() throws IOException, PdfException {
PdfReader reader = new PdfReader(new FileInputStream(sourceFolder+"iphone_user_guide.pdf"));
PdfDocument pdfDoc = new PdfDocument(reader);
PdfOutline outlines = pdfDoc.getCatalog().getOutlines();
List<PdfOutline> children = outlines.getAllChildren().get(0).getAllChildren();
Assert.assertEquals(outlines.getTitle(), "Outlines");
Assert.assertEquals(children.size(), 13);
Assert.assertTrue(children.get(0).getDestination() instanceof PdfStringDestination);
}
#location 6
#vulnerability type NULL_DEREFERENCE | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Test
public void imageTest01() throws IOException, InterruptedException {
String outFileName = destinationFolder + "imageTest01.pdf";
String cmpFileName = sourceFolder + "cmp_imageTest01.pdf";
FileOutputStream file = new FileOutputStream(outFileName);
PdfWriter writer = new PdfWriter(file);
PdfDocument pdfDoc = new PdfDocument(writer);
Document doc = new Document(pdfDoc);
PdfImageXObject xObject = new PdfImageXObject(ImageFactory.getImage(sourceFolder + "Desert.jpg"));
Image image = new Image(xObject, 100);
doc.add(new Paragraph(new Text("First Line")));
Paragraph p = new Paragraph();
p.add(image);
doc.add(p);
doc.add(new Paragraph(new Text("Second Line")));
doc.close();
Assert.assertNull(new CompareTool().compareByContent(outFileName, cmpFileName, destinationFolder, "diff"));
} | #vulnerable code
@Test
public void imageTest01() throws IOException, InterruptedException {
String outFileName = destinationFolder + "imageTest01.pdf";
String cmpFileName = sourceFolder + "cmp_imageTest01.pdf";
FileOutputStream file = new FileOutputStream(outFileName);
PdfWriter writer = new PdfWriter(file);
PdfDocument pdfDoc = new PdfDocument(writer);
Document doc = new Document(pdfDoc);
PdfImageXObject xObject = new PdfImageXObject(ImageFactory.getJpegImage(new File(sourceFolder+"Desert.jpg").toURI().toURL()));
Image image = new Image(xObject, 100);
doc.add(new Paragraph(new Text("First Line")));
Paragraph p = new Paragraph();
p.add(image);
doc.add(p);
doc.add(new Paragraph(new Text("Second Line")));
doc.close();
Assert.assertNull(new CompareTool().compareByContent(outFileName, cmpFileName, destinationFolder, "diff"));
}
#location 27
#vulnerability type RESOURCE_LEAK | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
public void flatFields() {
if (document.isAppendMode()) {
throw new PdfException(PdfException.FieldFlatteningIsNotSupportedInAppendMode);
}
Map<String, PdfFormField> fields = getFormFields();
PdfPage page = null;
for (Map.Entry<String, PdfFormField> entry : fields.entrySet()) {
PdfFormField field = entry.getValue();
PdfDictionary pageDic = field.getPdfObject().getAsDictionary(PdfName.P);
if (pageDic == null) {
continue;
}
page = getPage(pageDic);
PdfDictionary appDic = field.getPdfObject().getAsDictionary(PdfName.AP);
PdfObject asNormal = null;
if (appDic != null) {
asNormal = appDic.getAsStream(PdfName.N);
if (asNormal == null) {
asNormal = appDic.getAsDictionary(PdfName.N);
}
}
if (generateAppearance) {
if (appDic == null || asNormal == null) {
field.regenerateField();
appDic = field.getPdfObject().getAsDictionary(PdfName.AP);
}
}
if (appDic != null) {
PdfObject normal = appDic.get(PdfName.N);
PdfFormXObject xObject = null;
if (normal.isStream()) {
xObject = new PdfFormXObject((PdfStream) normal);
} else if (normal.isDictionary()) {
PdfName as = field.getPdfObject().getAsName(PdfName.AS);
xObject = new PdfFormXObject(((PdfDictionary)normal).getAsStream(as)).makeIndirect(document);
}
if (xObject != null) {
Rectangle box = field.getPdfObject().getAsRectangle(PdfName.Rect);
PdfCanvas canvas = new PdfCanvas(page);
canvas.addXObject(xObject, box.getX(), box.getY());
PdfArray fFields = getFields();
fFields.remove(field.getPdfObject().getIndirectReference());
PdfArray annots = page.getPdfObject().getAsArray(PdfName.Annots);
annots.remove(field.getPdfObject().getIndirectReference());
PdfDictionary parent = field.getPdfObject().getAsDictionary(PdfName.Parent);
if (parent != null) {
PdfArray kids = parent.getAsArray(PdfName.Kids);
kids.remove(field.getPdfObject().getIndirectReference());
if (kids == null || kids.isEmpty()) {
fFields.remove(parent.getIndirectReference());
}
}
}
}
}
if (page != null && page.getPdfObject().getAsArray(PdfName.Annots).isEmpty()) {
page.getPdfObject().remove(PdfName.Annots);
}
getPdfObject().remove(PdfName.NeedAppearances);
if (getFields().isEmpty()) {
document.getCatalog().getPdfObject().remove(PdfName.AcroForm);
}
} | #vulnerable code
public void flatFields() {
if (document.isAppendMode()) {
throw new PdfException(PdfException.FieldFlatteningIsNotSupportedInAppendMode);
}
List<PdfFormField> fields = getFormFields();
PdfPage page = null;
for (PdfFormField field : fields) {
PdfDictionary pageDic = field.getPdfObject().getAsDictionary(PdfName.P);
if (pageDic == null) {
continue;
}
for (int i = 1; i <= document.getNumOfPages(); i++) {
page = document.getPage(i);
if (page.getPdfObject() == pageDic) {
break;
}
}
PdfDictionary appDic = field.getPdfObject().getAsDictionary(PdfName.AP);
PdfObject asNormal = null;
if (appDic != null) {
asNormal = appDic.getAsStream(PdfName.N);
if (asNormal == null) {
asNormal = appDic.getAsDictionary(PdfName.N);
}
}
if (generateAppearance) {
if (appDic == null || asNormal == null) {
field.regenerateField();
appDic = field.getPdfObject().getAsDictionary(PdfName.AP);
}
}
if (appDic != null) {
PdfObject normal = appDic.get(PdfName.N);
PdfFormXObject xObject = null;
if (normal.isStream()) {
xObject = new PdfFormXObject((PdfStream) normal);
} else if (normal.isDictionary()) {
PdfName as = field.getPdfObject().getAsName(PdfName.AS);
xObject = new PdfFormXObject(((PdfDictionary)normal).getAsStream(as)).makeIndirect(document);
}
if (xObject != null) {
Rectangle box = field.getPdfObject().getAsRectangle(PdfName.Rect);
PdfCanvas canvas = new PdfCanvas(page);
canvas.addXObject(xObject, box.getX(), box.getY());
PdfArray fFields = getFields();
fFields.remove(field.getPdfObject().getIndirectReference());
PdfArray annots = page.getPdfObject().getAsArray(PdfName.Annots);
annots.remove(field.getPdfObject().getIndirectReference());
PdfDictionary parent = field.getPdfObject().getAsDictionary(PdfName.Parent);
if (parent != null) {
PdfArray kids = parent.getAsArray(PdfName.Kids);
kids.remove(field.getPdfObject().getIndirectReference());
if (kids == null || kids.isEmpty()) {
fFields.remove(parent.getIndirectReference());
}
}
}
}
}
if (page.getPdfObject().getAsArray(PdfName.Annots).isEmpty()) {
page.getPdfObject().remove(PdfName.Annots);
}
getPdfObject().remove(PdfName.NeedAppearances);
if (getFields().isEmpty()) {
document.getCatalog().getPdfObject().remove(PdfName.AcroForm);
}
}
#location 64
#vulnerability type NULL_DEREFERENCE | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
public OutputStream writeDouble(double value) throws IOException {
return writeFloat((float)value);
} | #vulnerable code
public OutputStream writeDouble(double value) throws IOException {
write(getIsoBytes(String.valueOf(value)));
return this;
}
#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 taggingTest05() throws Exception {
FileInputStream fis = new FileInputStream(sourceFolder + "iphone_user_guide.pdf");
PdfReader reader = new PdfReader(fis);
PdfDocument source = new PdfDocument(reader);
PdfWriter writer = new PdfWriter(new FileOutputStream(destinationFolder + "taggingTest05.pdf"));
PdfDocument destination = new PdfDocument(writer);
destination.setTagged();
source.copyPages(new TreeSet<Integer>() {{
add(3);
add(4);
add(10);
add(11);
}}, destination).copyPages(50, 52, destination);
destination.close();
source.close();
Assert.assertNull(new CompareTool().compareByContent(destinationFolder + "taggingTest05.pdf", sourceFolder + "cmp_taggingTest05.pdf", destinationFolder, "diff_"));
} | #vulnerable code
@Test
public void taggingTest05() throws Exception {
FileInputStream fis = new FileInputStream(sourceFolder + "iphone_user_guide.pdf");
PdfReader reader = new PdfReader(fis);
PdfDocument document = new PdfDocument(reader);
Assert.assertEquals(2072, document.getNextStructParentIndex().intValue());
document.close();
}
#location 7
#vulnerability type NULL_DEREFERENCE | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Test
public void imageTest03() throws IOException, InterruptedException {
String outFileName = destinationFolder + "imageTest03.pdf";
String cmpFileName = sourceFolder + "cmp_imageTest03.pdf";
FileOutputStream file = new FileOutputStream(outFileName);
PdfWriter writer = new PdfWriter(file);
PdfDocument pdfDoc = new PdfDocument(writer);
Document doc = new Document(pdfDoc);
PdfImageXObject xObject = new PdfImageXObject(pdfDoc, ImageFactory.getJpegImage(new File(sourceFolder+"Desert.jpg").toURI().toURL()));
Image image = new Image(xObject, 100);
doc.add(new Paragraph(new Text("First Line")));
Paragraph p = new Paragraph();
p.add(image);
image.setRotateAngle(Math.PI/6);
doc.add(p);
doc.add(new Paragraph(new Text("Second Line")));
doc.close();
Assert.assertNull(new CompareTool().compareByContent(outFileName, cmpFileName, destinationFolder, "diff"));
} | #vulnerable code
@Test
public void imageTest03() throws IOException, InterruptedException {
String outFileName = destinationFolder + "imageTest03.pdf";
String cmpFileName = sourceFolder + "cmp_imageTest03.pdf";
FileOutputStream file = new FileOutputStream(outFileName);
PdfWriter writer = new PdfWriter(file);
PdfDocument pdfDoc = new PdfDocument(writer);
Document doc = new Document(pdfDoc);
ByteArrayOutputStream buffer = new ByteArrayOutputStream();
int nRead;
FileInputStream is = new FileInputStream(sourceFolder+"Desert.jpg");
nRead = is.read();
while (nRead != -1){
buffer.write(nRead);
nRead = is.read();
}
PdfImageXObject xObject = new PdfImageXObject(pdfDoc, ImageFactory.getJpegImage(buffer.toByteArray()));
Image image = new Image(xObject, 100);
doc.add(new Paragraph(new Text("First Line")));
Paragraph p = new Paragraph();
p.add(image);
image.setRotateAngle(Math.PI/6);
doc.add(p);
doc.add(new Paragraph(new Text("Second Line")));
doc.close();
Assert.assertNull(new CompareTool().compareByContent(outFileName, cmpFileName, destinationFolder, "diff"));
}
#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 imageTest04() throws IOException, InterruptedException {
String outFileName = destinationFolder + "imageTest04.pdf";
String cmpFileName = sourceFolder + "cmp_imageTest04.pdf";
FileOutputStream file = new FileOutputStream(outFileName);
PdfWriter writer = new PdfWriter(file);
PdfDocument pdfDoc = new PdfDocument(writer);
Document doc = new Document(pdfDoc);
PdfImageXObject xObject = new PdfImageXObject(ImageFactory.getImage(sourceFolder + "Desert.jpg"));
Image image = new Image(xObject, 100);
Paragraph p = new Paragraph();
p.add(new Text("before image"));
p.add(image);
image.setRotationAngle(Math.PI / 6);
p.add(new Text("after image"));
doc.add(p);
doc.close();
Assert.assertNull(new CompareTool().compareByContent(outFileName, cmpFileName, destinationFolder, "diff"));
} | #vulnerable code
@Test
public void imageTest04() throws IOException, InterruptedException {
String outFileName = destinationFolder + "imageTest04.pdf";
String cmpFileName = sourceFolder + "cmp_imageTest04.pdf";
FileOutputStream file = new FileOutputStream(outFileName);
PdfWriter writer = new PdfWriter(file);
PdfDocument pdfDoc = new PdfDocument(writer);
Document doc = new Document(pdfDoc);
PdfImageXObject xObject = new PdfImageXObject(ImageFactory.getJpegImage(new File(sourceFolder+"Desert.jpg").toURI().toURL()));
Image image = new Image(xObject, 100);
Paragraph p = new Paragraph();
p.add(new Text("before image"));
p.add(image);
image.setRotationAngle(Math.PI / 6);
p.add(new Text("after image"));
doc.add(p);
doc.close();
Assert.assertNull(new CompareTool().compareByContent(outFileName, cmpFileName, destinationFolder, "diff"));
}
#location 28
#vulnerability type RESOURCE_LEAK | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Override
public PdfObject getDestinationPage(HashMap<Object, PdfObject> names) throws PdfException {
PdfArray array = (PdfArray) names.get(getPdfObject().toUnicodeString());
return array != null ? array.get(0, false) : null;
} | #vulnerable code
@Override
public PdfObject getDestinationPage(HashMap<Object, PdfObject> names) throws PdfException {
PdfArray array = (PdfArray) names.get(getPdfObject().toUnicodeString());
return array.get(0, 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 formFieldTest01() throws IOException {
PdfReader reader = new PdfReader(sourceFolder + "formFieldFile.pdf");
PdfDocument pdfDoc = new PdfDocument(reader);
PdfAcroForm form = PdfAcroForm.getAcroForm(pdfDoc, false);
Map<String, PdfFormField> fields = form.getFormFields();
PdfFormField field = fields.get("Text1");
Assert.assertTrue(fields.size() == 6);
Assert.assertTrue(field.getFieldName().toUnicodeString().equals("Text1"));
Assert.assertTrue(field.getValue().toString().equals("TestField"));
} | #vulnerable code
@Test
public void formFieldTest01() throws IOException {
PdfReader reader = new PdfReader(sourceFolder + "formFieldFile.pdf");
PdfDocument pdfDoc = new PdfDocument(reader);
PdfAcroForm form = PdfAcroForm.getAcroForm(pdfDoc, false);
ArrayList<PdfFormField> fields = (ArrayList<PdfFormField>) form.getFormFields();
PdfFormField field = fields.get(3);
Assert.assertTrue(fields.size() == 6);
Assert.assertTrue(field.getFieldName().toUnicodeString().equals("Text1"));
Assert.assertTrue(field.getValue().toString().equals("TestField"));
}
#location 6
#vulnerability type NULL_DEREFERENCE | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
public PdfFormXObject createFormXObjectWithBarcode(Color barColor, Color textColor) {
PdfFormXObject xObject = new PdfFormXObject(document, null);
Rectangle rect = placeBarcode(new PdfCanvas(xObject), barColor, textColor);
xObject.setBBox(rect.toPdfArray());
return xObject;
} | #vulnerable code
public PdfFormXObject createFormXObjectWithBarcode(Color barColor, Color textColor) {
PdfStream stream = new PdfStream(document);
PdfCanvas canvas = new PdfCanvas(stream, new PdfResources());
Rectangle rect = placeBarcode(canvas, barColor, textColor);
PdfFormXObject xObject = new PdfFormXObject(document, rect);
xObject.getPdfObject().getOutputStream().writeBytes(stream.getBytes());
return xObject;
}
#location 7
#vulnerability type RESOURCE_LEAK | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
protected void justify(float width) {
float ratio = getPropertyAsFloat(Property.SPACING_RATIO);
float freeWidth = occupiedArea.getBBox().getX() + width -
getLastChildRenderer().getOccupiedArea().getBBox().getX() - getLastChildRenderer().getOccupiedArea().getBBox().getWidth();
int numberOfSpaces = getNumberOfSpaces();
int lineLength = length();
float baseFactor = freeWidth / (ratio * numberOfSpaces + (1 - ratio) * (lineLength - 1));
float wordSpacing = ratio * baseFactor;
float characterSpacing = (1 - ratio) * baseFactor;
float lastRightPos = occupiedArea.getBBox().getX();
for (IRenderer child : childRenderers) {
float childX = child.getOccupiedArea().getBBox().getX();
child.move(lastRightPos - childX, 0);
childX = lastRightPos;
if (child instanceof TextRenderer) {
float childHSCale = child.getProperty(Property.HORIZONTAL_SCALING);
child.setProperty(Property.CHARACTER_SPACING, characterSpacing / childHSCale);
child.setProperty(Property.WORD_SPACING, wordSpacing / childHSCale);
child.getOccupiedArea().getBBox().setWidth(child.getOccupiedArea().getBBox().getWidth() +
characterSpacing * ((TextRenderer) child).length() + wordSpacing * ((TextRenderer) child).getNumberOfSpaces());
}
lastRightPos = childX + child.getOccupiedArea().getBBox().getWidth();
}
getOccupiedArea().getBBox().setWidth(width);
} | #vulnerable code
protected void justify(float width) {
float ratio = .5f;
float freeWidth = occupiedArea.getBBox().getX() + width -
getLastChildRenderer().getOccupiedArea().getBBox().getX() - getLastChildRenderer().getOccupiedArea().getBBox().getWidth();
int numberOfSpaces = getNumberOfSpaces();
int lineLength = length();
float baseFactor = freeWidth / (ratio * numberOfSpaces + lineLength - 1);
float wordSpacing = ratio * baseFactor;
float characterSpacing = baseFactor;
float lastRightPos = occupiedArea.getBBox().getX();
for (IRenderer child : childRenderers) {
float childX = child.getOccupiedArea().getBBox().getX();
child.move(lastRightPos - childX, 0);
childX = lastRightPos;
if (child instanceof TextRenderer) {
float childHSCale = child.getProperty(Property.HORIZONTAL_SCALING);
child.setProperty(Property.CHARACTER_SPACING, characterSpacing / childHSCale);
child.setProperty(Property.WORD_SPACING, wordSpacing / childHSCale);
child.getOccupiedArea().getBBox().setWidth(child.getOccupiedArea().getBBox().getWidth() +
characterSpacing * ((TextRenderer) child).length() + wordSpacing * ((TextRenderer) child).getNumberOfSpaces());
}
lastRightPos = childX + child.getOccupiedArea().getBBox().getWidth();
}
getOccupiedArea().getBBox().setWidth(width);
}
#location 17
#vulnerability type NULL_DEREFERENCE | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Test
public void imageTest02() throws IOException, InterruptedException {
String outFileName = destinationFolder + "imageTest02.pdf";
String cmpFileName = sourceFolder + "cmp_imageTest02.pdf";
FileOutputStream file = new FileOutputStream(outFileName);
PdfWriter writer = new PdfWriter(file);
PdfDocument pdfDoc = new PdfDocument(writer);
Document doc = new Document(pdfDoc);
PdfImageXObject xObject = new PdfImageXObject(pdfDoc, ImageFactory.getJpegImage(new File(sourceFolder+"Desert.jpg").toURI().toURL()));
Image image = new Image(xObject, 100);
Paragraph p = new Paragraph();
p.add(new Text("before image"));
p.add(image);
p.add(new Text("after image"));
doc.add(p);
doc.close();
Assert.assertNull(new CompareTool().compareByContent(outFileName, cmpFileName, destinationFolder, "diff"));
} | #vulnerable code
@Test
public void imageTest02() throws IOException, InterruptedException {
String outFileName = destinationFolder + "imageTest02.pdf";
String cmpFileName = sourceFolder + "cmp_imageTest02.pdf";
FileOutputStream file = new FileOutputStream(outFileName);
PdfWriter writer = new PdfWriter(file);
PdfDocument pdfDoc = new PdfDocument(writer);
Document doc = new Document(pdfDoc);
ByteArrayOutputStream buffer = new ByteArrayOutputStream();
int nRead;
FileInputStream is = new FileInputStream(sourceFolder+"Desert.jpg");
nRead = is.read();
while (nRead != -1){
buffer.write(nRead);
nRead = is.read();
}
PdfImageXObject xObject = new PdfImageXObject(pdfDoc, ImageFactory.getJpegImage(buffer.toByteArray()));
Image image = new Image(xObject, 100);
Paragraph p = new Paragraph();
p.add(new Text("before image"));
p.add(image);
p.add(new Text("after image"));
doc.add(p);
doc.close();
Assert.assertNull(new CompareTool().compareByContent(outFileName, cmpFileName, destinationFolder, "diff"));
}
#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 create1000PagesDocumentWithFullCompression() throws IOException, PdfException {
final String author = "Alexander Chingarev";
final String creator = "iText 6";
final String title = "Empty iText 6 Document";
FileOutputStream fos = new FileOutputStream(destinationFolder + "1000PagesDocumentWithFullCompression.pdf");
PdfWriter writer = new PdfWriter(fos);
writer.setFullCompression(true);
PdfDocument pdfDoc = new PdfDocument(writer);
pdfDoc.getInfo().setAuthor(author).
setCreator(creator).
setTitle(title);
for (int i = 0; i < 1000; i ++) {
PdfPage page = pdfDoc.addNewPage();
PdfCanvas canvas = new PdfCanvas(page.getContentStream());
canvas.rectangle(100, 100, 100, 100).fill();
page.flush();
}
pdfDoc.close();
com.itextpdf.text.pdf.PdfReader reader = new com.itextpdf.text.pdf.PdfReader(destinationFolder + "1000PagesDocumentWithFullCompression.pdf");
HashMap<String, String> info = reader.getInfo();
Assert.assertEquals(author, info.get("Author"));
Assert.assertEquals(creator, info.get("Creator"));
Assert.assertEquals(title, info.get("Title"));
PdfDictionary page = reader.getPageN(1);
Assert.assertEquals(com.itextpdf.text.pdf.PdfName.PAGE, page.get(com.itextpdf.text.pdf.PdfName.TYPE));
reader.close();
} | #vulnerable code
@Test
public void create1000PagesDocumentWithFullCompression() throws IOException, PdfException {
final String author = "Alexander Chingarev";
final String creator = "iText 6";
final String title = "Empty iText 6 Document";
FileOutputStream fos = new FileOutputStream(destinationFolder + "1000PagesDocumentWithFullCompression.pdf");
PdfWriter writer = new PdfWriter(new BufferedOutputStream(fos));
writer.setFullCompression(true);
PdfDocument pdfDoc = new PdfDocument(writer);
pdfDoc.getInfo().setAuthor(author).
setCreator(creator).
setTitle(title);
for (int i = 0; i < 1000; i ++) {
PdfPage page = pdfDoc.addNewPage();
PdfCanvas canvas = new PdfCanvas(page.getContentStream());
canvas.rectangle(100, 100, 100, 100).fill();
page.flush();
}
pdfDoc.close();
com.itextpdf.text.pdf.PdfReader reader = new com.itextpdf.text.pdf.PdfReader(destinationFolder + "1000PagesDocumentWithFullCompression.pdf");
HashMap<String, String> info = reader.getInfo();
Assert.assertEquals(author, info.get("Author"));
Assert.assertEquals(creator, info.get("Creator"));
Assert.assertEquals(title, info.get("Title"));
PdfDictionary page = reader.getPageN(1);
Assert.assertEquals(com.itextpdf.text.pdf.PdfName.PAGE, page.get(com.itextpdf.text.pdf.PdfName.TYPE));
reader.close();
}
#location 11
#vulnerability type RESOURCE_LEAK | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Override
public LayoutResult layout(LayoutContext layoutContext) {
LayoutArea area = layoutContext.getArea();
Rectangle layoutBox = area.getBBox();
occupiedArea = new LayoutArea(area.getPageNumber(), new Rectangle(layoutBox.getX(), layoutBox.getY() + layoutBox.getHeight(), 0, 0));
width = getPropertyAsFloat(Property.WIDTH);
Float angle = getPropertyAsFloat(Property.IMAGE_ROTATION_ANGLE);
PdfXObject xObject = ((Image) (getModelElement())).getXObject();
imageWidth = xObject.getWidth();
imageHeight = xObject.getHeight();
width = width == null ? imageWidth : width;
height = width / imageWidth * imageHeight;
fixedXPosition = getPropertyAsFloat(Property.X);
fixedYPosition = getPropertyAsFloat(Property.Y);
Float horizontalScaling = getPropertyAsFloat(Property.HORIZONTAL_SCALING);
Float verticalScaling = getPropertyAsFloat(Property.VERTICAL_SCALING);
AffineTransform t = new AffineTransform();
if (xObject instanceof PdfFormXObject && width != imageWidth) {
horizontalScaling *= width / imageWidth;
verticalScaling *= height / imageHeight;
}
if (horizontalScaling != 1) {
if (xObject instanceof PdfFormXObject) {
t.scale(horizontalScaling, 1);
}
width *= horizontalScaling;
}
if (verticalScaling != 1) {
if (xObject instanceof PdfFormXObject) {
t.scale(1, verticalScaling);
}
height *= verticalScaling;
}
float imageItselfScaledWidth = width;
float imageItselfScaledHeight = height;
if (angle != null) {
t.rotate(angle);
adjustPositionAfterRotation(angle);
}
getMatrix(t, imageItselfScaledWidth, imageItselfScaledHeight);
if (width > layoutBox.getWidth()){
return new LayoutResult(LayoutResult.NOTHING, occupiedArea, null, this);
}
if (height > layoutBox.getHeight()){
return new LayoutResult(LayoutResult.NOTHING, occupiedArea, null, this);
}
occupiedArea.getBBox().moveDown(height);
occupiedArea.getBBox().setHeight(height);
occupiedArea.getBBox().setWidth(width);
Float mx = getProperty(Property.X_DISTANCE);
Float my = getProperty(Property.Y_DISTANCE);
if (mx != null && my != null) {
translateImage(mx, my, t);
getMatrix(t, imageItselfScaledWidth, imageItselfScaledHeight);
}
if (fixedXPosition != null && fixedYPosition != null) {
occupiedArea.getBBox().setWidth(0);
occupiedArea.getBBox().setHeight(0);
}
return new LayoutResult(LayoutResult.FULL, occupiedArea, null, null);
} | #vulnerable code
@Override
public LayoutResult layout(LayoutContext layoutContext) {
LayoutArea area = layoutContext.getArea();
Rectangle layoutBox = area.getBBox();
occupiedArea = new LayoutArea(area.getPageNumber(), new Rectangle(layoutBox.getX(), layoutBox.getY() + layoutBox.getHeight(), 0, 0));
width = getPropertyAsFloat(Property.WIDTH);
Float angle = getPropertyAsFloat(Property.IMAGE_ROTATION_ANGLE);
PdfXObject xObject = ((Image) (getModelElement())).getXObject();
if (xObject instanceof PdfImageXObject) {
imageWidth = ((PdfImageXObject)xObject).getWidth();
imageHeight = ((PdfImageXObject)xObject).getHeight();
} else {
imageWidth = xObject.getPdfObject().getAsArray(PdfName.BBox).getAsFloat(2);
imageHeight = xObject.getPdfObject().getAsArray(PdfName.BBox).getAsFloat(3);
}
width = width == null ? imageWidth : width;
height = width / imageWidth * imageHeight;
fixedXPosition = getPropertyAsFloat(Property.X);
fixedYPosition = getPropertyAsFloat(Property.Y);
Float horizontalScaling = getPropertyAsFloat(Property.HORIZONTAL_SCALING);
Float verticalScaling = getPropertyAsFloat(Property.VERTICAL_SCALING);
AffineTransform t = new AffineTransform();
if (xObject instanceof PdfFormXObject && width != imageWidth) {
horizontalScaling *= width / imageWidth;
verticalScaling *= height / imageHeight;
}
if (horizontalScaling != 1) {
if (xObject instanceof PdfFormXObject) {
t.scale(horizontalScaling, 1);
}
width *= horizontalScaling;
}
if (verticalScaling != 1) {
if (xObject instanceof PdfFormXObject) {
t.scale(1, verticalScaling);
}
height *= verticalScaling;
}
float imageItselfScaledWidth = width;
float imageItselfScaledHeight = height;
if (angle != null) {
t.rotate(angle);
adjustPositionAfterRotation(angle);
}
getMatrix(t, imageItselfScaledWidth, imageItselfScaledHeight);
if (width > layoutBox.getWidth()){
return new LayoutResult(LayoutResult.NOTHING, occupiedArea, null, this);
}
if (height > layoutBox.getHeight()){
return new LayoutResult(LayoutResult.NOTHING, occupiedArea, null, this);
}
occupiedArea.getBBox().moveDown(height);
occupiedArea.getBBox().setHeight(height);
occupiedArea.getBBox().setWidth(width);
Float mx = getProperty(Property.X_DISTANCE);
Float my = getProperty(Property.Y_DISTANCE);
if (mx != null && my != null) {
translateImage(mx, my, t);
getMatrix(t, imageItselfScaledWidth, imageItselfScaledHeight);
}
if (fixedXPosition != null && fixedYPosition != null) {
occupiedArea.getBBox().setWidth(0);
occupiedArea.getBBox().setHeight(0);
}
return new LayoutResult(LayoutResult.FULL, occupiedArea, null, null);
}
#location 15
#vulnerability type NULL_DEREFERENCE | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Test
public void imageTest05() throws IOException, InterruptedException {
String outFileName = destinationFolder + "imageTest05.pdf";
String cmpFileName = sourceFolder + "cmp_imageTest05.pdf";
FileOutputStream file = new FileOutputStream(outFileName);
PdfWriter writer = new PdfWriter(file);
PdfDocument pdfDoc = new PdfDocument(writer);
Document doc = new Document(pdfDoc);
PdfImageXObject xObject = new PdfImageXObject(pdfDoc, ImageFactory.getJpegImage(new File(sourceFolder+"Desert.jpg").toURI().toURL()));
Image image = new Image(xObject, 100);
doc.add(new Paragraph(new Text("First Line")));
Paragraph p = new Paragraph();
p.add(image);
image.scale(1, 0.5f);
doc.add(p);
doc.add(new Paragraph(new Text("Second Line")));
doc.close();
Assert.assertNull(new CompareTool().compareByContent(outFileName, cmpFileName, destinationFolder, "diff"));
} | #vulnerable code
@Test
public void imageTest05() throws IOException, InterruptedException {
String outFileName = destinationFolder + "imageTest05.pdf";
String cmpFileName = sourceFolder + "cmp_imageTest05.pdf";
FileOutputStream file = new FileOutputStream(outFileName);
PdfWriter writer = new PdfWriter(file);
PdfDocument pdfDoc = new PdfDocument(writer);
Document doc = new Document(pdfDoc);
ByteArrayOutputStream buffer = new ByteArrayOutputStream();
int nRead;
FileInputStream is = new FileInputStream(sourceFolder+"Desert.jpg");
nRead = is.read();
while (nRead != -1){
buffer.write(nRead);
nRead = is.read();
}
PdfImageXObject xObject = new PdfImageXObject(pdfDoc, ImageFactory.getJpegImage(buffer.toByteArray()));
Image image = new Image(xObject, 100);
doc.add(new Paragraph(new Text("First Line")));
Paragraph p = new Paragraph();
p.add(image);
image.scale(1, 0.5f);
doc.add(p);
doc.add(new Paragraph(new Text("Second Line")));
doc.close();
Assert.assertNull(new CompareTool().compareByContent(outFileName, cmpFileName, destinationFolder, "diff"));
}
#location 25
#vulnerability type RESOURCE_LEAK | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
protected void buildResources(PdfDictionary dictionary) throws PdfException {
for (PdfName resourceType : dictionary.keySet()) {
if (nameToResource.get(resourceType) == null) {
nameToResource.put(resourceType, new HashMap<PdfName, PdfObject>());
}
PdfDictionary resources = dictionary.getAsDictionary(resourceType);
if (resources == null)
continue;
for (PdfName resourceName : resources.keySet()) {
PdfObject resource = resources.get(resourceName, false);
resourceToName.put(resource, resourceName);
nameToResource.get(resourceType).put(resourceName, resource);
}
}
Set<PdfName> names = getResourceNames();
fontNumber = getAvailableNumber(names, F);
imageNumber = getAvailableNumber(names, Im);
formNumber = getAvailableNumber(names, Fm);
egsNumber = getAvailableNumber(names, Gs);
propNumber = getAvailableNumber(names, Pr);
csNumber = getAvailableNumber(names, Cs);
} | #vulnerable code
protected void buildResources(PdfDictionary dictionary) throws PdfException {
for (PdfName resourceType : dictionary.keySet()) {
if (nameToResource.get(resourceType) == null) {
nameToResource.put(resourceType, new HashMap<PdfName, PdfObject>());
}
PdfDictionary resources = dictionary.getAsDictionary(resourceType);
for (PdfName resourceName : resources.keySet()) {
PdfObject resource = resources.get(resourceName, false);
resourceToName.put(resource, resourceName);
nameToResource.get(resourceType).put(resourceName, resource);
}
}
Set<PdfName> names = getResourceNames();
fontNumber = getAvailableNumber(names, F);
imageNumber = getAvailableNumber(names, Im);
formNumber = getAvailableNumber(names, Fm);
egsNumber = getAvailableNumber(names, Gs);
propNumber = getAvailableNumber(names, Pr);
csNumber = getAvailableNumber(names, Cs);
}
#location 7
#vulnerability type NULL_DEREFERENCE | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Override
public LayoutResult layout(LayoutContext layoutContext) {
LayoutArea area = layoutContext.getArea();
Rectangle layoutBox = area.getBBox();
occupiedArea = new LayoutArea(area.getPageNumber(), new Rectangle(layoutBox.getX(), layoutBox.getY() + layoutBox.getHeight(), 0, 0));
width = getPropertyAsFloat(Property.WIDTH);
Float angle = getPropertyAsFloat(Property.IMAGE_ROTATION_ANGLE);
PdfXObject xObject = ((Image) (getModelElement())).getXObject();
imageWidth = xObject.getWidth();
imageHeight = xObject.getHeight();
width = width == null ? imageWidth : width;
height = width / imageWidth * imageHeight;
fixedXPosition = getPropertyAsFloat(Property.X);
fixedYPosition = getPropertyAsFloat(Property.Y);
Float horizontalScaling = getPropertyAsFloat(Property.HORIZONTAL_SCALING);
Float verticalScaling = getPropertyAsFloat(Property.VERTICAL_SCALING);
AffineTransform t = new AffineTransform();
if (xObject instanceof PdfFormXObject && width != imageWidth) {
horizontalScaling *= width / imageWidth;
verticalScaling *= height / imageHeight;
}
if (horizontalScaling != 1) {
if (xObject instanceof PdfFormXObject) {
t.scale(horizontalScaling, 1);
}
width *= horizontalScaling;
}
if (verticalScaling != 1) {
if (xObject instanceof PdfFormXObject) {
t.scale(1, verticalScaling);
}
height *= verticalScaling;
}
float imageItselfScaledWidth = width;
float imageItselfScaledHeight = height;
if (angle != null) {
t.rotate(angle);
adjustPositionAfterRotation(angle);
}
getMatrix(t, imageItselfScaledWidth, imageItselfScaledHeight);
if (width > layoutBox.getWidth()){
return new LayoutResult(LayoutResult.NOTHING, occupiedArea, null, this);
}
if (height > layoutBox.getHeight()){
return new LayoutResult(LayoutResult.NOTHING, occupiedArea, null, this);
}
occupiedArea.getBBox().moveDown(height);
occupiedArea.getBBox().setHeight(height);
occupiedArea.getBBox().setWidth(width);
Float mx = getProperty(Property.X_DISTANCE);
Float my = getProperty(Property.Y_DISTANCE);
if (mx != null && my != null) {
translateImage(mx, my, t);
getMatrix(t, imageItselfScaledWidth, imageItselfScaledHeight);
}
if (fixedXPosition != null && fixedYPosition != null) {
occupiedArea.getBBox().setWidth(0);
occupiedArea.getBBox().setHeight(0);
}
return new LayoutResult(LayoutResult.FULL, occupiedArea, null, null);
} | #vulnerable code
@Override
public LayoutResult layout(LayoutContext layoutContext) {
LayoutArea area = layoutContext.getArea();
Rectangle layoutBox = area.getBBox();
occupiedArea = new LayoutArea(area.getPageNumber(), new Rectangle(layoutBox.getX(), layoutBox.getY() + layoutBox.getHeight(), 0, 0));
width = getPropertyAsFloat(Property.WIDTH);
Float angle = getPropertyAsFloat(Property.IMAGE_ROTATION_ANGLE);
PdfXObject xObject = ((Image) (getModelElement())).getXObject();
if (xObject instanceof PdfImageXObject) {
imageWidth = ((PdfImageXObject)xObject).getWidth();
imageHeight = ((PdfImageXObject)xObject).getHeight();
} else {
imageWidth = xObject.getPdfObject().getAsArray(PdfName.BBox).getAsFloat(2);
imageHeight = xObject.getPdfObject().getAsArray(PdfName.BBox).getAsFloat(3);
}
width = width == null ? imageWidth : width;
height = width / imageWidth * imageHeight;
fixedXPosition = getPropertyAsFloat(Property.X);
fixedYPosition = getPropertyAsFloat(Property.Y);
Float horizontalScaling = getPropertyAsFloat(Property.HORIZONTAL_SCALING);
Float verticalScaling = getPropertyAsFloat(Property.VERTICAL_SCALING);
AffineTransform t = new AffineTransform();
if (xObject instanceof PdfFormXObject && width != imageWidth) {
horizontalScaling *= width / imageWidth;
verticalScaling *= height / imageHeight;
}
if (horizontalScaling != 1) {
if (xObject instanceof PdfFormXObject) {
t.scale(horizontalScaling, 1);
}
width *= horizontalScaling;
}
if (verticalScaling != 1) {
if (xObject instanceof PdfFormXObject) {
t.scale(1, verticalScaling);
}
height *= verticalScaling;
}
float imageItselfScaledWidth = width;
float imageItselfScaledHeight = height;
if (angle != null) {
t.rotate(angle);
adjustPositionAfterRotation(angle);
}
getMatrix(t, imageItselfScaledWidth, imageItselfScaledHeight);
if (width > layoutBox.getWidth()){
return new LayoutResult(LayoutResult.NOTHING, occupiedArea, null, this);
}
if (height > layoutBox.getHeight()){
return new LayoutResult(LayoutResult.NOTHING, occupiedArea, null, this);
}
occupiedArea.getBBox().moveDown(height);
occupiedArea.getBBox().setHeight(height);
occupiedArea.getBBox().setWidth(width);
Float mx = getProperty(Property.X_DISTANCE);
Float my = getProperty(Property.Y_DISTANCE);
if (mx != null && my != null) {
translateImage(mx, my, t);
getMatrix(t, imageItselfScaledWidth, imageItselfScaledHeight);
}
if (fixedXPosition != null && fixedYPosition != null) {
occupiedArea.getBBox().setWidth(0);
occupiedArea.getBBox().setHeight(0);
}
return new LayoutResult(LayoutResult.FULL, occupiedArea, null, null);
}
#location 16
#vulnerability type NULL_DEREFERENCE | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Test
public void imageTest02() throws IOException, InterruptedException {
String outFileName = destinationFolder + "imageTest02.pdf";
String cmpFileName = sourceFolder + "cmp_imageTest02.pdf";
FileOutputStream file = new FileOutputStream(outFileName);
PdfWriter writer = new PdfWriter(file);
PdfDocument pdfDoc = new PdfDocument(writer);
Document doc = new Document(pdfDoc);
PdfImageXObject xObject = new PdfImageXObject(pdfDoc, ImageFactory.getJpegImage(new File(sourceFolder+"Desert.jpg").toURI().toURL()));
Image image = new Image(xObject, 100);
Paragraph p = new Paragraph();
p.add(new Text("before image"));
p.add(image);
p.add(new Text("after image"));
doc.add(p);
doc.close();
Assert.assertNull(new CompareTool().compareByContent(outFileName, cmpFileName, destinationFolder, "diff"));
} | #vulnerable code
@Test
public void imageTest02() throws IOException, InterruptedException {
String outFileName = destinationFolder + "imageTest02.pdf";
String cmpFileName = sourceFolder + "cmp_imageTest02.pdf";
FileOutputStream file = new FileOutputStream(outFileName);
PdfWriter writer = new PdfWriter(file);
PdfDocument pdfDoc = new PdfDocument(writer);
Document doc = new Document(pdfDoc);
ByteArrayOutputStream buffer = new ByteArrayOutputStream();
int nRead;
FileInputStream is = new FileInputStream(sourceFolder+"Desert.jpg");
nRead = is.read();
while (nRead != -1){
buffer.write(nRead);
nRead = is.read();
}
PdfImageXObject xObject = new PdfImageXObject(pdfDoc, ImageFactory.getJpegImage(buffer.toByteArray()));
Image image = new Image(xObject, 100);
Paragraph p = new Paragraph();
p.add(new Text("before image"));
p.add(image);
p.add(new Text("after image"));
doc.add(p);
doc.close();
Assert.assertNull(new CompareTool().compareByContent(outFileName, cmpFileName, destinationFolder, "diff"));
}
#location 23
#vulnerability type RESOURCE_LEAK | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
protected int writeXRefTable() throws IOException, PdfException {
int strtxref = currentPos;
if (fullCompression) {
PdfStream stream = new PdfStream(pdfDocument);
stream.put(PdfName.Type, PdfName.XRef);
stream.put(PdfName.Size, new PdfNumber(pdfDocument.getIndirects().size() + 1));
stream.put(PdfName.W, new PdfArray(new ArrayList<PdfObject>() {{
add(new PdfNumber(1));
add(new PdfNumber(4));
add(new PdfNumber(2));
}}));
stream.put(PdfName.Info, pdfDocument.trailer.getDocumentInfo());
stream.put(PdfName.Root, pdfDocument.trailer.getCatalog());
stream.getOutputStream().write(0);
stream.getOutputStream().write(intToBytes(0));
stream.getOutputStream().write(shortToBytes(0xFFFF));
for (PdfIndirectReference indirect : pdfDocument.getIndirects()) {
if (indirect.getObjectStreamNumber() == 0) {
stream.getOutputStream().write(1);
stream.getOutputStream().write(intToBytes(indirect.getOffset()));
stream.getOutputStream().write(shortToBytes(0));
} else {
stream.getOutputStream().write(2);
stream.getOutputStream().write(intToBytes(indirect.getObjectStreamNumber()));
stream.getOutputStream().write(shortToBytes(indirect.getIndex()));
}
}
stream.flush();
} else {
writeString("xref\n").
writeString("0 ").
writeInteger(pdfDocument.getIndirects().size() + 1).
writeString("\n0000000000 65535 f \n");
for (PdfIndirectReference indirect : pdfDocument.getIndirects()) {
writeString(objectOffsetFormatter.format(indirect.getOffset())).
writeBytes(endXRefEntry);
}
}
return strtxref;
} | #vulnerable code
protected int writeXRefTable() throws IOException, PdfException {
int strtxref = currentPos;
if (fullCompression) {
PdfStream stream = new PdfStream(pdfDocument);
stream.put(PdfName.Type, PdfName.XRef);
stream.put(PdfName.Size, new PdfNumber(pdfDocument.getIndirects().size() + 1));
stream.put(PdfName.W, new PdfArray(new ArrayList<PdfObject>() {{
add(new PdfNumber(1));
add(new PdfNumber(4));
add(new PdfNumber(2));
}}));
stream.put(PdfName.Info, pdfDocument.trailer.getDocumentInfo());
stream.put(PdfName.Root, pdfDocument.trailer.getCatalog());
stream.getOutputStream().write(0);
stream.getOutputStream().write(intToBytes(0));
stream.getOutputStream().write(shortToBytes(0xFFFF));
for (PdfIndirectReference indirect : pdfDocument.getIndirects()) {
if (indirect.getObjectStream() != null) {
stream.getOutputStream().write(2);
stream.getOutputStream().write(intToBytes(indirect.getObjectStream().getIndirectReference().getObjNr()));
stream.getOutputStream().write(shortToBytes(indirect.getOffset()));
} else {
stream.getOutputStream().write(1);
stream.getOutputStream().write(intToBytes(indirect.getOffset()));
stream.getOutputStream().write(shortToBytes(0));
}
}
stream.flush();
} else {
writeString("xref\n").
writeString("0 ").
writeInteger(pdfDocument.getIndirects().size() + 1).
writeString("\n0000000000 65535 f \n");
for (PdfIndirectReference indirect : pdfDocument.getIndirects()) {
writeString(objectOffsetFormatter.format(indirect.getOffset())).
writeBytes(endXRefEntry);
}
}
return strtxref;
}
#location 20
#vulnerability type NULL_DEREFERENCE | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Override
public LayoutResult layout(LayoutContext layoutContext) {
LayoutArea area = layoutContext.getArea();
Rectangle layoutBox = area.getBBox();
occupiedArea = new LayoutArea(area.getPageNumber(), new Rectangle(layoutBox.getX(), layoutBox.getY() + layoutBox.getHeight(), 0, 0));
width = getPropertyAsFloat(Property.WIDTH);
Float angle = getPropertyAsFloat(Property.IMAGE_ROTATION_ANGLE);
PdfXObject xObject = ((Image) (getModelElement())).getXObject();
imageWidth = xObject.getWidth();
imageHeight = xObject.getHeight();
width = width == null ? imageWidth : width;
height = width / imageWidth * imageHeight;
fixedXPosition = getPropertyAsFloat(Property.X);
fixedYPosition = getPropertyAsFloat(Property.Y);
Float horizontalScaling = getPropertyAsFloat(Property.HORIZONTAL_SCALING);
Float verticalScaling = getPropertyAsFloat(Property.VERTICAL_SCALING);
AffineTransform t = new AffineTransform();
if (xObject instanceof PdfFormXObject && width != imageWidth) {
horizontalScaling *= width / imageWidth;
verticalScaling *= height / imageHeight;
}
if (horizontalScaling != 1) {
if (xObject instanceof PdfFormXObject) {
t.scale(horizontalScaling, 1);
}
width *= horizontalScaling;
}
if (verticalScaling != 1) {
if (xObject instanceof PdfFormXObject) {
t.scale(1, verticalScaling);
}
height *= verticalScaling;
}
float imageItselfScaledWidth = width;
float imageItselfScaledHeight = height;
if (angle != null) {
t.rotate(angle);
adjustPositionAfterRotation(angle);
}
getMatrix(t, imageItselfScaledWidth, imageItselfScaledHeight);
if (width > layoutBox.getWidth()){
return new LayoutResult(LayoutResult.NOTHING, occupiedArea, null, this);
}
if (height > layoutBox.getHeight()){
return new LayoutResult(LayoutResult.NOTHING, occupiedArea, null, this);
}
occupiedArea.getBBox().moveDown(height);
occupiedArea.getBBox().setHeight(height);
occupiedArea.getBBox().setWidth(width);
Float mx = getProperty(Property.X_DISTANCE);
Float my = getProperty(Property.Y_DISTANCE);
if (mx != null && my != null) {
translateImage(mx, my, t);
getMatrix(t, imageItselfScaledWidth, imageItselfScaledHeight);
}
if (fixedXPosition != null && fixedYPosition != null) {
occupiedArea.getBBox().setWidth(0);
occupiedArea.getBBox().setHeight(0);
}
return new LayoutResult(LayoutResult.FULL, occupiedArea, null, null);
} | #vulnerable code
@Override
public LayoutResult layout(LayoutContext layoutContext) {
LayoutArea area = layoutContext.getArea();
Rectangle layoutBox = area.getBBox();
occupiedArea = new LayoutArea(area.getPageNumber(), new Rectangle(layoutBox.getX(), layoutBox.getY() + layoutBox.getHeight(), 0, 0));
width = getPropertyAsFloat(Property.WIDTH);
Float angle = getPropertyAsFloat(Property.IMAGE_ROTATION_ANGLE);
PdfXObject xObject = ((Image) (getModelElement())).getXObject();
if (xObject instanceof PdfImageXObject) {
imageWidth = ((PdfImageXObject)xObject).getWidth();
imageHeight = ((PdfImageXObject)xObject).getHeight();
} else {
imageWidth = xObject.getPdfObject().getAsArray(PdfName.BBox).getAsFloat(2);
imageHeight = xObject.getPdfObject().getAsArray(PdfName.BBox).getAsFloat(3);
}
width = width == null ? imageWidth : width;
height = width / imageWidth * imageHeight;
fixedXPosition = getPropertyAsFloat(Property.X);
fixedYPosition = getPropertyAsFloat(Property.Y);
Float horizontalScaling = getPropertyAsFloat(Property.HORIZONTAL_SCALING);
Float verticalScaling = getPropertyAsFloat(Property.VERTICAL_SCALING);
AffineTransform t = new AffineTransform();
if (xObject instanceof PdfFormXObject && width != imageWidth) {
horizontalScaling *= width / imageWidth;
verticalScaling *= height / imageHeight;
}
if (horizontalScaling != 1) {
if (xObject instanceof PdfFormXObject) {
t.scale(horizontalScaling, 1);
}
width *= horizontalScaling;
}
if (verticalScaling != 1) {
if (xObject instanceof PdfFormXObject) {
t.scale(1, verticalScaling);
}
height *= verticalScaling;
}
float imageItselfScaledWidth = width;
float imageItselfScaledHeight = height;
if (angle != null) {
t.rotate(angle);
adjustPositionAfterRotation(angle);
}
getMatrix(t, imageItselfScaledWidth, imageItselfScaledHeight);
if (width > layoutBox.getWidth()){
return new LayoutResult(LayoutResult.NOTHING, occupiedArea, null, this);
}
if (height > layoutBox.getHeight()){
return new LayoutResult(LayoutResult.NOTHING, occupiedArea, null, this);
}
occupiedArea.getBBox().moveDown(height);
occupiedArea.getBBox().setHeight(height);
occupiedArea.getBBox().setWidth(width);
Float mx = getProperty(Property.X_DISTANCE);
Float my = getProperty(Property.Y_DISTANCE);
if (mx != null && my != null) {
translateImage(mx, my, t);
getMatrix(t, imageItselfScaledWidth, imageItselfScaledHeight);
}
if (fixedXPosition != null && fixedYPosition != null) {
occupiedArea.getBBox().setWidth(0);
occupiedArea.getBBox().setHeight(0);
}
return new LayoutResult(LayoutResult.FULL, occupiedArea, null, null);
}
#location 16
#vulnerability type NULL_DEREFERENCE | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
public PdfFormXObject createFormXObjectWithBarcode(Color barColor, Color textColor) {
PdfFormXObject xObject = new PdfFormXObject(document, null);
Rectangle rect = placeBarcode(new PdfCanvas(xObject), barColor, textColor);
xObject.setBBox(rect.toPdfArray());
return xObject;
} | #vulnerable code
public PdfFormXObject createFormXObjectWithBarcode(Color barColor, Color textColor) {
PdfStream stream = new PdfStream(document);
PdfCanvas canvas = new PdfCanvas(stream, new PdfResources());
Rectangle rect = placeBarcode(canvas, barColor, textColor);
PdfFormXObject xObject = new PdfFormXObject(document, rect);
xObject.getPdfObject().getOutputStream().writeBytes(stream.getBytes());
return xObject;
}
#location 9
#vulnerability type RESOURCE_LEAK | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Test
public void create1000PagesDocument() throws IOException, PdfException {
final String author = "Alexander Chingarev";
final String creator = "iText 6";
final String title = "Empty iText 6 Document";
FileOutputStream fos = new FileOutputStream(destinationFolder + "1000PagesDocument.pdf");
PdfWriter writer = new PdfWriter(fos);
PdfDocument pdfDoc = new PdfDocument(writer);
pdfDoc.getInfo().setAuthor(author).
setCreator(creator).
setTitle(title);
for (int i = 0; i < 1000; i ++) {
PdfPage page = pdfDoc.addNewPage();
PdfCanvas canvas = new PdfCanvas(page.getContentStream());
canvas.rectangle(100, 100, 100, 100).fill();
page.flush();
}
pdfDoc.close();
com.itextpdf.text.pdf.PdfReader reader = new com.itextpdf.text.pdf.PdfReader(destinationFolder + "1000PagesDocument.pdf");
HashMap<String, String> info = reader.getInfo();
Assert.assertEquals(author, info.get("Author"));
Assert.assertEquals(creator, info.get("Creator"));
Assert.assertEquals(title, info.get("Title"));
PdfDictionary page = reader.getPageN(1);
Assert.assertEquals(com.itextpdf.text.pdf.PdfName.PAGE, page.get(com.itextpdf.text.pdf.PdfName.TYPE));
reader.close();
} | #vulnerable code
@Test
public void create1000PagesDocument() throws IOException, PdfException {
final String author = "Alexander Chingarev";
final String creator = "iText 6";
final String title = "Empty iText 6 Document";
FileOutputStream fos = new FileOutputStream(destinationFolder + "1000PagesDocument.pdf");
PdfWriter writer = new PdfWriter(fos);
PdfDocument pdfDoc = new PdfDocument(writer);
pdfDoc.getInfo().setAuthor(author).
setCreator(creator).
setTitle(title);
for (int i = 0; i < 1000; i ++) {
PdfPage page = pdfDoc.addNewPage();
PdfCanvas canvas = new PdfCanvas(page.getContentStream());
canvas.rectangle(100, 100, 100, 100).fill();
if (i % 2 == 0)
page.flush();
}
pdfDoc.close();
com.itextpdf.text.pdf.PdfReader reader = new com.itextpdf.text.pdf.PdfReader(destinationFolder + "1000PagesDocument.pdf");
HashMap<String, String> info = reader.getInfo();
Assert.assertEquals(author, info.get("Author"));
Assert.assertEquals(creator, info.get("Creator"));
Assert.assertEquals(title, info.get("Title"));
PdfDictionary page = reader.getPageN(1);
Assert.assertEquals(com.itextpdf.text.pdf.PdfName.PAGE, page.get(com.itextpdf.text.pdf.PdfName.TYPE));
reader.close();
}
#location 10
#vulnerability type RESOURCE_LEAK | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Test
public void imageTest04() throws IOException, InterruptedException {
String outFileName = destinationFolder + "imageTest04.pdf";
String cmpFileName = sourceFolder + "cmp_imageTest04.pdf";
FileOutputStream file = new FileOutputStream(outFileName);
PdfWriter writer = new PdfWriter(file);
PdfDocument pdfDoc = new PdfDocument(writer);
Document doc = new Document(pdfDoc);
PdfImageXObject xObject = new PdfImageXObject(pdfDoc, ImageFactory.getJpegImage(new File(sourceFolder+"Desert.jpg").toURI().toURL()));
Image image = new Image(xObject, 100);
Paragraph p = new Paragraph();
p.add(new Text("before image"));
p.add(image);
image.setRotateAngle(Math.PI/6);
p.add(new Text("after image"));
doc.add(p);
doc.close();
Assert.assertNull(new CompareTool().compareByContent(outFileName, cmpFileName, destinationFolder, "diff"));
} | #vulnerable code
@Test
public void imageTest04() throws IOException, InterruptedException {
String outFileName = destinationFolder + "imageTest04.pdf";
String cmpFileName = sourceFolder + "cmp_imageTest04.pdf";
FileOutputStream file = new FileOutputStream(outFileName);
PdfWriter writer = new PdfWriter(file);
PdfDocument pdfDoc = new PdfDocument(writer);
Document doc = new Document(pdfDoc);
ByteArrayOutputStream buffer = new ByteArrayOutputStream();
int nRead;
FileInputStream is = new FileInputStream(sourceFolder+"Desert.jpg");
nRead = is.read();
while (nRead != -1){
buffer.write(nRead);
nRead = is.read();
}
PdfImageXObject xObject = new PdfImageXObject(pdfDoc, ImageFactory.getJpegImage(buffer.toByteArray()));
Image image = new Image(xObject, 100);
Paragraph p = new Paragraph();
p.add(new Text("before image"));
p.add(image);
image.setRotateAngle(Math.PI/6);
p.add(new Text("after image"));
doc.add(p);
doc.close();
Assert.assertNull(new CompareTool().compareByContent(outFileName, cmpFileName, destinationFolder, "diff"));
}
#location 23
#vulnerability type RESOURCE_LEAK | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Test
public void imageTest01() throws IOException, InterruptedException {
String outFileName = destinationFolder + "imageTest01.pdf";
String cmpFileName = sourceFolder + "cmp_imageTest01.pdf";
FileOutputStream file = new FileOutputStream(outFileName);
PdfWriter writer = new PdfWriter(file);
PdfDocument pdfDoc = new PdfDocument(writer);
Document doc = new Document(pdfDoc);
PdfImageXObject xObject = new PdfImageXObject(pdfDoc, ImageFactory.getJpegImage(new File(sourceFolder+"Desert.jpg").toURI().toURL()));
Image image = new Image(xObject, 100);
doc.add(new Paragraph(new Text("First Line")));
Paragraph p = new Paragraph();
p.add(image);
doc.add(p);
doc.add(new Paragraph(new Text("Second Line")));
doc.close();
Assert.assertNull(new CompareTool().compareByContent(outFileName, cmpFileName, destinationFolder, "diff"));
} | #vulnerable code
@Test
public void imageTest01() throws IOException, InterruptedException {
String outFileName = destinationFolder + "imageTest01.pdf";
String cmpFileName = sourceFolder + "cmp_imageTest01.pdf";
FileOutputStream file = new FileOutputStream(outFileName);
PdfWriter writer = new PdfWriter(file);
PdfDocument pdfDoc = new PdfDocument(writer);
Document doc = new Document(pdfDoc);
ByteArrayOutputStream buffer = new ByteArrayOutputStream();
int nRead;
FileInputStream is = new FileInputStream(sourceFolder+"Desert.jpg");
nRead = is.read();
while (nRead != -1){
buffer.write(nRead);
nRead = is.read();
}
PdfImageXObject xObject = new PdfImageXObject(pdfDoc, ImageFactory.getJpegImage(buffer.toByteArray()));
Image image = new Image(xObject, 100);
doc.add(new Paragraph(new Text("First Line")));
Paragraph p = new Paragraph();
p.add(image);
doc.add(p);
doc.add(new Paragraph(new Text("Second Line")));
doc.close();
Assert.assertNull(new CompareTool().compareByContent(outFileName, cmpFileName, destinationFolder, "diff"));
}
#location 25
#vulnerability type RESOURCE_LEAK | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
public PdfObjectStream getObjectStream() throws IOException, PdfException {
if (!fullCompression)
return null;
if (objectStream == null) {
objectStream = new PdfObjectStream(pdfDocument);
}
if (objectStream.getSize() == PdfObjectStream.maxObjStreamSize) {
objectStream.flush();
objectStream = new PdfObjectStream(pdfDocument);
}
return objectStream;
} | #vulnerable code
public PdfObjectStream getObjectStream() throws IOException, PdfException {
if (!fullCompression)
return null;
if (objectStream == null) {
objectStream = new PdfObjectStream(pdfDocument);
}
if (objectStream.getSize() == PdfObjectStream.maxObjStreamSize) {
PdfObjectStream oldObjStream = objectStream;
objectStream.flush();
objectStream = new PdfObjectStream(pdfDocument);
objectStream.put(PdfName.Extends, oldObjStream);
}
return objectStream;
}
#location 11
#vulnerability type RESOURCE_LEAK | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Test
public void imageTest05() throws IOException, InterruptedException {
String outFileName = destinationFolder + "imageTest05.pdf";
String cmpFileName = sourceFolder + "cmp_imageTest05.pdf";
FileOutputStream file = new FileOutputStream(outFileName);
PdfWriter writer = new PdfWriter(file);
PdfDocument pdfDoc = new PdfDocument(writer);
Document doc = new Document(pdfDoc);
PdfImageXObject xObject = new PdfImageXObject(ImageFactory.getImage(sourceFolder + "Desert.jpg"));
Image image = new Image(xObject, 100);
doc.add(new Paragraph(new Text("First Line")));
Paragraph p = new Paragraph();
p.add(image);
image.scale(1, 0.5f);
doc.add(p);
doc.add(new Paragraph(new Text("Second Line")));
doc.close();
Assert.assertNull(new CompareTool().compareByContent(outFileName, cmpFileName, destinationFolder, "diff"));
} | #vulnerable code
@Test
public void imageTest05() throws IOException, InterruptedException {
String outFileName = destinationFolder + "imageTest05.pdf";
String cmpFileName = sourceFolder + "cmp_imageTest05.pdf";
FileOutputStream file = new FileOutputStream(outFileName);
PdfWriter writer = new PdfWriter(file);
PdfDocument pdfDoc = new PdfDocument(writer);
Document doc = new Document(pdfDoc);
PdfImageXObject xObject = new PdfImageXObject(ImageFactory.getJpegImage(new File(sourceFolder+"Desert.jpg").toURI().toURL()));
Image image = new Image(xObject, 100);
doc.add(new Paragraph(new Text("First Line")));
Paragraph p = new Paragraph();
p.add(image);
image.scale(1, 0.5f);
doc.add(p);
doc.add(new Paragraph(new Text("Second Line")));
doc.close();
Assert.assertNull(new CompareTool().compareByContent(outFileName, cmpFileName, destinationFolder, "diff"));
}
#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 imageTest04() throws IOException, InterruptedException {
String outFileName = destinationFolder + "imageTest04.pdf";
String cmpFileName = sourceFolder + "cmp_imageTest04.pdf";
FileOutputStream file = new FileOutputStream(outFileName);
PdfWriter writer = new PdfWriter(file);
PdfDocument pdfDoc = new PdfDocument(writer);
Document doc = new Document(pdfDoc);
PdfImageXObject xObject = new PdfImageXObject(pdfDoc, ImageFactory.getJpegImage(new File(sourceFolder+"Desert.jpg").toURI().toURL()));
Image image = new Image(xObject, 100);
Paragraph p = new Paragraph();
p.add(new Text("before image"));
p.add(image);
image.setRotateAngle(Math.PI/6);
p.add(new Text("after image"));
doc.add(p);
doc.close();
Assert.assertNull(new CompareTool().compareByContent(outFileName, cmpFileName, destinationFolder, "diff"));
} | #vulnerable code
@Test
public void imageTest04() throws IOException, InterruptedException {
String outFileName = destinationFolder + "imageTest04.pdf";
String cmpFileName = sourceFolder + "cmp_imageTest04.pdf";
FileOutputStream file = new FileOutputStream(outFileName);
PdfWriter writer = new PdfWriter(file);
PdfDocument pdfDoc = new PdfDocument(writer);
Document doc = new Document(pdfDoc);
ByteArrayOutputStream buffer = new ByteArrayOutputStream();
int nRead;
FileInputStream is = new FileInputStream(sourceFolder+"Desert.jpg");
nRead = is.read();
while (nRead != -1){
buffer.write(nRead);
nRead = is.read();
}
PdfImageXObject xObject = new PdfImageXObject(pdfDoc, ImageFactory.getJpegImage(buffer.toByteArray()));
Image image = new Image(xObject, 100);
Paragraph p = new Paragraph();
p.add(new Text("before image"));
p.add(image);
image.setRotateAngle(Math.PI/6);
p.add(new Text("after image"));
doc.add(p);
doc.close();
Assert.assertNull(new CompareTool().compareByContent(outFileName, cmpFileName, destinationFolder, "diff"));
}
#location 25
#vulnerability type RESOURCE_LEAK | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Override
public void addChild(IRenderer renderer) {
super.addChild(renderer);
if (currentArea == null) {
currentArea = getNextArea();
// try {
// new PdfCanvas(document.getPdfDocument().getPage(currentArea.getPageNumber())).rectangle(currentArea.getBBox()).stroke();
// } catch (Exception exc) {}
}
if (childRenderers.size() != 0 && childRenderers.get(childRenderers.size() - 1) == renderer) {
List<IRenderer> resultRenderers = new ArrayList<>();
LayoutResult result = null;
LayoutArea storedArea = null;
LayoutArea nextStoredArea = null;
while (renderer != null && (result = renderer.layout(new LayoutContext(currentArea.clone()))).getStatus() != LayoutResult.FULL) {
if (result.getStatus() == LayoutResult.PARTIAL) {
resultRenderers.add(result.getSplitRenderer());
if (nextStoredArea != null){
currentArea = nextStoredArea;
currentPageNumber = nextStoredArea.getPageNumber();
nextStoredArea = null;
} else {
getNextArea();
}
} else if (result.getStatus() == LayoutResult.NOTHING) {
if (currentArea.isEmptyArea() && !(renderer instanceof AreaBreakRenderer)){
Logger logger = LoggerFactory.getLogger(DocumentRenderer.class);
logger.warn("Element doesn't fit current area. KeepTogether property will be ignored.");
result.getOverflowRenderer().getModelElement().setProperty(Property.KEEP_TOGETHER, false);
renderer = result.getOverflowRenderer();
if (storedArea != null){
nextStoredArea = currentArea;
currentArea = storedArea;
currentPageNumber = storedArea.getPageNumber();
}
continue;
}
storedArea = currentArea;
if (result.getNewPageSize() != null)
getNextPageArea(result.getNewPageSize());
else {
getNextArea();
}
}
renderer = result.getOverflowRenderer();
}
assert result != null;
currentArea.getBBox().setHeight(currentArea.getBBox().getHeight() - result.getOccupiedArea().getBBox().getHeight());
currentArea.setEmptyArea(false);
if (renderer != null)
resultRenderers.add(renderer);
for (IRenderer resultRenderer : resultRenderers) {
alignChildHorizontally(resultRenderer, currentArea.getBBox().getWidth());
}
// TODO flush by page, not by elements?
if (immediateFlush) {
for (IRenderer resultRenderer : resultRenderers) {
flushSingleRenderer(resultRenderer);
}
}
childRenderers.remove(childRenderers.size() - 1);
childRenderers.addAll(resultRenderers);
} else {
Integer positionedPageNumber = renderer.getProperty(Property.PAGE_NUMBER);
if (positionedPageNumber == null)
positionedPageNumber = currentPageNumber;
renderer.layout(new LayoutContext(new LayoutArea(positionedPageNumber, currentArea.getBBox().clone())));
// TODO flush by page, not by elements?
if (immediateFlush) {
flushSingleRenderer(renderer);
}
}
} | #vulnerable code
@Override
public void addChild(IRenderer renderer) {
super.addChild(renderer);
if (currentArea == null) {
currentArea = getNextArea();
// try {
// new PdfCanvas(document.getPdfDocument().getPage(currentArea.getPageNumber())).rectangle(currentArea.getBBox()).stroke();
// } catch (Exception exc) {}
}
if (childRenderers.size() != 0 && childRenderers.get(childRenderers.size() - 1) == renderer) {
List<IRenderer> resultRenderers = new ArrayList<>();
LayoutResult result = null;
LayoutArea storedArea = null;
LayoutArea nextStoredArea = null;
while (renderer != null && (result = renderer.layout(new LayoutContext(currentArea.clone()))).getStatus() != LayoutResult.FULL) {
if (result.getStatus() == LayoutResult.PARTIAL) {
resultRenderers.add(result.getSplitRenderer());
if (nextStoredArea != null){
currentArea = nextStoredArea;
currentPageNumber = nextStoredArea.getPageNumber();
nextStoredArea = null;
} else {
getNextArea();
}
} else if (result.getStatus() == LayoutResult.NOTHING) {
if (currentArea.isEmptyArea() && !(renderer instanceof AreaBreakRenderer)){
Logger logger = LoggerFactory.getLogger(DocumentRenderer.class);
logger.warn("Element doesn't fit current area. KeepTogether property will be ignored.");
result.getOverflowRenderer().getModelElement().setProperty(Property.KEEP_TOGETHER, false);
renderer = result.getOverflowRenderer();
if (storedArea != null){
nextStoredArea = currentArea;
currentArea = storedArea;
currentPageNumber = storedArea.getPageNumber();
}
continue;
}
storedArea = currentArea;
if (result.getNewPageSize() != null)
getNextPageArea(result.getNewPageSize());
else {
getNextArea();
}
}
renderer = result.getOverflowRenderer();
}
currentArea.getBBox().setHeight(currentArea.getBBox().getHeight() - result.getOccupiedArea().getBBox().getHeight());
currentArea.setEmptyArea(false);
if (renderer != null)
resultRenderers.add(renderer);
for (IRenderer resultRenderer : resultRenderers) {
alignChildHorizontally(resultRenderer, currentArea.getBBox().getWidth());
}
// TODO flush by page, not by elements?
if (immediateFlush) {
for (IRenderer resultRenderer : resultRenderers) {
flushSingleRenderer(resultRenderer);
}
}
childRenderers.remove(childRenderers.size() - 1);
childRenderers.addAll(resultRenderers);
} else {
Integer positionedPageNumber = renderer.getProperty(Property.PAGE_NUMBER);
if (positionedPageNumber == null)
positionedPageNumber = currentPageNumber;
renderer.layout(new LayoutContext(new LayoutArea(positionedPageNumber, currentArea.getBBox().clone())));
// TODO flush by page, not by elements?
if (immediateFlush) {
flushSingleRenderer(renderer);
}
}
}
#location 51
#vulnerability type NULL_DEREFERENCE | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
public OutputStream writeInteger(int value) throws IOException {
writeInteger(value, 8);
return this;
} | #vulnerable code
public OutputStream writeInteger(int value) throws IOException {
write(getIsoBytes(String.valueOf(value)));
return this;
}
#location 2
#vulnerability type NULL_DEREFERENCE | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Override
public LayoutResult layout(LayoutContext layoutContext) {
LayoutArea area = layoutContext.getArea();
Rectangle layoutBox = area.getBBox();
occupiedArea = new LayoutArea(area.getPageNumber(), new Rectangle(layoutBox.getX(), layoutBox.getY() + layoutBox.getHeight(), 0, 0));
width = getPropertyAsFloat(Property.WIDTH);
Float angle = getPropertyAsFloat(Property.IMAGE_ROTATION_ANGLE);
PdfXObject xObject = ((Image) (getModelElement())).getXObject();
imageWidth = xObject.getWidth();
imageHeight = xObject.getHeight();
width = width == null ? imageWidth : width;
height = width / imageWidth * imageHeight;
fixedXPosition = getPropertyAsFloat(Property.X);
fixedYPosition = getPropertyAsFloat(Property.Y);
Float horizontalScaling = getPropertyAsFloat(Property.HORIZONTAL_SCALING);
Float verticalScaling = getPropertyAsFloat(Property.VERTICAL_SCALING);
AffineTransform t = new AffineTransform();
if (xObject instanceof PdfFormXObject && width != imageWidth) {
horizontalScaling *= width / imageWidth;
verticalScaling *= height / imageHeight;
}
if (horizontalScaling != 1) {
if (xObject instanceof PdfFormXObject) {
t.scale(horizontalScaling, 1);
}
width *= horizontalScaling;
}
if (verticalScaling != 1) {
if (xObject instanceof PdfFormXObject) {
t.scale(1, verticalScaling);
}
height *= verticalScaling;
}
float imageItselfScaledWidth = width;
float imageItselfScaledHeight = height;
if (angle != null) {
t.rotate(angle);
adjustPositionAfterRotation(angle);
}
getMatrix(t, imageItselfScaledWidth, imageItselfScaledHeight);
if (width > layoutBox.getWidth()){
return new LayoutResult(LayoutResult.NOTHING, occupiedArea, null, this);
}
if (height > layoutBox.getHeight()){
return new LayoutResult(LayoutResult.NOTHING, occupiedArea, null, this);
}
occupiedArea.getBBox().moveDown(height);
occupiedArea.getBBox().setHeight(height);
occupiedArea.getBBox().setWidth(width);
Float mx = getProperty(Property.X_DISTANCE);
Float my = getProperty(Property.Y_DISTANCE);
if (mx != null && my != null) {
translateImage(mx, my, t);
getMatrix(t, imageItselfScaledWidth, imageItselfScaledHeight);
}
if (fixedXPosition != null && fixedYPosition != null) {
occupiedArea.getBBox().setWidth(0);
occupiedArea.getBBox().setHeight(0);
}
return new LayoutResult(LayoutResult.FULL, occupiedArea, null, null);
} | #vulnerable code
@Override
public LayoutResult layout(LayoutContext layoutContext) {
LayoutArea area = layoutContext.getArea();
Rectangle layoutBox = area.getBBox();
occupiedArea = new LayoutArea(area.getPageNumber(), new Rectangle(layoutBox.getX(), layoutBox.getY() + layoutBox.getHeight(), 0, 0));
width = getPropertyAsFloat(Property.WIDTH);
Float angle = getPropertyAsFloat(Property.IMAGE_ROTATION_ANGLE);
PdfXObject xObject = ((Image) (getModelElement())).getXObject();
if (xObject instanceof PdfImageXObject) {
imageWidth = ((PdfImageXObject)xObject).getWidth();
imageHeight = ((PdfImageXObject)xObject).getHeight();
} else {
imageWidth = xObject.getPdfObject().getAsArray(PdfName.BBox).getAsFloat(2);
imageHeight = xObject.getPdfObject().getAsArray(PdfName.BBox).getAsFloat(3);
}
width = width == null ? imageWidth : width;
height = width / imageWidth * imageHeight;
fixedXPosition = getPropertyAsFloat(Property.X);
fixedYPosition = getPropertyAsFloat(Property.Y);
Float horizontalScaling = getPropertyAsFloat(Property.HORIZONTAL_SCALING);
Float verticalScaling = getPropertyAsFloat(Property.VERTICAL_SCALING);
AffineTransform t = new AffineTransform();
if (xObject instanceof PdfFormXObject && width != imageWidth) {
horizontalScaling *= width / imageWidth;
verticalScaling *= height / imageHeight;
}
if (horizontalScaling != 1) {
if (xObject instanceof PdfFormXObject) {
t.scale(horizontalScaling, 1);
}
width *= horizontalScaling;
}
if (verticalScaling != 1) {
if (xObject instanceof PdfFormXObject) {
t.scale(1, verticalScaling);
}
height *= verticalScaling;
}
float imageItselfScaledWidth = width;
float imageItselfScaledHeight = height;
if (angle != null) {
t.rotate(angle);
adjustPositionAfterRotation(angle);
}
getMatrix(t, imageItselfScaledWidth, imageItselfScaledHeight);
if (width > layoutBox.getWidth()){
return new LayoutResult(LayoutResult.NOTHING, occupiedArea, null, this);
}
if (height > layoutBox.getHeight()){
return new LayoutResult(LayoutResult.NOTHING, occupiedArea, null, this);
}
occupiedArea.getBBox().moveDown(height);
occupiedArea.getBBox().setHeight(height);
occupiedArea.getBBox().setWidth(width);
Float mx = getProperty(Property.X_DISTANCE);
Float my = getProperty(Property.Y_DISTANCE);
if (mx != null && my != null) {
translateImage(mx, my, t);
getMatrix(t, imageItselfScaledWidth, imageItselfScaledHeight);
}
if (fixedXPosition != null && fixedYPosition != null) {
occupiedArea.getBBox().setWidth(0);
occupiedArea.getBBox().setHeight(0);
}
return new LayoutResult(LayoutResult.FULL, occupiedArea, null, null);
}
#location 15
#vulnerability type NULL_DEREFERENCE | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Test
public void imageTest06() throws IOException, InterruptedException {
String outFileName = destinationFolder + "imageTest06.pdf";
String cmpFileName = sourceFolder + "cmp_imageTest06.pdf";
FileOutputStream file = new FileOutputStream(outFileName);
PdfWriter writer = new PdfWriter(file);
PdfDocument pdfDoc = new PdfDocument(writer);
Document doc = new Document(pdfDoc);
PdfImageXObject xObject = new PdfImageXObject(ImageFactory.getImage(sourceFolder + "Desert.jpg"));
Image image = new Image(xObject, 100);
doc.add(new Paragraph(new Text("First Line")));
Paragraph p = new Paragraph();
p.add(image);
image.setTranslationDistance(100, -100);
doc.add(p);
doc.add(new Paragraph(new Text("Second Line")));
doc.close();
Assert.assertNull(new CompareTool().compareByContent(outFileName, cmpFileName, destinationFolder, "diff"));
} | #vulnerable code
@Test
public void imageTest06() throws IOException, InterruptedException {
String outFileName = destinationFolder + "imageTest06.pdf";
String cmpFileName = sourceFolder + "cmp_imageTest06.pdf";
FileOutputStream file = new FileOutputStream(outFileName);
PdfWriter writer = new PdfWriter(file);
PdfDocument pdfDoc = new PdfDocument(writer);
Document doc = new Document(pdfDoc);
PdfImageXObject xObject = new PdfImageXObject(ImageFactory.getJpegImage(new File(sourceFolder+"Desert.jpg").toURI().toURL()));
Image image = new Image(xObject, 100);
doc.add(new Paragraph(new Text("First Line")));
Paragraph p = new Paragraph();
p.add(image);
image.setTranslationDistance(100, -100);
doc.add(p);
doc.add(new Paragraph(new Text("Second Line")));
doc.close();
Assert.assertNull(new CompareTool().compareByContent(outFileName, cmpFileName, destinationFolder, "diff"));
}
#location 28
#vulnerability type RESOURCE_LEAK | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
public static Boolean isProjectPermsPassByProjectId(Integer projectId)
{
List<Integer> projectIDList = ShiroUtils.getProjectIdForRoles();
Boolean result = false;
/*超级管理员权限*/
if("admin".equals(ShiroUtils.getLoginName())){
return true;
}
for(Integer pId:projectIDList){
if(projectId==pId){
result = true;
break;
}
}
if(!result){
log.warn("项目访问权限不通过,被访项目ID:{},用户项目权限列表:{}",projectId,JSON.toJSONString(projectIDList));
}
return result;
} | #vulnerable code
public static Boolean isProjectPermsPassByProjectId(Integer projectId)
{
List<Integer> projectIDList = ShiroUtils.getSysUser().getProjectIdForRoles();
Boolean result = false;
/*超级管理员权限*/
if("admin".equals(ShiroUtils.getLoginName())){
return true;
}
for(Integer pId:projectIDList){
if(projectId==pId){
result = true;
break;
}
}
return result;
}
#location 3
#vulnerability type NULL_DEREFERENCE | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
public static Boolean isProjectPermsPassByProjectId(Integer projectId)
{
List<Integer> projectIDList = ShiroUtils.getProjectIdForRoles();
Boolean result = false;
/*超级管理员权限*/
if("admin".equals(ShiroUtils.getLoginName())){
return true;
}
for(Integer pId:projectIDList){
if(projectId==pId){
result = true;
break;
}
}
if(!result){
log.warn("项目访问权限不通过,被访项目ID:{},用户项目权限列表:{}",projectId,JSON.toJSONString(projectIDList));
}
return result;
} | #vulnerable code
public static Boolean isProjectPermsPassByProjectId(Integer projectId)
{
List<Integer> projectIDList = ShiroUtils.getSysUser().getProjectIdForRoles();
Boolean result = false;
/*超级管理员权限*/
if("admin".equals(ShiroUtils.getLoginName())){
return true;
}
for(Integer pId:projectIDList){
if(projectId==pId){
result = true;
break;
}
}
return result;
}
#location 11
#vulnerability type NULL_DEREFERENCE | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Override
public void execute(JobExecutionContext context)
throws JobExecutionException {
try {
String name = context.getJobDetail().getName();
if(name.indexOf(PublicConst.JOBTASKNAMETYPE)>-1){
TestJobs job = new TestJobs();
String id=name.substring(0,name.indexOf(PublicConst.JOBTASKNAMETYPE));
System.out.println("执行命令中。。。");
for (int i = 0; i < QueueListener.list.size(); i++) {
job = QueueListener.list.get(i);
if (id.equals("" + job.getId())) {
break;
}else{
job=null;
}
}
if(null!=job){
toRunTask(job.getPlanproj(), job.getProjectid(),job.getId(),job.getTaskName(),job.getClientip(),job.getClientpath());
System.out.println("调用程序结束。。。");
}else{
System.out.println("没有定时任务需要启动。。。");
}
}else if(name.indexOf(PublicConst.JOBCLIENTNAMETYPE)>-1){
TestClient tc = new TestClient();
String id=name.substring(0,name.indexOf(PublicConst.JOBCLIENTNAMETYPE));
for (int i = 0; i < QueueListener.listen_Clientlist.size(); i++) {
tc = QueueListener.listen_Clientlist.get(i);
if (id.equals("" + tc.getId())) {
if(null!=tc){
String clientip=tc.getClientip();
try{
Map<String, Object> params = new HashMap<String, Object>(0);
String result=HttpRequest.httpClientGet("http://"+clientip+":"+PublicConst.CLIENTPORT+"/getclientstatus", params);
if("success".equals(result)){
if(tc.getStatus()!=0){
tc.setStatus(0);
QueueListener.listen_Clientlist.set(i, tc);
Query query = session.createQuery("update TestClient t set t.status =0 where id="+tc.getId());
query.executeUpdate();
}
}else{
log.error("【IP:"+tc.getClientip()+"】检查客户端异常!");
if(tc.getStatus()!=1){
tc.setStatus(1);
QueueListener.listen_Clientlist.set(i, tc);
Query query = session.createQuery("update TestClient t set t.status =1 where id="+tc.getId());
query.executeUpdate();
log.error("【IP:"+tc.getClientip()+"】客户端异常,修改客户端状态!");
}
}
}catch (RuntimeException e) {
log.error(e);
log.error("【IP:"+tc.getClientip()+"】检查客户端异常(RemoteException)!");
if(tc.getStatus()!=1){
tc.setStatus(1);
QueueListener.listen_Clientlist.set(i, tc);
Query query = session.createQuery("update TestClient t set t.status =1 where id="+tc.getId());
query.executeUpdate();
log.error("【IP:"+tc.getClientip()+"】客户端异常(RemoteException),修改客户端状态!");
}
break;
}
}
break;
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
} | #vulnerable code
@Override
public void execute(JobExecutionContext context)
throws JobExecutionException {
try {
String name = context.getJobDetail().getName();
if(name.indexOf(PublicConst.JOBTASKNAMETYPE)>-1){
TestJobs job = new TestJobs();
String id=name.substring(0,name.indexOf(PublicConst.JOBTASKNAMETYPE));
System.out.println("执行命令中。。。");
for (int i = 0; i < QueueListener.list.size(); i++) {
job = QueueListener.list.get(i);
if (id.equals("" + job.getId())) {
break;
}else{
job=null;
}
}
if(null!=job){
toRunTask(job.getPlanproj(), job.getId(),job.getTaskName(),job.getClientip(),job.getClientpath());
System.out.println("调用程序结束。。。");
}else{
System.out.println("没有定时任务需要启动。。。");
}
}else if(name.indexOf(PublicConst.JOBCLIENTNAMETYPE)>-1){
TestClient tc = new TestClient();
String id=name.substring(0,name.indexOf(PublicConst.JOBCLIENTNAMETYPE));
for (int i = 0; i < QueueListener.listen_Clientlist.size(); i++) {
tc = QueueListener.listen_Clientlist.get(i);
if (id.equals("" + tc.getId())) {
if(null!=tc){
String clientip=tc.getClientip();
try{
Map<String, Object> params = new HashMap<String, Object>(0);
String result=HttpRequest.httpClientGet("http://"+clientip+":"+PublicConst.CLIENTPORT+"/getclientstatus", params);
if("success".equals(result)){
if(tc.getStatus()!=0){
tc.setStatus(0);
QueueListener.listen_Clientlist.set(i, tc);
Query query = session.createQuery("update TestClient t set t.status =0 where id="+tc.getId());
query.executeUpdate();
}
}else{
log.error("【IP:"+tc.getClientip()+"】检查客户端异常!");
if(tc.getStatus()!=1){
tc.setStatus(1);
QueueListener.listen_Clientlist.set(i, tc);
Query query = session.createQuery("update TestClient t set t.status =1 where id="+tc.getId());
query.executeUpdate();
log.error("【IP:"+tc.getClientip()+"】客户端异常,修改客户端状态!");
}
}
}catch (RuntimeException e) {
log.error(e);
log.error("【IP:"+tc.getClientip()+"】检查客户端异常(RemoteException)!");
if(tc.getStatus()!=1){
tc.setStatus(1);
QueueListener.listen_Clientlist.set(i, tc);
Query query = session.createQuery("update TestClient t set t.status =1 where id="+tc.getId());
query.executeUpdate();
log.error("【IP:"+tc.getClientip()+"】客户端异常(RemoteException),修改客户端状态!");
}
break;
}
}
break;
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
#location 20
#vulnerability type NULL_DEREFERENCE | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
public void login() {
try {
//1 uuid
String uuid = wechatHttpService.getUUID();
cacheService.setUuid(uuid);
logger.info("[1] uuid completed");
//2 qr
byte[] qrData = wechatHttpService.getQR(uuid);
ByteArrayInputStream stream = new ByteArrayInputStream(qrData);
String qrUrl = QRCodeUtils.decode(stream);
stream.close();
String qr = QRCodeUtils.generateQR(qrUrl, 40, 40);
System.out.println(qr);
logger.info("[2] qrcode completed");
//3 login
LoginResult loginResponse = null;
while (true) {
loginResponse = wechatHttpService.login(uuid);
if (LoginCode.SUCCESS.getCode().equals(loginResponse.getCode())) {
if (loginResponse.getHostUrl() == null) {
throw new WechatException("hostUrl can't be found");
}
if (loginResponse.getRedirectUrl() == null) {
throw new WechatException("redirectUrl can't be found");
}
cacheService.setHostUrl(loginResponse.getHostUrl());
cacheService.setSyncUrl(loginResponse.getHostUrl().replaceFirst("^https://", "https://webpush."));
cacheService.setFileUrl(loginResponse.getHostUrl().replaceFirst("^https://", "https://file."));
break;
} else {
logger.info("[*] login status = " + loginResponse.getCode());
}
}
logger.info("[3] login completed");
//4 redirect login
Token token = wechatHttpService.redirectLogin(loginResponse.getRedirectUrl());
if (token.getRet() == 0) {
cacheService.setPassTicket(token.getPass_ticket());
cacheService.setsKey(token.getSkey());
cacheService.setSid(token.getWxsid());
cacheService.setUin(token.getWxuin());
BaseRequest baseRequest = new BaseRequest();
baseRequest.setUin(cacheService.getUin());
baseRequest.setSid(cacheService.getSid());
baseRequest.setSkey(cacheService.getsKey());
String rndDeviceId = "e" + String.valueOf(new Random().nextLong()).substring(1, 16);
baseRequest.setDeviceID(rndDeviceId);
cacheService.setBaseRequest(baseRequest);
} else {
throw new WechatException("token ret = " + token.getRet());
}
logger.info("[4] redirect completed");
//5 init
InitResponse initResponse = wechatHttpService.init(cacheService.getHostUrl(), cacheService.getBaseRequest(), cacheService.getPassTicket());
if (!WechatUtils.checkBaseResponse(initResponse.getBaseResponse())) {
throw new WechatException("initResponse ret = " + initResponse.getBaseResponse().getRet());
}
cacheService.setSyncKey(initResponse.getSyncKey());
cacheService.setOwner(initResponse.getUser());
logger.info("[5] init completed");
//6 status notify
StatusNotifyResponse statusNotifyResponse =
wechatHttpService.statusNotify(cacheService.getHostUrl(),
cacheService.getPassTicket(),
cacheService.getBaseRequest(),
cacheService.getOwner().getUserName(), 3);
if (!WechatUtils.checkBaseResponse(statusNotifyResponse.getBaseResponse())) {
throw new WechatException("statusNotifyResponse ret = " + statusNotifyResponse.getBaseResponse().getRet());
}
logger.info("[6] status notify completed");
//7 get contact
long seq = 0;
do {
GetContactResponse getContactResponse = wechatHttpService.getContact(cacheService.getHostUrl(), cacheService.getBaseRequest(), seq);
if (!WechatUtils.checkBaseResponse(getContactResponse.getBaseResponse())) {
throw new WechatException("getContactResponse ret = " + getContactResponse.getBaseResponse().getRet());
} else {
logger.info("[*] getContactResponse seq = " + getContactResponse.getSeq());
logger.info("[*] getContactResponse memberCount = " + getContactResponse.getMemberCount());
seq = getContactResponse.getSeq();
cacheService.getContacts().addAll(Arrays.stream(getContactResponse.getMemberList()).filter(x -> (x.getVerifyFlag() & 8) == 0).collect(Collectors.toSet()));
cacheService.getMediaPlatforms().addAll(Arrays.stream(getContactResponse.getMemberList()).filter(x -> (x.getVerifyFlag() & 8) > 0).collect(Collectors.toSet()));
}
} while (seq > 0);
logger.info("[7] get contact completed");
//8 batch get contact
ChatRoomDescription[] chatRoomDescriptions = Arrays.stream(initResponse.getContactList())
.map(x -> x.getUserName())
.filter(x -> x != null && x.startsWith("@@"))
.map(x -> {
ChatRoomDescription description = new ChatRoomDescription();
description.setUserName(x);
return description;
})
.toArray(ChatRoomDescription[]::new);
if (chatRoomDescriptions.length > 0) {
BatchGetContactResponse batchGetContactResponse = wechatHttpService.batchGetContact(
cacheService.getHostUrl(),
cacheService.getBaseRequest(),
cacheService.getPassTicket(),
chatRoomDescriptions);
if (!WechatUtils.checkBaseResponse(batchGetContactResponse.getBaseResponse())) {
throw new WechatException("batchGetContactResponse ret = " + batchGetContactResponse.getBaseResponse().getRet());
} else {
logger.info("[*] batchGetContactResponse count = " + batchGetContactResponse.getCount());
cacheService.getChatRooms().addAll(Arrays.asList(batchGetContactResponse.getContactList()));
}
}
logger.info("[8] batch get contact completed");
cacheService.setAlive(true);
logger.info("[-] login process completed");
startReceiving();
} catch (IOException ex) {
throw new WechatException(ex);
} catch (NotFoundException ex) {
throw new WechatException(ex);
} catch (WriterException ex) {
throw new WechatException(ex);
}
} | #vulnerable code
public void login() {
try {
//1 uuid
String uuid = wechatHttpService.getUUID();
cacheService.setUuid(uuid);
logger.info("[1] uuid completed");
//2 qr
byte[] qrData = wechatHttpService.getQR(uuid);
String path = "E://qr//qr.jpg";
OutputStream out = new FileOutputStream(path);
out.write(qrData);
out.flush();
out.close();
Runtime runtime = Runtime.getRuntime();
runtime.exec("cmd /c start " + path);
logger.info("[2] qrcode completed");
//3 login
LoginResult loginResponse = null;
while (true) {
loginResponse = wechatHttpService.login(uuid);
if (LoginCode.SUCCESS.getCode().equals(loginResponse.getCode())) {
if (loginResponse.getHostUrl() == null) {
throw new WechatException("hostUrl can't be found");
}
if (loginResponse.getRedirectUrl() == null) {
throw new WechatException("redirectUrl can't be found");
}
cacheService.setHostUrl(loginResponse.getHostUrl());
cacheService.setSyncUrl(loginResponse.getHostUrl().replaceFirst("^https://", "https://webpush."));
cacheService.setFileUrl(loginResponse.getHostUrl().replaceFirst("^https://", "https://file."));
break;
} else {
logger.info("[*] login status = " + loginResponse.getCode());
}
}
logger.info("[3] login completed");
//4 redirect login
Token token = wechatHttpService.redirectLogin(loginResponse.getRedirectUrl());
if (token.getRet() == 0) {
cacheService.setPassTicket(token.getPass_ticket());
cacheService.setsKey(token.getSkey());
cacheService.setSid(token.getWxsid());
cacheService.setUin(token.getWxuin());
BaseRequest baseRequest = new BaseRequest();
baseRequest.setUin(cacheService.getUin());
baseRequest.setSid(cacheService.getSid());
baseRequest.setSkey(cacheService.getsKey());
String rndDeviceId = "e" + String.valueOf(new Random().nextLong()).substring(1, 16);
baseRequest.setDeviceID(rndDeviceId);
cacheService.setBaseRequest(baseRequest);
} else {
throw new WechatException("token ret = " + token.getRet());
}
logger.info("[4] redirect completed");
//5 init
InitResponse initResponse = wechatHttpService.init(cacheService.getHostUrl(), cacheService.getBaseRequest(), cacheService.getPassTicket());
if (!WechatUtils.checkBaseResponse(initResponse.getBaseResponse())) {
throw new WechatException("initResponse ret = " + initResponse.getBaseResponse().getRet());
}
cacheService.setSyncKey(initResponse.getSyncKey());
cacheService.setOwner(initResponse.getUser());
logger.info("[5] init completed");
//6 status notify
StatusNotifyResponse statusNotifyResponse =
wechatHttpService.statusNotify(cacheService.getHostUrl(),
cacheService.getPassTicket(),
cacheService.getBaseRequest(),
cacheService.getOwner().getUserName(), 3);
if (!WechatUtils.checkBaseResponse(statusNotifyResponse.getBaseResponse())) {
throw new WechatException("statusNotifyResponse ret = " + statusNotifyResponse.getBaseResponse().getRet());
}
logger.info("[6] status notify completed");
//7 get contact
long seq = 0;
do {
GetContactResponse getContactResponse = wechatHttpService.getContact(cacheService.getHostUrl(), cacheService.getBaseRequest(), seq);
if (!WechatUtils.checkBaseResponse(getContactResponse.getBaseResponse())) {
throw new WechatException("getContactResponse ret = " + getContactResponse.getBaseResponse().getRet());
} else {
logger.info("[*] getContactResponse seq = " + getContactResponse.getSeq());
logger.info("[*] getContactResponse memberCount = " + getContactResponse.getMemberCount());
seq = getContactResponse.getSeq();
cacheService.getContacts().addAll(Arrays.stream(getContactResponse.getMemberList()).filter(x -> (x.getVerifyFlag() & 8) == 0).collect(Collectors.toSet()));
cacheService.getMediaPlatforms().addAll(Arrays.stream(getContactResponse.getMemberList()).filter(x -> (x.getVerifyFlag() & 8) > 0).collect(Collectors.toSet()));
}
} while (seq > 0);
logger.info("[7] get contact completed");
//8 batch get contact
ChatRoomDescription[] chatRoomDescriptions = Arrays.stream(initResponse.getContactList())
.map(x -> x.getUserName())
.filter(x -> x != null && x.startsWith("@@"))
.map(x -> {
ChatRoomDescription description = new ChatRoomDescription();
description.setUserName(x);
return description;
})
.toArray(ChatRoomDescription[]::new);
if (chatRoomDescriptions.length > 0) {
BatchGetContactResponse batchGetContactResponse = wechatHttpService.batchGetContact(
cacheService.getHostUrl(),
cacheService.getBaseRequest(),
cacheService.getPassTicket(),
chatRoomDescriptions);
if (!WechatUtils.checkBaseResponse(batchGetContactResponse.getBaseResponse())) {
throw new WechatException("batchGetContactResponse ret = " + batchGetContactResponse.getBaseResponse().getRet());
} else {
logger.info("[*] batchGetContactResponse count = " + batchGetContactResponse.getCount());
cacheService.getChatRooms().addAll(Arrays.asList(batchGetContactResponse.getContactList()));
}
}
logger.info("[8] batch get contact completed");
cacheService.setAlive(true);
logger.info("[-] login process completed");
startReceiving();
} catch (IOException ex) {
throw new WechatException(ex);
}
}
#location 15
#vulnerability type RESOURCE_LEAK | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
public void login() {
try {
//1 uuid
String uuid = wechatHttpService.getUUID();
cacheService.setUuid(uuid);
logger.info("[1] uuid completed");
//2 qr
byte[] qrData = wechatHttpService.getQR(uuid);
ByteArrayInputStream stream = new ByteArrayInputStream(qrData);
String qrUrl = QRCodeUtils.decode(stream);
stream.close();
String qr = QRCodeUtils.generateQR(qrUrl, 40, 40);
System.out.println(qr);
logger.info("[2] qrcode completed");
//3 login
LoginResult loginResponse = null;
while (true) {
loginResponse = wechatHttpService.login(uuid);
if (LoginCode.SUCCESS.getCode().equals(loginResponse.getCode())) {
if (loginResponse.getHostUrl() == null) {
throw new WechatException("hostUrl can't be found");
}
if (loginResponse.getRedirectUrl() == null) {
throw new WechatException("redirectUrl can't be found");
}
cacheService.setHostUrl(loginResponse.getHostUrl());
cacheService.setSyncUrl(loginResponse.getHostUrl().replaceFirst("^https://", "https://webpush."));
cacheService.setFileUrl(loginResponse.getHostUrl().replaceFirst("^https://", "https://file."));
break;
} else {
logger.info("[*] login status = " + loginResponse.getCode());
}
}
logger.info("[3] login completed");
//4 redirect login
Token token = wechatHttpService.redirectLogin(loginResponse.getRedirectUrl());
if (token.getRet() == 0) {
cacheService.setPassTicket(token.getPass_ticket());
cacheService.setsKey(token.getSkey());
cacheService.setSid(token.getWxsid());
cacheService.setUin(token.getWxuin());
BaseRequest baseRequest = new BaseRequest();
baseRequest.setUin(cacheService.getUin());
baseRequest.setSid(cacheService.getSid());
baseRequest.setSkey(cacheService.getsKey());
String rndDeviceId = "e" + String.valueOf(new Random().nextLong()).substring(1, 16);
baseRequest.setDeviceID(rndDeviceId);
cacheService.setBaseRequest(baseRequest);
} else {
throw new WechatException("token ret = " + token.getRet());
}
logger.info("[4] redirect completed");
//5 init
InitResponse initResponse = wechatHttpService.init(cacheService.getHostUrl(), cacheService.getBaseRequest(), cacheService.getPassTicket());
if (!WechatUtils.checkBaseResponse(initResponse.getBaseResponse())) {
throw new WechatException("initResponse ret = " + initResponse.getBaseResponse().getRet());
}
cacheService.setSyncKey(initResponse.getSyncKey());
cacheService.setOwner(initResponse.getUser());
logger.info("[5] init completed");
//6 status notify
StatusNotifyResponse statusNotifyResponse =
wechatHttpService.statusNotify(cacheService.getHostUrl(),
cacheService.getPassTicket(),
cacheService.getBaseRequest(),
cacheService.getOwner().getUserName(), 3);
if (!WechatUtils.checkBaseResponse(statusNotifyResponse.getBaseResponse())) {
throw new WechatException("statusNotifyResponse ret = " + statusNotifyResponse.getBaseResponse().getRet());
}
logger.info("[6] status notify completed");
//7 get contact
long seq = 0;
do {
GetContactResponse getContactResponse = wechatHttpService.getContact(cacheService.getHostUrl(), cacheService.getBaseRequest(), seq);
if (!WechatUtils.checkBaseResponse(getContactResponse.getBaseResponse())) {
throw new WechatException("getContactResponse ret = " + getContactResponse.getBaseResponse().getRet());
} else {
logger.info("[*] getContactResponse seq = " + getContactResponse.getSeq());
logger.info("[*] getContactResponse memberCount = " + getContactResponse.getMemberCount());
seq = getContactResponse.getSeq();
cacheService.getContacts().addAll(Arrays.stream(getContactResponse.getMemberList()).filter(x -> (x.getVerifyFlag() & 8) == 0).collect(Collectors.toSet()));
cacheService.getMediaPlatforms().addAll(Arrays.stream(getContactResponse.getMemberList()).filter(x -> (x.getVerifyFlag() & 8) > 0).collect(Collectors.toSet()));
}
} while (seq > 0);
logger.info("[7] get contact completed");
//8 batch get contact
ChatRoomDescription[] chatRoomDescriptions = Arrays.stream(initResponse.getContactList())
.map(x -> x.getUserName())
.filter(x -> x != null && x.startsWith("@@"))
.map(x -> {
ChatRoomDescription description = new ChatRoomDescription();
description.setUserName(x);
return description;
})
.toArray(ChatRoomDescription[]::new);
if (chatRoomDescriptions.length > 0) {
BatchGetContactResponse batchGetContactResponse = wechatHttpService.batchGetContact(
cacheService.getHostUrl(),
cacheService.getBaseRequest(),
cacheService.getPassTicket(),
chatRoomDescriptions);
if (!WechatUtils.checkBaseResponse(batchGetContactResponse.getBaseResponse())) {
throw new WechatException("batchGetContactResponse ret = " + batchGetContactResponse.getBaseResponse().getRet());
} else {
logger.info("[*] batchGetContactResponse count = " + batchGetContactResponse.getCount());
cacheService.getChatRooms().addAll(Arrays.asList(batchGetContactResponse.getContactList()));
}
}
logger.info("[8] batch get contact completed");
cacheService.setAlive(true);
logger.info("[-] login process completed");
startReceiving();
} catch (IOException ex) {
throw new WechatException(ex);
} catch (NotFoundException ex) {
throw new WechatException(ex);
} catch (WriterException ex) {
throw new WechatException(ex);
}
} | #vulnerable code
public void login() {
try {
//1 uuid
String uuid = wechatHttpService.getUUID();
cacheService.setUuid(uuid);
logger.info("[1] uuid completed");
//2 qr
byte[] qrData = wechatHttpService.getQR(uuid);
String path = "E://qr//qr.jpg";
OutputStream out = new FileOutputStream(path);
out.write(qrData);
out.flush();
out.close();
Runtime runtime = Runtime.getRuntime();
runtime.exec("cmd /c start " + path);
logger.info("[2] qrcode completed");
//3 login
LoginResult loginResponse = null;
while (true) {
loginResponse = wechatHttpService.login(uuid);
if (LoginCode.SUCCESS.getCode().equals(loginResponse.getCode())) {
if (loginResponse.getHostUrl() == null) {
throw new WechatException("hostUrl can't be found");
}
if (loginResponse.getRedirectUrl() == null) {
throw new WechatException("redirectUrl can't be found");
}
cacheService.setHostUrl(loginResponse.getHostUrl());
cacheService.setSyncUrl(loginResponse.getHostUrl().replaceFirst("^https://", "https://webpush."));
cacheService.setFileUrl(loginResponse.getHostUrl().replaceFirst("^https://", "https://file."));
break;
} else {
logger.info("[*] login status = " + loginResponse.getCode());
}
}
logger.info("[3] login completed");
//4 redirect login
Token token = wechatHttpService.redirectLogin(loginResponse.getRedirectUrl());
if (token.getRet() == 0) {
cacheService.setPassTicket(token.getPass_ticket());
cacheService.setsKey(token.getSkey());
cacheService.setSid(token.getWxsid());
cacheService.setUin(token.getWxuin());
BaseRequest baseRequest = new BaseRequest();
baseRequest.setUin(cacheService.getUin());
baseRequest.setSid(cacheService.getSid());
baseRequest.setSkey(cacheService.getsKey());
String rndDeviceId = "e" + String.valueOf(new Random().nextLong()).substring(1, 16);
baseRequest.setDeviceID(rndDeviceId);
cacheService.setBaseRequest(baseRequest);
} else {
throw new WechatException("token ret = " + token.getRet());
}
logger.info("[4] redirect completed");
//5 init
InitResponse initResponse = wechatHttpService.init(cacheService.getHostUrl(), cacheService.getBaseRequest(), cacheService.getPassTicket());
if (!WechatUtils.checkBaseResponse(initResponse.getBaseResponse())) {
throw new WechatException("initResponse ret = " + initResponse.getBaseResponse().getRet());
}
cacheService.setSyncKey(initResponse.getSyncKey());
cacheService.setOwner(initResponse.getUser());
logger.info("[5] init completed");
//6 status notify
StatusNotifyResponse statusNotifyResponse =
wechatHttpService.statusNotify(cacheService.getHostUrl(),
cacheService.getPassTicket(),
cacheService.getBaseRequest(),
cacheService.getOwner().getUserName(), 3);
if (!WechatUtils.checkBaseResponse(statusNotifyResponse.getBaseResponse())) {
throw new WechatException("statusNotifyResponse ret = " + statusNotifyResponse.getBaseResponse().getRet());
}
logger.info("[6] status notify completed");
//7 get contact
long seq = 0;
do {
GetContactResponse getContactResponse = wechatHttpService.getContact(cacheService.getHostUrl(), cacheService.getBaseRequest(), seq);
if (!WechatUtils.checkBaseResponse(getContactResponse.getBaseResponse())) {
throw new WechatException("getContactResponse ret = " + getContactResponse.getBaseResponse().getRet());
} else {
logger.info("[*] getContactResponse seq = " + getContactResponse.getSeq());
logger.info("[*] getContactResponse memberCount = " + getContactResponse.getMemberCount());
seq = getContactResponse.getSeq();
cacheService.getContacts().addAll(Arrays.stream(getContactResponse.getMemberList()).filter(x -> (x.getVerifyFlag() & 8) == 0).collect(Collectors.toSet()));
cacheService.getMediaPlatforms().addAll(Arrays.stream(getContactResponse.getMemberList()).filter(x -> (x.getVerifyFlag() & 8) > 0).collect(Collectors.toSet()));
}
} while (seq > 0);
logger.info("[7] get contact completed");
//8 batch get contact
ChatRoomDescription[] chatRoomDescriptions = Arrays.stream(initResponse.getContactList())
.map(x -> x.getUserName())
.filter(x -> x != null && x.startsWith("@@"))
.map(x -> {
ChatRoomDescription description = new ChatRoomDescription();
description.setUserName(x);
return description;
})
.toArray(ChatRoomDescription[]::new);
if (chatRoomDescriptions.length > 0) {
BatchGetContactResponse batchGetContactResponse = wechatHttpService.batchGetContact(
cacheService.getHostUrl(),
cacheService.getBaseRequest(),
cacheService.getPassTicket(),
chatRoomDescriptions);
if (!WechatUtils.checkBaseResponse(batchGetContactResponse.getBaseResponse())) {
throw new WechatException("batchGetContactResponse ret = " + batchGetContactResponse.getBaseResponse().getRet());
} else {
logger.info("[*] batchGetContactResponse count = " + batchGetContactResponse.getCount());
cacheService.getChatRooms().addAll(Arrays.asList(batchGetContactResponse.getContactList()));
}
}
logger.info("[8] batch get contact completed");
cacheService.setAlive(true);
logger.info("[-] login process completed");
startReceiving();
} catch (IOException ex) {
throw new WechatException(ex);
}
}
#location 115
#vulnerability type RESOURCE_LEAK | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
public static NSObject parse(final byte[] bytes) throws Exception {
ByteArrayInputStream bis = new ByteArrayInputStream(bytes);
return parse(bis);
} | #vulnerable code
public static NSObject parse(final byte[] bytes) throws Exception {
InputStream is = new InputStream() {
private int pos = 0;
@Override
public int read() throws IOException {
if (pos >= bytes.length) {
return -1;
}
return bytes[pos++];
}
};
return parse(is);
}
#location 16
#vulnerability type RESOURCE_LEAK | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
public static void saveAsXML(NSObject root, File out) throws IOException {
OutputStreamWriter w = new OutputStreamWriter(new FileOutputStream(out), "UTF-8");
w.write(root.toXMLPropertyList());
w.close();
} | #vulnerable code
public static void saveAsXML(NSObject root, File out) throws IOException {
FileWriter fw = new FileWriter(out);
fw.write(root.toXMLPropertyList());
fw.close();
}
#location 5
#vulnerability type RESOURCE_LEAK | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
public static NSObject parse(File f) throws Exception {
FileInputStream fis = new FileInputStream(f);
String magicString = new String(readAll(fis, 8), 0, 8);
fis.close();
if (magicString.startsWith("bplist00")) {
return BinaryPropertyListParser.parse(f);
} else if (magicString.startsWith("<?xml")) {
return XMLPropertyListParser.parse(f);
} else {
throw new UnsupportedOperationException("The given data is neither a binary nor a XML property list. ASCII property lists are not supported.");
}
} | #vulnerable code
public static NSObject parse(File f) throws Exception {
FileInputStream fis = new FileInputStream(f);
return parse(fis);
}
#location 3
#vulnerability type RESOURCE_LEAK | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
public static NSObject parse(File f) throws Exception {
FileInputStream fis = new FileInputStream(f);
return parse(fis);
} | #vulnerable code
public static NSObject parse(File f) throws Exception {
FileInputStream fis = new FileInputStream(f);
byte[] magic = new byte[8];
fis.read(magic);
String magic_string = new String(magic);
fis.close();
if (magic_string.startsWith("bplist00")) {
return BinaryPropertyListParser.parse(f);
} else if (magic_string.startsWith("<?xml")) {
return XMLPropertyListParser.parse(f);
} else {
throw new UnsupportedOperationException("The given file is neither a binary nor a XML property list. ASCII property lists are not supported.");
}
}
#location 12
#vulnerability type RESOURCE_LEAK | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
public void runTagger() throws IOException, ClassNotFoundException {
tagger = new Tagger();
if (!justTokenize) {
tagger.loadModel(modelFilename);
}
if (inputFormat.equals("conll")) {
runTaggerInEvalMode();
return;
}
assert (inputFormat.equals("json") || inputFormat.equals("text"));
JsonTweetReader jsonTweetReader = new JsonTweetReader();
LineNumberReader reader = new LineNumberReader(BasicFileIO.openFileToReadUTF8(inputFilename));
String line;
long currenttime = System.currentTimeMillis();
int numtoks = 0;
while ( (line = reader.readLine()) != null) {
String[] parts = line.split("\t");
String tweetData = parts[inputField-1];
if (reader.getLineNumber()==1) {
if (inputFormat.equals("auto")) {
detectAndSetInputFormat(tweetData);
}
}
String text;
if (inputFormat.equals("json")) {
text = jsonTweetReader.getText(tweetData);
if (text==null) {
System.err.println("Warning, null text (JSON parse error?), using blank string instead");
text = "";
}
} else {
text = tweetData;
}
Sentence sentence = new Sentence();
sentence.tokens = Twokenize.tokenizeRawTweetText(text);
ModelSentence modelSentence = null;
if (sentence.T() > 0 && !justTokenize) {
modelSentence = new ModelSentence(sentence.T());
tagger.featureExtractor.computeFeatures(sentence, modelSentence);
goDecode(modelSentence);
}
if (outputFormat.equals("conll")) {
outputJustTagging(sentence, modelSentence);
} else {
outputPrependedTagging(sentence, modelSentence, justTokenize, line);
}
numtoks += sentence.T();
}
long finishtime = System.currentTimeMillis();
System.err.printf("Tokenized%s %d tweets (%d tokens) in %.1f seconds: %.1f tweets/sec, %.1f tokens/sec\n",
justTokenize ? "" : " and tagged",
reader.getLineNumber(), numtoks, (finishtime-currenttime)/1000.0,
reader.getLineNumber() / ((finishtime-currenttime)/1000.0),
numtoks / ((finishtime-currenttime)/1000.0)
);
reader.close();
} | #vulnerable code
public void runTagger() throws IOException, ClassNotFoundException {
tagger = new Tagger();
if (!justTokenize) {
tagger.loadModel(modelFilename);
}
if (inputFormat.equals("conll")) {
runTaggerInEvalMode();
return;
}
assert (inputFormat.equals("json") || inputFormat.equals("text"));
JsonTweetReader jsonTweetReader = new JsonTweetReader();
LineNumberReader reader = new LineNumberReader(BasicFileIO.openFileToReadUTF8(inputFilename));
String line;
long currenttime = System.currentTimeMillis();
int numtoks = 0;
while ( (line = reader.readLine()) != null) {
String[] parts = line.split("\t");
String tweetData = parts[inputField-1];
String text;
if (inputFormat.equals("json")) {
text = jsonTweetReader.getText(tweetData);
} else {
text = tweetData;
}
Sentence sentence = new Sentence();
sentence.tokens = Twokenize.tokenizeRawTweetText(text);
ModelSentence modelSentence = null;
if (sentence.T() > 0 && !justTokenize) {
modelSentence = new ModelSentence(sentence.T());
tagger.featureExtractor.computeFeatures(sentence, modelSentence);
goDecode(modelSentence);
}
if (outputFormat.equals("conll")) {
outputJustTagging(sentence, modelSentence);
} else {
outputPrependedTagging(sentence, modelSentence, justTokenize, tweetData);
}
numtoks += sentence.T();
}
long finishtime = System.currentTimeMillis();
System.err.printf("Tokenized%s %d tweets (%d tokens) in %.1f seconds: %.1f tweets/sec, %.1f tokens/sec\n",
justTokenize ? "" : " and tagged",
reader.getLineNumber(), numtoks, (finishtime-currenttime)/1000.0,
reader.getLineNumber() / ((finishtime-currenttime)/1000.0),
numtoks / ((finishtime-currenttime)/1000.0)
);
reader.close();
}
#location 32
#vulnerability type NULL_DEREFERENCE | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
public static ArrayList<Sentence> readFile(String filename) throws IOException {
BufferedReader reader = BasicFileIO.openFileToReadUTF8(filename);
ArrayList sentences = new ArrayList<String>();
ArrayList<String> curLines = new ArrayList<String>();
String line;
while ( (line = reader.readLine()) != null ) {
if (line.matches("^\\s*$")) {
if (curLines.size() > 0) {
// Flush
sentences.add(sentenceFromLines(curLines));
curLines.clear();
}
} else {
curLines.add(line);
}
}
if (curLines.size() > 0) {
sentences.add(sentenceFromLines(curLines));
}
return sentences;
} | #vulnerable code
public static ArrayList<Sentence> readFile(String filename) throws IOException {
BufferedReader reader = BasicFileIO.openFileToRead(filename);
ArrayList sentences = new ArrayList<String>();
ArrayList<String> curLines = new ArrayList<String>();
String line;
while ( (line = reader.readLine()) != null ) {
if (line.matches("^\\s*$")) {
if (curLines.size() > 0) {
// Flush
sentences.add(sentenceFromLines(curLines));
curLines.clear();
}
} else {
curLines.add(line);
}
}
if (curLines.size() > 0) {
sentences.add(sentenceFromLines(curLines));
}
return sentences;
}
#location 21
#vulnerability type RESOURCE_LEAK | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Transactional(readOnly = true)
public MiddlewarePage list(Long apiId, MiddlewareDTO middlewareDTO, PageableDTO pageableDTO) {
Api api = apiRepository.findOne(apiId);
HeimdallException.checkThrow(isBlank(api), GLOBAL_RESOURCE_NOT_FOUND);
Middleware middleware = GenericConverter.mapper(middlewareDTO, Middleware.class);
Api apiFind = new Api();
apiFind.setId(apiId);
middleware.setApi(apiFind);
Example<Middleware> example = Example.of(middleware, ExampleMatcher.matching().withIgnoreCase().withStringMatcher(StringMatcher.CONTAINING));
Sort sort = new Sort(new Sort.Order(Sort.Direction.DESC, "creationDate"));
Pageable pageable = Pageable.setPageable(pageableDTO.getOffset(), pageableDTO.getLimit(), sort);
Page<Middleware> page = middlewareRepository.findAll(example, pageable);
MiddlewarePage middlewarePage = new MiddlewarePage(PageDTO.build(page));
return middlewarePage;
} | #vulnerable code
@Transactional(readOnly = true)
public MiddlewarePage list(Long apiId, MiddlewareDTO middlewareDTO, PageableDTO pageableDTO) {
Api api = apiRepository.findOne(apiId);
HeimdallException.checkThrow(isBlank(api), GLOBAL_RESOURCE_NOT_FOUND);
Middleware middleware = GenericConverter.mapper(middlewareDTO, Middleware.class);
Api apiFind = new Api();
apiFind.setId(apiId);
middleware.setApi(apiFind);
Example<Middleware> example = Example.of(middleware, ExampleMatcher.matching().withIgnoreCase().withStringMatcher(StringMatcher.CONTAINING));
Pageable pageable = Pageable.setPageable(pageableDTO.getOffset(), pageableDTO.getLimit());
Page<Middleware> page = middlewareRepository.findAll(example, pageable);
MiddlewarePage middlewarePage = new MiddlewarePage(PageDTO.build(page));
return middlewarePage;
}
#location 17
#vulnerability type NULL_DEREFERENCE | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
protected HeimdallRoute getMatchingHeimdallRoute(String requestURI, String method, RequestContext ctx) {
boolean auxMatch = false;
for (Entry<String, ZuulRoute> entry : routeLocator.getAtomicRoutes().get().entrySet()) {
if (entry.getKey() != null) {
String pattern = entry.getKey();
if (this.pathMatcher.match(pattern, requestURI)) {
auxMatch = true;
List<Operation> operations = operationRepository.findByEndPoint(pattern);
Operation operation = null;
if (operations != null && !operations.isEmpty()) {
operation = operations.stream().filter(o -> o.getMethod().equals(HttpMethod.ALL) || method.equals(o.getMethod().name().toUpperCase())).findFirst().orElse(null);
}
if (operation != null) {
ZuulRoute zuulRoute = entry.getValue();
String basePath = operation.getResource().getApi().getBasePath();
requestURI = org.apache.commons.lang.StringUtils.removeStart(requestURI, basePath);
ctx.put(PATTERN, org.apache.commons.lang.StringUtils.removeStart(pattern, basePath));
ctx.put(API_NAME, operation.getResource().getApi().getName());
ctx.put(API_ID, operation.getResource().getApi().getId());
ctx.put(RESOURCE_ID, operation.getResource().getId());
ctx.put(OPERATION_ID, operation.getId());
ctx.put("scopes", operation.getScopesIds());
List<Environment> environments = operation.getResource().getApi().getEnvironments();
String location = null;
if (environments != null) {
String host = ctx.getRequest().getHeader("Host");
Optional<Environment> environment;
if (host != null && !host.isEmpty()) {
environment = environments.stream().filter(e -> e.getInboundURL().toLowerCase().contains(host.toLowerCase())).findFirst();
} else {
environment = environments.stream().filter(e -> ctx.getRequest().getRequestURL().toString().toLowerCase().contains(e.getInboundURL().toLowerCase())).findFirst();
}
if (environment.isPresent()) {
location = environment.get().getOutboundURL();
ctx.put("environmentVariables", environment.get().getVariables());
}
}
Route route = new Route(zuulRoute.getId(), requestURI, location, "", zuulRoute.getRetryable() != null ? zuulRoute.getRetryable() : false, zuulRoute.isCustomSensitiveHeaders() ? zuulRoute.getSensitiveHeaders() : null);
TraceContextHolder traceContextHolder = TraceContextHolder.getInstance();
traceContextHolder.getActualTrace().setApiId(operation.getResource().getApi().getId());
traceContextHolder.getActualTrace().setApiName(operation.getResource().getApi().getName());
traceContextHolder.getActualTrace().setResourceId(operation.getResource().getId());
traceContextHolder.getActualTrace().setOperationId(operation.getId());
traceContextHolder.getActualTrace().setPattern(operation.getPath());
return new HeimdallRoute(pattern, route, false);
} else {
ctx.put(INTERRUPT, true);
}
}
}
}
if (auxMatch) {
return new HeimdallRoute().methodNotAllowed();
}
return null;
} | #vulnerable code
protected HeimdallRoute getMatchingHeimdallRoute(String requestURI, String method, RequestContext ctx) {
boolean auxMatch = false;
for (Entry<String, ZuulRoute> entry : routeLocator.getAtomicRoutes().get().entrySet()) {
if (entry.getKey() != null) {
String pattern = entry.getKey();
if (this.pathMatcher.match(pattern, requestURI)) {
auxMatch = true;
List<Operation> operations = operationRepository.findByEndPoint(pattern);
Operation operation = null;
if (operations != null && !operations.isEmpty()) {
operation = operations.stream().filter(o -> o.getMethod().equals(HttpMethod.ALL) || method.equals(o.getMethod().name().toUpperCase())).findFirst().orElse(null);
}
if (operation != null) {
ZuulRoute zuulRoute = entry.getValue();
String basePath = operation.getResource().getApi().getBasePath();
requestURI = org.apache.commons.lang.StringUtils.removeStart(requestURI, basePath);
ctx.put(PATTERN, org.apache.commons.lang.StringUtils.removeStart(pattern, basePath));
ctx.put(API_NAME, operation.getResource().getApi().getName());
ctx.put(API_ID, operation.getResource().getApi().getId());
ctx.put(RESOURCE_ID, operation.getResource().getId());
ctx.put(OPERATION_ID, operation.getId());
List<Environment> environments = operation.getResource().getApi().getEnvironments();
String location = null;
if (environments != null) {
String host = ctx.getRequest().getHeader("Host");
Optional<Environment> environment;
if (host != null && !host.isEmpty()) {
environment = environments.stream().filter(e -> e.getInboundURL().toLowerCase().contains(host.toLowerCase())).findFirst();
} else {
environment = environments.stream().filter(e -> ctx.getRequest().getRequestURL().toString().toLowerCase().contains(e.getInboundURL().toLowerCase())).findFirst();
}
if (environment.isPresent()) {
location = environment.get().getOutboundURL();
ctx.put("environmentVariables", environment.get().getVariables());
}
}
Route route = new Route(zuulRoute.getId(), requestURI, location, "", zuulRoute.getRetryable() != null ? zuulRoute.getRetryable() : false, zuulRoute.isCustomSensitiveHeaders() ? zuulRoute.getSensitiveHeaders() : null);
TraceContextHolder traceContextHolder = TraceContextHolder.getInstance();
traceContextHolder.getActualTrace().setApiId(operation.getResource().getApi().getId());
traceContextHolder.getActualTrace().setApiName(operation.getResource().getApi().getName());
traceContextHolder.getActualTrace().setResourceId(operation.getResource().getId());
traceContextHolder.getActualTrace().setOperationId(operation.getId());
traceContextHolder.getActualTrace().setPattern(operation.getPath());
return new HeimdallRoute(pattern, route, false);
} else {
ctx.put(INTERRUPT, true);
}
}
}
}
if (auxMatch) {
return new HeimdallRoute().methodNotAllowed();
}
return null;
}
#location 50
#vulnerability type NULL_DEREFERENCE | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
protected HeimdallRoute getMatchingHeimdallRoute(String requestURI, String method, RequestContext ctx) {
boolean auxMatch = false;
for (Entry<String, ZuulRoute> entry : routeLocator.getAtomicRoutes().get().entrySet()) {
if (Objeto.notBlank(entry.getKey())) {
String pattern = entry.getKey();
if (this.pathMatcher.match(pattern, requestURI)) {
auxMatch = true;
List<Operation> operations = operationRepository.findByEndPoint(pattern);
Operation operation = null;
if (Objeto.notBlank(operations)) {
operation = operations.stream().filter(o -> method.equals(o.getMethod().name().toUpperCase())).findFirst().orElse(null);
}
if (Objeto.notBlank(operation)) {
ZuulRoute zuulRoute = entry.getValue();
String basePath = operation.getResource().getApi().getBasePath();
requestURI = org.apache.commons.lang.StringUtils.removeStart(requestURI, basePath);
ctx.put("pattern", org.apache.commons.lang.StringUtils.removeStart(pattern, basePath));
List<Environment> environments = operation.getResource().getApi().getEnvironments();
String location = null;
if (Objeto.notBlank(environments)) {
String host = ctx.getRequest().getHeader("Host");
if (Objeto.isBlank(host)) {
host = ctx.getRequest().getHeader("host");
}
Optional<Environment> environment = Optional.ofNullable(null);
if (Objeto.notBlank(host)) {
String tempHost = host;
environment = environments.stream().filter(e -> e.getInboundURL().toLowerCase().contains(tempHost.toLowerCase())).findFirst();
} else {
environment = environments.stream().filter(e -> ctx.getRequest().getRequestURL().toString().toLowerCase().contains(e.getInboundURL().toLowerCase())).findFirst();
}
if (environment.isPresent()) {
location = environment.get().getOutboundURL();
ctx.put("environmentVariables", environment.get().getVariables());
}
}
Route route = new Route(zuulRoute.getId(), requestURI, location, "", zuulRoute.getRetryable() != null ? zuulRoute.getRetryable() : false, zuulRoute.isCustomSensitiveHeaders() ? zuulRoute.getSensitiveHeaders() : null);
TraceContextHolder traceContextHolder = TraceContextHolder.getInstance();
traceContextHolder.getActualTrace().setApiId(operation.getResource().getApi().getId());
traceContextHolder.getActualTrace().setApiName(operation.getResource().getApi().getName());
traceContextHolder.getActualTrace().setResourceId(operation.getResource().getId());
traceContextHolder.getActualTrace().setOperationId(operation.getId());
traceContextHolder.getActualTrace().setPattern(operation.getPath());
return new HeimdallRoute(pattern, route, false);
} else {
ctx.put(INTERRUPT, true);
}
}
}
}
if (auxMatch) {
return new HeimdallRoute().methodNotAllowed();
}
return null;
} | #vulnerable code
protected HeimdallRoute getMatchingHeimdallRoute(String requestURI, String method, RequestContext ctx) {
boolean auxMatch = false;
for (Entry<String, ZuulRoute> entry : routeLocator.getAtomicRoutes().get().entrySet()) {
if (Objeto.notBlank(entry.getKey())) {
String pattern = entry.getKey();
if (this.pathMatcher.match(pattern, requestURI)) {
auxMatch = true;
List<Operation> operations = operationRepository.findByEndPoint(pattern);
Operation operation = null;
if (Objeto.notBlank(operations)) {
operation = operations.stream().filter(o -> method.equals(o.getMethod().name().toUpperCase())).findFirst().orElse(null);
}
if (Objeto.notBlank(operation)) {
ZuulRoute zuulRoute = entry.getValue();
String basePath = operation.getResource().getApi().getBasePath();
requestURI = org.apache.commons.lang.StringUtils.removeStart(requestURI, basePath);
ctx.put("pattern", org.apache.commons.lang.StringUtils.removeStart(pattern, basePath));
List<Environment> environments = operation.getResource().getApi().getEnvironments();
String location = null;
if (Objeto.notBlank(environments)) {
String host = ctx.getRequest().getHeader("Host");
if (Objeto.isBlank(host)) {
host = ctx.getRequest().getHeader("host");
}
Optional<Environment> environment = Optional.ofNullable(null);
if (Objeto.notBlank(host)) {
String tempHost = host;
environment = environments.stream().filter(e -> e.getInboundURL().toLowerCase().contains(tempHost.toLowerCase())).findFirst();
} else {
environment = environments.stream().filter(e -> ctx.getRequest().getRequestURL().toString().toLowerCase().contains(e.getInboundURL().toLowerCase())).findFirst();
}
if (environment.isPresent()) {
location = environment.get().getOutboundURL();
ctx.put("environmentVariables", environment.get().getVariables());
}
}
Route route = new Route(zuulRoute.getId(), requestURI, location, "", zuulRoute.getRetryable() != null ? zuulRoute.getRetryable() : false, zuulRoute.isCustomSensitiveHeaders() ? zuulRoute.getSensitiveHeaders() : null);
TraceContextHolder.getInstance().getActualTrace().setApiId(operation.getResource().getApi().getId());
TraceContextHolder.getInstance().getActualTrace().setApiName(operation.getResource().getApi().getName());
TraceContextHolder.getInstance().getActualTrace().setResourceId(operation.getResource().getId());
TraceContextHolder.getInstance().getActualTrace().setOperationId(operation.getId());
TraceContextHolder.getInstance().getActualTrace().setPattern(operation.getPath());
return new HeimdallRoute(pattern, route, false);
} else {
ctx.put(INTERRUPT, true);
}
}
}
}
if (auxMatch) {
return new HeimdallRoute().methodNotAllowed();
}
return null;
}
#location 49
#vulnerability type NULL_DEREFERENCE | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Override
public Object run() {
long startTime = System.currentTimeMillis();
RequestContext context = RequestContext.getCurrentContext();
HttpServletRequest request = context.getRequest();
HttpHost httpHost = new HttpHost(
context.getRouteHost().getHost(),
context.getRouteHost().getPort(),
context.getRouteHost().getProtocol());
Long operationId = (Long) context.get(OPERATION_ID);
String operationPath = (String) context.get(OPERATION_PATH);
try {
Callable<Object> callable = super::run;
Object obj = circuitBreakerManager.failsafe(callable, operationId, operationPath);
detail.setStatus(Constants.SUCCESS);
return obj;
} catch (Exception e) {
detail.setStatus(Constants.FAILED);
log.error("Exception: {} - Message: {} - during routing request to (hostPath + uri): {} - Verb: {} - HostName: {} - Port: {} - SchemeName: {}",
e.getClass().getName(),
e.getMessage(),
request.getRequestURI(),
request.getMethod().toUpperCase(),
httpHost.getHostName(),
httpHost.getPort(),
httpHost.getSchemeName());
throw e;
} finally {
long endTime = System.currentTimeMillis();
long duration = (endTime - startTime);
detail.setName(this.getClass().getSimpleName());
detail.setTimeInMillisRun(duration);
TraceContextHolder.getInstance().getActualTrace().addFilter(detail);
}
} | #vulnerable code
@Override
public Object run() {
long startTime = System.currentTimeMillis();
RequestContext context = RequestContext.getCurrentContext();
HttpServletRequest request = context.getRequest();
String verb = getVerb(request);
String uri = this.helper.buildZuulRequestURI(request);
URL host = RequestContext.getCurrentContext().getRouteHost();
HttpHost httpHost = getHttpHost(host);
Long operationId = (Long) context.get(OPERATION_ID);
try {
Callable<Object> callable = () -> super.run();
Object obj = circuitBreakerManager.failsafe(callable, operationId);
detail.setStatus(Constants.SUCCESS);
return obj;
} catch (Exception e) {
detail.setStatus(Constants.FAILED);
log.error("Exception: {} - Message: {} - during routing request to (hostPath + uri): {} - Verb: {} - HostName: {} - Port: {} - SchemeName: {}",
e.getClass().getName(),
e.getMessage(),
request.getRequestURI(),
verb, httpHost.getHostName(),
httpHost.getPort(),
httpHost.getSchemeName());
throw e;
} finally {
long endTime = System.currentTimeMillis();
long duration = (endTime - startTime);
detail.setName(this.getClass().getSimpleName());
detail.setTimeInMillisRun(duration);
TraceContextHolder.getInstance().getActualTrace().addFilter(detail);
}
}
#location 36
#vulnerability type NULL_DEREFERENCE | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
private void execute() throws Throwable {
RequestContext ctx = RequestContext.getCurrentContext();
RequestResponseParser r = new RequestResponseParser();
r.setUri(UrlUtil.getCurrentUrl(ctx.getRequest()));
Map<String, String> headers = ResponseHandler.getResponseHeaders(ctx);
r.setHeaders(headers);
String body = ResponseHandler.getResponseBody(ctx, headers, helper);
r.setBody(body);
TraceContextHolder.getInstance().getActualTrace().setResponse(r);
} | #vulnerable code
private void execute() throws Throwable {
RequestContext ctx = RequestContext.getCurrentContext();
RequestResponseParser r = new RequestResponseParser();
r.setUri(UrlUtil.getCurrentUrl(ctx.getRequest()));
Map<String, String> headers = getResponseHeaders(ctx);
r.setHeaders(headers);
String content = headers.get(HttpHeaders.CONTENT_TYPE);
// if the content type is not defined by api server then permit to read the body. Prevent NPE
if (Objeto.isBlank(content)) content = "";
String[] types = content.split(";");
if (!ContentTypeUtils.belongsToBlackList(types)) {
@Cleanup
InputStream stream = ctx.getResponseDataStream();
String body;
body = StreamUtils.copyToString(stream, StandardCharsets.UTF_8);
if (body.isEmpty() && helper.call().response().getBody() != null) {
body = helper.call().response().getBody();
}
if (Objects.nonNull(body) && !body.isEmpty()) {
r.setBody(body);
}
ctx.setResponseDataStream(new ByteArrayInputStream(body.getBytes(StandardCharsets.UTF_8)));
}
TraceContextHolder.getInstance().getActualTrace().setResponse(r);
}
#location 16
#vulnerability type NULL_DEREFERENCE | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
private void execute() {
RequestContext ctx = RequestContext.getCurrentContext();
HttpServletRequest request = ctx.getRequest();
RequestResponseParser r = new RequestResponseParser();
r.setHeaders(getRequestHeadersInfo(request));
r.setBody(helper.call().request().getBody());
r.setUri(UrlUtil.getCurrentUrl(request));
TraceContextHolder.getInstance().getActualTrace().setRequest(r);
} | #vulnerable code
private void execute() {
Helper helper = new HelperImpl();
RequestContext ctx = RequestContext.getCurrentContext();
HttpServletRequest request = ctx.getRequest();
RequestResponseParser r = new RequestResponseParser();
r.setHeaders(getRequestHeadersInfo(request));
r.setBody(helper.call().request().getBody());
r.setUri(UrlUtil.getCurrentUrl(request));
TraceContextHolder.getInstance().getActualTrace().setRequest(r);
}
#location 9
#vulnerability type NULL_DEREFERENCE | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
public void execute(Integer status, String body) {
RequestContext ctx = RequestContext.getCurrentContext();
String response;
if (helper.json().isJson(body)) {
response = helper.json().parse(body);
helper.call().response().header().add("Content-Type", "application/json");
} else {
response = body;
helper.call().response().header().add("Content-Type", "text/plain");
}
helper.call().response().setBody(response);
ctx.setSendZuulResponse(false);
ctx.setResponseStatusCode(status);
TraceContextHolder.getInstance().getActualTrace().trace(ConstantsInterceptors.GLOBAL_MOCK_INTERCEPTOR_LOCALIZED, response);
} | #vulnerable code
public void execute(Integer status, String body) {
Helper helper = new HelperImpl();
RequestContext ctx = RequestContext.getCurrentContext();
String response;
if (helper.json().isJson(body)) {
response = helper.json().parse(body);
helper.call().response().header().add("Content-Type", "application/json");
} else {
response = body;
helper.call().response().header().add("Content-Type", "text/plain");
}
helper.call().response().setBody(response);
ctx.setSendZuulResponse(false);
ctx.setResponseStatusCode(status);
TraceContextHolder.getInstance().getActualTrace().trace(ConstantsInterceptors.GLOBAL_MOCK_INTERCEPTOR_LOCALIZED, response);
}
#location 10
#vulnerability type NULL_DEREFERENCE | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
private MongoDatabase database() {
return this.mongoClient.getDatabase(databaseName);
} | #vulnerable code
private MongoDatabase database() {
return createMongoClient().getDatabase(databaseName);
}
#location 3
#vulnerability type RESOURCE_LEAK | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
public void cacheInterceptor(String cacheName, Long timeToLive, List<String> headers, List<String> queryParams) {
RedissonClient redisson = (RedissonClient) BeanManager.getBean(RedissonClient.class);
RequestContext context = RequestContext.getCurrentContext();
if (shouldCache(context, headers, queryParams)) {
RBucket<ApiResponse> rBucket = redisson.getBucket(createCacheKey(context, cacheName, headers, queryParams));
if (rBucket.get() == null) {
context.put(CACHE_BUCKET, rBucket);
context.put(CACHE_TIME_TO_LIVE, timeToLive);
} else {
ApiResponse response = rBucket.get();
helper.call().response().header().addAll(response.getHeaders());
helper.call().response().setBody(response.getBody());
helper.call().response().setStatus(response.getStatus());
}
}
} | #vulnerable code
public void cacheInterceptor(String cacheName, Long timeToLive, List<String> headers, List<String> queryParams) {
Helper helper = new HelperImpl();
RedissonClient redisson = (RedissonClient) BeanManager.getBean(RedissonClient.class);
RequestContext context = RequestContext.getCurrentContext();
if (shouldCache(context, headers, queryParams)) {
RBucket<ApiResponse> rBucket = redisson.getBucket(createCacheKey(context, cacheName, headers, queryParams));
if (rBucket.get() == null) {
context.put(CACHE_BUCKET, rBucket);
context.put(CACHE_TIME_TO_LIVE, timeToLive);
} else {
ApiResponse response = rBucket.get();
helper.call().response().header().addAll(response.getHeaders());
helper.call().response().setBody(response.getBody());
helper.call().response().setStatus(response.getStatus());
}
}
}
#location 18
#vulnerability type NULL_DEREFERENCE | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Transactional(readOnly = true)
public MiddlewarePage list(Long apiId, MiddlewareDTO middlewareDTO, PageableDTO pageableDTO) {
Api api = apiRepository.findOne(apiId);
HeimdallException.checkThrow(isBlank(api), GLOBAL_RESOURCE_NOT_FOUND);
Middleware middleware = GenericConverter.mapper(middlewareDTO, Middleware.class);
Api apiFind = new Api();
apiFind.setId(apiId);
middleware.setApi(apiFind);
Example<Middleware> example = Example.of(middleware, ExampleMatcher.matching().withIgnoreCase().withStringMatcher(StringMatcher.CONTAINING));
Sort sort = new Sort(new Sort.Order(Sort.Direction.DESC, "creationDate"));
Pageable pageable = Pageable.setPageable(pageableDTO.getOffset(), pageableDTO.getLimit(), sort);
Page<Middleware> page = middlewareRepository.findAll(example, pageable);
MiddlewarePage middlewarePage = new MiddlewarePage(PageDTO.build(page));
return middlewarePage;
} | #vulnerable code
@Transactional(readOnly = true)
public MiddlewarePage list(Long apiId, MiddlewareDTO middlewareDTO, PageableDTO pageableDTO) {
Api api = apiRepository.findOne(apiId);
HeimdallException.checkThrow(isBlank(api), GLOBAL_RESOURCE_NOT_FOUND);
Middleware middleware = GenericConverter.mapper(middlewareDTO, Middleware.class);
Api apiFind = new Api();
apiFind.setId(apiId);
middleware.setApi(apiFind);
Example<Middleware> example = Example.of(middleware, ExampleMatcher.matching().withIgnoreCase().withStringMatcher(StringMatcher.CONTAINING));
Pageable pageable = Pageable.setPageable(pageableDTO.getOffset(), pageableDTO.getLimit());
Page<Middleware> page = middlewareRepository.findAll(example, pageable);
MiddlewarePage middlewarePage = new MiddlewarePage(PageDTO.build(page));
return middlewarePage;
}
#location 17
#vulnerability type NULL_DEREFERENCE | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Override
public void stop() {
try {
this.lock.writeLock().lock();
this.stop = true;
this.torrentFileProvider.unRegisterListener(this);
this.thread.interrupt();
try {
this.thread.join();
} catch (final InterruptedException ignored) {
}
this.delayQueue.drainAll().stream()
.filter(req -> req.getEvent() != RequestEvent.STARTED)
.map(AnnounceRequest::getAnnouncer)
.map(AnnounceRequest::createStop)
.forEach(this.announcerExecutor::execute);
this.announcerExecutor.awaitForRunningTasks();
} finally {
this.lock.writeLock().unlock();
}
} | #vulnerable code
@Override
public void stop() {
this.stop = true;
this.torrentFileProvider.unRegisterListener(this);
this.thread.interrupt();
try {
this.thread.join();
} catch (final InterruptedException ignored) {
}
this.delayQueue.drainAll().stream()
.filter(req -> req.getEvent() != RequestEvent.STARTED)
.map(AnnounceRequest::getAnnouncer)
.map(AnnounceRequest::createStop)
.forEach(this.announcerExecutor::execute);
this.announcerExecutor.awaitForRunningTasks();
}
#location 7
#vulnerability type THREAD_SAFETY_VIOLATION | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Test
public void shouldHandleNullConfig() throws Throwable
{
// Given
try( Driver driver = GraphDatabase.driver( neo4j.address(), AuthTokens.none(), null ) )
{
Session session = driver.session();
// When
session.close();
// Then
assertFalse( session.isOpen() );
}
} | #vulnerable code
@Test
public void shouldHandleNullConfig() throws Throwable
{
// Given
Driver driver = GraphDatabase.driver( neo4j.address(), AuthTokens.none(), null );
Session session = driver.session();
// When
session.close();
// Then
assertFalse( session.isOpen() );
}
#location 6
#vulnerability type RESOURCE_LEAK | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Test
public void shouldNotBeAbleToUseSessionWhileOngoingTransaction() throws Throwable
{
// Given
when( mock.isOpen() ).thenReturn( true );
sess.beginTransaction();
// Expect
exception.expect( ClientException.class );
// When
sess.run( "whatever" );
} | #vulnerable code
@Test
public void shouldNotBeAbleToUseSessionWhileOngoingTransaction() throws Throwable
{
// Given
Connection mock = mock( Connection.class );
when( mock.isOpen() ).thenReturn( true );
InternalSession sess = new InternalSession( mock );
sess.beginTransaction();
// Expect
exception.expect( ClientException.class );
// When
sess.run( "whatever" );
}
#location 15
#vulnerability type RESOURCE_LEAK | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
private void saveTrustedHost( String fingerprint ) throws IOException
{
this.fingerprint = fingerprint;
logger.info( "Adding %s as known and trusted certificate for %s.", fingerprint, serverId );
createKnownCertFileIfNotExists();
assertKnownHostFileWritable();
try ( BufferedWriter writer = new BufferedWriter( new FileWriter( knownHosts, true ) ) )
{
writer.write( serverId + " " + this.fingerprint );
writer.newLine();
}
} | #vulnerable code
private void saveTrustedHost( String fingerprint ) throws IOException
{
this.fingerprint = fingerprint;
logger.info( "Adding %s as known and trusted certificate for %s.", fingerprint, serverId );
createKnownCertFileIfNotExists();
assertKnownHostFileWritable();
BufferedWriter writer = new BufferedWriter( new FileWriter( knownHosts, true ) );
writer.write( serverId + " " + this.fingerprint );
writer.newLine();
writer.close();
}
#location 13
#vulnerability type RESOURCE_LEAK | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Test
public void shouldEstablishTLSConnection() throws Throwable
{
ConfigTest.deleteDefaultKnownCertFileIfExists();
Config config = Config.build().withTlsEnabled( true ).toConfig();
Driver driver = GraphDatabase.driver(
URI.create( Neo4jRunner.DEFAULT_URL ),
config );
ResultCursor result = driver.session().run( "RETURN 1" );
assertTrue( result.next() );
assertEquals( 1, result.value( 0 ).asInt() );
assertFalse( result.next() );
driver.close();
} | #vulnerable code
@Test
public void shouldEstablishTLSConnection() throws Throwable
{
ConfigTest.deleteDefaultKnownCertFileIfExists();
Config config = Config.build().withTlsEnabled( true ).toConfig();
Driver driver = GraphDatabase.driver(
URI.create( Neo4jRunner.DEFAULT_URL ),
config );
Result result = driver.session().run( "RETURN 1" );
assertTrue( result.next() );
assertEquals( 1, result.value( 0 ).asInt() );
assertFalse( result.next() );
driver.close();
}
#location 14
#vulnerability type RESOURCE_LEAK | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Test
public void testFields() throws Exception
{
// GIVEN
ResultBuilder builder = new ResultBuilder( "<unknown>", ParameterSupport.NO_PARAMETERS );
builder.keys( new String[]{"k1"} );
builder.record( new Value[]{value(42)} );
ResultCursor result = builder.build();
result.first();
// WHEN
List<Pair<String, Integer>> fields = Extract.fields( result, integerExtractor() );
// THEN
assertThat( fields, equalTo( Collections.singletonList( InternalPair.of( "k1", 42 ) ) ) );
} | #vulnerable code
@Test
public void testFields() throws Exception
{
// GIVEN
ResultBuilder builder = new ResultBuilder( "<unknown>", ParameterSupport.NO_PARAMETERS );
builder.keys( new String[]{"k1"} );
builder.record( new Value[]{value(42)} );
ResultCursor result = builder.build();
result.first();
// WHEN
List<Entry<Integer>> fields = Extract.fields( result, integerExtractor() );
// THEN
assertThat( fields, equalTo( Collections.singletonList( InternalEntry.of( "k1", 42 ) ) ) );
}
#location 12
#vulnerability type RESOURCE_LEAK | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
private boolean serverResponds() throws IOException, InterruptedException
{
try
{
URI uri = URI.create( DEFAULT_URL );
SocketClient client = new SocketClient( uri.getHost(), uri.getPort() );
client.start();
client.stop();
return true;
}
catch ( ClientException e )
{
return false;
}
} | #vulnerable code
private boolean serverResponds() throws IOException, InterruptedException
{
try
{
URI uri = URI.create( DEFAULT_URL );
SocketClient client = new SocketClient( uri.getHost(), uri.getPort(), new DevNullLogger() );
client.start();
client.stop();
return true;
}
catch ( ClientException e )
{
return false;
}
}
#location 11
#vulnerability type RESOURCE_LEAK | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Test
public void shouldNotBeAbleToUseSessionWhileOngoingTransaction() throws Throwable
{
// Given
when( mock.isOpen() ).thenReturn( true );
sess.beginTransaction();
// Expect
exception.expect( ClientException.class );
// When
sess.run( "whatever" );
} | #vulnerable code
@Test
public void shouldNotBeAbleToUseSessionWhileOngoingTransaction() throws Throwable
{
// Given
Connection mock = mock( Connection.class );
when( mock.isOpen() ).thenReturn( true );
InternalSession sess = new InternalSession( mock );
sess.beginTransaction();
// Expect
exception.expect( ClientException.class );
// When
sess.run( "whatever" );
}
#location 14
#vulnerability type RESOURCE_LEAK | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Override
public final Connection connect( BoltServerAddress address )
{
Connection connection = createConnection( address, securityPlan, logging );
// Because SocketConnection is not thread safe, wrap it in this guard
// to ensure concurrent access leads causes application errors
connection = new ConcurrencyGuardingConnection( connection );
try
{
connection.init( connectionSettings.userAgent(), tokenAsMap( connectionSettings.authToken() ) );
}
catch ( Throwable initError )
{
connection.close();
throw initError;
}
return connection;
} | #vulnerable code
@Override
public final Connection connect( BoltServerAddress address )
{
Connection connection = createConnection( address, securityPlan, logging );
// Because SocketConnection is not thread safe, wrap it in this guard
// to ensure concurrent access leads causes application errors
connection = new ConcurrencyGuardingConnection( connection );
connection.init( connectionSettings.userAgent(), tokenAsMap( connectionSettings.authToken() ) );
return connection;
}
#location 11
#vulnerability type RESOURCE_LEAK | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@BeforeEach
void setUp()
{
System.setProperty( DRIVER_METRICS_ENABLED_KEY, "true" );
logging = new LoggerNameTrackingLogging();
Config.ConfigBuilder builder = Config.builder()
.withLogging( logging )
.withMaxConnectionPoolSize( 100 )
.withConnectionAcquisitionTimeout( 1, MINUTES );
driver = (InternalDriver) GraphDatabase.driver( databaseUri(), authToken(), config( builder ) );
System.setProperty( DRIVER_METRICS_ENABLED_KEY, "false" );
ThreadFactory threadFactory = new DaemonThreadFactory( getClass().getSimpleName() + "-worker-" );
executor = Executors.newCachedThreadPool( threadFactory );
} | #vulnerable code
@BeforeEach
void setUp()
{
System.setProperty( DRIVER_METRICS_ENABLED_KEY, "true" );
logging = new LoggerNameTrackingLogging();
Config config = Config.builder()
.withoutEncryption()
.withLogging( logging )
.withMaxConnectionPoolSize( 100 )
.withConnectionAcquisitionTimeout( 1, MINUTES )
.build();
driver = (InternalDriver) GraphDatabase.driver( databaseUri(), authToken(), config );
System.setProperty( DRIVER_METRICS_ENABLED_KEY, "false" );
ThreadFactory threadFactory = new DaemonThreadFactory( getClass().getSimpleName() + "-worker-" );
executor = Executors.newCachedThreadPool( threadFactory );
}
#location 14
#vulnerability type NULL_DEREFERENCE | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
private static String resource( String fileName )
{
File resource = new File( TestNeo4j.TEST_RESOURCE_FOLDER_PATH, fileName );
if ( !resource.exists() )
{
fail( fileName + " does not exists" );
}
return resource.getAbsolutePath();
} | #vulnerable code
private static String resource( String fileName )
{
URL resource = StubServer.class.getClassLoader().getResource( fileName );
if ( resource == null )
{
fail( fileName + " does not exists" );
}
return resource.getFile();
}
#location 8
#vulnerability type NULL_DEREFERENCE | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
private void load() throws IOException
{
if ( !knownHosts.exists() )
{
return;
}
assertKnownHostFileReadable();
try ( BufferedReader reader = new BufferedReader( new FileReader( knownHosts ) ) )
{
String line;
while ( (line = reader.readLine()) != null )
{
if ( (!line.trim().startsWith( "#" )) )
{
String[] strings = line.split( " " );
if ( strings[0].trim().equals( serverId ) )
{
// load the certificate
fingerprint = strings[1].trim();
return;
}
}
}
}
} | #vulnerable code
private void load() throws IOException
{
if ( !knownHosts.exists() )
{
return;
}
assertKnownHostFileReadable();
BufferedReader reader = new BufferedReader( new FileReader( knownHosts ) );
String line;
while ( (line = reader.readLine()) != null )
{
if ( (!line.trim().startsWith( "#" )) )
{
String[] strings = line.split( " " );
if ( strings[0].trim().equals( serverId ) )
{
// load the certificate
fingerprint = strings[1].trim();
return;
}
}
}
reader.close();
}
#location 6
#vulnerability type RESOURCE_LEAK | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
public static Driver driver( URI uri, AuthToken authToken, Config config )
{
// Make sure we have some configuration to play with
config = config == null ? Config.defaultConfig() : config;
return new DriverFactory().newInstance( uri, authToken, config.routingSettings(), config );
} | #vulnerable code
public static Driver driver( URI uri, AuthToken authToken, Config config )
{
// Break down the URI into its constituent parts
String scheme = uri.getScheme();
BoltServerAddress address = BoltServerAddress.from( uri );
// Make sure we have some configuration to play with
if ( config == null )
{
config = Config.defaultConfig();
}
// Construct security plan
SecurityPlan securityPlan;
try
{
securityPlan = createSecurityPlan( address, config );
}
catch ( GeneralSecurityException | IOException ex )
{
throw new ClientException( "Unable to establish SSL parameters", ex );
}
ConnectionPool connectionPool = createConnectionPool( authToken, securityPlan, config );
switch ( scheme.toLowerCase() )
{
case "bolt":
return new DirectDriver( address, connectionPool, securityPlan, config.logging() );
case "bolt+routing":
return new RoutingDriver(
config.routingSettings(),
address,
connectionPool,
securityPlan,
Clock.SYSTEM,
config.logging() );
default:
throw new ClientException( format( "Unsupported URI scheme: %s", scheme ) );
}
}
#location 39
#vulnerability type RESOURCE_LEAK | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Test
public void shouldEstablishTLSConnection() throws Throwable
{
ConfigTest.deleteDefaultKnownCertFileIfExists();
Config config = Config.build().withTlsEnabled( true ).toConfig();
Driver driver = GraphDatabase.driver(
URI.create( Neo4jRunner.DEFAULT_URL ),
config );
ResultCursor result = driver.session().run( "RETURN 1" );
assertTrue( result.next() );
assertEquals( 1, result.value( 0 ).asInt() );
assertFalse( result.next() );
driver.close();
} | #vulnerable code
@Test
public void shouldEstablishTLSConnection() throws Throwable
{
ConfigTest.deleteDefaultKnownCertFileIfExists();
Config config = Config.build().withTlsEnabled( true ).toConfig();
Driver driver = GraphDatabase.driver(
URI.create( Neo4jRunner.DEFAULT_URL ),
config );
Result result = driver.session().run( "RETURN 1" );
assertTrue( result.next() );
assertEquals( 1, result.value( 0 ).asInt() );
assertFalse( result.next() );
driver.close();
}
#location 17
#vulnerability type RESOURCE_LEAK | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Test
void shouldSaveNewCert() throws Throwable
{
// Given
int newPort = 200;
BoltServerAddress address = new BoltServerAddress( knownServerIp, newPort );
Logger logger = mock(Logger.class);
TrustOnFirstUseTrustManager manager = new TrustOnFirstUseTrustManager( address, knownCertsFile, logger );
String fingerprint = fingerprint( knownCertificate );
// When
manager.checkServerTrusted( new X509Certificate[]{knownCertificate}, null );
// Then no exception should've been thrown, and we should've logged that we now trust this certificate
verify( logger ).info( "Adding %s as known and trusted certificate for %s.", fingerprint, "1.2.3.4:200" );
// And the file should contain the right info
try ( Scanner reader = new Scanner( knownCertsFile ) )
{
String line1 = nextLine( reader );
assertEquals( knownServer + " " + fingerprint, line1 );
assertTrue( reader.hasNextLine() );
String line2 = nextLine( reader );
assertEquals( knownServerIp + ":" + newPort + " " + fingerprint, line2 );
}
} | #vulnerable code
@Test
void shouldSaveNewCert() throws Throwable
{
// Given
int newPort = 200;
BoltServerAddress address = new BoltServerAddress( knownServerIp, newPort );
Logger logger = mock(Logger.class);
TrustOnFirstUseTrustManager manager = new TrustOnFirstUseTrustManager( address, knownCertsFile, logger );
String fingerprint = fingerprint( knownCertificate );
// When
manager.checkServerTrusted( new X509Certificate[]{knownCertificate}, null );
// Then no exception should've been thrown, and we should've logged that we now trust this certificate
verify( logger ).info( "Adding %s as known and trusted certificate for %s.", fingerprint, "1.2.3.4:200" );
// And the file should contain the right info
Scanner reader = new Scanner( knownCertsFile );
String line;
line = nextLine( reader );
assertEquals( knownServer + " " + fingerprint, line );
assertTrue( reader.hasNextLine() );
line = nextLine( reader );
assertEquals( knownServerIp + ":" + newPort + " " + fingerprint, line );
}
#location 22
#vulnerability type RESOURCE_LEAK | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Test
public void shouldBeAbleToOpenTxAfterPreviousIsClosed() throws Throwable
{
// Given
when( mock.isOpen() ).thenReturn( true );
sess.beginTransaction().close();
// When
Transaction tx = sess.beginTransaction();
// Then we should've gotten a transaction object back
assertNotNull( tx );
} | #vulnerable code
@Test
public void shouldBeAbleToOpenTxAfterPreviousIsClosed() throws Throwable
{
// Given
Connection mock = mock( Connection.class );
when( mock.isOpen() ).thenReturn( true );
InternalSession sess = new InternalSession( mock );
sess.beginTransaction().close();
// When
Transaction tx = sess.beginTransaction();
// Then we should've gotten a transaction object back
assertNotNull( tx );
}
#location 15
#vulnerability type RESOURCE_LEAK | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Test
public void shouldGetHelpfulErrorWhenTryingToConnectToHttpPort() throws Throwable
{
// Given
//the http server needs some time to start up
Thread.sleep( 2000 );
try( Driver driver = GraphDatabase.driver( "bolt://localhost:7474",
Config.build().withEncryptionLevel( Config.EncryptionLevel.NONE ).toConfig() ) )
{
// Expect
exception.expect( ClientException.class );
exception.expectMessage(
"Server responded HTTP. Make sure you are not trying to connect to the http endpoint " +
"(HTTP defaults to port 7474 whereas BOLT defaults to port 7687)" );
// When
try(Session session = driver.session() ){}
}
} | #vulnerable code
@Test
public void shouldGetHelpfulErrorWhenTryingToConnectToHttpPort() throws Throwable
{
// Given
//the http server needs some time to start up
Thread.sleep( 2000 );
Driver driver = GraphDatabase.driver( "bolt://localhost:7474", Config.build().withEncryptionLevel(
Config.EncryptionLevel.NONE ).toConfig());
// Expect
exception.expect( ClientException.class );
exception.expectMessage( "Server responded HTTP. Make sure you are not trying to connect to the http endpoint " +
"(HTTP defaults to port 7474 whereas BOLT defaults to port 7687)" );
// When
driver.session();
}
#location 16
#vulnerability type RESOURCE_LEAK | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Override
public final Connection connect( BoltServerAddress address )
{
Connection connection = createConnection( address, securityPlan, logging );
// Because SocketConnection is not thread safe, wrap it in this guard
// to ensure concurrent access leads causes application errors
connection = new ConcurrencyGuardingConnection( connection );
try
{
connection.init( connectionSettings.userAgent(), tokenAsMap( connectionSettings.authToken() ) );
}
catch ( Throwable initError )
{
connection.close();
throw initError;
}
return connection;
} | #vulnerable code
@Override
public final Connection connect( BoltServerAddress address )
{
Connection connection = createConnection( address, securityPlan, logging );
// Because SocketConnection is not thread safe, wrap it in this guard
// to ensure concurrent access leads causes application errors
connection = new ConcurrencyGuardingConnection( connection );
connection.init( connectionSettings.userAgent(), tokenAsMap( connectionSettings.authToken() ) );
return connection;
}
#location 11
#vulnerability type RESOURCE_LEAK | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Test
public void shouldEstablishTLSConnection() throws Throwable
{
Config config = Config.build().withEncryptionLevel( Config.EncryptionLevel.REQUIRED ).toConfig();
try( Driver driver = GraphDatabase.driver( URI.create( Neo4jRunner.DEFAULT_URL ), config );
Session session = driver.session() )
{
StatementResult result = session.run( "RETURN 1" );
assertEquals( 1, result.next().get( 0 ).asInt() );
assertFalse( result.hasNext() );
}
} | #vulnerable code
@Test
public void shouldEstablishTLSConnection() throws Throwable
{
Config config = Config.build().withEncryptionLevel( Config.EncryptionLevel.REQUIRED ).toConfig();
Driver driver = GraphDatabase.driver(
URI.create( Neo4jRunner.DEFAULT_URL ),
config );
StatementResult result = driver.session().run( "RETURN 1" );
assertEquals( 1, result.next().get( 0 ).asInt() );
assertFalse( result.hasNext() );
driver.close();
}
#location 16
#vulnerability type RESOURCE_LEAK | 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.