output
stringlengths 64
73.2k
| input
stringlengths 208
73.3k
| instruction
stringclasses 1
value |
---|---|---|
#fixed code
public ZooKeeper getClient(){
if (zooKeeper==null) {
try {
if (INSTANCE_INIT_LOCK.tryLock(2, TimeUnit.SECONDS)) {
if (zooKeeper==null) { // 二次校验,防止并发创建client
// init new-client
ZooKeeper newZk = null;
try {
newZk = new ZooKeeper(zkaddress, 10000, watcher);
if (zkdigest!=null && zkdigest.trim().length()>0) {
newZk.addAuthInfo("digest",zkdigest.getBytes()); // like "account:password"
}
newZk.exists(zkpath, false); // sync wait until succcess conn
// set success new-client
zooKeeper = newZk;
logger.info(">>>>>>>>>> xxl-conf, XxlZkClient init success.");
} catch (Exception e) {
// close fail new-client
if (newZk != null) {
newZk.close();
}
logger.error(e.getMessage(), e);
} finally {
INSTANCE_INIT_LOCK.unlock();
}
}
}
} catch (InterruptedException e) {
logger.error(e.getMessage(), e);
}
}
if (zooKeeper == null) {
throw new XxlConfException("XxlZkClient.zooKeeper is null.");
}
return zooKeeper;
}
|
#vulnerable code
public ZooKeeper getClient(){
if (zooKeeper==null) {
try {
if (INSTANCE_INIT_LOCK.tryLock(2, TimeUnit.SECONDS)) {
if (zooKeeper==null) { // 二次校验,防止并发创建client
try {
zooKeeper = new ZooKeeper(zkaddress, 10000, watcher); // TODO,本地变量方式,成功才会赋值
if (zkdigest!=null && zkdigest.trim().length()>0) {
zooKeeper.addAuthInfo("digest",zkdigest.getBytes()); // like "account:password"
}
zooKeeper.exists(zkpath, false); // sync
} catch (Exception e) {
logger.error(e.getMessage(), e);
} finally {
INSTANCE_INIT_LOCK.unlock();
}
logger.info(">>>>>>>>>> xxl-conf, XxlZkClient init success.");
}
}
} catch (InterruptedException e) {
logger.error(e.getMessage(), e);
}
}
if (zooKeeper == null) {
throw new XxlConfException("XxlZkClient.zooKeeper is null.");
}
return zooKeeper;
}
#location 2
#vulnerability type THREAD_SAFETY_VIOLATION
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
@Test
public void testUnwrapConnection() throws SQLException
{
HikariConfig config = new HikariConfig();
config.setMinimumIdle(1);
config.setMaximumPoolSize(1);
config.setInitializationFailFast(true);
config.setConnectionTestQuery("VALUES 1");
config.setDataSourceClassName("com.zaxxer.hikari.mocks.StubDataSource");
HikariDataSource ds = new HikariDataSource(config);
try
{
Assert.assertSame("Idle connections not as expected", 1, TestElf.getPool(ds).getIdleConnections());
Connection connection = ds.getConnection();
Assert.assertNotNull(connection);
StubConnection unwrapped = connection.unwrap(StubConnection.class);
Assert.assertTrue("unwrapped connection is not instance of StubConnection: " + unwrapped, (unwrapped != null && unwrapped instanceof StubConnection));
}
finally
{
ds.close();
}
}
|
#vulnerable code
@Test
public void testUnwrapConnection() throws SQLException
{
HikariConfig config = new HikariConfig();
config.setMinimumIdle(1);
config.setMaximumPoolSize(1);
config.setInitializationFailFast(true);
config.setConnectionTestQuery("VALUES 1");
config.setDataSourceClassName("com.zaxxer.hikari.mocks.StubDataSource");
HikariDataSource ds = new HikariDataSource(config);
try
{
Assert.assertSame("Idle connections not as expected", 1, TestElf.getPool(ds).getIdleConnections());
Connection connection = ds.getConnection();
Assert.assertNotNull(connection);
StubConnection unwrapped = connection.unwrap(StubConnection.class);
Assert.assertTrue("unwrapped connection is not instance of StubConnection: " + unwrapped, (unwrapped != null && unwrapped instanceof StubConnection));
}
finally
{
ds.shutdown();
}
}
#location 25
#vulnerability type RESOURCE_LEAK
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
@Test
public void testShutdown2() throws SQLException
{
Assert.assertSame("StubConnection count not as expected", 0, StubConnection.count.get());
StubConnection.slowCreate = true;
HikariConfig config = new HikariConfig();
config.setMinimumIdle(10);
config.setMaximumPoolSize(10);
config.setInitializationFailFast(false);
config.setConnectionTestQuery("VALUES 1");
config.setDataSourceClassName("com.zaxxer.hikari.mocks.StubDataSource");
HikariDataSource ds = new HikariDataSource(config);
HikariPool pool = TestElf.getPool(ds);
PoolUtilities.quietlySleep(300);
Assert.assertTrue("Totals connection count not as expected, ", pool.getTotalConnections() > 0);
ds.close();
Assert.assertSame("Active connection count not as expected, ", 0, pool.getActiveConnections());
Assert.assertSame("Idle connection count not as expected, ", 0, pool.getIdleConnections());
Assert.assertSame("Total connection count not as expected", 0, pool.getTotalConnections());
}
|
#vulnerable code
@Test
public void testShutdown2() throws SQLException
{
Assert.assertSame("StubConnection count not as expected", 0, StubConnection.count.get());
StubConnection.slowCreate = true;
HikariConfig config = new HikariConfig();
config.setMinimumIdle(10);
config.setMaximumPoolSize(10);
config.setInitializationFailFast(false);
config.setConnectionTestQuery("VALUES 1");
config.setDataSourceClassName("com.zaxxer.hikari.mocks.StubDataSource");
HikariDataSource ds = new HikariDataSource(config);
HikariPool pool = TestElf.getPool(ds);
PoolUtilities.quietlySleep(300);
Assert.assertTrue("Totals connection count not as expected, ", pool.getTotalConnections() > 0);
ds.shutdown();
Assert.assertSame("Active connection count not as expected, ", 0, pool.getActiveConnections());
Assert.assertSame("Idle connection count not as expected, ", 0, pool.getIdleConnections());
Assert.assertSame("Total connection count not as expected", 0, pool.getTotalConnections());
}
#location 22
#vulnerability type RESOURCE_LEAK
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
private long runAndMeasure(Measurable[] runners, CountDownLatch latch, String timeUnit)
{
for (int i = 0; i < runners.length; i++)
{
Thread t = new Thread(runners[i]);
t.start();
}
try
{
latch.await();
}
catch (InterruptedException e)
{
e.printStackTrace();
}
int i = 0;
long[] track = new long[runners.length];
long max = 0, avg = 0, med = 0;
long counter = 0;
long absoluteStart = Long.MAX_VALUE, absoluteFinish = Long.MIN_VALUE;
for (Measurable runner : runners)
{
long elapsed = runner.getElapsed();
absoluteStart = Math.min(absoluteStart, runner.getStart());
absoluteFinish = Math.max(absoluteFinish, runner.getFinish());
track[i++] = elapsed;
max = Math.max(max, elapsed);
avg = (avg + elapsed) / 2;
counter += runner.getCounter();
}
Arrays.sort(track);
med = track[runners.length / 2];
System.out.printf(" %s max=%d%5$s, avg=%d%5$s, med=%d%5$s\n", (Boolean.getBoolean("showCounter") ? "Counter=" + counter : ""), max, avg, med, timeUnit);
return absoluteFinish - absoluteStart;
}
|
#vulnerable code
private long runAndMeasure(Measurable[] runners, CountDownLatch latch, String timeUnit)
{
for (int i = 0; i < runners.length; i++)
{
Thread t = new Thread(runners[i]);
t.start();
}
try
{
latch.await();
}
catch (InterruptedException e)
{
e.printStackTrace();
}
int i = 0;
long[] track = new long[runners.length];
long max = 0, avg = 0, med = 0;
long absoluteStart = Long.MAX_VALUE, absoluteFinish = Long.MIN_VALUE;
for (Measurable runner : runners)
{
long elapsed = runner.getElapsed();
absoluteStart = Math.min(absoluteStart, runner.getStart());
absoluteFinish = Math.max(absoluteFinish, runner.getFinish());
track[i++] = elapsed;
max = Math.max(max, elapsed);
avg = (avg + elapsed) / 2;
}
Arrays.sort(track);
med = track[runners.length / 2];
System.out.printf(" max=%d%4$s, avg=%d%4$s, med=%d%4$s\n", max, avg, med, timeUnit);
return absoluteFinish - absoluteStart;
}
#location 34
#vulnerability type CHECKERS_PRINTF_ARGS
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
@Test
public void testOverflow()
{
ArrayList<Statement> verifyList = new ArrayList<>();
FastStatementList list = new FastStatementList();
for (int i = 0; i < 100; i++)
{
StubStatement statement = new StubStatement();
list.add(statement);
verifyList.add(statement);
}
for (int i = 0; i < 100; i++)
{
Assert.assertNotNull("Element " + i, list.get(i));
Assert.assertSame(verifyList.get(i), list.get(i));
}
}
|
#vulnerable code
@Test
public void testOverflow()
{
FastStatementList list = new FastStatementList();
for (int i = 0; i < 100; i++)
{
list.add(new StubStatement());
}
for (int i = 0; i < 100; i++)
{
Assert.assertNotNull("Element " + i, list.get(i));
}
}
#location 7
#vulnerability type RESOURCE_LEAK
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
@HikariInject
public ResultSet executeQuery() throws SQLException
{
try
{
IHikariResultSetProxy resultSet = (IHikariResultSetProxy) __executeQuery();
if (resultSet == null)
{
return null;
}
resultSet.setProxyStatement(this);
return (ResultSet) resultSet;
}
catch (SQLException e)
{
throw checkException(e);
}
}
|
#vulnerable code
@HikariInject
public ResultSet executeQuery() throws SQLException
{
IHikariResultSetProxy resultSet = (IHikariResultSetProxy) __executeQuery();
resultSet.setProxyStatement(this);
return (ResultSet) resultSet;
}
#location 5
#vulnerability type NULL_DEREFERENCE
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
@Test
public void testShutdown1() throws SQLException
{
Assert.assertSame("StubConnection count not as expected", 0, StubConnection.count.get());
StubConnection.slowCreate = true;
HikariConfig config = new HikariConfig();
config.setMinimumIdle(0);
config.setMaximumPoolSize(10);
config.setInitializationFailFast(true);
config.setConnectionTestQuery("VALUES 1");
config.setDataSourceClassName("com.zaxxer.hikari.mocks.StubDataSource");
final HikariDataSource ds = new HikariDataSource(config);
HikariPool pool = TestElf.getPool(ds);
Thread[] threads = new Thread[10];
for (int i = 0; i < 10; i++)
{
threads[i] = new Thread() {
public void run() {
try
{
if (ds.getConnection() != null)
{
PoolUtilities.quietlySleep(TimeUnit.SECONDS.toMillis(1));
}
}
catch (SQLException e)
{
}
}
};
threads[i].setDaemon(true);
threads[i].start();
}
PoolUtilities.quietlySleep(300);
Assert.assertTrue("Totals connection count not as expected, ", pool.getTotalConnections() > 0);
ds.close();
Assert.assertSame("Active connection count not as expected, ", 0, pool.getActiveConnections());
Assert.assertSame("Idle connection count not as expected, ", 0, pool.getIdleConnections());
Assert.assertSame("Total connection count not as expected", 0, pool.getTotalConnections());
}
|
#vulnerable code
@Test
public void testShutdown1() throws SQLException
{
Assert.assertSame("StubConnection count not as expected", 0, StubConnection.count.get());
StubConnection.slowCreate = true;
HikariConfig config = new HikariConfig();
config.setMinimumIdle(0);
config.setMaximumPoolSize(10);
config.setInitializationFailFast(true);
config.setConnectionTestQuery("VALUES 1");
config.setDataSourceClassName("com.zaxxer.hikari.mocks.StubDataSource");
final HikariDataSource ds = new HikariDataSource(config);
HikariPool pool = TestElf.getPool(ds);
Thread[] threads = new Thread[10];
for (int i = 0; i < 10; i++)
{
threads[i] = new Thread() {
public void run() {
try
{
if (ds.getConnection() != null)
{
PoolUtilities.quietlySleep(TimeUnit.SECONDS.toMillis(1));
}
}
catch (SQLException e)
{
}
}
};
threads[i].setDaemon(true);
threads[i].start();
}
PoolUtilities.quietlySleep(300);
Assert.assertTrue("Totals connection count not as expected, ", pool.getTotalConnections() > 0);
ds.shutdown();
Assert.assertSame("Active connection count not as expected, ", 0, pool.getActiveConnections());
Assert.assertSame("Idle connection count not as expected, ", 0, pool.getIdleConnections());
Assert.assertSame("Total connection count not as expected", 0, pool.getTotalConnections());
}
#location 43
#vulnerability type RESOURCE_LEAK
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
private long runAndMeasure(Measurable[] runners, CountDownLatch latch, String timeUnit)
{
for (int i = 0; i < runners.length; i++)
{
Thread t = new Thread(runners[i]);
t.start();
}
try
{
latch.await();
}
catch (InterruptedException e)
{
e.printStackTrace();
}
int i = 0;
long[] track = new long[runners.length];
long max = 0, avg = 0, med = 0;
long counter = 0;
long absoluteStart = Long.MAX_VALUE, absoluteFinish = Long.MIN_VALUE;
for (Measurable runner : runners)
{
long elapsed = runner.getElapsed();
absoluteStart = Math.min(absoluteStart, runner.getStart());
absoluteFinish = Math.max(absoluteFinish, runner.getFinish());
track[i++] = elapsed;
max = Math.max(max, elapsed);
avg = (avg + elapsed) / 2;
counter += runner.getCounter();
}
Arrays.sort(track);
med = track[runners.length / 2];
System.out.printf(" %s max=%d%5$s, avg=%d%5$s, med=%d%5$s\n", (Boolean.getBoolean("showCounter") ? "Counter=" + counter : ""), max, avg, med, timeUnit);
return absoluteFinish - absoluteStart;
}
|
#vulnerable code
private long runAndMeasure(Measurable[] runners, CountDownLatch latch, String timeUnit)
{
for (int i = 0; i < runners.length; i++)
{
Thread t = new Thread(runners[i]);
t.start();
}
try
{
latch.await();
}
catch (InterruptedException e)
{
e.printStackTrace();
}
int i = 0;
long[] track = new long[runners.length];
long max = 0, avg = 0, med = 0;
long absoluteStart = Long.MAX_VALUE, absoluteFinish = Long.MIN_VALUE;
for (Measurable runner : runners)
{
long elapsed = runner.getElapsed();
absoluteStart = Math.min(absoluteStart, runner.getStart());
absoluteFinish = Math.max(absoluteFinish, runner.getFinish());
track[i++] = elapsed;
max = Math.max(max, elapsed);
avg = (avg + elapsed) / 2;
}
Arrays.sort(track);
med = track[runners.length / 2];
System.out.printf(" max=%d%4$s, avg=%d%4$s, med=%d%4$s\n", max, avg, med, timeUnit);
return absoluteFinish - absoluteStart;
}
#location 34
#vulnerability type CHECKERS_PRINTF_ARGS
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
@Test
public void rampUpDownTest() throws SQLException, InterruptedException
{
HikariConfig config = new HikariConfig();
config.setMinimumIdle(5);
config.setMaximumPoolSize(60);
config.setInitializationFailFast(true);
config.setConnectionTestQuery("VALUES 1");
config.setDataSourceClassName("com.zaxxer.hikari.mocks.StubDataSource");
System.setProperty("com.zaxxer.hikari.housekeeping.periodMs", "250");
HikariDataSource ds = new HikariDataSource(config);
ds.setIdleTimeout(1000);
Assert.assertSame("Totals connections not as expected", 5, TestElf.getPool(ds).getTotalConnections());
Connection[] connections = new Connection[ds.getMaximumPoolSize()];
for (int i = 0; i < connections.length; i++)
{
connections[i] = ds.getConnection();
}
Assert.assertSame("Totals connections not as expected", 60, TestElf.getPool(ds).getTotalConnections());
for (Connection connection : connections)
{
connection.close();
}
Thread.sleep(2500);
Assert.assertSame("Totals connections not as expected", 5, TestElf.getPool(ds).getTotalConnections());
ds.close();
}
|
#vulnerable code
@Test
public void rampUpDownTest() throws SQLException, InterruptedException
{
HikariConfig config = new HikariConfig();
config.setMinimumIdle(5);
config.setMaximumPoolSize(60);
config.setInitializationFailFast(true);
config.setConnectionTestQuery("VALUES 1");
config.setDataSourceClassName("com.zaxxer.hikari.mocks.StubDataSource");
System.setProperty("com.zaxxer.hikari.housekeeping.periodMs", "250");
HikariDataSource ds = new HikariDataSource(config);
ds.setIdleTimeout(1000);
Assert.assertSame("Totals connections not as expected", 5, TestElf.getPool(ds).getTotalConnections());
Connection[] connections = new Connection[ds.getMaximumPoolSize()];
for (int i = 0; i < connections.length; i++)
{
connections[i] = ds.getConnection();
}
Assert.assertSame("Totals connections not as expected", 60, TestElf.getPool(ds).getTotalConnections());
for (Connection connection : connections)
{
connection.close();
}
Thread.sleep(2500);
Assert.assertSame("Totals connections not as expected", 5, TestElf.getPool(ds).getTotalConnections());
ds.shutdown();
}
#location 35
#vulnerability type RESOURCE_LEAK
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
@Test
public void testMaxLifetime() throws Exception
{
HikariConfig config = new HikariConfig();
config.setMinimumIdle(0);
config.setMaximumPoolSize(1);
config.setInitializationFailFast(true);
config.setConnectionTestQuery("VALUES 1");
config.setDataSourceClassName("com.zaxxer.hikari.mocks.StubDataSource");
System.setProperty("com.zaxxer.hikari.housekeeping.periodMs", "100");
HikariDataSource ds = new HikariDataSource(config);
try
{
System.clearProperty("com.zaxxer.hikari.housekeeping.periodMs");
ds.setMaxLifetime(700);
Assert.assertSame("Total connections not as expected", 0, TestElf.getPool(ds).getTotalConnections());
Assert.assertSame("Idle connections not as expected", 0, TestElf.getPool(ds).getIdleConnections());
Connection connection = ds.getConnection();
Assert.assertNotNull(connection);
Assert.assertSame("Second total connections not as expected", 1, TestElf.getPool(ds).getTotalConnections());
Assert.assertSame("Second idle connections not as expected", 0, TestElf.getPool(ds).getIdleConnections());
connection.close();
Assert.assertSame("Idle connections not as expected", 1, TestElf.getPool(ds).getIdleConnections());
Connection connection2 = ds.getConnection();
Assert.assertSame("Expected the same connection", connection, connection2);
Assert.assertSame("Second total connections not as expected", 1, TestElf.getPool(ds).getTotalConnections());
Assert.assertSame("Second idle connections not as expected", 0, TestElf.getPool(ds).getIdleConnections());
connection2.close();
Thread.sleep(2000);
connection2 = ds.getConnection();
Assert.assertNotSame("Expected a different connection", connection, connection2);
connection2.close();
Assert.assertSame("Post total connections not as expected", 1, TestElf.getPool(ds).getTotalConnections());
Assert.assertSame("Post idle connections not as expected", 1, TestElf.getPool(ds).getIdleConnections());
}
finally
{
ds.close();
}
}
|
#vulnerable code
@Test
public void testMaxLifetime() throws Exception
{
HikariConfig config = new HikariConfig();
config.setMinimumIdle(0);
config.setMaximumPoolSize(1);
config.setInitializationFailFast(true);
config.setConnectionTestQuery("VALUES 1");
config.setDataSourceClassName("com.zaxxer.hikari.mocks.StubDataSource");
System.setProperty("com.zaxxer.hikari.housekeeping.periodMs", "100");
HikariDataSource ds = new HikariDataSource(config);
try
{
System.clearProperty("com.zaxxer.hikari.housekeeping.periodMs");
ds.setMaxLifetime(700);
Assert.assertSame("Total connections not as expected", 0, TestElf.getPool(ds).getTotalConnections());
Assert.assertSame("Idle connections not as expected", 0, TestElf.getPool(ds).getIdleConnections());
Connection connection = ds.getConnection();
Assert.assertNotNull(connection);
Assert.assertSame("Second total connections not as expected", 1, TestElf.getPool(ds).getTotalConnections());
Assert.assertSame("Second idle connections not as expected", 0, TestElf.getPool(ds).getIdleConnections());
connection.close();
Assert.assertSame("Idle connections not as expected", 1, TestElf.getPool(ds).getIdleConnections());
Connection connection2 = ds.getConnection();
Assert.assertSame("Expected the same connection", connection, connection2);
Assert.assertSame("Second total connections not as expected", 1, TestElf.getPool(ds).getTotalConnections());
Assert.assertSame("Second idle connections not as expected", 0, TestElf.getPool(ds).getIdleConnections());
connection2.close();
Thread.sleep(2000);
connection2 = ds.getConnection();
Assert.assertNotSame("Expected a different connection", connection, connection2);
connection2.close();
Assert.assertSame("Post total connections not as expected", 1, TestElf.getPool(ds).getTotalConnections());
Assert.assertSame("Post idle connections not as expected", 1, TestElf.getPool(ds).getIdleConnections());
}
finally
{
ds.shutdown();
}
}
#location 51
#vulnerability type RESOURCE_LEAK
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
@Test
public void testShutdown3() throws SQLException
{
Assert.assertSame("StubConnection count not as expected", 0, StubConnection.count.get());
StubConnection.slowCreate = true;
HikariConfig config = new HikariConfig();
config.setMinimumIdle(5);
config.setMaximumPoolSize(5);
config.setInitializationFailFast(true);
config.setConnectionTestQuery("VALUES 1");
config.setDataSourceClassName("com.zaxxer.hikari.mocks.StubDataSource");
HikariDataSource ds = new HikariDataSource(config);
HikariPool pool = TestElf.getPool(ds);
PoolUtilities.quietlySleep(300);
Assert.assertTrue("Totals connection count not as expected, ", pool.getTotalConnections() == 5);
ds.close();
Assert.assertSame("Active connection count not as expected, ", 0, pool.getActiveConnections());
Assert.assertSame("Idle connection count not as expected, ", 0, pool.getIdleConnections());
Assert.assertSame("Total connection count not as expected", 0, pool.getTotalConnections());
}
|
#vulnerable code
@Test
public void testShutdown3() throws SQLException
{
Assert.assertSame("StubConnection count not as expected", 0, StubConnection.count.get());
StubConnection.slowCreate = true;
HikariConfig config = new HikariConfig();
config.setMinimumIdle(5);
config.setMaximumPoolSize(5);
config.setInitializationFailFast(true);
config.setConnectionTestQuery("VALUES 1");
config.setDataSourceClassName("com.zaxxer.hikari.mocks.StubDataSource");
HikariDataSource ds = new HikariDataSource(config);
HikariPool pool = TestElf.getPool(ds);
PoolUtilities.quietlySleep(300);
Assert.assertTrue("Totals connection count not as expected, ", pool.getTotalConnections() == 5);
ds.shutdown();
Assert.assertSame("Active connection count not as expected, ", 0, pool.getActiveConnections());
Assert.assertSame("Idle connection count not as expected, ", 0, pool.getIdleConnections());
Assert.assertSame("Total connection count not as expected", 0, pool.getTotalConnections());
}
#location 22
#vulnerability type RESOURCE_LEAK
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
public Connection getConnection() throws SQLException
{
final long start = System.currentTimeMillis();
final MetricsContext context = (isRecordMetrics ? metricsTracker.recordConnectionRequest(start) : MetricsTracker.NO_CONTEXT);
long timeout = connectionTimeout;
try {
do {
final PoolBagEntry bagEntry = connectionBag.borrow(timeout, TimeUnit.MILLISECONDS);
if (bagEntry == null) {
break; // We timed out... break and throw exception
}
final long now = System.currentTimeMillis();
if (now > bagEntry.expirationTime || (now - bagEntry.lastAccess > 1000L && !isConnectionAlive(bagEntry.connection, timeout))) {
closeConnection(bagEntry); // Throw away the dead connection and try again
timeout = connectionTimeout - elapsedTimeMs(start);
continue;
}
LeakTask leakTask = (leakDetectionThreshold == 0) ? NO_LEAK : new LeakTask(leakDetectionThreshold, houseKeepingExecutorService);
final IHikariConnectionProxy proxyConnection = ProxyFactory.getProxyConnection(this, bagEntry, leakTask);
if (isRecordMetrics) {
bagEntry.lastOpenTime = now;
}
return proxyConnection;
}
while (timeout > 0L);
}
catch (InterruptedException e) {
throw new SQLException("Interrupted during connection acquisition", e);
}
finally {
context.stop();
}
logPoolState("Timeout failure ");
throw new SQLException(String.format("Timeout of %dms encountered waiting for connection.", configuration.getConnectionTimeout()),
lastConnectionFailure.getAndSet(null));
}
|
#vulnerable code
public Connection getConnection() throws SQLException
{
final long start = System.currentTimeMillis();
final MetricsContext context = (isRecordMetrics ? metricsTracker.recordConnectionRequest(start) : MetricsTracker.NO_CONTEXT);
long timeout = connectionTimeout;
try {
do {
final PoolBagEntry bagEntry = connectionBag.borrow(timeout, TimeUnit.MILLISECONDS);
if (bagEntry == null) {
break; // We timed out... break and throw exception
}
final long now = System.currentTimeMillis();
if (now > bagEntry.expirationTime || (now - bagEntry.lastAccess > 1000L && !isConnectionAlive(bagEntry.connection, timeout))) {
closeConnection(bagEntry); // Throw away the dead connection and try again
timeout = connectionTimeout - elapsedTimeMs(start);
continue;
}
final IHikariConnectionProxy proxyConnection = ProxyFactory.getProxyConnection(this, bagEntry);
if (leakDetectionThreshold != 0) {
proxyConnection.captureStack(leakDetectionThreshold, houseKeepingExecutorService);
}
if (isRecordMetrics) {
bagEntry.lastOpenTime = now;
}
return proxyConnection;
}
while (timeout > 0L);
}
catch (InterruptedException e) {
throw new SQLException("Interrupted during connection acquisition", e);
}
finally {
context.stop();
}
logPoolState("Timeout failure ");
throw new SQLException(String.format("Timeout of %dms encountered waiting for connection.", configuration.getConnectionTimeout()),
lastConnectionFailure.getAndSet(null));
}
#location 24
#vulnerability type NULL_DEREFERENCE
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
@Test
public void testAutoCommit() throws SQLException
{
HikariDataSource ds = new HikariDataSource();
ds.setAutoCommit(true);
ds.setMinimumIdle(1);
ds.setMaximumPoolSize(1);
ds.setConnectionTestQuery("VALUES 1");
ds.setDataSourceClassName("com.zaxxer.hikari.mocks.StubDataSource");
try
{
Connection connection = ds.getConnection();
connection.setAutoCommit(false);
connection.close();
Connection connection2 = ds.getConnection();
Assert.assertSame(connection, connection2);
Assert.assertTrue(connection2.getAutoCommit());
connection2.close();
}
finally
{
ds.close();
}
}
|
#vulnerable code
@Test
public void testAutoCommit() throws SQLException
{
HikariDataSource ds = new HikariDataSource();
ds.setAutoCommit(true);
ds.setMinimumIdle(1);
ds.setMaximumPoolSize(1);
ds.setConnectionTestQuery("VALUES 1");
ds.setDataSourceClassName("com.zaxxer.hikari.mocks.StubDataSource");
try
{
Connection connection = ds.getConnection();
connection.setAutoCommit(false);
connection.close();
Connection connection2 = ds.getConnection();
Assert.assertSame(connection, connection2);
Assert.assertTrue(connection2.getAutoCommit());
connection2.close();
}
finally
{
ds.shutdown();
}
}
#location 24
#vulnerability type RESOURCE_LEAK
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
@Test
public void testBackfill() throws Exception
{
HikariConfig config = new HikariConfig();
config.setMinimumIdle(1);
config.setMaximumPoolSize(4);
config.setConnectionTimeout(500);
config.setInitializationFailFast(true);
config.setConnectionTestQuery("VALUES 1");
config.setDataSourceClassName("com.zaxxer.hikari.mocks.StubDataSource");
HikariDataSource ds = new HikariDataSource(config);
try
{
Assert.assertSame("Totals connections not as expected", 1, TestElf.getPool(ds).getTotalConnections());
Assert.assertSame("Idle connections not as expected", 1, TestElf.getPool(ds).getIdleConnections());
// This will take the pool down to zero
Connection connection = ds.getConnection();
Assert.assertNotNull(connection);
Assert.assertSame("Totals connections not as expected", 1, TestElf.getPool(ds).getTotalConnections());
Assert.assertSame("Idle connections not as expected", 0, TestElf.getPool(ds).getIdleConnections());
PreparedStatement statement = connection.prepareStatement("SELECT some, thing FROM somewhere WHERE something=?");
Assert.assertNotNull(statement);
ResultSet resultSet = statement.executeQuery();
Assert.assertNotNull(resultSet);
try
{
statement.getMaxFieldSize();
Assert.fail();
}
catch (Exception e)
{
Assert.assertSame(SQLException.class, e.getClass());
}
// The connection will be ejected from the pool here
connection.close();
Assert.assertSame("Totals connections not as expected", 0, TestElf.getPool(ds).getTotalConnections());
Assert.assertSame("Idle connections not as expected", 0, TestElf.getPool(ds).getIdleConnections());
// This will cause a backfill
connection = ds.getConnection();
connection.close();
Assert.assertTrue("Totals connections not as expected", TestElf.getPool(ds).getTotalConnections() > 0);
Assert.assertTrue("Idle connections not as expected", TestElf.getPool(ds).getIdleConnections() > 0);
}
finally
{
ds.close();
}
}
|
#vulnerable code
@Test
public void testBackfill() throws Exception
{
HikariConfig config = new HikariConfig();
config.setMinimumIdle(1);
config.setMaximumPoolSize(4);
config.setConnectionTimeout(500);
config.setInitializationFailFast(true);
config.setConnectionTestQuery("VALUES 1");
config.setDataSourceClassName("com.zaxxer.hikari.mocks.StubDataSource");
HikariDataSource ds = new HikariDataSource(config);
try
{
Assert.assertSame("Totals connections not as expected", 1, TestElf.getPool(ds).getTotalConnections());
Assert.assertSame("Idle connections not as expected", 1, TestElf.getPool(ds).getIdleConnections());
// This will take the pool down to zero
Connection connection = ds.getConnection();
Assert.assertNotNull(connection);
Assert.assertSame("Totals connections not as expected", 1, TestElf.getPool(ds).getTotalConnections());
Assert.assertSame("Idle connections not as expected", 0, TestElf.getPool(ds).getIdleConnections());
PreparedStatement statement = connection.prepareStatement("SELECT some, thing FROM somewhere WHERE something=?");
Assert.assertNotNull(statement);
ResultSet resultSet = statement.executeQuery();
Assert.assertNotNull(resultSet);
try
{
statement.getMaxFieldSize();
Assert.fail();
}
catch (Exception e)
{
Assert.assertSame(SQLException.class, e.getClass());
}
// The connection will be ejected from the pool here
connection.close();
Assert.assertSame("Totals connections not as expected", 0, TestElf.getPool(ds).getTotalConnections());
Assert.assertSame("Idle connections not as expected", 0, TestElf.getPool(ds).getIdleConnections());
// This will cause a backfill
connection = ds.getConnection();
connection.close();
Assert.assertTrue("Totals connections not as expected", TestElf.getPool(ds).getTotalConnections() > 0);
Assert.assertTrue("Idle connections not as expected", TestElf.getPool(ds).getIdleConnections() > 0);
}
finally
{
ds.shutdown();
}
}
#location 56
#vulnerability type RESOURCE_LEAK
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
@Test
public void testShutdown4() throws SQLException
{
StubConnection.slowCreate = true;
HikariConfig config = new HikariConfig();
config.setMinimumIdle(10);
config.setMaximumPoolSize(10);
config.setInitializationFailFast(false);
config.setConnectionTestQuery("VALUES 1");
config.setDataSourceClassName("com.zaxxer.hikari.mocks.StubDataSource");
HikariDataSource ds = new HikariDataSource(config);
PoolUtilities.quietlySleep(300);
ds.close();
long start = System.currentTimeMillis();
while (PoolUtilities.elapsedTimeMs(start) < TimeUnit.SECONDS.toMillis(5) && threadCount() > 0)
{
PoolUtilities.quietlySleep(250);
}
Assert.assertSame("Thread was leaked", 0, threadCount());
}
|
#vulnerable code
@Test
public void testShutdown4() throws SQLException
{
StubConnection.slowCreate = true;
HikariConfig config = new HikariConfig();
config.setMinimumIdle(10);
config.setMaximumPoolSize(10);
config.setInitializationFailFast(false);
config.setConnectionTestQuery("VALUES 1");
config.setDataSourceClassName("com.zaxxer.hikari.mocks.StubDataSource");
HikariDataSource ds = new HikariDataSource(config);
PoolUtilities.quietlySleep(300);
ds.shutdown();
long start = System.currentTimeMillis();
while (PoolUtilities.elapsedTimeMs(start) < TimeUnit.SECONDS.toMillis(5) && threadCount() > 0)
{
PoolUtilities.quietlySleep(250);
}
Assert.assertSame("Thread was leaked", 0, threadCount());
}
#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 testCreate() throws SQLException
{
HikariConfig config = new HikariConfig();
config.setMinimumIdle(1);
config.setMaximumPoolSize(1);
config.setInitializationFailFast(true);
config.setConnectionTestQuery("VALUES 1");
config.setDataSourceClassName("com.zaxxer.hikari.mocks.StubDataSource");
HikariDataSource ds = new HikariDataSource(config);
try
{
Assert.assertSame("Totals connections not as expected", 1, TestElf.getPool(ds).getTotalConnections());
Assert.assertSame("Idle connections not as expected", 1, TestElf.getPool(ds).getIdleConnections());
Connection connection = ds.getConnection();
Assert.assertNotNull(connection);
Assert.assertSame("Totals connections not as expected", 1, TestElf.getPool(ds).getTotalConnections());
Assert.assertSame("Idle connections not as expected", 0, TestElf.getPool(ds).getIdleConnections());
PreparedStatement statement = connection.prepareStatement("SELECT * FROM device WHERE device_id=?");
Assert.assertNotNull(statement);
statement.setInt(1, 0);
ResultSet resultSet = statement.executeQuery();
Assert.assertNotNull(resultSet);
Assert.assertFalse(resultSet.next());
resultSet.close();
statement.close();
connection.close();
Assert.assertSame("Totals connections not as expected", 1, TestElf.getPool(ds).getTotalConnections());
Assert.assertSame("Idle connections not as expected", 1, TestElf.getPool(ds).getIdleConnections());
}
finally
{
ds.close();
}
}
|
#vulnerable code
@Test
public void testCreate() throws SQLException
{
HikariConfig config = new HikariConfig();
config.setMinimumIdle(1);
config.setMaximumPoolSize(1);
config.setInitializationFailFast(true);
config.setConnectionTestQuery("VALUES 1");
config.setDataSourceClassName("com.zaxxer.hikari.mocks.StubDataSource");
HikariDataSource ds = new HikariDataSource(config);
try
{
Assert.assertSame("Totals connections not as expected", 1, TestElf.getPool(ds).getTotalConnections());
Assert.assertSame("Idle connections not as expected", 1, TestElf.getPool(ds).getIdleConnections());
Connection connection = ds.getConnection();
Assert.assertNotNull(connection);
Assert.assertSame("Totals connections not as expected", 1, TestElf.getPool(ds).getTotalConnections());
Assert.assertSame("Idle connections not as expected", 0, TestElf.getPool(ds).getIdleConnections());
PreparedStatement statement = connection.prepareStatement("SELECT * FROM device WHERE device_id=?");
Assert.assertNotNull(statement);
statement.setInt(1, 0);
ResultSet resultSet = statement.executeQuery();
Assert.assertNotNull(resultSet);
Assert.assertFalse(resultSet.next());
resultSet.close();
statement.close();
connection.close();
Assert.assertSame("Totals connections not as expected", 1, TestElf.getPool(ds).getTotalConnections());
Assert.assertSame("Idle connections not as expected", 1, TestElf.getPool(ds).getIdleConnections());
}
finally
{
ds.shutdown();
}
}
#location 42
#vulnerability type RESOURCE_LEAK
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
@Test
public void testOverflow()
{
ArrayList<Statement> verifyList = new ArrayList<>();
FastStatementList list = new FastStatementList();
for (int i = 0; i < 100; i++)
{
StubStatement statement = new StubStatement();
list.add(statement);
verifyList.add(statement);
}
for (int i = 0; i < 100; i++)
{
Assert.assertNotNull("Element " + i, list.get(i));
Assert.assertSame(verifyList.get(i), list.get(i));
}
}
|
#vulnerable code
@Test
public void testOverflow()
{
FastStatementList list = new FastStatementList();
for (int i = 0; i < 100; i++)
{
list.add(new StubStatement());
}
for (int i = 0; i < 100; i++)
{
Assert.assertNotNull("Element " + i, list.get(i));
}
}
#location 12
#vulnerability type RESOURCE_LEAK
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
@Test
public void testDoubleClose() throws Exception
{
HikariConfig config = new HikariConfig();
config.setMinimumIdle(1);
config.setMaximumPoolSize(1);
config.setInitializationFailFast(true);
config.setConnectionTestQuery("VALUES 1");
config.setDataSourceClassName("com.zaxxer.hikari.mocks.StubDataSource");
HikariDataSource ds = new HikariDataSource(config);
try
{
Connection connection = ds.getConnection();
connection.close();
connection.close();
}
finally
{
ds.close();
}
}
|
#vulnerable code
@Test
public void testDoubleClose() throws Exception
{
HikariConfig config = new HikariConfig();
config.setMinimumIdle(1);
config.setMaximumPoolSize(1);
config.setInitializationFailFast(true);
config.setConnectionTestQuery("VALUES 1");
config.setDataSourceClassName("com.zaxxer.hikari.mocks.StubDataSource");
HikariDataSource ds = new HikariDataSource(config);
try
{
Connection connection = ds.getConnection();
connection.close();
connection.close();
}
finally
{
ds.shutdown();
}
}
#location 20
#vulnerability type RESOURCE_LEAK
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
@Test
public void testConnectionRetries3() throws SQLException
{
HikariConfig config = new HikariConfig();
config.setMinimumIdle(0);
config.setMaximumPoolSize(2);
config.setConnectionTimeout(2800);
config.setConnectionTestQuery("VALUES 1");
config.setDataSourceClassName("com.zaxxer.hikari.mocks.StubDataSource");
HikariDataSource ds = new HikariDataSource(config);
final Connection connection1 = ds.getConnection();
final Connection connection2 = ds.getConnection();
Assert.assertNotNull(connection1);
Assert.assertNotNull(connection2);
ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(2);
scheduler.schedule(new Runnable() {
public void run()
{
try
{
connection1.close();
}
catch (Exception e)
{
e.printStackTrace(System.err);
}
}
}, 800, TimeUnit.MILLISECONDS);
long start = System.currentTimeMillis();
try
{
Connection connection3 = ds.getConnection();
connection3.close();
long elapsed = System.currentTimeMillis() - start;
Assert.assertTrue("Waited too long to get a connection.", (elapsed >= 700) && (elapsed < 950));
}
catch (SQLException e)
{
Assert.fail("Should not have timed out.");
}
finally
{
scheduler.shutdownNow();
ds.close();
}
}
|
#vulnerable code
@Test
public void testConnectionRetries3() throws SQLException
{
HikariConfig config = new HikariConfig();
config.setMinimumIdle(0);
config.setMaximumPoolSize(2);
config.setConnectionTimeout(2800);
config.setConnectionTestQuery("VALUES 1");
config.setDataSourceClassName("com.zaxxer.hikari.mocks.StubDataSource");
HikariDataSource ds = new HikariDataSource(config);
final Connection connection1 = ds.getConnection();
final Connection connection2 = ds.getConnection();
Assert.assertNotNull(connection1);
Assert.assertNotNull(connection2);
ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(2);
scheduler.schedule(new Runnable() {
public void run()
{
try
{
connection1.close();
}
catch (Exception e)
{
e.printStackTrace(System.err);
}
}
}, 800, TimeUnit.MILLISECONDS);
long start = System.currentTimeMillis();
try
{
Connection connection3 = ds.getConnection();
connection3.close();
long elapsed = System.currentTimeMillis() - start;
Assert.assertTrue("Waited too long to get a connection.", (elapsed >= 700) && (elapsed < 950));
}
catch (SQLException e)
{
Assert.fail("Should not have timed out.");
}
finally
{
scheduler.shutdownNow();
ds.shutdown();
}
}
#location 49
#vulnerability type RESOURCE_LEAK
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
@Test
public void testTransactionIsolation() throws SQLException
{
HikariDataSource ds = new HikariDataSource();
ds.setTransactionIsolation("TRANSACTION_READ_COMMITTED");
ds.setMinimumIdle(1);
ds.setMaximumPoolSize(1);
ds.setConnectionTestQuery("VALUES 1");
ds.setDataSourceClassName("com.zaxxer.hikari.mocks.StubDataSource");
try
{
Connection connection = ds.getConnection();
connection.setTransactionIsolation(Connection.TRANSACTION_READ_UNCOMMITTED);
connection.close();
Connection connection2 = ds.getConnection();
Assert.assertSame(connection, connection2);
Assert.assertEquals(Connection.TRANSACTION_READ_COMMITTED, connection2.getTransactionIsolation());
connection2.close();
}
finally
{
ds.close();
}
}
|
#vulnerable code
@Test
public void testTransactionIsolation() throws SQLException
{
HikariDataSource ds = new HikariDataSource();
ds.setTransactionIsolation("TRANSACTION_READ_COMMITTED");
ds.setMinimumIdle(1);
ds.setMaximumPoolSize(1);
ds.setConnectionTestQuery("VALUES 1");
ds.setDataSourceClassName("com.zaxxer.hikari.mocks.StubDataSource");
try
{
Connection connection = ds.getConnection();
connection.setTransactionIsolation(Connection.TRANSACTION_READ_UNCOMMITTED);
connection.close();
Connection connection2 = ds.getConnection();
Assert.assertSame(connection, connection2);
Assert.assertEquals(Connection.TRANSACTION_READ_COMMITTED, connection2.getTransactionIsolation());
connection2.close();
}
finally
{
ds.shutdown();
}
}
#location 24
#vulnerability type RESOURCE_LEAK
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
@Test
public void testMaxLifetime2() throws Exception
{
HikariConfig config = new HikariConfig();
config.setMinimumIdle(0);
config.setMaximumPoolSize(1);
config.setInitializationFailFast(true);
config.setConnectionTestQuery("VALUES 1");
config.setDataSourceClassName("com.zaxxer.hikari.mocks.StubDataSource");
HikariDataSource ds = new HikariDataSource(config);
try
{
ds.setMaxLifetime(700);
Assert.assertSame("Total connections not as expected", 0, TestElf.getPool(ds).getTotalConnections());
Assert.assertSame("Idle connections not as expected", 0, TestElf.getPool(ds).getIdleConnections());
Connection connection = ds.getConnection();
Assert.assertNotNull(connection);
Assert.assertSame("Second total connections not as expected", 1, TestElf.getPool(ds).getTotalConnections());
Assert.assertSame("Second idle connections not as expected", 0, TestElf.getPool(ds).getIdleConnections());
connection.close();
Assert.assertSame("Idle connections not as expected", 1, TestElf.getPool(ds).getIdleConnections());
Connection connection2 = ds.getConnection();
Assert.assertSame("Expected the same connection", connection, connection2);
Assert.assertSame("Second total connections not as expected", 1, TestElf.getPool(ds).getTotalConnections());
Assert.assertSame("Second idle connections not as expected", 0, TestElf.getPool(ds).getIdleConnections());
connection2.close();
Thread.sleep(800);
connection2 = ds.getConnection();
Assert.assertNotSame("Expected a different connection", connection, connection2);
connection2.close();
Assert.assertSame("Post total connections not as expected", 1, TestElf.getPool(ds).getTotalConnections());
Assert.assertSame("Post idle connections not as expected", 1, TestElf.getPool(ds).getIdleConnections());
}
finally
{
ds.close();
}
}
|
#vulnerable code
@Test
public void testMaxLifetime2() throws Exception
{
HikariConfig config = new HikariConfig();
config.setMinimumIdle(0);
config.setMaximumPoolSize(1);
config.setInitializationFailFast(true);
config.setConnectionTestQuery("VALUES 1");
config.setDataSourceClassName("com.zaxxer.hikari.mocks.StubDataSource");
HikariDataSource ds = new HikariDataSource(config);
try
{
ds.setMaxLifetime(700);
Assert.assertSame("Total connections not as expected", 0, TestElf.getPool(ds).getTotalConnections());
Assert.assertSame("Idle connections not as expected", 0, TestElf.getPool(ds).getIdleConnections());
Connection connection = ds.getConnection();
Assert.assertNotNull(connection);
Assert.assertSame("Second total connections not as expected", 1, TestElf.getPool(ds).getTotalConnections());
Assert.assertSame("Second idle connections not as expected", 0, TestElf.getPool(ds).getIdleConnections());
connection.close();
Assert.assertSame("Idle connections not as expected", 1, TestElf.getPool(ds).getIdleConnections());
Connection connection2 = ds.getConnection();
Assert.assertSame("Expected the same connection", connection, connection2);
Assert.assertSame("Second total connections not as expected", 1, TestElf.getPool(ds).getTotalConnections());
Assert.assertSame("Second idle connections not as expected", 0, TestElf.getPool(ds).getIdleConnections());
connection2.close();
Thread.sleep(800);
connection2 = ds.getConnection();
Assert.assertNotSame("Expected a different connection", connection, connection2);
connection2.close();
Assert.assertSame("Post total connections not as expected", 1, TestElf.getPool(ds).getTotalConnections());
Assert.assertSame("Post idle connections not as expected", 1, TestElf.getPool(ds).getIdleConnections());
}
finally
{
ds.shutdown();
}
}
#location 47
#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)
{
if (args.length < 3)
{
System.err.println("Usage: <poolname> <threads> <poolsize>");
System.err.println(" <poolname> 'hikari' or 'bone'");
System.exit(0);
}
THREADS = Integer.parseInt(args[1]);
POOL_MAX = Integer.parseInt(args[2]);
Benchmark1 benchmarks = new Benchmark1();
if (args[0].equals("hikari"))
{
benchmarks.ds = benchmarks.setupHikari();
System.out.printf("Benchmarking HikariCP - %d threads, %d connections", THREADS, POOL_MAX);
}
else if (args[0].equals("bone"))
{
benchmarks.ds = benchmarks.setupBone();
System.out.printf("Benchmarking BoneCP - %d threads, %d connections", THREADS, POOL_MAX);
}
else if (args[0].equals("dbpool"))
{
benchmarks.ds = benchmarks.setupDbPool();
System.out.printf("Benchmarking DbPool - %d threads, %d connections", THREADS, POOL_MAX);
}
else if (args[0].equals("c3p0"))
{
benchmarks.ds = benchmarks.setupC3P0();
System.out.printf("Benchmarking C3P0 - %d threads, %d connections", THREADS, POOL_MAX);
}
else
{
System.err.println("Start with one of: hikari, bone");
System.exit(0);
}
System.out.println("\nMixedBench");
System.out.println(" Warming up JIT");
benchmarks.startMixedBench(100, 10000);
System.out.println(" MixedBench Final Timing Runs");
long elapsed = 0;
elapsed += benchmarks.startMixedBench(THREADS, 1000);
elapsed += benchmarks.startMixedBench(THREADS, 1000);
elapsed += benchmarks.startMixedBench(THREADS, 1000);
elapsed += benchmarks.startMixedBench(THREADS, 1000);
System.out.printf("Elapsed time for timing runs (excluding thread start): %dms\n", TimeUnit.NANOSECONDS.toMillis(elapsed));
System.out.println("\nBoneBench");
System.out.println(" Warming up JIT");
benchmarks.startSillyBench(THREADS);
System.out.println(" BoneBench Final Timing Run");
benchmarks.startSillyBench(THREADS);
benchmarks.startSillyBench(THREADS);
benchmarks.startSillyBench(THREADS);
benchmarks.startSillyBench(THREADS);
}
|
#vulnerable code
public static void main(String... args)
{
if (args.length < 3)
{
System.err.println("Usage: <poolname> <threads> <poolsize>");
System.err.println(" <poolname> 'hikari' or 'bone'");
System.exit(0);
}
THREADS = Integer.parseInt(args[1]);
POOL_MAX = Integer.parseInt(args[2]);
Benchmark1 benchmarks = new Benchmark1();
if (args[0].equals("hikari"))
{
benchmarks.ds = benchmarks.setupHikari();
System.out.printf("Benchmarking HikariCP - %d threads, %d connections", THREADS, POOL_MAX);
}
else if (args[0].equals("bone"))
{
benchmarks.ds = benchmarks.setupBone();
System.out.printf("Benchmarking BoneCP - %d threads, %d connections", THREADS, POOL_MAX);
}
else
{
System.err.println("Start with one of: hikari, bone");
System.exit(0);
}
System.out.println("\nMixedBench");
System.out.println(" Warming up JIT");
benchmarks.startMixedBench(100, 10000);
System.out.println(" MixedBench Final Timing Runs");
long elapsed = 0;
elapsed += benchmarks.startMixedBench(THREADS, 1000);
elapsed += benchmarks.startMixedBench(THREADS, 1000);
elapsed += benchmarks.startMixedBench(THREADS, 1000);
elapsed += benchmarks.startMixedBench(THREADS, 1000);
System.out.printf("Elapsed time for timing runs (excluding thread start): %dms\n", TimeUnit.NANOSECONDS.toMillis(elapsed));
System.out.println("\nBoneBench");
System.out.println(" Warming up JIT");
benchmarks.startSillyBench(THREADS);
System.out.println(" BoneBench Final Timing Run");
benchmarks.startSillyBench(THREADS);
benchmarks.startSillyBench(THREADS);
benchmarks.startSillyBench(THREADS);
benchmarks.startSillyBench(THREADS);
}
#location 43
#vulnerability type RESOURCE_LEAK
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
@Override
public void startCrackedSession(ProtocolLibLoginSource source, StoredProfile profile, String username) {
BukkitLoginSession loginSession = new BukkitLoginSession(username, profile);
plugin.putSession(player.getAddress(), loginSession);
}
|
#vulnerable code
@Override
public void startCrackedSession(ProtocolLibLoginSource source, StoredProfile profile, String username) {
BukkitLoginSession loginSession = new BukkitLoginSession(username, profile);
plugin.getLoginSessions().put(player.getAddress().toString(), loginSession);
}
#location 4
#vulnerability type NULL_DEREFERENCE
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
public void onSessionRestore(RestoreSessionEvent restoreSessionEvent) {
Player player = restoreSessionEvent.getPlayer();
BukkitLoginSession session = plugin.getSession(player.getAddress());
if (session != null && session.isVerified()) {
restoreSessionEvent.setCancelled(true);
}
}
|
#vulnerable code
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true)
public void onSessionRestore(RestoreSessionEvent restoreSessionEvent) {
Player player = restoreSessionEvent.getPlayer();
String id = '/' + player.getAddress().getAddress().getHostAddress() + ':' + player.getAddress().getPort();
BukkitLoginSession session = plugin.getLoginSessions().get(id);
if (session != null && session.isVerified()) {
restoreSessionEvent.setCancelled(true);
}
}
#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() {
try {
BukkitLoginSession session = plugin.getSession(player.getAddress());
if (session == null) {
disconnect("invalid-request", true
, "GameProfile {0} tried to send encryption response at invalid state", player.getAddress());
} else {
verifyResponse(session);
}
} finally {
//this is a fake packet; it shouldn't be send to the server
synchronized (packetEvent.getAsyncMarker().getProcessingLock()) {
packetEvent.setCancelled(true);
}
ProtocolLibrary.getProtocolManager().getAsynchronousManager().signalPacketTransmission(packetEvent);
}
}
|
#vulnerable code
@Override
public void run() {
try {
BukkitLoginSession session = plugin.getLoginSessions().get(player.getAddress().toString());
if (session == null) {
disconnect("invalid-request", true
, "GameProfile {0} tried to send encryption response at invalid state", player.getAddress());
} else {
verifyResponse(session);
}
} finally {
//this is a fake packet; it shouldn't be send to the server
synchronized (packetEvent.getAsyncMarker().getProcessingLock()) {
packetEvent.setCancelled(true);
}
ProtocolLibrary.getProtocolManager().getAsynchronousManager().signalPacketTransmission(packetEvent);
}
}
#location 4
#vulnerability type NULL_DEREFERENCE
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
private void readMessage(Player player, LoginActionMessage message) {
String playerName = message.getPlayerName();
Type type = message.getType();
InetSocketAddress address = player.getAddress();
if (type == Type.LOGIN) {
BukkitLoginSession playerSession = new BukkitLoginSession(playerName, true);
playerSession.setVerified(true);
plugin.putSession(address, playerSession);
Bukkit.getScheduler().runTaskLaterAsynchronously(plugin, new ForceLoginTask(plugin.getCore(), player), 10L);
} else if (type == Type.REGISTER) {
Bukkit.getScheduler().runTaskLaterAsynchronously(plugin, () -> {
AuthPlugin<Player> authPlugin = plugin.getCore().getAuthPluginHook();
try {
//we need to check if the player is registered on Bukkit too
if (authPlugin == null || !authPlugin.isRegistered(playerName)) {
BukkitLoginSession playerSession = new BukkitLoginSession(playerName, false);
playerSession.setVerified(true);
plugin.putSession(address, playerSession);
new ForceLoginTask(plugin.getCore(), player).run();
}
} catch (Exception ex) {
plugin.getLog().error("Failed to query isRegistered for player: {}", player, ex);
}
}, 10L);
} else if (type == Type.CRACKED) {
//we don't start a force login task here so update it manually
plugin.getPremiumPlayers().put(player.getUniqueId(), PremiumStatus.CRACKED);
}
}
|
#vulnerable code
private void readMessage(Player player, LoginActionMessage message) {
String playerName = message.getPlayerName();
Type type = message.getType();
InetSocketAddress address = player.getAddress();
String id = '/' + address.getAddress().getHostAddress() + ':' + address.getPort();
if (type == Type.LOGIN) {
BukkitLoginSession playerSession = new BukkitLoginSession(playerName, true);
playerSession.setVerified(true);
plugin.getLoginSessions().put(id, playerSession);
Bukkit.getScheduler().runTaskLaterAsynchronously(plugin, new ForceLoginTask(plugin.getCore(), player), 10L);
} else if (type == Type.REGISTER) {
Bukkit.getScheduler().runTaskLaterAsynchronously(plugin, () -> {
AuthPlugin<Player> authPlugin = plugin.getCore().getAuthPluginHook();
try {
//we need to check if the player is registered on Bukkit too
if (authPlugin == null || !authPlugin.isRegistered(playerName)) {
BukkitLoginSession playerSession = new BukkitLoginSession(playerName, false);
playerSession.setVerified(true);
plugin.getLoginSessions().put(id, playerSession);
new ForceLoginTask(plugin.getCore(), player).run();
}
} catch (Exception ex) {
plugin.getLog().error("Failed to query isRegistered for player: {}", player, ex);
}
}, 10L);
} else if (type == Type.CRACKED) {
//we don't start a force login task here so update it manually
plugin.getPremiumPlayers().put(player.getUniqueId(), PremiumStatus.CRACKED);
}
}
#location 6
#vulnerability type NULL_DEREFERENCE
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
protected static String rootPath() {
String path = OS.getTarget();
String sep = System.getProperty("file.separator");
if (!path.endsWith(sep)) {
path += sep;
}
return path + "chronicle-jul" + Time.uniqueId();
}
|
#vulnerable code
protected static String rootPath() {
String path = System.getProperty("java.io.tmpdir");
String sep = System.getProperty("file.separator");
if (!path.endsWith(sep)) {
path += sep;
}
return path + "chronicle-jul";
}
#location 5
#vulnerability type NULL_DEREFERENCE
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
private String basePath() {
String path = OS.getTarget();
String sep = System.getProperty("file.separator");
if (!path.endsWith(sep)) {
path += sep;
}
return path + "chronicle-logger-" + Time.uniqueId() + sep;
}
|
#vulnerable code
private String basePath() {
String path = System.getProperty("java.io.tmpdir");
String sep = System.getProperty("file.separator");
if (!path.endsWith(sep)) {
path += sep;
}
return path + "chronicle-logger" + sep;
}
#location 5
#vulnerability type NULL_DEREFERENCE
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
static String basePath() {
String path = OS.getTarget();
String sep = System.getProperty("file.separator");
if (!path.endsWith(sep)) {
path += sep;
}
return path + "chronicle-jul-api" + Time.uniqueId();
}
|
#vulnerable code
static String basePath() {
String path = System.getProperty("java.io.tmpdir");
String sep = System.getProperty("file.separator");
if (!path.endsWith(sep)) {
path += sep;
}
return path + "chronicle-jul-api";
}
#location 5
#vulnerability type NULL_DEREFERENCE
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
static String rootPath() {
String path = OS.getTarget();
String sep = System.getProperty("file.separator");
if (!path.endsWith(sep)) {
path += sep;
}
return path + "chronicle-logback" + Time.uniqueId();
}
|
#vulnerable code
static String rootPath() {
String path = System.getProperty("java.io.tmpdir");
String sep = System.getProperty("file.separator");
if (!path.endsWith(sep)) {
path += sep;
}
return path + "chronicle-logback";
}
#location 5
#vulnerability type NULL_DEREFERENCE
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
static String rootPath() {
String path = OS.getTarget();
String sep = System.getProperty("file.separator");
if (!path.endsWith(sep)) {
path += sep;
}
return path + "chronicle-log4j2" + Time.uniqueId();
}
|
#vulnerable code
static String rootPath() {
String path = System.getProperty("java.io.tmpdir");
String sep = System.getProperty("file.separator");
if (!path.endsWith(sep)) {
path += sep;
}
return path + "chronicle-log4j2";
}
#location 5
#vulnerability type NULL_DEREFERENCE
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
static String basePath() {
String path = OS.getTarget();
String sep = System.getProperty("file.separator");
if (!path.endsWith(sep)) {
path += sep;
}
return path + "chronicle-slf4j" + Time.uniqueId();
}
|
#vulnerable code
static String basePath() {
String path = System.getProperty("java.io.tmpdir");
String sep = System.getProperty("file.separator");
if (!path.endsWith(sep)) {
path += sep;
}
return path + "chronicle-slf4j";
}
#location 5
#vulnerability type NULL_DEREFERENCE
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
static String basePath() {
String path = OS.getTarget();
String sep = System.getProperty("file.separator");
if (!path.endsWith(sep)) {
path += sep;
}
return path + "chronicle-jcl-" + Time.uniqueId();
}
|
#vulnerable code
static String basePath() {
String path = System.getProperty("java.io.tmpdir");
String sep = System.getProperty("file.separator");
if (!path.endsWith(sep)) {
path += sep;
}
return path + "chronicle-jcl";
}
#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 doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
HttpServletRequest httpRequest = (HttpServletRequest) request;
String path = httpRequest.getServletPath();
if (path.startsWith("/ws/")) {
String sessionKey = getSessionKey(httpRequest);
String sysRole = null;
boolean isAuthByApiKey = false;
if (sessionKey != null) {
User user = userService.getUserBySessionKey(sessionKey);
if (user != null) {
user.setSessionKey(sessionKey);
httpRequest.setAttribute(Constants.HTTP_REQUEST_ATTR_USER, user);
sysRole = user.getSysRole();
}
} else {
String apiKey = httpRequest.getHeader(Constants.HTTP_HEADER_API_KEY);
if (apiKey != null) {
User user = userService.getUserByApiKey(apiKey);
if (user != null) {
httpRequest.setAttribute(Constants.HTTP_REQUEST_ATTR_USER, user);
sysRole = user.getSysRole();
isAuthByApiKey = true;
}
}
}
if (sysRole != null) {
boolean isValid = false;
if (isAuthByApiKey) {
// Authorized by using API key
isValid = validateByApiKey(httpRequest.getMethod(), path);
} else {
// Authorized by using cookie.
if (Constants.SYS_ROLE_VIEWER.equals(sysRole)) {
isValid = validateViewer(httpRequest.getMethod(), path);
} else if (Constants.SYS_ROLE_DEVELOPER.equals(sysRole) || Constants.SYS_ROLE_ADMIN.equals(sysRole)) {
isValid = true;
} else {
isValid = false;
}
}
if (isValid) {
chain.doFilter(request, response);
} else {
return401(response);
}
} else {
return401(response);
}
} else {
chain.doFilter(request, response);
}
}
|
#vulnerable code
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
HttpServletRequest httpRequest = (HttpServletRequest) request;
String path = httpRequest.getServletPath();
if (path.startsWith("/ws/")) {
String sessionKey = getSessionKey(httpRequest);
String sysRole = null;
boolean isAuthByApiKey = false;
if (sessionKey != null) {
User user = userService.getUserBySessionKey(sessionKey);
user.setSessionKey(sessionKey);
if (user != null) {
httpRequest.setAttribute(Constants.HTTP_REQUEST_ATTR_USER, user);
sysRole = user.getSysRole();
}
} else {
String apiKey = httpRequest.getHeader(Constants.HTTP_HEADER_API_KEY);
if (apiKey != null) {
User user = userService.getUserByApiKey(apiKey);
if (user != null) {
httpRequest.setAttribute(Constants.HTTP_REQUEST_ATTR_USER, user);
sysRole = user.getSysRole();
isAuthByApiKey = true;
}
}
}
if (sysRole != null) {
boolean isValid = false;
if (isAuthByApiKey) {
// Authorized by using API key
isValid = validateByApiKey(httpRequest.getMethod(), path);
} else {
// Authorized by using cookie.
if (Constants.SYS_ROLE_VIEWER.equals(sysRole)) {
isValid = validateViewer(httpRequest.getMethod(), path);
} else if (Constants.SYS_ROLE_DEVELOPER.equals(sysRole) || Constants.SYS_ROLE_ADMIN.equals(sysRole)) {
isValid = true;
} else {
isValid = false;
}
}
if (isValid) {
chain.doFilter(request, response);
} else {
return401(response);
}
} else {
return401(response);
}
} else {
chain.doFilter(request, response);
}
}
#location 12
#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){
FullAPI test = null;
try {
test = new FullAPI.Builder()
.cfdPath("jsan_resources/feature_sets/writeprints_feature_set_limited.xml")
.psPath("jsan_resources/problem_sets/drexel_1_train_test.xml")
.setAnalyzer(new SparkAnalyzer())
.numThreads(1).analysisType(analysisType.TRAIN_TEST_KNOWN).useCache(false).chunkDocs(false)
.loadDocContents(true)
.build();
} catch (Exception e) {
e.printStackTrace();
System.err.println("Failed to intialize API, exiting...");
System.exit(1);
}
test.prepareInstances();
test.calcInfoGain();
//test.applyInfoGain(5);
test.run();
System.out.println(test.getStatString());
System.out.println(test.getReadableInfoGain(false));
System.out.println(test.getResults().toJson().toString());
//System.out.println(test.getClassificationAccuracy());
//System.out.println(test.getStatString());
}
|
#vulnerable code
public static void main(String[] args){
FullAPI test = null;
ProblemSet ps = new ProblemSet();
File parent = new File("/Users/tdutko200/git/jstylo/jsan_resources/corpora/drexel_1");
try {
for (File author : parent.listFiles()) {
if (!author.getName().equalsIgnoreCase(".DS_Store")) {
for (File document : author.listFiles()) {
if (!document.getName().equalsIgnoreCase(".DS_Store")) {
Document doc = new StringDocument(toDeleteGetStringFromFile(document), author.getName(),document.getName());
doc.load();
ps.addTrainDoc(author.getName(), doc);
}
}
}
}
} catch (Exception e) {
LOG.error("Womp womp.",e);
System.exit(1);
}
try {
test = new FullAPI.Builder()
.cfdPath("jsan_resources/feature_sets/writeprints_feature_set_limited.xml")
.ps(ps)
.setAnalyzer(new WekaAnalyzer())
.numThreads(1).analysisType(analysisType.CROSS_VALIDATION).useCache(false).chunkDocs(false)
.loadDocContents(true)
.build();
} catch (Exception e) {
e.printStackTrace();
System.err.println("Failed to intialize API, exiting...");
System.exit(1);
}
test.prepareInstances();
test.calcInfoGain();
//test.applyInfoGain(5);
test.run();
System.out.println(test.getStatString());
System.out.println(test.getReadableInfoGain(false));
System.out.println(test.getResults().toJson().toString());
//System.out.println(test.getClassificationAccuracy());
//System.out.println(test.getStatString());
}
#location 8
#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){
FullAPI test = new FullAPI.Builder()
.cfdPath("jsan_resources/feature_sets/writeprints_feature_set_limited.xml")
.psPath("./jsan_resources/problem_sets/drexel_1_small.xml")
.classifierPath("weka.classifiers.functions.SMO")
.numThreads(1)
.analysisType(analysisType.CROSS_VALIDATION)
.useCache(false)
.chunkDocs(false)
.useDocTitles(true)
.build();
test.prepareInstances();
//test.calcInfoGain();
//test.applyInfoGain(1500);
test.prepareAnalyzer();
test.run();
System.out.println(test.getStatString());
System.out.println(test.getReadableInfoGain(false));
//System.out.println(test.getClassificationAccuracy());
//System.out.println(test.getStatString());
}
|
#vulnerable code
public static void main(String[] args){
ProblemSet ps = new ProblemSet();
File sourceDir = new File("jsan_resources/corpora/drexel_1");
System.out.println(sourceDir.getAbsolutePath());
for (File author : sourceDir.listFiles()){
for (File doc : author.listFiles()){
ps.addTrainDoc(author.getName(), new Document(doc.getAbsolutePath(),author.getName(),doc.getName()));
}
}
FullAPI test = new FullAPI.Builder()
.cfdPath("jsan_resources/feature_sets/writeprints_feature_set_limited.xml")
//.psPath("./jsan_resources/problem_sets/enron_demo.xml")
.ps(ps)
.classifierPath("weka.classifiers.functions.SMO")
.numThreads(1)
.analysisType(analysisType.CROSS_VALIDATION)
.useCache(false)
.chunkDocs(false)
.build();
test.prepareInstances();
test.calcInfoGain();
//test.applyInfoGain(1500);
test.prepareAnalyzer();
test.run();
System.out.println(test.getStatString());
System.out.println(test.getReadableInfoGain(false));
//System.out.println(test.getClassificationAccuracy());
//System.out.println(test.getStatString());
}
#location 7
#vulnerability type NULL_DEREFERENCE
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
public static void saveMeBackup(File f, String toWrite) throws IOException
{
String backup = "/Users/bekahoverdorf/btbackup/timestamp" + BekahUtil.getNow();
String path = f.getAbsolutePath();
Scanner baseScanner = new Scanner(path);
Scanner pathScanner = baseScanner.useDelimiter("/");
boolean record = false;
while (pathScanner.hasNext())
{
String temp = pathScanner.next();
if (record)
{
backup += "/" + temp;
}
if (temp.equals("Documents") || temp.equals("NetBeansProjects"))
{
record = true;
}
}
// make the backup
File backupFile = new File(backup);
File backupDir = new File(backupFile.getParent());
backupDir.mkdirs();
backupFile.createNewFile();
FileWriter backupfstream = new FileWriter(backupFile);
BufferedWriter backupout = new BufferedWriter(backupfstream);
backupout.write(toWrite);
backupout.close();
// make the file
File dir = new File(f.getParent());
dir.mkdirs();
f.createNewFile();
FileWriter fstream = new FileWriter(f);
BufferedWriter out = new BufferedWriter(fstream);
out.write(toWrite);
out.close();
pathScanner.close();
baseScanner.close();
}
|
#vulnerable code
public static void saveMeBackup(File f, String toWrite) throws IOException
{
String backup = "/Users/bekahoverdorf/btbackup/timestamp" + BekahUtil.getNow();
String path = f.getAbsolutePath();
Scanner pathScanner = new Scanner(path).useDelimiter("/");
boolean record = false;
while (pathScanner.hasNext())
{
String temp = pathScanner.next();
if (record)
{
backup += "/" + temp;
}
if (temp.equals("Documents") || temp.equals("NetBeansProjects"))
{
record = true;
}
}
// make the backup
File backupFile = new File(backup);
File backupDir = new File(backupFile.getParent());
backupDir.mkdirs();
backupFile.createNewFile();
FileWriter backupfstream = new FileWriter(backupFile);
BufferedWriter backupout = new BufferedWriter(backupfstream);
backupout.write(toWrite);
backupout.close();
// make the file
File dir = new File(f.getParent());
dir.mkdirs();
f.createNewFile();
FileWriter fstream = new FileWriter(f);
BufferedWriter out = new BufferedWriter(fstream);
out.write(toWrite);
out.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 checkProviderInfo(ProviderGroup providerGroup) {
List<ProviderInfo> providerInfos = providerGroup == null ? null : providerGroup.getProviderInfos();
if (CommonUtils.isEmpty(providerInfos)) {
return;
}
Iterator<ProviderInfo> iterator = providerInfos.iterator();
while (iterator.hasNext()) {
ProviderInfo providerInfo = iterator.next();
if (!StringUtils.equals(providerInfo.getProtocolType(), consumerConfig.getProtocol())) {
if (LOGGER.isWarnEnabled(consumerConfig.getAppName())) {
LOGGER.warnWithApp(consumerConfig.getAppName(),
"Unmatched protocol between consumer [{}] and provider [{}].",
consumerConfig.getProtocol(), providerInfo.getProtocolType());
}
}
}
}
|
#vulnerable code
protected void checkProviderInfo(ProviderGroup providerGroup) {
List<ProviderInfo> providerInfos = providerGroup == null ? null : providerGroup.getProviderInfos();
if (CommonUtils.isEmpty(providerInfos)) {
return;
}
Iterator<ProviderInfo> iterator = providerInfos.iterator();
while (iterator.hasNext()) {
ProviderInfo providerInfo = iterator.next();
if (!StringUtils.equals(providerInfo.getProtocolType(), consumerConfig.getProtocol())) {
if (LOGGER.isWarnEnabled(consumerConfig.getAppName())) {
LOGGER.warnWithApp(consumerConfig.getAppName(),
"Unmatched protocol between consumer [{}] and provider [{}].",
consumerConfig.getProtocol(), providerInfo.getProtocolType());
}
}
if (StringUtils.isEmpty(providerInfo.getSerializationType())) {
providerInfo.setSerializationType(consumerConfig.getSerialization());
}
}
}
#location 16
#vulnerability type THREAD_SAFETY_VIOLATION
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
@Override
public void stop() {
if (!started) {
return;
}
try {
// 关闭端口,不关闭线程池
if (LOGGER.isInfoEnabled()) {
LOGGER.info("Stop the http rest server at port {}", serverConfig.getPort());
}
httpServer.stop();
} catch (Exception e) {
LOGGER.error("Stop the http rest server at port " + serverConfig.getPort() + " error !", e);
}
started = false;
}
|
#vulnerable code
@Override
public void stop() {
if (!started) {
return;
}
try {
// 关闭端口,不关闭线程池
if (LOGGER.isInfoEnabled()) {
LOGGER.info("Stop the http rest server at port {}", serverConfig.getPort());
}
httpServer.stop();
httpServer = null;
} catch (Exception e) {
LOGGER.error("Stop the http rest server at port " + serverConfig.getPort() + " error !", e);
}
started = false;
}
#location 11
#vulnerability type THREAD_SAFETY_VIOLATION
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
@Override
protected void decorateRequest(SofaRequest request) {
// 公共的设置
super.decorateRequest(request);
// 缓存是为了加快速度
request.setTargetServiceUniqueName(serviceName);
request.setSerializeType(serializeType == null ? 0 : serializeType);
if (!consumerConfig.isGeneric()) {
// 找到调用类型, generic的时候类型在filter里进行判断
request.setInvokeType(consumerConfig.getMethodInvokeType(request.getMethodName()));
}
RpcInvokeContext invokeCtx = RpcInvokeContext.peekContext();
RpcInternalContext internalContext = RpcInternalContext.getContext();
if (invokeCtx != null) {
// 如果用户设置了调用级别回调函数
SofaResponseCallback responseCallback = invokeCtx.getResponseCallback();
if (responseCallback != null) {
request.setSofaResponseCallback(responseCallback);
invokeCtx.setResponseCallback(null); // 一次性用完
invokeCtx.put(RemotingConstants.INVOKE_CTX_IS_ASYNC_CHAIN,
isSendableResponseCallback(responseCallback));
}
// 如果用户设置了调用级别超时时间
Integer timeout = invokeCtx.getTimeout();
if (timeout != null) {
request.setTimeout(timeout);
invokeCtx.setTimeout(null);// 一次性用完
}
// 如果用户指定了调用的URL
String targetURL = invokeCtx.getTargetURL();
if (targetURL != null) {
internalContext.setAttachment(HIDDEN_KEY_PINPOINT, targetURL);
invokeCtx.setTargetURL(null);// 一次性用完
}
// 如果用户指定了透传数据
if (RpcInvokeContext.isBaggageEnable()) {
// 需要透传
BaggageResolver.carryWithRequest(invokeCtx, request);
internalContext.setAttachment(HIDDEN_KEY_INVOKE_CONTEXT, invokeCtx);
}
}
if (RpcInternalContext.isAttachmentEnable()) {
internalContext.setAttachment(INTERNAL_KEY_APP_NAME, consumerConfig.getAppName());
internalContext.setAttachment(INTERNAL_KEY_PROTOCOL_NAME, consumerConfig.getProtocol());
}
// 额外属性通过HEAD传递给服务端
request.addRequestProp(RemotingConstants.HEAD_APP_NAME, consumerConfig.getAppName());
request.addRequestProp(RemotingConstants.HEAD_PROTOCOL, consumerConfig.getProtocol());
}
|
#vulnerable code
@Override
protected void decorateRequest(SofaRequest request) {
// 公共的设置
super.decorateRequest(request);
// 缓存是为了加快速度
request.setTargetServiceUniqueName(serviceName);
request.setSerializeType(serializeType);
if (!consumerConfig.isGeneric()) {
// 找到调用类型, generic的时候类型在filter里进行判断
request.setInvokeType(consumerConfig.getMethodInvokeType(request.getMethodName()));
}
RpcInvokeContext invokeCtx = RpcInvokeContext.peekContext();
RpcInternalContext internalContext = RpcInternalContext.getContext();
if (invokeCtx != null) {
// 如果用户设置了调用级别回调函数
SofaResponseCallback responseCallback = invokeCtx.getResponseCallback();
if (responseCallback != null) {
request.setSofaResponseCallback(responseCallback);
invokeCtx.setResponseCallback(null); // 一次性用完
invokeCtx.put(RemotingConstants.INVOKE_CTX_IS_ASYNC_CHAIN,
isSendableResponseCallback(responseCallback));
}
// 如果用户设置了调用级别超时时间
Integer timeout = invokeCtx.getTimeout();
if (timeout != null) {
request.setTimeout(timeout);
invokeCtx.setTimeout(null);// 一次性用完
}
// 如果用户指定了调用的URL
String targetURL = invokeCtx.getTargetURL();
if (targetURL != null) {
internalContext.setAttachment(HIDDEN_KEY_PINPOINT, targetURL);
invokeCtx.setTargetURL(null);// 一次性用完
}
// 如果用户指定了透传数据
if (RpcInvokeContext.isBaggageEnable()) {
// 需要透传
BaggageResolver.carryWithRequest(invokeCtx, request);
internalContext.setAttachment(HIDDEN_KEY_INVOKE_CONTEXT, invokeCtx);
}
}
if (RpcInternalContext.isAttachmentEnable()) {
internalContext.setAttachment(INTERNAL_KEY_APP_NAME, consumerConfig.getAppName());
internalContext.setAttachment(INTERNAL_KEY_PROTOCOL_NAME, consumerConfig.getProtocol());
}
// 额外属性通过HEAD传递给服务端
request.addRequestProp(RemotingConstants.HEAD_APP_NAME, consumerConfig.getAppName());
request.addRequestProp(RemotingConstants.HEAD_PROTOCOL, consumerConfig.getProtocol());
}
#location 8
#vulnerability type THREAD_SAFETY_VIOLATION
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
protected void checkProviderInfo(ProviderGroup providerGroup) {
List<ProviderInfo> providerInfos = providerGroup == null ? null : providerGroup.getProviderInfos();
if (CommonUtils.isEmpty(providerInfos)) {
return;
}
Iterator<ProviderInfo> iterator = providerInfos.iterator();
while (iterator.hasNext()) {
ProviderInfo providerInfo = iterator.next();
if (!StringUtils.equals(providerInfo.getProtocolType(), consumerConfig.getProtocol())) {
if (LOGGER.isWarnEnabled(consumerConfig.getAppName())) {
LOGGER.warnWithApp(consumerConfig.getAppName(),
"Unmatched protocol between consumer [{}] and provider [{}].",
consumerConfig.getProtocol(), providerInfo.getProtocolType());
}
}
}
}
|
#vulnerable code
protected void checkProviderInfo(ProviderGroup providerGroup) {
List<ProviderInfo> providerInfos = providerGroup == null ? null : providerGroup.getProviderInfos();
if (CommonUtils.isEmpty(providerInfos)) {
return;
}
Iterator<ProviderInfo> iterator = providerInfos.iterator();
while (iterator.hasNext()) {
ProviderInfo providerInfo = iterator.next();
if (!StringUtils.equals(providerInfo.getProtocolType(), consumerConfig.getProtocol())) {
if (LOGGER.isWarnEnabled(consumerConfig.getAppName())) {
LOGGER.warnWithApp(consumerConfig.getAppName(),
"Unmatched protocol between consumer [{}] and provider [{}].",
consumerConfig.getProtocol(), providerInfo.getProtocolType());
}
}
if (StringUtils.isEmpty(providerInfo.getSerializationType())) {
providerInfo.setSerializationType(consumerConfig.getSerialization());
}
}
}
#location 17
#vulnerability type THREAD_SAFETY_VIOLATION
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
@Test
public void testAll() throws Exception {
int timeoutPerSub = 1000;
ServerConfig serverConfig = new ServerConfig()
.setProtocol("bolt")
.setHost("0.0.0.0")
.setPort(12200);
ProviderConfig<?> provider = new ProviderConfig();
provider.setInterfaceId("com.alipay.xxx.TestService")
.setUniqueId("unique123Id")
.setApplication(new ApplicationConfig().setAppName("test-server"))
.setProxy("javassist")
.setRegister(true)
.setRegistry(registryConfig)
.setSerialization("hessian2")
.setServer(serverConfig)
.setWeight(222)
.setTimeout(3000);
// 注册
registry.register(provider);
ConsumerConfig<?> consumer = new ConsumerConfig();
consumer.setInterfaceId("com.alipay.xxx.TestService")
.setUniqueId("unique123Id")
.setApplication(new ApplicationConfig().setAppName("test-server"))
.setProxy("javassist")
.setSubscribe(true)
.setSerialization("java")
.setInvokeType("sync")
.setTimeout(4444);
String tag0 = MeshRegistryHelper.buildMeshKey(provider, serverConfig.getProtocol());
String tag1 = MeshRegistryHelper.buildMeshKey(consumer, consumer.getProtocol());
Assert.assertEquals(tag1, tag0);
// 订阅
MeshRegistryTest.MockProviderInfoListener providerInfoListener = new MeshRegistryTest.MockProviderInfoListener();
consumer.setProviderInfoListener(providerInfoListener);
List<ProviderGroup> groups = registry.subscribe(consumer);
Assert.assertNull(groups);
Thread.sleep(3000);
Map<String, ProviderGroup> ps = providerInfoListener.getData();
Assert.assertTrue(ps.size() == 1);
// 反注册
CountDownLatch latch = new CountDownLatch(1);
providerInfoListener.setCountDownLatch(latch);
registry.unRegister(provider);
latch.await(timeoutPerSub, TimeUnit.MILLISECONDS);
//mesh 并不直接感知.
Assert.assertTrue(ps.size() == 1);
// 一次发2个端口的再次注册
latch = new CountDownLatch(1);
providerInfoListener.setCountDownLatch(latch);
provider.getServer().add(new ServerConfig()
.setProtocol("bolt")
.setHost("0.0.0.0")
.setPort(12201));
registry.register(provider);
latch.await(timeoutPerSub * 2, TimeUnit.MILLISECONDS);
// 重复订阅
ConsumerConfig<?> consumer2 = new ConsumerConfig();
consumer2.setInterfaceId("com.alipay.xxx.TestService")
.setUniqueId("unique123Id")
.setApplication(new ApplicationConfig().setAppName("test-server"))
.setProxy("javassist")
.setSubscribe(true)
.setSerialization("java")
.setInvokeType("sync")
.setTimeout(4444);
CountDownLatch latch2 = new CountDownLatch(1);
MeshRegistryTest.MockProviderInfoListener providerInfoListener2 = new MeshRegistryTest.MockProviderInfoListener();
providerInfoListener2.setCountDownLatch(latch2);
consumer2.setProviderInfoListener(providerInfoListener2);
List<ProviderGroup> groups2 = registry.subscribe(consumer2);
Assert.assertNull(groups);
Thread.sleep(3000);
Map<String, ProviderGroup> ps2 = providerInfoListener2.getData();
Assert.assertTrue(ps2.size() == 1);
// 取消订阅者1
registry.unSubscribe(consumer);
// 批量反注册,判断订阅者2的数据
latch = new CountDownLatch(1);
providerInfoListener2.setCountDownLatch(latch);
List<ProviderConfig> providerConfigList = new ArrayList<ProviderConfig>();
providerConfigList.add(provider);
registry.batchUnRegister(providerConfigList);
latch.await(timeoutPerSub, TimeUnit.MILLISECONDS);
Assert.assertTrue(ps2.size() == 1);
// 批量取消订阅
List<ConsumerConfig> consumerConfigList = new ArrayList<ConsumerConfig>();
consumerConfigList.add(consumer2);
registry.batchUnSubscribe(consumerConfigList);
}
|
#vulnerable code
@Test
public void testAll() throws Exception {
int timeoutPerSub = 1000;
ServerConfig serverConfig = new ServerConfig()
.setProtocol("bolt")
.setHost("0.0.0.0")
.setPort(12200);
ProviderConfig<?> provider = new ProviderConfig();
provider.setInterfaceId("com.alipay.xxx.TestService")
.setUniqueId("unique123Id")
.setApplication(new ApplicationConfig().setAppName("test-server"))
.setProxy("javassist")
.setRegister(true)
.setRegistry(registryConfig)
.setSerialization("hessian2")
.setServer(serverConfig)
.setWeight(222)
.setTimeout(3000);
// 注册
registry.register(provider);
ConsumerConfig<?> consumer = new ConsumerConfig();
consumer.setInterfaceId("com.alipay.xxx.TestService")
.setUniqueId("unique123Id")
.setApplication(new ApplicationConfig().setAppName("test-server"))
.setProxy("javassist")
.setSubscribe(true)
.setSerialization("java")
.setInvokeType("sync")
.setTimeout(4444);
String tag0 = MeshRegistryHelper.buildMeshKey(provider, serverConfig.getProtocol());
String tag1 = MeshRegistryHelper.buildMeshKey(consumer, consumer.getProtocol());
Assert.assertEquals(tag1, tag0);
// 订阅
MeshRegistryTest.MockProviderInfoListener providerInfoListener = new MeshRegistryTest.MockProviderInfoListener();
consumer.setProviderInfoListener(providerInfoListener);
List<ProviderGroup> groups = registry.subscribe(consumer);
providerInfoListener.updateAllProviders(groups);
Map<String, ProviderGroup> ps = providerInfoListener.getData();
Assert.assertTrue(ps.size() == 1);
// 反注册
CountDownLatch latch = new CountDownLatch(1);
providerInfoListener.setCountDownLatch(latch);
registry.unRegister(provider);
latch.await(timeoutPerSub, TimeUnit.MILLISECONDS);
//mesh 并不直接感知.
Assert.assertTrue(ps.size() == 1);
// 一次发2个端口的再次注册
latch = new CountDownLatch(1);
providerInfoListener.setCountDownLatch(latch);
provider.getServer().add(new ServerConfig()
.setProtocol("bolt")
.setHost("0.0.0.0")
.setPort(12201));
registry.register(provider);
latch.await(timeoutPerSub * 2, TimeUnit.MILLISECONDS);
// 重复订阅
ConsumerConfig<?> consumer2 = new ConsumerConfig();
consumer2.setInterfaceId("com.alipay.xxx.TestService")
.setUniqueId("unique123Id")
.setApplication(new ApplicationConfig().setAppName("test-server"))
.setProxy("javassist")
.setSubscribe(true)
.setSerialization("java")
.setInvokeType("sync")
.setTimeout(4444);
CountDownLatch latch2 = new CountDownLatch(1);
MeshRegistryTest.MockProviderInfoListener providerInfoListener2 = new MeshRegistryTest.MockProviderInfoListener();
providerInfoListener2.setCountDownLatch(latch2);
consumer2.setProviderInfoListener(providerInfoListener2);
List<ProviderGroup> groups2 = registry.subscribe(consumer2);
providerInfoListener2.updateAllProviders(groups2);
Map<String, ProviderGroup> ps2 = providerInfoListener2.getData();
Assert.assertTrue(ps2.size() == 1);
// 取消订阅者1
registry.unSubscribe(consumer);
// 批量反注册,判断订阅者2的数据
latch = new CountDownLatch(1);
providerInfoListener2.setCountDownLatch(latch);
List<ProviderConfig> providerConfigList = new ArrayList<ProviderConfig>();
providerConfigList.add(provider);
registry.batchUnRegister(providerConfigList);
latch.await(timeoutPerSub, TimeUnit.MILLISECONDS);
Assert.assertTrue(ps2.size() == 1);
// 批量取消订阅
List<ConsumerConfig> consumerConfigList = new ArrayList<ConsumerConfig>();
consumerConfigList.add(consumer2);
registry.batchUnSubscribe(consumerConfigList);
}
#location 44
#vulnerability type NULL_DEREFERENCE
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
@Override
public void destroy() {
stop();
httpServer = null;
}
|
#vulnerable code
@Override
public void destroy() {
stop();
}
#location 3
#vulnerability type THREAD_SAFETY_VIOLATION
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
@Override
protected Object getFallback() {
events.add(SofaAsyncHystrixEvent.FALLBACK_EMIT);
if (lock.getCount() > 0) {
// > 0 说明 run 方法没有执行,或是执行时立刻失败了
this.sofaResponse = buildEmptyResponse(request);
lock.countDown();
events.add(SofaAsyncHystrixEvent.FALLBACK_UNLOCKED);
}
FallbackFactory fallbackFactory = SofaHystrixConfig.loadFallbackFactory((ConsumerConfig) invoker.getConfig());
if (fallbackFactory == null) {
return super.getFallback();
}
Object fallback = fallbackFactory.create(new FallbackContext(invoker, request, this.sofaResponse, this
.getExecutionException()));
if (fallback == null) {
return super.getFallback();
}
try {
return request.getMethod().invoke(fallback, request.getMethodArgs());
} catch (IllegalAccessException e) {
throw new SofaRpcRuntimeException("Hystrix fallback method failed to execute.", e);
} catch (InvocationTargetException e) {
throw new SofaRpcRuntimeException("Hystrix fallback method failed to execute.",
e.getTargetException());
} finally {
events.add(SofaAsyncHystrixEvent.FALLBACK_SUCCESS);
}
}
|
#vulnerable code
@Override
protected Object getFallback() {
events.add(SofaAsyncHystrixEvent.FALLBACK_EMIT);
if (lock.getCount() > 0) {
// > 0 说明 run 方法没有执行,或是执行时立刻失败了
this.sofaResponse = buildEmptyResponse(request);
lock.countDown();
events.add(SofaAsyncHystrixEvent.FALLBACK_UNLOCKED);
}
FallbackFactory fallbackFactory = SofaHystrixConfig.loadFallbackFactory((ConsumerConfig) invoker.getConfig());
if (fallbackFactory == null) {
return super.getFallback();
}
Object fallback = fallbackFactory.create(null, this.getExecutionException());
if (fallback == null) {
return super.getFallback();
}
try {
return request.getMethod().invoke(fallback, request.getMethodArgs());
} catch (IllegalAccessException e) {
throw new SofaRpcRuntimeException("Hystrix fallback method failed to execute.", e);
} catch (InvocationTargetException e) {
throw new SofaRpcRuntimeException("Hystrix fallback method failed to execute.",
e.getTargetException());
} finally {
events.add(SofaAsyncHystrixEvent.FALLBACK_SUCCESS);
}
}
#location 19
#vulnerability type NULL_DEREFERENCE
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
@Override
public void stop() {
if (!started) {
return;
}
try {
// 关闭端口,不关闭线程池
if (LOGGER.isInfoEnabled()) {
LOGGER.info("Stop the http rest server at port {}", serverConfig.getPort());
}
httpServer.stop();
} catch (Exception e) {
LOGGER.error("Stop the http rest server at port " + serverConfig.getPort() + " error !", e);
}
started = false;
}
|
#vulnerable code
@Override
public void stop() {
if (!started) {
return;
}
try {
// 关闭端口,不关闭线程池
if (LOGGER.isInfoEnabled()) {
LOGGER.info("Stop the http rest server at port {}", serverConfig.getPort());
}
httpServer.stop();
httpServer = null;
} catch (Exception e) {
LOGGER.error("Stop the http rest server at port " + serverConfig.getPort() + " error !", e);
}
started = false;
}
#location 12
#vulnerability type THREAD_SAFETY_VIOLATION
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
@Override
public List<ProviderGroup> subscribe(final ConsumerConfig config) {
String appName = config.getAppName();
if (!registryConfig.isSubscribe()) {
// 注册中心不订阅
if (LOGGER.isInfoEnabled(appName)) {
LOGGER.infoWithApp(appName, LogCodes.getLog(LogCodes.INFO_REGISTRY_IGNORE));
}
return null;
}
// 注册Consumer节点
if (config.isRegister()) {
try {
String consumerPath = buildConsumerPath(rootPath, config);
String url = ZookeeperRegistryHelper.convertConsumerToUrl(config);
String encodeUrl = URLEncoder.encode(url, "UTF-8");
getAndCheckZkClient().create().creatingParentContainersIfNeeded()
.withMode(CreateMode.EPHEMERAL) // Consumer临时节点
.forPath(consumerPath + CONTEXT_SEP + encodeUrl);
consumerUrls.put(config, url);
} catch (Exception e) {
throw new SofaRpcRuntimeException("Failed to register consumer to zookeeperRegistry!", e);
}
}
if (config.isSubscribe()) {
// 订阅配置
if (!INTERFACE_CONFIG_CACHE.containsKey(buildConfigPath(rootPath, config))) {
//订阅接口级配置
subscribeConfig(config, config.getConfigListener());
}
if (!INTERFACE_OVERRIDE_CACHE.containsKey(buildOverridePath(rootPath, config))) {
//订阅IP级配置
subscribeOverride(config, config.getConfigListener());
}
// 订阅Providers节点
try {
if (providerObserver == null) { // 初始化
providerObserver = new ZookeeperProviderObserver();
}
final String providerPath = buildProviderPath(rootPath, config);
if (LOGGER.isInfoEnabled(appName)) {
LOGGER.infoWithApp(appName, LogCodes.getLog(LogCodes.INFO_ROUTE_REGISTRY_SUB, providerPath));
}
PathChildrenCache pathChildrenCache = INTERFACE_PROVIDER_CACHE.get(config);
if (pathChildrenCache == null) {
// 监听配置节点下 子节点增加、子节点删除、子节点Data修改事件
ProviderInfoListener providerInfoListener = config.getProviderInfoListener();
providerObserver.addProviderListener(config, providerInfoListener);
// TODO 换成监听父节点变化(只是监听变化了,而不通知变化了什么,然后客户端自己来拉数据的)
pathChildrenCache = new PathChildrenCache(zkClient, providerPath, true);
final PathChildrenCache finalPathChildrenCache = pathChildrenCache;
pathChildrenCache.getListenable().addListener(new PathChildrenCacheListener() {
@Override
public void childEvent(CuratorFramework client1, PathChildrenCacheEvent event) throws Exception {
if (LOGGER.isDebugEnabled(config.getAppName())) {
LOGGER.debugWithApp(config.getAppName(),
"Receive zookeeper event: " + "type=[" + event.getType() + "]");
}
switch (event.getType()) {
case CHILD_ADDED: //加了一个provider
providerObserver.addProvider(config, providerPath, event.getData(),
finalPathChildrenCache.getCurrentData());
break;
case CHILD_REMOVED: //删了一个provider
providerObserver.removeProvider(config, providerPath, event.getData(),
finalPathChildrenCache.getCurrentData());
break;
case CHILD_UPDATED: // 更新一个Provider
providerObserver.updateProvider(config, providerPath, event.getData(),
finalPathChildrenCache.getCurrentData());
break;
default:
break;
}
}
});
pathChildrenCache.start(PathChildrenCache.StartMode.BUILD_INITIAL_CACHE);
INTERFACE_PROVIDER_CACHE.put(config, pathChildrenCache);
}
List<ProviderInfo> providerInfos = ZookeeperRegistryHelper.convertUrlsToProviders(
providerPath, pathChildrenCache.getCurrentData());
List<ProviderInfo> matchProviders = ZookeeperRegistryHelper.matchProviderInfos(config, providerInfos);
return Collections.singletonList(new ProviderGroup().addAll(matchProviders));
} catch (Exception e) {
throw new SofaRpcRuntimeException("Failed to subscribe provider from zookeeperRegistry!", e);
}
}
return null;
}
|
#vulnerable code
@Override
public List<ProviderGroup> subscribe(final ConsumerConfig config) {
String appName = config.getAppName();
if (!registryConfig.isSubscribe()) {
// 注册中心不订阅
if (LOGGER.isInfoEnabled(appName)) {
LOGGER.infoWithApp(appName, LogCodes.getLog(LogCodes.INFO_REGISTRY_IGNORE));
}
return null;
}
// 注册Consumer节点
if (config.isRegister()) {
try {
String consumerPath = buildConsumerPath(rootPath, config);
String url = ZookeeperRegistryHelper.convertConsumerToUrl(config);
String encodeUrl = URLEncoder.encode(url, "UTF-8");
getAndCheckZkClient().create().creatingParentContainersIfNeeded()
.withMode(CreateMode.EPHEMERAL) // Consumer临时节点
.forPath(consumerPath + CONTEXT_SEP + encodeUrl);
consumerUrls.put(config, url);
} catch (Exception e) {
throw new SofaRpcRuntimeException("Failed to register consumer to zookeeperRegistry!", e);
}
}
if (config.isSubscribe()) {
// 订阅配置
if (!INTERFACE_CONFIG_CACHE.containsKey(buildConfigPath(rootPath, config))) {
//订阅接口级配置
subscribeConfig(config, config.getConfigListener());
}
if (!INTERFACE_OVERRIDE_CACHE.containsKey(buildOverridePath(rootPath, config))) {
//订阅IP级配置
subscribeOverride(config, config.getConfigListener());
}
// 订阅Providers节点
try {
if (providerObserver == null) { // 初始化
providerObserver = new ZookeeperProviderObserver();
}
final String providerPath = buildProviderPath(rootPath, config);
if (LOGGER.isInfoEnabled(appName)) {
LOGGER.infoWithApp(appName, LogCodes.getLog(LogCodes.INFO_ROUTE_REGISTRY_SUB, providerPath));
}
// 监听配置节点下 子节点增加、子节点删除、子节点Data修改事件
ProviderInfoListener providerInfoListener = config.getProviderInfoListener();
providerObserver.addProviderListener(config, providerInfoListener);
// TODO 换成监听父节点变化(只是监听变化了,而不通知变化了什么,然后客户端自己来拉数据的)
PathChildrenCache pathChildrenCache = new PathChildrenCache(zkClient, providerPath, true);
pathChildrenCache.getListenable().addListener(new PathChildrenCacheListener() {
@Override
public void childEvent(CuratorFramework client1, PathChildrenCacheEvent event) throws Exception {
if (LOGGER.isDebugEnabled(config.getAppName())) {
LOGGER.debugWithApp(config.getAppName(),
"Receive zookeeper event: " + "type=[" + event.getType() + "]");
}
switch (event.getType()) {
case CHILD_ADDED: //加了一个provider
providerObserver.addProvider(config, providerPath, event.getData());
break;
case CHILD_REMOVED: //删了一个provider
providerObserver.removeProvider(config, providerPath, event.getData());
break;
case CHILD_UPDATED: // 更新一个Provider
providerObserver.updateProvider(config, providerPath, event.getData());
break;
default:
break;
}
}
});
pathChildrenCache.start(PathChildrenCache.StartMode.BUILD_INITIAL_CACHE);
List<ProviderInfo> providerInfos = ZookeeperRegistryHelper.convertUrlsToProviders(
providerPath, pathChildrenCache.getCurrentData());
List<ProviderInfo> matchProviders = ZookeeperRegistryHelper.matchProviderInfos(config, providerInfos);
return Collections.singletonList(new ProviderGroup().addAll(matchProviders));
} catch (Exception e) {
throw new SofaRpcRuntimeException("Failed to subscribe provider from zookeeperRegistry!", e);
}
}
return null;
}
#location 74
#vulnerability type RESOURCE_LEAK
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
@Override
public void updateProviders(ProviderGroup providerGroup) {
checkProviderInfo(providerGroup);
ProviderGroup oldProviderGroup = addressHolder.getProviderGroup(providerGroup.getName());
if (ProviderHelper.isEmpty(providerGroup)) {
addressHolder.updateProviders(providerGroup);
if (!ProviderHelper.isEmpty(oldProviderGroup)) {
if (LOGGER.isWarnEnabled(consumerConfig.getAppName())) {
LOGGER.warnWithApp(consumerConfig.getAppName(), "Provider list is emptied, may be all " +
"providers has been closed, or this consumer has been add to blacklist");
closeTransports();
}
}
} else {
addressHolder.updateProviders(providerGroup);
connectionHolder.updateProviders(providerGroup);
}
if (EventBus.isEnable(ProviderInfoUpdateEvent.class)) {
ProviderInfoUpdateEvent event = new ProviderInfoUpdateEvent(consumerConfig, oldProviderGroup, providerGroup);
EventBus.post(event);
}
}
|
#vulnerable code
@Override
public void updateProviders(ProviderGroup providerGroup) {
checkProviderInfo(providerGroup);
ProviderGroup oldProviderGroup = addressHolder.getProviderGroup(providerGroup.getName());
if (ProviderHelper.isEmpty(providerGroup)) {
addressHolder.updateProviders(providerGroup);
if (CommonUtils.isNotEmpty(oldProviderGroup.getProviderInfos())) {
if (LOGGER.isWarnEnabled(consumerConfig.getAppName())) {
LOGGER.warnWithApp(consumerConfig.getAppName(), "Provider list is emptied, may be all " +
"providers has been closed, or this consumer has been add to blacklist");
closeTransports();
}
}
} else {
addressHolder.updateProviders(providerGroup);
connectionHolder.updateProviders(providerGroup);
}
if (EventBus.isEnable(ProviderInfoUpdateEvent.class)) {
ProviderInfoUpdateEvent event = new ProviderInfoUpdateEvent(consumerConfig, oldProviderGroup, providerGroup);
EventBus.post(event);
}
}
#location 3
#vulnerability type THREAD_SAFETY_VIOLATION
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
@Override
protected void process(ComplexEventChunk<StreamEvent> streamEventChunk, Processor nextProcessor,
StreamEventCloner streamEventCloner, ComplexEventPopulater complexEventPopulater) {
ComplexEventChunk<StreamEvent> complexEventChunk = new ComplexEventChunk<StreamEvent>(false);
lock.lock();
try {
while (streamEventChunk.hasNext()) {
StreamEvent event = streamEventChunk.next();
if(event.getType() != ComplexEvent.Type.TIMER) {
streamEventChunk.remove(); //We might have the rest of the events linked to this event forming a chain.
long timestamp = (Long) timestampExecutor.execute(event);
if (expireFlag) {
if (timestamp < lastSentTimeStamp) {
continue;
}
}
ArrayList<StreamEvent> eventList = eventTreeMap.get(timestamp);
if (eventList == null) {
eventList = new ArrayList<StreamEvent>();
}
eventList.add(event);
eventTreeMap.put(timestamp, eventList);
if (timestamp > greatestTimestamp) {
greatestTimestamp = timestamp;
long minTimestamp = eventTreeMap.firstKey();
long timeDifference = greatestTimestamp - minTimestamp;
if (timeDifference > k) {
if (timeDifference < MAX_K) {
k = timeDifference;
} else {
k = MAX_K;
}
}
Iterator<Map.Entry<Long, ArrayList<StreamEvent>>> entryIterator = eventTreeMap.entrySet().iterator();
while (entryIterator.hasNext()) {
Map.Entry<Long, ArrayList<StreamEvent>> entry = entryIterator.next();
ArrayList<StreamEvent> list = expiredEventTreeMap.get(entry.getKey());
if (list != null) {
list.addAll(entry.getValue());
} else {
expiredEventTreeMap.put(entry.getKey(), entry.getValue());
}
}
eventTreeMap = new TreeMap<Long, ArrayList<StreamEvent>>();
entryIterator = expiredEventTreeMap.entrySet().iterator();
while (entryIterator.hasNext()) {
Map.Entry<Long, ArrayList<StreamEvent>> entry = entryIterator.next();
if (entry.getKey() + k <= greatestTimestamp) {
entryIterator.remove();
ArrayList<StreamEvent> timeEventList = entry.getValue();
lastSentTimeStamp = entry.getKey();
for (StreamEvent aTimeEventList : timeEventList) {
complexEventChunk.add(aTimeEventList);
}
}
}
}
} else {
if(expiredEventTreeMap.size() > 0) {
TreeMap<Long, ArrayList<StreamEvent>> expiredEventTreeMapSnapShot = expiredEventTreeMap;
expiredEventTreeMap = new TreeMap<Long, ArrayList<StreamEvent>>();
onTimerEvent(expiredEventTreeMapSnapShot, nextProcessor);
lastScheduledTimestamp = lastScheduledTimestamp + TIMER_DURATION;
scheduler.notifyAt(lastScheduledTimestamp);
}
}
}
} catch (ArrayIndexOutOfBoundsException ec) {
//This happens due to user specifying an invalid field index.
throw new ExecutionPlanCreationException("The very first parameter must be an Integer with a valid " +
" field index (0 to (fieldsLength-1)).");
}
lock.unlock();
nextProcessor.process(complexEventChunk);
}
|
#vulnerable code
@Override
protected void process(ComplexEventChunk<StreamEvent> streamEventChunk, Processor nextProcessor,
StreamEventCloner streamEventCloner, ComplexEventPopulater complexEventPopulater) {
ComplexEventChunk<StreamEvent> complexEventChunk = new ComplexEventChunk<StreamEvent>(false);
try {
while (streamEventChunk.hasNext()) {
StreamEvent event = streamEventChunk.next();
if(event.getType() != ComplexEvent.Type.TIMER) {
streamEventChunk.remove(); //We might have the rest of the events linked to this event forming a chain.
long timestamp = (Long) timestampExecutor.execute(event);
if (expireFlag) {
if (timestamp < lastSentTimeStamp) {
continue;
}
}
ArrayList<StreamEvent> eventList = eventTreeMap.get(timestamp);
if (eventList == null) {
eventList = new ArrayList<StreamEvent>();
}
eventList.add(event);
eventTreeMap.put(timestamp, eventList);
if (timestamp > greatestTimestamp) {
greatestTimestamp = timestamp;
long minTimestamp = eventTreeMap.firstKey();
if ((greatestTimestamp - minTimestamp) > k) {
if ((greatestTimestamp - minTimestamp) < MAX_K) {
k = greatestTimestamp - minTimestamp;
} else {
k = MAX_K;
}
}
lock.lock();
Iterator<Map.Entry<Long, ArrayList<StreamEvent>>> entryIterator = eventTreeMap.entrySet().iterator();
while (entryIterator.hasNext()) {
Map.Entry<Long, ArrayList<StreamEvent>> entry = entryIterator.next();
ArrayList<StreamEvent> list = expiredEventTreeMap.get(entry.getKey());
if (list != null) {
list.addAll(entry.getValue());
} else {
expiredEventTreeMap.put(entry.getKey(), entry.getValue());
}
}
eventTreeMap = new TreeMap<Long, ArrayList<StreamEvent>>();
entryIterator = expiredEventTreeMap.entrySet().iterator();
while (entryIterator.hasNext()) {
Map.Entry<Long, ArrayList<StreamEvent>> entry = entryIterator.next();
if (entry.getKey() + k <= greatestTimestamp) {
entryIterator.remove();
ArrayList<StreamEvent> timeEventList = entry.getValue();
lastSentTimeStamp = entry.getKey();
for (StreamEvent aTimeEventList : timeEventList) {
complexEventChunk.add(aTimeEventList);
}
}
}
lock.unlock();
}
} else {
onTimerEvent(expiredEventTreeMap, nextProcessor);
lastScheduledTimestamp = lastScheduledTimestamp + TIMER_DURATION;
scheduler.notifyAt(lastScheduledTimestamp);
}
}
} catch (ArrayIndexOutOfBoundsException ec) {
// This happens due to user specifying an invalid field index.
throw new ExecutionPlanCreationException("The very first parameter must be an Integer with a valid " +
" field index (0 to (fieldsLength-1)).");
}
nextProcessor.process(complexEventChunk);
}
#location 35
#vulnerability type THREAD_SAFETY_VIOLATION
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
public static QueryRuntime parse(Query query, ExecutionPlanContext executionPlanContext,
Map<String, AbstractDefinition> streamDefinitionMap,
Map<String, AbstractDefinition> tableDefinitionMap,
Map<String, EventTable> eventTableMap) {
List<VariableExpressionExecutor> executors = new ArrayList<VariableExpressionExecutor>();
QueryRuntime queryRuntime;
Element element = null;
LatencyTracker latencyTracker = null;
try {
element = AnnotationHelper.getAnnotationElement("info", "name", query.getAnnotations());
if (executionPlanContext.getStatisticsManager() != null) {
if (element != null) {
String metricName =
executionPlanContext.getSiddhiContext().getStatisticsConfiguration().getMatricPrefix() +
SiddhiConstants.METRIC_DELIMITER + SiddhiConstants.METRIC_INFIX_EXECUTION_PLANS +
SiddhiConstants.METRIC_DELIMITER + executionPlanContext.getName() +
SiddhiConstants.METRIC_DELIMITER + SiddhiConstants.METRIC_INFIX_SIDDHI +
SiddhiConstants.METRIC_DELIMITER + SiddhiConstants.METRIC_INFIX_QUERIES +
SiddhiConstants.METRIC_DELIMITER + element.getValue();
latencyTracker = executionPlanContext.getSiddhiContext()
.getStatisticsConfiguration()
.getFactory()
.createLatencyTracker(metricName, executionPlanContext.getStatisticsManager());
}
}
StreamRuntime streamRuntime = InputStreamParser.parse(query.getInputStream(),
executionPlanContext, streamDefinitionMap, tableDefinitionMap, eventTableMap, executors, latencyTracker);
QuerySelector selector = SelectorParser.parse(query.getSelector(), query.getOutputStream(),
executionPlanContext, streamRuntime.getMetaComplexEvent(), eventTableMap, executors);
boolean isWindow = query.getInputStream() instanceof JoinInputStream;
if (!isWindow && query.getInputStream() instanceof SingleInputStream) {
for (StreamHandler streamHandler : ((SingleInputStream) query.getInputStream()).getStreamHandlers()) {
if (streamHandler instanceof Window) {
isWindow = true;
break;
}
}
}
OutputRateLimiter outputRateLimiter = OutputParser.constructOutputRateLimiter(query.getOutputStream().getId(),
query.getOutputRate(), query.getSelector().getGroupByList().size() != 0, isWindow,
executionPlanContext.getScheduledExecutorService());
if (outputRateLimiter != null) {
outputRateLimiter.init(executionPlanContext, latencyTracker);
}
executionPlanContext.addEternalReferencedHolder(outputRateLimiter);
OutputCallback outputCallback = OutputParser.constructOutputCallback(query.getOutputStream(),
streamRuntime.getMetaComplexEvent().getOutputStreamDefinition(), eventTableMap, executionPlanContext);
QueryParserHelper.reduceMetaComplexEvent(streamRuntime.getMetaComplexEvent());
QueryParserHelper.updateVariablePosition(streamRuntime.getMetaComplexEvent(), executors);
QueryParserHelper.initStreamRuntime(streamRuntime, streamRuntime.getMetaComplexEvent());
selector.setEventPopulator(StateEventPopulatorFactory.constructEventPopulator(streamRuntime.getMetaComplexEvent()));
queryRuntime = new QueryRuntime(query, executionPlanContext, streamRuntime, selector, outputRateLimiter,
outputCallback, streamRuntime.getMetaComplexEvent());
if (outputRateLimiter instanceof WrappedSnapshotOutputRateLimiter) {
((WrappedSnapshotOutputRateLimiter) outputRateLimiter)
.init(streamRuntime.getMetaComplexEvent().getOutputStreamDefinition().getAttributeList().size(),
selector.getAttributeProcessorList(), streamRuntime.getMetaComplexEvent());
}
} catch (DuplicateDefinitionException e) {
if (element != null) {
throw new DuplicateDefinitionException(e.getMessage() + ", when creating query " + element.getValue(), e);
} else {
throw new DuplicateDefinitionException(e.getMessage(), e);
}
} catch (RuntimeException e) {
if (element != null) {
throw new ExecutionPlanCreationException(e.getMessage() + ", when creating query " + element.getValue(), e);
} else {
throw new ExecutionPlanCreationException(e.getMessage(), e);
}
}
return queryRuntime;
}
|
#vulnerable code
public static QueryRuntime parse(Query query, ExecutionPlanContext executionPlanContext,
Map<String, AbstractDefinition> streamDefinitionMap,
Map<String, AbstractDefinition> tableDefinitionMap,
Map<String, EventTable> eventTableMap) {
List<VariableExpressionExecutor> executors = new ArrayList<VariableExpressionExecutor>();
QueryRuntime queryRuntime;
Element element = null;
LatencyTracker latencyTracker = null;
try {
element = AnnotationHelper.getAnnotationElement("info", "name", query.getAnnotations());
if (executionPlanContext.getStatisticsManager()!=null) {
if (element != null) {
String metricName = executionPlanContext.getSiddhiContext().getStatisticsConfiguration().getMatricPrefix() + ".executionplan." + executionPlanContext.getName() + "." + element.getValue();
latencyTracker = executionPlanContext.getSiddhiContext()
.getStatisticsConfiguration()
.getFactory()
.createLatencyTracker(metricName, executionPlanContext.getStatisticsManager());
}
}
StreamRuntime streamRuntime = InputStreamParser.parse(query.getInputStream(),
executionPlanContext, streamDefinitionMap, tableDefinitionMap, eventTableMap, executors, latencyTracker);
QuerySelector selector = SelectorParser.parse(query.getSelector(), query.getOutputStream(),
executionPlanContext, streamRuntime.getMetaComplexEvent(), eventTableMap, executors);
boolean isWindow = query.getInputStream() instanceof JoinInputStream;
if (!isWindow && query.getInputStream() instanceof SingleInputStream) {
for (StreamHandler streamHandler : ((SingleInputStream) query.getInputStream()).getStreamHandlers()) {
if (streamHandler instanceof Window) {
isWindow = true;
break;
}
}
}
OutputRateLimiter outputRateLimiter = OutputParser.constructOutputRateLimiter(query.getOutputStream().getId(),
query.getOutputRate(), query.getSelector().getGroupByList().size() != 0, isWindow, executionPlanContext.getScheduledExecutorService());
outputRateLimiter.init(executionPlanContext, latencyTracker);
executionPlanContext.addEternalReferencedHolder(outputRateLimiter);
OutputCallback outputCallback = OutputParser.constructOutputCallback(query.getOutputStream(),
streamRuntime.getMetaComplexEvent().getOutputStreamDefinition(), eventTableMap, executionPlanContext);
QueryParserHelper.reduceMetaComplexEvent(streamRuntime.getMetaComplexEvent());
QueryParserHelper.updateVariablePosition(streamRuntime.getMetaComplexEvent(), executors);
QueryParserHelper.initStreamRuntime(streamRuntime, streamRuntime.getMetaComplexEvent());
selector.setEventPopulator(StateEventPopulatorFactory.constructEventPopulator(streamRuntime.getMetaComplexEvent()));
queryRuntime = new QueryRuntime(query, executionPlanContext, streamRuntime, selector, outputRateLimiter, outputCallback, streamRuntime.getMetaComplexEvent());
if (outputRateLimiter instanceof WrappedSnapshotOutputRateLimiter) {
((WrappedSnapshotOutputRateLimiter) outputRateLimiter).init(streamRuntime.getMetaComplexEvent().getOutputStreamDefinition().getAttributeList().size(), selector.getAttributeProcessorList(), streamRuntime.getMetaComplexEvent());
}
} catch (DuplicateDefinitionException e) {
if (element != null) {
throw new DuplicateDefinitionException(e.getMessage() + ", when creating query " + element.getValue(), e);
} else {
throw new DuplicateDefinitionException(e.getMessage(), e);
}
} catch (RuntimeException e) {
if (element != null) {
throw new ExecutionPlanCreationException(e.getMessage() + ", when creating query " + element.getValue(), e);
} else {
throw new ExecutionPlanCreationException(e.getMessage(), e);
}
}
return queryRuntime;
}
#location 39
#vulnerability type NULL_DEREFERENCE
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
@Test
public void testCreatingHttpSubscriptionXmlMapping() {
Subscription subscription = Subscription.Subscribe(
Transport.transport("http").
option("context", "/test").
option("transport", "http,https"));
subscription.map(Mapping.format("xml").
map("/h:time").
map("data", "//h:data").
option("xmlns:h", "http://www.w3.org/TR/html4/"));
subscription.insertInto("FooStream");
ExecutionPlan.executionPlan("test").addSubscription(subscription);
}
|
#vulnerable code
@Test
public void testCreatingHttpSubscriptionXmlMapping() {
Subscription subscription = Subscription.Subscribe(
Transport.transport("http").
option("context", "/test").
option("transport", "http,https"));
subscription.map(Mapper.mapper("xml").
map("/h:time").
map("data", "//h:data").
option("xmlns:h", "http://www.w3.org/TR/html4/"));
subscription.insertInto("FooStream");
ExecutionPlan.executionPlan("test").addSubscription(subscription);
}
#location 10
#vulnerability type NULL_DEREFERENCE
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
public static OutputCallback constructOutputCallback(OutputStream outStream, StreamDefinition outputStreamDefinition,
ExecutionPlanContext executionPlanContext) {
String id = outStream.getId();
//Construct CallBack
if (outStream instanceof InsertIntoStream) {
EventTable eventTable = executionPlanContext.getEventTableMap().get(id);
if (eventTable != null) {
DefinitionParserHelper.validateOutputStream(outputStreamDefinition, eventTable.getTableDefinition());
return new InsertIntoTableCallback(eventTable, outputStreamDefinition);
} else {
return new InsertIntoStreamCallback(outputStreamDefinition);
}
} else if (outStream instanceof DeleteStream || outStream instanceof UpdateStream) {
EventTable eventTable = executionPlanContext.getEventTableMap().get(id);
if (eventTable != null) {
TableDefinition eventTableDefinition = eventTable.getTableDefinition();
for (Attribute attribute : outputStreamDefinition.getAttributeList()) {
if (!eventTableDefinition.getAttributeList().contains(attribute)) {
throw new ExecutionPlanCreationException("Attribute " + attribute + " does not exist on Event Table " + eventTableDefinition);
}
}
MetaStreamEvent matchingMetaStreamEvent = new MetaStreamEvent();
matchingMetaStreamEvent.setTableEvent(true);
TableDefinition matchingTableDefinition = TableDefinition.id("");
for (Attribute attribute : outputStreamDefinition.getAttributeList()) {
matchingMetaStreamEvent.addOutputData(attribute);
matchingTableDefinition.attribute(attribute.getName(), attribute.getType());
}
matchingMetaStreamEvent.setInputDefinition(matchingTableDefinition);
if (outStream instanceof DeleteStream) {
Finder finder = eventTable.constructFinder(((DeleteStream) outStream).getOnDeleteExpression(), matchingMetaStreamEvent, executionPlanContext, null, 0);
return new DeleteTableCallback(eventTable, finder);
} else {
Finder finder = eventTable.constructFinder(((UpdateStream) outStream).getOnUpdateExpression(), matchingMetaStreamEvent, executionPlanContext, null, 0);
return new UpdateTableCallback(eventTable, finder, matchingTableDefinition);
}
} else {
throw new DefinitionNotExistException("Event table with id :" + id + " does not exist");
}
} else {
throw new ExecutionPlanCreationException(outStream.getClass().getName() + " not supported");
}
}
|
#vulnerable code
public static OutputCallback constructOutputCallback(OutputStream outStream, StreamDefinition outputStreamDefinition,
ExecutionPlanContext executionPlanContext) {
String id = outStream.getId();
//Construct CallBack
if (outStream instanceof InsertIntoStream) {
EventTable eventTable = executionPlanContext.getEventTableMap().get(id);
if (eventTable != null) {
DefinitionParserHelper.validateOutputStream(outputStreamDefinition, eventTable.getTableDefinition());
return new InsertIntoTableCallback(eventTable, outputStreamDefinition);
} else {
return new InsertIntoStreamCallback(outputStreamDefinition);
}
} else if (outStream instanceof DeleteStream) {
EventTable eventTable = executionPlanContext.getEventTableMap().get(id);
if (eventTable != null) {
DefinitionParserHelper.validateOutputStream(outputStreamDefinition, eventTable.getTableDefinition());
MetaStreamEvent matchingMetaStreamEvent = new MetaStreamEvent();
matchingMetaStreamEvent.setTableEvent(true);
TableDefinition tableDefinition = TableDefinition.id("");
for (Attribute attribute : outputStreamDefinition.getAttributeList()) {
matchingMetaStreamEvent.addOutputData(attribute);
tableDefinition.attribute(attribute.getName(), attribute.getType());
}
matchingMetaStreamEvent.setInputDefinition(tableDefinition);
Finder finder = eventTable.constructFinder(((DeleteStream) outStream).getOnDeleteExpression(), matchingMetaStreamEvent, executionPlanContext, null, 0);
return new DeleteTableCallback(eventTable, finder);
} else {
throw new DefinitionNotExistException("Event table with id :" + id + " does not exist");
}
} else if (outStream instanceof UpdateStream) {
EventTable eventTable = executionPlanContext.getEventTableMap().get(id);
if (eventTable != null) {
DefinitionParserHelper.validateOutputStream(outputStreamDefinition, eventTable.getTableDefinition());
MetaStateEvent metaStateEvent = createMetaStateEvent(outputStreamDefinition, eventTable);
Finder finder = eventTable.constructFinder(((UpdateStream) outStream).getOnUpdateExpression(), metaStateEvent, executionPlanContext, null, 0);
return new UpdateTableCallback(eventTable, finder, outputStreamDefinition);
} else {
throw new DefinitionNotExistException("Event table with id :" + id + " does not exist");
}
} else {
throw new ExecutionPlanCreationException(outStream.getClass().getName() + " not supported");
}
}
#location 21
#vulnerability type NULL_DEREFERENCE
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
@Override
public void process(StreamEvent event) {
StreamEvent head = event; //head of in events
StreamEvent expiredEventTail;
StreamEvent expiredEventHead;
while (event != null) {
processEvent(event);
event = event.getNext();
}
//if window is expired
if (count > length) {
int diff = count - length;
expiredEventTail = removeEventHead;
for (int i = 1; i < diff; i++) {
expiredEventTail = expiredEventTail.getNext();
}
expiredEventHead = removeEventHead;
removeEventHead = expiredEventTail.getNext();
expiredEventTail.setNext(null);
addToLast(head, expiredEventHead);
nextProcessor.process(head); //emit in events and remove events as expired events
count = count - diff;
} else {
nextProcessor.process(head); //emit only in events as window is not expired
}
}
|
#vulnerable code
@Override
public void process(StreamEvent event) {
StreamEvent head = event; //head of in events
StreamEvent expiredEventTail;
StreamEvent expiredEventHead;
while (event != null) {
processEvent(event);
event = event.getNext();
}
//if window is expired
if (count > length) {
int diff = count - length;
expiredEventTail = removeEventHead;
for (int i = 1; i < diff; i++) {
expiredEventTail = expiredEventTail.getNext();
}
expiredEventHead = removeEventHead;
removeEventHead = expiredEventTail.getNext();
expiredEventTail.setNext(null);
head.addToLast(expiredEventHead);
nextProcessor.process(head); //emit in events and remove events as expired events
count = count - diff;
} else {
nextProcessor.process(head); //emit only in events as window is not expired
}
}
#location 15
#vulnerability type NULL_DEREFERENCE
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
@Override
public void restoreState(Object[] state) {
eventChunk = (ComplexEventChunk<ComplexEvent>) state[0];
//endOfChunk = (Boolean) state[1];
}
|
#vulnerable code
@Override
public void restoreState(Object[] state) {
eventChunk = (ComplexEventChunk<ComplexEvent>) state[0];
endOfChunk = (Boolean) state[1];
}
#location 4
#vulnerability type THREAD_SAFETY_VIOLATION
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
@Override
public void process(ComplexEventChunk complexEventChunk) {
if (trigger) {
ComplexEventChunk<StateEvent> returnEventChunk = new ComplexEventChunk<StateEvent>(true);
StateEvent joinStateEvent = new StateEvent(2, 0);
StreamEvent nextEvent = (StreamEvent) complexEventChunk.getFirst();
complexEventChunk.clear();
while (nextEvent != null) {
StreamEvent streamEvent = nextEvent;
nextEvent = streamEvent.getNext();
streamEvent.setNext(null);
joinLock.lock();
try {
ComplexEvent.Type eventType = streamEvent.getType();
if (eventType == ComplexEvent.Type.TIMER || eventType == ComplexEvent.Type.RESET) {
continue;
}
joinStateEvent.setEvent(matchingStreamIndex, streamEvent);
StreamEvent foundStreamEvent = findableProcessor.find(joinStateEvent, finder);
joinStateEvent.setEvent(matchingStreamIndex, null);
if (foundStreamEvent == null) {
if (outerJoinProcessor && !leftJoinProcessor) {
returnEventChunk.add(joinEventBuilder(foundStreamEvent, streamEvent, eventType));
} else if (outerJoinProcessor && leftJoinProcessor) {
returnEventChunk.add(joinEventBuilder(streamEvent, foundStreamEvent, eventType));
}
} else {
while (foundStreamEvent != null) {
if (!leftJoinProcessor) {
returnEventChunk.add(joinEventBuilder(foundStreamEvent, streamEvent, eventType));
} else {
returnEventChunk.add(joinEventBuilder(streamEvent, foundStreamEvent, eventType));
}
foundStreamEvent = foundStreamEvent.getNext();
}
}
} finally {
joinLock.unlock();
}
if (returnEventChunk.getFirst() != null) {
selector.process(returnEventChunk);
returnEventChunk.clear();
}
}
}
}
|
#vulnerable code
@Override
public void process(ComplexEventChunk complexEventChunk) {
if (trigger) {
ComplexEventChunk<StateEvent> returnEventChunk = new ComplexEventChunk<StateEvent>(true);
StateEvent joinStateEvent = new StateEvent(2, 0);
StreamEvent nextEvent = (StreamEvent) complexEventChunk.getFirst();
complexEventChunk.clear();
while (nextEvent != null) {
StreamEvent streamEvent = nextEvent;
nextEvent = streamEvent.getNext();
streamEvent.setNext(null);
joinLock.lock();
try {
if (streamEvent.getType() == ComplexEvent.Type.TIMER) {
if (preJoinProcessor) {
complexEventChunk.add(streamEvent);
nextProcessor.process(complexEventChunk);
complexEventChunk.clear();
}
continue;
} else if (streamEvent.getType() == ComplexEvent.Type.CURRENT) {
if (!preJoinProcessor) {
continue;
}
} else if (streamEvent.getType() == ComplexEvent.Type.EXPIRED) {
if (preJoinProcessor) {
continue;
}
} else if (streamEvent.getType() == ComplexEvent.Type.RESET) {
continue;
}
joinStateEvent.setEvent(matchingStreamIndex, streamEvent);
StreamEvent foundStreamEvent = findableProcessor.find(joinStateEvent, finder);
joinStateEvent.setEvent(matchingStreamIndex, null);
if (foundStreamEvent == null) {
if (outerJoinProcessor && !leftJoinProcessor) {
returnEventChunk.add(joinEventBuilder(foundStreamEvent, streamEvent));
} else if (outerJoinProcessor && leftJoinProcessor) {
returnEventChunk.add(joinEventBuilder(streamEvent, foundStreamEvent));
}
} else {
while (foundStreamEvent != null) {
if (!leftJoinProcessor) {
returnEventChunk.add(joinEventBuilder(foundStreamEvent, streamEvent));
} else {
returnEventChunk.add(joinEventBuilder(streamEvent, foundStreamEvent));
}
foundStreamEvent = foundStreamEvent.getNext();
}
}
if (preJoinProcessor) {
complexEventChunk.add(streamEvent);
nextProcessor.process(complexEventChunk);
complexEventChunk.clear();
}
} finally {
joinLock.unlock();
}
if (returnEventChunk.getFirst() != null) {
selector.process(returnEventChunk);
returnEventChunk.clear();
}
}
} else {
if (preJoinProcessor) {
joinLock.lock();
try {
nextProcessor.process(complexEventChunk);
} finally {
joinLock.unlock();
}
}
}
}
#location 17
#vulnerability type THREAD_SAFETY_VIOLATION
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
@Override
public void process(ComplexEventChunk complexEventChunk) {
if (trigger) {
ComplexEventChunk<StateEvent> returnEventChunk = new ComplexEventChunk<StateEvent>(true);
StateEvent joinStateEvent = new StateEvent(2, 0);
StreamEvent nextEvent = (StreamEvent) complexEventChunk.getFirst();
complexEventChunk.clear();
while (nextEvent != null) {
StreamEvent streamEvent = nextEvent;
nextEvent = streamEvent.getNext();
streamEvent.setNext(null);
joinLock.lock();
try {
ComplexEvent.Type eventType = streamEvent.getType();
if (eventType == ComplexEvent.Type.TIMER || eventType == ComplexEvent.Type.RESET) {
continue;
}
joinStateEvent.setEvent(matchingStreamIndex, streamEvent);
StreamEvent foundStreamEvent = findableProcessor.find(joinStateEvent, finder);
joinStateEvent.setEvent(matchingStreamIndex, null);
if (foundStreamEvent == null) {
if (outerJoinProcessor && !leftJoinProcessor) {
returnEventChunk.add(joinEventBuilder(foundStreamEvent, streamEvent, eventType));
} else if (outerJoinProcessor && leftJoinProcessor) {
returnEventChunk.add(joinEventBuilder(streamEvent, foundStreamEvent, eventType));
}
} else {
while (foundStreamEvent != null) {
if (!leftJoinProcessor) {
returnEventChunk.add(joinEventBuilder(foundStreamEvent, streamEvent, eventType));
} else {
returnEventChunk.add(joinEventBuilder(streamEvent, foundStreamEvent, eventType));
}
foundStreamEvent = foundStreamEvent.getNext();
}
}
} finally {
joinLock.unlock();
}
if (returnEventChunk.getFirst() != null) {
selector.process(returnEventChunk);
returnEventChunk.clear();
}
}
}
}
|
#vulnerable code
@Override
public void process(ComplexEventChunk complexEventChunk) {
if (trigger) {
ComplexEventChunk<StateEvent> returnEventChunk = new ComplexEventChunk<StateEvent>(true);
StateEvent joinStateEvent = new StateEvent(2, 0);
StreamEvent nextEvent = (StreamEvent) complexEventChunk.getFirst();
complexEventChunk.clear();
while (nextEvent != null) {
StreamEvent streamEvent = nextEvent;
nextEvent = streamEvent.getNext();
streamEvent.setNext(null);
joinLock.lock();
try {
if (streamEvent.getType() == ComplexEvent.Type.TIMER) {
if (preJoinProcessor) {
complexEventChunk.add(streamEvent);
nextProcessor.process(complexEventChunk);
complexEventChunk.clear();
}
continue;
} else if (streamEvent.getType() == ComplexEvent.Type.CURRENT) {
if (!preJoinProcessor) {
continue;
}
} else if (streamEvent.getType() == ComplexEvent.Type.EXPIRED) {
if (preJoinProcessor) {
continue;
}
} else if (streamEvent.getType() == ComplexEvent.Type.RESET) {
continue;
}
joinStateEvent.setEvent(matchingStreamIndex, streamEvent);
StreamEvent foundStreamEvent = findableProcessor.find(joinStateEvent, finder);
joinStateEvent.setEvent(matchingStreamIndex, null);
if (foundStreamEvent == null) {
if (outerJoinProcessor && !leftJoinProcessor) {
returnEventChunk.add(joinEventBuilder(foundStreamEvent, streamEvent));
} else if (outerJoinProcessor && leftJoinProcessor) {
returnEventChunk.add(joinEventBuilder(streamEvent, foundStreamEvent));
}
} else {
while (foundStreamEvent != null) {
if (!leftJoinProcessor) {
returnEventChunk.add(joinEventBuilder(foundStreamEvent, streamEvent));
} else {
returnEventChunk.add(joinEventBuilder(streamEvent, foundStreamEvent));
}
foundStreamEvent = foundStreamEvent.getNext();
}
}
if (preJoinProcessor) {
complexEventChunk.add(streamEvent);
nextProcessor.process(complexEventChunk);
complexEventChunk.clear();
}
} finally {
joinLock.unlock();
}
if (returnEventChunk.getFirst() != null) {
selector.process(returnEventChunk);
returnEventChunk.clear();
}
}
} else {
if (preJoinProcessor) {
joinLock.lock();
try {
nextProcessor.process(complexEventChunk);
} finally {
joinLock.unlock();
}
}
}
}
#location 17
#vulnerability type THREAD_SAFETY_VIOLATION
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
private void populateMarkovMatrix(String markovMatrixStorageLocation) {
File file = new File(markovMatrixStorageLocation);
FileInputStream fileInputStream = null;
BufferedInputStream bufferedInputStream = null;
BufferedReader bufferedReader = null;
String[] statesNames = null;
String key;
String startState;
String endState;
Map<String, Double> transitionCount = new HashMap<String, Double>();
Map<String, Double> startStateCount = new HashMap<String, Double>();
try {
fileInputStream = new FileInputStream(file);
bufferedInputStream = new BufferedInputStream(fileInputStream);
bufferedReader = new BufferedReader(new InputStreamReader(bufferedInputStream));
int rowNumber = 0;
String row = bufferedReader.readLine();
if (row != null) {
statesNames = row.split(",");
}
while ((row = bufferedReader.readLine()) != null) {
if (rowNumber >= statesNames.length) {
throw new OperationNotSupportedException(
"Number of rows in the matrix should be equal to number of states. please provide a "
+ statesNames.length + " x " + statesNames.length + " matrix.");
}
startState = statesNames[rowNumber];
String[] values = row.split(",");
double totalCount = 0.0;
if (values.length != statesNames.length) {
throw new OperationNotSupportedException(
"Number of columns in the matrix should be equal to number of states. please provide a "
+ statesNames.length + " x " + statesNames.length + " matrix.");
}
for (String value : values) {
try {
totalCount = totalCount + Double.parseDouble(value);
} catch (NumberFormatException e) {
log.error("Exception occurred while reading the data file: " + markovMatrixStorageLocation
+ ". All values in the matrix should be in double.", e);
}
}
startStateCount.put(startState, totalCount);
for (int j = 0; j < statesNames.length; j++) {
endState = statesNames[j];
key = markovMatrix.getKey(startState, endState);
transitionCount.put(key, Double.parseDouble(values[j]));
}
rowNumber++;
}
} catch (IOException e) {
log.error("Exception occurred while reading the data file: " + markovMatrixStorageLocation, e);
} finally {
closedQuietly(markovMatrixStorageLocation, bufferedReader, bufferedInputStream, fileInputStream);
}
markovMatrix.setStartStateCount(startStateCount);
markovMatrix.setTransitionCount(transitionCount);
}
|
#vulnerable code
private void populateMarkovMatrix(String markovMatrixStorageLocation) {
File file = new File(markovMatrixStorageLocation);
FileInputStream fileInputStream = null;
BufferedInputStream bufferedInputStream = null;
BufferedReader bufferedReader = null;
String[] statesNames = null;
String key;
String startState;
String endState;
Map<String, Double> transitionCount = new HashMap<String, Double>();
Map<String, Double> startStateCount = new HashMap<String, Double>();
try {
fileInputStream = new FileInputStream(file);
bufferedInputStream = new BufferedInputStream(fileInputStream);
bufferedReader = new BufferedReader(new InputStreamReader(bufferedInputStream));
int rowNumber = 0;
String row = bufferedReader.readLine();
if (row != null) {
statesNames = row.split(",");
}
while ((row = bufferedReader.readLine()) != null) {
if (rowNumber >= statesNames.length) {
throw new OperationNotSupportedException(
"Number of rows in the matrix should be equal to number of states. please provide a "
+ statesNames.length + " x " + statesNames.length + " matrix");
}
startState = statesNames[rowNumber];
String[] values = row.split(",");
double totalCount = 0.0;
if (values.length != statesNames.length) {
throw new OperationNotSupportedException(
"Number of columns in the matrix should be equal to number of states. please provide a "
+ statesNames.length + " x " + statesNames.length + " matrix");
}
for (String value : values) {
try {
totalCount = totalCount + Double.parseDouble(value);
} catch (NumberFormatException e) {
log.error("Exception occurred while reading the data file " + markovMatrixStorageLocation
+ ". All values in the matrix should be in double", e);
}
}
startStateCount.put(startState, totalCount);
for (int j = 0; j < statesNames.length; j++) {
endState = statesNames[j];
key = markovMatrix.getKey(startState, endState);
transitionCount.put(key, Double.parseDouble(values[j]));
}
rowNumber++;
}
} catch (IOException e) {
log.error("Exception occurred while reading the data file " + markovMatrixStorageLocation, e);
} finally {
closeQuietly(bufferedReader, bufferedInputStream, fileInputStream);
}
markovMatrix.setStartStateCount(startStateCount);
markovMatrix.setTransitionCount(transitionCount);
}
#location 65
#vulnerability type NULL_DEREFERENCE
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
public void add(StreamEvent streamEvent){
StreamEvent borrowedEvent = eventManager.borrowEvent();
eventManager.convertStreamEvent(streamEvent, borrowedEvent);
if(lastReturned!=null){
StreamEvent lastEvent = lastReturned;
StreamEvent even= null;
while (lastEvent!=null){
even = lastEvent;
lastEvent = lastEvent.getNext();
}
even.setNext(borrowedEvent);
}else if(previousToLastReturned!=null){
previousToLastReturned.setNext(borrowedEvent);
} else if (first != null){
StreamEvent lastEvent = first;
StreamEvent even= null;
while (lastEvent!=null){
even = lastEvent;
lastEvent = lastEvent.getNext();
}
even.setNext(borrowedEvent);
} else {
assignEvent(borrowedEvent);
}
}
|
#vulnerable code
public void add(StreamEvent streamEvent){
StreamEvent firstConvertedEvent =null;
StreamEvent lastConvertedEvent = null;
while (streamEvent!=null){
StreamEvent borrowedEvent = eventManager.borrowEvent();
eventManager.convertStreamEvent(streamEvent, borrowedEvent);
if(firstConvertedEvent ==null){
firstConvertedEvent = borrowedEvent;
lastConvertedEvent = borrowedEvent;
} else {
lastConvertedEvent.setNext(borrowedEvent);
}
streamEvent = streamEvent.getNext();
}
if(first==null){
first = firstConvertedEvent;
} else if (lastReturned != null){
StreamEvent nextToLastReturned = lastReturned.getNext();
lastConvertedEvent.setNext(nextToLastReturned);
lastReturned.setNext(firstConvertedEvent);
} else { //when first!=null
lastConvertedEvent.setNext(first);
first = firstConvertedEvent;
}
}
#location 22
#vulnerability type NULL_DEREFERENCE
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
@Test
public void testCreatingHttpSubscriptionJsonMapping() {
Subscription subscription = Subscription.Subscribe(
Transport.transport("jms").
option("topic", "foo"));
subscription.map(
Mapping.format("json").
map("$.sensorData.time").
map("$.sensorData.data"));
subscription.insertInto("FooStream");
ExecutionPlan.executionPlan("test").addSubscription(subscription);
}
|
#vulnerable code
@Test
public void testCreatingHttpSubscriptionJsonMapping() {
Subscription subscription = Subscription.Subscribe(
Transport.transport("jms").
option("topic", "foo"));
subscription.map(
Mapper.mapper("json").
map("$.sensorData.time").
map("$.sensorData.data"));
subscription.insertInto("FooStream");
ExecutionPlan.executionPlan("test").addSubscription(subscription);
}
#location 10
#vulnerability type NULL_DEREFERENCE
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
@Override
public Object[] currentState() {
return new Object[]{eventChunk};
}
|
#vulnerable code
@Override
public Object[] currentState() {
return new Object[]{eventChunk, endOfChunk};
}
#location 3
#vulnerability type THREAD_SAFETY_VIOLATION
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
@Override
protected void process(ComplexEventChunk<StreamEvent> streamEventChunk, Processor nextProcessor,
StreamEventCloner streamEventCloner, ComplexEventPopulater complexEventPopulater) {
ComplexEventChunk<StreamEvent> complexEventChunk = new ComplexEventChunk<StreamEvent>(false);
lock.lock();
try {
while (streamEventChunk.hasNext()) {
StreamEvent event = streamEventChunk.next();
if(event.getType() != ComplexEvent.Type.TIMER) {
streamEventChunk.remove(); //We might have the rest of the events linked to this event forming a chain.
long timestamp = (Long) timestampExecutor.execute(event);
if (expireFlag) {
if (timestamp < lastSentTimeStamp) {
continue;
}
}
ArrayList<StreamEvent> eventList = eventTreeMap.get(timestamp);
if (eventList == null) {
eventList = new ArrayList<StreamEvent>();
}
eventList.add(event);
eventTreeMap.put(timestamp, eventList);
if (timestamp > greatestTimestamp) {
greatestTimestamp = timestamp;
long minTimestamp = eventTreeMap.firstKey();
long timeDifference = greatestTimestamp - minTimestamp;
if (timeDifference > k) {
if (timeDifference < MAX_K) {
k = timeDifference;
} else {
k = MAX_K;
}
}
Iterator<Map.Entry<Long, ArrayList<StreamEvent>>> entryIterator = eventTreeMap.entrySet().iterator();
while (entryIterator.hasNext()) {
Map.Entry<Long, ArrayList<StreamEvent>> entry = entryIterator.next();
ArrayList<StreamEvent> list = expiredEventTreeMap.get(entry.getKey());
if (list != null) {
list.addAll(entry.getValue());
} else {
expiredEventTreeMap.put(entry.getKey(), entry.getValue());
}
}
eventTreeMap = new TreeMap<Long, ArrayList<StreamEvent>>();
entryIterator = expiredEventTreeMap.entrySet().iterator();
while (entryIterator.hasNext()) {
Map.Entry<Long, ArrayList<StreamEvent>> entry = entryIterator.next();
if (entry.getKey() + k <= greatestTimestamp) {
entryIterator.remove();
ArrayList<StreamEvent> timeEventList = entry.getValue();
lastSentTimeStamp = entry.getKey();
for (StreamEvent aTimeEventList : timeEventList) {
complexEventChunk.add(aTimeEventList);
}
}
}
}
} else {
if(expiredEventTreeMap.size() > 0) {
TreeMap<Long, ArrayList<StreamEvent>> expiredEventTreeMapSnapShot = expiredEventTreeMap;
expiredEventTreeMap = new TreeMap<Long, ArrayList<StreamEvent>>();
onTimerEvent(expiredEventTreeMapSnapShot, nextProcessor);
lastScheduledTimestamp = lastScheduledTimestamp + TIMER_DURATION;
scheduler.notifyAt(lastScheduledTimestamp);
}
}
}
} catch (ArrayIndexOutOfBoundsException ec) {
//This happens due to user specifying an invalid field index.
throw new ExecutionPlanCreationException("The very first parameter must be an Integer with a valid " +
" field index (0 to (fieldsLength-1)).");
}
lock.unlock();
nextProcessor.process(complexEventChunk);
}
|
#vulnerable code
@Override
protected void process(ComplexEventChunk<StreamEvent> streamEventChunk, Processor nextProcessor,
StreamEventCloner streamEventCloner, ComplexEventPopulater complexEventPopulater) {
ComplexEventChunk<StreamEvent> complexEventChunk = new ComplexEventChunk<StreamEvent>(false);
try {
while (streamEventChunk.hasNext()) {
StreamEvent event = streamEventChunk.next();
if(event.getType() != ComplexEvent.Type.TIMER) {
streamEventChunk.remove(); //We might have the rest of the events linked to this event forming a chain.
long timestamp = (Long) timestampExecutor.execute(event);
if (expireFlag) {
if (timestamp < lastSentTimeStamp) {
continue;
}
}
ArrayList<StreamEvent> eventList = eventTreeMap.get(timestamp);
if (eventList == null) {
eventList = new ArrayList<StreamEvent>();
}
eventList.add(event);
eventTreeMap.put(timestamp, eventList);
if (timestamp > greatestTimestamp) {
greatestTimestamp = timestamp;
long minTimestamp = eventTreeMap.firstKey();
if ((greatestTimestamp - minTimestamp) > k) {
if ((greatestTimestamp - minTimestamp) < MAX_K) {
k = greatestTimestamp - minTimestamp;
} else {
k = MAX_K;
}
}
lock.lock();
Iterator<Map.Entry<Long, ArrayList<StreamEvent>>> entryIterator = eventTreeMap.entrySet().iterator();
while (entryIterator.hasNext()) {
Map.Entry<Long, ArrayList<StreamEvent>> entry = entryIterator.next();
ArrayList<StreamEvent> list = expiredEventTreeMap.get(entry.getKey());
if (list != null) {
list.addAll(entry.getValue());
} else {
expiredEventTreeMap.put(entry.getKey(), entry.getValue());
}
}
eventTreeMap = new TreeMap<Long, ArrayList<StreamEvent>>();
entryIterator = expiredEventTreeMap.entrySet().iterator();
while (entryIterator.hasNext()) {
Map.Entry<Long, ArrayList<StreamEvent>> entry = entryIterator.next();
if (entry.getKey() + k <= greatestTimestamp) {
entryIterator.remove();
ArrayList<StreamEvent> timeEventList = entry.getValue();
lastSentTimeStamp = entry.getKey();
for (StreamEvent aTimeEventList : timeEventList) {
complexEventChunk.add(aTimeEventList);
}
}
}
lock.unlock();
}
} else {
onTimerEvent(expiredEventTreeMap, nextProcessor);
lastScheduledTimestamp = lastScheduledTimestamp + TIMER_DURATION;
scheduler.notifyAt(lastScheduledTimestamp);
}
}
} catch (ArrayIndexOutOfBoundsException ec) {
// This happens due to user specifying an invalid field index.
throw new ExecutionPlanCreationException("The very first parameter must be an Integer with a valid " +
" field index (0 to (fieldsLength-1)).");
}
nextProcessor.process(complexEventChunk);
}
#location 17
#vulnerability type THREAD_SAFETY_VIOLATION
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
@Override
public void process(ComplexEventChunk complexEventChunk) {
if (trigger) {
ComplexEventChunk<StateEvent> returnEventChunk = new ComplexEventChunk<StateEvent>(true);
StateEvent joinStateEvent = new StateEvent(2, 0);
StreamEvent nextEvent = (StreamEvent) complexEventChunk.getFirst();
complexEventChunk.clear();
while (nextEvent != null) {
StreamEvent streamEvent = nextEvent;
nextEvent = streamEvent.getNext();
streamEvent.setNext(null);
joinLock.lock();
try {
ComplexEvent.Type eventType = streamEvent.getType();
if (eventType == ComplexEvent.Type.TIMER) {
continue;
} else if (eventType == ComplexEvent.Type.RESET) {
if (outerJoinProcessor && !leftJoinProcessor) {
returnEventChunk.add(joinEventBuilder(null, streamEvent, eventType));
} else if (outerJoinProcessor && leftJoinProcessor) {
returnEventChunk.add(joinEventBuilder(streamEvent, null, eventType));
}
} else {
joinStateEvent.setEvent(matchingStreamIndex, streamEvent);
StreamEvent foundStreamEvent = findableProcessor.find(joinStateEvent, finder);
joinStateEvent.setEvent(matchingStreamIndex, null);
if (foundStreamEvent == null) {
if (outerJoinProcessor && !leftJoinProcessor) {
returnEventChunk.add(joinEventBuilder(foundStreamEvent, streamEvent, eventType));
} else if (outerJoinProcessor && leftJoinProcessor) {
returnEventChunk.add(joinEventBuilder(streamEvent, foundStreamEvent, eventType));
}
} else {
while (foundStreamEvent != null) {
if (!leftJoinProcessor) {
returnEventChunk.add(joinEventBuilder(foundStreamEvent, streamEvent, eventType));
} else {
returnEventChunk.add(joinEventBuilder(streamEvent, foundStreamEvent, eventType));
}
foundStreamEvent = foundStreamEvent.getNext();
}
}
}
} finally {
joinLock.unlock();
}
if (returnEventChunk.getFirst() != null) {
selector.process(returnEventChunk);
returnEventChunk.clear();
}
}
} else {
if (preJoinProcessor) {
joinLock.lock();
try {
nextProcessor.process(complexEventChunk);
} finally {
joinLock.unlock();
}
}
}
}
|
#vulnerable code
@Override
public void process(ComplexEventChunk complexEventChunk) {
if (trigger) {
ComplexEventChunk<StateEvent> returnEventChunk = new ComplexEventChunk<StateEvent>(true);
StateEvent joinStateEvent = new StateEvent(2, 0);
StreamEvent nextEvent = (StreamEvent) complexEventChunk.getFirst();
complexEventChunk.clear();
while (nextEvent != null) {
StreamEvent streamEvent = nextEvent;
nextEvent = streamEvent.getNext();
streamEvent.setNext(null);
if (streamEvent.getType() == ComplexEvent.Type.RESET) {
if (outerJoinProcessor && !leftJoinProcessor) {
returnEventChunk.add(joinEventBuilder(null, streamEvent, streamEvent.getType()));
} else if (outerJoinProcessor && leftJoinProcessor) {
returnEventChunk.add(joinEventBuilder(streamEvent, null, streamEvent.getType()));
}
selector.process(returnEventChunk);
returnEventChunk.clear();
continue;
}
joinLock.lock();
try {
ComplexEvent.Type eventType = streamEvent.getType();
if (eventType == ComplexEvent.Type.TIMER) {
continue;
}
joinStateEvent.setEvent(matchingStreamIndex, streamEvent);
StreamEvent foundStreamEvent = findableProcessor.find(joinStateEvent, finder);
joinStateEvent.setEvent(matchingStreamIndex, null);
if (foundStreamEvent == null) {
if (outerJoinProcessor && !leftJoinProcessor) {
returnEventChunk.add(joinEventBuilder(foundStreamEvent, streamEvent, eventType));
} else if (outerJoinProcessor && leftJoinProcessor) {
returnEventChunk.add(joinEventBuilder(streamEvent, foundStreamEvent, eventType));
}
} else {
while (foundStreamEvent != null) {
if (!leftJoinProcessor) {
returnEventChunk.add(joinEventBuilder(foundStreamEvent, streamEvent, eventType));
} else {
returnEventChunk.add(joinEventBuilder(streamEvent, foundStreamEvent, eventType));
}
foundStreamEvent = foundStreamEvent.getNext();
}
}
} finally {
joinLock.unlock();
}
if (returnEventChunk.getFirst() != null) {
selector.process(returnEventChunk);
returnEventChunk.clear();
}
}
}
}
#location 16
#vulnerability type THREAD_SAFETY_VIOLATION
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
@Override
public void send(Event event, int streamIndex) {
inputProcessor.send(event, streamIndex);
// try {
// long sequenceNo = ringBuffer.next();
// try {
// IndexedEventFactory.IndexedEvent existingEvent = ringBuffer.get(sequenceNo);
// existingEvent.setEvent(event);
// existingEvent.setStreamIndex(streamIndex);
// } finally {
// eventSizeInDisruptor.incrementAndGet();
// ringBuffer.publish(sequenceNo); //Todo fix this for array of events
// }
// } catch (NullPointerException e) {
// throw new ExecutionPlanRuntimeException("Execution Plan:" + executionPlanContext.getName() + " not " +
// "initialised yet! Run executionPlanRuntime.start();", e);
// }
}
|
#vulnerable code
@Override
public void send(Event event, int streamIndex) {
try {
long sequenceNo = ringBuffer.next();
try {
IndexedEventFactory.IndexedEvent existingEvent = ringBuffer.get(sequenceNo);
existingEvent.setEvent(event);
existingEvent.setStreamIndex(streamIndex);
} finally {
eventSizeInDisruptor.incrementAndGet();
ringBuffer.publish(sequenceNo); //Todo fix this for array of events
}
} catch (NullPointerException e) {
throw new ExecutionPlanRuntimeException("Execution Plan:" + executionPlanContext.getName() + " not " +
"initialised yet! Run executionPlanRuntime.start();", e);
}
}
#location 11
#vulnerability type THREAD_SAFETY_VIOLATION
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
@Override
public void process(ComplexEventChunk complexEventChunk) {
if (trigger) {
ComplexEventChunk<StateEvent> returnEventChunk = new ComplexEventChunk<StateEvent>(true);
StateEvent joinStateEvent = new StateEvent(2, 0);
StreamEvent nextEvent = (StreamEvent) complexEventChunk.getFirst();
complexEventChunk.clear();
while (nextEvent != null) {
StreamEvent streamEvent = nextEvent;
nextEvent = streamEvent.getNext();
streamEvent.setNext(null);
joinLockWrapper.lock();
try {
ComplexEvent.Type eventType = streamEvent.getType();
if (eventType == ComplexEvent.Type.TIMER) {
continue;
} else if (eventType == ComplexEvent.Type.RESET) {
if (outerJoinProcessor && !leftJoinProcessor) {
returnEventChunk.add(joinEventBuilder(null, streamEvent, eventType));
} else if (outerJoinProcessor && leftJoinProcessor) {
returnEventChunk.add(joinEventBuilder(streamEvent, null, eventType));
}
} else {
joinStateEvent.setEvent(matchingStreamIndex, streamEvent);
StreamEvent foundStreamEvent = findableProcessor.find(joinStateEvent, finder);
joinStateEvent.setEvent(matchingStreamIndex, null);
if (foundStreamEvent == null) {
if (outerJoinProcessor && !leftJoinProcessor) {
returnEventChunk.add(joinEventBuilder(foundStreamEvent, streamEvent, eventType));
} else if (outerJoinProcessor && leftJoinProcessor) {
returnEventChunk.add(joinEventBuilder(streamEvent, foundStreamEvent, eventType));
}
} else {
while (foundStreamEvent != null) {
if (!leftJoinProcessor) {
returnEventChunk.add(joinEventBuilder(foundStreamEvent, streamEvent, eventType));
} else {
returnEventChunk.add(joinEventBuilder(streamEvent, foundStreamEvent, eventType));
}
foundStreamEvent = foundStreamEvent.getNext();
}
}
}
} finally {
joinLockWrapper.unlock();
}
if (returnEventChunk.getFirst() != null) {
selector.process(returnEventChunk);
returnEventChunk.clear();
}
}
}
}
|
#vulnerable code
@Override
public void process(ComplexEventChunk complexEventChunk) {
if (trigger) {
ComplexEventChunk<StateEvent> returnEventChunk = new ComplexEventChunk<StateEvent>(true);
StateEvent joinStateEvent = new StateEvent(2, 0);
StreamEvent nextEvent = (StreamEvent) complexEventChunk.getFirst();
complexEventChunk.clear();
while (nextEvent != null) {
StreamEvent streamEvent = nextEvent;
nextEvent = streamEvent.getNext();
streamEvent.setNext(null);
joinLock.lock();
try {
ComplexEvent.Type eventType = streamEvent.getType();
if (eventType == ComplexEvent.Type.TIMER) {
continue;
} else if (eventType == ComplexEvent.Type.RESET) {
if (outerJoinProcessor && !leftJoinProcessor) {
returnEventChunk.add(joinEventBuilder(null, streamEvent, eventType));
} else if (outerJoinProcessor && leftJoinProcessor) {
returnEventChunk.add(joinEventBuilder(streamEvent, null, eventType));
}
} else {
joinStateEvent.setEvent(matchingStreamIndex, streamEvent);
StreamEvent foundStreamEvent = findableProcessor.find(joinStateEvent, finder);
joinStateEvent.setEvent(matchingStreamIndex, null);
if (foundStreamEvent == null) {
if (outerJoinProcessor && !leftJoinProcessor) {
returnEventChunk.add(joinEventBuilder(foundStreamEvent, streamEvent, eventType));
} else if (outerJoinProcessor && leftJoinProcessor) {
returnEventChunk.add(joinEventBuilder(streamEvent, foundStreamEvent, eventType));
}
} else {
while (foundStreamEvent != null) {
if (!leftJoinProcessor) {
returnEventChunk.add(joinEventBuilder(foundStreamEvent, streamEvent, eventType));
} else {
returnEventChunk.add(joinEventBuilder(streamEvent, foundStreamEvent, eventType));
}
foundStreamEvent = foundStreamEvent.getNext();
}
}
}
} finally {
joinLock.unlock();
}
if (returnEventChunk.getFirst() != null) {
selector.process(returnEventChunk);
returnEventChunk.clear();
}
}
} else {
if (preJoinProcessor) {
joinLock.lock();
try {
nextProcessor.process(complexEventChunk);
} finally {
joinLock.unlock();
}
}
}
}
#location 3
#vulnerability type THREAD_SAFETY_VIOLATION
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
@Override
protected void process(ComplexEventChunk<StreamEvent> streamEventChunk, Processor nextProcessor,
StreamEventCloner streamEventCloner, ComplexEventPopulater complexEventPopulater) {
ComplexEventChunk<StreamEvent> complexEventChunk = new ComplexEventChunk<StreamEvent>(false);
lock.lock();
try {
while (streamEventChunk.hasNext()) {
StreamEvent event = streamEventChunk.next();
if(event.getType() != ComplexEvent.Type.TIMER) {
streamEventChunk.remove(); //We might have the rest of the events linked to this event forming a chain.
long timestamp = (Long) timestampExecutor.execute(event);
if (expireFlag) {
if (timestamp < lastSentTimeStamp) {
continue;
}
}
ArrayList<StreamEvent> eventList = eventTreeMap.get(timestamp);
if (eventList == null) {
eventList = new ArrayList<StreamEvent>();
}
eventList.add(event);
eventTreeMap.put(timestamp, eventList);
if (timestamp > greatestTimestamp) {
greatestTimestamp = timestamp;
long minTimestamp = eventTreeMap.firstKey();
long timeDifference = greatestTimestamp - minTimestamp;
if (timeDifference > k) {
if (timeDifference < MAX_K) {
k = timeDifference;
} else {
k = MAX_K;
}
}
Iterator<Map.Entry<Long, ArrayList<StreamEvent>>> entryIterator = eventTreeMap.entrySet().iterator();
while (entryIterator.hasNext()) {
Map.Entry<Long, ArrayList<StreamEvent>> entry = entryIterator.next();
ArrayList<StreamEvent> list = expiredEventTreeMap.get(entry.getKey());
if (list != null) {
list.addAll(entry.getValue());
} else {
expiredEventTreeMap.put(entry.getKey(), entry.getValue());
}
}
eventTreeMap = new TreeMap<Long, ArrayList<StreamEvent>>();
entryIterator = expiredEventTreeMap.entrySet().iterator();
while (entryIterator.hasNext()) {
Map.Entry<Long, ArrayList<StreamEvent>> entry = entryIterator.next();
if (entry.getKey() + k <= greatestTimestamp) {
entryIterator.remove();
ArrayList<StreamEvent> timeEventList = entry.getValue();
lastSentTimeStamp = entry.getKey();
for (StreamEvent aTimeEventList : timeEventList) {
complexEventChunk.add(aTimeEventList);
}
}
}
}
} else {
if(expiredEventTreeMap.size() > 0) {
TreeMap<Long, ArrayList<StreamEvent>> expiredEventTreeMapSnapShot = expiredEventTreeMap;
expiredEventTreeMap = new TreeMap<Long, ArrayList<StreamEvent>>();
onTimerEvent(expiredEventTreeMapSnapShot, nextProcessor);
lastScheduledTimestamp = lastScheduledTimestamp + TIMER_DURATION;
scheduler.notifyAt(lastScheduledTimestamp);
}
}
}
} catch (ArrayIndexOutOfBoundsException ec) {
//This happens due to user specifying an invalid field index.
throw new ExecutionPlanCreationException("The very first parameter must be an Integer with a valid " +
" field index (0 to (fieldsLength-1)).");
}
lock.unlock();
nextProcessor.process(complexEventChunk);
}
|
#vulnerable code
@Override
protected void process(ComplexEventChunk<StreamEvent> streamEventChunk, Processor nextProcessor,
StreamEventCloner streamEventCloner, ComplexEventPopulater complexEventPopulater) {
ComplexEventChunk<StreamEvent> complexEventChunk = new ComplexEventChunk<StreamEvent>(false);
try {
while (streamEventChunk.hasNext()) {
StreamEvent event = streamEventChunk.next();
if(event.getType() != ComplexEvent.Type.TIMER) {
streamEventChunk.remove(); //We might have the rest of the events linked to this event forming a chain.
long timestamp = (Long) timestampExecutor.execute(event);
if (expireFlag) {
if (timestamp < lastSentTimeStamp) {
continue;
}
}
ArrayList<StreamEvent> eventList = eventTreeMap.get(timestamp);
if (eventList == null) {
eventList = new ArrayList<StreamEvent>();
}
eventList.add(event);
eventTreeMap.put(timestamp, eventList);
if (timestamp > greatestTimestamp) {
greatestTimestamp = timestamp;
long minTimestamp = eventTreeMap.firstKey();
if ((greatestTimestamp - minTimestamp) > k) {
if ((greatestTimestamp - minTimestamp) < MAX_K) {
k = greatestTimestamp - minTimestamp;
} else {
k = MAX_K;
}
}
lock.lock();
Iterator<Map.Entry<Long, ArrayList<StreamEvent>>> entryIterator = eventTreeMap.entrySet().iterator();
while (entryIterator.hasNext()) {
Map.Entry<Long, ArrayList<StreamEvent>> entry = entryIterator.next();
ArrayList<StreamEvent> list = expiredEventTreeMap.get(entry.getKey());
if (list != null) {
list.addAll(entry.getValue());
} else {
expiredEventTreeMap.put(entry.getKey(), entry.getValue());
}
}
eventTreeMap = new TreeMap<Long, ArrayList<StreamEvent>>();
entryIterator = expiredEventTreeMap.entrySet().iterator();
while (entryIterator.hasNext()) {
Map.Entry<Long, ArrayList<StreamEvent>> entry = entryIterator.next();
if (entry.getKey() + k <= greatestTimestamp) {
entryIterator.remove();
ArrayList<StreamEvent> timeEventList = entry.getValue();
lastSentTimeStamp = entry.getKey();
for (StreamEvent aTimeEventList : timeEventList) {
complexEventChunk.add(aTimeEventList);
}
}
}
lock.unlock();
}
} else {
onTimerEvent(expiredEventTreeMap, nextProcessor);
lastScheduledTimestamp = lastScheduledTimestamp + TIMER_DURATION;
scheduler.notifyAt(lastScheduledTimestamp);
}
}
} catch (ArrayIndexOutOfBoundsException ec) {
// This happens due to user specifying an invalid field index.
throw new ExecutionPlanCreationException("The very first parameter must be an Integer with a valid " +
" field index (0 to (fieldsLength-1)).");
}
nextProcessor.process(complexEventChunk);
}
#location 61
#vulnerability type THREAD_SAFETY_VIOLATION
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
@Override
protected void process(ComplexEventChunk<StreamEvent> streamEventChunk, Processor nextProcessor,
StreamEventCloner streamEventCloner, ComplexEventPopulater complexEventPopulater) {
ComplexEventChunk<StreamEvent> complexEventChunk = new ComplexEventChunk<StreamEvent>(false);
lock.lock();
try {
while (streamEventChunk.hasNext()) {
StreamEvent event = streamEventChunk.next();
if(event.getType() != ComplexEvent.Type.TIMER) {
streamEventChunk.remove(); //We might have the rest of the events linked to this event forming a chain.
long timestamp = (Long) timestampExecutor.execute(event);
if (expireFlag) {
if (timestamp < lastSentTimeStamp) {
continue;
}
}
ArrayList<StreamEvent> eventList = eventTreeMap.get(timestamp);
if (eventList == null) {
eventList = new ArrayList<StreamEvent>();
}
eventList.add(event);
eventTreeMap.put(timestamp, eventList);
if (timestamp > greatestTimestamp) {
greatestTimestamp = timestamp;
long minTimestamp = eventTreeMap.firstKey();
long timeDifference = greatestTimestamp - minTimestamp;
if (timeDifference > k) {
if (timeDifference < MAX_K) {
k = timeDifference;
} else {
k = MAX_K;
}
}
Iterator<Map.Entry<Long, ArrayList<StreamEvent>>> entryIterator = eventTreeMap.entrySet().iterator();
while (entryIterator.hasNext()) {
Map.Entry<Long, ArrayList<StreamEvent>> entry = entryIterator.next();
ArrayList<StreamEvent> list = expiredEventTreeMap.get(entry.getKey());
if (list != null) {
list.addAll(entry.getValue());
} else {
expiredEventTreeMap.put(entry.getKey(), entry.getValue());
}
}
eventTreeMap = new TreeMap<Long, ArrayList<StreamEvent>>();
entryIterator = expiredEventTreeMap.entrySet().iterator();
while (entryIterator.hasNext()) {
Map.Entry<Long, ArrayList<StreamEvent>> entry = entryIterator.next();
if (entry.getKey() + k <= greatestTimestamp) {
entryIterator.remove();
ArrayList<StreamEvent> timeEventList = entry.getValue();
lastSentTimeStamp = entry.getKey();
for (StreamEvent aTimeEventList : timeEventList) {
complexEventChunk.add(aTimeEventList);
}
}
}
}
} else {
if(expiredEventTreeMap.size() > 0) {
TreeMap<Long, ArrayList<StreamEvent>> expiredEventTreeMapSnapShot = expiredEventTreeMap;
expiredEventTreeMap = new TreeMap<Long, ArrayList<StreamEvent>>();
onTimerEvent(expiredEventTreeMapSnapShot, nextProcessor);
lastScheduledTimestamp = lastScheduledTimestamp + TIMER_DURATION;
scheduler.notifyAt(lastScheduledTimestamp);
}
}
}
} catch (ArrayIndexOutOfBoundsException ec) {
//This happens due to user specifying an invalid field index.
throw new ExecutionPlanCreationException("The very first parameter must be an Integer with a valid " +
" field index (0 to (fieldsLength-1)).");
}
lock.unlock();
nextProcessor.process(complexEventChunk);
}
|
#vulnerable code
@Override
protected void process(ComplexEventChunk<StreamEvent> streamEventChunk, Processor nextProcessor,
StreamEventCloner streamEventCloner, ComplexEventPopulater complexEventPopulater) {
ComplexEventChunk<StreamEvent> complexEventChunk = new ComplexEventChunk<StreamEvent>(false);
try {
while (streamEventChunk.hasNext()) {
StreamEvent event = streamEventChunk.next();
if(event.getType() != ComplexEvent.Type.TIMER) {
streamEventChunk.remove(); //We might have the rest of the events linked to this event forming a chain.
long timestamp = (Long) timestampExecutor.execute(event);
if (expireFlag) {
if (timestamp < lastSentTimeStamp) {
continue;
}
}
ArrayList<StreamEvent> eventList = eventTreeMap.get(timestamp);
if (eventList == null) {
eventList = new ArrayList<StreamEvent>();
}
eventList.add(event);
eventTreeMap.put(timestamp, eventList);
if (timestamp > greatestTimestamp) {
greatestTimestamp = timestamp;
long minTimestamp = eventTreeMap.firstKey();
if ((greatestTimestamp - minTimestamp) > k) {
if ((greatestTimestamp - minTimestamp) < MAX_K) {
k = greatestTimestamp - minTimestamp;
} else {
k = MAX_K;
}
}
lock.lock();
Iterator<Map.Entry<Long, ArrayList<StreamEvent>>> entryIterator = eventTreeMap.entrySet().iterator();
while (entryIterator.hasNext()) {
Map.Entry<Long, ArrayList<StreamEvent>> entry = entryIterator.next();
ArrayList<StreamEvent> list = expiredEventTreeMap.get(entry.getKey());
if (list != null) {
list.addAll(entry.getValue());
} else {
expiredEventTreeMap.put(entry.getKey(), entry.getValue());
}
}
eventTreeMap = new TreeMap<Long, ArrayList<StreamEvent>>();
entryIterator = expiredEventTreeMap.entrySet().iterator();
while (entryIterator.hasNext()) {
Map.Entry<Long, ArrayList<StreamEvent>> entry = entryIterator.next();
if (entry.getKey() + k <= greatestTimestamp) {
entryIterator.remove();
ArrayList<StreamEvent> timeEventList = entry.getValue();
lastSentTimeStamp = entry.getKey();
for (StreamEvent aTimeEventList : timeEventList) {
complexEventChunk.add(aTimeEventList);
}
}
}
lock.unlock();
}
} else {
onTimerEvent(expiredEventTreeMap, nextProcessor);
lastScheduledTimestamp = lastScheduledTimestamp + TIMER_DURATION;
scheduler.notifyAt(lastScheduledTimestamp);
}
}
} catch (ArrayIndexOutOfBoundsException ec) {
// This happens due to user specifying an invalid field index.
throw new ExecutionPlanCreationException("The very first parameter must be an Integer with a valid " +
" field index (0 to (fieldsLength-1)).");
}
nextProcessor.process(complexEventChunk);
}
#location 37
#vulnerability type THREAD_SAFETY_VIOLATION
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
@Override
protected void process(ComplexEventChunk<StreamEvent> streamEventChunk, Processor nextProcessor, StreamEventCloner streamEventCloner, ComplexEventPopulater complexEventPopulater) {
while (streamEventChunk.hasNext()) {
ComplexEvent complexEvent = streamEventChunk.next();
Object[] inputData = new Object[attributeExpressionLength-paramPosition];
// Obtain x value that user wants to use to forecast Y
double xDash = ((Number) attributeExpressionExecutors[paramPosition-1].execute(complexEvent)).doubleValue();
for (int i = paramPosition; i < attributeExpressionLength; i++) {
inputData[i-paramPosition] = attributeExpressionExecutors[i].execute(complexEvent);
}
Object[] coefficients = regressionCalculator.calculateLinearRegression(inputData);
if (coefficients == null) {
streamEventChunk.remove();
} else {
Object[] outputData = new Object[coefficients.length+1];
System.arraycopy(coefficients, 0, outputData, 0, coefficients.length);
// Calculating forecast Y based on regression equation and given x
outputData[coefficients.length] = ((Number) coefficients[coefficients.length-2]).doubleValue() + ((Number) coefficients[coefficients.length-1]).doubleValue() * xDash;
complexEventPopulater.populateComplexEvent(complexEvent, outputData);
}
}
nextProcessor.process(streamEventChunk);
}
|
#vulnerable code
@Override
protected void process(ComplexEventChunk<StreamEvent> streamEventChunk, Processor nextProcessor, StreamEventCloner streamEventCloner, ComplexEventPopulater complexEventPopulater) {
while (streamEventChunk.hasNext()) {
ComplexEvent complexEvent = streamEventChunk.next();
Object[] inputData = new Object[attributeExpressionLength-paramPosition];
double xDash = ((Number) attributeExpressionExecutors[paramPosition-1].execute(complexEvent)).doubleValue();
for (int i = paramPosition; i < attributeExpressionLength; i++) {
inputData[i-paramPosition] = attributeExpressionExecutors[i].execute(complexEvent);
}
Object[] temp = regressionCalculator.calculateLinearRegression(inputData);
Object[] outputData = new Object[temp.length+1];
System.arraycopy(temp, 0, outputData, 0, temp.length);
outputData[temp.length] = ((Number) temp[temp.length-2]).doubleValue() + ((Number) temp[temp.length-1]).doubleValue() * xDash;
if (outputData == null) {
streamEventChunk.remove();
} else {
complexEventPopulater.populateComplexEvent(complexEvent, outputData);
}
}
nextProcessor.process(streamEventChunk);
}
#location 12
#vulnerability type NULL_DEREFERENCE
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
@Override
protected void process(ComplexEventChunk<StreamEvent> streamEventChunk, Processor nextProcessor,
StreamEventCloner streamEventCloner, ComplexEventPopulater complexEventPopulater) {
ComplexEventChunk<StreamEvent> complexEventChunk = new ComplexEventChunk<StreamEvent>(false);
lock.lock();
try {
while (streamEventChunk.hasNext()) {
StreamEvent event = streamEventChunk.next();
if(event.getType() != ComplexEvent.Type.TIMER) {
streamEventChunk.remove(); //We might have the rest of the events linked to this event forming a chain.
long timestamp = (Long) timestampExecutor.execute(event);
if (expireFlag) {
if (timestamp < lastSentTimeStamp) {
continue;
}
}
ArrayList<StreamEvent> eventList = eventTreeMap.get(timestamp);
if (eventList == null) {
eventList = new ArrayList<StreamEvent>();
}
eventList.add(event);
eventTreeMap.put(timestamp, eventList);
if (timestamp > greatestTimestamp) {
greatestTimestamp = timestamp;
long minTimestamp = eventTreeMap.firstKey();
long timeDifference = greatestTimestamp - minTimestamp;
if (timeDifference > k) {
if (timeDifference < MAX_K) {
k = timeDifference;
} else {
k = MAX_K;
}
}
Iterator<Map.Entry<Long, ArrayList<StreamEvent>>> entryIterator = eventTreeMap.entrySet().iterator();
while (entryIterator.hasNext()) {
Map.Entry<Long, ArrayList<StreamEvent>> entry = entryIterator.next();
ArrayList<StreamEvent> list = expiredEventTreeMap.get(entry.getKey());
if (list != null) {
list.addAll(entry.getValue());
} else {
expiredEventTreeMap.put(entry.getKey(), entry.getValue());
}
}
eventTreeMap = new TreeMap<Long, ArrayList<StreamEvent>>();
entryIterator = expiredEventTreeMap.entrySet().iterator();
while (entryIterator.hasNext()) {
Map.Entry<Long, ArrayList<StreamEvent>> entry = entryIterator.next();
if (entry.getKey() + k <= greatestTimestamp) {
entryIterator.remove();
ArrayList<StreamEvent> timeEventList = entry.getValue();
lastSentTimeStamp = entry.getKey();
for (StreamEvent aTimeEventList : timeEventList) {
complexEventChunk.add(aTimeEventList);
}
}
}
}
} else {
if(expiredEventTreeMap.size() > 0) {
TreeMap<Long, ArrayList<StreamEvent>> expiredEventTreeMapSnapShot = expiredEventTreeMap;
expiredEventTreeMap = new TreeMap<Long, ArrayList<StreamEvent>>();
onTimerEvent(expiredEventTreeMapSnapShot, nextProcessor);
lastScheduledTimestamp = lastScheduledTimestamp + TIMER_DURATION;
scheduler.notifyAt(lastScheduledTimestamp);
}
}
}
} catch (ArrayIndexOutOfBoundsException ec) {
//This happens due to user specifying an invalid field index.
throw new ExecutionPlanCreationException("The very first parameter must be an Integer with a valid " +
" field index (0 to (fieldsLength-1)).");
}
lock.unlock();
nextProcessor.process(complexEventChunk);
}
|
#vulnerable code
@Override
protected void process(ComplexEventChunk<StreamEvent> streamEventChunk, Processor nextProcessor,
StreamEventCloner streamEventCloner, ComplexEventPopulater complexEventPopulater) {
ComplexEventChunk<StreamEvent> complexEventChunk = new ComplexEventChunk<StreamEvent>(false);
try {
while (streamEventChunk.hasNext()) {
StreamEvent event = streamEventChunk.next();
if(event.getType() != ComplexEvent.Type.TIMER) {
streamEventChunk.remove(); //We might have the rest of the events linked to this event forming a chain.
long timestamp = (Long) timestampExecutor.execute(event);
if (expireFlag) {
if (timestamp < lastSentTimeStamp) {
continue;
}
}
ArrayList<StreamEvent> eventList = eventTreeMap.get(timestamp);
if (eventList == null) {
eventList = new ArrayList<StreamEvent>();
}
eventList.add(event);
eventTreeMap.put(timestamp, eventList);
if (timestamp > greatestTimestamp) {
greatestTimestamp = timestamp;
long minTimestamp = eventTreeMap.firstKey();
if ((greatestTimestamp - minTimestamp) > k) {
if ((greatestTimestamp - minTimestamp) < MAX_K) {
k = greatestTimestamp - minTimestamp;
} else {
k = MAX_K;
}
}
lock.lock();
Iterator<Map.Entry<Long, ArrayList<StreamEvent>>> entryIterator = eventTreeMap.entrySet().iterator();
while (entryIterator.hasNext()) {
Map.Entry<Long, ArrayList<StreamEvent>> entry = entryIterator.next();
ArrayList<StreamEvent> list = expiredEventTreeMap.get(entry.getKey());
if (list != null) {
list.addAll(entry.getValue());
} else {
expiredEventTreeMap.put(entry.getKey(), entry.getValue());
}
}
eventTreeMap = new TreeMap<Long, ArrayList<StreamEvent>>();
entryIterator = expiredEventTreeMap.entrySet().iterator();
while (entryIterator.hasNext()) {
Map.Entry<Long, ArrayList<StreamEvent>> entry = entryIterator.next();
if (entry.getKey() + k <= greatestTimestamp) {
entryIterator.remove();
ArrayList<StreamEvent> timeEventList = entry.getValue();
lastSentTimeStamp = entry.getKey();
for (StreamEvent aTimeEventList : timeEventList) {
complexEventChunk.add(aTimeEventList);
}
}
}
lock.unlock();
}
} else {
onTimerEvent(expiredEventTreeMap, nextProcessor);
lastScheduledTimestamp = lastScheduledTimestamp + TIMER_DURATION;
scheduler.notifyAt(lastScheduledTimestamp);
}
}
} catch (ArrayIndexOutOfBoundsException ec) {
// This happens due to user specifying an invalid field index.
throw new ExecutionPlanCreationException("The very first parameter must be an Integer with a valid " +
" field index (0 to (fieldsLength-1)).");
}
nextProcessor.process(complexEventChunk);
}
#location 75
#vulnerability type THREAD_SAFETY_VIOLATION
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
@Override
public void process(ComplexEventChunk complexEventChunk) {
if (trigger) {
ComplexEventChunk<StateEvent> returnEventChunk = new ComplexEventChunk<StateEvent>(true);
StateEvent joinStateEvent = new StateEvent(2, 0);
StreamEvent nextEvent = (StreamEvent) complexEventChunk.getFirst();
complexEventChunk.clear();
while (nextEvent != null) {
StreamEvent streamEvent = nextEvent;
nextEvent = streamEvent.getNext();
streamEvent.setNext(null);
joinLockWrapper.lock();
try {
ComplexEvent.Type eventType = streamEvent.getType();
if (eventType == ComplexEvent.Type.TIMER) {
continue;
} else if (eventType == ComplexEvent.Type.RESET) {
if (outerJoinProcessor && !leftJoinProcessor) {
returnEventChunk.add(joinEventBuilder(null, streamEvent, eventType));
} else if (outerJoinProcessor && leftJoinProcessor) {
returnEventChunk.add(joinEventBuilder(streamEvent, null, eventType));
}
} else {
joinStateEvent.setEvent(matchingStreamIndex, streamEvent);
StreamEvent foundStreamEvent = findableProcessor.find(joinStateEvent, finder);
joinStateEvent.setEvent(matchingStreamIndex, null);
if (foundStreamEvent == null) {
if (outerJoinProcessor && !leftJoinProcessor) {
returnEventChunk.add(joinEventBuilder(foundStreamEvent, streamEvent, eventType));
} else if (outerJoinProcessor && leftJoinProcessor) {
returnEventChunk.add(joinEventBuilder(streamEvent, foundStreamEvent, eventType));
}
} else {
while (foundStreamEvent != null) {
if (!leftJoinProcessor) {
returnEventChunk.add(joinEventBuilder(foundStreamEvent, streamEvent, eventType));
} else {
returnEventChunk.add(joinEventBuilder(streamEvent, foundStreamEvent, eventType));
}
foundStreamEvent = foundStreamEvent.getNext();
}
}
}
} finally {
joinLockWrapper.unlock();
}
if (returnEventChunk.getFirst() != null) {
selector.process(returnEventChunk);
returnEventChunk.clear();
}
}
}
}
|
#vulnerable code
@Override
public void process(ComplexEventChunk complexEventChunk) {
if (trigger) {
ComplexEventChunk<StateEvent> returnEventChunk = new ComplexEventChunk<StateEvent>(true);
StateEvent joinStateEvent = new StateEvent(2, 0);
StreamEvent nextEvent = (StreamEvent) complexEventChunk.getFirst();
complexEventChunk.clear();
while (nextEvent != null) {
StreamEvent streamEvent = nextEvent;
nextEvent = streamEvent.getNext();
streamEvent.setNext(null);
joinLock.lock();
try {
ComplexEvent.Type eventType = streamEvent.getType();
if (eventType == ComplexEvent.Type.TIMER) {
continue;
} else if (eventType == ComplexEvent.Type.RESET) {
if (outerJoinProcessor && !leftJoinProcessor) {
returnEventChunk.add(joinEventBuilder(null, streamEvent, eventType));
} else if (outerJoinProcessor && leftJoinProcessor) {
returnEventChunk.add(joinEventBuilder(streamEvent, null, eventType));
}
} else {
joinStateEvent.setEvent(matchingStreamIndex, streamEvent);
StreamEvent foundStreamEvent = findableProcessor.find(joinStateEvent, finder);
joinStateEvent.setEvent(matchingStreamIndex, null);
if (foundStreamEvent == null) {
if (outerJoinProcessor && !leftJoinProcessor) {
returnEventChunk.add(joinEventBuilder(foundStreamEvent, streamEvent, eventType));
} else if (outerJoinProcessor && leftJoinProcessor) {
returnEventChunk.add(joinEventBuilder(streamEvent, foundStreamEvent, eventType));
}
} else {
while (foundStreamEvent != null) {
if (!leftJoinProcessor) {
returnEventChunk.add(joinEventBuilder(foundStreamEvent, streamEvent, eventType));
} else {
returnEventChunk.add(joinEventBuilder(streamEvent, foundStreamEvent, eventType));
}
foundStreamEvent = foundStreamEvent.getNext();
}
}
}
} finally {
joinLock.unlock();
}
if (returnEventChunk.getFirst() != null) {
selector.process(returnEventChunk);
returnEventChunk.clear();
}
}
} else {
if (preJoinProcessor) {
joinLock.lock();
try {
nextProcessor.process(complexEventChunk);
} finally {
joinLock.unlock();
}
}
}
}
#location 11
#vulnerability type THREAD_SAFETY_VIOLATION
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
@Override
protected void process(ComplexEventChunk<StreamEvent> streamEventChunk, Processor nextProcessor,
StreamEventCloner streamEventCloner, ComplexEventPopulater complexEventPopulater) {
ComplexEventChunk<StreamEvent> complexEventChunk = new ComplexEventChunk<StreamEvent>(false);
lock.lock();
try {
while (streamEventChunk.hasNext()) {
StreamEvent event = streamEventChunk.next();
if(event.getType() != ComplexEvent.Type.TIMER) {
streamEventChunk.remove(); //We might have the rest of the events linked to this event forming a chain.
long timestamp = (Long) timestampExecutor.execute(event);
if (expireFlag) {
if (timestamp < lastSentTimeStamp) {
continue;
}
}
ArrayList<StreamEvent> eventList = eventTreeMap.get(timestamp);
if (eventList == null) {
eventList = new ArrayList<StreamEvent>();
}
eventList.add(event);
eventTreeMap.put(timestamp, eventList);
if (timestamp > greatestTimestamp) {
greatestTimestamp = timestamp;
long minTimestamp = eventTreeMap.firstKey();
long timeDifference = greatestTimestamp - minTimestamp;
if (timeDifference > k) {
if (timeDifference < MAX_K) {
k = timeDifference;
} else {
k = MAX_K;
}
}
Iterator<Map.Entry<Long, ArrayList<StreamEvent>>> entryIterator = eventTreeMap.entrySet().iterator();
while (entryIterator.hasNext()) {
Map.Entry<Long, ArrayList<StreamEvent>> entry = entryIterator.next();
ArrayList<StreamEvent> list = expiredEventTreeMap.get(entry.getKey());
if (list != null) {
list.addAll(entry.getValue());
} else {
expiredEventTreeMap.put(entry.getKey(), entry.getValue());
}
}
eventTreeMap = new TreeMap<Long, ArrayList<StreamEvent>>();
entryIterator = expiredEventTreeMap.entrySet().iterator();
while (entryIterator.hasNext()) {
Map.Entry<Long, ArrayList<StreamEvent>> entry = entryIterator.next();
if (entry.getKey() + k <= greatestTimestamp) {
entryIterator.remove();
ArrayList<StreamEvent> timeEventList = entry.getValue();
lastSentTimeStamp = entry.getKey();
for (StreamEvent aTimeEventList : timeEventList) {
complexEventChunk.add(aTimeEventList);
}
}
}
}
} else {
if(expiredEventTreeMap.size() > 0) {
TreeMap<Long, ArrayList<StreamEvent>> expiredEventTreeMapSnapShot = expiredEventTreeMap;
expiredEventTreeMap = new TreeMap<Long, ArrayList<StreamEvent>>();
onTimerEvent(expiredEventTreeMapSnapShot, nextProcessor);
lastScheduledTimestamp = lastScheduledTimestamp + TIMER_DURATION;
scheduler.notifyAt(lastScheduledTimestamp);
}
}
}
} catch (ArrayIndexOutOfBoundsException ec) {
//This happens due to user specifying an invalid field index.
throw new ExecutionPlanCreationException("The very first parameter must be an Integer with a valid " +
" field index (0 to (fieldsLength-1)).");
}
lock.unlock();
nextProcessor.process(complexEventChunk);
}
|
#vulnerable code
@Override
protected void process(ComplexEventChunk<StreamEvent> streamEventChunk, Processor nextProcessor,
StreamEventCloner streamEventCloner, ComplexEventPopulater complexEventPopulater) {
ComplexEventChunk<StreamEvent> complexEventChunk = new ComplexEventChunk<StreamEvent>(false);
try {
while (streamEventChunk.hasNext()) {
StreamEvent event = streamEventChunk.next();
if(event.getType() != ComplexEvent.Type.TIMER) {
streamEventChunk.remove(); //We might have the rest of the events linked to this event forming a chain.
long timestamp = (Long) timestampExecutor.execute(event);
if (expireFlag) {
if (timestamp < lastSentTimeStamp) {
continue;
}
}
ArrayList<StreamEvent> eventList = eventTreeMap.get(timestamp);
if (eventList == null) {
eventList = new ArrayList<StreamEvent>();
}
eventList.add(event);
eventTreeMap.put(timestamp, eventList);
if (timestamp > greatestTimestamp) {
greatestTimestamp = timestamp;
long minTimestamp = eventTreeMap.firstKey();
if ((greatestTimestamp - minTimestamp) > k) {
if ((greatestTimestamp - minTimestamp) < MAX_K) {
k = greatestTimestamp - minTimestamp;
} else {
k = MAX_K;
}
}
lock.lock();
Iterator<Map.Entry<Long, ArrayList<StreamEvent>>> entryIterator = eventTreeMap.entrySet().iterator();
while (entryIterator.hasNext()) {
Map.Entry<Long, ArrayList<StreamEvent>> entry = entryIterator.next();
ArrayList<StreamEvent> list = expiredEventTreeMap.get(entry.getKey());
if (list != null) {
list.addAll(entry.getValue());
} else {
expiredEventTreeMap.put(entry.getKey(), entry.getValue());
}
}
eventTreeMap = new TreeMap<Long, ArrayList<StreamEvent>>();
entryIterator = expiredEventTreeMap.entrySet().iterator();
while (entryIterator.hasNext()) {
Map.Entry<Long, ArrayList<StreamEvent>> entry = entryIterator.next();
if (entry.getKey() + k <= greatestTimestamp) {
entryIterator.remove();
ArrayList<StreamEvent> timeEventList = entry.getValue();
lastSentTimeStamp = entry.getKey();
for (StreamEvent aTimeEventList : timeEventList) {
complexEventChunk.add(aTimeEventList);
}
}
}
lock.unlock();
}
} else {
onTimerEvent(expiredEventTreeMap, nextProcessor);
lastScheduledTimestamp = lastScheduledTimestamp + TIMER_DURATION;
scheduler.notifyAt(lastScheduledTimestamp);
}
}
} catch (ArrayIndexOutOfBoundsException ec) {
// This happens due to user specifying an invalid field index.
throw new ExecutionPlanCreationException("The very first parameter must be an Integer with a valid " +
" field index (0 to (fieldsLength-1)).");
}
nextProcessor.process(complexEventChunk);
}
#location 33
#vulnerability type THREAD_SAFETY_VIOLATION
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
@Override
protected void add(List<Object[]> records) {
String sql = this.composeInsertQuery();
try {
this.batchExecuteQueriesWithRecords(sql, records, false);
} catch (SQLException e) {
throw new RDBMSTableException("Error in adding events to '" + this.tableName + "' store: "
+ e.getMessage(), e);
}
}
|
#vulnerable code
@Override
protected void add(List<Object[]> records) {
String insertQuery = this.resolveTableName(this.queryConfigurationEntry.getRecordInsertQuery());
StringBuilder params = new StringBuilder();
int fieldsLeft = this.attributes.size();
while (fieldsLeft > 0) {
params.append(QUESTION_MARK);
if (fieldsLeft > 1) {
params.append(SEPARATOR);
}
fieldsLeft = fieldsLeft - 1;
}
insertQuery = insertQuery.replace(Q_PLACEHOLDER, params.toString());
try {
this.batchExecuteQueriesWithRecords(insertQuery, records, false);
} catch (SQLException e) {
throw new RDBMSTableException("Error in adding events to '" + this.tableName + "' store: "
+ e.getMessage(), e);
}
}
#location 13
#vulnerability type NULL_DEREFERENCE
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
@Override
protected void process(ComplexEventChunk<StreamEvent> streamEventChunk, Processor nextProcessor,
StreamEventCloner streamEventCloner, ComplexEventPopulater complexEventPopulater) {
ComplexEventChunk<StreamEvent> complexEventChunk = new ComplexEventChunk<StreamEvent>(false);
lock.lock();
try {
while (streamEventChunk.hasNext()) {
StreamEvent event = streamEventChunk.next();
if(event.getType() != ComplexEvent.Type.TIMER) {
streamEventChunk.remove(); //We might have the rest of the events linked to this event forming a chain.
long timestamp = (Long) timestampExecutor.execute(event);
if (expireFlag) {
if (timestamp < lastSentTimeStamp) {
continue;
}
}
ArrayList<StreamEvent> eventList = eventTreeMap.get(timestamp);
if (eventList == null) {
eventList = new ArrayList<StreamEvent>();
}
eventList.add(event);
eventTreeMap.put(timestamp, eventList);
if (timestamp > greatestTimestamp) {
greatestTimestamp = timestamp;
long minTimestamp = eventTreeMap.firstKey();
long timeDifference = greatestTimestamp - minTimestamp;
if (timeDifference > k) {
if (timeDifference < MAX_K) {
k = timeDifference;
} else {
k = MAX_K;
}
}
Iterator<Map.Entry<Long, ArrayList<StreamEvent>>> entryIterator = eventTreeMap.entrySet().iterator();
while (entryIterator.hasNext()) {
Map.Entry<Long, ArrayList<StreamEvent>> entry = entryIterator.next();
ArrayList<StreamEvent> list = expiredEventTreeMap.get(entry.getKey());
if (list != null) {
list.addAll(entry.getValue());
} else {
expiredEventTreeMap.put(entry.getKey(), entry.getValue());
}
}
eventTreeMap = new TreeMap<Long, ArrayList<StreamEvent>>();
entryIterator = expiredEventTreeMap.entrySet().iterator();
while (entryIterator.hasNext()) {
Map.Entry<Long, ArrayList<StreamEvent>> entry = entryIterator.next();
if (entry.getKey() + k <= greatestTimestamp) {
entryIterator.remove();
ArrayList<StreamEvent> timeEventList = entry.getValue();
lastSentTimeStamp = entry.getKey();
for (StreamEvent aTimeEventList : timeEventList) {
complexEventChunk.add(aTimeEventList);
}
}
}
}
} else {
if(expiredEventTreeMap.size() > 0) {
TreeMap<Long, ArrayList<StreamEvent>> expiredEventTreeMapSnapShot = expiredEventTreeMap;
expiredEventTreeMap = new TreeMap<Long, ArrayList<StreamEvent>>();
onTimerEvent(expiredEventTreeMapSnapShot, nextProcessor);
lastScheduledTimestamp = lastScheduledTimestamp + TIMER_DURATION;
scheduler.notifyAt(lastScheduledTimestamp);
}
}
}
} catch (ArrayIndexOutOfBoundsException ec) {
//This happens due to user specifying an invalid field index.
throw new ExecutionPlanCreationException("The very first parameter must be an Integer with a valid " +
" field index (0 to (fieldsLength-1)).");
}
lock.unlock();
nextProcessor.process(complexEventChunk);
}
|
#vulnerable code
@Override
protected void process(ComplexEventChunk<StreamEvent> streamEventChunk, Processor nextProcessor,
StreamEventCloner streamEventCloner, ComplexEventPopulater complexEventPopulater) {
ComplexEventChunk<StreamEvent> complexEventChunk = new ComplexEventChunk<StreamEvent>(false);
try {
while (streamEventChunk.hasNext()) {
StreamEvent event = streamEventChunk.next();
if(event.getType() != ComplexEvent.Type.TIMER) {
streamEventChunk.remove(); //We might have the rest of the events linked to this event forming a chain.
long timestamp = (Long) timestampExecutor.execute(event);
if (expireFlag) {
if (timestamp < lastSentTimeStamp) {
continue;
}
}
ArrayList<StreamEvent> eventList = eventTreeMap.get(timestamp);
if (eventList == null) {
eventList = new ArrayList<StreamEvent>();
}
eventList.add(event);
eventTreeMap.put(timestamp, eventList);
if (timestamp > greatestTimestamp) {
greatestTimestamp = timestamp;
long minTimestamp = eventTreeMap.firstKey();
if ((greatestTimestamp - minTimestamp) > k) {
if ((greatestTimestamp - minTimestamp) < MAX_K) {
k = greatestTimestamp - minTimestamp;
} else {
k = MAX_K;
}
}
lock.lock();
Iterator<Map.Entry<Long, ArrayList<StreamEvent>>> entryIterator = eventTreeMap.entrySet().iterator();
while (entryIterator.hasNext()) {
Map.Entry<Long, ArrayList<StreamEvent>> entry = entryIterator.next();
ArrayList<StreamEvent> list = expiredEventTreeMap.get(entry.getKey());
if (list != null) {
list.addAll(entry.getValue());
} else {
expiredEventTreeMap.put(entry.getKey(), entry.getValue());
}
}
eventTreeMap = new TreeMap<Long, ArrayList<StreamEvent>>();
entryIterator = expiredEventTreeMap.entrySet().iterator();
while (entryIterator.hasNext()) {
Map.Entry<Long, ArrayList<StreamEvent>> entry = entryIterator.next();
if (entry.getKey() + k <= greatestTimestamp) {
entryIterator.remove();
ArrayList<StreamEvent> timeEventList = entry.getValue();
lastSentTimeStamp = entry.getKey();
for (StreamEvent aTimeEventList : timeEventList) {
complexEventChunk.add(aTimeEventList);
}
}
}
lock.unlock();
}
} else {
onTimerEvent(expiredEventTreeMap, nextProcessor);
lastScheduledTimestamp = lastScheduledTimestamp + TIMER_DURATION;
scheduler.notifyAt(lastScheduledTimestamp);
}
}
} catch (ArrayIndexOutOfBoundsException ec) {
// This happens due to user specifying an invalid field index.
throw new ExecutionPlanCreationException("The very first parameter must be an Integer with a valid " +
" field index (0 to (fieldsLength-1)).");
}
nextProcessor.process(complexEventChunk);
}
#location 6
#vulnerability type THREAD_SAFETY_VIOLATION
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
protected void processAndClear(int processIndex, StreamEvent streamEvent) {
ComplexEventChunk<StateEvent> retEventChunk = new ComplexEventChunk<StateEvent>(false);
ComplexEventChunk<StreamEvent> currentStreamEventChunk = new ComplexEventChunk<StreamEvent>(streamEvent, streamEvent, false);
ComplexEventChunk<StateEvent> eventChunk = ((StreamPreStateProcessor) nextProcessors[processIndex]).processAndReturn(currentStreamEventChunk);
if(eventChunk.getFirst() != null){
retEventChunk.add(eventChunk.getFirst());
}
eventChunk.clear();
if(querySelector!= null) {
while (retEventChunk.hasNext()) {
StateEvent stateEvent = retEventChunk.next();
retEventChunk.remove();
querySelector.process(new ComplexEventChunk<StateEvent>(stateEvent,stateEvent, false));
}
}
}
|
#vulnerable code
protected void processAndClear(int processIndex, StreamEvent streamEvent) {
ComplexEventChunk<StateEvent> retEventChunk = new ComplexEventChunk<StateEvent>(false);
ComplexEventChunk<StreamEvent> currentStreamEventChunk = new ComplexEventChunk<StreamEvent>(streamEvent, streamEvent, false);
synchronized (lockKey) {
ComplexEventChunk<StateEvent> eventChunk = ((StreamPreStateProcessor) nextProcessors[processIndex]).processAndReturn(currentStreamEventChunk);
if(eventChunk.getFirst() != null){
retEventChunk.add(eventChunk.getFirst());
}
eventChunk.clear();
}
if(querySelector!= null) {
while (retEventChunk.hasNext()) {
StateEvent stateEvent = retEventChunk.next();
retEventChunk.remove();
querySelector.process(new ComplexEventChunk<StateEvent>(stateEvent,stateEvent, false));
}
}
}
#location 16
#vulnerability type THREAD_SAFETY_VIOLATION
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
@Override
public void process(ComplexEventChunk complexEventChunk) {
if (trigger) {
ComplexEventChunk<StateEvent> returnEventChunk = new ComplexEventChunk<StateEvent>(true);
StateEvent joinStateEvent = new StateEvent(2, 0);
StreamEvent nextEvent = (StreamEvent) complexEventChunk.getFirst();
complexEventChunk.clear();
while (nextEvent != null) {
StreamEvent streamEvent = nextEvent;
nextEvent = streamEvent.getNext();
streamEvent.setNext(null);
joinLockWrapper.lock();
try {
ComplexEvent.Type eventType = streamEvent.getType();
if (eventType == ComplexEvent.Type.TIMER) {
continue;
} else if (eventType == ComplexEvent.Type.RESET) {
if (outerJoinProcessor && !leftJoinProcessor) {
returnEventChunk.add(joinEventBuilder(null, streamEvent, eventType));
} else if (outerJoinProcessor && leftJoinProcessor) {
returnEventChunk.add(joinEventBuilder(streamEvent, null, eventType));
}
} else {
joinStateEvent.setEvent(matchingStreamIndex, streamEvent);
StreamEvent foundStreamEvent = findableProcessor.find(joinStateEvent, finder);
joinStateEvent.setEvent(matchingStreamIndex, null);
if (foundStreamEvent == null) {
if (outerJoinProcessor && !leftJoinProcessor) {
returnEventChunk.add(joinEventBuilder(foundStreamEvent, streamEvent, eventType));
} else if (outerJoinProcessor && leftJoinProcessor) {
returnEventChunk.add(joinEventBuilder(streamEvent, foundStreamEvent, eventType));
}
} else {
while (foundStreamEvent != null) {
if (!leftJoinProcessor) {
returnEventChunk.add(joinEventBuilder(foundStreamEvent, streamEvent, eventType));
} else {
returnEventChunk.add(joinEventBuilder(streamEvent, foundStreamEvent, eventType));
}
foundStreamEvent = foundStreamEvent.getNext();
}
}
}
} finally {
joinLockWrapper.unlock();
}
if (returnEventChunk.getFirst() != null) {
selector.process(returnEventChunk);
returnEventChunk.clear();
}
}
}
}
|
#vulnerable code
@Override
public void process(ComplexEventChunk complexEventChunk) {
if (trigger) {
ComplexEventChunk<StateEvent> returnEventChunk = new ComplexEventChunk<StateEvent>(true);
StateEvent joinStateEvent = new StateEvent(2, 0);
StreamEvent nextEvent = (StreamEvent) complexEventChunk.getFirst();
complexEventChunk.clear();
while (nextEvent != null) {
StreamEvent streamEvent = nextEvent;
nextEvent = streamEvent.getNext();
streamEvent.setNext(null);
joinLock.lock();
try {
ComplexEvent.Type eventType = streamEvent.getType();
if (eventType == ComplexEvent.Type.TIMER) {
continue;
} else if (eventType == ComplexEvent.Type.RESET) {
if (outerJoinProcessor && !leftJoinProcessor) {
returnEventChunk.add(joinEventBuilder(null, streamEvent, eventType));
} else if (outerJoinProcessor && leftJoinProcessor) {
returnEventChunk.add(joinEventBuilder(streamEvent, null, eventType));
}
} else {
joinStateEvent.setEvent(matchingStreamIndex, streamEvent);
StreamEvent foundStreamEvent = findableProcessor.find(joinStateEvent, finder);
joinStateEvent.setEvent(matchingStreamIndex, null);
if (foundStreamEvent == null) {
if (outerJoinProcessor && !leftJoinProcessor) {
returnEventChunk.add(joinEventBuilder(foundStreamEvent, streamEvent, eventType));
} else if (outerJoinProcessor && leftJoinProcessor) {
returnEventChunk.add(joinEventBuilder(streamEvent, foundStreamEvent, eventType));
}
} else {
while (foundStreamEvent != null) {
if (!leftJoinProcessor) {
returnEventChunk.add(joinEventBuilder(foundStreamEvent, streamEvent, eventType));
} else {
returnEventChunk.add(joinEventBuilder(streamEvent, foundStreamEvent, eventType));
}
foundStreamEvent = foundStreamEvent.getNext();
}
}
}
} finally {
joinLock.unlock();
}
if (returnEventChunk.getFirst() != null) {
selector.process(returnEventChunk);
returnEventChunk.clear();
}
}
} else {
if (preJoinProcessor) {
joinLock.lock();
try {
nextProcessor.process(complexEventChunk);
} finally {
joinLock.unlock();
}
}
}
}
#location 6
#vulnerability type THREAD_SAFETY_VIOLATION
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
@Override
protected void process(ComplexEventChunk<StreamEvent> streamEventChunk, Processor nextProcessor,
StreamEventCloner streamEventCloner, ComplexEventPopulater complexEventPopulater) {
ComplexEventChunk<StreamEvent> complexEventChunk = new ComplexEventChunk<StreamEvent>(false);
lock.lock();
try {
while (streamEventChunk.hasNext()) {
StreamEvent event = streamEventChunk.next();
if(event.getType() != ComplexEvent.Type.TIMER) {
streamEventChunk.remove(); //We might have the rest of the events linked to this event forming a chain.
long timestamp = (Long) timestampExecutor.execute(event);
if (expireFlag) {
if (timestamp < lastSentTimeStamp) {
continue;
}
}
ArrayList<StreamEvent> eventList = eventTreeMap.get(timestamp);
if (eventList == null) {
eventList = new ArrayList<StreamEvent>();
}
eventList.add(event);
eventTreeMap.put(timestamp, eventList);
if (timestamp > greatestTimestamp) {
greatestTimestamp = timestamp;
long minTimestamp = eventTreeMap.firstKey();
long timeDifference = greatestTimestamp - minTimestamp;
if (timeDifference > k) {
if (timeDifference < MAX_K) {
k = timeDifference;
} else {
k = MAX_K;
}
}
Iterator<Map.Entry<Long, ArrayList<StreamEvent>>> entryIterator = eventTreeMap.entrySet().iterator();
while (entryIterator.hasNext()) {
Map.Entry<Long, ArrayList<StreamEvent>> entry = entryIterator.next();
ArrayList<StreamEvent> list = expiredEventTreeMap.get(entry.getKey());
if (list != null) {
list.addAll(entry.getValue());
} else {
expiredEventTreeMap.put(entry.getKey(), entry.getValue());
}
}
eventTreeMap = new TreeMap<Long, ArrayList<StreamEvent>>();
entryIterator = expiredEventTreeMap.entrySet().iterator();
while (entryIterator.hasNext()) {
Map.Entry<Long, ArrayList<StreamEvent>> entry = entryIterator.next();
if (entry.getKey() + k <= greatestTimestamp) {
entryIterator.remove();
ArrayList<StreamEvent> timeEventList = entry.getValue();
lastSentTimeStamp = entry.getKey();
for (StreamEvent aTimeEventList : timeEventList) {
complexEventChunk.add(aTimeEventList);
}
}
}
}
} else {
if(expiredEventTreeMap.size() > 0) {
TreeMap<Long, ArrayList<StreamEvent>> expiredEventTreeMapSnapShot = expiredEventTreeMap;
expiredEventTreeMap = new TreeMap<Long, ArrayList<StreamEvent>>();
onTimerEvent(expiredEventTreeMapSnapShot, nextProcessor);
lastScheduledTimestamp = lastScheduledTimestamp + TIMER_DURATION;
scheduler.notifyAt(lastScheduledTimestamp);
}
}
}
} catch (ArrayIndexOutOfBoundsException ec) {
//This happens due to user specifying an invalid field index.
throw new ExecutionPlanCreationException("The very first parameter must be an Integer with a valid " +
" field index (0 to (fieldsLength-1)).");
}
lock.unlock();
nextProcessor.process(complexEventChunk);
}
|
#vulnerable code
@Override
protected void process(ComplexEventChunk<StreamEvent> streamEventChunk, Processor nextProcessor,
StreamEventCloner streamEventCloner, ComplexEventPopulater complexEventPopulater) {
ComplexEventChunk<StreamEvent> complexEventChunk = new ComplexEventChunk<StreamEvent>(false);
try {
while (streamEventChunk.hasNext()) {
StreamEvent event = streamEventChunk.next();
if(event.getType() != ComplexEvent.Type.TIMER) {
streamEventChunk.remove(); //We might have the rest of the events linked to this event forming a chain.
long timestamp = (Long) timestampExecutor.execute(event);
if (expireFlag) {
if (timestamp < lastSentTimeStamp) {
continue;
}
}
ArrayList<StreamEvent> eventList = eventTreeMap.get(timestamp);
if (eventList == null) {
eventList = new ArrayList<StreamEvent>();
}
eventList.add(event);
eventTreeMap.put(timestamp, eventList);
if (timestamp > greatestTimestamp) {
greatestTimestamp = timestamp;
long minTimestamp = eventTreeMap.firstKey();
if ((greatestTimestamp - minTimestamp) > k) {
if ((greatestTimestamp - minTimestamp) < MAX_K) {
k = greatestTimestamp - minTimestamp;
} else {
k = MAX_K;
}
}
lock.lock();
Iterator<Map.Entry<Long, ArrayList<StreamEvent>>> entryIterator = eventTreeMap.entrySet().iterator();
while (entryIterator.hasNext()) {
Map.Entry<Long, ArrayList<StreamEvent>> entry = entryIterator.next();
ArrayList<StreamEvent> list = expiredEventTreeMap.get(entry.getKey());
if (list != null) {
list.addAll(entry.getValue());
} else {
expiredEventTreeMap.put(entry.getKey(), entry.getValue());
}
}
eventTreeMap = new TreeMap<Long, ArrayList<StreamEvent>>();
entryIterator = expiredEventTreeMap.entrySet().iterator();
while (entryIterator.hasNext()) {
Map.Entry<Long, ArrayList<StreamEvent>> entry = entryIterator.next();
if (entry.getKey() + k <= greatestTimestamp) {
entryIterator.remove();
ArrayList<StreamEvent> timeEventList = entry.getValue();
lastSentTimeStamp = entry.getKey();
for (StreamEvent aTimeEventList : timeEventList) {
complexEventChunk.add(aTimeEventList);
}
}
}
lock.unlock();
}
} else {
onTimerEvent(expiredEventTreeMap, nextProcessor);
lastScheduledTimestamp = lastScheduledTimestamp + TIMER_DURATION;
scheduler.notifyAt(lastScheduledTimestamp);
}
}
} catch (ArrayIndexOutOfBoundsException ec) {
// This happens due to user specifying an invalid field index.
throw new ExecutionPlanCreationException("The very first parameter must be an Integer with a valid " +
" field index (0 to (fieldsLength-1)).");
}
nextProcessor.process(complexEventChunk);
}
#location 15
#vulnerability type THREAD_SAFETY_VIOLATION
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
@Override
public void process(ComplexEventChunk complexEventChunk) {
List<ComplexEventChunk<ComplexEvent>> outputEventChunks = new ArrayList<ComplexEventChunk<ComplexEvent>>();
complexEventChunk.reset();
synchronized (this) {
complexEventChunk.reset();
while (complexEventChunk.hasNext()) {
ComplexEvent event = complexEventChunk.next();
if (event.getType() == ComplexEvent.Type.TIMER) {
tryFlushEvents(outputEventChunks, event);
} else if (event.getType() == ComplexEvent.Type.CURRENT) {
complexEventChunk.remove();
tryFlushEvents(outputEventChunks, event);
GroupedComplexEvent groupedComplexEvent = ((GroupedComplexEvent) event);
groupByKeyEvents.put(groupedComplexEvent.getGroupKey(), groupedComplexEvent.getComplexEvent());
}
}
}
for (ComplexEventChunk eventChunk : outputEventChunks) {
sendToCallBacks(eventChunk);
}
}
|
#vulnerable code
@Override
public void process(ComplexEventChunk complexEventChunk) {
List<ComplexEventChunk<ComplexEvent>> outputEventChunks = new ArrayList<ComplexEventChunk<ComplexEvent>>();
complexEventChunk.reset();
synchronized (this) {
complexEventChunk.reset();
while (complexEventChunk.hasNext()) {
ComplexEvent event = complexEventChunk.next();
if (event.getType() == ComplexEvent.Type.TIMER) {
if (event.getTimestamp() >= scheduledTime) {
ComplexEventChunk<ComplexEvent> outputEventChunk = new ComplexEventChunk<ComplexEvent>(false);
for (ComplexEvent complexEvent : groupByKeyEvents.values()) {
outputEventChunk.add(cloneComplexEvent(complexEvent));
}
outputEventChunks.add(outputEventChunk);
scheduledTime += value;
scheduler.notifyAt(scheduledTime);
}
} else if (event.getType() == ComplexEvent.Type.CURRENT) {
complexEventChunk.remove();
GroupedComplexEvent groupedComplexEvent = ((GroupedComplexEvent) event);
groupByKeyEvents.put(groupedComplexEvent.getGroupKey(), groupedComplexEvent.getComplexEvent());
}
}
}
for (ComplexEventChunk eventChunk : outputEventChunks) {
sendToCallBacks(eventChunk);
}
}
#location 13
#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 Lock consumerLock = this.consumerLock;
while (!inactive) {
while (!paused) {
// The time, in milliseconds, spent waiting in poll if data is not available. If 0, returns
// immediately with any records that are available now. Must not be negative
ConsumerRecords<byte[], byte[]> records;
try {
consumerLock.lock();
records = consumer.poll(100);
} finally {
consumerLock.unlock();
}
for (ConsumerRecord record : records) {
String event = record.value().toString();
if (log.isDebugEnabled()) {
log.debug("Event received in Kafka Event Adaptor: " + event + ", offSet: " + record.offset()
+ ", key: " + record.key() + ", topic: " + record.topic() + ", partition: " + record
.partition());
}
topicOffsetMap.get(record.topic()).put(record.partition(), record.offset());
sourceEventListener.onEvent(event);
}
try {
consumerLock.lock();
if (!records.isEmpty()) {
consumer.commitAsync();
}
} catch (CommitFailedException e) {
log.error("Kafka commit failed for topic kafka_result_topic", e);
} finally {
consumerLock.unlock();
}
}
}
consumerLock.lock();
consumer.close();
consumerLock.unlock();
}
|
#vulnerable code
@Override
public void run() {
while (!inactive) {
while (!paused) {
// The time, in milliseconds, spent waiting in poll if data is not available. If 0, returns
// immediately with any records that are available now. Must not be negative
ConsumerRecords<byte[], byte[]> records = consumer.poll(200);
for (ConsumerRecord record : records) {
String event = record.value().toString();
if (log.isDebugEnabled()) {
log.debug("Event received in Kafka Event Adaptor: " + event + ", offSet: " + record.offset() +
", key: " + record.key() + ", topic: " + record.topic() + ", partition: " + record
.partition());
}
topicOffsetMap.get(record.topic()).put(record.partition(), record.offset());
sourceEventListener.onEvent(event);
}
try {
if (!records.isEmpty()) {
consumer.commitAsync();
}
} catch (CommitFailedException e) {
log.error("Kafka commit failed for topic kafka_result_topic", e);
}
}
try {
Thread.sleep(1);
} catch (InterruptedException ignore) {
}
}
consumer.close();
}
#location 15
#vulnerability type NULL_DEREFERENCE
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
@Override
protected void process(ComplexEventChunk<StreamEvent> streamEventChunk, Processor nextProcessor,
StreamEventCloner streamEventCloner, ComplexEventPopulater complexEventPopulater) {
ComplexEventChunk<StreamEvent> complexEventChunk = new ComplexEventChunk<StreamEvent>(false);
lock.lock();
try {
while (streamEventChunk.hasNext()) {
StreamEvent event = streamEventChunk.next();
if(event.getType() != ComplexEvent.Type.TIMER) {
streamEventChunk.remove(); //We might have the rest of the events linked to this event forming a chain.
long timestamp = (Long) timestampExecutor.execute(event);
if (expireFlag) {
if (timestamp < lastSentTimeStamp) {
continue;
}
}
ArrayList<StreamEvent> eventList = eventTreeMap.get(timestamp);
if (eventList == null) {
eventList = new ArrayList<StreamEvent>();
}
eventList.add(event);
eventTreeMap.put(timestamp, eventList);
if (timestamp > greatestTimestamp) {
greatestTimestamp = timestamp;
long minTimestamp = eventTreeMap.firstKey();
long timeDifference = greatestTimestamp - minTimestamp;
if (timeDifference > k) {
if (timeDifference < MAX_K) {
k = timeDifference;
} else {
k = MAX_K;
}
}
Iterator<Map.Entry<Long, ArrayList<StreamEvent>>> entryIterator = eventTreeMap.entrySet().iterator();
while (entryIterator.hasNext()) {
Map.Entry<Long, ArrayList<StreamEvent>> entry = entryIterator.next();
ArrayList<StreamEvent> list = expiredEventTreeMap.get(entry.getKey());
if (list != null) {
list.addAll(entry.getValue());
} else {
expiredEventTreeMap.put(entry.getKey(), entry.getValue());
}
}
eventTreeMap = new TreeMap<Long, ArrayList<StreamEvent>>();
entryIterator = expiredEventTreeMap.entrySet().iterator();
while (entryIterator.hasNext()) {
Map.Entry<Long, ArrayList<StreamEvent>> entry = entryIterator.next();
if (entry.getKey() + k <= greatestTimestamp) {
entryIterator.remove();
ArrayList<StreamEvent> timeEventList = entry.getValue();
lastSentTimeStamp = entry.getKey();
for (StreamEvent aTimeEventList : timeEventList) {
complexEventChunk.add(aTimeEventList);
}
}
}
}
} else {
if(expiredEventTreeMap.size() > 0) {
TreeMap<Long, ArrayList<StreamEvent>> expiredEventTreeMapSnapShot = expiredEventTreeMap;
expiredEventTreeMap = new TreeMap<Long, ArrayList<StreamEvent>>();
onTimerEvent(expiredEventTreeMapSnapShot, nextProcessor);
lastScheduledTimestamp = lastScheduledTimestamp + TIMER_DURATION;
scheduler.notifyAt(lastScheduledTimestamp);
}
}
}
} catch (ArrayIndexOutOfBoundsException ec) {
//This happens due to user specifying an invalid field index.
throw new ExecutionPlanCreationException("The very first parameter must be an Integer with a valid " +
" field index (0 to (fieldsLength-1)).");
}
lock.unlock();
nextProcessor.process(complexEventChunk);
}
|
#vulnerable code
@Override
protected void process(ComplexEventChunk<StreamEvent> streamEventChunk, Processor nextProcessor,
StreamEventCloner streamEventCloner, ComplexEventPopulater complexEventPopulater) {
ComplexEventChunk<StreamEvent> complexEventChunk = new ComplexEventChunk<StreamEvent>(false);
try {
while (streamEventChunk.hasNext()) {
StreamEvent event = streamEventChunk.next();
if(event.getType() != ComplexEvent.Type.TIMER) {
streamEventChunk.remove(); //We might have the rest of the events linked to this event forming a chain.
long timestamp = (Long) timestampExecutor.execute(event);
if (expireFlag) {
if (timestamp < lastSentTimeStamp) {
continue;
}
}
ArrayList<StreamEvent> eventList = eventTreeMap.get(timestamp);
if (eventList == null) {
eventList = new ArrayList<StreamEvent>();
}
eventList.add(event);
eventTreeMap.put(timestamp, eventList);
if (timestamp > greatestTimestamp) {
greatestTimestamp = timestamp;
long minTimestamp = eventTreeMap.firstKey();
if ((greatestTimestamp - minTimestamp) > k) {
if ((greatestTimestamp - minTimestamp) < MAX_K) {
k = greatestTimestamp - minTimestamp;
} else {
k = MAX_K;
}
}
lock.lock();
Iterator<Map.Entry<Long, ArrayList<StreamEvent>>> entryIterator = eventTreeMap.entrySet().iterator();
while (entryIterator.hasNext()) {
Map.Entry<Long, ArrayList<StreamEvent>> entry = entryIterator.next();
ArrayList<StreamEvent> list = expiredEventTreeMap.get(entry.getKey());
if (list != null) {
list.addAll(entry.getValue());
} else {
expiredEventTreeMap.put(entry.getKey(), entry.getValue());
}
}
eventTreeMap = new TreeMap<Long, ArrayList<StreamEvent>>();
entryIterator = expiredEventTreeMap.entrySet().iterator();
while (entryIterator.hasNext()) {
Map.Entry<Long, ArrayList<StreamEvent>> entry = entryIterator.next();
if (entry.getKey() + k <= greatestTimestamp) {
entryIterator.remove();
ArrayList<StreamEvent> timeEventList = entry.getValue();
lastSentTimeStamp = entry.getKey();
for (StreamEvent aTimeEventList : timeEventList) {
complexEventChunk.add(aTimeEventList);
}
}
}
lock.unlock();
}
} else {
onTimerEvent(expiredEventTreeMap, nextProcessor);
lastScheduledTimestamp = lastScheduledTimestamp + TIMER_DURATION;
scheduler.notifyAt(lastScheduledTimestamp);
}
}
} catch (ArrayIndexOutOfBoundsException ec) {
// This happens due to user specifying an invalid field index.
throw new ExecutionPlanCreationException("The very first parameter must be an Integer with a valid " +
" field index (0 to (fieldsLength-1)).");
}
nextProcessor.process(complexEventChunk);
}
#location 74
#vulnerability type THREAD_SAFETY_VIOLATION
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
@Override
public void process(ComplexEventChunk complexEventChunk) {
if (trigger) {
ComplexEventChunk<StateEvent> returnEventChunk = new ComplexEventChunk<StateEvent>(true);
StateEvent joinStateEvent = new StateEvent(2, 0);
StreamEvent nextEvent = (StreamEvent) complexEventChunk.getFirst();
complexEventChunk.clear();
while (nextEvent != null) {
StreamEvent streamEvent = nextEvent;
nextEvent = streamEvent.getNext();
streamEvent.setNext(null);
joinLock.lock();
try {
ComplexEvent.Type eventType = streamEvent.getType();
if (eventType == ComplexEvent.Type.TIMER) {
continue;
} else if (eventType == ComplexEvent.Type.RESET) {
if (outerJoinProcessor && !leftJoinProcessor) {
returnEventChunk.add(joinEventBuilder(null, streamEvent, eventType));
} else if (outerJoinProcessor && leftJoinProcessor) {
returnEventChunk.add(joinEventBuilder(streamEvent, null, eventType));
}
} else {
joinStateEvent.setEvent(matchingStreamIndex, streamEvent);
StreamEvent foundStreamEvent = findableProcessor.find(joinStateEvent, finder);
joinStateEvent.setEvent(matchingStreamIndex, null);
if (foundStreamEvent == null) {
if (outerJoinProcessor && !leftJoinProcessor) {
returnEventChunk.add(joinEventBuilder(foundStreamEvent, streamEvent, eventType));
} else if (outerJoinProcessor && leftJoinProcessor) {
returnEventChunk.add(joinEventBuilder(streamEvent, foundStreamEvent, eventType));
}
} else {
while (foundStreamEvent != null) {
if (!leftJoinProcessor) {
returnEventChunk.add(joinEventBuilder(foundStreamEvent, streamEvent, eventType));
} else {
returnEventChunk.add(joinEventBuilder(streamEvent, foundStreamEvent, eventType));
}
foundStreamEvent = foundStreamEvent.getNext();
}
}
}
} finally {
joinLock.unlock();
}
if (returnEventChunk.getFirst() != null) {
selector.process(returnEventChunk);
returnEventChunk.clear();
}
}
} else {
if (preJoinProcessor) {
joinLock.lock();
try {
nextProcessor.process(complexEventChunk);
} finally {
joinLock.unlock();
}
}
}
}
|
#vulnerable code
@Override
public void process(ComplexEventChunk complexEventChunk) {
if (trigger) {
ComplexEventChunk<StateEvent> returnEventChunk = new ComplexEventChunk<StateEvent>(true);
StateEvent joinStateEvent = new StateEvent(2, 0);
StreamEvent nextEvent = (StreamEvent) complexEventChunk.getFirst();
complexEventChunk.clear();
while (nextEvent != null) {
StreamEvent streamEvent = nextEvent;
nextEvent = streamEvent.getNext();
streamEvent.setNext(null);
if (streamEvent.getType() == ComplexEvent.Type.RESET) {
if (outerJoinProcessor && !leftJoinProcessor) {
returnEventChunk.add(joinEventBuilder(null, streamEvent, streamEvent.getType()));
} else if (outerJoinProcessor && leftJoinProcessor) {
returnEventChunk.add(joinEventBuilder(streamEvent, null, streamEvent.getType()));
}
selector.process(returnEventChunk);
returnEventChunk.clear();
continue;
}
joinLock.lock();
try {
ComplexEvent.Type eventType = streamEvent.getType();
if (eventType == ComplexEvent.Type.TIMER) {
continue;
}
joinStateEvent.setEvent(matchingStreamIndex, streamEvent);
StreamEvent foundStreamEvent = findableProcessor.find(joinStateEvent, finder);
joinStateEvent.setEvent(matchingStreamIndex, null);
if (foundStreamEvent == null) {
if (outerJoinProcessor && !leftJoinProcessor) {
returnEventChunk.add(joinEventBuilder(foundStreamEvent, streamEvent, eventType));
} else if (outerJoinProcessor && leftJoinProcessor) {
returnEventChunk.add(joinEventBuilder(streamEvent, foundStreamEvent, eventType));
}
} else {
while (foundStreamEvent != null) {
if (!leftJoinProcessor) {
returnEventChunk.add(joinEventBuilder(foundStreamEvent, streamEvent, eventType));
} else {
returnEventChunk.add(joinEventBuilder(streamEvent, foundStreamEvent, eventType));
}
foundStreamEvent = foundStreamEvent.getNext();
}
}
} finally {
joinLock.unlock();
}
if (returnEventChunk.getFirst() != null) {
selector.process(returnEventChunk);
returnEventChunk.clear();
}
}
}
}
#location 35
#vulnerability type THREAD_SAFETY_VIOLATION
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
@Override
protected void process(ComplexEventChunk<StreamEvent> streamEventChunk, Processor nextProcessor, StreamEventCloner streamEventCloner) {
while (streamEventChunk.hasNext()) {
StreamEvent streamEvent = streamEventChunk.next();
StreamEvent clonedEvent = streamEventCloner.copyStreamEvent(streamEvent);
clonedEvent.setType(StreamEvent.Type.EXPIRED);
if (count < length) {
count++;
this.expiredEventChunk.add(clonedEvent);
} else {
StreamEvent firstEvent = this.expiredEventChunk.poll();
if(firstEvent!=null) {
streamEventChunk.insertBeforeCurrent(firstEvent);
this.expiredEventChunk.add(clonedEvent);
}
else {
streamEventChunk.insertBeforeCurrent(clonedEvent);
}
}
}
nextProcessor.process(streamEventChunk);
}
|
#vulnerable code
@Override
protected void process(ComplexEventChunk<StreamEvent> streamEventChunk, Processor nextProcessor, StreamEventCloner streamEventCloner) {
while (streamEventChunk.hasNext()) {
StreamEvent streamEvent = streamEventChunk.next();
StreamEvent clonedEvent = streamEventCloner.copyStreamEvent(streamEvent);
clonedEvent.setType(StreamEvent.Type.EXPIRED);
if (count < length) {
count++;
this.expiredEventChunk.add(clonedEvent);
} else {
StreamEvent firstEvent = this.expiredEventChunk.poll();
streamEventChunk.insertBeforeCurrent(firstEvent);
this.expiredEventChunk.add(clonedEvent);
}
}
nextProcessor.process(streamEventChunk);
}
#location 12
#vulnerability type NULL_DEREFERENCE
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
@Override
protected void process(ComplexEventChunk<StreamEvent> streamEventChunk, Processor nextProcessor,
StreamEventCloner streamEventCloner, ComplexEventPopulater complexEventPopulater) {
ComplexEventChunk<StreamEvent> complexEventChunk = new ComplexEventChunk<StreamEvent>(false);
lock.lock();
try {
while (streamEventChunk.hasNext()) {
StreamEvent event = streamEventChunk.next();
if(event.getType() != ComplexEvent.Type.TIMER) {
streamEventChunk.remove(); //We might have the rest of the events linked to this event forming a chain.
long timestamp = (Long) timestampExecutor.execute(event);
if (expireFlag) {
if (timestamp < lastSentTimeStamp) {
continue;
}
}
ArrayList<StreamEvent> eventList = eventTreeMap.get(timestamp);
if (eventList == null) {
eventList = new ArrayList<StreamEvent>();
}
eventList.add(event);
eventTreeMap.put(timestamp, eventList);
if (timestamp > greatestTimestamp) {
greatestTimestamp = timestamp;
long minTimestamp = eventTreeMap.firstKey();
long timeDifference = greatestTimestamp - minTimestamp;
if (timeDifference > k) {
if (timeDifference < MAX_K) {
k = timeDifference;
} else {
k = MAX_K;
}
}
Iterator<Map.Entry<Long, ArrayList<StreamEvent>>> entryIterator = eventTreeMap.entrySet().iterator();
while (entryIterator.hasNext()) {
Map.Entry<Long, ArrayList<StreamEvent>> entry = entryIterator.next();
ArrayList<StreamEvent> list = expiredEventTreeMap.get(entry.getKey());
if (list != null) {
list.addAll(entry.getValue());
} else {
expiredEventTreeMap.put(entry.getKey(), entry.getValue());
}
}
eventTreeMap = new TreeMap<Long, ArrayList<StreamEvent>>();
entryIterator = expiredEventTreeMap.entrySet().iterator();
while (entryIterator.hasNext()) {
Map.Entry<Long, ArrayList<StreamEvent>> entry = entryIterator.next();
if (entry.getKey() + k <= greatestTimestamp) {
entryIterator.remove();
ArrayList<StreamEvent> timeEventList = entry.getValue();
lastSentTimeStamp = entry.getKey();
for (StreamEvent aTimeEventList : timeEventList) {
complexEventChunk.add(aTimeEventList);
}
}
}
}
} else {
if(expiredEventTreeMap.size() > 0) {
TreeMap<Long, ArrayList<StreamEvent>> expiredEventTreeMapSnapShot = expiredEventTreeMap;
expiredEventTreeMap = new TreeMap<Long, ArrayList<StreamEvent>>();
onTimerEvent(expiredEventTreeMapSnapShot, nextProcessor);
lastScheduledTimestamp = lastScheduledTimestamp + TIMER_DURATION;
scheduler.notifyAt(lastScheduledTimestamp);
}
}
}
} catch (ArrayIndexOutOfBoundsException ec) {
//This happens due to user specifying an invalid field index.
throw new ExecutionPlanCreationException("The very first parameter must be an Integer with a valid " +
" field index (0 to (fieldsLength-1)).");
}
lock.unlock();
nextProcessor.process(complexEventChunk);
}
|
#vulnerable code
@Override
protected void process(ComplexEventChunk<StreamEvent> streamEventChunk, Processor nextProcessor,
StreamEventCloner streamEventCloner, ComplexEventPopulater complexEventPopulater) {
ComplexEventChunk<StreamEvent> complexEventChunk = new ComplexEventChunk<StreamEvent>(false);
try {
while (streamEventChunk.hasNext()) {
StreamEvent event = streamEventChunk.next();
if(event.getType() != ComplexEvent.Type.TIMER) {
streamEventChunk.remove(); //We might have the rest of the events linked to this event forming a chain.
long timestamp = (Long) timestampExecutor.execute(event);
if (expireFlag) {
if (timestamp < lastSentTimeStamp) {
continue;
}
}
ArrayList<StreamEvent> eventList = eventTreeMap.get(timestamp);
if (eventList == null) {
eventList = new ArrayList<StreamEvent>();
}
eventList.add(event);
eventTreeMap.put(timestamp, eventList);
if (timestamp > greatestTimestamp) {
greatestTimestamp = timestamp;
long minTimestamp = eventTreeMap.firstKey();
if ((greatestTimestamp - minTimestamp) > k) {
if ((greatestTimestamp - minTimestamp) < MAX_K) {
k = greatestTimestamp - minTimestamp;
} else {
k = MAX_K;
}
}
lock.lock();
Iterator<Map.Entry<Long, ArrayList<StreamEvent>>> entryIterator = eventTreeMap.entrySet().iterator();
while (entryIterator.hasNext()) {
Map.Entry<Long, ArrayList<StreamEvent>> entry = entryIterator.next();
ArrayList<StreamEvent> list = expiredEventTreeMap.get(entry.getKey());
if (list != null) {
list.addAll(entry.getValue());
} else {
expiredEventTreeMap.put(entry.getKey(), entry.getValue());
}
}
eventTreeMap = new TreeMap<Long, ArrayList<StreamEvent>>();
entryIterator = expiredEventTreeMap.entrySet().iterator();
while (entryIterator.hasNext()) {
Map.Entry<Long, ArrayList<StreamEvent>> entry = entryIterator.next();
if (entry.getKey() + k <= greatestTimestamp) {
entryIterator.remove();
ArrayList<StreamEvent> timeEventList = entry.getValue();
lastSentTimeStamp = entry.getKey();
for (StreamEvent aTimeEventList : timeEventList) {
complexEventChunk.add(aTimeEventList);
}
}
}
lock.unlock();
}
} else {
onTimerEvent(expiredEventTreeMap, nextProcessor);
lastScheduledTimestamp = lastScheduledTimestamp + TIMER_DURATION;
scheduler.notifyAt(lastScheduledTimestamp);
}
}
} catch (ArrayIndexOutOfBoundsException ec) {
// This happens due to user specifying an invalid field index.
throw new ExecutionPlanCreationException("The very first parameter must be an Integer with a valid " +
" field index (0 to (fieldsLength-1)).");
}
nextProcessor.process(complexEventChunk);
}
#location 32
#vulnerability type THREAD_SAFETY_VIOLATION
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
@Override
protected void process(ComplexEventChunk<StreamEvent> streamEventChunk, Processor nextProcessor,
StreamEventCloner streamEventCloner, ComplexEventPopulater complexEventPopulater) {
ComplexEventChunk<StreamEvent> complexEventChunk = new ComplexEventChunk<StreamEvent>(false);
lock.lock();
try {
while (streamEventChunk.hasNext()) {
StreamEvent event = streamEventChunk.next();
if(event.getType() != ComplexEvent.Type.TIMER) {
streamEventChunk.remove(); //We might have the rest of the events linked to this event forming a chain.
long timestamp = (Long) timestampExecutor.execute(event);
if (expireFlag) {
if (timestamp < lastSentTimeStamp) {
continue;
}
}
ArrayList<StreamEvent> eventList = eventTreeMap.get(timestamp);
if (eventList == null) {
eventList = new ArrayList<StreamEvent>();
}
eventList.add(event);
eventTreeMap.put(timestamp, eventList);
if (timestamp > greatestTimestamp) {
greatestTimestamp = timestamp;
long minTimestamp = eventTreeMap.firstKey();
long timeDifference = greatestTimestamp - minTimestamp;
if (timeDifference > k) {
if (timeDifference < MAX_K) {
k = timeDifference;
} else {
k = MAX_K;
}
}
Iterator<Map.Entry<Long, ArrayList<StreamEvent>>> entryIterator = eventTreeMap.entrySet().iterator();
while (entryIterator.hasNext()) {
Map.Entry<Long, ArrayList<StreamEvent>> entry = entryIterator.next();
ArrayList<StreamEvent> list = expiredEventTreeMap.get(entry.getKey());
if (list != null) {
list.addAll(entry.getValue());
} else {
expiredEventTreeMap.put(entry.getKey(), entry.getValue());
}
}
eventTreeMap = new TreeMap<Long, ArrayList<StreamEvent>>();
entryIterator = expiredEventTreeMap.entrySet().iterator();
while (entryIterator.hasNext()) {
Map.Entry<Long, ArrayList<StreamEvent>> entry = entryIterator.next();
if (entry.getKey() + k <= greatestTimestamp) {
entryIterator.remove();
ArrayList<StreamEvent> timeEventList = entry.getValue();
lastSentTimeStamp = entry.getKey();
for (StreamEvent aTimeEventList : timeEventList) {
complexEventChunk.add(aTimeEventList);
}
}
}
}
} else {
if(expiredEventTreeMap.size() > 0) {
TreeMap<Long, ArrayList<StreamEvent>> expiredEventTreeMapSnapShot = expiredEventTreeMap;
expiredEventTreeMap = new TreeMap<Long, ArrayList<StreamEvent>>();
onTimerEvent(expiredEventTreeMapSnapShot, nextProcessor);
lastScheduledTimestamp = lastScheduledTimestamp + TIMER_DURATION;
scheduler.notifyAt(lastScheduledTimestamp);
}
}
}
} catch (ArrayIndexOutOfBoundsException ec) {
//This happens due to user specifying an invalid field index.
throw new ExecutionPlanCreationException("The very first parameter must be an Integer with a valid " +
" field index (0 to (fieldsLength-1)).");
}
lock.unlock();
nextProcessor.process(complexEventChunk);
}
|
#vulnerable code
@Override
protected void process(ComplexEventChunk<StreamEvent> streamEventChunk, Processor nextProcessor,
StreamEventCloner streamEventCloner, ComplexEventPopulater complexEventPopulater) {
ComplexEventChunk<StreamEvent> complexEventChunk = new ComplexEventChunk<StreamEvent>(false);
try {
while (streamEventChunk.hasNext()) {
StreamEvent event = streamEventChunk.next();
if(event.getType() != ComplexEvent.Type.TIMER) {
streamEventChunk.remove(); //We might have the rest of the events linked to this event forming a chain.
long timestamp = (Long) timestampExecutor.execute(event);
if (expireFlag) {
if (timestamp < lastSentTimeStamp) {
continue;
}
}
ArrayList<StreamEvent> eventList = eventTreeMap.get(timestamp);
if (eventList == null) {
eventList = new ArrayList<StreamEvent>();
}
eventList.add(event);
eventTreeMap.put(timestamp, eventList);
if (timestamp > greatestTimestamp) {
greatestTimestamp = timestamp;
long minTimestamp = eventTreeMap.firstKey();
if ((greatestTimestamp - minTimestamp) > k) {
if ((greatestTimestamp - minTimestamp) < MAX_K) {
k = greatestTimestamp - minTimestamp;
} else {
k = MAX_K;
}
}
lock.lock();
Iterator<Map.Entry<Long, ArrayList<StreamEvent>>> entryIterator = eventTreeMap.entrySet().iterator();
while (entryIterator.hasNext()) {
Map.Entry<Long, ArrayList<StreamEvent>> entry = entryIterator.next();
ArrayList<StreamEvent> list = expiredEventTreeMap.get(entry.getKey());
if (list != null) {
list.addAll(entry.getValue());
} else {
expiredEventTreeMap.put(entry.getKey(), entry.getValue());
}
}
eventTreeMap = new TreeMap<Long, ArrayList<StreamEvent>>();
entryIterator = expiredEventTreeMap.entrySet().iterator();
while (entryIterator.hasNext()) {
Map.Entry<Long, ArrayList<StreamEvent>> entry = entryIterator.next();
if (entry.getKey() + k <= greatestTimestamp) {
entryIterator.remove();
ArrayList<StreamEvent> timeEventList = entry.getValue();
lastSentTimeStamp = entry.getKey();
for (StreamEvent aTimeEventList : timeEventList) {
complexEventChunk.add(aTimeEventList);
}
}
}
lock.unlock();
}
} else {
onTimerEvent(expiredEventTreeMap, nextProcessor);
lastScheduledTimestamp = lastScheduledTimestamp + TIMER_DURATION;
scheduler.notifyAt(lastScheduledTimestamp);
}
}
} catch (ArrayIndexOutOfBoundsException ec) {
// This happens due to user specifying an invalid field index.
throw new ExecutionPlanCreationException("The very first parameter must be an Integer with a valid " +
" field index (0 to (fieldsLength-1)).");
}
nextProcessor.process(complexEventChunk);
}
#location 9
#vulnerability type THREAD_SAFETY_VIOLATION
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
protected ComplexEvent createSendEvent(ComplexEvent originalEvent, Map<Integer, Object> aggregateAttributeValueMap) {
ComplexEvent copiedEvent = cloneComplexEvent(originalEvent);
for (Integer position : aggregateAttributePositionList) {
copiedEvent.getOutputData()[position] = aggregateAttributeValueMap.get(position);
}
return copiedEvent;
}
|
#vulnerable code
protected ComplexEvent createSendEvent(ComplexEvent originalEvent, Map<Integer, Object> aggregateAttributeValueMap) {
ComplexEvent copiedEvent = null;
if (originalEvent instanceof StreamEvent) {
copiedEvent = streamEventCloner.copyStreamEvent((StreamEvent) originalEvent);
} else if (originalEvent instanceof StateEvent) {
copiedEvent = stateEventCloner.copyStateEvent((StateEvent) originalEvent);
}
for (Integer position : aggregateAttributePositionList) {
copiedEvent.getOutputData()[position] = aggregateAttributeValueMap.get(position);
}
return copiedEvent;
}
#location 4
#vulnerability type THREAD_SAFETY_VIOLATION
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
@Override
public void process(ComplexEventChunk complexEventChunk) {
if (trigger) {
ComplexEventChunk<StateEvent> returnEventChunk = new ComplexEventChunk<StateEvent>(true);
StateEvent joinStateEvent = new StateEvent(2, 0);
StreamEvent nextEvent = (StreamEvent) complexEventChunk.getFirst();
complexEventChunk.clear();
while (nextEvent != null) {
StreamEvent streamEvent = nextEvent;
nextEvent = streamEvent.getNext();
streamEvent.setNext(null);
joinLockWrapper.lock();
try {
ComplexEvent.Type eventType = streamEvent.getType();
if (eventType == ComplexEvent.Type.TIMER) {
continue;
} else if (eventType == ComplexEvent.Type.RESET) {
if (outerJoinProcessor && !leftJoinProcessor) {
returnEventChunk.add(joinEventBuilder(null, streamEvent, eventType));
} else if (outerJoinProcessor && leftJoinProcessor) {
returnEventChunk.add(joinEventBuilder(streamEvent, null, eventType));
}
} else {
joinStateEvent.setEvent(matchingStreamIndex, streamEvent);
StreamEvent foundStreamEvent = findableProcessor.find(joinStateEvent, finder);
joinStateEvent.setEvent(matchingStreamIndex, null);
if (foundStreamEvent == null) {
if (outerJoinProcessor && !leftJoinProcessor) {
returnEventChunk.add(joinEventBuilder(foundStreamEvent, streamEvent, eventType));
} else if (outerJoinProcessor && leftJoinProcessor) {
returnEventChunk.add(joinEventBuilder(streamEvent, foundStreamEvent, eventType));
}
} else {
while (foundStreamEvent != null) {
if (!leftJoinProcessor) {
returnEventChunk.add(joinEventBuilder(foundStreamEvent, streamEvent, eventType));
} else {
returnEventChunk.add(joinEventBuilder(streamEvent, foundStreamEvent, eventType));
}
foundStreamEvent = foundStreamEvent.getNext();
}
}
}
} finally {
joinLockWrapper.unlock();
}
if (returnEventChunk.getFirst() != null) {
selector.process(returnEventChunk);
returnEventChunk.clear();
}
}
}
}
|
#vulnerable code
@Override
public void process(ComplexEventChunk complexEventChunk) {
if (trigger) {
ComplexEventChunk<StateEvent> returnEventChunk = new ComplexEventChunk<StateEvent>(true);
StateEvent joinStateEvent = new StateEvent(2, 0);
StreamEvent nextEvent = (StreamEvent) complexEventChunk.getFirst();
complexEventChunk.clear();
while (nextEvent != null) {
StreamEvent streamEvent = nextEvent;
nextEvent = streamEvent.getNext();
streamEvent.setNext(null);
joinLock.lock();
try {
ComplexEvent.Type eventType = streamEvent.getType();
if (eventType == ComplexEvent.Type.TIMER) {
continue;
} else if (eventType == ComplexEvent.Type.RESET) {
if (outerJoinProcessor && !leftJoinProcessor) {
returnEventChunk.add(joinEventBuilder(null, streamEvent, eventType));
} else if (outerJoinProcessor && leftJoinProcessor) {
returnEventChunk.add(joinEventBuilder(streamEvent, null, eventType));
}
} else {
joinStateEvent.setEvent(matchingStreamIndex, streamEvent);
StreamEvent foundStreamEvent = findableProcessor.find(joinStateEvent, finder);
joinStateEvent.setEvent(matchingStreamIndex, null);
if (foundStreamEvent == null) {
if (outerJoinProcessor && !leftJoinProcessor) {
returnEventChunk.add(joinEventBuilder(foundStreamEvent, streamEvent, eventType));
} else if (outerJoinProcessor && leftJoinProcessor) {
returnEventChunk.add(joinEventBuilder(streamEvent, foundStreamEvent, eventType));
}
} else {
while (foundStreamEvent != null) {
if (!leftJoinProcessor) {
returnEventChunk.add(joinEventBuilder(foundStreamEvent, streamEvent, eventType));
} else {
returnEventChunk.add(joinEventBuilder(streamEvent, foundStreamEvent, eventType));
}
foundStreamEvent = foundStreamEvent.getNext();
}
}
}
} finally {
joinLock.unlock();
}
if (returnEventChunk.getFirst() != null) {
selector.process(returnEventChunk);
returnEventChunk.clear();
}
}
} else {
if (preJoinProcessor) {
joinLock.lock();
try {
nextProcessor.process(complexEventChunk);
} finally {
joinLock.unlock();
}
}
}
}
#location 12
#vulnerability type THREAD_SAFETY_VIOLATION
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
@Override
public void process(ComplexEventChunk complexEventChunk) {
if (trigger) {
ComplexEventChunk<StateEvent> returnEventChunk = new ComplexEventChunk<StateEvent>(true);
StateEvent joinStateEvent = new StateEvent(2, 0);
StreamEvent nextEvent = (StreamEvent) complexEventChunk.getFirst();
complexEventChunk.clear();
while (nextEvent != null) {
StreamEvent streamEvent = nextEvent;
nextEvent = streamEvent.getNext();
streamEvent.setNext(null);
joinLockWrapper.lock();
try {
ComplexEvent.Type eventType = streamEvent.getType();
if (eventType == ComplexEvent.Type.TIMER) {
continue;
} else if (eventType == ComplexEvent.Type.RESET) {
if (outerJoinProcessor && !leftJoinProcessor) {
returnEventChunk.add(joinEventBuilder(null, streamEvent, eventType));
} else if (outerJoinProcessor && leftJoinProcessor) {
returnEventChunk.add(joinEventBuilder(streamEvent, null, eventType));
}
} else {
joinStateEvent.setEvent(matchingStreamIndex, streamEvent);
StreamEvent foundStreamEvent = findableProcessor.find(joinStateEvent, finder);
joinStateEvent.setEvent(matchingStreamIndex, null);
if (foundStreamEvent == null) {
if (outerJoinProcessor && !leftJoinProcessor) {
returnEventChunk.add(joinEventBuilder(foundStreamEvent, streamEvent, eventType));
} else if (outerJoinProcessor && leftJoinProcessor) {
returnEventChunk.add(joinEventBuilder(streamEvent, foundStreamEvent, eventType));
}
} else {
while (foundStreamEvent != null) {
if (!leftJoinProcessor) {
returnEventChunk.add(joinEventBuilder(foundStreamEvent, streamEvent, eventType));
} else {
returnEventChunk.add(joinEventBuilder(streamEvent, foundStreamEvent, eventType));
}
foundStreamEvent = foundStreamEvent.getNext();
}
}
}
} finally {
joinLockWrapper.unlock();
}
if (returnEventChunk.getFirst() != null) {
selector.process(returnEventChunk);
returnEventChunk.clear();
}
}
}
}
|
#vulnerable code
@Override
public void process(ComplexEventChunk complexEventChunk) {
if (trigger) {
ComplexEventChunk<StateEvent> returnEventChunk = new ComplexEventChunk<StateEvent>(true);
StateEvent joinStateEvent = new StateEvent(2, 0);
StreamEvent nextEvent = (StreamEvent) complexEventChunk.getFirst();
complexEventChunk.clear();
while (nextEvent != null) {
StreamEvent streamEvent = nextEvent;
nextEvent = streamEvent.getNext();
streamEvent.setNext(null);
joinLock.lock();
try {
ComplexEvent.Type eventType = streamEvent.getType();
if (eventType == ComplexEvent.Type.TIMER) {
continue;
} else if (eventType == ComplexEvent.Type.RESET) {
if (outerJoinProcessor && !leftJoinProcessor) {
returnEventChunk.add(joinEventBuilder(null, streamEvent, eventType));
} else if (outerJoinProcessor && leftJoinProcessor) {
returnEventChunk.add(joinEventBuilder(streamEvent, null, eventType));
}
} else {
joinStateEvent.setEvent(matchingStreamIndex, streamEvent);
StreamEvent foundStreamEvent = findableProcessor.find(joinStateEvent, finder);
joinStateEvent.setEvent(matchingStreamIndex, null);
if (foundStreamEvent == null) {
if (outerJoinProcessor && !leftJoinProcessor) {
returnEventChunk.add(joinEventBuilder(foundStreamEvent, streamEvent, eventType));
} else if (outerJoinProcessor && leftJoinProcessor) {
returnEventChunk.add(joinEventBuilder(streamEvent, foundStreamEvent, eventType));
}
} else {
while (foundStreamEvent != null) {
if (!leftJoinProcessor) {
returnEventChunk.add(joinEventBuilder(foundStreamEvent, streamEvent, eventType));
} else {
returnEventChunk.add(joinEventBuilder(streamEvent, foundStreamEvent, eventType));
}
foundStreamEvent = foundStreamEvent.getNext();
}
}
}
} finally {
joinLock.unlock();
}
if (returnEventChunk.getFirst() != null) {
selector.process(returnEventChunk);
returnEventChunk.clear();
}
}
} else {
if (preJoinProcessor) {
joinLock.lock();
try {
nextProcessor.process(complexEventChunk);
} finally {
joinLock.unlock();
}
}
}
}
#location 13
#vulnerability type THREAD_SAFETY_VIOLATION
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
@Override
public void process(ComplexEventChunk complexEventChunk) {
if (trigger) {
ComplexEventChunk<StateEvent> returnEventChunk = new ComplexEventChunk<StateEvent>(true);
StateEvent joinStateEvent = new StateEvent(2, 0);
StreamEvent nextEvent = (StreamEvent) complexEventChunk.getFirst();
complexEventChunk.clear();
while (nextEvent != null) {
StreamEvent streamEvent = nextEvent;
nextEvent = streamEvent.getNext();
streamEvent.setNext(null);
joinLockWrapper.lock();
try {
ComplexEvent.Type eventType = streamEvent.getType();
if (eventType == ComplexEvent.Type.TIMER) {
continue;
} else if (eventType == ComplexEvent.Type.RESET) {
if (outerJoinProcessor && !leftJoinProcessor) {
returnEventChunk.add(joinEventBuilder(null, streamEvent, eventType));
} else if (outerJoinProcessor && leftJoinProcessor) {
returnEventChunk.add(joinEventBuilder(streamEvent, null, eventType));
}
} else {
joinStateEvent.setEvent(matchingStreamIndex, streamEvent);
StreamEvent foundStreamEvent = findableProcessor.find(joinStateEvent, finder);
joinStateEvent.setEvent(matchingStreamIndex, null);
if (foundStreamEvent == null) {
if (outerJoinProcessor && !leftJoinProcessor) {
returnEventChunk.add(joinEventBuilder(foundStreamEvent, streamEvent, eventType));
} else if (outerJoinProcessor && leftJoinProcessor) {
returnEventChunk.add(joinEventBuilder(streamEvent, foundStreamEvent, eventType));
}
} else {
while (foundStreamEvent != null) {
if (!leftJoinProcessor) {
returnEventChunk.add(joinEventBuilder(foundStreamEvent, streamEvent, eventType));
} else {
returnEventChunk.add(joinEventBuilder(streamEvent, foundStreamEvent, eventType));
}
foundStreamEvent = foundStreamEvent.getNext();
}
}
}
} finally {
joinLockWrapper.unlock();
}
if (returnEventChunk.getFirst() != null) {
selector.process(returnEventChunk);
returnEventChunk.clear();
}
}
}
}
|
#vulnerable code
@Override
public void process(ComplexEventChunk complexEventChunk) {
if (trigger) {
ComplexEventChunk<StateEvent> returnEventChunk = new ComplexEventChunk<StateEvent>(true);
StateEvent joinStateEvent = new StateEvent(2, 0);
StreamEvent nextEvent = (StreamEvent) complexEventChunk.getFirst();
complexEventChunk.clear();
while (nextEvent != null) {
StreamEvent streamEvent = nextEvent;
nextEvent = streamEvent.getNext();
streamEvent.setNext(null);
joinLock.lock();
try {
ComplexEvent.Type eventType = streamEvent.getType();
if (eventType == ComplexEvent.Type.TIMER) {
continue;
} else if (eventType == ComplexEvent.Type.RESET) {
if (outerJoinProcessor && !leftJoinProcessor) {
returnEventChunk.add(joinEventBuilder(null, streamEvent, eventType));
} else if (outerJoinProcessor && leftJoinProcessor) {
returnEventChunk.add(joinEventBuilder(streamEvent, null, eventType));
}
} else {
joinStateEvent.setEvent(matchingStreamIndex, streamEvent);
StreamEvent foundStreamEvent = findableProcessor.find(joinStateEvent, finder);
joinStateEvent.setEvent(matchingStreamIndex, null);
if (foundStreamEvent == null) {
if (outerJoinProcessor && !leftJoinProcessor) {
returnEventChunk.add(joinEventBuilder(foundStreamEvent, streamEvent, eventType));
} else if (outerJoinProcessor && leftJoinProcessor) {
returnEventChunk.add(joinEventBuilder(streamEvent, foundStreamEvent, eventType));
}
} else {
while (foundStreamEvent != null) {
if (!leftJoinProcessor) {
returnEventChunk.add(joinEventBuilder(foundStreamEvent, streamEvent, eventType));
} else {
returnEventChunk.add(joinEventBuilder(streamEvent, foundStreamEvent, eventType));
}
foundStreamEvent = foundStreamEvent.getNext();
}
}
}
} finally {
joinLock.unlock();
}
if (returnEventChunk.getFirst() != null) {
selector.process(returnEventChunk);
returnEventChunk.clear();
}
}
} else {
if (preJoinProcessor) {
joinLock.lock();
try {
nextProcessor.process(complexEventChunk);
} finally {
joinLock.unlock();
}
}
}
}
#location 49
#vulnerability type THREAD_SAFETY_VIOLATION
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
@Override
public void process(ComplexEventChunk complexEventChunk) {
if (trigger) {
ComplexEventChunk<StateEvent> returnEventChunk = new ComplexEventChunk<StateEvent>(true);
StateEvent joinStateEvent = new StateEvent(2, 0);
StreamEvent nextEvent = (StreamEvent) complexEventChunk.getFirst();
complexEventChunk.clear();
while (nextEvent != null) {
StreamEvent streamEvent = nextEvent;
nextEvent = streamEvent.getNext();
streamEvent.setNext(null);
joinLock.lock();
try {
ComplexEvent.Type eventType = streamEvent.getType();
if (eventType == ComplexEvent.Type.TIMER) {
continue;
} else if (eventType == ComplexEvent.Type.RESET) {
if (outerJoinProcessor && !leftJoinProcessor) {
returnEventChunk.add(joinEventBuilder(null, streamEvent, eventType));
} else if (outerJoinProcessor && leftJoinProcessor) {
returnEventChunk.add(joinEventBuilder(streamEvent, null, eventType));
}
} else {
joinStateEvent.setEvent(matchingStreamIndex, streamEvent);
StreamEvent foundStreamEvent = findableProcessor.find(joinStateEvent, finder);
joinStateEvent.setEvent(matchingStreamIndex, null);
if (foundStreamEvent == null) {
if (outerJoinProcessor && !leftJoinProcessor) {
returnEventChunk.add(joinEventBuilder(foundStreamEvent, streamEvent, eventType));
} else if (outerJoinProcessor && leftJoinProcessor) {
returnEventChunk.add(joinEventBuilder(streamEvent, foundStreamEvent, eventType));
}
} else {
while (foundStreamEvent != null) {
if (!leftJoinProcessor) {
returnEventChunk.add(joinEventBuilder(foundStreamEvent, streamEvent, eventType));
} else {
returnEventChunk.add(joinEventBuilder(streamEvent, foundStreamEvent, eventType));
}
foundStreamEvent = foundStreamEvent.getNext();
}
}
}
} finally {
joinLock.unlock();
}
if (returnEventChunk.getFirst() != null) {
selector.process(returnEventChunk);
returnEventChunk.clear();
}
}
} else {
if (preJoinProcessor) {
joinLock.lock();
try {
nextProcessor.process(complexEventChunk);
} finally {
joinLock.unlock();
}
}
}
}
|
#vulnerable code
@Override
public void process(ComplexEventChunk complexEventChunk) {
if (trigger) {
ComplexEventChunk<StateEvent> returnEventChunk = new ComplexEventChunk<StateEvent>(true);
StateEvent joinStateEvent = new StateEvent(2, 0);
StreamEvent nextEvent = (StreamEvent) complexEventChunk.getFirst();
complexEventChunk.clear();
while (nextEvent != null) {
StreamEvent streamEvent = nextEvent;
nextEvent = streamEvent.getNext();
streamEvent.setNext(null);
if (streamEvent.getType() == ComplexEvent.Type.RESET) {
if (outerJoinProcessor && !leftJoinProcessor) {
returnEventChunk.add(joinEventBuilder(null, streamEvent, streamEvent.getType()));
} else if (outerJoinProcessor && leftJoinProcessor) {
returnEventChunk.add(joinEventBuilder(streamEvent, null, streamEvent.getType()));
}
selector.process(returnEventChunk);
returnEventChunk.clear();
continue;
}
joinLock.lock();
try {
ComplexEvent.Type eventType = streamEvent.getType();
if (eventType == ComplexEvent.Type.TIMER) {
continue;
}
joinStateEvent.setEvent(matchingStreamIndex, streamEvent);
StreamEvent foundStreamEvent = findableProcessor.find(joinStateEvent, finder);
joinStateEvent.setEvent(matchingStreamIndex, null);
if (foundStreamEvent == null) {
if (outerJoinProcessor && !leftJoinProcessor) {
returnEventChunk.add(joinEventBuilder(foundStreamEvent, streamEvent, eventType));
} else if (outerJoinProcessor && leftJoinProcessor) {
returnEventChunk.add(joinEventBuilder(streamEvent, foundStreamEvent, eventType));
}
} else {
while (foundStreamEvent != null) {
if (!leftJoinProcessor) {
returnEventChunk.add(joinEventBuilder(foundStreamEvent, streamEvent, eventType));
} else {
returnEventChunk.add(joinEventBuilder(streamEvent, foundStreamEvent, eventType));
}
foundStreamEvent = foundStreamEvent.getNext();
}
}
} finally {
joinLock.unlock();
}
if (returnEventChunk.getFirst() != null) {
selector.process(returnEventChunk);
returnEventChunk.clear();
}
}
}
}
#location 18
#vulnerability type THREAD_SAFETY_VIOLATION
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
@Override
public void process(ComplexEventChunk complexEventChunk) {
if (trigger) {
ComplexEventChunk<StateEvent> returnEventChunk = new ComplexEventChunk<StateEvent>(true);
StateEvent joinStateEvent = new StateEvent(2, 0);
StreamEvent nextEvent = (StreamEvent) complexEventChunk.getFirst();
complexEventChunk.clear();
while (nextEvent != null) {
StreamEvent streamEvent = nextEvent;
nextEvent = streamEvent.getNext();
streamEvent.setNext(null);
joinLockWrapper.lock();
try {
ComplexEvent.Type eventType = streamEvent.getType();
if (eventType == ComplexEvent.Type.TIMER) {
continue;
} else if (eventType == ComplexEvent.Type.RESET) {
if (outerJoinProcessor && !leftJoinProcessor) {
returnEventChunk.add(joinEventBuilder(null, streamEvent, eventType));
} else if (outerJoinProcessor && leftJoinProcessor) {
returnEventChunk.add(joinEventBuilder(streamEvent, null, eventType));
}
} else {
joinStateEvent.setEvent(matchingStreamIndex, streamEvent);
StreamEvent foundStreamEvent = findableProcessor.find(joinStateEvent, finder);
joinStateEvent.setEvent(matchingStreamIndex, null);
if (foundStreamEvent == null) {
if (outerJoinProcessor && !leftJoinProcessor) {
returnEventChunk.add(joinEventBuilder(foundStreamEvent, streamEvent, eventType));
} else if (outerJoinProcessor && leftJoinProcessor) {
returnEventChunk.add(joinEventBuilder(streamEvent, foundStreamEvent, eventType));
}
} else {
while (foundStreamEvent != null) {
if (!leftJoinProcessor) {
returnEventChunk.add(joinEventBuilder(foundStreamEvent, streamEvent, eventType));
} else {
returnEventChunk.add(joinEventBuilder(streamEvent, foundStreamEvent, eventType));
}
foundStreamEvent = foundStreamEvent.getNext();
}
}
}
} finally {
joinLockWrapper.unlock();
}
if (returnEventChunk.getFirst() != null) {
selector.process(returnEventChunk);
returnEventChunk.clear();
}
}
}
}
|
#vulnerable code
@Override
public void process(ComplexEventChunk complexEventChunk) {
if (trigger) {
ComplexEventChunk<StateEvent> returnEventChunk = new ComplexEventChunk<StateEvent>(true);
StateEvent joinStateEvent = new StateEvent(2, 0);
StreamEvent nextEvent = (StreamEvent) complexEventChunk.getFirst();
complexEventChunk.clear();
while (nextEvent != null) {
StreamEvent streamEvent = nextEvent;
nextEvent = streamEvent.getNext();
streamEvent.setNext(null);
joinLock.lock();
try {
ComplexEvent.Type eventType = streamEvent.getType();
if (eventType == ComplexEvent.Type.TIMER) {
continue;
} else if (eventType == ComplexEvent.Type.RESET) {
if (outerJoinProcessor && !leftJoinProcessor) {
returnEventChunk.add(joinEventBuilder(null, streamEvent, eventType));
} else if (outerJoinProcessor && leftJoinProcessor) {
returnEventChunk.add(joinEventBuilder(streamEvent, null, eventType));
}
} else {
joinStateEvent.setEvent(matchingStreamIndex, streamEvent);
StreamEvent foundStreamEvent = findableProcessor.find(joinStateEvent, finder);
joinStateEvent.setEvent(matchingStreamIndex, null);
if (foundStreamEvent == null) {
if (outerJoinProcessor && !leftJoinProcessor) {
returnEventChunk.add(joinEventBuilder(foundStreamEvent, streamEvent, eventType));
} else if (outerJoinProcessor && leftJoinProcessor) {
returnEventChunk.add(joinEventBuilder(streamEvent, foundStreamEvent, eventType));
}
} else {
while (foundStreamEvent != null) {
if (!leftJoinProcessor) {
returnEventChunk.add(joinEventBuilder(foundStreamEvent, streamEvent, eventType));
} else {
returnEventChunk.add(joinEventBuilder(streamEvent, foundStreamEvent, eventType));
}
foundStreamEvent = foundStreamEvent.getNext();
}
}
}
} finally {
joinLock.unlock();
}
if (returnEventChunk.getFirst() != null) {
selector.process(returnEventChunk);
returnEventChunk.clear();
}
}
} else {
if (preJoinProcessor) {
joinLock.lock();
try {
nextProcessor.process(complexEventChunk);
} finally {
joinLock.unlock();
}
}
}
}
#location 7
#vulnerability type THREAD_SAFETY_VIOLATION
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
@Override
protected void process(ComplexEventChunk<StreamEvent> streamEventChunk, Processor nextProcessor,
StreamEventCloner streamEventCloner, ComplexEventPopulater complexEventPopulater) {
ComplexEventChunk<StreamEvent> complexEventChunk = new ComplexEventChunk<StreamEvent>(false);
lock.lock();
try {
while (streamEventChunk.hasNext()) {
StreamEvent event = streamEventChunk.next();
if(event.getType() != ComplexEvent.Type.TIMER) {
streamEventChunk.remove(); //We might have the rest of the events linked to this event forming a chain.
long timestamp = (Long) timestampExecutor.execute(event);
if (expireFlag) {
if (timestamp < lastSentTimeStamp) {
continue;
}
}
ArrayList<StreamEvent> eventList = eventTreeMap.get(timestamp);
if (eventList == null) {
eventList = new ArrayList<StreamEvent>();
}
eventList.add(event);
eventTreeMap.put(timestamp, eventList);
if (timestamp > greatestTimestamp) {
greatestTimestamp = timestamp;
long minTimestamp = eventTreeMap.firstKey();
long timeDifference = greatestTimestamp - minTimestamp;
if (timeDifference > k) {
if (timeDifference < MAX_K) {
k = timeDifference;
} else {
k = MAX_K;
}
}
Iterator<Map.Entry<Long, ArrayList<StreamEvent>>> entryIterator = eventTreeMap.entrySet().iterator();
while (entryIterator.hasNext()) {
Map.Entry<Long, ArrayList<StreamEvent>> entry = entryIterator.next();
ArrayList<StreamEvent> list = expiredEventTreeMap.get(entry.getKey());
if (list != null) {
list.addAll(entry.getValue());
} else {
expiredEventTreeMap.put(entry.getKey(), entry.getValue());
}
}
eventTreeMap = new TreeMap<Long, ArrayList<StreamEvent>>();
entryIterator = expiredEventTreeMap.entrySet().iterator();
while (entryIterator.hasNext()) {
Map.Entry<Long, ArrayList<StreamEvent>> entry = entryIterator.next();
if (entry.getKey() + k <= greatestTimestamp) {
entryIterator.remove();
ArrayList<StreamEvent> timeEventList = entry.getValue();
lastSentTimeStamp = entry.getKey();
for (StreamEvent aTimeEventList : timeEventList) {
complexEventChunk.add(aTimeEventList);
}
}
}
}
} else {
if(expiredEventTreeMap.size() > 0) {
TreeMap<Long, ArrayList<StreamEvent>> expiredEventTreeMapSnapShot = expiredEventTreeMap;
expiredEventTreeMap = new TreeMap<Long, ArrayList<StreamEvent>>();
onTimerEvent(expiredEventTreeMapSnapShot, nextProcessor);
lastScheduledTimestamp = lastScheduledTimestamp + TIMER_DURATION;
scheduler.notifyAt(lastScheduledTimestamp);
}
}
}
} catch (ArrayIndexOutOfBoundsException ec) {
//This happens due to user specifying an invalid field index.
throw new ExecutionPlanCreationException("The very first parameter must be an Integer with a valid " +
" field index (0 to (fieldsLength-1)).");
}
lock.unlock();
nextProcessor.process(complexEventChunk);
}
|
#vulnerable code
@Override
protected void process(ComplexEventChunk<StreamEvent> streamEventChunk, Processor nextProcessor,
StreamEventCloner streamEventCloner, ComplexEventPopulater complexEventPopulater) {
ComplexEventChunk<StreamEvent> complexEventChunk = new ComplexEventChunk<StreamEvent>(false);
try {
while (streamEventChunk.hasNext()) {
StreamEvent event = streamEventChunk.next();
if(event.getType() != ComplexEvent.Type.TIMER) {
streamEventChunk.remove(); //We might have the rest of the events linked to this event forming a chain.
long timestamp = (Long) timestampExecutor.execute(event);
if (expireFlag) {
if (timestamp < lastSentTimeStamp) {
continue;
}
}
ArrayList<StreamEvent> eventList = eventTreeMap.get(timestamp);
if (eventList == null) {
eventList = new ArrayList<StreamEvent>();
}
eventList.add(event);
eventTreeMap.put(timestamp, eventList);
if (timestamp > greatestTimestamp) {
greatestTimestamp = timestamp;
long minTimestamp = eventTreeMap.firstKey();
if ((greatestTimestamp - minTimestamp) > k) {
if ((greatestTimestamp - minTimestamp) < MAX_K) {
k = greatestTimestamp - minTimestamp;
} else {
k = MAX_K;
}
}
lock.lock();
Iterator<Map.Entry<Long, ArrayList<StreamEvent>>> entryIterator = eventTreeMap.entrySet().iterator();
while (entryIterator.hasNext()) {
Map.Entry<Long, ArrayList<StreamEvent>> entry = entryIterator.next();
ArrayList<StreamEvent> list = expiredEventTreeMap.get(entry.getKey());
if (list != null) {
list.addAll(entry.getValue());
} else {
expiredEventTreeMap.put(entry.getKey(), entry.getValue());
}
}
eventTreeMap = new TreeMap<Long, ArrayList<StreamEvent>>();
entryIterator = expiredEventTreeMap.entrySet().iterator();
while (entryIterator.hasNext()) {
Map.Entry<Long, ArrayList<StreamEvent>> entry = entryIterator.next();
if (entry.getKey() + k <= greatestTimestamp) {
entryIterator.remove();
ArrayList<StreamEvent> timeEventList = entry.getValue();
lastSentTimeStamp = entry.getKey();
for (StreamEvent aTimeEventList : timeEventList) {
complexEventChunk.add(aTimeEventList);
}
}
}
lock.unlock();
}
} else {
onTimerEvent(expiredEventTreeMap, nextProcessor);
lastScheduledTimestamp = lastScheduledTimestamp + TIMER_DURATION;
scheduler.notifyAt(lastScheduledTimestamp);
}
}
} catch (ArrayIndexOutOfBoundsException ec) {
// This happens due to user specifying an invalid field index.
throw new ExecutionPlanCreationException("The very first parameter must be an Integer with a valid " +
" field index (0 to (fieldsLength-1)).");
}
nextProcessor.process(complexEventChunk);
}
#location 18
#vulnerability type THREAD_SAFETY_VIOLATION
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
@Override
protected void process(ComplexEventChunk<StreamEvent> streamEventChunk, Processor nextProcessor,
StreamEventCloner streamEventCloner, ComplexEventPopulater complexEventPopulater) {
ComplexEventChunk<StreamEvent> complexEventChunk = new ComplexEventChunk<StreamEvent>(false);
lock.lock();
try {
while (streamEventChunk.hasNext()) {
StreamEvent event = streamEventChunk.next();
if(event.getType() != ComplexEvent.Type.TIMER) {
streamEventChunk.remove(); //We might have the rest of the events linked to this event forming a chain.
long timestamp = (Long) timestampExecutor.execute(event);
if (expireFlag) {
if (timestamp < lastSentTimeStamp) {
continue;
}
}
ArrayList<StreamEvent> eventList = eventTreeMap.get(timestamp);
if (eventList == null) {
eventList = new ArrayList<StreamEvent>();
}
eventList.add(event);
eventTreeMap.put(timestamp, eventList);
if (timestamp > greatestTimestamp) {
greatestTimestamp = timestamp;
long minTimestamp = eventTreeMap.firstKey();
long timeDifference = greatestTimestamp - minTimestamp;
if (timeDifference > k) {
if (timeDifference < MAX_K) {
k = timeDifference;
} else {
k = MAX_K;
}
}
Iterator<Map.Entry<Long, ArrayList<StreamEvent>>> entryIterator = eventTreeMap.entrySet().iterator();
while (entryIterator.hasNext()) {
Map.Entry<Long, ArrayList<StreamEvent>> entry = entryIterator.next();
ArrayList<StreamEvent> list = expiredEventTreeMap.get(entry.getKey());
if (list != null) {
list.addAll(entry.getValue());
} else {
expiredEventTreeMap.put(entry.getKey(), entry.getValue());
}
}
eventTreeMap = new TreeMap<Long, ArrayList<StreamEvent>>();
entryIterator = expiredEventTreeMap.entrySet().iterator();
while (entryIterator.hasNext()) {
Map.Entry<Long, ArrayList<StreamEvent>> entry = entryIterator.next();
if (entry.getKey() + k <= greatestTimestamp) {
entryIterator.remove();
ArrayList<StreamEvent> timeEventList = entry.getValue();
lastSentTimeStamp = entry.getKey();
for (StreamEvent aTimeEventList : timeEventList) {
complexEventChunk.add(aTimeEventList);
}
}
}
}
} else {
if(expiredEventTreeMap.size() > 0) {
TreeMap<Long, ArrayList<StreamEvent>> expiredEventTreeMapSnapShot = expiredEventTreeMap;
expiredEventTreeMap = new TreeMap<Long, ArrayList<StreamEvent>>();
onTimerEvent(expiredEventTreeMapSnapShot, nextProcessor);
lastScheduledTimestamp = lastScheduledTimestamp + TIMER_DURATION;
scheduler.notifyAt(lastScheduledTimestamp);
}
}
}
} catch (ArrayIndexOutOfBoundsException ec) {
//This happens due to user specifying an invalid field index.
throw new ExecutionPlanCreationException("The very first parameter must be an Integer with a valid " +
" field index (0 to (fieldsLength-1)).");
}
lock.unlock();
nextProcessor.process(complexEventChunk);
}
|
#vulnerable code
@Override
protected void process(ComplexEventChunk<StreamEvent> streamEventChunk, Processor nextProcessor,
StreamEventCloner streamEventCloner, ComplexEventPopulater complexEventPopulater) {
ComplexEventChunk<StreamEvent> complexEventChunk = new ComplexEventChunk<StreamEvent>(false);
try {
while (streamEventChunk.hasNext()) {
StreamEvent event = streamEventChunk.next();
if(event.getType() != ComplexEvent.Type.TIMER) {
streamEventChunk.remove(); //We might have the rest of the events linked to this event forming a chain.
long timestamp = (Long) timestampExecutor.execute(event);
if (expireFlag) {
if (timestamp < lastSentTimeStamp) {
continue;
}
}
ArrayList<StreamEvent> eventList = eventTreeMap.get(timestamp);
if (eventList == null) {
eventList = new ArrayList<StreamEvent>();
}
eventList.add(event);
eventTreeMap.put(timestamp, eventList);
if (timestamp > greatestTimestamp) {
greatestTimestamp = timestamp;
long minTimestamp = eventTreeMap.firstKey();
if ((greatestTimestamp - minTimestamp) > k) {
if ((greatestTimestamp - minTimestamp) < MAX_K) {
k = greatestTimestamp - minTimestamp;
} else {
k = MAX_K;
}
}
lock.lock();
Iterator<Map.Entry<Long, ArrayList<StreamEvent>>> entryIterator = eventTreeMap.entrySet().iterator();
while (entryIterator.hasNext()) {
Map.Entry<Long, ArrayList<StreamEvent>> entry = entryIterator.next();
ArrayList<StreamEvent> list = expiredEventTreeMap.get(entry.getKey());
if (list != null) {
list.addAll(entry.getValue());
} else {
expiredEventTreeMap.put(entry.getKey(), entry.getValue());
}
}
eventTreeMap = new TreeMap<Long, ArrayList<StreamEvent>>();
entryIterator = expiredEventTreeMap.entrySet().iterator();
while (entryIterator.hasNext()) {
Map.Entry<Long, ArrayList<StreamEvent>> entry = entryIterator.next();
if (entry.getKey() + k <= greatestTimestamp) {
entryIterator.remove();
ArrayList<StreamEvent> timeEventList = entry.getValue();
lastSentTimeStamp = entry.getKey();
for (StreamEvent aTimeEventList : timeEventList) {
complexEventChunk.add(aTimeEventList);
}
}
}
lock.unlock();
}
} else {
onTimerEvent(expiredEventTreeMap, nextProcessor);
lastScheduledTimestamp = lastScheduledTimestamp + TIMER_DURATION;
scheduler.notifyAt(lastScheduledTimestamp);
}
}
} catch (ArrayIndexOutOfBoundsException ec) {
// This happens due to user specifying an invalid field index.
throw new ExecutionPlanCreationException("The very first parameter must be an Integer with a valid " +
" field index (0 to (fieldsLength-1)).");
}
nextProcessor.process(complexEventChunk);
}
#location 39
#vulnerability type THREAD_SAFETY_VIOLATION
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
@Override
public void process(StreamEvent event) {
StreamEvent head = event; //head of in events
StreamEvent expiredEventTail;
StreamEvent expiredEventHead;
while (event != null) {
processEvent(event);
event = event.getNext();
}
//if window is expired
if (count > length) {
int diff = count - length;
expiredEventTail = removeEventHead;
for (int i = 1; i < diff; i++) {
expiredEventTail = expiredEventTail.getNext();
}
expiredEventHead = removeEventHead;
removeEventHead = expiredEventTail.getNext();
expiredEventTail.setNext(null);
addToLast(head, expiredEventHead);
nextProcessor.process(head); //emit in events and remove events as expired events
count = count - diff;
} else {
nextProcessor.process(head); //emit only in events as window is not expired
}
}
|
#vulnerable code
@Override
public void process(StreamEvent event) {
StreamEvent head = event; //head of in events
StreamEvent expiredEventTail;
StreamEvent expiredEventHead;
while (event != null) {
processEvent(event);
event = event.getNext();
}
//if window is expired
if (count > length) {
int diff = count - length;
expiredEventTail = removeEventHead;
for (int i = 1; i < diff; i++) {
expiredEventTail = expiredEventTail.getNext();
}
expiredEventHead = removeEventHead;
removeEventHead = expiredEventTail.getNext();
expiredEventTail.setNext(null);
head.addToLast(expiredEventHead);
nextProcessor.process(head); //emit in events and remove events as expired events
count = count - diff;
} else {
nextProcessor.process(head); //emit only in events as window is not expired
}
}
#location 18
#vulnerability type NULL_DEREFERENCE
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
@Override
public void process(ComplexEventChunk complexEventChunk) {
if (trigger) {
ComplexEventChunk<StateEvent> returnEventChunk = new ComplexEventChunk<StateEvent>(true);
StateEvent joinStateEvent = new StateEvent(2, 0);
StreamEvent nextEvent = (StreamEvent) complexEventChunk.getFirst();
complexEventChunk.clear();
while (nextEvent != null) {
StreamEvent streamEvent = nextEvent;
nextEvent = streamEvent.getNext();
streamEvent.setNext(null);
joinLock.lock();
try {
ComplexEvent.Type eventType = streamEvent.getType();
if (eventType == ComplexEvent.Type.TIMER) {
continue;
} else if (eventType == ComplexEvent.Type.RESET) {
if (outerJoinProcessor && !leftJoinProcessor) {
returnEventChunk.add(joinEventBuilder(null, streamEvent, eventType));
} else if (outerJoinProcessor && leftJoinProcessor) {
returnEventChunk.add(joinEventBuilder(streamEvent, null, eventType));
}
} else {
joinStateEvent.setEvent(matchingStreamIndex, streamEvent);
StreamEvent foundStreamEvent = findableProcessor.find(joinStateEvent, finder);
joinStateEvent.setEvent(matchingStreamIndex, null);
if (foundStreamEvent == null) {
if (outerJoinProcessor && !leftJoinProcessor) {
returnEventChunk.add(joinEventBuilder(foundStreamEvent, streamEvent, eventType));
} else if (outerJoinProcessor && leftJoinProcessor) {
returnEventChunk.add(joinEventBuilder(streamEvent, foundStreamEvent, eventType));
}
} else {
while (foundStreamEvent != null) {
if (!leftJoinProcessor) {
returnEventChunk.add(joinEventBuilder(foundStreamEvent, streamEvent, eventType));
} else {
returnEventChunk.add(joinEventBuilder(streamEvent, foundStreamEvent, eventType));
}
foundStreamEvent = foundStreamEvent.getNext();
}
}
}
} finally {
joinLock.unlock();
}
if (returnEventChunk.getFirst() != null) {
selector.process(returnEventChunk);
returnEventChunk.clear();
}
}
} else {
if (preJoinProcessor) {
joinLock.lock();
try {
nextProcessor.process(complexEventChunk);
} finally {
joinLock.unlock();
}
}
}
}
|
#vulnerable code
@Override
public void process(ComplexEventChunk complexEventChunk) {
if (trigger) {
ComplexEventChunk<StateEvent> returnEventChunk = new ComplexEventChunk<StateEvent>(true);
StateEvent joinStateEvent = new StateEvent(2, 0);
StreamEvent nextEvent = (StreamEvent) complexEventChunk.getFirst();
complexEventChunk.clear();
while (nextEvent != null) {
StreamEvent streamEvent = nextEvent;
nextEvent = streamEvent.getNext();
streamEvent.setNext(null);
if (streamEvent.getType() == ComplexEvent.Type.RESET) {
if (outerJoinProcessor && !leftJoinProcessor) {
returnEventChunk.add(joinEventBuilder(null, streamEvent, streamEvent.getType()));
} else if (outerJoinProcessor && leftJoinProcessor) {
returnEventChunk.add(joinEventBuilder(streamEvent, null, streamEvent.getType()));
}
selector.process(returnEventChunk);
returnEventChunk.clear();
continue;
}
joinLock.lock();
try {
ComplexEvent.Type eventType = streamEvent.getType();
if (eventType == ComplexEvent.Type.TIMER) {
continue;
}
joinStateEvent.setEvent(matchingStreamIndex, streamEvent);
StreamEvent foundStreamEvent = findableProcessor.find(joinStateEvent, finder);
joinStateEvent.setEvent(matchingStreamIndex, null);
if (foundStreamEvent == null) {
if (outerJoinProcessor && !leftJoinProcessor) {
returnEventChunk.add(joinEventBuilder(foundStreamEvent, streamEvent, eventType));
} else if (outerJoinProcessor && leftJoinProcessor) {
returnEventChunk.add(joinEventBuilder(streamEvent, foundStreamEvent, eventType));
}
} else {
while (foundStreamEvent != null) {
if (!leftJoinProcessor) {
returnEventChunk.add(joinEventBuilder(foundStreamEvent, streamEvent, eventType));
} else {
returnEventChunk.add(joinEventBuilder(streamEvent, foundStreamEvent, eventType));
}
foundStreamEvent = foundStreamEvent.getNext();
}
}
} finally {
joinLock.unlock();
}
if (returnEventChunk.getFirst() != null) {
selector.process(returnEventChunk);
returnEventChunk.clear();
}
}
}
}
#location 37
#vulnerability type THREAD_SAFETY_VIOLATION
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException {
LOGGER.info("CSP-Reporting-Servlet");
try (BufferedReader reader = new BufferedReader(new InputStreamReader(request.getInputStream()))) {
StringBuilder responseBuilder = new StringBuilder();
String inputStr;
while ((inputStr = reader.readLine()) != null) {
responseBuilder.append(inputStr);
}
LOGGER.info("REPORT " + responseBuilder.toString());
JSONObject json = new JSONObject(responseBuilder.toString());
JSONObject cspReport = json.getJSONObject("csp-report");
LOGGER.info("document-uri: " + cspReport.getString("document-uri"));
LOGGER.info("referrer: " + cspReport.getString("referrer"));
LOGGER.info("blocked-uri: " + cspReport.getString("blocked-uri"));
LOGGER.info("violated-directive: " + cspReport.getString("violated-directive"));
LOGGER.info("source-file: " + cspReport.getString("source-file"));
LOGGER.info("script-sample: " + cspReport.getString("script-sample"));
LOGGER.info("line-number: " + cspReport.getString("line-number"));
} catch (IOException | JSONException ex) {
LOGGER.error(ex.getMessage(), ex);
}
}
|
#vulnerable code
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException {
LOGGER.info("CSP-Reporting-Servlet");
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(request.getInputStream()));
StringBuilder responseBuilder = new StringBuilder();
String inputStr;
while ((inputStr = reader.readLine()) != null) {
responseBuilder.append(inputStr);
}
LOGGER.info("REPORT " + responseBuilder.toString());
JSONObject json = new JSONObject(responseBuilder.toString());
JSONObject cspReport = json.getJSONObject("csp-report");
LOGGER.info("document-uri: " + cspReport.getString("document-uri"));
LOGGER.info("referrer: " + cspReport.getString("referrer"));
LOGGER.info("blocked-uri: " + cspReport.getString("blocked-uri"));
LOGGER.info("violated-directive: " + cspReport.getString("violated-directive"));
LOGGER.info("source-file: " + cspReport.getString("source-file"));
LOGGER.info("script-sample: " + cspReport.getString("script-sample"));
LOGGER.info("line-number: " + cspReport.getString("line-number"));
} catch (IOException | JSONException ex) {
LOGGER.error(ex.getMessage(), ex);
}
}
#location 24
#vulnerability type RESOURCE_LEAK
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
protected void registerWithLongPollingServer(AsyncBrowserSession bs) {
JUnitSession.getInstance().getDependency(HttpLongPollingServer.class).registerBrowserSession(bs);
}
|
#vulnerable code
protected void registerWithLongPollingServer(AsyncBrowserSession bs) {
JUnitSession.getInstance().getDependency(AsyncServerSession.class).registerBrowserSession(bs);
}
#location 2
#vulnerability type NULL_DEREFERENCE
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
private void addCallToSuper(ClassScope classScope, GenerationContext context, Collection<Expression> args) {
PreConditions.checkNotNull(classScope);
Option<ClassWrapper> superClass = classScope.getClazz().getSuperclass();
if (superClass.isDefined()) {
if (ClassUtils.isSyntheticType(superClass.getOrThrow())) {
// do not add call to super class is it's a synthetic
return;
}
if (superClass.getOrThrow().getClazz().equals(Object.class)) {
// avoid useless call to super() when the super class is Object
return;
}
printer.print(stJsName(superClass.getOrThrow())).print(".call");
printArguments(Collections.singleton("this"), args, Collections.<String> emptyList(), context);
printer.print(";");
}
}
|
#vulnerable code
private void addCallToSuper(ClassScope classScope, GenerationContext context, Collection<Expression> args) {
PreConditions.checkNotNull(classScope);
if (classScope.getClazz().getSuperclass().isDefined()
&& !classScope.getClazz().getSuperclass().getOrThrow().getClazz().equals(Object.class)) {
// avoid useless call to super() when the super class is Object
printer.print(stJsName(classScope.getClazz().getSuperClass())).print(".call");
printArguments(Collections.singleton("this"), args, Collections.<String> emptyList(), context);
printer.print(";");
}
}
#location 6
#vulnerability type NULL_DEREFERENCE
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
protected void registerWithLongPollingServer(AsyncBrowserSession bs) {
JUnitSession.getInstance().getDependency(HttpLongPollingServer.class).registerBrowserSession(bs);
}
|
#vulnerable code
protected void registerWithLongPollingServer(AsyncBrowserSession bs) {
JUnitSession.getInstance().getDependency(AsyncServerSession.class).registerBrowserSession(bs);
}
#location 2
#vulnerability type NULL_DEREFERENCE
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
@Override
public void visit(ClassOrInterfaceDeclaration n, GenerationContext context) {
printComments(n, context);
ClassScope scope = (ClassScope) scope(n);
if (resolvedType(n) == null) {
// for anonymous object creation the type is set already
resolvedType(n, scope.resolveType(n.getName()).getType());
}
ClassWrapper type = (ClassWrapper)resolvedType(n);
String namespace = null;
if (ClassUtils.isRootType(type)) {
namespace = ClassUtils.getNamespace(type);
if (namespace != null) {
printer.printLn("stjs.ns(\"" + namespace + "\");");
}
}
String className = null;
if(!type.isAnonymousClass()){
if(!type.isInnerType() && !type.isAnonymousClass() && namespace == null){
printer.print("var ");
}
className = names.getTypeName(type);
if(type.isInnerType()){
printer.print("constructor.");
printer.print(type.getSimpleName());
} else {
className = names.getTypeName(type);
printer.print(className);
}
printer.print(" = ");
if(!type.hasAnonymousDeclaringClass()){
printConstructorImplementation(n, context, scope, type.isAnonymousClass());
printer.printLn(";");
}
}else{
printer.print("(");
}
printer.print("stjs.extend(");
if(type.isAnonymousClass() || type.hasAnonymousDeclaringClass()){
printConstructorImplementation(n, context, scope, type.isAnonymousClass());
}else{
printer.print(className);
}
printer.print(", ");
// print the super class
List<TypeWrapper> interfaces;
if(n.isInterface()){
// interfaces do not have super classes. For interfaces, extends actually means implements
printer.print("null, ");
interfaces = getExtends(n);
} else {
List<TypeWrapper> superClass = getExtends(n);
if(superClass.size() > 0){
printer.print(names.getTypeName(superClass.get(0)));
}else{
printer.print("null");
}
printer.print(", ");
interfaces = getImplements(n);
}
// print the implemented interfaces
printer.print("[");
for (int i = 0; i < interfaces.size(); i ++) {
if(i > 0){
printer.print(", ");
}
printer.print(names.getTypeName(interfaces.get(i)));
}
printer.print("], ");
printMembers(n.getMembers(), context);
printer.print(", ");
printTypeDescription(n, context);
printer.print(")");
if(!type.isAnonymousClass()){
printer.printLn(";");
if(!type.isInnerType()){
printGlobals(filterGlobals(n, type), context);
printStaticInitializers(n, context);
printMainMethodCall(n, type);
}
}else {
printer.print(")");
}
}
|
#vulnerable code
@Override
public void visit(ClassOrInterfaceDeclaration n, GenerationContext context) {
printComments(n, context);
ClassScope scope = (ClassScope) scope(n);
if (resolvedType(n) == null) {
// for anonymous object creation the type is set already
resolvedType(n, scope.resolveType(n.getName()).getType());
}
ClassWrapper type = (ClassWrapper)resolvedType(n);
String namespace = null;
if (ClassUtils.isRootType(type)) {
namespace = ClassUtils.getNamespace(type);
if (namespace != null) {
printer.printLn("stjs.ns(\"" + namespace + "\");");
}
}
String className = null;
if(!type.isAnonymousClass()){
if(!type.isInnerType() && !type.isAnonymousClass() && namespace == null){
printer.print("var ");
}
className = names.getTypeName(type);
if(type.isInnerType()){
printer.print("constructor.");
printer.print(type.getSimpleName());
} else {
className = names.getTypeName(type);
printer.print(className);
}
printer.print(" = ");
printConstructorImplementation(n, context, scope, type.isAnonymousClass());
printer.printLn(";");
}else{
printer.print("(");
}
printer.print("stjs.extend(");
if(type.isAnonymousClass()){
printConstructorImplementation(n, context, scope, type.isAnonymousClass());
}else{
printer.print(className);
}
printer.print(", ");
// print the super class
List<TypeWrapper> interfaces;
if(n.isInterface()){
// interfaces do not have super classes. For interfaces, extends actually means implements
printer.print("null, ");
interfaces = getExtends(n);
} else {
List<TypeWrapper> superClass = getExtends(n);
if(superClass.size() > 0){
printer.print(names.getTypeName(superClass.get(0)));
}else{
printer.print("null");
}
printer.print(", ");
interfaces = getImplements(n);
}
// print the implemented interfaces
printer.print("[");
for (int i = 0; i < interfaces.size(); i ++) {
if(i > 0){
printer.print(", ");
}
printer.print(names.getTypeName(interfaces.get(i)));
}
printer.print("], ");
printMembers(n.getMembers(), context);
printer.print(", ");
printTypeDescription(n, context);
printer.print(")");
if(!type.isAnonymousClass()){
printer.printLn(";");
if(!type.isInnerType()){
printGlobals(filterGlobals(n, type), context);
printStaticInitializers(n, context);
printMainMethodCall(n, type);
}
}else {
printer.print(")");
}
}
#location 33
#vulnerability type NULL_DEREFERENCE
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
private void fnStatement() {
move(true);
checkVariableName(this.lookhead);
checkFunctionName(this.lookhead, true);
getCodeGeneratorWithTimes().onConstant(this.lookhead);
move(true);
if (!expectChar('(')) {
reportSyntaxError("expect '(' after function name");
}
lambda(true);
ensureFeatureEnabled(Feature.Assignment);
getCodeGeneratorWithTimes().onAssignment(currentToken().withMeta(Constants.DEFINE_META, true));
}
|
#vulnerable code
private void fnStatement() {
move(true);
checkVariableName();
checkFunctionName();
getCodeGeneratorWithTimes().onConstant(this.lookhead);
move(true);
if (!expectChar('(')) {
reportSyntaxError("expect '(' after function name");
}
lambda(true);
ensureFeatureEnabled(Feature.Assignment);
getCodeGeneratorWithTimes().onAssignment(currentToken().withMeta(Constants.DEFINE_META, true));
}
#location 5
#vulnerability type NULL_DEREFERENCE
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
public CodeGenerator newCodeGenerator(AviatorClassLoader classLoader) {
switch (getOptimizeLevel()) {
case AviatorEvaluator.COMPILE:
ASMCodeGenerator asmCodeGenerator = new ASMCodeGenerator(this, classLoader,
traceOutputStream, getOptionValue(Options.TRACE).bool);
asmCodeGenerator.start();
return asmCodeGenerator;
case AviatorEvaluator.EVAL:
return new OptimizeCodeGenerator(this, classLoader, traceOutputStream,
getOptionValue(Options.TRACE).bool);
default:
throw new IllegalArgumentException("Unknow option " + getOptimizeLevel());
}
}
|
#vulnerable code
public CodeGenerator newCodeGenerator(AviatorClassLoader classLoader) {
switch (getOptimizeLevel()) {
case AviatorEvaluator.COMPILE:
ASMCodeGenerator asmCodeGenerator = new ASMCodeGenerator(this, classLoader,
traceOutputStream, (Boolean) getOption(Options.TRACE));
asmCodeGenerator.start();
return asmCodeGenerator;
case AviatorEvaluator.EVAL:
return new OptimizeCodeGenerator(this, classLoader, traceOutputStream,
(Boolean) getOption(Options.TRACE));
default:
throw new IllegalArgumentException("Unknow option " + getOptimizeLevel());
}
}
#location 5
#vulnerability type NULL_DEREFERENCE
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
@Override
public AviatorObject match(AviatorObject other, Map<String, Object> env) {
switch (other.getAviatorType()) {
case String:
AviatorString aviatorString = (AviatorString) other;
Matcher m = this.pattern.matcher(aviatorString.lexeme);
if (m.matches()) {
boolean captureGroups =
AviatorEvaluator.getOption(Options.PUT_CAPTURING_GROUPS_INTO_ENV);
if (captureGroups && env != null && env != Collections.EMPTY_MAP) {
int groupCount = m.groupCount();
for (int i = 0; i <= groupCount; i++) {
env.put("$" + i, m.group(i));
}
}
return AviatorBoolean.TRUE;
} else {
return AviatorBoolean.FALSE;
}
case JavaType:
AviatorJavaType javaType = (AviatorJavaType) other;
final Object javaValue = javaType.getValue(env);
if (TypeUtils.isString(javaValue)) {
return this.match(new AviatorString(String.valueOf(javaValue)), env);
} else {
throw new ExpressionRuntimeException(
this.desc(env) + " could not match " + other.desc(env));
}
default:
throw new ExpressionRuntimeException(
this.desc(env) + " could not match " + other.desc(env));
}
}
|
#vulnerable code
@Override
public AviatorObject match(AviatorObject other, Map<String, Object> env) {
switch (other.getAviatorType()) {
case String:
AviatorString aviatorString = (AviatorString) other;
Matcher m = this.pattern.matcher(aviatorString.lexeme);
if (m.matches()) {
boolean captureGroups =
AviatorEvaluator.getOption(Options.CAPTURING_GROUPS_IN_PATTERN_MATCHES);
if (captureGroups && env != null && env != Collections.EMPTY_MAP) {
int groupCount = m.groupCount();
for (int i = 0; i <= groupCount; i++) {
env.put("$" + i, m.group(i));
}
}
return AviatorBoolean.TRUE;
} else {
return AviatorBoolean.FALSE;
}
case JavaType:
AviatorJavaType javaType = (AviatorJavaType) other;
final Object javaValue = javaType.getValue(env);
if (TypeUtils.isString(javaValue)) {
return this.match(new AviatorString(String.valueOf(javaValue)), env);
} else {
throw new ExpressionRuntimeException(
this.desc(env) + " could not match " + other.desc(env));
}
default:
throw new ExpressionRuntimeException(
this.desc(env) + " could not match " + other.desc(env));
}
}
#location 9
#vulnerability type NULL_DEREFERENCE
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
public CodeGenerator newCodeGenerator(final AviatorClassLoader classLoader) {
switch (getOptimizeLevel()) {
case AviatorEvaluator.COMPILE:
ASMCodeGenerator asmCodeGenerator =
new ASMCodeGenerator(this, classLoader, this.traceOutputStream);
asmCodeGenerator.start();
return asmCodeGenerator;
case AviatorEvaluator.EVAL:
return new OptimizeCodeGenerator(this, classLoader, this.traceOutputStream);
default:
throw new IllegalArgumentException("Unknow option " + getOptimizeLevel());
}
}
|
#vulnerable code
public CodeGenerator newCodeGenerator(final AviatorClassLoader classLoader) {
switch (getOptimizeLevel()) {
case AviatorEvaluator.COMPILE:
ASMCodeGenerator asmCodeGenerator = new ASMCodeGenerator(this, classLoader,
this.traceOutputStream, getOptionValue(Options.TRACE).bool);
asmCodeGenerator.start();
return asmCodeGenerator;
case AviatorEvaluator.EVAL:
return new OptimizeCodeGenerator(this, classLoader, this.traceOutputStream,
getOptionValue(Options.TRACE).bool);
default:
throw new IllegalArgumentException("Unknow option " + getOptimizeLevel());
}
}
#location 10
#vulnerability type THREAD_SAFETY_VIOLATION
|
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.