output
stringlengths 64
73.2k
| input
stringlengths 208
73.3k
| instruction
stringclasses 1
value |
---|---|---|
#fixed code
protected Connection getConnectionProxy(Connection connection) throws SQLException {
if (!RootContext.inGlobalTransaction()) {
return connection;
}
return getConnectionProxyXA(connection);
}
|
#vulnerable code
protected Connection getConnectionProxy(Connection connection) throws SQLException {
Connection physicalConn = connection.unwrap(Connection.class);
XAConnection xaConnection = XAUtils.createXAConnection(physicalConn, this);
ConnectionProxyXA connectionProxyXA = new ConnectionProxyXA(connection, xaConnection, this, RootContext.getXID());
connectionProxyXA.init();
return connectionProxyXA;
}
#location 6
#vulnerability type RESOURCE_LEAK
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
@Override
public boolean removeConfig(String dataId, long timeoutMills) {
ConfigFuture configFuture = new ConfigFuture(dataId, null, ConfigFuture.ConfigOperation.REMOVE, timeoutMills);
consulNotifierExecutor.execute(() -> {
complete(getConsulClient().deleteKVValue(dataId), configFuture);
});
return (Boolean) configFuture.get();
}
|
#vulnerable code
@Override
public boolean removeConfig(String dataId, long timeoutMills) {
ConfigFuture configFuture = new ConfigFuture(dataId, null, ConfigFuture.ConfigOperation.REMOVE, timeoutMills);
consulConfigExecutor.execute(() -> {
complete(getConsulClient().deleteKVValue(dataId), configFuture);
});
return (Boolean) configFuture.get();
}
#location 4
#vulnerability type THREAD_SAFETY_VIOLATION
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
@Test
public void testRestoredFromFileCommitRetry() throws Exception {
SessionHolder.init("file");
GlobalSession globalSession = new GlobalSession("demo-app", "my_test_tx_group", "test", 6000);
globalSession.addSessionLifecycleListener(SessionHolder.getRootSessionManager());
globalSession.begin();
BranchSession branchSession1 = SessionHelper.newBranchByGlobal(globalSession, BranchType.AT, RESOURCE_ID,
"ta:1", "xxx");
branchSession1.lock();
globalSession.addBranch(branchSession1);
LockManager lockManager = LockManagerFactory.get();
Assert.assertFalse(lockManager.isLockable(0L, RESOURCE_ID, "ta:1"));
globalSession.changeStatus(GlobalStatus.Committing);
globalSession.changeBranchStatus(branchSession1, BranchStatus.PhaseTwo_CommitFailed_Retryable);
globalSession.changeStatus(GlobalStatus.CommitRetrying);
lockManager.cleanAllLocks();
Assert.assertTrue(lockManager.isLockable(0L, RESOURCE_ID, "ta:1"));
// Re-init SessionHolder: restore sessions from file
SessionHolder.init("file");
long tid = globalSession.getTransactionId();
GlobalSession reloadSession = SessionHolder.findGlobalSession(tid);
Assert.assertEquals(reloadSession.getStatus(), GlobalStatus.CommitRetrying);
GlobalSession sessionInRetryCommittingQueue = SessionHolder.getRetryCommittingSessionManager()
.findGlobalSession(tid);
Assert.assertTrue(reloadSession == sessionInRetryCommittingQueue);
BranchSession reloadBranchSession = reloadSession.getBranch(branchSession1.getBranchId());
Assert.assertEquals(reloadBranchSession.getStatus(), BranchStatus.PhaseTwo_CommitFailed_Retryable);
// Lock is held by session in CommitRetrying status
Assert.assertFalse(lockManager.isLockable(0L, RESOURCE_ID, "ta:1"));
//clear
reloadSession.addSessionLifecycleListener(SessionHolder.getRootSessionManager());
reloadSession.end();
}
|
#vulnerable code
@Test
public void testRestoredFromFileCommitRetry() throws Exception {
SessionHolder.init(".");
GlobalSession globalSession = new GlobalSession("demo-app", "my_test_tx_group", "test", 6000);
globalSession.addSessionLifecycleListener(SessionHolder.getRootSessionManager());
globalSession.begin();
BranchSession branchSession1 = SessionHelper.newBranchByGlobal(globalSession, BranchType.AT, RESOURCE_ID,
"ta:1", "xxx");
branchSession1.lock();
globalSession.addBranch(branchSession1);
LockManager lockManager = LockManagerFactory.get();
Assert.assertFalse(lockManager.isLockable(0L, RESOURCE_ID, "ta:1"));
globalSession.changeStatus(GlobalStatus.Committing);
globalSession.changeBranchStatus(branchSession1, BranchStatus.PhaseTwo_CommitFailed_Retryable);
globalSession.changeStatus(GlobalStatus.CommitRetrying);
lockManager.cleanAllLocks();
Assert.assertTrue(lockManager.isLockable(0L, RESOURCE_ID, "ta:1"));
// Re-init SessionHolder: restore sessions from file
SessionHolder.init(".");
long tid = globalSession.getTransactionId();
GlobalSession reloadSession = SessionHolder.findGlobalSession(tid);
Assert.assertEquals(reloadSession.getStatus(), GlobalStatus.CommitRetrying);
GlobalSession sessionInRetryCommittingQueue = SessionHolder.getRetryCommittingSessionManager()
.findGlobalSession(tid);
Assert.assertTrue(reloadSession == sessionInRetryCommittingQueue);
BranchSession reloadBranchSession = reloadSession.getBranch(branchSession1.getBranchId());
Assert.assertEquals(reloadBranchSession.getStatus(), BranchStatus.PhaseTwo_CommitFailed_Retryable);
// Lock is held by session in CommitRetrying status
Assert.assertFalse(lockManager.isLockable(0L, RESOURCE_ID, "ta:1"));
}
#location 3
#vulnerability type RESOURCE_LEAK
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
public static void refresh(final DataSourceProxy dataSourceProxy){
ConcurrentMap<String, TableMeta> tableMetaMap = TABLE_META_CACHE.asMap();
for (Entry<String, TableMeta> entry : tableMetaMap.entrySet()) {
String key = getCacheKey(dataSourceProxy, entry.getValue().getTableName());
if(entry.getKey().equals(key)){
try {
TableMeta tableMeta = fetchSchema(dataSourceProxy, entry.getValue().getTableName());
if (!tableMeta.equals(entry.getValue())){
TABLE_META_CACHE.put(entry.getKey(), tableMeta);
LOGGER.info("table meta change was found, update table meta cache automatically.");
}
} catch (SQLException e) {
LOGGER.error("get table meta error:{}", e.getMessage(), e);
}
}
}
}
|
#vulnerable code
public static void refresh(final DataSourceProxy dataSourceProxy){
ConcurrentMap<String, TableMeta> tableMetaMap = TABLE_META_CACHE.asMap();
for (Entry<String, TableMeta> entry : tableMetaMap.entrySet()) {
try {
TableMeta tableMeta = fetchSchema(dataSourceProxy, entry.getValue().getTableName());
if (tableMeta == null){
LOGGER.error("get table meta error");
}
if (!tableMeta.equals(entry.getValue())){
TABLE_META_CACHE.put(entry.getKey(), tableMeta);
LOGGER.info("table meta change was found, update table meta cache automatically.");
}
} catch (SQLException e) {
LOGGER.error("get table meta error:{}", e.getMessage(), e);
}
}
}
#location 9
#vulnerability type NULL_DEREFERENCE
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
public static byte[] decompress(byte[] bytes) {
if (bytes == null) {
throw new NullPointerException("bytes is null");
}
ByteArrayOutputStream out = new ByteArrayOutputStream();
try (GZIPInputStream gunzip = new GZIPInputStream(new ByteArrayInputStream(bytes))) {
byte[] buffer = new byte[BUFFER_SIZE];
int n;
while ((n = gunzip.read(buffer)) > -1) {
out.write(buffer, 0, n);
}
return out.toByteArray();
} catch (IOException e) {
throw new RuntimeException("gzip decompress error", e);
}
}
|
#vulnerable code
public static byte[] decompress(byte[] bytes) {
if (bytes == null) {
throw new NullPointerException("bytes is null");
}
ByteArrayOutputStream out = null;
GZIPInputStream gunzip = null;
try {
out = new ByteArrayOutputStream();
gunzip = new GZIPInputStream(new ByteArrayInputStream(bytes));
byte[] buffer = new byte[BUFFER_SIZE];
int n;
while ((n = gunzip.read(buffer)) > -1) {
out.write(buffer, 0, n);
}
gunzip.close();
return out.toByteArray();
} catch (IOException e) {
throw new RuntimeException("gzip decompress error", e);
} finally {
IOUtil.close(out);
}
}
#location 17
#vulnerability type RESOURCE_LEAK
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
@Test
public void testRestoredFromFile() throws Exception {
SessionHolder.init("file");
GlobalSession globalSession = new GlobalSession("demo-app", "my_test_tx_group", "test", 6000);
globalSession.addSessionLifecycleListener(SessionHolder.getRootSessionManager());
globalSession.begin();
BranchSession branchSession1 = SessionHelper.newBranchByGlobal(globalSession, BranchType.AT, RESOURCE_ID,
"ta:1,2;tb:3", "xxx");
branchSession1.lock();
globalSession.addBranch(branchSession1);
LockManager lockManager = LockManagerFactory.get();
Assert.assertFalse(lockManager.isLockable(0L, RESOURCE_ID, "ta:1"));
Assert.assertFalse(lockManager.isLockable(0L, RESOURCE_ID, "ta:2"));
Assert.assertFalse(lockManager.isLockable(0L, RESOURCE_ID, "tb:3"));
Assert.assertTrue(lockManager.isLockable(0L, RESOURCE_ID, "ta:4"));
Assert.assertTrue(lockManager.isLockable(0L, RESOURCE_ID, "tb:5"));
lockManager.cleanAllLocks();
Assert.assertTrue(lockManager.isLockable(0L, RESOURCE_ID, "ta:1"));
Assert.assertTrue(lockManager.isLockable(0L, RESOURCE_ID, "ta:2"));
Assert.assertTrue(lockManager.isLockable(0L, RESOURCE_ID, "tb:3"));
// Re-init SessionHolder: restore sessions from file
SessionHolder.init("file");
long tid = globalSession.getTransactionId();
GlobalSession reloadSession = SessionHolder.findGlobalSession(tid);
Assert.assertNotNull(reloadSession);
Assert.assertFalse(globalSession == reloadSession);
Assert.assertEquals(globalSession.getApplicationId(), reloadSession.getApplicationId());
Assert.assertFalse(lockManager.isLockable(0L, RESOURCE_ID, "ta:1"));
Assert.assertFalse(lockManager.isLockable(0L, RESOURCE_ID, "ta:2"));
Assert.assertFalse(lockManager.isLockable(0L, RESOURCE_ID, "tb:3"));
Assert.assertTrue(lockManager.isLockable(globalSession.getTransactionId(), RESOURCE_ID, "tb:3"));
//clear
reloadSession.addSessionLifecycleListener(SessionHolder.getRootSessionManager());
reloadSession.end();
}
|
#vulnerable code
@Test
public void testRestoredFromFile() throws Exception {
SessionHolder.init(".");
GlobalSession globalSession = new GlobalSession("demo-app", "my_test_tx_group", "test", 6000);
globalSession.addSessionLifecycleListener(SessionHolder.getRootSessionManager());
globalSession.begin();
BranchSession branchSession1 = SessionHelper.newBranchByGlobal(globalSession, BranchType.AT, RESOURCE_ID,
"ta:1,2;tb:3", "xxx");
branchSession1.lock();
globalSession.addBranch(branchSession1);
LockManager lockManager = LockManagerFactory.get();
Assert.assertFalse(lockManager.isLockable(0L, RESOURCE_ID, "ta:1"));
Assert.assertFalse(lockManager.isLockable(0L, RESOURCE_ID, "ta:2"));
Assert.assertFalse(lockManager.isLockable(0L, RESOURCE_ID, "tb:3"));
Assert.assertTrue(lockManager.isLockable(0L, RESOURCE_ID, "ta:4"));
Assert.assertTrue(lockManager.isLockable(0L, RESOURCE_ID, "tb:5"));
lockManager.cleanAllLocks();
Assert.assertTrue(lockManager.isLockable(0L, RESOURCE_ID, "ta:1"));
Assert.assertTrue(lockManager.isLockable(0L, RESOURCE_ID, "ta:2"));
Assert.assertTrue(lockManager.isLockable(0L, RESOURCE_ID, "tb:3"));
// Re-init SessionHolder: restore sessions from file
SessionHolder.init(".");
long tid = globalSession.getTransactionId();
GlobalSession reloadSession = SessionHolder.findGlobalSession(tid);
Assert.assertNotNull(reloadSession);
Assert.assertFalse(globalSession == reloadSession);
Assert.assertEquals(globalSession.getApplicationId(), reloadSession.getApplicationId());
Assert.assertFalse(lockManager.isLockable(0L, RESOURCE_ID, "ta:1"));
Assert.assertFalse(lockManager.isLockable(0L, RESOURCE_ID, "ta:2"));
Assert.assertFalse(lockManager.isLockable(0L, RESOURCE_ID, "tb:3"));
Assert.assertTrue(lockManager.isLockable(globalSession.getTransactionId(), RESOURCE_ID, "tb:3"));
}
#location 3
#vulnerability type RESOURCE_LEAK
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
@Override
public void addConfigListener(String dataId, ConfigChangeListener listener) {
configListenersMap.putIfAbsent(dataId, new ArrayList<>());
configChangeNotifiersMap.putIfAbsent(dataId, new ArrayList<>());
ConfigChangeNotifier configChangeNotifier = new ConfigChangeNotifier(dataId, listener);
configChangeNotifiersMap.get(dataId).add(configChangeNotifier);
if (null != listener.getExecutor()) {
listener.getExecutor().submit(configChangeNotifier);
} else {
consulNotifierExecutor.submit(configChangeNotifier);
}
}
|
#vulnerable code
@Override
public void addConfigListener(String dataId, ConfigChangeListener listener) {
configListenersMap.putIfAbsent(dataId, new ArrayList<>());
configChangeNotifiersMap.putIfAbsent(dataId, new ArrayList<>());
ConfigChangeNotifier configChangeNotifier = new ConfigChangeNotifier(dataId, listener);
configChangeNotifiersMap.get(dataId).add(configChangeNotifier);
if (null != listener.getExecutor()) {
listener.getExecutor().submit(configChangeNotifier);
} else {
consulConfigExecutor.submit(configChangeNotifier);
}
}
#location 10
#vulnerability type THREAD_SAFETY_VIOLATION
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
@Test
public void testRestoredFromFileAsyncCommitting() throws Exception {
SessionHolder.init("file");
GlobalSession globalSession = new GlobalSession("demo-app", "my_test_tx_group", "test", 6000);
globalSession.addSessionLifecycleListener(SessionHolder.getRootSessionManager());
globalSession.begin();
BranchSession branchSession1 = SessionHelper.newBranchByGlobal(globalSession, BranchType.AT, RESOURCE_ID,
"ta:1", "xxx");
Assert.assertTrue(branchSession1.lock());
globalSession.addBranch(branchSession1);
LockManager lockManager = LockManagerFactory.get();
Assert.assertFalse(lockManager.isLockable(0L, RESOURCE_ID, "ta:1"));
globalSession.changeStatus(GlobalStatus.AsyncCommitting);
lockManager.cleanAllLocks();
Assert.assertTrue(lockManager.isLockable(0L, RESOURCE_ID, "ta:1"));
// Re-init SessionHolder: restore sessions from file
SessionHolder.init("file");
long tid = globalSession.getTransactionId();
GlobalSession reloadSession = SessionHolder.findGlobalSession(tid);
Assert.assertEquals(reloadSession.getStatus(), GlobalStatus.AsyncCommitting);
GlobalSession sessionInAsyncCommittingQueue = SessionHolder.getAsyncCommittingSessionManager()
.findGlobalSession(tid);
Assert.assertTrue(reloadSession == sessionInAsyncCommittingQueue);
// No locking for session in AsyncCommitting status
Assert.assertTrue(lockManager.isLockable(0L, RESOURCE_ID, "ta:1"));
//clear
reloadSession.addSessionLifecycleListener(SessionHolder.getRootSessionManager());
reloadSession.end();
}
|
#vulnerable code
@Test
public void testRestoredFromFileAsyncCommitting() throws Exception {
SessionHolder.init(".");
GlobalSession globalSession = new GlobalSession("demo-app", "my_test_tx_group", "test", 6000);
globalSession.addSessionLifecycleListener(SessionHolder.getRootSessionManager());
globalSession.begin();
BranchSession branchSession1 = SessionHelper.newBranchByGlobal(globalSession, BranchType.AT, RESOURCE_ID,
"ta:1", "xxx");
Assert.assertTrue(branchSession1.lock());
globalSession.addBranch(branchSession1);
LockManager lockManager = LockManagerFactory.get();
Assert.assertFalse(lockManager.isLockable(0L, RESOURCE_ID, "ta:1"));
globalSession.changeStatus(GlobalStatus.AsyncCommitting);
lockManager.cleanAllLocks();
Assert.assertTrue(lockManager.isLockable(0L, RESOURCE_ID, "ta:1"));
// Re-init SessionHolder: restore sessions from file
SessionHolder.init(".");
long tid = globalSession.getTransactionId();
GlobalSession reloadSession = SessionHolder.findGlobalSession(tid);
Assert.assertEquals(reloadSession.getStatus(), GlobalStatus.AsyncCommitting);
GlobalSession sessionInAsyncCommittingQueue = SessionHolder.getAsyncCommittingSessionManager()
.findGlobalSession(tid);
Assert.assertTrue(reloadSession == sessionInAsyncCommittingQueue);
// No locking for session in AsyncCommitting status
Assert.assertTrue(lockManager.isLockable(0L, RESOURCE_ID, "ta:1"));
}
#location 3
#vulnerability type RESOURCE_LEAK
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
@Test
public void refreshTest_0() throws SQLException {
MockDriver mockDriver = new MockDriver(columnMetas, indexMetas);
DruidDataSource druidDataSource = new DruidDataSource();
druidDataSource.setUrl("jdbc:mock:xxx");
druidDataSource.setDriver(mockDriver);
DataSourceProxy dataSourceProxy = new DataSourceProxy(druidDataSource);
TableMeta tableMeta = getTableMetaCache().getTableMeta(dataSourceProxy.getPlainConnection(), "t1",
dataSourceProxy.getResourceId());
//change the columns meta
columnMetas =
new Object[][] {
new Object[] {"", "", "t1", "id", Types.INTEGER, "INTEGER", 64, 0, 10, 1, "", "", 0, 0, 64, 1, "NO", "YES"},
new Object[] {"", "", "t1", "name1", Types.VARCHAR, "VARCHAR", 65, 0, 10, 0, "", "", 0, 0, 64, 2, "YES",
"NO"},
new Object[] {"", "", "t1", "name2", Types.VARCHAR, "VARCHAR", 64, 0, 10, 0, "", "", 0, 0, 64, 3, "YES",
"NO"},
new Object[] {"", "", "t1", "name3", Types.VARCHAR, "VARCHAR", 64, 0, 10, 0, "", "", 0, 0, 64, 4, "YES",
"NO"}
};
mockDriver.setMockColumnsMetasReturnValue(columnMetas);
getTableMetaCache().refresh(dataSourceProxy.getPlainConnection(), dataSourceProxy.getResourceId());
}
|
#vulnerable code
@Test
public void refreshTest_0() {
MockDriver mockDriver = new MockDriver(columnMetas, indexMetas);
DruidDataSource druidDataSource = new DruidDataSource();
druidDataSource.setUrl("jdbc:mock:xxx");
druidDataSource.setDriver(mockDriver);
DataSourceProxy dataSourceProxy = new DataSourceProxy(druidDataSource);
TableMeta tableMeta = getTableMetaCache().getTableMeta(dataSourceProxy, "t1");
//change the columns meta
columnMetas =
new Object[][] {
new Object[] {"", "", "t1", "id", Types.INTEGER, "INTEGER", 64, 0, 10, 1, "", "", 0, 0, 64, 1, "NO", "YES"},
new Object[] {"", "", "t1", "name1", Types.VARCHAR, "VARCHAR", 65, 0, 10, 0, "", "", 0, 0, 64, 2, "YES",
"NO"},
new Object[] {"", "", "t1", "name2", Types.VARCHAR, "VARCHAR", 64, 0, 10, 0, "", "", 0, 0, 64, 3, "YES",
"NO"},
new Object[] {"", "", "t1", "name3", Types.VARCHAR, "VARCHAR", 64, 0, 10, 0, "", "", 0, 0, 64, 4, "YES",
"NO"}
};
mockDriver.setMockColumnsMetasReturnValue(columnMetas);
getTableMetaCache().refresh(dataSourceProxy);
}
#location 24
#vulnerability type RESOURCE_LEAK
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
@Override
public void addConfigListener(String dataId, ConfigChangeListener listener) {
configListenersMap.putIfAbsent(dataId, new ArrayList<>());
configChangeNotifiersMap.putIfAbsent(dataId, new ArrayList<>());
ConfigChangeNotifier configChangeNotifier = new ConfigChangeNotifier(dataId, listener);
configChangeNotifiersMap.get(dataId).add(configChangeNotifier);
if (null != listener.getExecutor()) {
listener.getExecutor().submit(configChangeNotifier);
} else {
consulNotifierExecutor.submit(configChangeNotifier);
}
}
|
#vulnerable code
@Override
public void addConfigListener(String dataId, ConfigChangeListener listener) {
configListenersMap.putIfAbsent(dataId, new ArrayList<>());
configChangeNotifiersMap.putIfAbsent(dataId, new ArrayList<>());
ConfigChangeNotifier configChangeNotifier = new ConfigChangeNotifier(dataId, listener);
configChangeNotifiersMap.get(dataId).add(configChangeNotifier);
if (null != listener.getExecutor()) {
listener.getExecutor().submit(configChangeNotifier);
} else {
consulConfigExecutor.submit(configChangeNotifier);
}
}
#location 6
#vulnerability type THREAD_SAFETY_VIOLATION
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
@Override
public boolean removeConfig(String dataId, long timeoutMills) {
ConfigFuture configFuture = new ConfigFuture(dataId, null, ConfigOperation.REMOVE, timeoutMills);
configOperateExecutor.submit(new ConfigOperateRunnable(configFuture));
return (Boolean)configFuture.get(timeoutMills, TimeUnit.MILLISECONDS);
}
|
#vulnerable code
@Override
public boolean removeConfig(String dataId, long timeoutMills) {
ConfigFuture configFuture = new ConfigFuture(dataId, null, ConfigOperation.REMOVE, timeoutMills);
configOperateExecutor.submit(new ConfigOperateRunnable(configFuture));
return (Boolean)configFuture.get();
}
#location 5
#vulnerability type NULL_DEREFERENCE
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
public void registerResource(String resourceGroupId, String resourceId) {
if (LOGGER.isInfoEnabled()) {
LOGGER.info("register to RM resourceId:{}", resourceId);
}
if (getClientChannelManager().getChannels().isEmpty()) {
getClientChannelManager().reconnect(transactionServiceGroup);
return;
}
synchronized (getClientChannelManager().getChannels()) {
for (Map.Entry<String, Channel> entry : getClientChannelManager().getChannels().entrySet()) {
String serverAddress = entry.getKey();
Channel rmChannel = entry.getValue();
if (LOGGER.isInfoEnabled()) {
LOGGER.info("register resource, resourceId:{}", resourceId);
}
sendRegisterMessage(serverAddress, rmChannel, resourceId);
}
}
}
|
#vulnerable code
public void registerResource(String resourceGroupId, String resourceId) {
if (LOGGER.isInfoEnabled()) {
LOGGER.info("register to RM resourceId:" + resourceId);
}
if (getClientChannelManager().getChannels().isEmpty()) {
getClientChannelManager().reconnect(transactionServiceGroup);
return;
}
synchronized (getClientChannelManager().getChannels()) {
for (Map.Entry<String, Channel> entry : getClientChannelManager().getChannels().entrySet()) {
String serverAddress = entry.getKey();
Channel rmChannel = entry.getValue();
if (LOGGER.isInfoEnabled()) {
LOGGER.info("register resource, resourceId:" + resourceId);
}
sendRegisterMessage(serverAddress, rmChannel, resourceId);
}
}
}
#location 6
#vulnerability type THREAD_SAFETY_VIOLATION
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
@Override
public BranchStatus branchRollback(BranchType branchType, String xid, long branchId, String resourceId,
String applicationData) throws TransactionException {
try {
BranchRollbackRequest request = new BranchRollbackRequest();
request.setXid(xid);
request.setBranchId(branchId);
request.setResourceId(resourceId);
request.setApplicationData(applicationData);
request.setBranchType(branchType);
GlobalSession globalSession = SessionHolder.findGlobalSession(xid);
if (globalSession == null) {
return BranchStatus.PhaseTwo_Rollbacked;
}
if (BranchType.SAGA.equals(branchType)) {
Map<String, Channel> channels = ChannelManager.getRmChannels();
if (channels == null || channels.size() == 0) {
LOGGER.error(
"Failed to rollback SAGA global[" + globalSession.getXid() + ", RM channels is empty.");
return BranchStatus.PhaseTwo_RollbackFailed_Retryable;
}
String sagaResourceId = globalSession.getApplicationId() + "#" + globalSession
.getTransactionServiceGroup();
Channel sagaChannel = channels.get(sagaResourceId);
if (sagaChannel == null) {
LOGGER.error("Failed to rollback SAGA global[" + globalSession.getXid()
+ ", cannot find channel by resourceId[" + sagaResourceId + "]");
return BranchStatus.PhaseTwo_RollbackFailed_Retryable;
}
BranchRollbackResponse response = (BranchRollbackResponse) messageSender.sendSyncRequest(sagaChannel,
request);
return response.getBranchStatus();
} else {
BranchSession branchSession = globalSession.getBranch(branchId);
if (null != branchSession) {
BranchRollbackResponse response = (BranchRollbackResponse) messageSender.sendSyncRequest(resourceId,
branchSession.getClientId(), request);
return response.getBranchStatus();
} else {
return BranchStatus.PhaseTwo_Rollbacked;
}
}
} catch (IOException | TimeoutException e) {
throw new BranchTransactionException(FailedToSendBranchRollbackRequest,
String.format("Send branch rollback failed, xid = %s branchId = %s", xid, branchId), e);
}
}
|
#vulnerable code
@Override
public BranchStatus branchRollback(BranchType branchType, String xid, long branchId, String resourceId,
String applicationData) throws TransactionException {
try {
BranchRollbackRequest request = new BranchRollbackRequest();
request.setXid(xid);
request.setBranchId(branchId);
request.setResourceId(resourceId);
request.setApplicationData(applicationData);
request.setBranchType(branchType);
GlobalSession globalSession = SessionHolder.findGlobalSession(xid);
if (globalSession == null) {
return BranchStatus.PhaseTwo_Rollbacked;
}
if (BranchType.SAGA.equals(branchType)) {
Map<String, Channel> channels = ChannelManager.getRmChannels();
if (channels == null || channels.size() == 0) {
LOGGER.error(
"Failed to rollback SAGA global[" + globalSession.getXid() + ", RM channels is empty.");
return BranchStatus.PhaseTwo_RollbackFailed_Retryable;
}
String sagaResourceId = globalSession.getApplicationId() + "#" + globalSession
.getTransactionServiceGroup();
Channel sagaChannel = channels.get(sagaResourceId);
if (sagaChannel == null) {
LOGGER.error("Failed to rollback SAGA global[" + globalSession.getXid()
+ ", cannot find channel by resourceId[" + sagaResourceId + "]");
return BranchStatus.PhaseTwo_RollbackFailed_Retryable;
}
BranchRollbackResponse response = (BranchRollbackResponse)messageSender.sendSyncRequest(sagaChannel,
request);
return response.getBranchStatus();
} else {
BranchSession branchSession = globalSession.getBranch(branchId);
BranchRollbackResponse response = (BranchRollbackResponse)messageSender.sendSyncRequest(resourceId,
branchSession.getClientId(), request);
return response.getBranchStatus();
}
} catch (IOException | TimeoutException e) {
throw new BranchTransactionException(FailedToSendBranchRollbackRequest,
String.format("Send branch rollback failed, xid = %s branchId = %s", xid, branchId), e);
}
}
#location 41
#vulnerability type NULL_DEREFERENCE
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
@Test
public void testReadingEscapedXml() throws Exception {
// given
xmlRecordReader = new XmlRecordReader("website", getDataSource("/websites.xml"));
xmlRecordReader.open();
// when
XmlRecord record1 = xmlRecordReader.readRecord();
XmlRecord record2 = xmlRecordReader.readRecord();
XmlRecord record3 = xmlRecordReader.readRecord();
XmlRecord record4 = xmlRecordReader.readRecord();
XmlRecord record5 = xmlRecordReader.readRecord();
XmlRecord record6 = xmlRecordReader.readRecord();
// then
assertThat(record1.getPayload()).isXmlEqualTo("<website name=\"google\" url=\"http://www.google.com?query=test&sort=asc\"/>");
assertThat(record2.getPayload()).isXmlEqualTo("<website name=\"l'equipe\" url=\"http://www.lequipe.fr\"/>");
assertThat(record3.getPayload()).isXmlEqualTo("<website name=\"l"internaute.com\" url=\"http://www.linternaute.com\"/>");
assertThat(record4.getPayload()).isXmlEqualTo("<website name=\"google\">http://www.google.com?query=test&sort=asc</website>");
assertThat(record5.getPayload()).isXmlEqualTo("<website name=\"test\"><test>foo</test></website>");
assertThat(record6).isNull();
}
|
#vulnerable code
@Test
public void testReadingEscapedXml() throws Exception {
xmlRecordReader.close();
xmlRecordReader = new XmlRecordReader("website", getDataSource("/websites.xml"));
xmlRecordReader.open();
XmlRecord record = xmlRecordReader.readRecord();
assertThat(record.getPayload()).isXmlEqualTo("<website name=\"google\" url=\"http://www.google.com?query=test&sort=asc\"/>");
record = xmlRecordReader.readRecord();
assertThat(record.getPayload()).isXmlEqualTo("<website name=\"l'equipe\" url=\"http://www.lequipe.fr\"/>");
record = xmlRecordReader.readRecord();
assertThat(record.getPayload()).isXmlEqualTo("<website name=\"l"internaute.com\" url=\"http://www.linternaute.com\"/>");
record = xmlRecordReader.readRecord();
assertThat(record.getPayload()).isXmlEqualTo("<website name=\"google\">http://www.google.com?query=test&sort=asc</website>");
record = xmlRecordReader.readRecord();
assertThat(record.getPayload()).isXmlEqualTo("<website name=\"test\"><test>foo</test></website>");
record = xmlRecordReader.readRecord();
assertThat(record).isNull();
}
#location 16
#vulnerability type NULL_DEREFERENCE
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
public static void main(String[] args) throws Exception {
String fruits = "1,apple\n2,orange\n3,banana\n4,apple\n5,pear";
// Create queues
BlockingQueue<Record> appleQueue = new LinkedBlockingQueue<Record>();
BlockingQueue<Record> orangeQueue = new LinkedBlockingQueue<Record>();
BlockingQueue<Record> defaultQueue = new LinkedBlockingQueue<Record>();
// Create a content based record dispatcher to dispatch records to according queues based on their content
ContentBasedRecordDispatcher recordDispatcher = new ContentBasedRecordDispatcherBuilder()
.when(new AppleRecordPredicate()).dispatchTo(appleQueue)
.when(new OrangeRecordPredicate()).dispatchTo(orangeQueue)
.otherwise(defaultQueue)
.build();
// Build a master engine that will read records from the data source and dispatch them to worker engines
Engine masterEngine = aNewEngine()
.reader(new StringRecordReader(fruits))
.processor(recordDispatcher)
.batchProcessEventListener(new PoisonRecordBroadcaster(recordDispatcher))
.build();
// Build easy batch engines
Engine workerEngine1 = buildWorkerEngine(appleQueue);
Engine workerEngine2 = buildWorkerEngine(orangeQueue);
Engine workerEngine3 = buildWorkerEngine(defaultQueue);
// Create a threads pool to call Easy Batch engines in parallel
ExecutorService executorService = Executors.newFixedThreadPool(THREAD_POOL_SIZE);
// Submit master and worker engines to executor service
executorService.submit(masterEngine);
executorService.submit(workerEngine1);
executorService.submit(workerEngine2);
executorService.submit(workerEngine3);
// Shutdown executor service
executorService.shutdown();
}
|
#vulnerable code
public static void main(String[] args) throws Exception {
//Create queues
BlockingQueue<Record> appleQueue = new LinkedBlockingQueue<Record>();
BlockingQueue<Record> orangeQueue = new LinkedBlockingQueue<Record>();
BlockingQueue<Record> defaultQueue = new LinkedBlockingQueue<Record>();
// Build easy batch engines
Engine engine1 = buildBatchEngine(appleQueue);
Engine engine2 = buildBatchEngine(orangeQueue);
Engine engine3 = buildBatchEngine(defaultQueue);
//create a 3 threads pool to call Easy Batch engines in parallel
ExecutorService executorService = Executors.newFixedThreadPool(3);
//submit workers to executor service
Future<Report> reportFuture1 = executorService.submit(engine1);
Future<Report> reportFuture2 = executorService.submit(engine2);
Future<Report> reportFuture3 = executorService.submit(engine3);
//create a content based record dispatcher to dispatch records to previously created queues
RecordDispatcher recordDispatcher = new ContentBasedRecordDispatcherBuilder()
.when(new AppleRecordPredicate()).dispatchTo(appleQueue)
.when(new OrangeRecordPredicate()).dispatchTo(orangeQueue)
.otherwise(defaultQueue)
.build();
//read data source and dispatch record to queues based on their content
StringRecordReader stringRecordReader = new StringRecordReader("1,apple\n2,orange\n3,banana\n4,apple\n5,pear");
stringRecordReader.open();
while (stringRecordReader.hasNextRecord()) {
Record record = stringRecordReader.readNextRecord();
recordDispatcher.dispatchRecord(record);
}
stringRecordReader.close();
//send poison records when all input data has been dispatched to workers
recordDispatcher.dispatchRecord(new PoisonRecord());
//wait for easy batch instances termination and get partial reports
Report report1 = reportFuture1.get();
Report report2 = reportFuture2.get();
Report report3 = reportFuture3.get();
//merge partial reports into a global one
ReportMerger reportMerger = new DefaultReportMerger();
Report finalReport = reportMerger.mergerReports(report1, report2, report3);
System.out.println(finalReport);
//shutdown executor service
executorService.shutdown();
}
#location 35
#vulnerability type RESOURCE_LEAK
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
public static void main(String[] args) throws Exception {
// Input file tweets.csv
File tweets = new File(args[0]);
// Create queues
BlockingQueue<Record> queue1 = new LinkedBlockingQueue<Record>();
BlockingQueue<Record> queue2 = new LinkedBlockingQueue<Record>();
// Create a round robin record dispatcher that will be used to distribute records to worker engines
RoundRobinRecordDispatcher roundRobinRecordDispatcher = new RoundRobinRecordDispatcher(Arrays.asList(queue1, queue2));
// Build a master engine that will read records from the data source and dispatch them to worker engines
Engine masterEngine = aNewEngine()
.reader(new FlatFileRecordReader(tweets))
.processor(roundRobinRecordDispatcher)
.batchProcessEventListener(new PoisonRecordBroadcaster(roundRobinRecordDispatcher))
.build();
// Build worker engines
Engine workerEngine1 = buildWorkerEngine(queue1);
Engine workerEngine2 = buildWorkerEngine(queue2);
// Create a thread pool to call master and worker engines in parallel
ExecutorService executorService = Executors.newFixedThreadPool(THREAD_POOL_SIZE);
// Submit workers to executor service
executorService.submit(masterEngine);
executorService.submit(workerEngine1);
executorService.submit(workerEngine2);
// Shutdown executor service
executorService.shutdown();
}
|
#vulnerable code
public static void main(String[] args) throws Exception {
// Input file tweets.csv
File tweets = new File(args[0]);
//Create queues
BlockingQueue<Record> queue1 = new LinkedBlockingQueue<Record>();
BlockingQueue<Record> queue2 = new LinkedBlockingQueue<Record>();
// Build easy batch engines
Engine engine1 = buildBatchEngine(queue1);
Engine engine2 = buildBatchEngine(queue2);
//create a 2 threads pool to call engines in parallel
ExecutorService executorService = Executors.newFixedThreadPool(THREAD_POOL_SIZE);
//submit workers to executor service
Future<Report> reportFuture1 = executorService.submit(engine1);
Future<Report> reportFuture2 = executorService.submit(engine2);
//create a record dispatcher to dispatch records to previously created queues
RecordDispatcher recordDispatcher = new RoundRobinRecordDispatcher(Arrays.asList(queue1, queue2));
//read data source and dispatch records to queues in round-robin fashion
FlatFileRecordReader flatFileRecordReader = new FlatFileRecordReader(tweets);
flatFileRecordReader.open();
while (flatFileRecordReader.hasNextRecord()) {
Record record = flatFileRecordReader.readNextRecord();
recordDispatcher.dispatchRecord(record);
}
flatFileRecordReader.close();
//send poison records when all input data has been dispatched to workers
recordDispatcher.dispatchRecord(new PoisonRecord());
//wait for easy batch instances termination and get partial reports
Report report1 = reportFuture1.get();
Report report2 = reportFuture2.get();
//merge partial reports into a global one
ReportMerger reportMerger = new DefaultReportMerger();
Report finalReport = reportMerger.mergerReports(report1, report2);
System.out.println(finalReport);
//shutdown executor service
executorService.shutdown();
}
#location 30
#vulnerability type RESOURCE_LEAK
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
public void configure() throws BatchConfigurationException {
/*
* Configure CB4J logger
*/
configureCB4JLogger();
logger.info("Configuration started at : " + new Date());
/*
* Configure record reader
*/
configureRecordReader();
/*
* Configure record parser
*/
configureRecordParser();
/*
* Configure loggers for ignored/rejected records
*/
configureIgnoredAndRejectedRecordsLoggers();
/*
* Configure batch reporter : if no custom reporter registered, use default implementation
*/
if (batchReporter == null) {
batchReporter = new DefaultBatchReporterImpl();
}
/*
* Configure record validator with provided validators : if no custom validator registered, use default implementation
*/
if (recordValidator == null) {
recordValidator = new DefaultRecordValidatorImpl(fieldValidators);
}
/*
* Check record mapper
*/
if (recordMapper == null) {
String error = "Configuration failed : no record mapper registered";
logger.severe(error);
throw new BatchConfigurationException(error);
}
/*
* Check record processor
*/
if (recordProcessor == null) {
String error = "Configuration failed : no record processor registered";
logger.severe(error);
throw new BatchConfigurationException(error);
}
/*
* register JMX MBean
*/
configureJmxMBean();
logger.info("Configuration successful");
logger.info("Configuration parameters details : " + configurationProperties);
}
|
#vulnerable code
public void configure() throws BatchConfigurationException {
/*
* Configure CB4J logger
*/
logger.setUseParentHandlers(false);
ConsoleHandler consoleHandler = new ConsoleHandler();
consoleHandler.setFormatter(new LogFormatter());
logger.addHandler(consoleHandler);
logger.info("Configuration started at : " + new Date());
/*
* Configure record reader parameters
*/
String inputData = configurationProperties.getProperty(BatchConstants.INPUT_DATA_PATH);
String encoding = configurationProperties.getProperty(BatchConstants.INPUT_DATA_ENCODING);
final String skipHeaderProperty = configurationProperties.getProperty(BatchConstants.INPUT_DATA_SKIP_HEADER);
//check if input data file is specified
if (inputData == null) {
String error = "Configuration failed : input data file is mandatory but was not specified";
logger.severe(error);
throw new BatchConfigurationException(error);
}
try {
boolean skipHeader;
if (skipHeaderProperty != null) {
skipHeader = Boolean.valueOf(skipHeaderProperty);
} else {
skipHeader = BatchConstants.DEFAULT_SKIP_HEADER;
logger.warning("Skip header property not specified, default to false");
}
if (encoding == null || (encoding != null && encoding.length() == 0)) {
encoding = System.getProperty("file.encoding");
logger.warning("No encoding specified for input data, using system default encoding : " + encoding);
} else {
if (Charset.availableCharsets().get(encoding) != null && !Charset.isSupported(encoding)) {
logger.warning("Encoding '" + encoding + "' not supported, using system default encoding : " + System.getProperty("file.encoding"));
encoding = System.getProperty("file.encoding");
} else {
logger.config("Using '" + encoding + "' encoding for input file reading");
}
}
recordReader = new RecordReaderImpl(inputData, encoding, skipHeader);
logger.config("Data input file : " + inputData);
} catch (FileNotFoundException e) {
String error = "Configuration failed : input data file '" + inputData + "' could not be opened";
logger.severe(error);
throw new BatchConfigurationException(error);
}
/*
* Configure record parser parameters
* Convention over configuration : default separator is ","
*/
String recordSizeProperty = configurationProperties.getProperty(BatchConstants.INPUT_RECORD_SIZE);
try {
if (recordSizeProperty == null || (recordSizeProperty != null && recordSizeProperty.length() == 0)) {
String error = "Record size property is not set";
logger.severe(error);
throw new BatchConfigurationException(error);
}
int recordSize = Integer.parseInt(recordSizeProperty);
String fieldsSeparator = configurationProperties.getProperty(BatchConstants.INPUT_FIELD_SEPARATOR);
if (fieldsSeparator == null || (fieldsSeparator != null && fieldsSeparator.length() == 0)) {
fieldsSeparator = BatchConstants.DEFAULT_FIELD_SEPARATOR;
logger.warning("No field separator specified, using default : '" + fieldsSeparator + "'");
}
logger.config("Record size specified : " + recordSize);
logger.config("Fields separator specified : '" + fieldsSeparator + "'");
recordParser = new RecordParserImpl(recordSize, fieldsSeparator);
} catch (NumberFormatException e) {
String error = "Record size property is not recognized as a number : " + recordSizeProperty;
logger.severe(error);
throw new BatchConfigurationException(error);
}
/*
* Configure loggers for ignored/rejected records
*/
ReportFormatter reportFormatter = new ReportFormatter();
String outputIgnored = configurationProperties.getProperty(BatchConstants.OUTPUT_DATA_IGNORED);
if (outputIgnored == null || (outputIgnored != null && outputIgnored.length() == 0)) {
outputIgnored = BatchConfigurationUtil.removeExtension(inputData) + BatchConstants.DEFAULT_IGNORED_SUFFIX;
logger.warning("No log file specified for ignored records, using default : " + outputIgnored);
}
try {
FileHandler ignoredRecordsHandler = new FileHandler(outputIgnored);
ignoredRecordsHandler.setFormatter(reportFormatter);
Logger ignoredRecordsReporter = Logger.getLogger(BatchConstants.LOGGER_CB4J_IGNORED);
ignoredRecordsReporter.addHandler(ignoredRecordsHandler);
} catch (IOException e) {
String error = "Unable to use file for ignored records : " + outputIgnored;
logger.severe(error);
throw new BatchConfigurationException(error);
}
String outputRejected = configurationProperties.getProperty(BatchConstants.OUTPUT_DATA_REJECTED);
if (outputRejected == null || (outputRejected != null && outputRejected.length() == 0)) {
outputRejected = BatchConfigurationUtil.removeExtension(inputData) + BatchConstants.DEFAULT_REJECTED_SUFFIX;
logger.warning("No log file specified for rejected records, using default : " + outputRejected);
}
try {
FileHandler rejectedRecordsHandler = new FileHandler(outputRejected);
rejectedRecordsHandler.setFormatter(reportFormatter);
Logger rejectedRecordsReporter = Logger.getLogger(BatchConstants.LOGGER_CB4J_REJECTED);
rejectedRecordsReporter.addHandler(rejectedRecordsHandler);
} catch (IOException e) {
String error = "Unable to use file for rejected records : " + outputRejected;
logger.severe(error);
throw new BatchConfigurationException(error);
}
/*
* Configure batch reporter : if no custom reporter registered, use default implementation
*/
if (batchReporter == null) {
batchReporter = new DefaultBatchReporterImpl();
}
/*
* Configure record validator with provided validators : : if no custom validator registered, use default implementation
*/
if (recordValidator == null) {
recordValidator = new DefaultRecordValidatorImpl(fieldValidators);
}
/*
* Check record mapper
*/
if (recordMapper == null) {
String error = "Configuration failed : no record mapper registered";
logger.severe(error);
throw new BatchConfigurationException(error);
}
/*
* Check record processor
*/
if (recordProcessor == null) {
String error = "Configuration failed : no record processor registered";
logger.severe(error);
throw new BatchConfigurationException(error);
}
/*
* Configure JMX MBean
*/
MBeanServer mbs = ManagementFactory.getPlatformMBeanServer();
ObjectName name;
try {
name = new ObjectName("net.benas.cb4j.jmx:type=BatchMonitorMBean");
BatchMonitorMBean batchMonitorMBean = new BatchMonitor(batchReporter);
mbs.registerMBean(batchMonitorMBean, name);
logger.info("CB4J JMX MBean registered successfully as: " + name.getCanonicalName());
} catch (Exception e) {
String error = "Unable to register CB4J JMX MBean. Root exception is :" + e.getMessage();
logger.warning(error);
}
logger.info("Configuration successful");
logger.info("Configuration parameters details : " + configurationProperties);
}
#location 48
#vulnerability type RESOURCE_LEAK
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
@Override
public void open() throws Exception {
currentRecordNumber = 0;
scanner = new Scanner(input, charsetName);
}
|
#vulnerable code
@Override
public void open() throws Exception {
currentRecordNumber = 0;
scanner = new Scanner(new FileInputStream(input), charsetName);
}
#location 4
#vulnerability type RESOURCE_LEAK
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
public static void main(String[] args) throws Exception {
// Input file tweets.csv
File tweets = new File(args[0]);
// Create queues
BlockingQueue<Record> queue1 = new LinkedBlockingQueue<Record>();
BlockingQueue<Record> queue2 = new LinkedBlockingQueue<Record>();
// Create a round robin record dispatcher that will be used to distribute records to worker engines
RoundRobinRecordDispatcher roundRobinRecordDispatcher = new RoundRobinRecordDispatcher(Arrays.asList(queue1, queue2));
// Build a master engine that will read records from the data source and dispatch them to worker engines
Engine masterEngine = aNewEngine()
.reader(new FlatFileRecordReader(tweets))
.processor(roundRobinRecordDispatcher)
.batchProcessEventListener(new PoisonRecordBroadcaster(roundRobinRecordDispatcher))
.build();
// Build worker engines
Engine workerEngine1 = buildWorkerEngine(queue1);
Engine workerEngine2 = buildWorkerEngine(queue2);
// Create a thread pool to call master and worker engines in parallel
ExecutorService executorService = Executors.newFixedThreadPool(THREAD_POOL_SIZE);
// Submit workers to executor service
executorService.submit(masterEngine);
executorService.submit(workerEngine1);
executorService.submit(workerEngine2);
// Shutdown executor service
executorService.shutdown();
}
|
#vulnerable code
public static void main(String[] args) throws Exception {
// Input file tweets.csv
File tweets = new File(args[0]);
//Create queues
BlockingQueue<Record> queue1 = new LinkedBlockingQueue<Record>();
BlockingQueue<Record> queue2 = new LinkedBlockingQueue<Record>();
// Build easy batch engines
Engine engine1 = buildBatchEngine(queue1);
Engine engine2 = buildBatchEngine(queue2);
//create a 2 threads pool to call engines in parallel
ExecutorService executorService = Executors.newFixedThreadPool(THREAD_POOL_SIZE);
//submit workers to executor service
Future<Report> reportFuture1 = executorService.submit(engine1);
Future<Report> reportFuture2 = executorService.submit(engine2);
//create a record dispatcher to dispatch records to previously created queues
RecordDispatcher recordDispatcher = new RoundRobinRecordDispatcher(Arrays.asList(queue1, queue2));
//read data source and dispatch records to queues in round-robin fashion
FlatFileRecordReader flatFileRecordReader = new FlatFileRecordReader(tweets);
flatFileRecordReader.open();
while (flatFileRecordReader.hasNextRecord()) {
Record record = flatFileRecordReader.readNextRecord();
recordDispatcher.dispatchRecord(record);
}
flatFileRecordReader.close();
//send poison records when all input data has been dispatched to workers
recordDispatcher.dispatchRecord(new PoisonRecord());
//wait for easy batch instances termination and get partial reports
Report report1 = reportFuture1.get();
Report report2 = reportFuture2.get();
//merge partial reports into a global one
ReportMerger reportMerger = new DefaultReportMerger();
Report finalReport = reportMerger.mergerReports(report1, report2);
System.out.println(finalReport);
//shutdown executor service
executorService.shutdown();
}
#location 31
#vulnerability type RESOURCE_LEAK
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
@Test
public void testXmlRecordReading() throws Exception {
// given
dataSource = new File("src/test/resources/data.xml");
xmlFileRecordReader = new XmlFileRecordReader(dataSource, "data");
xmlFileRecordReader.open();
String expectedDataSourceName = dataSource.getAbsolutePath();
// when
XmlRecord xmlRecord1 = xmlFileRecordReader.readRecord();
XmlRecord xmlRecord2 = xmlFileRecordReader.readRecord();
XmlRecord xmlRecord3 = xmlFileRecordReader.readRecord();
XmlRecord xmlRecord4 = xmlFileRecordReader.readRecord();
// then
assertThat(xmlRecord1.getHeader().getNumber()).isEqualTo(1L);
assertThat(xmlRecord1.getHeader().getSource()).isEqualTo(expectedDataSourceName);
assertThat(xmlRecord1.getPayload()).isEqualTo("<data>1</data>");
assertThat(xmlRecord2.getHeader().getNumber()).isEqualTo(2L);
assertThat(xmlRecord2.getHeader().getSource()).isEqualTo(expectedDataSourceName);
assertThat(xmlRecord2.getPayload()).isEqualTo("<data>2</data>");
assertThat(xmlRecord3.getHeader().getNumber()).isEqualTo(3L);
assertThat(xmlRecord3.getHeader().getSource()).isEqualTo(expectedDataSourceName);
assertThat(xmlRecord3.getPayload()).isEqualTo("<data>3</data>");
assertThat(xmlRecord4).isNull();
}
|
#vulnerable code
@Test
public void testXmlRecordReading() throws Exception {
String expectedDataSourceName = dataSource.getAbsolutePath();
XmlRecord xmlRecord = xmlFileRecordReader.readRecord();
assertThat(xmlRecord.getHeader().getNumber()).isEqualTo(1L);
assertThat(xmlRecord.getHeader().getSource()).isEqualTo(expectedDataSourceName);
assertThat(xmlRecord.getPayload()).isEqualTo("<data>1</data>");
xmlRecord = xmlFileRecordReader.readRecord();
assertThat(xmlRecord.getHeader().getNumber()).isEqualTo(2L);
assertThat(xmlRecord.getHeader().getSource()).isEqualTo(expectedDataSourceName);
assertThat(xmlRecord.getPayload()).isEqualTo("<data>2</data>");
xmlRecord = xmlFileRecordReader.readRecord();
assertThat(xmlRecord.getHeader().getNumber()).isEqualTo(3L);
assertThat(xmlRecord.getHeader().getSource()).isEqualTo(expectedDataSourceName);
assertThat(xmlRecord.getPayload()).isEqualTo("<data>3</data>");
xmlRecord = xmlFileRecordReader.readRecord();
assertThat(xmlRecord.getHeader().getNumber()).isEqualTo(4L);
assertThat(xmlRecord.getHeader().getSource()).isEqualTo(expectedDataSourceName);
assertThat(xmlRecord.getPayload()).isEqualTo("<data>4</data>");
xmlRecord = xmlFileRecordReader.readRecord();
assertThat(xmlRecord.getHeader().getNumber()).isEqualTo(5L);
assertThat(xmlRecord.getHeader().getSource()).isEqualTo(expectedDataSourceName);
assertThat(xmlRecord.getPayload()).isEqualTo("<data>5</data>");
xmlRecord = xmlFileRecordReader.readRecord();
assertThat(xmlRecord).isNull();
}
#location 26
#vulnerability type NULL_DEREFERENCE
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
@Override
public StringRecord processRecord(final Record<P> record) throws Exception {
StringWriter stringWriter = new StringWriter();
CSVPrinter csvPrinter = new CSVPrinter(stringWriter, csvFormat);
Iterable<Object> iterable = fieldExtractor.extractFields(record.getPayload());
csvPrinter.printRecord(iterable);
csvPrinter.flush();
csvPrinter.close();
return new StringRecord(record.getHeader(), stringWriter.toString());
}
|
#vulnerable code
@Override
public StringRecord processRecord(final Record<P> record) throws Exception {
StringWriter stringWriter = new StringWriter();
CSVPrinter csvPrinter = new CSVPrinter(stringWriter, csvFormat);
Iterable<Object> iterable = fieldExtractor.extractFields(record.getPayload());
csvPrinter.printRecord(iterable);
csvPrinter.flush();
return new StringRecord(record.getHeader(), stringWriter.toString());
}
#location 7
#vulnerability type RESOURCE_LEAK
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
@Test
public void testReadingXmlWithCustomNamespace() throws Exception {
// given
xmlRecordReader = new XmlRecordReader("bean", getDataSource("/beans.xml"));
xmlRecordReader.open();
// when
XmlRecord record1 = xmlRecordReader.readRecord();
XmlRecord record2 = xmlRecordReader.readRecord();
XmlRecord record3 = xmlRecordReader.readRecord();
// then
assertThat(record1.getPayload()).isXmlEqualTo("<bean id=\"foo\" class=\"java.lang.String\"><description>foo bean</description></bean>");
assertThat(record2.getPayload()).isXmlEqualTo("<bean id=\"bar\" class=\"java.lang.String\"/>");
assertThat(record3).isNull();
}
|
#vulnerable code
@Test
public void testReadingXmlWithCustomNamespace() throws Exception {
xmlRecordReader.close();
xmlRecordReader = new XmlRecordReader("bean", getDataSource("/beans.xml"));
xmlRecordReader.open();
XmlRecord record = xmlRecordReader.readRecord();
assertThat(record.getPayload()).isXmlEqualTo("<bean id=\"foo\" class=\"java.lang.String\"><description>foo bean</description></bean>");
record = xmlRecordReader.readRecord();
assertThat(record.getPayload()).isXmlEqualTo("<bean id=\"bar\" class=\"java.lang.String\"/>");
record = xmlRecordReader.readRecord();
assertThat(record).isNull();
}
#location 11
#vulnerability type NULL_DEREFERENCE
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
@Test
public void testReadingEscapedXml() throws Exception {
// given
xmlRecordReader = new XmlRecordReader("website", getDataSource("/websites.xml"));
xmlRecordReader.open();
// when
XmlRecord record1 = xmlRecordReader.readRecord();
XmlRecord record2 = xmlRecordReader.readRecord();
XmlRecord record3 = xmlRecordReader.readRecord();
XmlRecord record4 = xmlRecordReader.readRecord();
XmlRecord record5 = xmlRecordReader.readRecord();
XmlRecord record6 = xmlRecordReader.readRecord();
// then
assertThat(record1.getPayload()).isXmlEqualTo("<website name=\"google\" url=\"http://www.google.com?query=test&sort=asc\"/>");
assertThat(record2.getPayload()).isXmlEqualTo("<website name=\"l'equipe\" url=\"http://www.lequipe.fr\"/>");
assertThat(record3.getPayload()).isXmlEqualTo("<website name=\"l"internaute.com\" url=\"http://www.linternaute.com\"/>");
assertThat(record4.getPayload()).isXmlEqualTo("<website name=\"google\">http://www.google.com?query=test&sort=asc</website>");
assertThat(record5.getPayload()).isXmlEqualTo("<website name=\"test\"><test>foo</test></website>");
assertThat(record6).isNull();
}
|
#vulnerable code
@Test
public void testReadingEscapedXml() throws Exception {
xmlRecordReader.close();
xmlRecordReader = new XmlRecordReader("website", getDataSource("/websites.xml"));
xmlRecordReader.open();
XmlRecord record = xmlRecordReader.readRecord();
assertThat(record.getPayload()).isXmlEqualTo("<website name=\"google\" url=\"http://www.google.com?query=test&sort=asc\"/>");
record = xmlRecordReader.readRecord();
assertThat(record.getPayload()).isXmlEqualTo("<website name=\"l'equipe\" url=\"http://www.lequipe.fr\"/>");
record = xmlRecordReader.readRecord();
assertThat(record.getPayload()).isXmlEqualTo("<website name=\"l"internaute.com\" url=\"http://www.linternaute.com\"/>");
record = xmlRecordReader.readRecord();
assertThat(record.getPayload()).isXmlEqualTo("<website name=\"google\">http://www.google.com?query=test&sort=asc</website>");
record = xmlRecordReader.readRecord();
assertThat(record.getPayload()).isXmlEqualTo("<website name=\"test\"><test>foo</test></website>");
record = xmlRecordReader.readRecord();
assertThat(record).isNull();
}
#location 19
#vulnerability type NULL_DEREFERENCE
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
@Test
public void testXmlRecordReading() throws Exception {
// given
dataSource = new File("src/test/resources/data.xml");
xmlFileRecordReader = new XmlFileRecordReader(dataSource, "data");
xmlFileRecordReader.open();
String expectedDataSourceName = dataSource.getAbsolutePath();
// when
XmlRecord xmlRecord1 = xmlFileRecordReader.readRecord();
XmlRecord xmlRecord2 = xmlFileRecordReader.readRecord();
XmlRecord xmlRecord3 = xmlFileRecordReader.readRecord();
XmlRecord xmlRecord4 = xmlFileRecordReader.readRecord();
// then
assertThat(xmlRecord1.getHeader().getNumber()).isEqualTo(1L);
assertThat(xmlRecord1.getHeader().getSource()).isEqualTo(expectedDataSourceName);
assertThat(xmlRecord1.getPayload()).isEqualTo("<data>1</data>");
assertThat(xmlRecord2.getHeader().getNumber()).isEqualTo(2L);
assertThat(xmlRecord2.getHeader().getSource()).isEqualTo(expectedDataSourceName);
assertThat(xmlRecord2.getPayload()).isEqualTo("<data>2</data>");
assertThat(xmlRecord3.getHeader().getNumber()).isEqualTo(3L);
assertThat(xmlRecord3.getHeader().getSource()).isEqualTo(expectedDataSourceName);
assertThat(xmlRecord3.getPayload()).isEqualTo("<data>3</data>");
assertThat(xmlRecord4).isNull();
}
|
#vulnerable code
@Test
public void testXmlRecordReading() throws Exception {
String expectedDataSourceName = dataSource.getAbsolutePath();
XmlRecord xmlRecord = xmlFileRecordReader.readRecord();
assertThat(xmlRecord.getHeader().getNumber()).isEqualTo(1L);
assertThat(xmlRecord.getHeader().getSource()).isEqualTo(expectedDataSourceName);
assertThat(xmlRecord.getPayload()).isEqualTo("<data>1</data>");
xmlRecord = xmlFileRecordReader.readRecord();
assertThat(xmlRecord.getHeader().getNumber()).isEqualTo(2L);
assertThat(xmlRecord.getHeader().getSource()).isEqualTo(expectedDataSourceName);
assertThat(xmlRecord.getPayload()).isEqualTo("<data>2</data>");
xmlRecord = xmlFileRecordReader.readRecord();
assertThat(xmlRecord.getHeader().getNumber()).isEqualTo(3L);
assertThat(xmlRecord.getHeader().getSource()).isEqualTo(expectedDataSourceName);
assertThat(xmlRecord.getPayload()).isEqualTo("<data>3</data>");
xmlRecord = xmlFileRecordReader.readRecord();
assertThat(xmlRecord.getHeader().getNumber()).isEqualTo(4L);
assertThat(xmlRecord.getHeader().getSource()).isEqualTo(expectedDataSourceName);
assertThat(xmlRecord.getPayload()).isEqualTo("<data>4</data>");
xmlRecord = xmlFileRecordReader.readRecord();
assertThat(xmlRecord.getHeader().getNumber()).isEqualTo(5L);
assertThat(xmlRecord.getHeader().getSource()).isEqualTo(expectedDataSourceName);
assertThat(xmlRecord.getPayload()).isEqualTo("<data>5</data>");
xmlRecord = xmlFileRecordReader.readRecord();
assertThat(xmlRecord).isNull();
}
#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 testRecordLimit() throws Exception {
List<String> dataSource = Arrays.asList("foo", "bar", "baz");
JobReport jobReport = aNewJob()
.reader(new IterableRecordReader(dataSource))
.limit(2)
.processor(new RecordCollector())
.call();
assertThat(jobReport.getMetrics().getTotalCount()).isEqualTo(2);
assertThat(jobReport.getMetrics().getSuccessCount()).isEqualTo(2);
List<GenericRecord> records = (List<GenericRecord>) jobReport.getResult();
assertThat(records).extracting("payload").containsExactly("foo", "bar");
}
|
#vulnerable code
@Test
public void testRecordLimit() throws Exception {
List<String> dataSource = Arrays.asList("foo", "bar", "baz");
JobReport jobReport = aNewJob()
.reader(new IterableRecordReader(dataSource))
.limit(2)
.processor(new RecordCollector())
.call();
assertThat(jobReport.getMetrics().getTotalCount()).isEqualTo(2);
assertThat(jobReport.getMetrics().getSuccessCount()).isEqualTo(2);
List<GenericRecord> records = (List<GenericRecord>) jobReport.getResult();
assertThat(records).isNotNull().hasSize(2);
assertThat(records.get(0).getPayload()).isNotNull().isEqualTo("foo");
assertThat(records.get(1).getPayload()).isNotNull().isEqualTo("bar");
}
#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 testReadingEscapedXml() throws Exception {
// given
xmlRecordReader = new XmlRecordReader("website", getDataSource("/websites.xml"));
xmlRecordReader.open();
// when
XmlRecord record1 = xmlRecordReader.readRecord();
XmlRecord record2 = xmlRecordReader.readRecord();
XmlRecord record3 = xmlRecordReader.readRecord();
XmlRecord record4 = xmlRecordReader.readRecord();
XmlRecord record5 = xmlRecordReader.readRecord();
XmlRecord record6 = xmlRecordReader.readRecord();
// then
assertThat(record1.getPayload()).isXmlEqualTo("<website name=\"google\" url=\"http://www.google.com?query=test&sort=asc\"/>");
assertThat(record2.getPayload()).isXmlEqualTo("<website name=\"l'equipe\" url=\"http://www.lequipe.fr\"/>");
assertThat(record3.getPayload()).isXmlEqualTo("<website name=\"l"internaute.com\" url=\"http://www.linternaute.com\"/>");
assertThat(record4.getPayload()).isXmlEqualTo("<website name=\"google\">http://www.google.com?query=test&sort=asc</website>");
assertThat(record5.getPayload()).isXmlEqualTo("<website name=\"test\"><test>foo</test></website>");
assertThat(record6).isNull();
}
|
#vulnerable code
@Test
public void testReadingEscapedXml() throws Exception {
xmlRecordReader.close();
xmlRecordReader = new XmlRecordReader("website", getDataSource("/websites.xml"));
xmlRecordReader.open();
XmlRecord record = xmlRecordReader.readRecord();
assertThat(record.getPayload()).isXmlEqualTo("<website name=\"google\" url=\"http://www.google.com?query=test&sort=asc\"/>");
record = xmlRecordReader.readRecord();
assertThat(record.getPayload()).isXmlEqualTo("<website name=\"l'equipe\" url=\"http://www.lequipe.fr\"/>");
record = xmlRecordReader.readRecord();
assertThat(record.getPayload()).isXmlEqualTo("<website name=\"l"internaute.com\" url=\"http://www.linternaute.com\"/>");
record = xmlRecordReader.readRecord();
assertThat(record.getPayload()).isXmlEqualTo("<website name=\"google\">http://www.google.com?query=test&sort=asc</website>");
record = xmlRecordReader.readRecord();
assertThat(record.getPayload()).isXmlEqualTo("<website name=\"test\"><test>foo</test></website>");
record = xmlRecordReader.readRecord();
assertThat(record).isNull();
}
#location 13
#vulnerability type NULL_DEREFERENCE
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
@Test
public void testXmlRecordReading() throws Exception {
// given
dataSource = new File("src/test/resources/data.xml");
xmlFileRecordReader = new XmlFileRecordReader(dataSource, "data");
xmlFileRecordReader.open();
String expectedDataSourceName = dataSource.getAbsolutePath();
// when
XmlRecord xmlRecord1 = xmlFileRecordReader.readRecord();
XmlRecord xmlRecord2 = xmlFileRecordReader.readRecord();
XmlRecord xmlRecord3 = xmlFileRecordReader.readRecord();
XmlRecord xmlRecord4 = xmlFileRecordReader.readRecord();
// then
assertThat(xmlRecord1.getHeader().getNumber()).isEqualTo(1L);
assertThat(xmlRecord1.getHeader().getSource()).isEqualTo(expectedDataSourceName);
assertThat(xmlRecord1.getPayload()).isEqualTo("<data>1</data>");
assertThat(xmlRecord2.getHeader().getNumber()).isEqualTo(2L);
assertThat(xmlRecord2.getHeader().getSource()).isEqualTo(expectedDataSourceName);
assertThat(xmlRecord2.getPayload()).isEqualTo("<data>2</data>");
assertThat(xmlRecord3.getHeader().getNumber()).isEqualTo(3L);
assertThat(xmlRecord3.getHeader().getSource()).isEqualTo(expectedDataSourceName);
assertThat(xmlRecord3.getPayload()).isEqualTo("<data>3</data>");
assertThat(xmlRecord4).isNull();
}
|
#vulnerable code
@Test
public void testXmlRecordReading() throws Exception {
String expectedDataSourceName = dataSource.getAbsolutePath();
XmlRecord xmlRecord = xmlFileRecordReader.readRecord();
assertThat(xmlRecord.getHeader().getNumber()).isEqualTo(1L);
assertThat(xmlRecord.getHeader().getSource()).isEqualTo(expectedDataSourceName);
assertThat(xmlRecord.getPayload()).isEqualTo("<data>1</data>");
xmlRecord = xmlFileRecordReader.readRecord();
assertThat(xmlRecord.getHeader().getNumber()).isEqualTo(2L);
assertThat(xmlRecord.getHeader().getSource()).isEqualTo(expectedDataSourceName);
assertThat(xmlRecord.getPayload()).isEqualTo("<data>2</data>");
xmlRecord = xmlFileRecordReader.readRecord();
assertThat(xmlRecord.getHeader().getNumber()).isEqualTo(3L);
assertThat(xmlRecord.getHeader().getSource()).isEqualTo(expectedDataSourceName);
assertThat(xmlRecord.getPayload()).isEqualTo("<data>3</data>");
xmlRecord = xmlFileRecordReader.readRecord();
assertThat(xmlRecord.getHeader().getNumber()).isEqualTo(4L);
assertThat(xmlRecord.getHeader().getSource()).isEqualTo(expectedDataSourceName);
assertThat(xmlRecord.getPayload()).isEqualTo("<data>4</data>");
xmlRecord = xmlFileRecordReader.readRecord();
assertThat(xmlRecord.getHeader().getNumber()).isEqualTo(5L);
assertThat(xmlRecord.getHeader().getSource()).isEqualTo(expectedDataSourceName);
assertThat(xmlRecord.getPayload()).isEqualTo("<data>5</data>");
xmlRecord = xmlFileRecordReader.readRecord();
assertThat(xmlRecord).isNull();
}
#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 integrationTest() throws Exception {
File inputTweets = new File(this.getClass().getResource("/tweets-in.xlsx").toURI());
File outputTweets = new File(this.getClass().getResource("/tweets-out.xlsx").toURI());
Job job = JobBuilder.aNewJob()
.reader(new MsExcelRecordReader(inputTweets))
.mapper(new MsExcelRecordMapper(Tweet.class, "id", "user", "message"))
.marshaller(new MsExcelRecordMarshaller<>(Tweet.class, "id", "user", "message"))
.writer(new MsExcelRecordWriter(outputTweets, SHEET_NAME))
.build();
JobReport report = JobExecutor.execute(job);
assertThat(report).isNotNull();
assertThat(report.getMetrics().getTotalCount()).isEqualTo(2);
assertThat(report.getMetrics().getSuccessCount()).isEqualTo(2);
assertThat(report.getStatus()).isEqualTo(JobStatus.COMPLETED);
XSSFWorkbook workbook = new XSSFWorkbook(new FileInputStream(outputTweets));
XSSFSheet sheet = workbook.getSheet(SHEET_NAME);
XSSFRow row = sheet.getRow(1);
assertThat(row.getCell(0).getNumericCellValue()).isEqualTo(1.0);
assertThat(row.getCell(1).getStringCellValue()).isEqualTo("foo");
assertThat(row.getCell(2).getStringCellValue()).isEqualTo("hi");
row = sheet.getRow(2);
assertThat(row.getCell(0).getNumericCellValue()).isEqualTo(2.0);
assertThat(row.getCell(1).getStringCellValue()).isEqualTo("bar");
assertThat(row.getCell(2).getStringCellValue()).isEqualTo("hello");
}
|
#vulnerable code
@Test
public void integrationTest() throws Exception {
File inputTweets = new File(this.getClass().getResource("/tweets-in.xls").toURI());
File outputTweets = new File(this.getClass().getResource("/tweets-out.xls").toURI());
Job job = JobBuilder.aNewJob()
.reader(new MsExcelRecordReader(inputTweets))
.mapper(new MsExcelRecordMapper(Tweet.class, "id", "user", "message"))
.marshaller(new MsExcelRecordMarshaller<>(Tweet.class, "id", "user", "message"))
.writer(new MsExcelRecordWriter(outputTweets, SHEET_NAME))
.build();
JobReport report = JobExecutor.execute(job);
assertThat(report).isNotNull();
assertThat(report.getMetrics().getTotalCount()).isEqualTo(2);
assertThat(report.getMetrics().getSuccessCount()).isEqualTo(2);
assertThat(report.getStatus()).isEqualTo(JobStatus.COMPLETED);
HSSFWorkbook workbook = new HSSFWorkbook(new FileInputStream(outputTweets));
HSSFSheet sheet = workbook.getSheet(SHEET_NAME);
HSSFRow firstRow = sheet.getRow(1);
assertThat(firstRow.getCell(0).getNumericCellValue()).isEqualTo(1.0);
assertThat(firstRow.getCell(1).getStringCellValue()).isEqualTo("foo");
assertThat(firstRow.getCell(2).getStringCellValue()).isEqualTo("hi");
HSSFRow secondRow = sheet.getRow(2);
assertThat(secondRow.getCell(0).getNumericCellValue()).isEqualTo(2.0);
assertThat(secondRow.getCell(1).getStringCellValue()).isEqualTo("bar");
assertThat(secondRow.getCell(2).getStringCellValue()).isEqualTo("hello");
}
#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 integrationTest() throws Exception {
Path inputTweets = Paths.get("src/test/resources/tweets-in.xlsx");
Path outputTweets = Paths.get("src/test/resources/tweets-out.xlsx");
String[] fields = {"id", "user", "message"};
Job job = JobBuilder.aNewJob()
.reader(new MsExcelRecordReader(inputTweets))
.mapper(new MsExcelRecordMapper<>(Tweet.class, fields))
.marshaller(new MsExcelRecordMarshaller<>(Tweet.class, fields))
.writer(new MsExcelRecordWriter(outputTweets, SHEET_NAME))
.build();
JobReport report = new JobExecutor().execute(job);
assertThat(report).isNotNull();
assertThat(report.getMetrics().getReadCount()).isEqualTo(2);
assertThat(report.getMetrics().getWriteCount()).isEqualTo(2);
assertThat(report.getStatus()).isEqualTo(JobStatus.COMPLETED);
XSSFWorkbook workbook = new XSSFWorkbook(new FileInputStream(outputTweets.toFile()));
XSSFSheet sheet = workbook.getSheet(SHEET_NAME);
XSSFRow row = sheet.getRow(1);
assertThat(row.getCell(0).getNumericCellValue()).isEqualTo(1.0);
assertThat(row.getCell(1).getStringCellValue()).isEqualTo("foo");
assertThat(row.getCell(2).getStringCellValue()).isEqualTo("hi");
row = sheet.getRow(2);
assertThat(row.getCell(0).getNumericCellValue()).isEqualTo(2.0);
assertThat(row.getCell(1).getStringCellValue()).isEqualTo("bar");
assertThat(row.getCell(2).getStringCellValue()).isEqualTo("hello");
}
|
#vulnerable code
@Test
public void integrationTest() throws Exception {
File inputTweets = new File(this.getClass().getResource("/tweets-in.xlsx").toURI());
File outputTweets = new File(this.getClass().getResource("/tweets-out.xlsx").toURI());
String[] fields = {"id", "user", "message"};
Job job = JobBuilder.aNewJob()
.reader(new MsExcelRecordReader(inputTweets))
.mapper(new MsExcelRecordMapper<>(Tweet.class, fields))
.marshaller(new MsExcelRecordMarshaller<>(Tweet.class, fields))
.writer(new MsExcelRecordWriter(outputTweets, SHEET_NAME))
.build();
JobReport report = new JobExecutor().execute(job);
assertThat(report).isNotNull();
assertThat(report.getMetrics().getReadCount()).isEqualTo(2);
assertThat(report.getMetrics().getWriteCount()).isEqualTo(2);
assertThat(report.getStatus()).isEqualTo(JobStatus.COMPLETED);
XSSFWorkbook workbook = new XSSFWorkbook(new FileInputStream(outputTweets));
XSSFSheet sheet = workbook.getSheet(SHEET_NAME);
XSSFRow row = sheet.getRow(1);
assertThat(row.getCell(0).getNumericCellValue()).isEqualTo(1.0);
assertThat(row.getCell(1).getStringCellValue()).isEqualTo("foo");
assertThat(row.getCell(2).getStringCellValue()).isEqualTo("hi");
row = sheet.getRow(2);
assertThat(row.getCell(0).getNumericCellValue()).isEqualTo(2.0);
assertThat(row.getCell(1).getStringCellValue()).isEqualTo("bar");
assertThat(row.getCell(2).getStringCellValue()).isEqualTo("hello");
}
#location 15
#vulnerability type RESOURCE_LEAK
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
@Test
@SuppressWarnings("unchecked")
public void integrationTest() throws Exception {
String dataSource = "foo" + LINE_SEPARATOR + "" + LINE_SEPARATOR + "bar" + LINE_SEPARATOR + "" + LINE_SEPARATOR;
JobReport jobReport = aNewJob()
.reader(new StringRecordReader(dataSource))
.filter(new EmptyRecordFilter())
.processor(new RecordCollector())
.call();
assertThat(jobReport).isNotNull();
assertThat(jobReport.getMetrics().getTotalCount()).isEqualTo(4);
assertThat(jobReport.getMetrics().getFilteredCount()).isEqualTo(2);
assertThat(jobReport.getMetrics().getSuccessCount()).isEqualTo(2);
List<StringRecord> records = (List<StringRecord>) jobReport.getResult();
assertThat(records).extracting("payload").containsExactly("foo", "bar");
}
|
#vulnerable code
@Test
@SuppressWarnings("unchecked")
public void integrationTest() throws Exception {
String dataSource = "foo" + LINE_SEPARATOR + "" + LINE_SEPARATOR + "bar" + LINE_SEPARATOR + "" + LINE_SEPARATOR;
JobReport jobReport = aNewJob()
.reader(new StringRecordReader(dataSource))
.filter(new EmptyRecordFilter())
.processor(new RecordCollector())
.call();
assertThat(jobReport).isNotNull();
assertThat(jobReport.getMetrics().getTotalCount()).isEqualTo(4);
assertThat(jobReport.getMetrics().getFilteredCount()).isEqualTo(2);
assertThat(jobReport.getMetrics().getSuccessCount()).isEqualTo(2);
List<StringRecord> records = (List<StringRecord>) jobReport.getResult();
assertThat(records).hasSize(2);
assertThat(records.get(0).getPayload()).isEqualTo("foo");
assertThat(records.get(1).getPayload()).isEqualTo("bar");
}
#location 19
#vulnerability type NULL_DEREFERENCE
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
@Test
public void testReadingEscapedXml() throws Exception {
// given
xmlRecordReader = new XmlRecordReader("website", getDataSource("/websites.xml"));
xmlRecordReader.open();
// when
XmlRecord record1 = xmlRecordReader.readRecord();
XmlRecord record2 = xmlRecordReader.readRecord();
XmlRecord record3 = xmlRecordReader.readRecord();
XmlRecord record4 = xmlRecordReader.readRecord();
XmlRecord record5 = xmlRecordReader.readRecord();
XmlRecord record6 = xmlRecordReader.readRecord();
// then
assertThat(record1.getPayload()).isXmlEqualTo("<website name=\"google\" url=\"http://www.google.com?query=test&sort=asc\"/>");
assertThat(record2.getPayload()).isXmlEqualTo("<website name=\"l'equipe\" url=\"http://www.lequipe.fr\"/>");
assertThat(record3.getPayload()).isXmlEqualTo("<website name=\"l"internaute.com\" url=\"http://www.linternaute.com\"/>");
assertThat(record4.getPayload()).isXmlEqualTo("<website name=\"google\">http://www.google.com?query=test&sort=asc</website>");
assertThat(record5.getPayload()).isXmlEqualTo("<website name=\"test\"><test>foo</test></website>");
assertThat(record6).isNull();
}
|
#vulnerable code
@Test
public void testReadingEscapedXml() throws Exception {
xmlRecordReader.close();
xmlRecordReader = new XmlRecordReader("website", getDataSource("/websites.xml"));
xmlRecordReader.open();
XmlRecord record = xmlRecordReader.readRecord();
assertThat(record.getPayload()).isXmlEqualTo("<website name=\"google\" url=\"http://www.google.com?query=test&sort=asc\"/>");
record = xmlRecordReader.readRecord();
assertThat(record.getPayload()).isXmlEqualTo("<website name=\"l'equipe\" url=\"http://www.lequipe.fr\"/>");
record = xmlRecordReader.readRecord();
assertThat(record.getPayload()).isXmlEqualTo("<website name=\"l"internaute.com\" url=\"http://www.linternaute.com\"/>");
record = xmlRecordReader.readRecord();
assertThat(record.getPayload()).isXmlEqualTo("<website name=\"google\">http://www.google.com?query=test&sort=asc</website>");
record = xmlRecordReader.readRecord();
assertThat(record.getPayload()).isXmlEqualTo("<website name=\"test\"><test>foo</test></website>");
record = xmlRecordReader.readRecord();
assertThat(record).isNull();
}
#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 testXmlRecordReading() throws Exception {
// given
dataSource = new File("src/test/resources/data.xml");
xmlFileRecordReader = new XmlFileRecordReader(dataSource, "data");
xmlFileRecordReader.open();
String expectedDataSourceName = dataSource.getAbsolutePath();
// when
XmlRecord xmlRecord1 = xmlFileRecordReader.readRecord();
XmlRecord xmlRecord2 = xmlFileRecordReader.readRecord();
XmlRecord xmlRecord3 = xmlFileRecordReader.readRecord();
XmlRecord xmlRecord4 = xmlFileRecordReader.readRecord();
// then
assertThat(xmlRecord1.getHeader().getNumber()).isEqualTo(1L);
assertThat(xmlRecord1.getHeader().getSource()).isEqualTo(expectedDataSourceName);
assertThat(xmlRecord1.getPayload()).isEqualTo("<data>1</data>");
assertThat(xmlRecord2.getHeader().getNumber()).isEqualTo(2L);
assertThat(xmlRecord2.getHeader().getSource()).isEqualTo(expectedDataSourceName);
assertThat(xmlRecord2.getPayload()).isEqualTo("<data>2</data>");
assertThat(xmlRecord3.getHeader().getNumber()).isEqualTo(3L);
assertThat(xmlRecord3.getHeader().getSource()).isEqualTo(expectedDataSourceName);
assertThat(xmlRecord3.getPayload()).isEqualTo("<data>3</data>");
assertThat(xmlRecord4).isNull();
}
|
#vulnerable code
@Test
public void testXmlRecordReading() throws Exception {
String expectedDataSourceName = dataSource.getAbsolutePath();
XmlRecord xmlRecord = xmlFileRecordReader.readRecord();
assertThat(xmlRecord.getHeader().getNumber()).isEqualTo(1L);
assertThat(xmlRecord.getHeader().getSource()).isEqualTo(expectedDataSourceName);
assertThat(xmlRecord.getPayload()).isEqualTo("<data>1</data>");
xmlRecord = xmlFileRecordReader.readRecord();
assertThat(xmlRecord.getHeader().getNumber()).isEqualTo(2L);
assertThat(xmlRecord.getHeader().getSource()).isEqualTo(expectedDataSourceName);
assertThat(xmlRecord.getPayload()).isEqualTo("<data>2</data>");
xmlRecord = xmlFileRecordReader.readRecord();
assertThat(xmlRecord.getHeader().getNumber()).isEqualTo(3L);
assertThat(xmlRecord.getHeader().getSource()).isEqualTo(expectedDataSourceName);
assertThat(xmlRecord.getPayload()).isEqualTo("<data>3</data>");
xmlRecord = xmlFileRecordReader.readRecord();
assertThat(xmlRecord.getHeader().getNumber()).isEqualTo(4L);
assertThat(xmlRecord.getHeader().getSource()).isEqualTo(expectedDataSourceName);
assertThat(xmlRecord.getPayload()).isEqualTo("<data>4</data>");
xmlRecord = xmlFileRecordReader.readRecord();
assertThat(xmlRecord.getHeader().getNumber()).isEqualTo(5L);
assertThat(xmlRecord.getHeader().getSource()).isEqualTo(expectedDataSourceName);
assertThat(xmlRecord.getPayload()).isEqualTo("<data>5</data>");
xmlRecord = xmlFileRecordReader.readRecord();
assertThat(xmlRecord).isNull();
}
#location 11
#vulnerability type NULL_DEREFERENCE
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
@Test
public void integrationTest() throws Exception {
File inputTweets = new File(this.getClass().getResource("/tweets-in.xls").toURI());
File outputTweets = new File(this.getClass().getResource("/tweets-out.xls").toURI());
Job job = JobBuilder.aNewJob()
.reader(new MsExcelRecordReader(inputTweets))
.filter(new HeaderRecordFilter())
.mapper(new MsExcelRecordMapper(Tweet.class, "id", "user", "message"))
.marshaller(new MsExcelRecordMarshaller<>(Tweet.class, "id", "user", "message"))
.writer(new MsExcelRecordWriter(outputTweets))
.build();
JobReport report = JobExecutor.execute(job);
assertThat(report).isNotNull();
assertThat(report.getMetrics().getTotalCount()).isEqualTo(3);
assertThat(report.getMetrics().getFilteredCount()).isEqualTo(1);
assertThat(report.getMetrics().getSuccessCount()).isEqualTo(2);
}
|
#vulnerable code
@Test
public void integrationTest() throws Exception {
File inputTweets = new File(this.getClass().getResource("/tweets-in.xls").toURI());
File outputTweets = new File(this.getClass().getResource("/tweets-out.xls").toURI());
Job job = JobBuilder.aNewJob()
.reader(new MsExcelRecordReader(inputTweets))
.filter(new HeaderRecordFilter())
.mapper(new MsExcelRecordMapper(Tweet.class, "id", "user", "message"))
//.marshaller(new MsExcelRecordMarshaller<>(Tweet.class, "id", "user", "message"))
//.writer(new MsExcelRecordWriter(outputTweets))
.writer(new StandardOutputRecordWriter())
.build();
JobReport report = JobExecutor.execute(job);
assertThat(report).isNotNull();
assertThat(report.getMetrics().getTotalCount()).isEqualTo(3);
assertThat(report.getMetrics().getFilteredCount()).isEqualTo(1);
assertThat(report.getMetrics().getSuccessCount()).isEqualTo(2);
}
#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 testReadingEscapedXml() throws Exception {
// given
xmlRecordReader = new XmlRecordReader("website", getDataSource("/websites.xml"));
xmlRecordReader.open();
// when
XmlRecord record1 = xmlRecordReader.readRecord();
XmlRecord record2 = xmlRecordReader.readRecord();
XmlRecord record3 = xmlRecordReader.readRecord();
XmlRecord record4 = xmlRecordReader.readRecord();
XmlRecord record5 = xmlRecordReader.readRecord();
XmlRecord record6 = xmlRecordReader.readRecord();
// then
assertThat(record1.getPayload()).isXmlEqualTo("<website name=\"google\" url=\"http://www.google.com?query=test&sort=asc\"/>");
assertThat(record2.getPayload()).isXmlEqualTo("<website name=\"l'equipe\" url=\"http://www.lequipe.fr\"/>");
assertThat(record3.getPayload()).isXmlEqualTo("<website name=\"l"internaute.com\" url=\"http://www.linternaute.com\"/>");
assertThat(record4.getPayload()).isXmlEqualTo("<website name=\"google\">http://www.google.com?query=test&sort=asc</website>");
assertThat(record5.getPayload()).isXmlEqualTo("<website name=\"test\"><test>foo</test></website>");
assertThat(record6).isNull();
}
|
#vulnerable code
@Test
public void testReadingEscapedXml() throws Exception {
xmlRecordReader.close();
xmlRecordReader = new XmlRecordReader("website", getDataSource("/websites.xml"));
xmlRecordReader.open();
XmlRecord record = xmlRecordReader.readRecord();
assertThat(record.getPayload()).isXmlEqualTo("<website name=\"google\" url=\"http://www.google.com?query=test&sort=asc\"/>");
record = xmlRecordReader.readRecord();
assertThat(record.getPayload()).isXmlEqualTo("<website name=\"l'equipe\" url=\"http://www.lequipe.fr\"/>");
record = xmlRecordReader.readRecord();
assertThat(record.getPayload()).isXmlEqualTo("<website name=\"l"internaute.com\" url=\"http://www.linternaute.com\"/>");
record = xmlRecordReader.readRecord();
assertThat(record.getPayload()).isXmlEqualTo("<website name=\"google\">http://www.google.com?query=test&sort=asc</website>");
record = xmlRecordReader.readRecord();
assertThat(record.getPayload()).isXmlEqualTo("<website name=\"test\"><test>foo</test></website>");
record = xmlRecordReader.readRecord();
assertThat(record).isNull();
}
#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 testReadingXmlWithCustomNamespace() throws Exception {
// given
xmlRecordReader = new XmlRecordReader("bean", getDataSource("/beans.xml"));
xmlRecordReader.open();
// when
XmlRecord record1 = xmlRecordReader.readRecord();
XmlRecord record2 = xmlRecordReader.readRecord();
XmlRecord record3 = xmlRecordReader.readRecord();
// then
assertThat(record1.getPayload()).isXmlEqualTo("<bean id=\"foo\" class=\"java.lang.String\"><description>foo bean</description></bean>");
assertThat(record2.getPayload()).isXmlEqualTo("<bean id=\"bar\" class=\"java.lang.String\"/>");
assertThat(record3).isNull();
}
|
#vulnerable code
@Test
public void testReadingXmlWithCustomNamespace() throws Exception {
xmlRecordReader.close();
xmlRecordReader = new XmlRecordReader("bean", getDataSource("/beans.xml"));
xmlRecordReader.open();
XmlRecord record = xmlRecordReader.readRecord();
assertThat(record.getPayload()).isXmlEqualTo("<bean id=\"foo\" class=\"java.lang.String\"><description>foo bean</description></bean>");
record = xmlRecordReader.readRecord();
assertThat(record.getPayload()).isXmlEqualTo("<bean id=\"bar\" class=\"java.lang.String\"/>");
record = xmlRecordReader.readRecord();
assertThat(record).isNull();
}
#location 8
#vulnerability type NULL_DEREFERENCE
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
@Override
public String validateRecord(Record record) {
String error = super.validateRecord(record);
if (error == null){//no errors after applying declared validators on each field => all fields are valid
//add custom validation : field 2 content must start with field's 1 content
final String content1 = record.getFieldContentByIndex(1);
final String content2 = record.getFieldContentByIndex(2);
if (!content2.startsWith(content1))
return "field 2 content [" + content2 + "] must start with field's 1 content [" + content1 + "]";
}
return null;
}
|
#vulnerable code
@Override
public String validateRecord(Record record) {
String error = super.validateRecord(record);
if (error.length() == 0){//no errors after applying declared validators on each field => all fields are valid
//add custom validation : field 2 content must starts with field 1 content
final String content1 = record.getFieldContentByIndex(1);
final String content2 = record.getFieldContentByIndex(2);
if (!content2.startsWith(content1))
return "field 2 content [" + content2 + "] must start with field 1 content [" + content1 + "]";
}
return "";
}
#location 5
#vulnerability type NULL_DEREFERENCE
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
@Override
public void run() {
final SingleWriterRecorder recorder =
new SingleWriterRecorder(
config.lowestTrackableValue,
config.highestTrackableValue,
config.numberOfSignificantValueDigits
);
Histogram intervalHistogram = null;
HiccupRecorder hiccupRecorder;
final long uptimeAtInitialStartTime = ManagementFactory.getRuntimeMXBean().getUptime();
long now = System.currentTimeMillis();
long jvmStartTime = now - uptimeAtInitialStartTime;
long reportingStartTime = jvmStartTime;
if (config.inputFileName == null) {
// Normal operating mode.
// Launch a hiccup recorder, a process termination monitor, and an optional control process:
hiccupRecorder = this.createHiccupRecorder(recorder);
if (config.terminateWithStdInput) {
new TerminateWithStdInputReader();
}
if (config.controlProcessCommand != null) {
new ExecProcess(config.controlProcessCommand, "ControlProcess", log, config.verbose);
}
} else {
// Take input from file instead of sampling it ourselves.
// Launch an input hiccup recorder, but no termination monitoring or control process:
hiccupRecorder = new InputRecorder(recorder, config.inputFileName);
}
histogramLogWriter.outputComment("[Logged with " + getVersionString() + "]");
histogramLogWriter.outputLogFormatVersion();
try {
final long startTime;
if (config.inputFileName == null) {
// Normal operating mode:
if (config.startDelayMs > 0) {
// Run hiccup recorder during startDelayMs time to let code warm up:
hiccupRecorder.start();
while (config.startDelayMs > System.currentTimeMillis() - jvmStartTime) {
Thread.sleep(100);
}
hiccupRecorder.terminate();
hiccupRecorder.join();
recorder.reset();
hiccupRecorder = new HiccupRecorder(recorder, config.allocateObjects);
}
hiccupRecorder.start();
startTime = System.currentTimeMillis();
if (config.startTimeAtZero) {
reportingStartTime = startTime;
}
histogramLogWriter.outputStartTime(reportingStartTime);
histogramLogWriter.setBaseTime(reportingStartTime);
} else {
// Reading from input file, not sampling ourselves...:
hiccupRecorder.start();
reportingStartTime = startTime = hiccupRecorder.getCurrentTimeMsecWithDelay(0);
histogramLogWriter.outputComment("[Data read from input file \"" + config.inputFileName + "\" at " + new Date() + "]");
}
histogramLogWriter.outputLegend();
long nextReportingTime = startTime + config.reportingIntervalMs;
long intervalStartTimeMsec = 0;
while ((now > 0) && ((config.runTimeMs == 0) || (config.runTimeMs > now - startTime))) {
now = hiccupRecorder.getCurrentTimeMsecWithDelay(nextReportingTime); // could return -1 to indicate termination
if (now > nextReportingTime) {
// Get the latest interval histogram and give the recorder a fresh Histogram for the next interval
intervalHistogram = recorder.getIntervalHistogram(intervalHistogram);
while (now > nextReportingTime) {
nextReportingTime += config.reportingIntervalMs;
}
if (config.inputFileName != null) {
// When read from input file, use timestamps from file input for start/end of log intervals:
intervalHistogram.setStartTimeStamp(intervalStartTimeMsec);
intervalHistogram.setEndTimeStamp(now);
intervalStartTimeMsec = now;
}
if (intervalHistogram.getTotalCount() > 0) {
histogramLogWriter.outputIntervalHistogram(intervalHistogram);
}
}
}
} catch (InterruptedException e) {
if (config.verbose) {
log.println("# HiccupMeter terminating...");
}
}
try {
hiccupRecorder.terminate();
hiccupRecorder.join();
} catch (InterruptedException e) {
if (config.verbose) {
log.println("# HiccupMeter terminate/join interrupted");
}
}
}
|
#vulnerable code
@Override
public void run() {
final SingleWriterRecorder recorder =
new SingleWriterRecorder(
config.lowestTrackableValue,
config.highestTrackableValue,
config.numberOfSignificantValueDigits
);
Histogram intervalHistogram = null;
HiccupRecorder hiccupRecorder;
final long uptimeAtInitialStartTime = ManagementFactory.getRuntimeMXBean().getUptime();
long now = System.currentTimeMillis();
long jvmStartTime = now - uptimeAtInitialStartTime;
long reportingStartTime = jvmStartTime;
if (config.inputFileName == null) {
// Normal operating mode.
// Launch a hiccup recorder, a process termination monitor, and an optional control process:
hiccupRecorder = this.createHiccupRecorder(recorder);
if (config.terminateWithStdInput) {
new TerminateWithStdInputReader();
}
if (config.controlProcessCommand != null) {
new ExecProcess(config.controlProcessCommand, "ControlProcess", log, config.verbose);
}
} else {
// Take input from file instead of sampling it ourselves.
// Launch an input hiccup recorder, but no termination monitoring or control process:
hiccupRecorder = new InputRecorder(recorder, config.inputFileName);
}
histogramLogWriter.outputComment("[Logged with " + getVersionString() + "]");
histogramLogWriter.outputLogFormatVersion();
try {
final long startTime;
if (config.inputFileName == null) {
// Normal operating mode:
if (config.startDelayMs > 0) {
// Run hiccup recorder during startDelayMs time to let code warm up:
hiccupRecorder.start();
while (config.startDelayMs > System.currentTimeMillis() - jvmStartTime) {
Thread.sleep(100);
}
hiccupRecorder.terminate();
hiccupRecorder.join();
recorder.reset();
hiccupRecorder = new HiccupRecorder(recorder, config.allocateObjects);
}
hiccupRecorder.start();
startTime = System.currentTimeMillis();
if (config.startTimeAtZero) {
reportingStartTime = startTime;
}
histogramLogWriter.outputStartTime(reportingStartTime);
histogramLogWriter.setBaseTime(reportingStartTime);
} else {
// Reading from input file, not sampling ourselves...:
hiccupRecorder.start();
reportingStartTime = startTime = hiccupRecorder.getCurrentTimeMsecWithDelay(0);
histogramLogWriter.outputComment("[Data read from input file \"" + config.inputFileName + "\" at " + new Date() + "]");
}
histogramLogWriter.outputLegend();
long nextReportingTime = startTime + config.reportingIntervalMs;
while ((now > 0) && ((config.runTimeMs == 0) || (config.runTimeMs > now - startTime))) {
now = hiccupRecorder.getCurrentTimeMsecWithDelay(nextReportingTime); // could return -1 to indicate termination
if (now > nextReportingTime) {
// Get the latest interval histogram and give the recorder a fresh Histogram for the next interval
intervalHistogram = recorder.getIntervalHistogram(intervalHistogram);
while (now > nextReportingTime) {
nextReportingTime += config.reportingIntervalMs;
}
if (intervalHistogram.getTotalCount() > 0) {
histogramLogWriter.outputIntervalHistogram(intervalHistogram);
}
}
}
} catch (InterruptedException e) {
if (config.verbose) {
log.println("# HiccupMeter terminating...");
}
}
try {
hiccupRecorder.terminate();
hiccupRecorder.join();
} catch (InterruptedException e) {
if (config.verbose) {
log.println("# HiccupMeter terminate/join interrupted");
}
}
}
#location 50
#vulnerability type RESOURCE_LEAK
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
public void init() {
KafkaConsumer kafkaConsumer=new KafkaConsumer(getProperties());
//kafka消费消息,接收MQTT发来的消息
kafkaConsumer.subscribe(Arrays.asList(conf.get("mqttwk.broker.kafka.producer.topic")));
int sum=0;
while (true) {
ConsumerRecords<String, String> records = kafkaConsumer.poll(Duration.ofMillis(500));
for (ConsumerRecord<String, String> record : records) {
log.debugf("offset = %d, key = %s, value = %s%n", record.offset(), record.key(), new String(HexUtil.decodeHex(record.value())));
log.debugf("总计收到 %s条",++sum);
}
}
}
|
#vulnerable code
public void init() {
KafkaConsumer kafkaConsumer=new KafkaConsumer(getProperties());
//kafka消费消息,接收MQTT发来的消息
kafkaConsumer.subscribe(Arrays.asList(conf.get("mqttwk.broker.kafka.producer.topic")));
int sum=0;
while (true) {
ConsumerRecords<String, String> records = kafkaConsumer.poll(500);
for (ConsumerRecord<String, String> record : records) {
log.debugf("offset = %d, key = %s, value = %s%n", record.offset(), record.key(), new String(HexUtil.decodeHex(record.value())));
log.debugf("总计收到 %s条",++sum);
}
}
}
#location 11
#vulnerability type RESOURCE_LEAK
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
public void testZipArchiveCreation() throws Exception {
// Archive
final File output = new File(dir, "bla.zip");
final File file1 = getFile("test1.xml");
final File file2 = getFile("test2.xml");
final OutputStream out = new FileOutputStream(output);
ArchiveOutputStream os = null;
try {
os = new ArchiveStreamFactory()
.createArchiveOutputStream("zip", out);
os.putArchiveEntry(new ZipArchiveEntry("testdata/test1.xml"));
IOUtils.copy(new FileInputStream(file1), os);
os.closeArchiveEntry();
os.putArchiveEntry(new ZipArchiveEntry("testdata/test2.xml"));
IOUtils.copy(new FileInputStream(file2), os);
os.closeArchiveEntry();
} finally {
if (os != null) {
os.close();
} else {
out.close();
}
}
// Unarchive the same
List results = new ArrayList();
final InputStream is = new FileInputStream(output);
ArchiveInputStream in = null;
try {
in = new ArchiveStreamFactory()
.createArchiveInputStream("zip", is);
ZipArchiveEntry entry = null;
while((entry = (ZipArchiveEntry)in.getNextEntry()) != null) {
File outfile = new File(resultDir.getCanonicalPath() + "/result/" + entry.getName());
outfile.getParentFile().mkdirs();
OutputStream o = new FileOutputStream(outfile);
try {
IOUtils.copy(in, o);
} finally {
o.close();
}
results.add(outfile);
}
} finally {
if (in != null) {
in.close();
} else {
is.close();
}
}
assertEquals(results.size(), 2);
File result = (File)results.get(0);
assertEquals(file1.length(), result.length());
result = (File)results.get(1);
assertEquals(file2.length(), result.length());
}
|
#vulnerable code
public void testZipArchiveCreation() throws Exception {
// Archive
final File output = new File(dir, "bla.zip");
final File file1 = getFile("test1.xml");
final File file2 = getFile("test2.xml");
{
final OutputStream out = new FileOutputStream(output);
final ArchiveOutputStream os = new ArchiveStreamFactory().createArchiveOutputStream("zip", out);
os.putArchiveEntry(new ZipArchiveEntry("testdata/test1.xml"));
IOUtils.copy(new FileInputStream(file1), os);
os.closeArchiveEntry();
os.putArchiveEntry(new ZipArchiveEntry("testdata/test2.xml"));
IOUtils.copy(new FileInputStream(file2), os);
os.closeArchiveEntry();
os.close();
}
// Unarchive the same
List results = new ArrayList();
{
final InputStream is = new FileInputStream(output);
final ArchiveInputStream in = new ArchiveStreamFactory().createArchiveInputStream("zip", is);
File result = File.createTempFile("dir-result", "");
result.delete();
result.mkdir();
ZipArchiveEntry entry = null;
while((entry = (ZipArchiveEntry)in.getNextEntry()) != null) {
File outfile = new File(result.getCanonicalPath() + "/result/" + entry.getName());
outfile.getParentFile().mkdirs();
OutputStream out = new FileOutputStream(outfile);
IOUtils.copy(in, out);
out.close();
results.add(outfile);
}
in.close();
}
assertEquals(results.size(), 2);
File result = (File)results.get(0);
assertEquals(file1.length(), result.length());
result = (File)results.get(1);
assertEquals(file2.length(), result.length());
}
#location 19
#vulnerability type RESOURCE_LEAK
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
public void testDetection() throws Exception {
final ArchiveStreamFactory factory = new ArchiveStreamFactory();
final ArchiveInputStream ar = factory.createArchiveInputStream(
new BufferedInputStream(new FileInputStream(
new File(getClass().getClassLoader().getResource("bla.ar").getFile()))));
assertNotNull(ar);
assertTrue(ar instanceof ArArchiveInputStream);
final ArchiveInputStream tar = factory.createArchiveInputStream(
new BufferedInputStream(new FileInputStream(
new File(getClass().getClassLoader().getResource("bla.tar").getFile()))));
assertNotNull(tar);
assertTrue(tar instanceof TarArchiveInputStream);
final ArchiveInputStream zip = factory.createArchiveInputStream(
new BufferedInputStream(new FileInputStream(
new File(getClass().getClassLoader().getResource("bla.zip").getFile()))));
assertNotNull(zip);
assertTrue(zip instanceof ZipArchiveInputStream);
final ArchiveInputStream jar = factory.createArchiveInputStream(
new BufferedInputStream(new FileInputStream(
new File(getClass().getClassLoader().getResource("bla.jar").getFile()))));
assertNotNull(jar);
assertTrue(jar instanceof ZipArchiveInputStream);
final ArchiveInputStream cpio = factory.createArchiveInputStream(
new BufferedInputStream(new FileInputStream(
new File(getClass().getClassLoader().getResource("bla.cpio").getFile()))));
assertNotNull(cpio);
assertTrue(cpio instanceof CpioArchiveInputStream);
// final ArchiveInputStream tgz = factory.createArchiveInputStream(
// new BufferedInputStream(new FileInputStream(
// new File(getClass().getClassLoader().getResource("bla.tgz").getFile()))));
// assertTrue(tgz instanceof TarArchiveInputStream);
}
|
#vulnerable code
public void testDetection() throws Exception {
final ArchiveStreamFactory factory = new ArchiveStreamFactory();
final ArchiveInputStream ar = factory.createArchiveInputStream(
new BufferedInputStream(new FileInputStream(
new File(getClass().getClassLoader().getResource("bla.ar").getFile()))));
assertNotNull(ar);
assertTrue(ar instanceof ArArchiveInputStream);
final ArchiveInputStream tar = factory.createArchiveInputStream(
new BufferedInputStream(new FileInputStream(
new File(getClass().getClassLoader().getResource("bla.tar").getFile()))));
assertNotNull(tar);
assertTrue(tar instanceof TarArchiveInputStream);
final ArchiveInputStream zip = factory.createArchiveInputStream(
new BufferedInputStream(new FileInputStream(
new File(getClass().getClassLoader().getResource("bla.zip").getFile()))));
assertNotNull(zip);
assertTrue(zip instanceof ZipArchiveInputStream);
final ArchiveInputStream jar = factory.createArchiveInputStream(
new BufferedInputStream(new FileInputStream(
new File(getClass().getClassLoader().getResource("bla.jar").getFile()))));
assertNotNull(jar);
assertTrue(jar instanceof JarArchiveInputStream);
final ArchiveInputStream cpio = factory.createArchiveInputStream(
new BufferedInputStream(new FileInputStream(
new File(getClass().getClassLoader().getResource("bla.cpio").getFile()))));
assertNotNull(cpio);
assertTrue(cpio instanceof CpioArchiveInputStream);
// final ArchiveInputStream tgz = factory.createArchiveInputStream(
// new BufferedInputStream(new FileInputStream(
// new File(getClass().getClassLoader().getResource("bla.tgz").getFile()))));
// assertTrue(tgz instanceof TarArchiveInputStream);
}
#location 28
#vulnerability type RESOURCE_LEAK
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
public InputStream compress(InputStream input) throws CompressException {
FileOutputStream outputStream = null;
FileOutputStream tempFileOutputStream = null;
try {
File temp = File.createTempFile("commons_","jkt");
tempFileOutputStream = new FileOutputStream(temp);
compressTo(input, tempFileOutputStream);
return new FileInputStream(temp);
} catch (IOException e) {
throw new CompressException("An IO Exception has occured", e);
} finally {
try {
if(tempFileOutputStream != null) {
tempFileOutputStream.close();
}
if(outputStream != null) {
outputStream.close();
}
} catch (IOException e) {
throw new CompressException("An IO Exception occured while closing the streams", e);
}
}
}
|
#vulnerable code
public InputStream compress(InputStream input) throws CompressException {
FileOutputStream outputStream = null;
FileOutputStream tempFileOutputStream = null;
try {
File temp = File.createTempFile("commons_","jkt");
tempFileOutputStream = new FileOutputStream(temp);
compressTo(input, tempFileOutputStream);
return new FileInputStream(temp);
} catch (IOException e) {
throw new CompressException("An IO Exception has occured", e);
} finally {
try {
tempFileOutputStream.close();
outputStream.close();
} catch (IOException e) {
throw new CompressException("An IO Exception occured while closing the streams", e);
}
}
}
#location 14
#vulnerability type NULL_DEREFERENCE
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
public void testBzip2Unarchive() throws Exception {
final File input = getFile("bla.txt.bz2");
final File output = new File(dir, "bla.txt");
final InputStream is = new FileInputStream(input);
final CompressorInputStream in = new CompressorStreamFactory().createCompressorInputStream("bzip2", is);
IOUtils.copy(in, new FileOutputStream(output));
in.close();
}
|
#vulnerable code
public void testBzip2Unarchive() throws Exception {
final File output = new File(dir, "test-entpackt.txt");
System.out.println(dir);
final File input = new File(getClass().getClassLoader().getResource("bla.txt.bz2").getFile());
final InputStream is = new FileInputStream(input);
//final CompressorInputStream in = new CompressorStreamFactory().createCompressorInputStream("bzip2", is);
final CompressorInputStream in = new BZip2CompressorInputStream(is);
IOUtils.copy(in, new FileOutputStream(output));
in.close();
}
#location 7
#vulnerability type RESOURCE_LEAK
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
public void testCBZip2InputStreamClose()
throws Exception
{
final InputStream input = getInputStream( "asf-logo-huge.tar.bz2" );
final File outputFile = getOutputFile( ".tar.bz2" );
final OutputStream output = new FileOutputStream( outputFile );
CompressUtils.copy( input, output );
IOUtils.closeQuietly( input );
IOUtils.closeQuietly( output );
assertTrue( "Check output file exists." , outputFile.exists() );
final InputStream input2 = new FileInputStream( outputFile );
final InputStream packedInput = getPackedInput( input2 );
IOUtils.closeQuietly( packedInput );
try
{
input2.read();
assertTrue("Source input stream is still opened.", false);
} catch ( Exception e )
{
// Read closed stream.
}
forceDelete( outputFile );
}
|
#vulnerable code
public void testCBZip2InputStreamClose()
throws Exception
{
final InputStream input = getInputStream( "asf-logo-huge.tar.bz2" );
final File outputFile = getOutputFile( ".tar.bz2" );
final OutputStream output = new FileOutputStream( outputFile );
CompressUtils.copy( input, output );
shutdownStream( input );
shutdownStream( output );
assertTrue( "Check output file exists." , outputFile.exists() );
final InputStream input2 = new FileInputStream( outputFile );
final InputStream packedInput = getPackedInput( input2 );
shutdownStream( packedInput );
try
{
input2.read();
assertTrue("Source input stream is still opened.", false);
} catch ( Exception e )
{
// Read closed stream.
}
forceDelete( outputFile );
}
#location 13
#vulnerability type RESOURCE_LEAK
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
public void testDetection() throws Exception {
final ArchiveStreamFactory factory = new ArchiveStreamFactory();
final ArchiveInputStream ar = factory.createArchiveInputStream(
new BufferedInputStream(new FileInputStream(
new File(getClass().getClassLoader().getResource("bla.ar").getFile()))));
assertNotNull(ar);
assertTrue(ar instanceof ArArchiveInputStream);
final ArchiveInputStream tar = factory.createArchiveInputStream(
new BufferedInputStream(new FileInputStream(
new File(getClass().getClassLoader().getResource("bla.tar").getFile()))));
assertNotNull(tar);
assertTrue(tar instanceof TarArchiveInputStream);
final ArchiveInputStream zip = factory.createArchiveInputStream(
new BufferedInputStream(new FileInputStream(
new File(getClass().getClassLoader().getResource("bla.zip").getFile()))));
assertNotNull(zip);
assertTrue(zip instanceof ZipArchiveInputStream);
final ArchiveInputStream jar = factory.createArchiveInputStream(
new BufferedInputStream(new FileInputStream(
new File(getClass().getClassLoader().getResource("bla.jar").getFile()))));
assertNotNull(jar);
assertTrue(jar instanceof ZipArchiveInputStream);
final ArchiveInputStream cpio = factory.createArchiveInputStream(
new BufferedInputStream(new FileInputStream(
new File(getClass().getClassLoader().getResource("bla.cpio").getFile()))));
assertNotNull(cpio);
assertTrue(cpio instanceof CpioArchiveInputStream);
// final ArchiveInputStream tgz = factory.createArchiveInputStream(
// new BufferedInputStream(new FileInputStream(
// new File(getClass().getClassLoader().getResource("bla.tgz").getFile()))));
// assertTrue(tgz instanceof TarArchiveInputStream);
}
|
#vulnerable code
public void testDetection() throws Exception {
final ArchiveStreamFactory factory = new ArchiveStreamFactory();
final ArchiveInputStream ar = factory.createArchiveInputStream(
new BufferedInputStream(new FileInputStream(
new File(getClass().getClassLoader().getResource("bla.ar").getFile()))));
assertNotNull(ar);
assertTrue(ar instanceof ArArchiveInputStream);
final ArchiveInputStream tar = factory.createArchiveInputStream(
new BufferedInputStream(new FileInputStream(
new File(getClass().getClassLoader().getResource("bla.tar").getFile()))));
assertNotNull(tar);
assertTrue(tar instanceof TarArchiveInputStream);
final ArchiveInputStream zip = factory.createArchiveInputStream(
new BufferedInputStream(new FileInputStream(
new File(getClass().getClassLoader().getResource("bla.zip").getFile()))));
assertNotNull(zip);
assertTrue(zip instanceof ZipArchiveInputStream);
final ArchiveInputStream jar = factory.createArchiveInputStream(
new BufferedInputStream(new FileInputStream(
new File(getClass().getClassLoader().getResource("bla.jar").getFile()))));
assertNotNull(jar);
assertTrue(jar instanceof JarArchiveInputStream);
final ArchiveInputStream cpio = factory.createArchiveInputStream(
new BufferedInputStream(new FileInputStream(
new File(getClass().getClassLoader().getResource("bla.cpio").getFile()))));
assertNotNull(cpio);
assertTrue(cpio instanceof CpioArchiveInputStream);
// final ArchiveInputStream tgz = factory.createArchiveInputStream(
// new BufferedInputStream(new FileInputStream(
// new File(getClass().getClassLoader().getResource("bla.tgz").getFile()))));
// assertTrue(tgz instanceof TarArchiveInputStream);
}
#location 22
#vulnerability type RESOURCE_LEAK
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
public void testJarUnarchive() throws Exception {
final File input = getFile("bla.jar");
final InputStream is = new FileInputStream(input);
final ArchiveInputStream in = new ArchiveStreamFactory().createArchiveInputStream("jar", is);
ZipArchiveEntry entry = (ZipArchiveEntry)in.getNextEntry();
File o = new File(dir, entry.getName());
o.getParentFile().mkdirs();
OutputStream out = new FileOutputStream(o);
IOUtils.copy(in, out);
out.close();
entry = (ZipArchiveEntry)in.getNextEntry();
o = new File(dir, entry.getName());
o.getParentFile().mkdirs();
out = new FileOutputStream(o);
IOUtils.copy(in, out);
out.close();
entry = (ZipArchiveEntry)in.getNextEntry();
o = new File(dir, entry.getName());
o.getParentFile().mkdirs();
out = new FileOutputStream(o);
IOUtils.copy(in, out);
out.close();
in.close();
is.close();
}
|
#vulnerable code
public void testJarUnarchive() throws Exception {
final File input = getFile("bla.jar");
final InputStream is = new FileInputStream(input);
final ArchiveInputStream in = new ArchiveStreamFactory().createArchiveInputStream("jar", is);
ZipArchiveEntry entry = (ZipArchiveEntry)in.getNextEntry();
File o = new File(dir, entry.getName());
o.getParentFile().mkdirs();
OutputStream out = new FileOutputStream(o);
IOUtils.copy(in, out);
out.close();
entry = (ZipArchiveEntry)in.getNextEntry();
o = new File(dir, entry.getName());
o.getParentFile().mkdirs();
out = new FileOutputStream(o);
IOUtils.copy(in, out);
out.close();
entry = (ZipArchiveEntry)in.getNextEntry();
o = new File(dir, entry.getName());
o.getParentFile().mkdirs();
out = new FileOutputStream(o);
IOUtils.copy(in, out);
out.close();
in.close();
}
#location 27
#vulnerability type RESOURCE_LEAK
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
public void testArUnarchive() throws Exception {
final File output = new File(dir, "bla.ar");
{
final File file1 = getFile("test1.xml");
final File file2 = getFile("test2.xml");
final OutputStream out = new FileOutputStream(output);
final ArchiveOutputStream os = new ArchiveStreamFactory().createArchiveOutputStream("ar", out);
os.putArchiveEntry(new ArArchiveEntry("test1.xml", file1.length()));
IOUtils.copy(new FileInputStream(file1), os);
os.closeArchiveEntry();
os.putArchiveEntry(new ArArchiveEntry("test2.xml", file2.length()));
IOUtils.copy(new FileInputStream(file2), os);
os.closeArchiveEntry();
os.close();
out.close();
}
// UnArArchive Operation
final File input = output;
final InputStream is = new FileInputStream(input);
final ArchiveInputStream in = new ArchiveStreamFactory().createArchiveInputStream(new BufferedInputStream(is));
final ArArchiveEntry entry = (ArArchiveEntry)in.getNextEntry();
File target = new File(dir, entry.getName());
final OutputStream out = new FileOutputStream(target);
IOUtils.copy(in, out);
out.close();
in.close();
is.close();
}
|
#vulnerable code
public void testArUnarchive() throws Exception {
final File output = new File(dir, "bla.ar");
{
final File file1 = getFile("test1.xml");
final File file2 = getFile("test2.xml");
final OutputStream out = new FileOutputStream(output);
final ArchiveOutputStream os = new ArchiveStreamFactory().createArchiveOutputStream("ar", out);
os.putArchiveEntry(new ArArchiveEntry("test1.xml", file1.length()));
IOUtils.copy(new FileInputStream(file1), os);
os.closeArchiveEntry();
os.putArchiveEntry(new ArArchiveEntry("test2.xml", file2.length()));
IOUtils.copy(new FileInputStream(file2), os);
os.closeArchiveEntry();
os.close();
out.close();
}
// UnArArchive Operation
final File input = output;
final InputStream is = new FileInputStream(input);
final ArchiveInputStream in = new ArchiveStreamFactory().createArchiveInputStream("ar", is);
final ArArchiveEntry entry = (ArArchiveEntry)in.getNextEntry();
File target = new File(dir, entry.getName());
final OutputStream out = new FileOutputStream(target);
IOUtils.copy(in, out);
out.close();
in.close();
is.close();
}
#location 18
#vulnerability type RESOURCE_LEAK
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
public void testArDelete() throws Exception {
final File output = new File(dir, "bla.ar");
{
// create
final File file1 = getFile("test1.xml");
final File file2 = getFile("test2.xml");
final OutputStream out = new FileOutputStream(output);
final ArchiveOutputStream os = new ArchiveStreamFactory().createArchiveOutputStream("ar", out);
os.putArchiveEntry(new ArArchiveEntry("test1.xml", file1.length()));
IOUtils.copy(new FileInputStream(file1), os);
os.closeArchiveEntry();
os.putArchiveEntry(new ArArchiveEntry("test2.xml", file2.length()));
IOUtils.copy(new FileInputStream(file2), os);
os.closeArchiveEntry();
os.close();
out.close();
}
assertEquals(282, output.length());
final File output2 = new File(dir, "bla2.ar");
int copied = 0;
int deleted = 0;
{
// remove all but one file
final InputStream is = new FileInputStream(output);
final OutputStream os = new FileOutputStream(output2);
final ArchiveOutputStream aos = new ArchiveStreamFactory().createArchiveOutputStream("ar", os);
final ArchiveInputStream ais = new ArchiveStreamFactory().createArchiveInputStream(new BufferedInputStream(is));
while(true) {
final ArArchiveEntry entry = (ArArchiveEntry)ais.getNextEntry();
if (entry == null) {
break;
}
if ("test1.xml".equals(entry.getName())) {
aos.putArchiveEntry(entry);
IOUtils.copy(ais, aos);
aos.closeArchiveEntry();
copied++;
} else {
IOUtils.copy(ais, new ByteArrayOutputStream());
deleted++;
}
}
ais.close();
aos.close();
is.close();
os.close();
}
assertEquals(1, copied);
assertEquals(1, deleted);
assertEquals(144, output2.length());
long files = 0;
long sum = 0;
{
final InputStream is = new FileInputStream(output2);
final ArchiveInputStream ais = new ArchiveStreamFactory().createArchiveInputStream(new BufferedInputStream(is));
while(true) {
final ArArchiveEntry entry = (ArArchiveEntry)ais.getNextEntry();
if (entry == null) {
break;
}
IOUtils.copy(ais, new ByteArrayOutputStream());
sum += entry.getLength();
files++;
}
ais.close();
is.close();
}
assertEquals(1, files);
assertEquals(76, sum);
}
|
#vulnerable code
public void testArDelete() throws Exception {
final File output = new File(dir, "bla.ar");
{
// create
final File file1 = getFile("test1.xml");
final File file2 = getFile("test2.xml");
final OutputStream out = new FileOutputStream(output);
final ArchiveOutputStream os = new ArchiveStreamFactory().createArchiveOutputStream("ar", out);
os.putArchiveEntry(new ArArchiveEntry("test1.xml", file1.length()));
IOUtils.copy(new FileInputStream(file1), os);
os.closeArchiveEntry();
os.putArchiveEntry(new ArArchiveEntry("test2.xml", file2.length()));
IOUtils.copy(new FileInputStream(file2), os);
os.closeArchiveEntry();
os.close();
out.close();
}
final File output2 = new File(dir, "bla2.ar");
{
// remove all but one file
final InputStream is = new FileInputStream(output);
final OutputStream os = new FileOutputStream(output2);
final ArchiveOutputStream aos = new ArchiveStreamFactory().createArchiveOutputStream("ar", os);
final ArchiveInputStream ais = new ArchiveStreamFactory().createArchiveInputStream(new BufferedInputStream(is));
while(true) {
final ArArchiveEntry entry = (ArArchiveEntry)ais.getNextEntry();
if (entry == null) {
break;
}
if ("test1.xml".equals(entry.getName())) {
aos.putArchiveEntry(entry);
IOUtils.copy(ais, aos);
} else {
IOUtils.copy(ais, new ByteArrayOutputStream());
}
}
ais.close();
aos.close();
is.close();
os.close();
}
long sum = 0;
{
final InputStream is = new FileInputStream(output2);
final ArchiveInputStream ais = new ArchiveStreamFactory().createArchiveInputStream(new BufferedInputStream(is));
while(true) {
final ArArchiveEntry entry = (ArArchiveEntry)ais.getNextEntry();
if (entry == null) {
break;
}
IOUtils.copy(ais, new ByteArrayOutputStream());
sum += entry.getLength();
}
ais.close();
is.close();
}
assertEquals(76, sum);
}
#location 20
#vulnerability type RESOURCE_LEAK
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
public void testBzipCreation() throws Exception {
final File input = getFile("test.txt");
final File output = new File(dir, "test.txt.bz2");
final OutputStream out = new FileOutputStream(output);
final CompressorOutputStream cos = new CompressorStreamFactory().createCompressorOutputStream("bzip2", out);
IOUtils.copy(new FileInputStream(input), cos);
cos.close();
}
|
#vulnerable code
public void testBzipCreation() throws Exception {
final File output = new File(dir, "bla.txt.bz2");
System.out.println(dir);
final File file1 = new File(getClass().getClassLoader().getResource("test.txt").getFile());
final OutputStream out = new FileOutputStream(output);
CompressorOutputStream cos = new CompressorStreamFactory().createCompressorOutputStream("bzip2", out);
IOUtils.copy(new FileInputStream(file1), cos);
cos.close();
}
#location 7
#vulnerability type RESOURCE_LEAK
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
public void testDetection() throws Exception {
final ArchiveStreamFactory factory = new ArchiveStreamFactory();
final ArchiveInputStream ar = factory.createArchiveInputStream(
new BufferedInputStream(new FileInputStream(
new File(getClass().getClassLoader().getResource("bla.ar").getFile()))));
assertNotNull(ar);
assertTrue(ar instanceof ArArchiveInputStream);
final ArchiveInputStream tar = factory.createArchiveInputStream(
new BufferedInputStream(new FileInputStream(
new File(getClass().getClassLoader().getResource("bla.tar").getFile()))));
assertNotNull(tar);
assertTrue(tar instanceof TarArchiveInputStream);
final ArchiveInputStream zip = factory.createArchiveInputStream(
new BufferedInputStream(new FileInputStream(
new File(getClass().getClassLoader().getResource("bla.zip").getFile()))));
assertNotNull(zip);
assertTrue(zip instanceof ZipArchiveInputStream);
final ArchiveInputStream jar = factory.createArchiveInputStream(
new BufferedInputStream(new FileInputStream(
new File(getClass().getClassLoader().getResource("bla.jar").getFile()))));
assertNotNull(jar);
assertTrue(jar instanceof ZipArchiveInputStream);
final ArchiveInputStream cpio = factory.createArchiveInputStream(
new BufferedInputStream(new FileInputStream(
new File(getClass().getClassLoader().getResource("bla.cpio").getFile()))));
assertNotNull(cpio);
assertTrue(cpio instanceof CpioArchiveInputStream);
// final ArchiveInputStream tgz = factory.createArchiveInputStream(
// new BufferedInputStream(new FileInputStream(
// new File(getClass().getClassLoader().getResource("bla.tgz").getFile()))));
// assertTrue(tgz instanceof TarArchiveInputStream);
}
|
#vulnerable code
public void testDetection() throws Exception {
final ArchiveStreamFactory factory = new ArchiveStreamFactory();
final ArchiveInputStream ar = factory.createArchiveInputStream(
new BufferedInputStream(new FileInputStream(
new File(getClass().getClassLoader().getResource("bla.ar").getFile()))));
assertNotNull(ar);
assertTrue(ar instanceof ArArchiveInputStream);
final ArchiveInputStream tar = factory.createArchiveInputStream(
new BufferedInputStream(new FileInputStream(
new File(getClass().getClassLoader().getResource("bla.tar").getFile()))));
assertNotNull(tar);
assertTrue(tar instanceof TarArchiveInputStream);
final ArchiveInputStream zip = factory.createArchiveInputStream(
new BufferedInputStream(new FileInputStream(
new File(getClass().getClassLoader().getResource("bla.zip").getFile()))));
assertNotNull(zip);
assertTrue(zip instanceof ZipArchiveInputStream);
final ArchiveInputStream jar = factory.createArchiveInputStream(
new BufferedInputStream(new FileInputStream(
new File(getClass().getClassLoader().getResource("bla.jar").getFile()))));
assertNotNull(jar);
assertTrue(jar instanceof JarArchiveInputStream);
final ArchiveInputStream cpio = factory.createArchiveInputStream(
new BufferedInputStream(new FileInputStream(
new File(getClass().getClassLoader().getResource("bla.cpio").getFile()))));
assertNotNull(cpio);
assertTrue(cpio instanceof CpioArchiveInputStream);
// final ArchiveInputStream tgz = factory.createArchiveInputStream(
// new BufferedInputStream(new FileInputStream(
// new File(getClass().getClassLoader().getResource("bla.tgz").getFile()))));
// assertTrue(tgz instanceof TarArchiveInputStream);
}
#location 16
#vulnerability type RESOURCE_LEAK
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
public void testJarUnarchiveAll() throws Exception {
final File input = getFile("bla.jar");
final InputStream is = new FileInputStream(input);
final ArchiveInputStream in = new ArchiveStreamFactory().createArchiveInputStream("jar", is);
ArchiveEntry entry = in.getNextEntry();
while (entry != null) {
File archiveEntry = new File(dir, entry.getName());
archiveEntry.getParentFile().mkdirs();
if(entry.isDirectory()){
archiveEntry.mkdir();
entry = in.getNextEntry();
continue;
}
OutputStream out = new FileOutputStream(archiveEntry);
IOUtils.copy(in, out);
out.close();
entry = in.getNextEntry();
}
in.close();
is.close();
}
|
#vulnerable code
public void testJarUnarchiveAll() throws Exception {
final File input = getFile("bla.jar");
final InputStream is = new FileInputStream(input);
final ArchiveInputStream in = new ArchiveStreamFactory().createArchiveInputStream("jar", is);
ArchiveEntry entry = in.getNextEntry();
while (entry != null) {
File archiveEntry = new File(dir, entry.getName());
archiveEntry.getParentFile().mkdirs();
if(entry.isDirectory()){
archiveEntry.mkdir();
entry = in.getNextEntry();
continue;
}
OutputStream out = new FileOutputStream(archiveEntry);
IOUtils.copy(in, out);
out.close();
entry = in.getNextEntry();
}
in.close();
}
#location 21
#vulnerability type RESOURCE_LEAK
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
public void testTarArchiveLongNameCreation() throws Exception {
String name = "testdata/12345678901234567890123456789012345678901234567890123456789012345678901234567890123456.xml";
byte[] bytes = name.getBytes();
assertEquals(bytes.length, 99);
final File output = new File(dir, "bla.tar");
final File file1 = getFile("test1.xml");
final OutputStream out = new FileOutputStream(output);
final ArchiveOutputStream os = new ArchiveStreamFactory().createArchiveOutputStream("tar", out);
final TarArchiveEntry entry = new TarArchiveEntry(name);
entry.setModTime(0);
entry.setSize(file1.length());
entry.setUserId(0);
entry.setGroupId(0);
entry.setUserName("avalon");
entry.setGroupName("excalibur");
entry.setMode(0100000);
os.putArchiveEntry(entry);
IOUtils.copy(new FileInputStream(file1), os);
os.closeArchiveEntry();
os.close();
ArchiveOutputStream os2 = null;
try {
String toLongName = "testdata/123456789012345678901234567890123456789012345678901234567890123456789012345678901234567.xml";
final File output2 = new File(dir, "bla.tar");
final OutputStream out2 = new FileOutputStream(output2);
os2 = new ArchiveStreamFactory().createArchiveOutputStream("tar", out2);
final TarArchiveEntry entry2 = new TarArchiveEntry(toLongName);
entry2.setModTime(0);
entry2.setSize(file1.length());
entry2.setUserId(0);
entry2.setGroupId(0);
entry2.setUserName("avalon");
entry2.setGroupName("excalibur");
entry2.setMode(0100000);
os.putArchiveEntry(entry);
IOUtils.copy(new FileInputStream(file1), os2);
} catch(IOException e) {
assertTrue(true);
} finally {
if (os2 != null){
os2.closeArchiveEntry();
}
}
}
|
#vulnerable code
public void testTarArchiveLongNameCreation() throws Exception {
String name = "testdata/12345678901234567890123456789012345678901234567890123456789012345678901234567890123456.xml";
byte[] bytes = name.getBytes();
assertEquals(bytes.length, 99);
final File output = new File(dir, "bla.tar");
final File file1 = getFile("test1.xml");
final OutputStream out = new FileOutputStream(output);
final ArchiveOutputStream os = new ArchiveStreamFactory().createArchiveOutputStream("tar", out);
final TarArchiveEntry entry = new TarArchiveEntry(name);
entry.setModTime(0);
entry.setSize(file1.length());
entry.setUserId(0);
entry.setGroupId(0);
entry.setUserName("avalon");
entry.setGroupName("excalibur");
entry.setMode(0100000);
os.putArchiveEntry(entry);
IOUtils.copy(new FileInputStream(file1), os);
os.closeArchiveEntry();
os.close();
ArchiveOutputStream os2 = null;
try {
String toLongName = "testdata/123456789012345678901234567890123456789012345678901234567890123456789012345678901234567.xml";
final File output2 = new File(dir, "bla.tar");
final OutputStream out2 = new FileOutputStream(output2);
os2 = new ArchiveStreamFactory().createArchiveOutputStream("tar", out2);
final TarArchiveEntry entry2 = new TarArchiveEntry(toLongName);
entry2.setModTime(0);
entry2.setSize(file1.length());
entry2.setUserId(0);
entry2.setGroupId(0);
entry2.setUserName("avalon");
entry2.setGroupName("excalibur");
entry2.setMode(0100000);
os.putArchiveEntry(entry);
IOUtils.copy(new FileInputStream(file1), os2);
} catch(IOException e) {
assertTrue(true);
} finally {
os2.closeArchiveEntry();
}
}
#location 43
#vulnerability type NULL_DEREFERENCE
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
public void testTarArchiveLongNameCreation() throws Exception {
String name = "testdata/12345678901234567890123456789012345678901234567890123456789012345678901234567890123456.xml";
byte[] bytes = name.getBytes();
assertEquals(bytes.length, 99);
final File output = new File(dir, "bla.tar");
final File file1 = getFile("test1.xml");
final OutputStream out = new FileOutputStream(output);
final ArchiveOutputStream os = new ArchiveStreamFactory().createArchiveOutputStream("tar", out);
final TarArchiveEntry entry = new TarArchiveEntry(name);
entry.setModTime(0);
entry.setSize(file1.length());
entry.setUserId(0);
entry.setGroupId(0);
entry.setUserName("avalon");
entry.setGroupName("excalibur");
entry.setMode(0100000);
os.putArchiveEntry(entry);
FileInputStream in = new FileInputStream(file1);
IOUtils.copy(in, os);
os.closeArchiveEntry();
os.close();
out.close();
in.close();
ArchiveOutputStream os2 = null;
try {
String toLongName = "testdata/123456789012345678901234567890123456789012345678901234567890123456789012345678901234567.xml";
final File output2 = new File(dir, "bla.tar");
final OutputStream out2 = new FileOutputStream(output2);
os2 = new ArchiveStreamFactory().createArchiveOutputStream("tar", out2);
final TarArchiveEntry entry2 = new TarArchiveEntry(toLongName);
entry2.setModTime(0);
entry2.setSize(file1.length());
entry2.setUserId(0);
entry2.setGroupId(0);
entry2.setUserName("avalon");
entry2.setGroupName("excalibur");
entry2.setMode(0100000);
os.putArchiveEntry(entry);
IOUtils.copy(new FileInputStream(file1), os2);
} catch(IOException e) {
assertTrue(true);
} finally {
if (os2 != null){
os2.closeArchiveEntry();
os2.close();
}
}
}
|
#vulnerable code
public void testTarArchiveLongNameCreation() throws Exception {
String name = "testdata/12345678901234567890123456789012345678901234567890123456789012345678901234567890123456.xml";
byte[] bytes = name.getBytes();
assertEquals(bytes.length, 99);
final File output = new File(dir, "bla.tar");
final File file1 = getFile("test1.xml");
final OutputStream out = new FileOutputStream(output);
final ArchiveOutputStream os = new ArchiveStreamFactory().createArchiveOutputStream("tar", out);
final TarArchiveEntry entry = new TarArchiveEntry(name);
entry.setModTime(0);
entry.setSize(file1.length());
entry.setUserId(0);
entry.setGroupId(0);
entry.setUserName("avalon");
entry.setGroupName("excalibur");
entry.setMode(0100000);
os.putArchiveEntry(entry);
IOUtils.copy(new FileInputStream(file1), os);
os.closeArchiveEntry();
os.close();
ArchiveOutputStream os2 = null;
try {
String toLongName = "testdata/123456789012345678901234567890123456789012345678901234567890123456789012345678901234567.xml";
final File output2 = new File(dir, "bla.tar");
final OutputStream out2 = new FileOutputStream(output2);
os2 = new ArchiveStreamFactory().createArchiveOutputStream("tar", out2);
final TarArchiveEntry entry2 = new TarArchiveEntry(toLongName);
entry2.setModTime(0);
entry2.setSize(file1.length());
entry2.setUserId(0);
entry2.setGroupId(0);
entry2.setUserName("avalon");
entry2.setGroupName("excalibur");
entry2.setMode(0100000);
os.putArchiveEntry(entry);
IOUtils.copy(new FileInputStream(file1), os2);
} catch(IOException e) {
assertTrue(true);
} finally {
if (os2 != null){
os2.closeArchiveEntry();
}
}
}
#location 19
#vulnerability type RESOURCE_LEAK
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
public void testArUnarchive() throws Exception {
final File output = new File(dir, "bla.ar");
{
final File file1 = getFile("test1.xml");
final File file2 = getFile("test2.xml");
final OutputStream out = new FileOutputStream(output);
final ArchiveOutputStream os = new ArchiveStreamFactory().createArchiveOutputStream("ar", out);
os.putArchiveEntry(new ArArchiveEntry("test1.xml", file1.length()));
IOUtils.copy(new FileInputStream(file1), os);
os.closeArchiveEntry();
os.putArchiveEntry(new ArArchiveEntry("test2.xml", file2.length()));
IOUtils.copy(new FileInputStream(file2), os);
os.closeArchiveEntry();
os.close();
out.close();
}
// UnArArchive Operation
final File input = output;
final InputStream is = new FileInputStream(input);
final ArchiveInputStream in = new ArchiveStreamFactory().createArchiveInputStream("ar", is);
final ArArchiveEntry entry = (ArArchiveEntry)in.getNextEntry();
File target = new File(dir, entry.getName());
final OutputStream out = new FileOutputStream(target);
IOUtils.copy(in, out);
out.close();
in.close();
is.close();
}
|
#vulnerable code
public void testArUnarchive() throws Exception {
final File output = new File(dir, "bla.ar");
{
final File file1 = getFile("test1.xml");
final File file2 = getFile("test2.xml");
final OutputStream out = new FileOutputStream(output);
final ArchiveOutputStream os = new ArchiveStreamFactory().createArchiveOutputStream("ar", out);
os.putArchiveEntry(new ArArchiveEntry("test1.xml", file1.length()));
IOUtils.copy(new FileInputStream(file1), os);
os.closeArchiveEntry();
os.putArchiveEntry(new ArArchiveEntry("test2.xml", file2.length()));
IOUtils.copy(new FileInputStream(file2), os);
os.closeArchiveEntry();
os.close();
}
// UnArArchive Operation
final File input = output;
final InputStream is = new FileInputStream(input);
final ArchiveInputStream in = new ArchiveStreamFactory().createArchiveInputStream("ar", is);
final ArArchiveEntry entry = (ArArchiveEntry)in.getNextEntry();
File target = new File(dir, entry.getName());
final OutputStream out = new FileOutputStream(target);
IOUtils.copy(in, out);
out.close();
in.close();
}
#location 31
#vulnerability type RESOURCE_LEAK
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
public void testCpioUnarchive() throws Exception {
final File output = new File(dir, "bla.cpio");
{
final File file1 = getFile("test1.xml");
final File file2 = getFile("test2.xml");
final OutputStream out = new FileOutputStream(output);
final ArchiveOutputStream os = new ArchiveStreamFactory().createArchiveOutputStream("cpio", out);
os.putArchiveEntry(new CpioArchiveEntry("test1.xml", file1.length()));
IOUtils.copy(new FileInputStream(file1), os);
os.closeArchiveEntry();
os.putArchiveEntry(new CpioArchiveEntry("test2.xml", file2.length()));
IOUtils.copy(new FileInputStream(file2), os);
os.closeArchiveEntry();
os.close();
out.close();
}
// Unarchive Operation
final File input = output;
final InputStream is = new FileInputStream(input);
final ArchiveInputStream in = new ArchiveStreamFactory().createArchiveInputStream("cpio", is);
Map result = new HashMap();
ArchiveEntry entry = null;
while ((entry = in.getNextEntry()) != null) {
File target = new File(dir, entry.getName());
final OutputStream out = new FileOutputStream(target);
IOUtils.copy(in, out);
out.close();
result.put(entry.getName(), target);
}
in.close();
int lineSepLength = System.getProperty("line.separator").length();
File t = (File)result.get("test1.xml");
assertTrue("Expected " + t.getAbsolutePath() + " to exist", t.exists());
assertEquals("length of " + t.getAbsolutePath(),
72 + 4 * lineSepLength, t.length());
t = (File)result.get("test2.xml");
assertTrue("Expected " + t.getAbsolutePath() + " to exist", t.exists());
assertEquals("length of " + t.getAbsolutePath(),
73 + 5 * lineSepLength, t.length());
}
|
#vulnerable code
public void testCpioUnarchive() throws Exception {
final File output = new File(dir, "bla.cpio");
{
final File file1 = getFile("test1.xml");
final File file2 = getFile("test2.xml");
final OutputStream out = new FileOutputStream(output);
final ArchiveOutputStream os = new ArchiveStreamFactory().createArchiveOutputStream("cpio", out);
os.putArchiveEntry(new CpioArchiveEntry("test1.xml", file1.length()));
IOUtils.copy(new FileInputStream(file1), os);
os.closeArchiveEntry();
os.putArchiveEntry(new CpioArchiveEntry("test2.xml", file2.length()));
IOUtils.copy(new FileInputStream(file2), os);
os.closeArchiveEntry();
os.close();
}
// Unarchive Operation
final File input = output;
final InputStream is = new FileInputStream(input);
final ArchiveInputStream in = new ArchiveStreamFactory().createArchiveInputStream("cpio", is);
final CpioArchiveEntry entry = (CpioArchiveEntry)in.getNextEntry();
File target = new File(dir, entry.getName());
final OutputStream out = new FileOutputStream(target);
IOUtils.copy(in, out);
out.close();
in.close();
}
#location 17
#vulnerability type RESOURCE_LEAK
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
public void testGzipCreation() throws Exception {
final File input = getFile("test1.xml");
final File output = new File(dir, "test1.xml.gz");
final OutputStream out = new FileOutputStream(output);
final CompressorOutputStream cos = new CompressorStreamFactory().createCompressorOutputStream("gz", out);
IOUtils.copy(new FileInputStream(input), cos);
cos.close();
}
|
#vulnerable code
public void testGzipCreation() throws Exception {
final File output = new File(dir, "bla.gz");
final File file1 = new File(getClass().getClassLoader().getResource("test1.xml").getFile());
final OutputStream out = new FileOutputStream(output);
CompressorOutputStream cos = new CompressorStreamFactory().createCompressorOutputStream("gz", out);
IOUtils.copy(new FileInputStream(file1), cos);
cos.close();
}
#location 6
#vulnerability type RESOURCE_LEAK
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
public void testBzip2Unarchive() throws Exception {
final File input = getFile("bla.txt.bz2");
final File output = new File(dir, "bla.txt");
final InputStream is = new FileInputStream(input);
final CompressorInputStream in = new CompressorStreamFactory().createCompressorInputStream("bzip2", is);
FileOutputStream os = new FileOutputStream(output);
IOUtils.copy(in, os);
is.close();
os.close();
}
|
#vulnerable code
public void testBzip2Unarchive() throws Exception {
final File input = getFile("bla.txt.bz2");
final File output = new File(dir, "bla.txt");
final InputStream is = new FileInputStream(input);
final CompressorInputStream in = new CompressorStreamFactory().createCompressorInputStream("bzip2", is);
IOUtils.copy(in, new FileOutputStream(output));
in.close();
}
#location 6
#vulnerability type RESOURCE_LEAK
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
protected void checkArchiveContent(File archive, List expected)
throws Exception {
final InputStream is = new FileInputStream(archive);
try {
final BufferedInputStream buf = new BufferedInputStream(is);
final ArchiveInputStream in = factory.createArchiveInputStream(buf);
this.checkArchiveContent(in, expected);
} finally {
is.close();
}
}
|
#vulnerable code
protected void checkArchiveContent(File archive, List expected)
throws Exception {
final InputStream is = new FileInputStream(archive);
try {
final BufferedInputStream buf = new BufferedInputStream(is);
final ArchiveInputStream in =
archive.getName().endsWith(".tar") ? // tar does not autodetect at present
factory.createArchiveInputStream("tar", buf) :
factory.createArchiveInputStream(buf);
this.checkArchiveContent(in, expected);
} finally {
is.close();
}
}
#location 8
#vulnerability type RESOURCE_LEAK
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
public void testCpioUnarchive() throws Exception {
final File output = new File(dir, "bla.cpio");
{
final File file1 = getFile("test1.xml");
final File file2 = getFile("test2.xml");
final OutputStream out = new FileOutputStream(output);
final ArchiveOutputStream os = new ArchiveStreamFactory().createArchiveOutputStream("cpio", out);
os.putArchiveEntry(new CpioArchiveEntry("test1.xml", file1.length()));
IOUtils.copy(new FileInputStream(file1), os);
os.closeArchiveEntry();
os.putArchiveEntry(new CpioArchiveEntry("test2.xml", file2.length()));
IOUtils.copy(new FileInputStream(file2), os);
os.closeArchiveEntry();
os.close();
out.close();
}
// Unarchive Operation
final File input = output;
final InputStream is = new FileInputStream(input);
final ArchiveInputStream in = new ArchiveStreamFactory().createArchiveInputStream("cpio", is);
Map result = new HashMap();
ArchiveEntry entry = null;
while ((entry = in.getNextEntry()) != null) {
File target = new File(dir, entry.getName());
final OutputStream out = new FileOutputStream(target);
IOUtils.copy(in, out);
out.close();
result.put(entry.getName(), target);
}
in.close();
int lineSepLength = System.getProperty("line.separator").length();
File t = (File)result.get("test1.xml");
assertTrue("Expected " + t.getAbsolutePath() + " to exist", t.exists());
assertEquals("length of " + t.getAbsolutePath(),
72 + 4 * lineSepLength, t.length());
t = (File)result.get("test2.xml");
assertTrue("Expected " + t.getAbsolutePath() + " to exist", t.exists());
assertEquals("length of " + t.getAbsolutePath(),
73 + 5 * lineSepLength, t.length());
}
|
#vulnerable code
public void testCpioUnarchive() throws Exception {
final File output = new File(dir, "bla.cpio");
{
final File file1 = getFile("test1.xml");
final File file2 = getFile("test2.xml");
final OutputStream out = new FileOutputStream(output);
final ArchiveOutputStream os = new ArchiveStreamFactory().createArchiveOutputStream("cpio", out);
os.putArchiveEntry(new CpioArchiveEntry("test1.xml", file1.length()));
IOUtils.copy(new FileInputStream(file1), os);
os.closeArchiveEntry();
os.putArchiveEntry(new CpioArchiveEntry("test2.xml", file2.length()));
IOUtils.copy(new FileInputStream(file2), os);
os.closeArchiveEntry();
os.close();
}
// Unarchive Operation
final File input = output;
final InputStream is = new FileInputStream(input);
final ArchiveInputStream in = new ArchiveStreamFactory().createArchiveInputStream("cpio", is);
final CpioArchiveEntry entry = (CpioArchiveEntry)in.getNextEntry();
File target = new File(dir, entry.getName());
final OutputStream out = new FileOutputStream(target);
IOUtils.copy(in, out);
out.close();
in.close();
}
#location 8
#vulnerability type RESOURCE_LEAK
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
public void testCpioUnarchive() throws Exception {
final File output = new File(dir, "bla.cpio");
{
final File file1 = getFile("test1.xml");
final File file2 = getFile("test2.xml");
final OutputStream out = new FileOutputStream(output);
final ArchiveOutputStream os = new ArchiveStreamFactory().createArchiveOutputStream("cpio", out);
CpioArchiveEntry entry = new CpioArchiveEntry("test1.xml", file1.length());
entry.setMode(CpioConstants.C_ISREG);
os.putArchiveEntry(entry);
IOUtils.copy(new FileInputStream(file1), os);
os.closeArchiveEntry();
entry = new CpioArchiveEntry("test2.xml", file2.length());
entry.setMode(CpioConstants.C_ISREG);
os.putArchiveEntry(entry);
IOUtils.copy(new FileInputStream(file2), os);
os.closeArchiveEntry();
os.close();
out.close();
}
// Unarchive Operation
final File input = output;
final InputStream is = new FileInputStream(input);
final ArchiveInputStream in = new ArchiveStreamFactory().createArchiveInputStream("cpio", is);
Map result = new HashMap();
ArchiveEntry entry = null;
while ((entry = in.getNextEntry()) != null) {
File target = new File(dir, entry.getName());
final OutputStream out = new FileOutputStream(target);
IOUtils.copy(in, out);
out.close();
result.put(entry.getName(), target);
}
in.close();
is.close();
int lineSepLength = System.getProperty("line.separator").length();
File t = (File)result.get("test1.xml");
assertTrue("Expected " + t.getAbsolutePath() + " to exist", t.exists());
assertEquals("length of " + t.getAbsolutePath(),
72 + 4 * lineSepLength, t.length());
t = (File)result.get("test2.xml");
assertTrue("Expected " + t.getAbsolutePath() + " to exist", t.exists());
assertEquals("length of " + t.getAbsolutePath(),
73 + 5 * lineSepLength, t.length());
}
|
#vulnerable code
public void testCpioUnarchive() throws Exception {
final File output = new File(dir, "bla.cpio");
{
final File file1 = getFile("test1.xml");
final File file2 = getFile("test2.xml");
final OutputStream out = new FileOutputStream(output);
final ArchiveOutputStream os = new ArchiveStreamFactory().createArchiveOutputStream("cpio", out);
os.putArchiveEntry(new CpioArchiveEntry("test1.xml", file1.length()));
IOUtils.copy(new FileInputStream(file1), os);
os.closeArchiveEntry();
os.putArchiveEntry(new CpioArchiveEntry("test2.xml", file2.length()));
IOUtils.copy(new FileInputStream(file2), os);
os.closeArchiveEntry();
os.close();
out.close();
}
// Unarchive Operation
final File input = output;
final InputStream is = new FileInputStream(input);
final ArchiveInputStream in = new ArchiveStreamFactory().createArchiveInputStream("cpio", is);
Map result = new HashMap();
ArchiveEntry entry = null;
while ((entry = in.getNextEntry()) != null) {
File target = new File(dir, entry.getName());
final OutputStream out = new FileOutputStream(target);
IOUtils.copy(in, out);
out.close();
result.put(entry.getName(), target);
}
in.close();
is.close();
int lineSepLength = System.getProperty("line.separator").length();
File t = (File)result.get("test1.xml");
assertTrue("Expected " + t.getAbsolutePath() + " to exist", t.exists());
assertEquals("length of " + t.getAbsolutePath(),
72 + 4 * lineSepLength, t.length());
t = (File)result.get("test2.xml");
assertTrue("Expected " + t.getAbsolutePath() + " to exist", t.exists());
assertEquals("length of " + t.getAbsolutePath(),
73 + 5 * lineSepLength, t.length());
}
#location 10
#vulnerability type RESOURCE_LEAK
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
protected File createArchive(String archivename) throws Exception {
ArchiveOutputStream out = null;
OutputStream stream = null;
try {
archive = File.createTempFile("test", "." + archivename);
archiveList = new ArrayList();
stream = new FileOutputStream(archive);
out = factory.createArchiveOutputStream(archivename, stream);
final File file1 = getFile("test1.xml");
final File file2 = getFile("test2.xml");
final File file3 = getFile("test3.xml");
final File file4 = getFile("test4.xml");
final File file5 = getFile("test.txt");
final File file6 = getFile("test with spaces.txt");
addArchiveEntry(out, "testdata/test1.xml", file1);
addArchiveEntry(out, "testdata/test2.xml", file2);
addArchiveEntry(out, "test/test3.xml", file3);
addArchiveEntry(out, "bla/test4.xml", file4);
addArchiveEntry(out, "bla/test5.xml", file4);
addArchiveEntry(out, "bla/blubber/test6.xml", file4);
addArchiveEntry(out, "test.txt", file5);
addArchiveEntry(out, "something/bla", file6);
addArchiveEntry(out, "test with spaces.txt", file6);
return archive;
} finally {
if (out != null) {
out.close();
} else if (stream != null) {
stream.close();
}
}
}
|
#vulnerable code
protected File createArchive(String archivename) throws Exception {
ArchiveOutputStream out = null;
OutputStream stream = null;
try {
archive = File.createTempFile("test", "." + archivename);
stream = new FileOutputStream(archive);
out = new ArchiveStreamFactory().createArchiveOutputStream(
archivename, stream);
final File file1 = getFile("test1.xml");
final File file2 = getFile("test2.xml");
final File file3 = getFile("test3.xml");
final File file4 = getFile("test4.xml");
final File file5 = getFile("test.txt");
final File file6 = getFile("test with spaces.txt");
ZipArchiveEntry entry = new ZipArchiveEntry("testdata/test1.xml");
entry.setSize(file1.length());
out.putArchiveEntry(entry);
IOUtils.copy(new FileInputStream(file1), out);
out.closeArchiveEntry();
entry = new ZipArchiveEntry("testdata/test2.xml");
entry.setSize(file2.length());
out.putArchiveEntry(entry);
IOUtils.copy(new FileInputStream(file2), out);
out.closeArchiveEntry();
entry = new ZipArchiveEntry("test/test3.xml");
entry.setSize(file3.length());
out.putArchiveEntry(entry);
IOUtils.copy(new FileInputStream(file3), out);
out.closeArchiveEntry();
entry = new ZipArchiveEntry("bla/test4.xml");
entry.setSize(file4.length());
out.putArchiveEntry(entry);
IOUtils.copy(new FileInputStream(file4), out);
out.closeArchiveEntry();
entry = new ZipArchiveEntry("bla/test5.xml");
entry.setSize(file4.length());
out.putArchiveEntry(entry);
IOUtils.copy(new FileInputStream(file4), out);
out.closeArchiveEntry();
entry = new ZipArchiveEntry("bla/blubber/test6.xml");
entry.setSize(file4.length());
out.putArchiveEntry(entry);
IOUtils.copy(new FileInputStream(file4), out);
out.closeArchiveEntry();
entry = new ZipArchiveEntry("test.txt");
entry.setSize(file5.length());
out.putArchiveEntry(entry);
IOUtils.copy(new FileInputStream(file5), out);
out.closeArchiveEntry();
entry = new ZipArchiveEntry("something/bla");
entry.setSize(file6.length());
out.putArchiveEntry(entry);
IOUtils.copy(new FileInputStream(file6), out);
out.closeArchiveEntry();
entry = new ZipArchiveEntry("test with spaces.txt");
entry.setSize(file6.length());
out.putArchiveEntry(entry);
IOUtils.copy(new FileInputStream(file6), out);
out.closeArchiveEntry();
return archive;
} finally {
if (out != null) {
out.close();
} else if (stream != null) {
stream.close();
}
}
}
#location 27
#vulnerability type RESOURCE_LEAK
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
public void testCpioUnarchive() throws Exception {
final File output = new File(dir, "bla.cpio");
{
final File file1 = getFile("test1.xml");
final File file2 = getFile("test2.xml");
final OutputStream out = new FileOutputStream(output);
final ArchiveOutputStream os = new ArchiveStreamFactory().createArchiveOutputStream("cpio", out);
os.putArchiveEntry(new CpioArchiveEntry("test1.xml", file1.length()));
IOUtils.copy(new FileInputStream(file1), os);
os.closeArchiveEntry();
os.putArchiveEntry(new CpioArchiveEntry("test2.xml", file2.length()));
IOUtils.copy(new FileInputStream(file2), os);
os.closeArchiveEntry();
os.close();
out.close();
}
// Unarchive Operation
final File input = output;
final InputStream is = new FileInputStream(input);
final ArchiveInputStream in = new ArchiveStreamFactory().createArchiveInputStream("cpio", is);
Map result = new HashMap();
ArchiveEntry entry = null;
while ((entry = in.getNextEntry()) != null) {
File target = new File(dir, entry.getName());
final OutputStream out = new FileOutputStream(target);
IOUtils.copy(in, out);
out.close();
result.put(entry.getName(), target);
}
in.close();
int lineSepLength = System.getProperty("line.separator").length();
File t = (File)result.get("test1.xml");
assertTrue("Expected " + t.getAbsolutePath() + " to exist", t.exists());
assertEquals("length of " + t.getAbsolutePath(),
72 + 4 * lineSepLength, t.length());
t = (File)result.get("test2.xml");
assertTrue("Expected " + t.getAbsolutePath() + " to exist", t.exists());
assertEquals("length of " + t.getAbsolutePath(),
73 + 5 * lineSepLength, t.length());
}
|
#vulnerable code
public void testCpioUnarchive() throws Exception {
final File output = new File(dir, "bla.cpio");
{
final File file1 = getFile("test1.xml");
final File file2 = getFile("test2.xml");
final OutputStream out = new FileOutputStream(output);
final ArchiveOutputStream os = new ArchiveStreamFactory().createArchiveOutputStream("cpio", out);
os.putArchiveEntry(new CpioArchiveEntry("test1.xml", file1.length()));
IOUtils.copy(new FileInputStream(file1), os);
os.closeArchiveEntry();
os.putArchiveEntry(new CpioArchiveEntry("test2.xml", file2.length()));
IOUtils.copy(new FileInputStream(file2), os);
os.closeArchiveEntry();
os.close();
}
// Unarchive Operation
final File input = output;
final InputStream is = new FileInputStream(input);
final ArchiveInputStream in = new ArchiveStreamFactory().createArchiveInputStream("cpio", is);
final CpioArchiveEntry entry = (CpioArchiveEntry)in.getNextEntry();
File target = new File(dir, entry.getName());
final OutputStream out = new FileOutputStream(target);
IOUtils.copy(in, out);
out.close();
in.close();
}
#location 17
#vulnerability type RESOURCE_LEAK
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
public void testCpioUnarchive() throws Exception {
final File output = new File(dir, "bla.cpio");
{
final File file1 = getFile("test1.xml");
final File file2 = getFile("test2.xml");
final OutputStream out = new FileOutputStream(output);
final ArchiveOutputStream os = new ArchiveStreamFactory().createArchiveOutputStream("cpio", out);
CpioArchiveEntry entry = new CpioArchiveEntry("test1.xml", file1.length());
entry.setMode(CpioConstants.C_ISREG);
os.putArchiveEntry(entry);
IOUtils.copy(new FileInputStream(file1), os);
os.closeArchiveEntry();
entry = new CpioArchiveEntry("test2.xml", file2.length());
entry.setMode(CpioConstants.C_ISREG);
os.putArchiveEntry(entry);
IOUtils.copy(new FileInputStream(file2), os);
os.closeArchiveEntry();
os.close();
out.close();
}
// Unarchive Operation
final File input = output;
final InputStream is = new FileInputStream(input);
final ArchiveInputStream in = new ArchiveStreamFactory().createArchiveInputStream("cpio", is);
Map result = new HashMap();
ArchiveEntry entry = null;
while ((entry = in.getNextEntry()) != null) {
File target = new File(dir, entry.getName());
final OutputStream out = new FileOutputStream(target);
IOUtils.copy(in, out);
out.close();
result.put(entry.getName(), target);
}
in.close();
is.close();
int lineSepLength = System.getProperty("line.separator").length();
File t = (File)result.get("test1.xml");
assertTrue("Expected " + t.getAbsolutePath() + " to exist", t.exists());
assertEquals("length of " + t.getAbsolutePath(),
72 + 4 * lineSepLength, t.length());
t = (File)result.get("test2.xml");
assertTrue("Expected " + t.getAbsolutePath() + " to exist", t.exists());
assertEquals("length of " + t.getAbsolutePath(),
73 + 5 * lineSepLength, t.length());
}
|
#vulnerable code
public void testCpioUnarchive() throws Exception {
final File output = new File(dir, "bla.cpio");
{
final File file1 = getFile("test1.xml");
final File file2 = getFile("test2.xml");
final OutputStream out = new FileOutputStream(output);
final ArchiveOutputStream os = new ArchiveStreamFactory().createArchiveOutputStream("cpio", out);
os.putArchiveEntry(new CpioArchiveEntry("test1.xml", file1.length()));
IOUtils.copy(new FileInputStream(file1), os);
os.closeArchiveEntry();
os.putArchiveEntry(new CpioArchiveEntry("test2.xml", file2.length()));
IOUtils.copy(new FileInputStream(file2), os);
os.closeArchiveEntry();
os.close();
out.close();
}
// Unarchive Operation
final File input = output;
final InputStream is = new FileInputStream(input);
final ArchiveInputStream in = new ArchiveStreamFactory().createArchiveInputStream("cpio", is);
Map result = new HashMap();
ArchiveEntry entry = null;
while ((entry = in.getNextEntry()) != null) {
File target = new File(dir, entry.getName());
final OutputStream out = new FileOutputStream(target);
IOUtils.copy(in, out);
out.close();
result.put(entry.getName(), target);
}
in.close();
is.close();
int lineSepLength = System.getProperty("line.separator").length();
File t = (File)result.get("test1.xml");
assertTrue("Expected " + t.getAbsolutePath() + " to exist", t.exists());
assertEquals("length of " + t.getAbsolutePath(),
72 + 4 * lineSepLength, t.length());
t = (File)result.get("test2.xml");
assertTrue("Expected " + t.getAbsolutePath() + " to exist", t.exists());
assertEquals("length of " + t.getAbsolutePath(),
73 + 5 * lineSepLength, t.length());
}
#location 14
#vulnerability type RESOURCE_LEAK
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
public void testBzipCreation() throws Exception {
final File input = getFile("test.txt");
final File output = new File(dir, "test.txt.bz2");
final OutputStream out = new FileOutputStream(output);
final CompressorOutputStream cos = new CompressorStreamFactory().createCompressorOutputStream("bzip2", out);
FileInputStream in = new FileInputStream(input);
IOUtils.copy(in, cos);
cos.close();
in.close();
}
|
#vulnerable code
public void testBzipCreation() throws Exception {
final File input = getFile("test.txt");
final File output = new File(dir, "test.txt.bz2");
final OutputStream out = new FileOutputStream(output);
final CompressorOutputStream cos = new CompressorStreamFactory().createCompressorOutputStream("bzip2", out);
IOUtils.copy(new FileInputStream(input), cos);
cos.close();
}
#location 6
#vulnerability type RESOURCE_LEAK
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
public void testArDelete() throws Exception {
final File output = new File(dir, "bla.ar");
{
// create
final File file1 = getFile("test1.xml");
final File file2 = getFile("test2.xml");
final OutputStream out = new FileOutputStream(output);
final ArchiveOutputStream os = new ArchiveStreamFactory().createArchiveOutputStream("ar", out);
os.putArchiveEntry(new ArArchiveEntry("test1.xml", file1.length()));
IOUtils.copy(new FileInputStream(file1), os);
os.closeArchiveEntry();
os.putArchiveEntry(new ArArchiveEntry("test2.xml", file2.length()));
IOUtils.copy(new FileInputStream(file2), os);
os.closeArchiveEntry();
os.close();
out.close();
}
assertEquals(282, output.length());
final File output2 = new File(dir, "bla2.ar");
int copied = 0;
int deleted = 0;
{
// remove all but one file
final InputStream is = new FileInputStream(output);
final OutputStream os = new FileOutputStream(output2);
final ArchiveOutputStream aos = new ArchiveStreamFactory().createArchiveOutputStream("ar", os);
final ArchiveInputStream ais = new ArchiveStreamFactory().createArchiveInputStream(new BufferedInputStream(is));
while(true) {
final ArArchiveEntry entry = (ArArchiveEntry)ais.getNextEntry();
if (entry == null) {
break;
}
if ("test1.xml".equals(entry.getName())) {
aos.putArchiveEntry(entry);
IOUtils.copy(ais, aos);
aos.closeArchiveEntry();
copied++;
} else {
IOUtils.copy(ais, new ByteArrayOutputStream());
deleted++;
}
}
ais.close();
aos.close();
is.close();
os.close();
}
assertEquals(1, copied);
assertEquals(1, deleted);
assertEquals(144, output2.length());
long files = 0;
long sum = 0;
{
final InputStream is = new FileInputStream(output2);
final ArchiveInputStream ais = new ArchiveStreamFactory().createArchiveInputStream(new BufferedInputStream(is));
while(true) {
final ArArchiveEntry entry = (ArArchiveEntry)ais.getNextEntry();
if (entry == null) {
break;
}
IOUtils.copy(ais, new ByteArrayOutputStream());
sum += entry.getLength();
files++;
}
ais.close();
is.close();
}
assertEquals(1, files);
assertEquals(76, sum);
}
|
#vulnerable code
public void testArDelete() throws Exception {
final File output = new File(dir, "bla.ar");
{
// create
final File file1 = getFile("test1.xml");
final File file2 = getFile("test2.xml");
final OutputStream out = new FileOutputStream(output);
final ArchiveOutputStream os = new ArchiveStreamFactory().createArchiveOutputStream("ar", out);
os.putArchiveEntry(new ArArchiveEntry("test1.xml", file1.length()));
IOUtils.copy(new FileInputStream(file1), os);
os.closeArchiveEntry();
os.putArchiveEntry(new ArArchiveEntry("test2.xml", file2.length()));
IOUtils.copy(new FileInputStream(file2), os);
os.closeArchiveEntry();
os.close();
out.close();
}
final File output2 = new File(dir, "bla2.ar");
{
// remove all but one file
final InputStream is = new FileInputStream(output);
final OutputStream os = new FileOutputStream(output2);
final ArchiveOutputStream aos = new ArchiveStreamFactory().createArchiveOutputStream("ar", os);
final ArchiveInputStream ais = new ArchiveStreamFactory().createArchiveInputStream(new BufferedInputStream(is));
while(true) {
final ArArchiveEntry entry = (ArArchiveEntry)ais.getNextEntry();
if (entry == null) {
break;
}
if ("test1.xml".equals(entry.getName())) {
aos.putArchiveEntry(entry);
IOUtils.copy(ais, aos);
} else {
IOUtils.copy(ais, new ByteArrayOutputStream());
}
}
ais.close();
aos.close();
is.close();
os.close();
}
long sum = 0;
{
final InputStream is = new FileInputStream(output2);
final ArchiveInputStream ais = new ArchiveStreamFactory().createArchiveInputStream(new BufferedInputStream(is));
while(true) {
final ArArchiveEntry entry = (ArArchiveEntry)ais.getNextEntry();
if (entry == null) {
break;
}
IOUtils.copy(ais, new ByteArrayOutputStream());
sum += entry.getLength();
}
ais.close();
is.close();
}
assertEquals(76, sum);
}
#location 20
#vulnerability type RESOURCE_LEAK
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
public void testBzip2Unarchive() throws Exception {
final File input = getFile("bla.txt.bz2");
final File output = new File(dir, "bla.txt");
final InputStream is = new FileInputStream(input);
final CompressorInputStream in = new CompressorStreamFactory().createCompressorInputStream("bzip2", is);
IOUtils.copy(in, new FileOutputStream(output));
in.close();
}
|
#vulnerable code
public void testBzip2Unarchive() throws Exception {
final File output = new File(dir, "test-entpackt.txt");
System.out.println(dir);
final File input = new File(getClass().getClassLoader().getResource("bla.txt.bz2").getFile());
final InputStream is = new FileInputStream(input);
//final CompressorInputStream in = new CompressorStreamFactory().createCompressorInputStream("bzip2", is);
final CompressorInputStream in = new BZip2CompressorInputStream(is);
IOUtils.copy(in, new FileOutputStream(output));
in.close();
}
#location 10
#vulnerability type RESOURCE_LEAK
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
public void testZipArchiveCreation() throws Exception {
// Archive
final File output = new File(dir, "bla.zip");
final File file1 = getFile("test1.xml");
final File file2 = getFile("test2.xml");
final OutputStream out = new FileOutputStream(output);
ArchiveOutputStream os = null;
try {
os = new ArchiveStreamFactory()
.createArchiveOutputStream("zip", out);
os.putArchiveEntry(new ZipArchiveEntry("testdata/test1.xml"));
IOUtils.copy(new FileInputStream(file1), os);
os.closeArchiveEntry();
os.putArchiveEntry(new ZipArchiveEntry("testdata/test2.xml"));
IOUtils.copy(new FileInputStream(file2), os);
os.closeArchiveEntry();
} finally {
if (os != null) {
os.close();
} else {
out.close();
}
}
// Unarchive the same
List results = new ArrayList();
final InputStream is = new FileInputStream(output);
ArchiveInputStream in = null;
try {
in = new ArchiveStreamFactory()
.createArchiveInputStream("zip", is);
ZipArchiveEntry entry = null;
while((entry = (ZipArchiveEntry)in.getNextEntry()) != null) {
File outfile = new File(resultDir.getCanonicalPath() + "/result/" + entry.getName());
outfile.getParentFile().mkdirs();
OutputStream o = new FileOutputStream(outfile);
try {
IOUtils.copy(in, o);
} finally {
o.close();
}
results.add(outfile);
}
} finally {
if (in != null) {
in.close();
} else {
is.close();
}
}
assertEquals(results.size(), 2);
File result = (File)results.get(0);
assertEquals(file1.length(), result.length());
result = (File)results.get(1);
assertEquals(file2.length(), result.length());
}
|
#vulnerable code
public void testZipArchiveCreation() throws Exception {
// Archive
final File output = new File(dir, "bla.zip");
final File file1 = getFile("test1.xml");
final File file2 = getFile("test2.xml");
{
final OutputStream out = new FileOutputStream(output);
final ArchiveOutputStream os = new ArchiveStreamFactory().createArchiveOutputStream("zip", out);
os.putArchiveEntry(new ZipArchiveEntry("testdata/test1.xml"));
IOUtils.copy(new FileInputStream(file1), os);
os.closeArchiveEntry();
os.putArchiveEntry(new ZipArchiveEntry("testdata/test2.xml"));
IOUtils.copy(new FileInputStream(file2), os);
os.closeArchiveEntry();
os.close();
}
// Unarchive the same
List results = new ArrayList();
{
final InputStream is = new FileInputStream(output);
final ArchiveInputStream in = new ArchiveStreamFactory().createArchiveInputStream("zip", is);
File result = File.createTempFile("dir-result", "");
result.delete();
result.mkdir();
ZipArchiveEntry entry = null;
while((entry = (ZipArchiveEntry)in.getNextEntry()) != null) {
File outfile = new File(result.getCanonicalPath() + "/result/" + entry.getName());
outfile.getParentFile().mkdirs();
OutputStream out = new FileOutputStream(outfile);
IOUtils.copy(in, out);
out.close();
results.add(outfile);
}
in.close();
}
assertEquals(results.size(), 2);
File result = (File)results.get(0);
assertEquals(file1.length(), result.length());
result = (File)results.get(1);
assertEquals(file2.length(), result.length());
}
#location 18
#vulnerability type RESOURCE_LEAK
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
public void testCpioUnarchive() throws Exception {
final File output = new File(dir, "bla.cpio");
{
final File file1 = getFile("test1.xml");
final File file2 = getFile("test2.xml");
final OutputStream out = new FileOutputStream(output);
final ArchiveOutputStream os = new ArchiveStreamFactory().createArchiveOutputStream("cpio", out);
os.putArchiveEntry(new CpioArchiveEntry("test1.xml", file1.length()));
IOUtils.copy(new FileInputStream(file1), os);
os.closeArchiveEntry();
os.putArchiveEntry(new CpioArchiveEntry("test2.xml", file2.length()));
IOUtils.copy(new FileInputStream(file2), os);
os.closeArchiveEntry();
os.close();
out.close();
}
// Unarchive Operation
final File input = output;
final InputStream is = new FileInputStream(input);
final ArchiveInputStream in = new ArchiveStreamFactory().createArchiveInputStream("cpio", is);
Map result = new HashMap();
ArchiveEntry entry = null;
while ((entry = in.getNextEntry()) != null) {
File target = new File(dir, entry.getName());
final OutputStream out = new FileOutputStream(target);
IOUtils.copy(in, out);
out.close();
result.put(entry.getName(), target);
}
in.close();
int lineSepLength = System.getProperty("line.separator").length();
File t = (File)result.get("test1.xml");
assertTrue("Expected " + t.getAbsolutePath() + " to exist", t.exists());
assertEquals("length of " + t.getAbsolutePath(),
72 + 4 * lineSepLength, t.length());
t = (File)result.get("test2.xml");
assertTrue("Expected " + t.getAbsolutePath() + " to exist", t.exists());
assertEquals("length of " + t.getAbsolutePath(),
73 + 5 * lineSepLength, t.length());
}
|
#vulnerable code
public void testCpioUnarchive() throws Exception {
final File output = new File(dir, "bla.cpio");
{
final File file1 = getFile("test1.xml");
final File file2 = getFile("test2.xml");
final OutputStream out = new FileOutputStream(output);
final ArchiveOutputStream os = new ArchiveStreamFactory().createArchiveOutputStream("cpio", out);
os.putArchiveEntry(new CpioArchiveEntry("test1.xml", file1.length()));
IOUtils.copy(new FileInputStream(file1), os);
os.closeArchiveEntry();
os.putArchiveEntry(new CpioArchiveEntry("test2.xml", file2.length()));
IOUtils.copy(new FileInputStream(file2), os);
os.closeArchiveEntry();
os.close();
}
// Unarchive Operation
final File input = output;
final InputStream is = new FileInputStream(input);
final ArchiveInputStream in = new ArchiveStreamFactory().createArchiveInputStream("cpio", is);
final CpioArchiveEntry entry = (CpioArchiveEntry)in.getNextEntry();
File target = new File(dir, entry.getName());
final OutputStream out = new FileOutputStream(target);
IOUtils.copy(in, out);
out.close();
in.close();
}
#location 17
#vulnerability type RESOURCE_LEAK
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
public void testDetection() throws Exception {
final ArchiveStreamFactory factory = new ArchiveStreamFactory();
final ArchiveInputStream ar = factory.createArchiveInputStream(
new BufferedInputStream(new FileInputStream(
new File(getClass().getClassLoader().getResource("bla.ar").getFile()))));
assertNotNull(ar);
assertTrue(ar instanceof ArArchiveInputStream);
final ArchiveInputStream tar = factory.createArchiveInputStream(
new BufferedInputStream(new FileInputStream(
new File(getClass().getClassLoader().getResource("bla.tar").getFile()))));
assertNotNull(tar);
assertTrue(tar instanceof TarArchiveInputStream);
final ArchiveInputStream zip = factory.createArchiveInputStream(
new BufferedInputStream(new FileInputStream(
new File(getClass().getClassLoader().getResource("bla.zip").getFile()))));
assertNotNull(zip);
assertTrue(zip instanceof ZipArchiveInputStream);
final ArchiveInputStream jar = factory.createArchiveInputStream(
new BufferedInputStream(new FileInputStream(
new File(getClass().getClassLoader().getResource("bla.jar").getFile()))));
assertNotNull(jar);
assertTrue(jar instanceof ZipArchiveInputStream);
final ArchiveInputStream cpio = factory.createArchiveInputStream(
new BufferedInputStream(new FileInputStream(
new File(getClass().getClassLoader().getResource("bla.cpio").getFile()))));
assertNotNull(cpio);
assertTrue(cpio instanceof CpioArchiveInputStream);
// final ArchiveInputStream tgz = factory.createArchiveInputStream(
// new BufferedInputStream(new FileInputStream(
// new File(getClass().getClassLoader().getResource("bla.tgz").getFile()))));
// assertTrue(tgz instanceof TarArchiveInputStream);
}
|
#vulnerable code
public void testDetection() throws Exception {
final ArchiveStreamFactory factory = new ArchiveStreamFactory();
final ArchiveInputStream ar = factory.createArchiveInputStream(
new BufferedInputStream(new FileInputStream(
new File(getClass().getClassLoader().getResource("bla.ar").getFile()))));
assertNotNull(ar);
assertTrue(ar instanceof ArArchiveInputStream);
final ArchiveInputStream tar = factory.createArchiveInputStream(
new BufferedInputStream(new FileInputStream(
new File(getClass().getClassLoader().getResource("bla.tar").getFile()))));
assertNotNull(tar);
assertTrue(tar instanceof TarArchiveInputStream);
final ArchiveInputStream zip = factory.createArchiveInputStream(
new BufferedInputStream(new FileInputStream(
new File(getClass().getClassLoader().getResource("bla.zip").getFile()))));
assertNotNull(zip);
assertTrue(zip instanceof ZipArchiveInputStream);
final ArchiveInputStream jar = factory.createArchiveInputStream(
new BufferedInputStream(new FileInputStream(
new File(getClass().getClassLoader().getResource("bla.jar").getFile()))));
assertNotNull(jar);
assertTrue(jar instanceof JarArchiveInputStream);
final ArchiveInputStream cpio = factory.createArchiveInputStream(
new BufferedInputStream(new FileInputStream(
new File(getClass().getClassLoader().getResource("bla.cpio").getFile()))));
assertNotNull(cpio);
assertTrue(cpio instanceof CpioArchiveInputStream);
// final ArchiveInputStream tgz = factory.createArchiveInputStream(
// new BufferedInputStream(new FileInputStream(
// new File(getClass().getClassLoader().getResource("bla.tgz").getFile()))));
// assertTrue(tgz instanceof TarArchiveInputStream);
}
#location 4
#vulnerability type RESOURCE_LEAK
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
protected File createEmptyArchive(String archivename) throws Exception {
ArchiveOutputStream out = null;
OutputStream stream = null;
archiveList = new ArrayList();
try {
archive = File.createTempFile("empty", "." + archivename);
stream = new FileOutputStream(archive);
out = factory.createArchiveOutputStream(archivename, stream);
out.finish();
} finally {
if (out != null) {
out.close();
} else if (stream != null) {
stream.close();
}
}
return archive;
}
|
#vulnerable code
protected File createEmptyArchive(String archivename) throws Exception {
ArchiveOutputStream out = null;
OutputStream stream = null;
archiveList = new ArrayList();
try {
archive = File.createTempFile("empty", "." + archivename);
stream = new FileOutputStream(archive);
out = factory.createArchiveOutputStream(archivename, stream);
} finally {
if (out != null) {
out.close();
} else if (stream != null) {
stream.close();
}
}
return archive;
}
#location 11
#vulnerability type RESOURCE_LEAK
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
protected File createArchive(String archivename) throws Exception {
ArchiveOutputStream out = null;
OutputStream stream = null;
try {
archive = File.createTempFile("test", "." + archivename);
archiveList = new ArrayList();
stream = new FileOutputStream(archive);
out = factory.createArchiveOutputStream(archivename, stream);
final File file1 = getFile("test1.xml");
final File file2 = getFile("test2.xml");
final File file3 = getFile("test3.xml");
final File file4 = getFile("test4.xml");
final File file5 = getFile("test.txt");
final File file6 = getFile("test with spaces.txt");
addArchiveEntry(out, "testdata/test1.xml", file1);
addArchiveEntry(out, "testdata/test2.xml", file2);
addArchiveEntry(out, "test/test3.xml", file3);
addArchiveEntry(out, "bla/test4.xml", file4);
addArchiveEntry(out, "bla/test5.xml", file4);
addArchiveEntry(out, "bla/blubber/test6.xml", file4);
addArchiveEntry(out, "test.txt", file5);
addArchiveEntry(out, "something/bla", file6);
addArchiveEntry(out, "test with spaces.txt", file6);
return archive;
} finally {
if (out != null) {
out.close();
} else if (stream != null) {
stream.close();
}
}
}
|
#vulnerable code
protected File createArchive(String archivename) throws Exception {
ArchiveOutputStream out = null;
OutputStream stream = null;
try {
archive = File.createTempFile("test", "." + archivename);
stream = new FileOutputStream(archive);
out = new ArchiveStreamFactory().createArchiveOutputStream(
archivename, stream);
final File file1 = getFile("test1.xml");
final File file2 = getFile("test2.xml");
final File file3 = getFile("test3.xml");
final File file4 = getFile("test4.xml");
final File file5 = getFile("test.txt");
final File file6 = getFile("test with spaces.txt");
ZipArchiveEntry entry = new ZipArchiveEntry("testdata/test1.xml");
entry.setSize(file1.length());
out.putArchiveEntry(entry);
IOUtils.copy(new FileInputStream(file1), out);
out.closeArchiveEntry();
entry = new ZipArchiveEntry("testdata/test2.xml");
entry.setSize(file2.length());
out.putArchiveEntry(entry);
IOUtils.copy(new FileInputStream(file2), out);
out.closeArchiveEntry();
entry = new ZipArchiveEntry("test/test3.xml");
entry.setSize(file3.length());
out.putArchiveEntry(entry);
IOUtils.copy(new FileInputStream(file3), out);
out.closeArchiveEntry();
entry = new ZipArchiveEntry("bla/test4.xml");
entry.setSize(file4.length());
out.putArchiveEntry(entry);
IOUtils.copy(new FileInputStream(file4), out);
out.closeArchiveEntry();
entry = new ZipArchiveEntry("bla/test5.xml");
entry.setSize(file4.length());
out.putArchiveEntry(entry);
IOUtils.copy(new FileInputStream(file4), out);
out.closeArchiveEntry();
entry = new ZipArchiveEntry("bla/blubber/test6.xml");
entry.setSize(file4.length());
out.putArchiveEntry(entry);
IOUtils.copy(new FileInputStream(file4), out);
out.closeArchiveEntry();
entry = new ZipArchiveEntry("test.txt");
entry.setSize(file5.length());
out.putArchiveEntry(entry);
IOUtils.copy(new FileInputStream(file5), out);
out.closeArchiveEntry();
entry = new ZipArchiveEntry("something/bla");
entry.setSize(file6.length());
out.putArchiveEntry(entry);
IOUtils.copy(new FileInputStream(file6), out);
out.closeArchiveEntry();
entry = new ZipArchiveEntry("test with spaces.txt");
entry.setSize(file6.length());
out.putArchiveEntry(entry);
IOUtils.copy(new FileInputStream(file6), out);
out.closeArchiveEntry();
return archive;
} finally {
if (out != null) {
out.close();
} else if (stream != null) {
stream.close();
}
}
}
#location 33
#vulnerability type RESOURCE_LEAK
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
public void testZipArchiveCreation() throws Exception {
// Archive
final File output = new File(dir, "bla.zip");
final File file1 = getFile("test1.xml");
final File file2 = getFile("test2.xml");
final OutputStream out = new FileOutputStream(output);
ArchiveOutputStream os = null;
try {
os = new ArchiveStreamFactory()
.createArchiveOutputStream("zip", out);
os.putArchiveEntry(new ZipArchiveEntry("testdata/test1.xml"));
IOUtils.copy(new FileInputStream(file1), os);
os.closeArchiveEntry();
os.putArchiveEntry(new ZipArchiveEntry("testdata/test2.xml"));
IOUtils.copy(new FileInputStream(file2), os);
os.closeArchiveEntry();
} finally {
if (os != null) {
os.close();
} else {
out.close();
}
}
// Unarchive the same
List results = new ArrayList();
final InputStream is = new FileInputStream(output);
ArchiveInputStream in = null;
try {
in = new ArchiveStreamFactory()
.createArchiveInputStream("zip", is);
ZipArchiveEntry entry = null;
while((entry = (ZipArchiveEntry)in.getNextEntry()) != null) {
File outfile = new File(resultDir.getCanonicalPath() + "/result/" + entry.getName());
outfile.getParentFile().mkdirs();
OutputStream o = new FileOutputStream(outfile);
try {
IOUtils.copy(in, o);
} finally {
o.close();
}
results.add(outfile);
}
} finally {
if (in != null) {
in.close();
} else {
is.close();
}
}
assertEquals(results.size(), 2);
File result = (File)results.get(0);
assertEquals(file1.length(), result.length());
result = (File)results.get(1);
assertEquals(file2.length(), result.length());
}
|
#vulnerable code
public void testZipArchiveCreation() throws Exception {
// Archive
final File output = new File(dir, "bla.zip");
final File file1 = getFile("test1.xml");
final File file2 = getFile("test2.xml");
{
final OutputStream out = new FileOutputStream(output);
final ArchiveOutputStream os = new ArchiveStreamFactory().createArchiveOutputStream("zip", out);
os.putArchiveEntry(new ZipArchiveEntry("testdata/test1.xml"));
IOUtils.copy(new FileInputStream(file1), os);
os.closeArchiveEntry();
os.putArchiveEntry(new ZipArchiveEntry("testdata/test2.xml"));
IOUtils.copy(new FileInputStream(file2), os);
os.closeArchiveEntry();
os.close();
}
// Unarchive the same
List results = new ArrayList();
{
final InputStream is = new FileInputStream(output);
final ArchiveInputStream in = new ArchiveStreamFactory().createArchiveInputStream("zip", is);
File result = File.createTempFile("dir-result", "");
result.delete();
result.mkdir();
ZipArchiveEntry entry = null;
while((entry = (ZipArchiveEntry)in.getNextEntry()) != null) {
File outfile = new File(result.getCanonicalPath() + "/result/" + entry.getName());
outfile.getParentFile().mkdirs();
OutputStream out = new FileOutputStream(outfile);
IOUtils.copy(in, out);
out.close();
results.add(outfile);
}
in.close();
}
assertEquals(results.size(), 2);
File result = (File)results.get(0);
assertEquals(file1.length(), result.length());
result = (File)results.get(1);
assertEquals(file2.length(), result.length());
}
#location 9
#vulnerability type RESOURCE_LEAK
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
public InputStream compress(InputStream input) throws CompressException {
FileOutputStream outputStream = null;
FileOutputStream tempFileOutputStream = null;
try {
File temp = File.createTempFile("commons_","jkt");
tempFileOutputStream = new FileOutputStream(temp);
compressTo(input, tempFileOutputStream);
return new FileInputStream(temp);
} catch (IOException e) {
throw new CompressException("An IO Exception has occured", e);
} finally {
try {
if(tempFileOutputStream != null) {
tempFileOutputStream.close();
}
if(outputStream != null) {
outputStream.close();
}
} catch (IOException e) {
throw new CompressException("An IO Exception occured while closing the streams", e);
}
}
}
|
#vulnerable code
public InputStream compress(InputStream input) throws CompressException {
FileOutputStream outputStream = null;
FileOutputStream tempFileOutputStream = null;
try {
File temp = File.createTempFile("commons_","jkt");
tempFileOutputStream = new FileOutputStream(temp);
compressTo(input, tempFileOutputStream);
return new FileInputStream(temp);
} catch (IOException e) {
throw new CompressException("An IO Exception has occured", e);
} finally {
try {
tempFileOutputStream.close();
outputStream.close();
} catch (IOException e) {
throw new CompressException("An IO Exception occured while closing the streams", e);
}
}
}
#location 13
#vulnerability type NULL_DEREFERENCE
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
public void testGzipUnarchive() throws Exception {
final File input = getFile("bla.tgz");
final File output = new File(dir, "bla.tar");
final InputStream is = new FileInputStream(input);
final CompressorInputStream in = new CompressorStreamFactory().createCompressorInputStream("gz", is);
FileOutputStream out = new FileOutputStream(output);
IOUtils.copy(in, out);
in.close();
is.close();
out.close();
}
|
#vulnerable code
public void testGzipUnarchive() throws Exception {
final File input = getFile("bla.tgz");
final File output = new File(dir, "bla.tar");
final InputStream is = new FileInputStream(input);
final CompressorInputStream in = new CompressorStreamFactory().createCompressorInputStream("gz", is);
IOUtils.copy(in, new FileOutputStream(output));
in.close();
}
#location 6
#vulnerability type RESOURCE_LEAK
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
public void testArDelete() throws Exception {
final File output = new File(dir, "bla.ar");
{
// create
final File file1 = getFile("test1.xml");
final File file2 = getFile("test2.xml");
final OutputStream out = new FileOutputStream(output);
final ArchiveOutputStream os = new ArchiveStreamFactory().createArchiveOutputStream("ar", out);
os.putArchiveEntry(new ArArchiveEntry("test1.xml", file1.length()));
IOUtils.copy(new FileInputStream(file1), os);
os.closeArchiveEntry();
os.putArchiveEntry(new ArArchiveEntry("test2.xml", file2.length()));
IOUtils.copy(new FileInputStream(file2), os);
os.closeArchiveEntry();
os.close();
out.close();
}
assertEquals(282, output.length());
final File output2 = new File(dir, "bla2.ar");
int copied = 0;
int deleted = 0;
{
// remove all but one file
final InputStream is = new FileInputStream(output);
final OutputStream os = new FileOutputStream(output2);
final ArchiveOutputStream aos = new ArchiveStreamFactory().createArchiveOutputStream("ar", os);
final ArchiveInputStream ais = new ArchiveStreamFactory().createArchiveInputStream(new BufferedInputStream(is));
while(true) {
final ArArchiveEntry entry = (ArArchiveEntry)ais.getNextEntry();
if (entry == null) {
break;
}
if ("test1.xml".equals(entry.getName())) {
aos.putArchiveEntry(entry);
IOUtils.copy(ais, aos);
aos.closeArchiveEntry();
copied++;
} else {
IOUtils.copy(ais, new ByteArrayOutputStream());
deleted++;
}
}
ais.close();
aos.close();
is.close();
os.close();
}
assertEquals(1, copied);
assertEquals(1, deleted);
assertEquals(144, output2.length());
long files = 0;
long sum = 0;
{
final InputStream is = new FileInputStream(output2);
final ArchiveInputStream ais = new ArchiveStreamFactory().createArchiveInputStream(new BufferedInputStream(is));
while(true) {
final ArArchiveEntry entry = (ArArchiveEntry)ais.getNextEntry();
if (entry == null) {
break;
}
IOUtils.copy(ais, new ByteArrayOutputStream());
sum += entry.getLength();
files++;
}
ais.close();
is.close();
}
assertEquals(1, files);
assertEquals(76, sum);
}
|
#vulnerable code
public void testArDelete() throws Exception {
final File output = new File(dir, "bla.ar");
{
// create
final File file1 = getFile("test1.xml");
final File file2 = getFile("test2.xml");
final OutputStream out = new FileOutputStream(output);
final ArchiveOutputStream os = new ArchiveStreamFactory().createArchiveOutputStream("ar", out);
os.putArchiveEntry(new ArArchiveEntry("test1.xml", file1.length()));
IOUtils.copy(new FileInputStream(file1), os);
os.closeArchiveEntry();
os.putArchiveEntry(new ArArchiveEntry("test2.xml", file2.length()));
IOUtils.copy(new FileInputStream(file2), os);
os.closeArchiveEntry();
os.close();
out.close();
}
final File output2 = new File(dir, "bla2.ar");
{
// remove all but one file
final InputStream is = new FileInputStream(output);
final OutputStream os = new FileOutputStream(output2);
final ArchiveOutputStream aos = new ArchiveStreamFactory().createArchiveOutputStream("ar", os);
final ArchiveInputStream ais = new ArchiveStreamFactory().createArchiveInputStream(new BufferedInputStream(is));
while(true) {
final ArArchiveEntry entry = (ArArchiveEntry)ais.getNextEntry();
if (entry == null) {
break;
}
if ("test1.xml".equals(entry.getName())) {
aos.putArchiveEntry(entry);
IOUtils.copy(ais, aos);
} else {
IOUtils.copy(ais, new ByteArrayOutputStream());
}
}
ais.close();
aos.close();
is.close();
os.close();
}
long sum = 0;
{
final InputStream is = new FileInputStream(output2);
final ArchiveInputStream ais = new ArchiveStreamFactory().createArchiveInputStream(new BufferedInputStream(is));
while(true) {
final ArArchiveEntry entry = (ArArchiveEntry)ais.getNextEntry();
if (entry == null) {
break;
}
IOUtils.copy(ais, new ByteArrayOutputStream());
sum += entry.getLength();
}
ais.close();
is.close();
}
assertEquals(76, sum);
}
#location 20
#vulnerability type RESOURCE_LEAK
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
@PreAuthorize("isAuthenticated()")
public String fetchNewToken(Optional<Long> expirationMillis,
Optional<String> optionalUsername) {
UserDto<ID> currentUser = LemonUtils.currentUser();
String username = optionalUsername.orElse(currentUser.getUsername());
LemonUtils.ensureAuthority(currentUser.getUsername().equals(username) ||
currentUser.isGoodAdmin(), "com.naturalprogrammer.spring.notGoodAdminOrSameUser");
return LemonSecurityConfig.TOKEN_PREFIX +
jwtService.createToken(JwtService.AUTH_AUDIENCE, username,
expirationMillis.orElse(properties.getJwt().getExpirationMillis()));
}
|
#vulnerable code
@PreAuthorize("isAuthenticated()")
public String fetchNewToken(Optional<Long> expirationMillis,
Optional<String> optionalUsername) {
SpringUser<ID> springUser = LemonUtils.getSpringUser();
String username = optionalUsername.orElse(springUser.getUsername());
LemonUtils.ensureAuthority(springUser.getUsername().equals(username) ||
springUser.isGoodAdmin(), "com.naturalprogrammer.spring.notGoodAdminOrSameUser");
return LemonSecurityConfig.TOKEN_PREFIX +
jwtService.createToken(JwtService.AUTH_AUDIENCE, username,
expirationMillis.orElse(properties.getJwt().getExpirationMillis()));
}
#location 6
#vulnerability type NULL_DEREFERENCE
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response,
Authentication authentication) throws IOException, ServletException {
// instead of this, the statement below is introduced: handle(request, response, authentication);
response.setStatus(HttpServletResponse.SC_OK);
response.getOutputStream().print(objectMapper.writeValueAsString(SaUtil.getBean(SaService.class).userForClient()));
clearAuthenticationAttributes(request);
//log.info("AuthenticationSuccess: " + SaUtil.getLoggedInUser());
}
|
#vulnerable code
public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response,
Authentication authentication) throws IOException, ServletException {
// instead of this, the statement below is introduced: handle(request, response, authentication);
response.setStatus(HttpServletResponse.SC_OK);
response.getOutputStream().print(objectMapper.writeValueAsString(SaUtil.getLoggedInUser().getUserDto()));
clearAuthenticationAttributes(request);
log.info("AuthenticationSuccess: " + SaUtil.getLoggedInUser().getUserDto());
}
#location 8
#vulnerability type NULL_DEREFERENCE
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
@UserEditPermission
@Transactional(propagation=Propagation.REQUIRED, readOnly=false)
public String changePassword(U user, @Valid ChangePasswordForm changePasswordForm) {
log.debug("Changing password for user: " + user);
// Get the old password of the logged in user (logged in user may be an ADMIN)
UserDto<ID> currentUser = LemonUtils.currentUser();
U loggedIn = userRepository.findById(currentUser.getId()).get();
String oldPassword = loggedIn.getPassword();
// checks
LemonUtils.ensureFound(user);
LemonUtils.validate("changePasswordForm.oldPassword",
passwordEncoder.matches(changePasswordForm.getOldPassword(),
oldPassword),
"com.naturalprogrammer.spring.wrong.password").go();
// sets the password
user.setPassword(passwordEncoder.encode(changePasswordForm.getPassword()));
user.setCredentialsUpdatedMillis(System.currentTimeMillis());
userRepository.save(user);
// // after successful commit
// LemonUtils.afterCommit(() -> {
//
// UserDto<ID> currentUser = LemonUtils.getSpringUser();
//
//// if (currentUser.getId().equals(user.getId())) { // if current-user's password changed,
////
//// log.debug("Logging out ...");
//// LemonUtils.logOut(); // log him out
//// }
// });
//
log.debug("Changed password for user: " + user);
return user.toUserDto().getUsername();
}
|
#vulnerable code
@UserEditPermission
@Transactional(propagation=Propagation.REQUIRED, readOnly=false)
public String changePassword(U user, @Valid ChangePasswordForm changePasswordForm) {
log.debug("Changing password for user: " + user);
// Get the old password of the logged in user (logged in user may be an ADMIN)
SpringUser<ID> springUser = LemonUtils.getSpringUser();
U loggedIn = userRepository.findById(springUser.getId()).get();
String oldPassword = loggedIn.getPassword();
// checks
LemonUtils.ensureFound(user);
LemonUtils.validate("changePasswordForm.oldPassword",
passwordEncoder.matches(changePasswordForm.getOldPassword(),
oldPassword),
"com.naturalprogrammer.spring.wrong.password").go();
// sets the password
user.setPassword(passwordEncoder.encode(changePasswordForm.getPassword()));
user.setCredentialsUpdatedMillis(System.currentTimeMillis());
userRepository.save(user);
// // after successful commit
// LemonUtils.afterCommit(() -> {
//
// SpringUser<ID> currentUser = LemonUtils.getSpringUser();
//
//// if (currentUser.getId().equals(user.getId())) { // if current-user's password changed,
////
//// log.debug("Logging out ...");
//// LemonUtils.logOut(); // log him out
//// }
// });
//
log.debug("Changed password for user: " + user);
return user.toSpringUser().getUsername();
}
#location 9
#vulnerability type NULL_DEREFERENCE
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response,
Authentication authentication) throws IOException, ServletException {
// instead of this, the statement below is introduced: handle(request, response, authentication);
response.setStatus(HttpServletResponse.SC_OK);
response.getOutputStream().print(objectMapper.writeValueAsString(SaUtil.getBean(SaService.class).userForClient()));
clearAuthenticationAttributes(request);
//log.info("AuthenticationSuccess: " + SaUtil.getLoggedInUser());
}
|
#vulnerable code
public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response,
Authentication authentication) throws IOException, ServletException {
// instead of this, the statement below is introduced: handle(request, response, authentication);
response.setStatus(HttpServletResponse.SC_OK);
response.getOutputStream().print(objectMapper.writeValueAsString(SaUtil.getLoggedInUser().getUserDto()));
clearAuthenticationAttributes(request);
log.info("AuthenticationSuccess: " + SaUtil.getLoggedInUser().getUserDto());
}
#location 6
#vulnerability type NULL_DEREFERENCE
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
@Transactional(propagation=Propagation.REQUIRED, readOnly=false)
public SpringUser<ID> loginWithNonce(@Valid NonceForm<ID> nonce, HttpServletResponse response) {
U user = userRepository.findById(nonce.getUserId())
.orElseThrow(MultiErrorException.supplier(
"com.naturalprogrammer.spring.userNotFound"));
if (user.getNonce().equals(nonce.getNonce())) {
user.setNonce(null);
userRepository.save(user);
jwtService.addJwtAuthHeader(response, user.toSpringUser().getUsername(), properties.getJwt().getExpirationMilli());
return user.toSpringUser();
}
throw MultiErrorException.supplier("com.naturalprogrammer.spring.invalidNonce").get();
}
|
#vulnerable code
@Transactional(propagation=Propagation.REQUIRED, readOnly=false)
public SpringUser<ID> loginWithNonce(@Valid NonceForm<ID> nonce, HttpServletResponse response) {
U user = userRepository.findById(nonce.getUserId())
.orElseThrow(MultiErrorException.supplier(
"com.naturalprogrammer.spring.userNotFound"));
if (user.getNonce().equals(nonce.getNonce())) {
user.setNonce(null);
userRepository.save(user);
jwtService.addJwtAuthHeader(response, user.getId().toString(), properties.getJwt().getExpirationMilli());
return user.toSpringUser();
}
throw MultiErrorException.supplier("com.naturalprogrammer.spring.invalidNonce").get();
}
#location 13
#vulnerability type NULL_DEREFERENCE
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
public void hideConfidentialFields() {
password = null; // JsonIgnore didn't work because of JsonIgnore
//verificationCode = null;
//forgotPasswordCode = null;
if (!hasPermission(LemonUtils.currentUser(), Permission.EDIT))
email = null;
log.debug("Hid confidential fields for user: " + this);
}
|
#vulnerable code
public void hideConfidentialFields() {
password = null; // JsonIgnore didn't work because of JsonIgnore
//verificationCode = null;
//forgotPasswordCode = null;
if (!hasPermission(LemonUtils.getSpringUser(), Permission.EDIT))
email = null;
log.debug("Hid confidential fields for user: " + this);
}
#location 7
#vulnerability type NULL_DEREFERENCE
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
public U fetchUser(@Valid @Email @NotBlank String email) {
log.debug("Fetching user by email: " + email);
U user = userRepository.findByEmail(email)
.orElseThrow(() -> MultiErrorException.of("email",
"com.naturalprogrammer.spring.userNotFound"));
user.decorate().hideConfidentialFields();
log.debug("Returning user: " + user);
return user;
}
|
#vulnerable code
public U fetchUser(@Valid @Email @NotBlank String email) {
log.debug("Fetching user by email: " + email);
U user = userRepository.findByEmail(email);
LemonUtil.check("email", user != null,
"com.naturalprogrammer.spring.userNotFound").go();
user.decorate().hideConfidentialFields();
log.debug("Returning user: " + user);
return user;
}
#location 9
#vulnerability type NULL_DEREFERENCE
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
@Override
protected String determineTargetUrl(HttpServletRequest request,
HttpServletResponse response) {
UserDto<ID> currentUser = LemonUtils.currentUser();
String shortLivedAuthToken = jwtService.createToken(
JwtService.AUTH_AUDIENCE,
currentUser.getUsername(),
(long) properties.getJwt().getShortLivedMillis());
String targetUrl = LemonUtils.fetchCookie(request,
HttpCookieOAuth2AuthorizationRequestRepository.LEMON_REDIRECT_URI_COOKIE_PARAM_NAME)
.map(Cookie::getValue)
.orElse(properties.getOauth2AuthenticationSuccessUrl());
HttpCookieOAuth2AuthorizationRequestRepository.deleteCookies(request, response);
return targetUrl + shortLivedAuthToken;
//
// return properties.getApplicationUrl()
// + "/social-login-success?token="
// + shortLivedAuthToken;
}
|
#vulnerable code
@Override
protected String determineTargetUrl(HttpServletRequest request,
HttpServletResponse response) {
SpringUser<ID> springUser = LemonUtils.getSpringUser();
String shortLivedAuthToken = jwtService.createToken(
JwtService.AUTH_AUDIENCE,
springUser.getUsername(),
(long) properties.getJwt().getShortLivedMillis());
String targetUrl = LemonUtils.fetchCookie(request,
HttpCookieOAuth2AuthorizationRequestRepository.LEMON_REDIRECT_URI_COOKIE_PARAM_NAME)
.map(Cookie::getValue)
.orElse(properties.getOauth2AuthenticationSuccessUrl());
HttpCookieOAuth2AuthorizationRequestRepository.deleteCookies(request, response);
return targetUrl + shortLivedAuthToken;
//
// return properties.getApplicationUrl()
// + "/social-login-success?token="
// + shortLivedAuthToken;
}
#location 9
#vulnerability type NULL_DEREFERENCE
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
@Transactional(propagation=Propagation.REQUIRED, readOnly=false)
public void resetPassword(String forgotPasswordCode, @Valid @Password String newPassword) {
log.debug("Resetting password ...");
U user = userRepository
.findByForgotPasswordCode(forgotPasswordCode)
.orElseThrow(() -> MultiErrorException.of(
"com.naturalprogrammer.spring.invalidLink"));
user.setPassword(passwordEncoder.encode(newPassword));
user.setForgotPasswordCode(null);
userRepository.save(user);
log.debug("Password reset.");
}
|
#vulnerable code
@Transactional(propagation=Propagation.REQUIRED, readOnly=false)
public void resetPassword(String forgotPasswordCode, @Valid @Password String newPassword) {
log.debug("Resetting password ...");
U user = userRepository.findByForgotPasswordCode(forgotPasswordCode);
LemonUtil.check(user != null, "com.naturalprogrammer.spring.invalidLink").go();
user.setPassword(passwordEncoder.encode(newPassword));
user.setForgotPasswordCode(null);
userRepository.save(user);
log.debug("Password reset.");
}
#location 9
#vulnerability type NULL_DEREFERENCE
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response,
Authentication authentication) throws IOException, ServletException {
// instead of this, the statement below is introduced: handle(request, response, authentication);
response.setStatus(HttpServletResponse.SC_OK);
response.getOutputStream().print(objectMapper.writeValueAsString(SaUtil.getLoggedInUser().getUserDto()));
clearAuthenticationAttributes(request);
log.info("AuthenticationSuccess: " + SaUtil.getLoggedInUser().getUserDto());
}
|
#vulnerable code
public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response,
Authentication authentication) throws IOException, ServletException {
// instead of this, the statement below is introduced: handle(request, response, authentication);
response.setStatus(HttpServletResponse.SC_OK);
response.getOutputStream().print(objectMapper.writeValueAsString(SaUtil.getSessionUser().getUserDto()));
clearAuthenticationAttributes(request);
log.info("AuthenticationSuccess: " + SaUtil.getSessionUser().getUserDto());
}
#location 6
#vulnerability type NULL_DEREFERENCE
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
public static void main(String args[]) {
System.out.println(test());
}
|
#vulnerable code
public static void main(String args[]) throws IOException, ClassNotFoundException {
File obfuscatedFile;
JarFile jarFile = new JarFile(obfuscatedFile = new File("helloWorld-obf.jar"));
Enumeration<JarEntry> e = jarFile.entries();
URL[] urls = {new URL("jar:file:" + obfuscatedFile.getAbsolutePath() + "!/")};
URLClassLoader cl = URLClassLoader.newInstance(urls);
Class c = null;
while (e.hasMoreElements()) {
JarEntry je = e.nextElement();
if (je.isDirectory() || !je.getName().endsWith(".class")) {
continue;
}
// -6 because of .class
String className = je.getName().substring(0, je.getName().length() - 6);
className = className.replace('/', '.');
System.out.println(className);
if (className.equals("Test")) {
c = cl.loadClass(className);
}
}
Objects.requireNonNull(c);
}
#location 4
#vulnerability type RESOURCE_LEAK
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
@Override
public void transformPost(JObfImpl inst, HashMap<String, ClassNode> nodes) {
if (!enabled.getObject()) return;
HashMap<String, String> mappings = new HashMap<>();
mappings.clear();
List<ClassWrapper> classWrappers = new ArrayList<>();
JObf.log.info("Building Hierarchy...");
for (ClassNode value : nodes.values()) {
ClassWrapper cw = new ClassWrapper(value, false, new byte[0]);
classWrappers.add(cw);
JObfImpl.INSTANCE.buildHierarchy(cw, null);
}
JObf.log.info("Finished building hierarchy");
long current = System.currentTimeMillis();
JObf.log.info("Generating mappings...");
NameUtils.setup("", "", "", true);
AtomicInteger classCounter = new AtomicInteger();
classWrappers.forEach(classWrapper -> {
boolean excluded = this.excluded(classWrapper);
for (MethodWrapper method : classWrapper.methods) {
method.methodNode.access &= ~Opcodes.ACC_PRIVATE;
method.methodNode.access &= ~Opcodes.ACC_PROTECTED;
method.methodNode.access |= Opcodes.ACC_PUBLIC;
}
for (FieldWrapper fieldWrapper : classWrapper.fields) {
fieldWrapper.fieldNode.access &= ~Opcodes.ACC_PRIVATE;
fieldWrapper.fieldNode.access &= ~Opcodes.ACC_PROTECTED;
fieldWrapper.fieldNode.access |= Opcodes.ACC_PUBLIC;
}
if (excluded) return;
classWrapper.methods.stream().filter(methodWrapper -> !Modifier.isNative(methodWrapper.methodNode.access)
&& !methodWrapper.methodNode.name.equals("main") && !methodWrapper.methodNode.name.equals("premain")
&& !methodWrapper.methodNode.name.startsWith("<")).forEach(methodWrapper -> {
// if (!excluded) {
// }
if (canRenameMethodTree(mappings, new HashSet<>(), methodWrapper, classWrapper.originalName)) {
this.renameMethodTree(mappings, new HashSet<>(), methodWrapper, classWrapper.originalName, NameUtils.generateMethodName(classWrapper.originalName, methodWrapper.originalDescription));
}
});
classWrapper.fields.forEach(fieldWrapper -> {
// if (!excluded) {
// }
if (canRenameFieldTree(mappings, new HashSet<>(), fieldWrapper, classWrapper.originalName)) {
this.renameFieldTree(new HashSet<>(), fieldWrapper, classWrapper.originalName, NameUtils.generateFieldName(classWrapper.originalName), mappings);
}
});
classWrapper.classNode.access &= ~Opcodes.ACC_PRIVATE;
classWrapper.classNode.access &= ~Opcodes.ACC_PROTECTED;
classWrapper.classNode.access |= Opcodes.ACC_PUBLIC;
putMapping(mappings, classWrapper.originalName, (repackage)
? repackageName + '/' + NameUtils.generateClassName() : NameUtils.generateClassName());
classCounter.incrementAndGet();
});
// try {
// FileOutputStream outStream = new FileOutputStream("mappings.txt");
// PrintStream printStream = new PrintStream(outStream);
//
// for (Map.Entry<String, String> stringStringEntry : mappings.entrySet()) {
// printStream.println(stringStringEntry.getKey() + " -> " + stringStringEntry.getValue());
// }
//
// outStream.close();
// } catch (IOException e) {
// e.printStackTrace();
// }
JObf.log.info(String.format("Finished generating mappings (%dms)", (System.currentTimeMillis() - current)));
JObf.log.info("Applying mappings...");
current = System.currentTimeMillis();
Remapper simpleRemapper = new MemberRemapper(mappings);
for (ClassWrapper classWrapper : classWrappers) {
ClassNode classNode = classWrapper.classNode;
ClassNode copy = new ClassNode();
classNode.accept(new ClassRemapper(copy, simpleRemapper));
for (int i = 0; i < copy.methods.size(); i++) {
classWrapper.methods.get(i).methodNode = copy.methods.get(i);
/*for (AbstractInsnNode insn : methodNode.instructions.toArray()) { // TODO: Fix lambdas + interface
if (insn instanceof InvokeDynamicInsnNode) {
InvokeDynamicInsnNode indy = (InvokeDynamicInsnNode) insn;
if (indy.bsm.getOwner().equals("java/lang/invoke/LambdaMetafactory")) {
Handle handle = (Handle) indy.bsmArgs[1];
String newName = mappings.get(handle.getOwner() + '.' + handle.getName() + handle.getDesc());
if (newName != null) {
indy.name = newName;
indy.bsm = new Handle(handle.getTag(), handle.getOwner(), newName, handle.getDesc(), false);
}
}
}
}*/
}
if (copy.fields != null) {
for (int i = 0; i < copy.fields.size(); i++) {
classWrapper.fields.get(i).fieldNode = copy.fields.get(i);
}
}
classWrapper.classNode = copy;
JObfImpl.classes.remove(classWrapper.originalName + ".class");
JObfImpl.classes.put(classWrapper.classNode.name + ".class", classWrapper.classNode);
// JObfImpl.INSTANCE.getClassPath().put();
// this.getClasses().put(classWrapper.classNode.name, classWrapper);
JObfImpl.INSTANCE.getClassPath().put(classWrapper.classNode.name, classWrapper);
}
JObf.log.info(String.format("Finished applying mappings (%dms)", (System.currentTimeMillis() - current)));
}
|
#vulnerable code
@Override
public void transformPost(JObfImpl inst, HashMap<String, ClassNode> nodes) {
if (!enabled.getObject()) return;
HashMap<String, String> mappings = new HashMap<>();
mappings.clear();
List<ClassWrapper> classWrappers = new ArrayList<>();
System.out.println("Building Hierarchy");
for (ClassNode value : nodes.values()) {
ClassWrapper cw = new ClassWrapper(value, false, new byte[0]);
classWrappers.add(cw);
JObfImpl.INSTANCE.buildHierarchy(cw, null);
}
System.out.println("Finished building hierarchy");
long current = System.currentTimeMillis();
JObf.log.info("Generating mappings...");
NameUtils.setup("", "", "", true);
AtomicInteger classCounter = new AtomicInteger();
classWrappers.forEach(classWrapper -> {
boolean excluded = this.excluded(classWrapper);
for (MethodWrapper method : classWrapper.methods) {
method.methodNode.access &= ~Opcodes.ACC_PRIVATE;
method.methodNode.access &= ~Opcodes.ACC_PROTECTED;
method.methodNode.access |= Opcodes.ACC_PUBLIC;
}
for (FieldWrapper fieldWrapper : classWrapper.fields) {
fieldWrapper.fieldNode.access &= ~Opcodes.ACC_PRIVATE;
fieldWrapper.fieldNode.access &= ~Opcodes.ACC_PROTECTED;
fieldWrapper.fieldNode.access |= Opcodes.ACC_PUBLIC;
}
if (excluded) return;
classWrapper.methods.stream().filter(methodWrapper -> !Modifier.isNative(methodWrapper.methodNode.access)
&& !methodWrapper.methodNode.name.equals("main") && !methodWrapper.methodNode.name.equals("premain")
&& !methodWrapper.methodNode.name.startsWith("<")).forEach(methodWrapper -> {
// if (!excluded) {
// }
if (canRenameMethodTree(mappings, new HashSet<>(), methodWrapper, classWrapper.originalName)) {
this.renameMethodTree(mappings, new HashSet<>(), methodWrapper, classWrapper.originalName, NameUtils.generateMethodName(classWrapper.originalName, methodWrapper.originalDescription));
}
});
classWrapper.fields.forEach(fieldWrapper -> {
// if (!excluded) {
// }
if (canRenameFieldTree(mappings, new HashSet<>(), fieldWrapper, classWrapper.originalName)) {
this.renameFieldTree(new HashSet<>(), fieldWrapper, classWrapper.originalName, NameUtils.generateFieldName(classWrapper.originalName), mappings);
}
});
classWrapper.classNode.access &= ~Opcodes.ACC_PRIVATE;
classWrapper.classNode.access &= ~Opcodes.ACC_PROTECTED;
classWrapper.classNode.access |= Opcodes.ACC_PUBLIC;
putMapping(mappings, classWrapper.originalName, (repackage)
? repackageName + '/' + NameUtils.generateClassName() : NameUtils.generateClassName());
classCounter.incrementAndGet();
});
try {
FileOutputStream outStream = new FileOutputStream("mappings.txt");
PrintStream printStream = new PrintStream(outStream);
for (Map.Entry<String, String> stringStringEntry : mappings.entrySet()) {
printStream.println(stringStringEntry.getKey() + " -> " + stringStringEntry.getValue());
}
outStream.close();
} catch (IOException e) {
e.printStackTrace();
}
JObf.log.info(String.format("Finished generating mappings (%dms)", (System.currentTimeMillis() - current)));
JObf.log.info("Applying mappings...");
current = System.currentTimeMillis();
Remapper simpleRemapper = new MemberRemapper(mappings);
for (ClassWrapper classWrapper : classWrappers) {
ClassNode classNode = classWrapper.classNode;
ClassNode copy = new ClassNode();
classNode.accept(new ClassRemapper(copy, simpleRemapper));
for (int i = 0; i < copy.methods.size(); i++) {
classWrapper.methods.get(i).methodNode = copy.methods.get(i);
/*for (AbstractInsnNode insn : methodNode.instructions.toArray()) { // TODO: Fix lambdas + interface
if (insn instanceof InvokeDynamicInsnNode) {
InvokeDynamicInsnNode indy = (InvokeDynamicInsnNode) insn;
if (indy.bsm.getOwner().equals("java/lang/invoke/LambdaMetafactory")) {
Handle handle = (Handle) indy.bsmArgs[1];
String newName = mappings.get(handle.getOwner() + '.' + handle.getName() + handle.getDesc());
if (newName != null) {
indy.name = newName;
indy.bsm = new Handle(handle.getTag(), handle.getOwner(), newName, handle.getDesc(), false);
}
}
}
}*/
}
if (copy.fields != null) {
for (int i = 0; i < copy.fields.size(); i++) {
classWrapper.fields.get(i).fieldNode = copy.fields.get(i);
}
}
classWrapper.classNode = copy;
JObfImpl.classes.remove(classWrapper.originalName + ".class");
JObfImpl.classes.put(classWrapper.classNode.name + ".class", classWrapper.classNode);
// JObfImpl.INSTANCE.getClassPath().put();
// this.getClasses().put(classWrapper.classNode.name, classWrapper);
JObfImpl.INSTANCE.getClassPath().put(classWrapper.classNode.name, classWrapper);
}
JObf.log.info(String.format("Finished applying mappings (%dms)", (System.currentTimeMillis() - current)));
}
#location 79
#vulnerability type RESOURCE_LEAK
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
public static BasicAttributeInfo newAttributeInfo(ConstantPool constantPool, short attributeNameIndex) {
BasicAttributeInfo basicAttributeInfo = null;
String attributeName = null;
ConstantPoolInfo constantPoolInfo = constantPool.getCpInfo()[attributeNameIndex - 1];
if (constantPoolInfo instanceof ConstantUtf8Info) {
attributeName = ((ConstantUtf8Info) constantPoolInfo).getValue();
}
System.out.println("attributeName = " + attributeName);
if (attributeName.equals("Code")) {
basicAttributeInfo = new Code(constantPool, attributeNameIndex);
} else if (attributeName.equals("ConstantValue")) {
basicAttributeInfo = new ConstantValue(constantPool, attributeNameIndex);
} else if (attributeName.equals("Deprecated")) {
basicAttributeInfo = new Deprecated(constantPool, attributeNameIndex);
} else if (attributeName.equals("Exceptions")) {
basicAttributeInfo = new Exceptions(constantPool, attributeNameIndex);
} else if (attributeName.equals("LineNumberTable")) {
basicAttributeInfo = new LineNumberTable(constantPool, attributeNameIndex);
} else if (attributeName.equals("LocalVariableTable")) {
basicAttributeInfo = new LocalVariableTable(constantPool, attributeNameIndex);
} else if (attributeName.equals("LocalVariableTypeTable")) {
basicAttributeInfo = new LocalVariableTypeTable(constantPool, attributeNameIndex);
} else if (attributeName.equals("SourceFile")) {
basicAttributeInfo = new SourceFile(constantPool, attributeNameIndex);
} else if (attributeName.equals("Synthetic")) {
basicAttributeInfo = new Synthetic(constantPool, attributeNameIndex);
} else if (attributeName.equals("Signature")) {
basicAttributeInfo = new Signature(constantPool, attributeNameIndex);
} else if (attributeName.equals("BootstrapMethods")) {
basicAttributeInfo = new BootstrapMethods(constantPool, attributeNameIndex);
} else if (attributeName.equals("InnerClasses")) {
basicAttributeInfo = new InnerClasses(constantPool, attributeNameIndex);
} else {
basicAttributeInfo = new Unparsed(constantPool, attributeNameIndex);
}
basicAttributeInfo.setAttributeNameIndex(attributeNameIndex);
return basicAttributeInfo;
}
|
#vulnerable code
public static BasicAttributeInfo newAttributeInfo(ConstantPool constantPool, short attributeNameIndex) {
BasicAttributeInfo basicAttributeInfo = null;
String attributeName = null;
ConstantPoolInfo constantPoolInfo = constantPool.getCpInfo()[attributeNameIndex - 1];
if (constantPoolInfo instanceof ConstantUtf8Info) {
attributeName = ((ConstantUtf8Info) constantPoolInfo).getValue();
}
if (attributeName.equals("Code")) {
basicAttributeInfo = new Code(constantPool, attributeNameIndex);
} else if (attributeName.equals("ConstantValue")) {
basicAttributeInfo = new ConstantValue(constantPool, attributeNameIndex);
} else if (attributeName.equals("Deprecated")) {
basicAttributeInfo = new Deprecated(constantPool, attributeNameIndex);
} else if (attributeName.equals("Exceptions")) {
basicAttributeInfo = new Exceptions(constantPool, attributeNameIndex);
} else if (attributeName.equals("LineNumberTable")) {
basicAttributeInfo = new LineNumberTable(constantPool, attributeNameIndex);
} else if (attributeName.equals("LocalVariableTable")) {
basicAttributeInfo = new LocalVariableTable(constantPool, attributeNameIndex);
} else if (attributeName.equals("SourceFile")) {
basicAttributeInfo = new SourceFile(constantPool, attributeNameIndex);
} else if (attributeName.equals("Synthetic")) {
basicAttributeInfo = new Synthetic(constantPool, attributeNameIndex);
}
basicAttributeInfo.setAttributeNameIndex(attributeNameIndex);
return basicAttributeInfo;
}
#location 25
#vulnerability type NULL_DEREFERENCE
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
private String[] fileToStringArray (File f, String encoding)
{
try {
return streamToStringArray(new FileInputStream(f), encoding);
} catch (IOException e) {
throw new IllegalArgumentException("Trouble reading file "+f);
}
}
|
#vulnerable code
private String[] fileToStringArray (File f, String encoding)
{
ArrayList<String> wordarray = new ArrayList<String>();
try {
BufferedReader input = null;
if (encoding == null) {
input = new BufferedReader (new FileReader (f));
}
else {
input = new BufferedReader( new InputStreamReader( new FileInputStream(f), encoding ));
}
String line;
while (( line = input.readLine()) != null) {
String[] words = line.split ("\\s+");
for (int i = 0; i < words.length; i++)
wordarray.add (words[i]);
}
} catch (IOException e) {
throw new IllegalArgumentException("Trouble reading file "+f);
}
return (String[]) wordarray.toArray(new String[]{});
}
#location 22
#vulnerability type RESOURCE_LEAK
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
public void printState (PrintStream out) {
Alphabet alphabet = instances.getDataAlphabet();
out.println ("#doc pos typeindex type topic");
for (int doc = 0; doc < topics.size(); doc++) {
FeatureSequence tokenSequence =
(FeatureSequence) instances.get(doc).getData();
FeatureSequence topicSequence =
(FeatureSequence) instances.get(doc).getData();
for (int token = 0; token < topicSequence.getLength(); token++) {
int type = tokenSequence.getIndexAtPosition(token);
int topic = topicSequence.getIndexAtPosition(token);
out.print(doc); out.print(' ');
out.print(token); out.print(' ');
out.print(type); out.print(' ');
out.print(alphabet.lookupObject(type)); out.print(' ');
out.print(topic); out.println();
}
}
}
|
#vulnerable code
public void printState (PrintStream out) {
Alphabet a = instances.getDataAlphabet();
out.println ("#doc pos typeindex type topic");
for (int di = 0; di < topics.length; di++) {
FeatureSequence fs = (FeatureSequence) instances.get(di).getData();
for (int token = 0; token < topics[di].length; token++) {
int type = fs.getIndexAtPosition(token);
out.print(di); out.print(' ');
out.print(token); out.print(' ');
out.print(type); out.print(' ');
out.print(a.lookupObject(type)); out.print(' ');
out.print(topics[di][token]); out.println();
}
}
}
#location 11
#vulnerability type NULL_DEREFERENCE
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
private String[] fileToStringArray (File f, String encoding)
{
try {
return streamToStringArray(new FileInputStream(f), encoding);
} catch (IOException e) {
throw new IllegalArgumentException("Trouble reading file "+f);
}
}
|
#vulnerable code
private String[] fileToStringArray (File f, String encoding)
{
ArrayList<String> wordarray = new ArrayList<String>();
try {
BufferedReader input = null;
if (encoding == null) {
input = new BufferedReader (new FileReader (f));
}
else {
input = new BufferedReader( new InputStreamReader( new FileInputStream(f), encoding ));
}
String line;
while (( line = input.readLine()) != null) {
String[] words = line.split ("\\s+");
for (int i = 0; i < words.length; i++)
wordarray.add (words[i]);
}
} catch (IOException e) {
throw new IllegalArgumentException("Trouble reading file "+f);
}
return (String[]) wordarray.toArray(new String[]{});
}
#location 12
#vulnerability type RESOURCE_LEAK
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
static HprofByteBuffer createHprofByteBuffer(File dumpFile)
throws IOException {
long fileLen = dumpFile.length();
if (fileLen < MINIMAL_SIZE) {
String errText = "File size is too small";
throw new IOException(errText);
}
try {
if (fileLen < Integer.MAX_VALUE) {
return new HprofMappedByteBuffer(dumpFile);
} else {
return new HprofLongMappedByteBuffer(dumpFile);
}
} catch (IOException ex) {
if (ex.getCause() instanceof OutOfMemoryError) { // can happen on 32bit Windows, since there is only 2G for memory mapped data for whole java process.
return new PagedFileHprofByteBuffer(new RandomAccessFile(dumpFile, "r"), 4 << 20, 16);
}
throw ex;
}
}
|
#vulnerable code
static HprofByteBuffer createHprofByteBuffer(File dumpFile)
throws IOException {
long fileLen = dumpFile.length();
if (fileLen < MINIMAL_SIZE) {
String errText = "File size is too small";
throw new IOException(errText);
}
try {
if (fileLen < Integer.MAX_VALUE) {
return new HprofMappedByteBuffer(dumpFile);
} else {
return new HprofLongMappedByteBuffer(dumpFile);
}
} catch (IOException ex) {
if (ex.getCause() instanceof OutOfMemoryError) { // can happen on 32bit Windows, since there is only 2G for memory mapped data for whole java process.
return new HprofFileBuffer(dumpFile);
}
throw ex;
}
}
#location 18
#vulnerability type RESOURCE_LEAK
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
public static String stringValue(Instance obj) {
if (obj == null) return null;
if (!"java.lang.String".equals(obj.getJavaClass().getName()))
throw new IllegalArgumentException("Is not a string: " + obj.getInstanceId() + " (" + obj.getJavaClass().getName() + ")");
Boolean COMPACT_STRINGS = (Boolean) obj.getJavaClass().getValueOfStaticField("COMPACT_STRINGS");
if (COMPACT_STRINGS == null)
return stringValue_java8(obj); // We're pre Java 9
Object valueInstance = obj.getValueOfField("value");
PrimitiveArrayInstance chars = (PrimitiveArrayInstance) valueInstance;
byte UTF16 = 1;
byte coder = COMPACT_STRINGS ? (Byte) obj.getValueOfField("coder") : UTF16;
int len = chars.getLength() >> coder;
char[] text = new char[len];
List<String> values = (List) chars.getValues();
if (coder == UTF16)
for (int i = 0; i < text.length; i++) {
text[i] = (char)
((Integer.parseInt(values.get(i*2+1)) << 8)
| (Integer.parseInt(values.get(i*2)) & 0xFF));
}
else
for (int i = 0; i < text.length; i++)
text[i] = (char) Integer.parseInt(values.get(i));
return new String(text);
}
|
#vulnerable code
public static String stringValue(Instance obj) {
if (obj == null) {
return null;
}
if (!"java.lang.String".equals(obj.getJavaClass().getName())) {
throw new IllegalArgumentException("Is not a string: " + obj.getInstanceId() + " (" + obj.getJavaClass().getName() + ")");
}
char[] text = null;
int offset = 0;
int len = -1;
for(FieldValue f: obj.getFieldValues()) {
Field ff = f.getField();
if ("value".equals(ff.getName())) {
PrimitiveArrayInstance chars = (PrimitiveArrayInstance) ((ObjectFieldValue)f).getInstance();
text = new char[chars.getLength()];
for(int i = 0; i != text.length; ++i) {
text[i] = ((String)chars.getValues().get(i)).charAt(0);
}
}
// fields below were removed in Java 7
else if ("offset".equals(ff.getName())) {
offset = Integer.valueOf(f.getValue());
}
else if ("count".equals(ff.getName())) {
len = Integer.valueOf(f.getValue());
}
}
if (len < 0) {
len = text.length;
}
return new String(text, offset, len);
}
#location 30
#vulnerability type NULL_DEREFERENCE
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
private void addNonCachedMetricsListener(CuratorFramework curatorFramework) {
nonCachedMetricsIPRWLock = new InterProcessReadWriteLock(curatorFramework, NON_CACHED_METRICS_LOCK_PATH);
testIPRWLock(curatorFramework, nonCachedMetricsIPRWLock, NON_CACHED_METRICS_LOCK_PATH);
nonCachedMetricsIP = new DistributedAtomicValue(curatorFramework, NON_CACHED_METRICS, new RetryForever(1000));
TreeCacheListener nonCachedMetricsListener = new TreeCacheListener() {
@Override
public void childEvent(CuratorFramework curatorFramework, TreeCacheEvent event) throws Exception {
if (event.getType().equals(TreeCacheEvent.Type.NODE_UPDATED)) {
LOG.info("Handling nonCachedMetricsIP event {}", event.getType().toString());
readNonCachedMetricsIP();
}
}
};
try (TreeCache nonCachedMetricsTreeCache = new TreeCache(curatorFramework, NON_CACHED_METRICS)) {
nonCachedMetricsTreeCache.getListenable().addListener(nonCachedMetricsListener);
nonCachedMetricsTreeCache.start();
} catch (Exception e) {
LOG.error(e.getMessage(), e);
}
}
|
#vulnerable code
private void addNonCachedMetricsListener(CuratorFramework curatorFramework) {
nonCachedMetricsIPRWLock = new InterProcessReadWriteLock(curatorFramework, NON_CACHED_METRICS_LOCK_PATH);
testIPRWLock(curatorFramework, nonCachedMetricsIPRWLock, NON_CACHED_METRICS_LOCK_PATH);
nonCachedMetricsIP = new DistributedAtomicValue(curatorFramework, NON_CACHED_METRICS, new RetryForever(1000));
TreeCacheListener nonCachedMetricsListener = new TreeCacheListener() {
@Override
public void childEvent(CuratorFramework curatorFramework, TreeCacheEvent event) throws Exception {
if (event.getType().equals(TreeCacheEvent.Type.NODE_UPDATED)) {
LOG.info("Handling nonCachedMetricsIP event {}", event.getType().toString());
readNonCachedMetricsIP();
}
}
};
try {
TreeCache nonCachedMetricsTreeCache = new TreeCache(curatorFramework, NON_CACHED_METRICS);
nonCachedMetricsTreeCache.getListenable().addListener(nonCachedMetricsListener);
nonCachedMetricsTreeCache.start();
} catch (Exception e) {
LOG.error(e.getMessage(), e);
}
}
#location 19
#vulnerability type RESOURCE_LEAK
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
@ReadOperation
public HaloMetricResponse HaloMetric() {
HaloMetricResponse haloMetricResponse=new HaloMetricResponse();
MetricResponse jvmThreadsLive=metric("jvm.threads.live",null);
haloMetricResponse.setJvmThreadslive(String.valueOf(jvmThreadsLive.getMeasurements().get(0).getValue()));
MetricResponse jvmNemoryUsedHeap=metric("jvm.memory.used", Arrays.asList("area:heap") );
haloMetricResponse.setJvmMemoryUsedHeap(String.valueOf(jvmNemoryUsedHeap.getMeasurements().get(0).getValue()));
MetricResponse jvmNemoryUsedNonHeap=metric("jvm.memory.used", Arrays.asList("area:nonheap") );
haloMetricResponse.setJvmMemoryUsedNonHeap(String.valueOf(jvmNemoryUsedNonHeap.getMeasurements().get(0).getValue()));
// 2.0 actuator/metrics 中没有这个key
MetricResponse systemLoadAverage=metric("system.load.average.1m", null );
if(systemLoadAverage!=null){
haloMetricResponse.setSystemloadAverage(String.valueOf(systemLoadAverage.getMeasurements().get(0).getValue()));
}
MetricResponse heapCommitted=metric("jvm.memory.committed", Arrays.asList("area:heap") );
haloMetricResponse.setHeapCommitted(String.valueOf(heapCommitted.getMeasurements().get(0).getValue()));
MetricResponse nonheapCommitted=metric("jvm.memory.committed", Arrays.asList("area:nonheap") );
haloMetricResponse.setNonheapCommitted(String.valueOf(nonheapCommitted.getMeasurements().get(0).getValue()));
MetricResponse heapMax=metric("jvm.memory.max", Arrays.asList("area:heap") );
haloMetricResponse.setHeapMax(String.valueOf(heapMax.getMeasurements().get(0).getValue()));
getGcinfo(haloMetricResponse);
MemoryUsage memoryUsage = ManagementFactory.getMemoryMXBean()
.getHeapMemoryUsage();
haloMetricResponse.setHeapInit(String.valueOf(memoryUsage.getInit()));
Runtime runtime = Runtime.getRuntime();
haloMetricResponse.setProcessors(String.valueOf(runtime.availableProcessors()));
return haloMetricResponse;
}
|
#vulnerable code
@ReadOperation
public HaloMetricResponse HaloMetric() {
HaloMetricResponse haloMetricResponse=new HaloMetricResponse();
MetricResponse jvmThreadsLive=metric("jvm.threads.live",null);
haloMetricResponse.setJvmThreadslive(String.valueOf(jvmThreadsLive.getMeasurements().get(0).getValue()));
MetricResponse jvmNemoryUsedHeap=metric("jvm.memory.used", Arrays.asList("area:heap") );
haloMetricResponse.setJvmMemoryUsedHeap(String.valueOf(jvmNemoryUsedHeap.getMeasurements().get(0).getValue()));
MetricResponse jvmNemoryUsedNonHeap=metric("jvm.memory.used", Arrays.asList("area:nonheap") );
haloMetricResponse.setJvmMemoryUsedNonHeap(String.valueOf(jvmNemoryUsedNonHeap.getMeasurements().get(0).getValue()));
MetricResponse systemLoadAverage=metric("system.load.average.1m", null );
haloMetricResponse.setSystemloadAverage(String.valueOf(systemLoadAverage.getMeasurements().get(0).getValue()));
MetricResponse heapCommitted=metric("jvm.memory.committed", Arrays.asList("area:heap") );
haloMetricResponse.setHeapCommitted(String.valueOf(heapCommitted.getMeasurements().get(0).getValue()));
MetricResponse nonheapCommitted=metric("jvm.memory.committed", Arrays.asList("area:nonheap") );
haloMetricResponse.setNonheapCommitted(String.valueOf(nonheapCommitted.getMeasurements().get(0).getValue()));
MetricResponse heapMax=metric("jvm.memory.max", Arrays.asList("area:heap") );
haloMetricResponse.setHeapMax(String.valueOf(heapMax.getMeasurements().get(0).getValue()));
getGcinfo(haloMetricResponse);
MemoryUsage memoryUsage = ManagementFactory.getMemoryMXBean()
.getHeapMemoryUsage();
haloMetricResponse.setHeapInit(String.valueOf(memoryUsage.getInit()));
Runtime runtime = Runtime.getRuntime();
haloMetricResponse.setProcessors(String.valueOf(runtime.availableProcessors()));
return haloMetricResponse;
}
#location 12
#vulnerability type NULL_DEREFERENCE
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
@Test
public void track1FormatTest() {
EmvTrack1 track1 = TrackUtils
.extractTrack1Data(
BytesUtils
.fromString("42353231313131313131313131313131315E202F2020202020202020202020202020202020202020202020205E31363038323032303030303030303030303030312020303030202020202030"));
Assertions.assertThat(track1).isNotNull();
Assertions.assertThat(track1.getCardNumber()).isEqualTo("5211111111111111");
SimpleDateFormat sdf = new SimpleDateFormat("MM/yyyy");
Assertions.assertThat(sdf.format(track1.getExpireDate())).isEqualTo("08/2016");
Assertions.assertThat(track1.getHolderFirstname()).isNull();
Assertions.assertThat(track1.getHolderLastname()).isNull();
Assertions.assertThat(track1.getService()).isNotNull();
Assertions.assertThat(track1.getService().getServiceCode1()).isEqualTo(ServiceCode1Enum.INTERNATIONNAL_ICC);
Assertions.assertThat(track1.getService().getServiceCode1().getInterchange()).isNotNull();
Assertions.assertThat(track1.getService().getServiceCode1().getTechnology()).isNotNull();
Assertions.assertThat(track1.getService().getServiceCode2()).isEqualTo(ServiceCode2Enum.NORMAL);
Assertions.assertThat(track1.getService().getServiceCode2().getAuthorizationProcessing()).isNotNull();
Assertions.assertThat(track1.getService().getServiceCode3()).isEqualTo(ServiceCode3Enum.GOODS_SERVICES);
Assertions.assertThat(track1.getService().getServiceCode3().getAllowedServices()).isNotNull();
Assertions.assertThat(track1.getService().getServiceCode3().getPinRequirements()).isNotNull();
}
|
#vulnerable code
@Test
public void track1FormatTest() {
EmvCard card = new EmvCard();
boolean ret = TrackUtils
.extractTrack1Data(
card,
BytesUtils
.fromString("564C42353231313131313131313131313131315E202F2020202020202020202020202020202020202020202020205E31363038323032303030303030303030303030312020303030202020202030"));
Assertions.assertThat(ret).isTrue();
Assertions.assertThat(card).isNotNull();
Assertions.assertThat(card.getCardNumber()).isEqualTo("5211111111111111");
SimpleDateFormat sdf = new SimpleDateFormat("MM/yyyy");
Assertions.assertThat(sdf.format(card.getExpireDate())).isEqualTo("08/2016");
Assertions.assertThat(card.getTrack1()).isNotNull();
Assertions.assertThat(card.getTrack1().getHolderFirstname()).isNull();
Assertions.assertThat(card.getTrack1().getHolderLastname()).isNull();
Assertions.assertThat(card.getTrack1().getService()).isNotNull();
Assertions.assertThat(card.getTrack1().getService().getServiceCode1()).isEqualTo(ServiceCode1Enum.INTERNATIONNAL_ICC);
Assertions.assertThat(card.getTrack1().getService().getServiceCode1().getInterchange()).isNotNull();
Assertions.assertThat(card.getTrack1().getService().getServiceCode1().getTechnology()).isNotNull();
Assertions.assertThat(card.getTrack1().getService().getServiceCode2()).isEqualTo(ServiceCode2Enum.NORMAL);
Assertions.assertThat(card.getTrack1().getService().getServiceCode2().getAuthorizationProcessing()).isNotNull();
Assertions.assertThat(card.getTrack1().getService().getServiceCode3()).isEqualTo(ServiceCode3Enum.GOODS_SERVICES);
Assertions.assertThat(card.getTrack1().getService().getServiceCode3().getAllowedServices()).isNotNull();
Assertions.assertThat(card.getTrack1().getService().getServiceCode3().getPinRequirements()).isNotNull();
}
#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 track1Test() {
EmvTrack1 track1 = TrackUtils
.extractTrack1Data(
BytesUtils
.fromString("42343131313131313131313131313131313F305E202F5E31373032323031313030333F313030313030303030303030303030303F"));
Assertions.assertThat(track1).isNotNull();
Assertions.assertThat(track1.getCardNumber()).isEqualTo("4111111111111111");
SimpleDateFormat sdf = new SimpleDateFormat("MM/yyyy");
Assertions.assertThat(sdf.format(track1.getExpireDate())).isEqualTo("02/2017");
Assertions.assertThat(track1).isNotNull();
Assertions.assertThat(track1.getService()).isNotNull();
Assertions.assertThat(track1.getService().getServiceCode1()).isEqualTo(ServiceCode1Enum.INTERNATIONNAL_ICC);
Assertions.assertThat(track1.getService().getServiceCode1().getInterchange()).isNotNull();
Assertions.assertThat(track1.getService().getServiceCode1().getTechnology()).isNotNull();
Assertions.assertThat(track1.getService().getServiceCode2()).isEqualTo(ServiceCode2Enum.NORMAL);
Assertions.assertThat(track1.getService().getServiceCode2().getAuthorizationProcessing()).isNotNull();
Assertions.assertThat(track1.getService().getServiceCode3()).isEqualTo(ServiceCode3Enum.NO_RESTRICTION);
Assertions.assertThat(track1.getService().getServiceCode3().getAllowedServices()).isNotNull();
Assertions.assertThat(track1.getService().getServiceCode3().getPinRequirements()).isNotNull();
}
|
#vulnerable code
@Test
public void track1Test() {
EmvCard card = new EmvCard();
boolean ret = TrackUtils
.extractTrack1Data(
card,
BytesUtils
.fromString("70 75 9F 6C 02 00 01 9F 62 06 00 00 00 38 00 00 9F 63 06 00 00 00 00 E0 E0 56 34 42343131313131313131313131313131313f305e202f5e31373032323031313030333f313030313030303030303030303030303f30303030 9F 64 01 03 9F 65 02 1C 00 9F 66 02 03 F0 9F 6B 13 5566887766556677 D1 81 02 01 00 00 00 00 00 10 0F 9F 67 01 03 90 00"));
Assertions.assertThat(ret).isTrue();
Assertions.assertThat(card).isNotNull();
Assertions.assertThat(card.getCardNumber()).isEqualTo("4111111111111111");
SimpleDateFormat sdf = new SimpleDateFormat("MM/yyyy");
Assertions.assertThat(sdf.format(card.getExpireDate())).isEqualTo("02/2017");
Assertions.assertThat(card.getTrack1()).isNotNull();
Assertions.assertThat(card.getTrack1().getService()).isNotNull();
Assertions.assertThat(card.getTrack1().getService().getServiceCode1()).isEqualTo(ServiceCode1Enum.INTERNATIONNAL_ICC);
Assertions.assertThat(card.getTrack1().getService().getServiceCode1().getInterchange()).isNotNull();
Assertions.assertThat(card.getTrack1().getService().getServiceCode1().getTechnology()).isNotNull();
Assertions.assertThat(card.getTrack1().getService().getServiceCode2()).isEqualTo(ServiceCode2Enum.NORMAL);
Assertions.assertThat(card.getTrack1().getService().getServiceCode2().getAuthorizationProcessing()).isNotNull();
Assertions.assertThat(card.getTrack1().getService().getServiceCode3()).isEqualTo(ServiceCode3Enum.NO_RESTRICTION);
Assertions.assertThat(card.getTrack1().getService().getServiceCode3().getAllowedServices()).isNotNull();
Assertions.assertThat(card.getTrack1().getService().getServiceCode3().getPinRequirements()).isNotNull();
}
#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 track1NameTest() {
EmvTrack1 track1 = TrackUtils
.extractTrack1Data(
BytesUtils
.fromString("42343131313131313131313131313131313F305E446F652F4A6F686E5E31373032323031313030333F313030313030303030303030303030303F"));
Assertions.assertThat(track1).isNotNull();
Assertions.assertThat(track1.getCardNumber()).isEqualTo("4111111111111111");
SimpleDateFormat sdf = new SimpleDateFormat("MM/yyyy");
Assertions.assertThat(sdf.format(track1.getExpireDate())).isEqualTo("02/2017");
Assertions.assertThat(track1).isNotNull();
Assertions.assertThat(track1.getHolderFirstname()).isEqualTo("John");
Assertions.assertThat(track1.getHolderLastname()).isEqualTo("Doe");
Assertions.assertThat(track1.getService()).isNotNull();
Assertions.assertThat(track1.getService().getServiceCode1()).isEqualTo(ServiceCode1Enum.INTERNATIONNAL_ICC);
Assertions.assertThat(track1.getService().getServiceCode1().getInterchange()).isNotNull();
Assertions.assertThat(track1.getService().getServiceCode1().getTechnology()).isNotNull();
Assertions.assertThat(track1.getService().getServiceCode2()).isEqualTo(ServiceCode2Enum.NORMAL);
Assertions.assertThat(track1.getService().getServiceCode2().getAuthorizationProcessing()).isNotNull();
Assertions.assertThat(track1.getService().getServiceCode3()).isEqualTo(ServiceCode3Enum.NO_RESTRICTION);
Assertions.assertThat(track1.getService().getServiceCode3().getAllowedServices()).isNotNull();
Assertions.assertThat(track1.getService().getServiceCode3().getPinRequirements()).isNotNull();
}
|
#vulnerable code
@Test
public void track1NameTest() {
EmvCard card = new EmvCard();
boolean ret = TrackUtils
.extractTrack1Data(
card,
BytesUtils
.fromString("563A42343131313131313131313131313131313F305E446F652F4A6F686E5E31373032323031313030333F313030313030303030303030303030303F30303030"));
Assertions.assertThat(ret).isTrue();
Assertions.assertThat(card).isNotNull();
Assertions.assertThat(card.getCardNumber()).isEqualTo("4111111111111111");
SimpleDateFormat sdf = new SimpleDateFormat("MM/yyyy");
Assertions.assertThat(sdf.format(card.getExpireDate())).isEqualTo("02/2017");
Assertions.assertThat(card.getTrack1()).isNotNull();
Assertions.assertThat(card.getTrack1().getHolderFirstname()).isEqualTo("John");
Assertions.assertThat(card.getTrack1().getHolderLastname()).isEqualTo("Doe");
Assertions.assertThat(card.getTrack1().getService()).isNotNull();
Assertions.assertThat(card.getTrack1().getService().getServiceCode1()).isEqualTo(ServiceCode1Enum.INTERNATIONNAL_ICC);
Assertions.assertThat(card.getTrack1().getService().getServiceCode1().getInterchange()).isNotNull();
Assertions.assertThat(card.getTrack1().getService().getServiceCode1().getTechnology()).isNotNull();
Assertions.assertThat(card.getTrack1().getService().getServiceCode2()).isEqualTo(ServiceCode2Enum.NORMAL);
Assertions.assertThat(card.getTrack1().getService().getServiceCode2().getAuthorizationProcessing()).isNotNull();
Assertions.assertThat(card.getTrack1().getService().getServiceCode3()).isEqualTo(ServiceCode3Enum.NO_RESTRICTION);
Assertions.assertThat(card.getTrack1().getService().getServiceCode3().getAllowedServices()).isNotNull();
Assertions.assertThat(card.getTrack1().getService().getServiceCode3().getPinRequirements()).isNotNull();
}
#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 testRefs()
{
List<String> failed = TestInference.testAll("tests", false);
if (failed != null)
{
String msg = "Some tests failed. " +
"\nLook at 'failed_refs.json' in corresponding directories for details.";
msg += "\n----------------------------= FAILED TESTS --------------------------=";
for (String fail : failed)
{
msg += "\n - " + fail;
}
msg += "\n----------------------------------------------------------------------";
fail(msg);
}
}
|
#vulnerable code
@Test
public void testRefs()
{
List<String> failed = TestInference.testAll("tests", false);
String msg = "";
for (String fail : failed)
{
msg += "[failed] " + fail;
}
assertTrue("Some tests failed :\n" + msg, failed == null);
}
#location 6
#vulnerability type NULL_DEREFERENCE
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
@Nullable
public String extendPath(@NotNull String name) {
if (name.endsWith(".py")) {
name = Util.moduleNameFor(name);
}
if (path.equals("")) {
return name;
}
String sep;
switch (scopeType) {
case MODULE:
case CLASS:
case INSTANCE:
case SCOPE:
sep = ".";
break;
case FUNCTION:
sep = "@";
break;
default:
Util.msg("unsupported context for extendPath: " + scopeType);
return path;
}
return path + sep + name;
}
|
#vulnerable code
@Nullable
public String extendPath(@NotNull String name) {
if (name.endsWith(".py")) {
name = Util.moduleNameFor(name);
}
if (path.equals("")) {
return name;
}
String sep;
switch (scopeType) {
case MODULE:
case CLASS:
case INSTANCE:
case SCOPE:
sep = ".";
break;
case FUNCTION:
sep = "&";
break;
default:
System.err.println("unsupported context for extendPath: " + scopeType);
return path;
}
return path + sep + name;
}
#location 6
#vulnerability type NULL_DEREFERENCE
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
@NotNull
public List<Entry> generate(@NotNull Scope scope, @NotNull String path) {
List<Entry> result = new ArrayList<Entry>();
Set<Binding> entries = new TreeSet<Binding>();
for (Binding b : scope.values()) {
if (!b.isSynthetic()
&& !b.isBuiltin()
&& !b.getDefs().isEmpty()
&& path.equals(b.getSingle().getFile())) {
entries.add(b);
}
}
for (Binding nb : entries) {
Def signode = nb.getSingle();
List<Entry> kids = null;
if (nb.getKind() == Binding.Kind.CLASS) {
Type realType = nb.getType();
if (realType.isUnionType()) {
for (Type t : realType.asUnionType().getTypes()) {
if (t.isClassType()) {
realType = t;
break;
}
}
}
kids = generate(realType.getTable(), path);
}
Entry kid = kids != null ? new Branch() : new Leaf();
kid.setOffset(signode.getStart());
kid.setQname(nb.getQname());
kid.setKind(nb.getKind());
if (kids != null) {
kid.setChildren(kids);
}
result.add(kid);
}
return result;
}
|
#vulnerable code
@NotNull
public List<Entry> generate(@NotNull Scope scope, @NotNull String path) {
List<Entry> result = new ArrayList<Entry>();
Set<Binding> entries = new TreeSet<Binding>();
for (Binding b : scope.values()) {
if (!b.isSynthetic()
&& !b.isBuiltin()
&& !b.getDefs().isEmpty()
&& path.equals(b.getFirstNode().getFile())) {
entries.add(b);
}
}
for (Binding nb : entries) {
Def signode = nb.getFirstNode();
List<Entry> kids = null;
if (nb.getKind() == Binding.Kind.CLASS) {
Type realType = nb.getType();
if (realType.isUnionType()) {
for (Type t : realType.asUnionType().getTypes()) {
if (t.isClassType()) {
realType = t;
break;
}
}
}
kids = generate(realType.getTable(), path);
}
Entry kid = kids != null ? new Branch() : new Leaf();
kid.setOffset(signode.getStart());
kid.setQname(nb.getQname());
kid.setKind(nb.getKind());
if (kids != null) {
kid.setChildren(kids);
}
result.add(kid);
}
return result;
}
#location 10
#vulnerability type NULL_DEREFERENCE
|
Below is the vulnerable code, please generate the patch based on the following information.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.