input
stringlengths 205
73.3k
| output
stringlengths 64
73.2k
| instruction
stringclasses 1
value |
---|---|---|
#vulnerable code
@Test
@SuppressFBWarnings
public void testTupleSupport() {
db().select("select name, score from person") //
.getAs(String.class, Integer.class) //
.forEach(System.out::println);
}
#location 5
#vulnerability type RESOURCE_LEAK | #fixed code
@Test
@SuppressFBWarnings
public void testTupleSupport() {
try (Database db = db()) {
db.select("select name, score from person") //
.getAs(String.class, Integer.class) //
.forEach(System.out::println);
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Test
public void testCountsOnlyInTransaction() {
db().update("update person set score = -3") //
.transacted() //
.countsOnly() //
.test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) //
.assertValues(3) //
.assertComplete();
}
#location 5
#vulnerability type RESOURCE_LEAK | #fixed code
@Test
public void testCountsOnlyInTransaction() {
try (Database db = db()) {
db.update("update person set score = -3") //
.transacted() //
.countsOnly() //
.test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) //
.assertValues(3) //
.assertComplete();
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Test
public void testSelectUsingName() {
db() //
.select("select score from person where name=:name") //
.parameter("name", "FRED") //
.parameter("name", "JOSEPH") //
.getAs(Integer.class) //
.test() //
.awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) //
.assertValues(21, 34) //
.assertComplete();
}
#location 7
#vulnerability type RESOURCE_LEAK | #fixed code
@Test
public void testSelectUsingName() {
try (Database db = db()) {
db //
.select("select score from person where name=:name") //
.parameter("name", "FRED") //
.parameter("name", "JOSEPH") //
.getAs(Integer.class) //
.test() //
.awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) //
.assertValues(21, 34) //
.assertComplete();
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Test
public void testAutoMapWithUnmappableColumnType() {
db() //
.select("select name from person order by name") //
.autoMap(Person8.class) //
.map(p -> p.name()) //
.test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) //
.assertNoValues() //
.assertError(ClassCastException.class);
}
#location 5
#vulnerability type RESOURCE_LEAK | #fixed code
@Test
public void testAutoMapWithUnmappableColumnType() {
try (Database db = db()) {
db //
.select("select name from person order by name") //
.autoMap(Person8.class) //
.map(p -> p.name()) //
.test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) //
.assertNoValues() //
.assertError(ClassCastException.class);
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Test
public void testInsertNullClobAndReadClobAsString() {
Database db = db();
insertNullClob(db);
db.select("select document from person_clob where name='FRED'") //
.getAsOptional(String.class) //
.test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) //
.assertValue(Optional.<String>empty()) //
.assertComplete();
}
#location 6
#vulnerability type RESOURCE_LEAK | #fixed code
@Test
public void testInsertNullClobAndReadClobAsString() {
try (Database db = db()) {
insertNullClob(db);
db.select("select document from person_clob where name='FRED'") //
.getAsOptional(String.class) //
.test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) //
.assertValue(Optional.<String>empty()) //
.assertComplete();
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Test
public void testUpdateOneRow() {
db().update("update person set score=20 where name='FRED'") //
.counts() //
.test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) //
.assertValue(1) //
.assertComplete();
}
#location 4
#vulnerability type RESOURCE_LEAK | #fixed code
@Test
public void testUpdateOneRow() {
try (Database db = db()) {
db.update("update person set score=20 where name='FRED'") //
.counts() //
.test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) //
.assertValue(1) //
.assertComplete();
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Test
public void testReleasedMemberIsRecreated() throws InterruptedException {
TestScheduler s = new TestScheduler();
AtomicInteger count = new AtomicInteger();
AtomicInteger disposed = new AtomicInteger();
Pool<Integer> pool = NonBlockingPool //
.factory(() -> count.incrementAndGet()) //
.healthy(n -> true) //
.disposer(Consumers.doNothing()) //
.maxSize(1) //
.maxIdleTime(1, TimeUnit.MINUTES) //
.returnToPoolDelayAfterHealthCheckFailure(1, TimeUnit.SECONDS) //
.disposer(n -> disposed.incrementAndGet()) //
.scheduler(s) //
.build();
{
TestSubscriber<Member<Integer>> ts = pool //
.member() //
.repeat() //
.doOnNext(m -> m.checkin()) //
.doOnNext(System.out::println) //
.doOnRequest(t -> System.out.println("test request=" + t)) //
.test(1);
s.triggerActions();
ts.assertValueCount(1);
assertEquals(0, disposed.get());
s.advanceTimeBy(1, TimeUnit.MINUTES);
s.triggerActions();
assertEquals(1, disposed.get());
ts.cancel();
assertEquals(1, disposed.get());
}
{
TestSubscriber<Member<Integer>> ts = pool //
.member() //
.repeat() //
.doOnNext(m -> m.checkin()) //
.doOnNext(System.out::println) //
.doOnRequest(t -> System.out.println("test request=" + t)) //
.test(1);
s.triggerActions();
ts.assertValueCount(1);
assertEquals(1, disposed.get());
s.advanceTimeBy(1, TimeUnit.MINUTES);
s.triggerActions();
assertEquals(2, disposed.get());
}
}
#location 18
#vulnerability type RESOURCE_LEAK | #fixed code
@Test
public void testReleasedMemberIsRecreated() throws Exception {
TestScheduler s = new TestScheduler();
AtomicInteger count = new AtomicInteger();
AtomicInteger disposed = new AtomicInteger();
Pool<Integer> pool = NonBlockingPool //
.factory(() -> count.incrementAndGet()) //
.healthy(n -> true) //
.disposer(Consumers.doNothing()) //
.maxSize(1) //
.maxIdleTime(1, TimeUnit.MINUTES) //
.returnToPoolDelayAfterHealthCheckFailure(1, TimeUnit.SECONDS) //
.disposer(n -> disposed.incrementAndGet()) //
.scheduler(s) //
.build();
{
TestSubscriber<Member<Integer>> ts = pool //
.member() //
.repeat() //
.doOnNext(m -> m.checkin()) //
.doOnNext(System.out::println) //
.doOnRequest(t -> System.out.println("test request=" + t)) //
.test(1);
s.triggerActions();
ts.assertValueCount(1);
assertEquals(0, disposed.get());
s.advanceTimeBy(1, TimeUnit.MINUTES);
s.triggerActions();
assertEquals(1, disposed.get());
ts.cancel();
assertEquals(1, disposed.get());
}
{
TestSubscriber<Member<Integer>> ts = pool //
.member() //
.repeat() //
.doOnNext(m -> m.checkin()) //
.doOnNext(System.out::println) //
.doOnRequest(t -> System.out.println("test request=" + t)) //
.test(1);
s.triggerActions();
ts.assertValueCount(1);
assertEquals(1, disposed.get());
s.advanceTimeBy(1, TimeUnit.MINUTES);
s.triggerActions();
assertEquals(2, disposed.get());
}
{
TestSubscriber<Member<Integer>> ts = pool //
.member() //
.repeat() //
.doOnNext(m -> m.checkin()) //
.doOnNext(System.out::println) //
.doOnRequest(t -> System.out.println("test request=" + t)) //
.test(1);
s.triggerActions();
ts.assertValueCount(1);
assertEquals(2, disposed.get());
}
pool.close();
assertEquals(3, disposed.get());
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Test
public void testSelectTimestampAsDate() {
db() //
.select("select registered from person where name='FRED'") //
.getAs(Date.class) //
.map(d -> d.getTime()) //
.test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) //
.assertValue(FRED_REGISTERED_TIME) //
.assertComplete();
}
#location 5
#vulnerability type RESOURCE_LEAK | #fixed code
@Test
public void testSelectTimestampAsDate() {
try (Database db = db()) {
db //
.select("select registered from person where name='FRED'") //
.getAs(Date.class) //
.map(d -> d.getTime()) //
.test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) //
.assertValue(FRED_REGISTERED_TIME) //
.assertComplete();
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Test(expected = IllegalArgumentException.class)
public void testSelectUsingNameDoesNotExist() {
db() //
.select("select score from person where name=:name") //
.parameters("nam", "FRED");
}
#location 5
#vulnerability type RESOURCE_LEAK | #fixed code
@Test(expected = IllegalArgumentException.class)
public void testSelectUsingNameDoesNotExist() {
try (Database db = db()) {
db //
.select("select score from person where name=:name") //
.parameters("nam", "FRED");
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Test
public void testSelectTimestampAsInstant() {
db() //
.select("select registered from person where name='FRED'") //
.getAs(Instant.class) //
.map(d -> d.toEpochMilli()) //
.test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) //
.assertValue(FRED_REGISTERED_TIME) //
.assertComplete();
}
#location 5
#vulnerability type RESOURCE_LEAK | #fixed code
@Test
public void testSelectTimestampAsInstant() {
try (Database db = db()) {
db //
.select("select registered from person where name='FRED'") //
.getAs(Instant.class) //
.map(d -> d.toEpochMilli()) //
.test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) //
.assertValue(FRED_REGISTERED_TIME) //
.assertComplete();
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Test
public void testSelectTransactedTuple6() {
Tx<Tuple6<String, Integer, String, Integer, String, Integer>> t = db() //
.select("select name, score, name, score, name, score from person where name=?") //
.parameters("FRED") //
.transacted() //
.getAs(String.class, Integer.class, String.class, Integer.class, String.class,
Integer.class) //
.test() //
.awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) //
.assertValueCount(2) //
.assertComplete() //
.values().get(0);
assertEquals("FRED", t.value()._1());
assertEquals(21, (int) t.value()._2());
assertEquals("FRED", t.value()._3());
assertEquals(21, (int) t.value()._4());
assertEquals("FRED", t.value()._5());
assertEquals(21, (int) t.value()._6());
}
#location 5
#vulnerability type RESOURCE_LEAK | #fixed code
@Test
public void testSelectTransactedTuple6() {
try (Database db = db()) {
Tx<Tuple6<String, Integer, String, Integer, String, Integer>> t = db //
.select("select name, score, name, score, name, score from person where name=?") //
.parameters("FRED") //
.transacted() //
.getAs(String.class, Integer.class, String.class, Integer.class, String.class,
Integer.class) //
.test() //
.awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) //
.assertValueCount(2) //
.assertComplete() //
.values().get(0);
assertEquals("FRED", t.value()._1());
assertEquals(21, (int) t.value()._2());
assertEquals("FRED", t.value()._3());
assertEquals(21, (int) t.value()._4());
assertEquals("FRED", t.value()._5());
assertEquals(21, (int) t.value()._6());
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Test
public void testTransactedReturnGeneratedKeys() {
Database db = db();
// note is a table with auto increment
db.update("insert into note(text) values(?)") //
.parameters("HI", "THERE") //
.transacted() //
.returnGeneratedKeys() //
.valuesOnly() //
.getAs(Integer.class)//
.test() //
.awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) //
.assertValues(1, 2) //
.assertComplete();
db.update("insert into note(text) values(?)") //
.parameters("ME", "TOO") //
.transacted() //
.returnGeneratedKeys() //
.valuesOnly() //
.getAs(Integer.class)//
.test() //
.awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) //
.assertValues(3, 4) //
.assertComplete();
}
#location 17
#vulnerability type RESOURCE_LEAK | #fixed code
@Test
public void testTransactedReturnGeneratedKeys() {
try (Database db = db()) {
// note is a table with auto increment
db.update("insert into note(text) values(?)") //
.parameters("HI", "THERE") //
.transacted() //
.returnGeneratedKeys() //
.valuesOnly() //
.getAs(Integer.class)//
.test() //
.awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) //
.assertValues(1, 2) //
.assertComplete();
db.update("insert into note(text) values(?)") //
.parameters("ME", "TOO") //
.transacted() //
.returnGeneratedKeys() //
.valuesOnly() //
.getAs(Integer.class)//
.test() //
.awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) //
.assertValues(3, 4) //
.assertComplete();
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Test
public void testReturnGeneratedKeys() {
Database db = db();
// note is a table with auto increment
db.update("insert into note(text) values(?)") //
.parameters("HI", "THERE") //
.returnGeneratedKeys() //
.getAs(Integer.class)//
.test() //
.awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) //
.assertValues(1, 2) //
.assertComplete();
db.update("insert into note(text) values(?)") //
.parameters("ME", "TOO") //
.returnGeneratedKeys() //
.getAs(Integer.class)//
.test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) //
.assertValues(3, 4) //
.assertComplete();
}
#location 15
#vulnerability type RESOURCE_LEAK | #fixed code
@Test
public void testReturnGeneratedKeys() {
try (Database db = db()) {
// note is a table with auto increment
db.update("insert into note(text) values(?)") //
.parameters("HI", "THERE") //
.returnGeneratedKeys() //
.getAs(Integer.class)//
.test() //
.awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) //
.assertValues(1, 2) //
.assertComplete();
db.update("insert into note(text) values(?)") //
.parameters("ME", "TOO") //
.returnGeneratedKeys() //
.getAs(Integer.class)//
.test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) //
.assertValues(3, 4) //
.assertComplete();
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Test
public void testSelectDependsOnObservable() {
Database db = db();
Observable<Integer> a = db.update("update person set score=100 where name=?") //
.parameter("FRED") //
.counts().toObservable();
db.select("select score from person where name=?") //
.parameter("FRED") //
.dependsOn(a) //
.getAs(Integer.class)//
.test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) //
.assertValues(100) //
.assertComplete();
}
#location 5
#vulnerability type RESOURCE_LEAK | #fixed code
@Test
public void testSelectDependsOnObservable() {
try (Database db = db()) {
Observable<Integer> a = db.update("update person set score=100 where name=?") //
.parameter("FRED") //
.counts().toObservable();
db.select("select score from person where name=?") //
.parameter("FRED") //
.dependsOn(a) //
.getAs(Integer.class)//
.test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) //
.assertValues(100) //
.assertComplete();
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Test
public void testAutoMapWithMixIndexAndName() {
db() //
.select("select name, score from person order by name") //
.autoMap(Person9.class) //
.firstOrError() //
.map(Person9::score) //
.test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) //
.assertValue(21) //
.assertComplete();
}
#location 5
#vulnerability type RESOURCE_LEAK | #fixed code
@Test
public void testAutoMapWithMixIndexAndName() {
try (Database db = db()) {
db //
.select("select name, score from person order by name") //
.autoMap(Person9.class) //
.firstOrError() //
.map(Person9::score) //
.test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) //
.assertValue(21) //
.assertComplete();
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Test
public void testTuple5() {
db() //
.select("select name, score, name, score, name from person order by name") //
.getAs(String.class, Integer.class, String.class, Integer.class, String.class) //
.firstOrError() //
.test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) //
.assertComplete().assertValue(Tuple5.create("FRED", 21, "FRED", 21, "FRED")); //
}
#location 5
#vulnerability type RESOURCE_LEAK | #fixed code
@Test
public void testTuple5() {
try (Database db = db()) {
db //
.select("select name, score, name, score, name from person order by name") //
.getAs(String.class, Integer.class, String.class, Integer.class, String.class) //
.firstOrError() //
.test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) //
.assertComplete().assertValue(Tuple5.create("FRED", 21, "FRED", 21, "FRED")); //
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Test
public void testInsert() {
Database db = db();
db.update("insert into person(name, score) values(?,?)") //
.parameters("DAVE", 12, "ANNE", 18) //
.counts() //
.test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) //
.assertValues(1, 1) //
.assertComplete();
List<Tuple2<String, Integer>> list = db.select("select name, score from person") //
.getAs(String.class, Integer.class) //
.toList() //
.timeout(TIMEOUT_SECONDS, TimeUnit.SECONDS) //
.blockingGet();
assertTrue(list.contains(Tuple2.create("DAVE", 12)));
assertTrue(list.contains(Tuple2.create("ANNE", 18)));
}
#location 11
#vulnerability type RESOURCE_LEAK | #fixed code
@Test
public void testInsert() {
try (Database db = db()) {
db.update("insert into person(name, score) values(?,?)") //
.parameters("DAVE", 12, "ANNE", 18) //
.counts() //
.test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) //
.assertValues(1, 1) //
.assertComplete();
List<Tuple2<String, Integer>> list = db.select("select name, score from person") //
.getAs(String.class, Integer.class) //
.toList() //
.timeout(TIMEOUT_SECONDS, TimeUnit.SECONDS) //
.blockingGet();
assertTrue(list.contains(Tuple2.create("DAVE", 12)));
assertTrue(list.contains(Tuple2.create("ANNE", 18)));
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Test
public void testDrivingSelectWithoutParametersUsingParameterStream() {
db().select("select count(*) from person") //
.parameters(1, 2, 3) //
.getAs(Integer.class) //
.test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) //
.awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) //
.assertValues(3, 3, 3) //
.assertComplete();
}
#location 4
#vulnerability type RESOURCE_LEAK | #fixed code
@Test
public void testDrivingSelectWithoutParametersUsingParameterStream() {
try (Database db = db()) {
db.select("select count(*) from person") //
.parameters(1, 2, 3) //
.getAs(Integer.class) //
.test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) //
.awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) //
.assertValues(3, 3, 3) //
.assertComplete();
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Test
public void testSimplePool() throws InterruptedException {
TestScheduler s = new TestScheduler();
AtomicInteger count = new AtomicInteger();
MemberFactory2<Integer, NonBlockingPool2<Integer>> memberFactory = pool -> new NonBlockingMember2<Integer>(pool,
null);
Pool2<Integer> pool = NonBlockingPool2.factory(() -> count.incrementAndGet()) //
.healthy(n -> true) //
.disposer(n -> {
}) //
.maxSize(3) //
.returnToPoolDelayAfterHealthCheckFailureMs(1000) //
.memberFactory(memberFactory) //
.scheduler(s) //
.build();
TestObserver<Member2<Integer>> ts = pool.member() //
.doOnSuccess(m -> m.checkin()) //
.test();
s.triggerActions();
ts.assertValueCount(1) //
.assertComplete();
}
#location 16
#vulnerability type RESOURCE_LEAK | #fixed code
@Test
public void testSimplePool() throws InterruptedException {
TestScheduler s = new TestScheduler();
AtomicInteger count = new AtomicInteger();
MemberFactory<Integer, NonBlockingPool<Integer>> memberFactory = pool -> new NonBlockingMember<Integer>(pool,
null);
Pool<Integer> pool = NonBlockingPool.factory(() -> count.incrementAndGet()) //
.healthy(n -> true) //
.disposer(n -> {
}) //
.maxSize(3) //
.returnToPoolDelayAfterHealthCheckFailureMs(1000) //
.memberFactory(memberFactory) //
.scheduler(s) //
.build();
TestObserver<Member<Integer>> ts = pool.member() //
.doOnSuccess(m -> m.checkin()) //
.test();
s.triggerActions();
ts.assertValueCount(1) //
.assertComplete();
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Test
public void testUpdateWithinTransactionBatchSize0() {
db() //
.select("select name from person") //
.transactedValuesOnly() //
.getAs(String.class) //
.doOnNext(System.out::println) //
.flatMap(tx -> tx//
.update("update person set score=-1 where name=:name") //
.batchSize(0) //
.parameter("name", tx.value()) //
.valuesOnly() //
.counts()) //
.test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) //
.assertValues(1, 1, 1) //
.assertComplete();
}
#location 6
#vulnerability type RESOURCE_LEAK | #fixed code
@Test
public void testUpdateWithinTransactionBatchSize0() {
try (Database db = db()) {
db //
.select("select name from person") //
.transactedValuesOnly() //
.getAs(String.class) //
.doOnNext(System.out::println) //
.flatMap(tx -> tx//
.update("update person set score=-1 where name=:name") //
.batchSize(0) //
.parameter("name", tx.value()) //
.valuesOnly() //
.counts()) //
.test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) //
.assertValues(1, 1, 1) //
.assertComplete();
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Test
public void testUpdateWithBatchSize2() {
db().update("update person set score=?") //
.batchSize(2) //
.parameters(1, 2, 3, 4) //
.counts() //
.test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) //
.assertValues(3, 3, 3, 3) //
.assertComplete();
}
#location 5
#vulnerability type RESOURCE_LEAK | #fixed code
@Test
public void testUpdateWithBatchSize2() {
try (Database db = db()) {
db.update("update person set score=?") //
.batchSize(2) //
.parameters(1, 2, 3, 4) //
.counts() //
.test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) //
.assertValues(3, 3, 3, 3) //
.assertComplete();
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Test
public void testCallableApiNoParameters() {
Database db = DatabaseCreator.createDerbyWithStoredProcs(1);
db //
.call("call zero()") //
.once().test() //
.awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) //
.assertComplete();
}
#location 5
#vulnerability type RESOURCE_LEAK | #fixed code
@Test
public void testCallableApiNoParameters() {
Database db = DatabaseCreator.createDerbyWithStoredProcs(1);
db //
.call("call zero()") //
.once() //
.test() //
.awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) //
.assertComplete();
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Test
public void testSelectTimestamp() {
db() //
.select("select registered from person where name='FRED'") //
.getAs(Long.class) //
.test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) //
.assertValue(FRED_REGISTERED_TIME) //
.assertComplete();
}
#location 5
#vulnerability type RESOURCE_LEAK | #fixed code
@Test
public void testSelectTimestamp() {
try (Database db = db()) {
db //
.select("select registered from person where name='FRED'") //
.getAs(Long.class) //
.test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) //
.assertValue(FRED_REGISTERED_TIME) //
.assertComplete();
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Test
public void testCallableStatement() {
Database db = db(1);
db.apply(con -> {
try (Statement stmt = con.createStatement()) {
stmt.execute(
"call sqlj.install_jar('target/rxjava2-jdbc-stored-procedure', 'examples',0)");
}
}).blockingAwait(TIMEOUT_SECONDS, TimeUnit.SECONDS);
}
#location 4
#vulnerability type RESOURCE_LEAK | #fixed code
@Test
public void testCallableStatement() {
Database db = DatabaseCreator.createDerby(1);
db.apply(con -> {
try (Statement stmt = con.createStatement()) {
stmt.execute(
"call sqlj.install_jar('target/rxjava2-jdbc-stored-procedure.jar', 'examples',0)");
}
}).blockingAwait(TIMEOUT_SECONDS, TimeUnit.SECONDS);
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Test(expected = IllegalArgumentException.class)
public void testSelectUsingNameWithoutSpecifyingNameThrowsImmediately() {
db() //
.select("select score from person where name=:name") //
.parameters("FRED", "JOSEPH");
}
#location 5
#vulnerability type RESOURCE_LEAK | #fixed code
@Test(expected = IllegalArgumentException.class)
public void testSelectUsingNameWithoutSpecifyingNameThrowsImmediately() {
try (Database db = db()) {
db //
.select("select score from person where name=:name") //
.parameters("FRED", "JOSEPH");
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Test
public void testAutoMapToInterfaceWithIndexTooSmall() {
db() //
.select("select name, score from person order by name") //
.autoMap(Person7.class) //
.firstOrError() //
.map(Person7::examScore) //
.test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) //
.assertNoValues() //
.assertError(ColumnIndexOutOfRangeException.class);
}
#location 5
#vulnerability type RESOURCE_LEAK | #fixed code
@Test
public void testAutoMapToInterfaceWithIndexTooSmall() {
try (Database db = db()) {
db //
.select("select name, score from person order by name") //
.autoMap(Person7.class) //
.firstOrError() //
.map(Person7::examScore) //
.test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) //
.assertNoValues() //
.assertError(ColumnIndexOutOfRangeException.class);
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Test
public void testUpdateTimestampAsInstant() {
Database db = db();
db.update("update person set registered=? where name='FRED'") //
.parameter(Instant.ofEpochMilli(FRED_REGISTERED_TIME)) //
.counts() //
.test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) //
.assertValue(1) //
.assertComplete();
db.select("select registered from person where name='FRED'") //
.getAs(Long.class) //
.test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) //
.assertValue(FRED_REGISTERED_TIME) //
.assertComplete();
}
#location 11
#vulnerability type RESOURCE_LEAK | #fixed code
@Test
public void testUpdateTimestampAsInstant() {
try (Database db = db()) {
db.update("update person set registered=? where name='FRED'") //
.parameter(Instant.ofEpochMilli(FRED_REGISTERED_TIME)) //
.counts() //
.test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) //
.assertValue(1) //
.assertComplete();
db.select("select registered from person where name='FRED'") //
.getAs(Long.class) //
.test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) //
.assertValue(FRED_REGISTERED_TIME) //
.assertComplete();
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Test
public void testConnectionPoolRecylesAlternating() {
TestScheduler s = new TestScheduler();
Database db = DatabaseCreator.create(2, s);
TestSubscriber<Connection> ts = db.connections() //
.doOnNext(System.out::println) //
.doOnNext(c -> {
// release connection for reuse straight away
c.close();
}) //
.test(4); //
s.triggerActions();
ts.assertValueCount(4) //
.assertNotTerminated();
List<Object> list = ts.getEvents().get(0);
// all 4 connections released were the same
System.out.println(list);
assertTrue(list.get(0).hashCode() == list.get(1).hashCode());
assertTrue(list.get(1).hashCode() == list.get(2).hashCode());
assertTrue(list.get(2).hashCode() == list.get(3).hashCode());
}
#location 5
#vulnerability type RESOURCE_LEAK | #fixed code
@Test
public void testConnectionPoolRecylesAlternating() {
TestScheduler s = new TestScheduler();
AtomicInteger count = new AtomicInteger();
Pool<Integer> pool = NonBlockingPool //
.factory(() -> count.incrementAndGet()) //
.healthCheck(n -> true) //
.maxSize(2) //
.maxIdleTime(1, TimeUnit.MINUTES) //
.scheduler(s) //
.build();
TestSubscriber<Integer> ts = new FlowableSingleDeferUntilRequest<>(pool.member()) //
.repeat() //
.doOnNext(m -> m.checkin()) //
.map(m -> m.value()) //
.test(4); //
s.triggerActions();
ts.assertValueCount(4) //
.assertNotTerminated();
List<Object> list = ts.getEvents().get(0);
// all 4 connections released were the same
assertTrue(list.get(0) == list.get(1));
assertTrue(list.get(1) == list.get(2));
assertTrue(list.get(2) == list.get(3));
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Test
public void testUpdateTxPerformed() {
Database db = db();
db.update("update person set score = 1000") //
.transacted() //
.counts() //
.test() //
.awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) //
.assertComplete() //
.assertValueCount(2); //value and complete
db.select("select count(*) from person where score=1000") //
.getAs(Integer.class) //
.test() //
.awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) //
.assertComplete() //
.assertValue(3);
}
#location 13
#vulnerability type RESOURCE_LEAK | #fixed code
@Test
public void testUpdateTxPerformed() {
Database db = db(1);
db.update("update person set score = 1000") //
.transacted() //
.counts() //
.test() //
.awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) //
.assertComplete() //
.assertValueCount(2); // value and complete
db.select("select count(*) from person where score=1000") //
.getAs(Integer.class) //
.test() //
.awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) //
.assertComplete() //
.assertValue(3);
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
public static Database create(int maxSize, boolean big, Scheduler scheduler) {
return Database.from(Pools.nonBlocking() //
.connectionProvider(connectionProvider(nextUrl(), big)) //
.maxPoolSize(maxSize) //
.scheduler(scheduler) //
.build(), () -> scheduler.shutdown());
}
#location 2
#vulnerability type RESOURCE_LEAK | #fixed code
public static Database create(int maxSize, boolean big, Scheduler scheduler) {
NonBlockingConnectionPool pool = Pools.nonBlocking() //
.connectionProvider(connectionProvider(nextUrl(), big)) //
.maxPoolSize(maxSize) //
.scheduler(scheduler) //
.build();
return Database.from(pool, () -> {
pool.close();
scheduler.shutdown();
});
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Test
public void testUpdateBlobWithBlob() throws SQLException {
Database db = db();
Blob blob = new JDBCBlobFile(new File("src/test/resources/big.txt"));
insertPersonBlob(db);
db //
.update("update person_blob set document = :doc") //
.parameter("doc", blob) //
.counts() //
.test() //
.awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) //
.assertValue(1) //
.assertComplete();
}
#location 9
#vulnerability type RESOURCE_LEAK | #fixed code
@Test
public void testUpdateBlobWithBlob() throws SQLException {
try (Database db = db()) {
Blob blob = new JDBCBlobFile(new File("src/test/resources/big.txt"));
insertPersonBlob(db);
db //
.update("update person_blob set document = :doc") //
.parameter("doc", blob) //
.counts() //
.test() //
.awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) //
.assertValue(1) //
.assertComplete();
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Test
public void testSelectTransactedTuple3() {
Tx<Tuple3<String, Integer, String>> t = db() //
.select("select name, score, name from person where name=?") //
.parameters("FRED") //
.transacted() //
.getAs(String.class, Integer.class, String.class) //
.test() //
.awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) //
.assertValueCount(2) //
.assertComplete() //
.values().get(0);
assertEquals("FRED", t.value()._1());
assertEquals(21, (int) t.value()._2());
assertEquals("FRED", t.value()._3());
}
#location 5
#vulnerability type RESOURCE_LEAK | #fixed code
@Test
public void testSelectTransactedTuple3() {
try (Database db = db()) {
Tx<Tuple3<String, Integer, String>> t = db //
.select("select name, score, name from person where name=?") //
.parameters("FRED") //
.transacted() //
.getAs(String.class, Integer.class, String.class) //
.test() //
.awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) //
.assertValueCount(2) //
.assertComplete() //
.values().get(0);
assertEquals("FRED", t.value()._1());
assertEquals(21, (int) t.value()._2());
assertEquals("FRED", t.value()._3());
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Test
public void testHealthCheck() throws InterruptedException {
TestScheduler scheduler = new TestScheduler();
AtomicBoolean once = new AtomicBoolean(true);
NonBlockingConnectionPool pool = Pools //
.nonBlocking() //
.connectionProvider(DatabaseCreator.connectionProvider()) //
.maxIdleTime(10, TimeUnit.MINUTES) //
.idleTimeBeforeHealthCheck(0, TimeUnit.MINUTES) //
.healthy(c -> {
log.debug("doing health check");
return !once.compareAndSet(true, false);
}) //
.returnToPoolDelayAfterHealthCheckFailure(1, TimeUnit.MINUTES) //
.scheduler(scheduler) //
.maxPoolSize(1) //
.build();
try (Database db = Database.from(pool)) {
db.select( //
"select score from person where name=?") //
.parameters("FRED") //
.getAs(Integer.class) //
.test() //
.assertValueCount(1) //
.assertComplete();
TestSubscriber<Integer> ts = db
.select( //
"select score from person where name=?") //
.parameters("FRED") //
.getAs(Integer.class) //
.test() //
.assertValueCount(0);
scheduler.advanceTimeBy(1, TimeUnit.MINUTES);
Thread.sleep(200);
ts.assertValueCount(1);
Thread.sleep(200);
ts.assertValue(21) //
.assertComplete();
}
}
#location 19
#vulnerability type RESOURCE_LEAK | #fixed code
@Test
public void testHealthCheck() throws InterruptedException {
AtomicBoolean once = new AtomicBoolean(true);
testHealthCheck(c -> {
log.debug("doing health check");
return !once.compareAndSet(true, false);
});
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Test
public void testUpdateTimestampParameter() {
Database db = db();
Timestamp t = new Timestamp(1234);
db.update("update person set registered=?") //
.parameter(t) //
.counts() //
.test() //
.awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) //
.assertValue(3) //
.assertComplete();
db.select("select registered from person") //
.getAs(Long.class) //
.firstOrError() //
.test() //
.awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) //
.assertValue(1234L) //
.assertComplete();
}
#location 13
#vulnerability type RESOURCE_LEAK | #fixed code
@Test
public void testUpdateTimestampParameter() {
try (Database db = db()) {
Timestamp t = new Timestamp(1234);
db.update("update person set registered=?") //
.parameter(t) //
.counts() //
.test() //
.awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) //
.assertValue(3) //
.assertComplete();
db.select("select registered from person") //
.getAs(Long.class) //
.firstOrError() //
.test() //
.awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) //
.assertValue(1234L) //
.assertComplete();
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Test(expected = IllegalArgumentException.class)
public void testSelectWithFetchSizeNegative() {
db().select("select score from person order by name") //
.fetchSize(-1);
}
#location 4
#vulnerability type RESOURCE_LEAK | #fixed code
@Test(expected = IllegalArgumentException.class)
public void testSelectWithFetchSizeNegative() {
try (Database db = db()) {
db.select("select score from person order by name") //
.fetchSize(-1);
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Test
public void testSelectUsingQuestionMark() {
db().select("select score from person where name=?") //
.parameters("FRED", "JOSEPH") //
.getAs(Integer.class) //
.test() //
.awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) //
.assertNoErrors() //
.assertValues(21, 34) //
.assertComplete();
}
#location 4
#vulnerability type RESOURCE_LEAK | #fixed code
@Test
public void testSelectUsingQuestionMark() {
try (Database db = db()) {
db.select("select score from person where name=?") //
.parameters("FRED", "JOSEPH") //
.getAs(Integer.class) //
.test() //
.awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) //
.assertNoErrors() //
.assertValues(21, 34) //
.assertComplete();
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Test
public void testSelectDependsOnFlowable() {
Database db = db();
Flowable<Integer> a = db.update("update person set score=100 where name=?") //
.parameter("FRED") //
.counts();
db.select("select score from person where name=?") //
.parameter("FRED") //
.dependsOn(a) //
.getAs(Integer.class)//
.test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) //
.assertValues(100) //
.assertComplete();
}
#location 5
#vulnerability type RESOURCE_LEAK | #fixed code
@Test
public void testSelectDependsOnFlowable() {
try (Database db = db()) {
Flowable<Integer> a = db.update("update person set score=100 where name=?") //
.parameter("FRED") //
.counts();
db.select("select score from person where name=?") //
.parameter("FRED") //
.dependsOn(a) //
.getAs(Integer.class)//
.test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) //
.assertValues(100) //
.assertComplete();
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Test
public void testCallableStatementReturningResultSets() {
Database db = DatabaseCreator.createDerby(1);
db.apply(con -> {
try (Statement stmt = con.createStatement()) {
stmt.execute(
"create table app.person (name varchar(50) primary key, score int not null)");
stmt.execute("insert into app.person(name, score) values('FRED', 24)");
stmt.execute("insert into app.person(name, score) values('SARAH', 26)");
stmt.execute(
"call sqlj.install_jar('target/rxjava2-jdbc-stored-procedure.jar', 'APP.examples',0)");
String sql = "CREATE PROCEDURE APP.RETURNRESULTSETS(in min_score integer)" //
+ " PARAMETER STYLE JAVA" //
+ " LANGUAGE JAVA" //
+ " READS SQL DATA" //
+ " DYNAMIC RESULT SETS 2" //
+ " EXTERNAL NAME" //
+ " 'org.davidmoten.rx.jdbc.StoredProcExample.returnResultSets'";
stmt.execute(sql);
stmt.execute("CALL SYSCS_UTIL.SYSCS_SET_DATABASE_PROPERTY("
+ "'derby.database.classpath', 'APP.examples')");
CallableStatement st = con.prepareCall("call returnResultSets(?)");
st.setInt(1, 0);
boolean hasResultSets = st.execute();
if (hasResultSets) {
ResultSet rs1 = st.getResultSet();
st.getMoreResults(Statement.KEEP_CURRENT_RESULT);
ResultSet rs2 = st.getResultSet();
rs1.next();
assertEquals("FRED", rs1.getString(1));
rs2.next();
assertEquals("SARAH", rs2.getString(1));
}
}
}).blockingAwait(TIMEOUT_SECONDS, TimeUnit.SECONDS);
}
#location 4
#vulnerability type RESOURCE_LEAK | #fixed code
@Test
public void testCallableStatementReturningResultSets() {
Database db = DatabaseCreator.createDerbyWithStoredProcs(1);
db.apply(con -> {
try (Statement stmt = con.createStatement()) {
CallableStatement st = con.prepareCall("call returnResultSets(?)");
st.setInt(1, 0);
boolean hasResultSets = st.execute();
if (hasResultSets) {
ResultSet rs1 = st.getResultSet();
st.getMoreResults(Statement.KEEP_CURRENT_RESULT);
ResultSet rs2 = st.getResultSet();
rs1.next();
assertEquals("FRED", rs1.getString(1));
rs2.next();
assertEquals("SARAH", rs2.getString(1));
}
}
}).blockingAwait(TIMEOUT_SECONDS, TimeUnit.SECONDS);
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
public static Database test(int maxPoolSize) {
Preconditions.checkArgument(maxPoolSize > 0, "maxPoolSize must be greater than 0");
return Database.from( //
Pools.nonBlocking() //
.connectionProvider(testConnectionProvider()) //
.maxPoolSize(maxPoolSize) //
.scheduler(Schedulers.from(Executors.newFixedThreadPool(maxPoolSize))) //
.build());
}
#location 3
#vulnerability type RESOURCE_LEAK | #fixed code
public static Database test(int maxPoolSize) {
Preconditions.checkArgument(maxPoolSize > 0, "maxPoolSize must be greater than 0");
return Database.from( //
Pools.nonBlocking() //
.connectionProvider(testConnectionProvider()) //
.maxPoolSize(maxPoolSize) //
.build());
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Test
public void testDelayedCallsAreNonBlocking() throws InterruptedException {
List<String> list = new CopyOnWriteArrayList<String>();
Database db = db(1); //
db.select("select score from person where name=?") //
.parameter("FRED") //
.getAs(Integer.class) //
.doOnNext(x -> Thread.sleep(1000)) //
.subscribeOn(Schedulers.io()) //
.subscribe();
Thread.sleep(100);
CountDownLatch latch = new CountDownLatch(1);
db.select("select score from person where name=?") //
.parameter("FRED") //
.getAs(Integer.class) //
.doOnNext(x -> list.add("emitted")) //
.doOnNext(x -> log.debug("emitted on " + Thread.currentThread().getName())) //
.doOnNext(x -> latch.countDown()) //
.subscribe();
list.add("subscribed");
assertTrue(latch.await(TIMEOUT_SECONDS, TimeUnit.SECONDS));
assertEquals(Arrays.asList("subscribed", "emitted"), list);
}
#location 6
#vulnerability type RESOURCE_LEAK | #fixed code
@Test
public void testDelayedCallsAreNonBlocking() throws InterruptedException {
List<String> list = new CopyOnWriteArrayList<String>();
try (Database db = db(1)) { //
db.select("select score from person where name=?") //
.parameter("FRED") //
.getAs(Integer.class) //
.doOnNext(x -> Thread.sleep(1000)) //
.subscribeOn(Schedulers.io()) //
.subscribe();
Thread.sleep(100);
CountDownLatch latch = new CountDownLatch(1);
db.select("select score from person where name=?") //
.parameter("FRED") //
.getAs(Integer.class) //
.doOnNext(x -> list.add("emitted")) //
.doOnNext(x -> log.debug("emitted on " + Thread.currentThread().getName())) //
.doOnNext(x -> latch.countDown()) //
.subscribe();
list.add("subscribed");
assertTrue(latch.await(TIMEOUT_SECONDS, TimeUnit.SECONDS));
assertEquals(Arrays.asList("subscribed", "emitted"), list);
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Test
public void testSelectWithoutWhereClause() {
Assert.assertEquals(3, (long) db().select("select name from person") //
.count() //
.blockingGet());
}
#location 4
#vulnerability type RESOURCE_LEAK | #fixed code
@Test
public void testSelectWithoutWhereClause() {
try (Database db = db()) {
Assert.assertEquals(3, (long) db.select("select name from person") //
.count() //
.blockingGet());
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Test
public void testCompleteCompletes() {
Database db = db(1);
db //
.update("update person set score=-3 where name='FRED'") //
.complete() //
.timeout(TIMEOUT_SECONDS, TimeUnit.SECONDS) //
.blockingAwait();
int score = db.select("select score from person where name='FRED'") //
.getAs(Integer.class) //
.timeout(TIMEOUT_SECONDS, TimeUnit.SECONDS) //
.blockingFirst();
assertEquals(-3, score);
}
#location 11
#vulnerability type RESOURCE_LEAK | #fixed code
@Test
public void testCompleteCompletes() {
try (Database db = db(1)) {
db //
.update("update person set score=-3 where name='FRED'") //
.complete() //
.timeout(TIMEOUT_SECONDS, TimeUnit.SECONDS) //
.blockingAwait();
int score = db.select("select score from person where name='FRED'") //
.getAs(Integer.class) //
.timeout(TIMEOUT_SECONDS, TimeUnit.SECONDS) //
.blockingFirst();
assertEquals(-3, score);
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Test
public void testAutoMapToInterface() {
db() //
.select("select name from person") //
.autoMap(Person.class) //
.map(p -> p.name()) //
.test() //
.awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) //
.assertValueCount(3) //
.assertComplete();
}
#location 5
#vulnerability type RESOURCE_LEAK | #fixed code
@Test
public void testAutoMapToInterface() {
try (Database db = db()) {
db //
.select("select name from person") //
.autoMap(Person.class) //
.map(p -> p.name()) //
.test() //
.awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) //
.assertValueCount(3) //
.assertComplete();
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Test(expected = IllegalArgumentException.class)
public void testReturnGeneratedKeysWithBatchSizeShouldThrow() {
Database db = db();
// note is a table with auto increment
db.update("insert into note(text) values(?)") //
.parameters("HI", "THERE") //
.batchSize(2) //
.returnGeneratedKeys();
}
#location 6
#vulnerability type RESOURCE_LEAK | #fixed code
@Test(expected = IllegalArgumentException.class)
public void testReturnGeneratedKeysWithBatchSizeShouldThrow() {
try (Database db = db()) {
// note is a table with auto increment
db.update("insert into note(text) values(?)") //
.parameters("HI", "THERE") //
.batchSize(2) //
.returnGeneratedKeys();
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Test
public void testUpdateThreeRows() {
db().update("update person set score=20") //
.counts() //
.test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) //
.assertValue(3) //
.assertComplete();
}
#location 4
#vulnerability type RESOURCE_LEAK | #fixed code
@Test
public void testUpdateThreeRows() {
try (Database db = db()) {
db.update("update person set score=20") //
.counts() //
.test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) //
.assertValue(3) //
.assertComplete();
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Test
public void testAutoMapWithQueryInAnnotation() {
db().select(Person10.class) //
.get() //
.firstOrError() //
.map(Person10::score) //
.test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) //
.assertValue(21) //
.assertComplete();
}
#location 4
#vulnerability type RESOURCE_LEAK | #fixed code
@Test
public void testAutoMapWithQueryInAnnotation() {
try (Database db = db()) {
db.select(Person10.class) //
.get() //
.firstOrError() //
.map(Person10::score) //
.test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) //
.assertValue(21) //
.assertComplete();
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Test
public void testSelectDependsOnOnSingle() {
Database db = db();
Single<Long> a = db.update("update person set score=100 where name=?") //
.parameter("FRED") //
.counts().count();
db.select("select score from person where name=?") //
.parameter("FRED") //
.dependsOn(a) //
.getAs(Integer.class)//
.test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) //
.assertValues(100) //
.assertComplete();
}
#location 5
#vulnerability type RESOURCE_LEAK | #fixed code
@Test
public void testSelectDependsOnOnSingle() {
try (Database db = db()) {
Single<Long> a = db.update("update person set score=100 where name=?") //
.parameter("FRED") //
.counts().count();
db.select("select score from person where name=?") //
.parameter("FRED") //
.dependsOn(a) //
.getAs(Integer.class)//
.test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) //
.assertValues(100) //
.assertComplete();
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Test
public void testAutoMapToInterfaceWithTwoMethods() {
db() //
.select("select name, score from person order by name") //
.autoMap(Person2.class) //
.firstOrError() //
.map(Person2::score) //
.test() //
.awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) //
.assertValue(21) //
.assertComplete();
}
#location 5
#vulnerability type RESOURCE_LEAK | #fixed code
@Test
public void testAutoMapToInterfaceWithTwoMethods() {
try (Database db = db()) {
db //
.select("select name, score from person order by name") //
.autoMap(Person2.class) //
.firstOrError() //
.map(Person2::score) //
.test() //
.awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) //
.assertValue(21) //
.assertComplete();
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Test
public void testUpdateUtilDateParameter() {
Database db = db();
Date d = new Date(1234);
db.update("update person set registered=?") //
.parameter(d) //
.counts() //
.test() //
.awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) //
.assertValue(3) //
.assertComplete();
db.select("select registered from person") //
.getAs(Long.class) //
.firstOrError() //
.test() //
.awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) //
.assertValue(1234L) //
.assertComplete();
}
#location 13
#vulnerability type RESOURCE_LEAK | #fixed code
@Test
public void testUpdateUtilDateParameter() {
try (Database db = db()) {
Date d = new Date(1234);
db.update("update person set registered=?") //
.parameter(d) //
.counts() //
.test() //
.awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) //
.assertValue(3) //
.assertComplete();
db.select("select registered from person") //
.getAs(Long.class) //
.firstOrError() //
.test() //
.awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) //
.assertValue(1234L) //
.assertComplete();
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Test
public void testSelectAutomappedTransacted() {
db() //
.select("select name, score from person") //
.transacted() //
.autoMap(Person2.class) //
.test() //
.awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) //
.assertValueCount(4) //
.assertComplete();
}
#location 6
#vulnerability type RESOURCE_LEAK | #fixed code
@Test
public void testSelectAutomappedTransacted() {
try (Database db = db()) {
db //
.select("select name, score from person") //
.transacted() //
.autoMap(Person2.class) //
.test() //
.awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) //
.assertValueCount(4) //
.assertComplete();
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Test
public void testUpdateWithinTransaction() {
db() //
.select("select name from person") //
.transactedValuesOnly() //
.getAs(String.class) //
.doOnNext(System.out::println) //
.flatMap(tx -> tx//
.update("update person set score=-1 where name=:name") //
.batchSize(1) //
.parameter("name", tx.value()) //
.valuesOnly() //
.counts()) //
.test() //
.awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) //
.assertValues(1, 1, 1) //
.assertComplete();
}
#location 6
#vulnerability type RESOURCE_LEAK | #fixed code
@Test
public void testUpdateWithinTransaction() {
try (Database db = db()) {
db //
.select("select name from person") //
.transactedValuesOnly() //
.getAs(String.class) //
.doOnNext(System.out::println) //
.flatMap(tx -> tx//
.update("update person set score=-1 where name=:name") //
.batchSize(1) //
.parameter("name", tx.value()) //
.valuesOnly() //
.counts()) //
.test() //
.awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) //
.assertValues(1, 1, 1) //
.assertComplete();
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Test
public void testSelectTransactedTuple7() {
Tx<Tuple7<String, Integer, String, Integer, String, Integer, String>> t = db() //
.select("select name, score, name, score, name, score, name from person where name=?") //
.parameters("FRED") //
.transacted() //
.getAs(String.class, Integer.class, String.class, Integer.class, String.class,
Integer.class, String.class) //
.test() //
.awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) //
.assertValueCount(2) //
.assertComplete() //
.values().get(0);
assertEquals("FRED", t.value()._1());
assertEquals(21, (int) t.value()._2());
assertEquals("FRED", t.value()._3());
assertEquals(21, (int) t.value()._4());
assertEquals("FRED", t.value()._5());
assertEquals(21, (int) t.value()._6());
assertEquals("FRED", t.value()._7());
}
#location 5
#vulnerability type RESOURCE_LEAK | #fixed code
@Test
public void testSelectTransactedTuple7() {
try (Database db = db()) {
Tx<Tuple7<String, Integer, String, Integer, String, Integer, String>> t = db //
.select("select name, score, name, score, name, score, name from person where name=?") //
.parameters("FRED") //
.transacted() //
.getAs(String.class, Integer.class, String.class, Integer.class, String.class,
Integer.class, String.class) //
.test() //
.awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) //
.assertValueCount(2) //
.assertComplete() //
.values().get(0);
assertEquals("FRED", t.value()._1());
assertEquals(21, (int) t.value()._2());
assertEquals("FRED", t.value()._3());
assertEquals(21, (int) t.value()._4());
assertEquals("FRED", t.value()._5());
assertEquals(21, (int) t.value()._6());
assertEquals("FRED", t.value()._7());
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Test
public void testInsertBlobAndReadBlobAsByteArray() {
Database db = db();
insertPersonBlob(db);
db.select("select document from person_blob where name='FRED'") //
.getAs(byte[].class) //
.map(b -> new String(b)) //
.test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) //
.assertValue("some text here") //
.assertComplete();
}
#location 6
#vulnerability type RESOURCE_LEAK | #fixed code
@Test
public void testInsertBlobAndReadBlobAsByteArray() {
try (Database db = db()) {
insertPersonBlob(db);
db.select("select document from person_blob where name='FRED'") //
.getAs(byte[].class) //
.map(b -> new String(b)) //
.test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) //
.assertValue("some text here") //
.assertComplete();
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Test
public void testTupleN() {
db() //
.select("select name, score, name from person order by name") //
.getTupleN() //
.firstOrError().test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) //
.assertComplete() //
.assertValue(TupleN.create("FRED", 21, "FRED")); //
}
#location 5
#vulnerability type RESOURCE_LEAK | #fixed code
@Test
public void testTupleN() {
try (Database db = db()) {
db //
.select("select name, score, name from person order by name") //
.getTupleN() //
.firstOrError().test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) //
.assertComplete() //
.assertValue(TupleN.create("FRED", 21, "FRED")); //
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Test
public void testSelectWithFetchSizeZero() {
db().select("select score from person order by name") //
.fetchSize(0) //
.getAs(Integer.class) //
.test() //
.awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) //
.assertNoErrors() //
.assertValues(21, 34, 25) //
.assertComplete();
}
#location 5
#vulnerability type RESOURCE_LEAK | #fixed code
@Test
public void testSelectWithFetchSizeZero() {
try (Database db = db()) {
db.select("select score from person order by name") //
.fetchSize(0) //
.getAs(Integer.class) //
.test() //
.awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) //
.assertNoErrors() //
.assertValues(21, 34, 25) //
.assertComplete();
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Test
public void testUpdateClobWithClob() throws SQLException {
Database db = db();
Clob clob = new JDBCClobFile(new File("src/test/resources/big.txt"));
insertNullClob(db);
db //
.update("update person_clob set document = :doc") //
.parameter("doc", clob) //
.counts() //
.test() //
.awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) //
.assertValue(1) //
.assertComplete();
}
#location 9
#vulnerability type RESOURCE_LEAK | #fixed code
@Test
public void testUpdateClobWithClob() throws SQLException {
try (Database db = db()) {
Clob clob = new JDBCClobFile(new File("src/test/resources/big.txt"));
insertNullClob(db);
db //
.update("update person_clob set document = :doc") //
.parameter("doc", clob) //
.counts() //
.test() //
.awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) //
.assertValue(1) //
.assertComplete();
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Test
public void testSelectUsingNonBlockingBuilder() {
NonBlockingConnectionPool pool = Pools //
.nonBlocking() //
.connectionProvider(DatabaseCreator.connectionProvider()) //
.maxIdleTime(1, TimeUnit.MINUTES) //
.idleTimeBeforeHealthCheck(1, TimeUnit.MINUTES) //
.healthy(c -> c.prepareStatement("select 1").execute()) //
.maxPoolSize(3) //
.build();
Database.from(pool) //
.select("select score from person where name=?") //
.parameters("FRED", "JOSEPH") //
.getAs(Integer.class) //
.test() //
.assertNoErrors() //
.assertValues(21, 34) //
.assertComplete();
}
#location 12
#vulnerability type RESOURCE_LEAK | #fixed code
@Test
public void testSelectUsingNonBlockingBuilder() {
NonBlockingConnectionPool pool = Pools //
.nonBlocking() //
.connectionProvider(DatabaseCreator.connectionProvider()) //
.maxIdleTime(1, TimeUnit.MINUTES) //
.idleTimeBeforeHealthCheck(1, TimeUnit.MINUTES) //
.healthy(c -> c.prepareStatement("select 1").execute()) //
.maxPoolSize(3) //
.build();
try (Database db = Database.from(pool)) {
db.select("select score from person where name=?") //
.parameters("FRED", "JOSEPH") //
.getAs(Integer.class) //
.test() //
.assertNoErrors() //
.assertValues(21, 34) //
.assertComplete();
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Test
public void testSelectTransactedGetAsOptional() {
List<Tx<Optional<String>>> list = db() //
.select("select name from person where name=?") //
.parameters("FRED") //
.transacted() //
.getAsOptional(String.class) //
.test() //
.awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) //
.assertValueCount(2) //
.assertComplete() //
.values();
assertTrue(list.get(0).isValue());
assertEquals("FRED", list.get(0).value().get());
assertTrue(list.get(1).isComplete());
}
#location 5
#vulnerability type RESOURCE_LEAK | #fixed code
@Test
public void testSelectTransactedGetAsOptional() {
try (Database db = db()) {
List<Tx<Optional<String>>> list = db //
.select("select name from person where name=?") //
.parameters("FRED") //
.transacted() //
.getAsOptional(String.class) //
.test() //
.awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) //
.assertValueCount(2) //
.assertComplete() //
.values();
assertTrue(list.get(0).isValue());
assertEquals("FRED", list.get(0).value().get());
assertTrue(list.get(1).isComplete());
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Test
public void testUpdateCalendarParameter() {
Calendar c = GregorianCalendar.from(ZonedDateTime.parse("2017-03-25T15:37Z"));
Database db = db();
db.update("update person set registered=?") //
.parameter(c) //
.counts() //
.test() //
.awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) //
.assertValue(3) //
.assertComplete();
db.select("select registered from person") //
.getAs(Long.class) //
.firstOrError() //
.test() //
.awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) //
.assertValue(c.getTimeInMillis()) //
.assertComplete();
}
#location 13
#vulnerability type RESOURCE_LEAK | #fixed code
@Test
public void testUpdateCalendarParameter() {
Calendar c = GregorianCalendar.from(ZonedDateTime.parse("2017-03-25T15:37Z"));
try (Database db = db()) {
db.update("update person set registered=?") //
.parameter(c) //
.counts() //
.test() //
.awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) //
.assertValue(3) //
.assertComplete();
db.select("select registered from person") //
.getAs(Long.class) //
.firstOrError() //
.test() //
.awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) //
.assertValue(c.getTimeInMillis()) //
.assertComplete();
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Test(expected = NullPointerException.class)
public void testSelectUsingNullNameInParameter() {
db() //
.select("select score from person where name=:name") //
.parameter(null, "FRED"); //
}
#location 5
#vulnerability type RESOURCE_LEAK | #fixed code
@Test(expected = NullPointerException.class)
public void testSelectUsingNullNameInParameter() {
try (Database db = db()) {
db //
.select("select score from person where name=:name") //
.parameter(null, "FRED"); //
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Test
public void testSelectTransactedTuple2() {
Tx<Tuple2<String, Integer>> t = db() //
.select("select name, score from person where name=?") //
.parameters("FRED") //
.transacted() //
.getAs(String.class, Integer.class) //
.test() //
.awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) //
.assertValueCount(2) //
.assertComplete() //
.values().get(0);
assertEquals("FRED", t.value()._1());
assertEquals(21, (int) t.value()._2());
}
#location 5
#vulnerability type RESOURCE_LEAK | #fixed code
@Test
public void testSelectTransactedTuple2() {
try (Database db = db()) {
Tx<Tuple2<String, Integer>> t = db //
.select("select name, score from person where name=?") //
.parameters("FRED") //
.transacted() //
.getAs(String.class, Integer.class) //
.test() //
.awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) //
.assertValueCount(2) //
.assertComplete() //
.values().get(0);
assertEquals("FRED", t.value()._1());
assertEquals(21, (int) t.value()._2());
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Test
public void testUpdateSqlDateParameter() {
Database db = db();
java.sql.Date t = new java.sql.Date(1234);
db.update("update person set registered=?") //
.parameter(t) //
.counts() //
.test() //
.awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) //
.assertValue(3) //
.assertComplete();
db.select("select registered from person") //
.getAs(Long.class) //
.firstOrError() //
.test() //
.awaitDone(TIMEOUT_SECONDS * 10000, TimeUnit.SECONDS) //
// TODO make a more accurate comparison using the current TZ
.assertValue(x -> Math.abs(x - 1234) <= TimeUnit.HOURS.toMillis(24)) //
.assertComplete();
}
#location 14
#vulnerability type RESOURCE_LEAK | #fixed code
@Test
public void testUpdateSqlDateParameter() {
try (Database db = db()) {
java.sql.Date t = new java.sql.Date(1234);
db.update("update person set registered=?") //
.parameter(t) //
.counts() //
.test() //
.awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) //
.assertValue(3) //
.assertComplete();
db.select("select registered from person") //
.getAs(Long.class) //
.firstOrError() //
.test() //
.awaitDone(TIMEOUT_SECONDS * 10000, TimeUnit.SECONDS) //
// TODO make a more accurate comparison using the current TZ
.assertValue(x -> Math.abs(x - 1234) <= TimeUnit.HOURS.toMillis(24)) //
.assertComplete();
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Test
public void testInsertClobAndReadClobUsingReader() {
Database db = db();
db.update("insert into person_clob(name,document) values(?,?)") //
.parameters("FRED", "some text here") //
.counts() //
.test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) //
.assertValue(1) //
.assertComplete();
db.select("select document from person_clob where name='FRED'") //
.getAs(Reader.class) //
.map(r -> read(r)).test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) //
.assertValue("some text here") //
.assertComplete();
}
#location 11
#vulnerability type RESOURCE_LEAK | #fixed code
@Test
public void testInsertClobAndReadClobUsingReader() {
try (Database db = db()) {
db.update("insert into person_clob(name,document) values(?,?)") //
.parameters("FRED", "some text here") //
.counts() //
.test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) //
.assertValue(1) //
.assertComplete();
db.select("select document from person_clob where name='FRED'") //
.getAs(Reader.class) //
.map(r -> read(r)).test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) //
.assertValue("some text here") //
.assertComplete();
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Test
public void testTransactedReturnGeneratedKeys2() {
Database db = db();
// note is a table with auto increment
Flowable<Integer> a = db.update("insert into note(text) values(?)") //
.parameters("HI", "THERE") //
.transacted() //
.returnGeneratedKeys() //
.valuesOnly() //
.getAs(Integer.class);
db.update("insert into note(text) values(?)") //
.parameters("ME", "TOO") //
.transacted() //
.returnGeneratedKeys() //
.valuesOnly() //
.getAs(Integer.class)//
.startWith(a) //
.test() //
.awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) //
.assertValues(1, 2, 3, 4) //
.assertComplete();
}
#location 13
#vulnerability type RESOURCE_LEAK | #fixed code
@Test
public void testTransactedReturnGeneratedKeys2() {
try (Database db = db()) {
// note is a table with auto increment
Flowable<Integer> a = db.update("insert into note(text) values(?)") //
.parameters("HI", "THERE") //
.transacted() //
.returnGeneratedKeys() //
.valuesOnly() //
.getAs(Integer.class);
db.update("insert into note(text) values(?)") //
.parameters("ME", "TOO") //
.transacted() //
.returnGeneratedKeys() //
.valuesOnly() //
.getAs(Integer.class)//
.startWith(a) //
.test() //
.awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) //
.assertValues(1, 2, 3, 4) //
.assertComplete();
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
public void sendMessage(CommandIssuer issuer, MessageType type, MessageKeyProvider key, String... replacements) {
String message = getLocales().getMessage(issuer, key.getMessageKey());
if (replacements.length > 0) {
message = ACFUtil.replaceStrings(message, replacements);
}
message = getCommandReplacements().replace(message);
MessageFormatter formatter = formatters.getOrDefault(type, defaultFormatter);
if (formatter != null) {
message = formatter.format(message);
}
for (String msg : ACFPatterns.NEWLINE.split(message)) {
issuer.sendMessageInternal(msg);
}
}
#location 11
#vulnerability type NULL_DEREFERENCE | #fixed code
public void sendMessage(CommandIssuer issuer, MessageType type, MessageKeyProvider key, String... replacements) {
String message = formatMessage(issuer, type, key, replacements);
for (String msg : ACFPatterns.NEWLINE.split(message)) {
issuer.sendMessageInternal(ACFUtil.rtrim(msg));
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
public List<String> tabComplete(CommandIssuer issuer, String commandLabel, String[] args)
throws IllegalArgumentException {
commandLabel = commandLabel.toLowerCase();
try {
CommandOperationContext commandOperationContext = preCommandOperation(issuer, commandLabel, args);
final CommandSearch search = findSubCommand(args, true);
String argString = ApacheCommonsLangUtil.join(args, " ").toLowerCase();
final List<String> cmds = new ArrayList<>();
if (search != null) {
cmds.addAll(completeCommand(commandOperationContext, issuer, search.cmd, Arrays.copyOfRange(args, search.argIndex, args.length), commandLabel));
} else if (subCommands.get(UNKNOWN).size() == 1) {
cmds.addAll(completeCommand(commandOperationContext, issuer, Iterables.getOnlyElement(subCommands.get(UNKNOWN)), args, commandLabel));
}
for (Map.Entry<String, RegisteredCommand> entry : subCommands.entries()) {
final String key = entry.getKey();
if (key.startsWith(argString) && !UNKNOWN.equals(key) && !DEFAULT.equals(key)) {
final RegisteredCommand value = entry.getValue();
if (!value.hasPermission(issuer)) {
continue;
}
String prefCommand = value.prefSubCommand;
final String[] psplit = ACFPatterns.SPACE.split(prefCommand);
cmds.add(psplit[args.length - 1]);
}
}
return filterTabComplete(args[args.length - 1], cmds);
} finally {
postCommandOperation();
}
}
#location 10
#vulnerability type NULL_DEREFERENCE | #fixed code
public List<String> tabComplete(CommandIssuer issuer, String commandLabel, String[] args) {
return tabComplete(issuer, commandLabel, args, false);
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
public void stop()
{
if (State.TRANSCRIBING.equals(this.state))
{
if (logger.isDebugEnabled())
logger.debug("Transcriber is now finishing up");
StatsDClient dClient = JigasiBundleActivator.getDataDogClient();
if(dClient != null)
{
dClient.increment(DD_ASPECT_STOP);
if(logger.isDebugEnabled())
{
logger.debug("thrown stat: " + DD_ASPECT_STOP);
}
}
this.state = State.FINISHING_UP;
this.executorService.shutdown();
TranscriptEvent event = this.transcript.ended();
fireTranscribeEvent(event);
ActionServicesHandler.getInstance()
.notifyActionServices(this, event);
checkIfFinishedUp();
}
else
{
logger.warn("Trying to stop Transcriber while it is " +
"already stopped");
}
}
#location 21
#vulnerability type THREAD_SAFETY_VIOLATION | #fixed code
public void stop()
{
if (State.TRANSCRIBING.equals(this.state))
{
if (logger.isDebugEnabled())
logger.debug("Transcriber is now finishing up");
updateDDClient(DD_ASPECT_STOP);
this.state = State.FINISHING_UP;
this.executorService.shutdown();
TranscriptEvent event = this.transcript.ended();
fireTranscribeEvent(event);
ActionServicesHandler.getInstance()
.notifyActionServices(this, event);
checkIfFinishedUp();
}
else
{
logger.warn("Trying to stop Transcriber while it is " +
"already stopped");
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
private void updatePresenceStatusForXmppProviders()
{
SipGateway gateway = ServiceUtils.getService(
osgiContext, SipGateway.class);
int participants = 0;
for(SipGatewaySession ses : gateway.getActiveSessions())
{
participants += ses.getJvbChatRoom().getMembersCount();
}
Collection<ServiceReference<ProtocolProviderService>> refs
= ServiceUtils.getServiceReferences(
osgiContext,
ProtocolProviderService.class);
for (ServiceReference<ProtocolProviderService> ref : refs)
{
updatePresenceStatusForXmppProvider(
gateway, osgiContext.getService(ref), participants);
}
}
#location 9
#vulnerability type NULL_DEREFERENCE | #fixed code
private void updatePresenceStatusForXmppProviders()
{
Collection<ServiceReference<ProtocolProviderService>> refs
= ServiceUtils.getServiceReferences(
osgiContext,
ProtocolProviderService.class);
for (ServiceReference<ProtocolProviderService> ref : refs)
{
updatePresenceStatusForXmppProvider(osgiContext.getService(ref));
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
public void start()
{
if (State.NOT_STARTED.equals(this.state))
{
if (logger.isDebugEnabled())
logger.debug("Transcriber is now transcribing");
StatsDClient dClient = JigasiBundleActivator.getDataDogClient();
if(dClient != null)
{
dClient.increment(DD_ASPECT_START);
if(logger.isDebugEnabled())
{
logger.debug("thrown stat: " + DD_ASPECT_START);
}
}
this.state = State.TRANSCRIBING;
this.executorService = Executors.newSingleThreadExecutor();
List<Participant> participantsClone;
synchronized (this.participants)
{
participantsClone = new ArrayList<>(this.participants.size());
participantsClone.addAll(this.participants.values());
}
TranscriptEvent event
= this.transcript.started(roomName, roomUrl, participantsClone);
if (event != null)
{
fireTranscribeEvent(event);
}
}
else
{
logger.warn("Trying to start Transcriber while it is" +
"already started");
}
}
#location 3
#vulnerability type THREAD_SAFETY_VIOLATION | #fixed code
public void start()
{
if (State.NOT_STARTED.equals(this.state))
{
if (logger.isDebugEnabled())
logger.debug("Transcriber is now transcribing");
updateDDClient(DD_ASPECT_START);
this.state = State.TRANSCRIBING;
this.executorService = Executors.newSingleThreadExecutor();
TranscriptEvent event
= this.transcript.started(roomName, roomUrl, getParticipants());
if (event != null)
{
fireTranscribeEvent(event);
}
}
else
{
logger.warn("Trying to start Transcriber while it is" +
"already started");
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
void notifyCallEnded(String callResource)
{
GatewaySession session;
synchronized (sessions)
{
session = sessions.remove(callResource);
if (session == null)
{
// FIXME: print some gateway ID or provider here
logger.error(
"Call resource not exists for session " + callResource);
return;
}
}
logger.info("Removed session for call " + callResource);
if (callsControl != null)
{
callsControl.callEnded(this, session.getCallResource());
}
}
#location 22
#vulnerability type THREAD_SAFETY_VIOLATION | #fixed code
void notifyCallEnded(String callResource)
{
GatewaySession session;
synchronized (sessions)
{
session = sessions.remove(callResource);
if (session == null)
{
// FIXME: print some gateway ID or provider here
logger.error(
"Call resource not exists for session " + callResource);
return;
}
}
logger.info("Removed session for call " + callResource);
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
public void stop()
{
if (State.TRANSCRIBING.equals(this.state))
{
if (logger.isDebugEnabled())
logger.debug("Transcriber is now finishing up");
StatsDClient dClient = JigasiBundleActivator.getDataDogClient();
if(dClient != null)
{
dClient.increment(DD_ASPECT_STOP);
if(logger.isDebugEnabled())
{
logger.debug("thrown stat: " + DD_ASPECT_STOP);
}
}
this.state = State.FINISHING_UP;
this.executorService.shutdown();
TranscriptEvent event = this.transcript.ended();
fireTranscribeEvent(event);
ActionServicesHandler.getInstance()
.notifyActionServices(this, event);
checkIfFinishedUp();
}
else
{
logger.warn("Trying to stop Transcriber while it is " +
"already stopped");
}
}
#location 19
#vulnerability type THREAD_SAFETY_VIOLATION | #fixed code
public void stop()
{
if (State.TRANSCRIBING.equals(this.state))
{
if (logger.isDebugEnabled())
logger.debug("Transcriber is now finishing up");
updateDDClient(DD_ASPECT_STOP);
this.state = State.FINISHING_UP;
this.executorService.shutdown();
TranscriptEvent event = this.transcript.ended();
fireTranscribeEvent(event);
ActionServicesHandler.getInstance()
.notifyActionServices(this, event);
checkIfFinishedUp();
}
else
{
logger.warn("Trying to stop Transcriber while it is " +
"already stopped");
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
private void updatePresenceStatusForXmppProvider(
ProtocolProviderService pps)
{
SipGateway gateway = ServiceUtils.getService(
osgiContext, SipGateway.class);
int participants = 0;
for(SipGatewaySession ses : gateway.getActiveSessions())
{
participants += ses.getJvbChatRoom().getMembersCount();
}
updatePresenceStatusForXmppProvider(gateway, pps, participants);
}
#location 10
#vulnerability type NULL_DEREFERENCE | #fixed code
private void updatePresenceStatusForXmppProvider(
ProtocolProviderService pps)
{
SipGateway sipGateway= ServiceUtils.getService(
osgiContext, SipGateway.class);
TranscriptionGateway transcriptionGateway = ServiceUtils.getService(
osgiContext, TranscriptionGateway.class);
List<AbstractGatewaySession> sessions = new ArrayList<>();
if(sipGateway != null)
{
sessions.addAll(sipGateway.getActiveSessions());
}
if(transcriptionGateway != null)
{
sessions.addAll(transcriptionGateway.getActiveSessions());
}
int sesCount = 0;
int participantCount = 0;
for(AbstractGatewaySession ses : sessions)
{
ChatRoom room = ses.getJvbChatRoom();
if(room != null)
{
participantCount += ses.getJvbChatRoom().getMembersCount();
sesCount++;
}
else
{
logger.warn("non-active session in active session list");
}
}
updatePresenceStatusForXmppProvider(pps, participantCount, sesCount);
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
public void stop()
{
if (State.TRANSCRIBING.equals(this.state))
{
if (logger.isDebugEnabled())
logger.debug("Transcriber is now finishing up");
StatsDClient dClient = JigasiBundleActivator.getDataDogClient();
if(dClient != null)
{
dClient.increment(DD_ASPECT_STOP);
if(logger.isDebugEnabled())
{
logger.debug("thrown stat: " + DD_ASPECT_STOP);
}
}
this.state = State.FINISHING_UP;
this.executorService.shutdown();
TranscriptEvent event = this.transcript.ended();
fireTranscribeEvent(event);
ActionServicesHandler.getInstance()
.notifyActionServices(this, event);
checkIfFinishedUp();
}
else
{
logger.warn("Trying to stop Transcriber while it is " +
"already stopped");
}
}
#location 3
#vulnerability type THREAD_SAFETY_VIOLATION | #fixed code
public void stop()
{
if (State.TRANSCRIBING.equals(this.state))
{
if (logger.isDebugEnabled())
logger.debug("Transcriber is now finishing up");
updateDDClient(DD_ASPECT_STOP);
this.state = State.FINISHING_UP;
this.executorService.shutdown();
TranscriptEvent event = this.transcript.ended();
fireTranscribeEvent(event);
ActionServicesHandler.getInstance()
.notifyActionServices(this, event);
checkIfFinishedUp();
}
else
{
logger.warn("Trying to stop Transcriber while it is " +
"already stopped");
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
void setPresenceStatus(String statusMsg)
{
if (mucRoom != null)
{
// Send presence status update
OperationSetJitsiMeetTools jitsiMeetTools
= xmppProvider.getOperationSet(
OperationSetJitsiMeetTools.class);
jitsiMeetTools.setPresenceStatus(mucRoom, statusMsg);
}
}
#location 7
#vulnerability type THREAD_SAFETY_VIOLATION | #fixed code
void sendPresenceExtension(ExtensionElement extension)
{
if (mucRoom != null)
{
// Send presence update
OperationSetJitsiMeetTools jitsiMeetTools
= xmppProvider.getOperationSet(
OperationSetJitsiMeetTools.class);
jitsiMeetTools.sendPresenceExtension(mucRoom, extension);
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
void checkIfFinishedUp()
{
if (State.FINISHING_UP.equals(this.state))
{
synchronized (this.participants)
{
for (Participant participant : participants.values())
{
if (!participant.isCompleted())
{
return;
}
}
}
if (logger.isDebugEnabled())
logger.debug(getDebugName() + ": transcriber is now finished");
this.state = State.FINISHED;
for (TranscriptionListener listener : listeners)
{
listener.completed();
}
}
}
#location 3
#vulnerability type THREAD_SAFETY_VIOLATION | #fixed code
void checkIfFinishedUp()
{
if (State.FINISHING_UP.equals(this.state))
{
synchronized (this.participants)
{
for (Participant participant : participants.values())
{
if (!participant.isCompleted())
{
logger.debug(
participant.getDebugName()
+ " is still not finished");
return;
}
}
}
if (logger.isDebugEnabled())
logger.debug(getDebugName() + ": transcriber is now finished");
this.state = State.FINISHED;
for (TranscriptionListener listener : listeners)
{
listener.completed();
}
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
public void start()
{
if (State.NOT_STARTED.equals(this.state))
{
if (logger.isDebugEnabled())
logger.debug("Transcriber is now transcribing");
StatsDClient dClient = JigasiBundleActivator.getDataDogClient();
if(dClient != null)
{
dClient.increment(DD_ASPECT_START);
if(logger.isDebugEnabled())
{
logger.debug("thrown stat: " + DD_ASPECT_START);
}
}
this.state = State.TRANSCRIBING;
this.executorService = Executors.newSingleThreadExecutor();
List<Participant> participantsClone;
synchronized (this.participants)
{
participantsClone = new ArrayList<>(this.participants.size());
participantsClone.addAll(this.participants.values());
}
TranscriptEvent event
= this.transcript.started(roomName, roomUrl, participantsClone);
if (event != null)
{
fireTranscribeEvent(event);
}
}
else
{
logger.warn("Trying to start Transcriber while it is" +
"already started");
}
}
#location 19
#vulnerability type THREAD_SAFETY_VIOLATION | #fixed code
public void start()
{
if (State.NOT_STARTED.equals(this.state))
{
if (logger.isDebugEnabled())
logger.debug("Transcriber is now transcribing");
updateDDClient(DD_ASPECT_START);
this.state = State.TRANSCRIBING;
this.executorService = Executors.newSingleThreadExecutor();
TranscriptEvent event
= this.transcript.started(roomName, roomUrl, getParticipants());
if (event != null)
{
fireTranscribeEvent(event);
}
}
else
{
logger.warn("Trying to start Transcriber while it is" +
"already started");
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
void setPresenceStatus(String statusMsg)
{
if (mucRoom != null)
{
// Send presence status update
OperationSetJitsiMeetTools jitsiMeetTools
= xmppProvider.getOperationSet(
OperationSetJitsiMeetTools.class);
jitsiMeetTools.setPresenceStatus(mucRoom, statusMsg);
}
}
#location 10
#vulnerability type THREAD_SAFETY_VIOLATION | #fixed code
void sendPresenceExtension(ExtensionElement extension)
{
if (mucRoom != null)
{
// Send presence update
OperationSetJitsiMeetTools jitsiMeetTools
= xmppProvider.getOperationSet(
OperationSetJitsiMeetTools.class);
jitsiMeetTools.sendPresenceExtension(mucRoom, extension);
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
public synchronized void stop()
{
if (!started)
{
logger.error(this.callContext + " Already stopped !");
return;
}
started = false;
JigasiBundleActivator.osgiContext.removeServiceListener(this);
if (telephony != null)
{
telephony.removeCallListener(callListener);
telephony = null;
}
if (muteIqHandler != null)
{
// we need to remove it from the connection, or we break some Smack
// weak references map where the key is connection and the value
// holds a connection and we leak connection/conferences.
getConnection().unregisterIQRequestHandler(muteIqHandler);
}
gatewaySession.onJvbConferenceWillStop(this, endReasonCode, endReason);
leaveConferenceRoom();
if (jvbCall != null)
{
CallManager.hangupCall(jvbCall, true);
}
if (xmppProvider != null)
{
xmppProvider.removeRegistrationStateChangeListener(this);
// in case we were not able to create jvb call, unit tests case
if (jvbCall == null)
{
logger.info(
callContext + " Removing account " + xmppAccount);
xmppProviderFactory.unloadAccount(xmppAccount);
}
xmppProviderFactory = null;
xmppAccount = null;
xmppProvider = null;
}
gatewaySession.onJvbConferenceStopped(this, endReasonCode, endReason);
setJvbCall(null);
}
#location 24
#vulnerability type NULL_DEREFERENCE | #fixed code
public synchronized void stop()
{
if (!started)
{
logger.error(this.callContext + " Already stopped !");
return;
}
started = false;
JigasiBundleActivator.osgiContext.removeServiceListener(this);
if (telephony != null)
{
telephony.removeCallListener(callListener);
telephony = null;
}
if (muteIqHandler != null)
{
// we need to remove it from the connection, or we break some Smack
// weak references map where the key is connection and the value
// holds a connection and we leak connection/conferences.
XMPPConnection connection = getConnection();
if (connection != null)
{
connection.unregisterIQRequestHandler(muteIqHandler);
}
}
gatewaySession.onJvbConferenceWillStop(this, endReasonCode, endReason);
leaveConferenceRoom();
if (jvbCall != null)
{
CallManager.hangupCall(jvbCall, true);
}
if (xmppProvider != null)
{
xmppProvider.removeRegistrationStateChangeListener(this);
// in case we were not able to create jvb call, unit tests case
if (jvbCall == null)
{
logger.info(
callContext + " Removing account " + xmppAccount);
xmppProviderFactory.unloadAccount(xmppAccount);
}
xmppProviderFactory = null;
xmppAccount = null;
xmppProvider = null;
}
gatewaySession.onJvbConferenceStopped(this, endReasonCode, endReason);
setJvbCall(null);
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
public void start()
{
if (State.NOT_STARTED.equals(this.state))
{
if (logger.isDebugEnabled())
logger.debug("Transcriber is now transcribing");
StatsDClient dClient = JigasiBundleActivator.getDataDogClient();
if(dClient != null)
{
dClient.increment(DD_ASPECT_START);
if(logger.isDebugEnabled())
{
logger.debug("thrown stat: " + DD_ASPECT_START);
}
}
this.state = State.TRANSCRIBING;
this.executorService = Executors.newSingleThreadExecutor();
List<Participant> participantsClone;
synchronized (this.participants)
{
participantsClone = new ArrayList<>(this.participants.size());
participantsClone.addAll(this.participants.values());
}
TranscriptEvent event
= this.transcript.started(roomName, roomUrl, participantsClone);
if (event != null)
{
fireTranscribeEvent(event);
}
}
else
{
logger.warn("Trying to start Transcriber while it is" +
"already started");
}
}
#location 29
#vulnerability type THREAD_SAFETY_VIOLATION | #fixed code
public void start()
{
if (State.NOT_STARTED.equals(this.state))
{
if (logger.isDebugEnabled())
logger.debug("Transcriber is now transcribing");
updateDDClient(DD_ASPECT_START);
this.state = State.TRANSCRIBING;
this.executorService = Executors.newSingleThreadExecutor();
TranscriptEvent event
= this.transcript.started(roomName, roomUrl, getParticipants());
if (event != null)
{
fireTranscribeEvent(event);
}
}
else
{
logger.warn("Trying to start Transcriber while it is" +
"already started");
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
public void start()
{
if (State.NOT_STARTED.equals(this.state))
{
if (logger.isDebugEnabled())
logger.debug("Transcriber is now transcribing");
StatsDClient dClient = JigasiBundleActivator.getDataDogClient();
if(dClient != null)
{
dClient.increment(DD_ASPECT_START);
if(logger.isDebugEnabled())
{
logger.debug("thrown stat: " + DD_ASPECT_START);
}
}
this.state = State.TRANSCRIBING;
this.executorService = Executors.newSingleThreadExecutor();
List<Participant> participantsClone;
synchronized (this.participants)
{
participantsClone = new ArrayList<>(this.participants.size());
participantsClone.addAll(this.participants.values());
}
TranscriptEvent event
= this.transcript.started(roomName, roomUrl, participantsClone);
if (event != null)
{
fireTranscribeEvent(event);
}
}
else
{
logger.warn("Trying to start Transcriber while it is" +
"already started");
}
}
#location 18
#vulnerability type THREAD_SAFETY_VIOLATION | #fixed code
public void start()
{
if (State.NOT_STARTED.equals(this.state))
{
if (logger.isDebugEnabled())
logger.debug("Transcriber is now transcribing");
updateDDClient(DD_ASPECT_START);
this.state = State.TRANSCRIBING;
this.executorService = Executors.newSingleThreadExecutor();
TranscriptEvent event
= this.transcript.started(roomName, roomUrl, getParticipants());
if (event != null)
{
fireTranscribeEvent(event);
}
}
else
{
logger.warn("Trying to start Transcriber while it is" +
"already started");
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
void onJvbConferenceStopped(JvbConference jvbConference,
int reasonCode, String reason)
{
this.jvbConference = null;
if (sipCall != null)
{
hangUp(reasonCode, reason);
}
else
{
allCallsEnded();
}
}
#location 8
#vulnerability type NULL_DEREFERENCE | #fixed code
void onConferenceCallInvited(Call incomingCall)
{
// Incoming SIP connection mode sets common conference here
if (destination == null)
{
incomingCall.setConference(sipCall.getConference());
boolean useTranslator = incomingCall.getProtocolProvider()
.getAccountID().getAccountPropertyBoolean(
ProtocolProviderFactory.USE_TRANSLATOR_IN_CONFERENCE,
false);
CallPeer peer = incomingCall.getCallPeers().next();
// if use translator is enabled add a ssrc rewriter
if (useTranslator && !addSsrcRewriter(peer))
{
peer.addCallPeerListener(new CallPeerAdapter()
{
@Override
public void peerStateChanged(CallPeerChangeEvent evt)
{
CallPeer peer = evt.getSourceCallPeer();
CallPeerState peerState = peer.getState();
if (CallPeerState.CONNECTED.equals(peerState))
{
peer.removeCallPeerListener(this);
addSsrcRewriter(peer);
}
}
});
}
}
Exception error = this.onConferenceCallStarted(incomingCall);
if (error != null)
{
logger.error(this.callContext + " " + error, error);
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
public void start()
{
if (State.NOT_STARTED.equals(this.state))
{
if (logger.isDebugEnabled())
logger.debug("Transcriber is now transcribing");
StatsDClient dClient = JigasiBundleActivator.getDataDogClient();
if(dClient != null)
{
dClient.increment(DD_ASPECT_START);
if(logger.isDebugEnabled())
{
logger.debug("thrown stat: " + DD_ASPECT_START);
}
}
this.state = State.TRANSCRIBING;
this.executorService = Executors.newSingleThreadExecutor();
List<Participant> participantsClone;
synchronized (this.participants)
{
participantsClone = new ArrayList<>(this.participants.size());
participantsClone.addAll(this.participants.values());
}
TranscriptEvent event
= this.transcript.started(roomName, roomUrl, participantsClone);
if (event != null)
{
fireTranscribeEvent(event);
}
}
else
{
logger.warn("Trying to start Transcriber while it is" +
"already started");
}
}
#location 29
#vulnerability type THREAD_SAFETY_VIOLATION | #fixed code
public void start()
{
if (State.NOT_STARTED.equals(this.state))
{
if (logger.isDebugEnabled())
logger.debug("Transcriber is now transcribing");
updateDDClient(DD_ASPECT_START);
this.state = State.TRANSCRIBING;
this.executorService = Executors.newSingleThreadExecutor();
TranscriptEvent event
= this.transcript.started(roomName, roomUrl, getParticipants());
if (event != null)
{
fireTranscribeEvent(event);
}
}
else
{
logger.warn("Trying to start Transcriber while it is" +
"already started");
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
void onJvbConferenceStopped(JvbConference jvbConference,
int reasonCode, String reason)
{
this.jvbConference = null;
if (call != null)
{
hangUp(reasonCode, reason);
}
else
{
allCallsEnded();
}
}
#location 8
#vulnerability type NULL_DEREFERENCE | #fixed code
void onConferenceCallInvited(Call incomingCall)
{
// Incoming SIP connection mode sets common conference here
if (destination == null)
{
call.setConference(incomingCall.getConference());
boolean useTranslator = incomingCall.getProtocolProvider()
.getAccountID().getAccountPropertyBoolean(
ProtocolProviderFactory.USE_TRANSLATOR_IN_CONFERENCE,
false);
CallPeer peer = incomingCall.getCallPeers().next();
// if use translator is enabled add a ssrc rewriter
if (useTranslator && !addSsrcRewriter(peer))
{
peer.addCallPeerListener(new CallPeerAdapter()
{
@Override
public void peerStateChanged(CallPeerChangeEvent evt)
{
CallPeer peer = evt.getSourceCallPeer();
CallPeerState peerState = peer.getState();
if (CallPeerState.CONNECTED.equals(peerState))
{
peer.removeCallPeerListener(this);
addSsrcRewriter(peer);
}
}
});
}
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Override
public String pay(final String target, final Cash amount,
final String details) throws IOException {
if (amount.compareTo(new Cash.S("$20")) < 0) {
throw new SoftException(
new Par(
"The amount %s is too small,",
"we won't send now to avoid big %s commission"
).say(amount, this.currency)
);
}
final Props props = new Props(this.farm);
final Coinbase base = new CoinbaseBuilder().withApiKey(
props.get("//coinbase/key"), props.get("//coinbase/secret")
).build();
this.fund(base, props.get("//coinbase/account"));
final Transaction trn = new Transaction();
trn.setTo(target);
trn.setAmount(
Money.parse(
String.format(
"USD %.2f",
amount.exchange(Currency.USD).decimal().doubleValue()
)
)
);
trn.setNotes(details);
trn.setInstantBuy(true);
try {
return base.sendMoney(trn).getId();
} catch (final CoinbaseException ex) {
throw new IOException(
String.format(
"Failed to send %s to %s: %s",
trn.getAmount(), trn.getTo(), trn.getNotes()
),
ex
);
}
}
#location 9
#vulnerability type RESOURCE_LEAK | #fixed code
@Override
public String pay(final String target, final Cash amount,
final String details) throws IOException {
final Props props = new Props(this.farm);
final Coinbase base = new CoinbaseBuilder().withApiKey(
props.get("//coinbase/key"), props.get("//coinbase/secret")
).build();
this.fund(base, props.get("//coinbase/account"));
final Transaction trn = new Transaction();
trn.setTo(target);
trn.setAmount(
Money.parse(
String.format(
"USD %.2f",
amount.exchange(Currency.USD).decimal().doubleValue()
)
)
);
trn.setNotes(details);
trn.setInstantBuy(true);
try {
return base.sendMoney(trn).getId();
} catch (final CoinbaseException ex) {
throw new IOException(
String.format(
"Failed to send %s to %s: %s",
trn.getAmount(), trn.getTo(), trn.getNotes()
),
ex
);
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
public String pay(final Project project,
final String login, final Cash amount,
final String reason) throws IOException {
final People people = new People(this.farm).bootstrap();
final String wallet = people.wallet(login);
if (wallet.isEmpty()) {
throw new SoftException(
new Par(
"@%s doesn't have payment method configured, we can't pay"
).say(login)
);
}
final String method = people.bank(login);
final Bank bank;
if ("paypal".equals(method)) {
bank = new Paypal(this.farm);
} else {
throw new SoftException(
new Par(
"@%s has an unsupported payment method \"%s\""
).say(login, method)
);
}
final Cash commission = bank.fee(amount);
final String pid = bank.pay(
wallet, amount, new Par.ToText(reason).toString()
);
new Ledger(project).bootstrap().add(
new Ledger.Transaction(
amount.add(commission),
"liabilities", method,
"assets", "cash",
String.format(
"%s (amount:%s, commission:%s, PID:%s)",
new Par.ToText(reason).toString(),
amount, commission, pid
)
),
new Ledger.Transaction(
commission,
"expenses", "jobs",
"liabilities", method,
String.format(
"%s (commission)",
new Par.ToText(reason).toString()
)
),
new Ledger.Transaction(
amount,
"expenses", "jobs",
"liabilities", String.format("@%s", login),
reason
)
);
return pid;
}
#location 21
#vulnerability type RESOURCE_LEAK | #fixed code
public String pay(final Project project,
final String login, final Cash amount,
final String reason) throws IOException {
final People people = new People(this.farm).bootstrap();
final String wallet = people.wallet(login);
if (wallet.isEmpty()) {
throw new SoftException(
new Par(
"@%s doesn't have payment method configured, we can't pay"
).say(login)
);
}
final String method = people.bank(login);
if (!this.banks.containsKey(method)) {
throw new SoftException(
new Par(
"@%s has an unsupported payment method \"%s\""
).say(login, method)
);
}
final Bank bank = this.banks.get(method);
final Cash commission = bank.fee(amount);
final String pid = bank.pay(
wallet, amount, new Par.ToText(reason).toString()
);
new Ledger(project).bootstrap().add(
new Ledger.Transaction(
amount.add(commission),
"liabilities", method,
"assets", "cash",
String.format(
"%s (amount:%s, commission:%s, PID:%s)",
new Par.ToText(reason).toString(),
amount, commission, pid
)
),
new Ledger.Transaction(
commission,
"expenses", "jobs",
"liabilities", method,
String.format(
"%s (commission)",
new Par.ToText(reason).toString()
)
),
new Ledger.Transaction(
amount,
"expenses", "jobs",
"liabilities", String.format("@%s", login),
reason
)
);
return pid;
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Test
public void redirectOnError() throws Exception {
final Take take = new TkApp(new PropsFarm(new FkFarm()));
final String message = "Internal application error";
MatcherAssert.assertThat(
"Could not redirect on error",
new TextOf(
take.act(new RqFake("GET", "/?PsByFlag=PsGithub")).body()
).asString(),
new StringContains(message)
);
MatcherAssert.assertThat(
"Could not redirect on error (with code)",
new TextOf(
take.act(
new RqFake(
"GET",
"/?PsByFlag=PsGithub&code=1257b773ba07221e7eb5"
)
).body()
).asString(),
new StringContains(message)
);
}
#location 3
#vulnerability type RESOURCE_LEAK | #fixed code
@Test
public void redirectOnError() throws Exception {
// @checkstyle MethodBodyCommentsCheck (30 lines)
//final Take take = new TkApp(new PropsFarm(new FkFarm()));
//final String message = "Internal application error";
//MatcherAssert.assertThat(
// "Could not redirect on error",
// new TextOf(
// take.act(new RqFake("GET", "/?PsByFlag=PsGithub")).body()
// ).asString(),
// new IsNot<>(
// new StringContains(message)
// )
//);
//MatcherAssert.assertThat(
// "Could not redirect on error (with code)",
// new TextOf(
// take.act(
// new RqFake(
// "GET",
// "/?PsByFlag=PsGithub&code=1257b773ba07221e7eb5"
// )
// ).body()
// ).asString(),
// new IsNot<>(
// new StringContains(message)
// )
//);
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Test
public void assignsAndResigns() throws Exception {
final Project project = new FkProject();
final Orders orders = new Orders(new PropsFarm(), project).bootstrap();
final String job = "gh:yegor256/0pdd#13";
new Wbs(project).bootstrap().add(job);
orders.assign(job, "yegor256", "0");
}
#location 7
#vulnerability type RESOURCE_LEAK | #fixed code
@Test
public void assignsAndResigns() throws Exception {
final Project project = new FkProject();
final Orders orders = new Orders(new PropsFarm(), project).bootstrap();
final String job = "gh:yegor256/0pdd#13";
new Wbs(project).bootstrap().add(job);
orders.assign(job, "yegor256", UUID.randomUUID().toString());
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Test
@SuppressWarnings("unchecked")
public void showsThatUserAlreadyHasMentor() throws IOException {
final Farm farm = new PropsFarm(new FkFarm());
final People people = new People(farm).bootstrap();
final String mentor = "yoda";
final String applicant = "luke";
people.touch(mentor);
people.touch(applicant);
people.invite(applicant, mentor, true);
MatcherAssert.assertThat(
new TkApp(farm).act(
new RqWithBody(
new RqWithUser(
farm,
new RqFake("GET", "/join-post"),
applicant
),
"personality=INTJ-A&stackoverflow=187242"
)
),
Matchers.allOf(
new HmRsStatus(HttpURLConnection.HTTP_SEE_OTHER),
new HmRsHeader("Location", "/join"),
new HmRsHeader(
"Set-Cookie",
Matchers.hasItems(
Matchers.containsString(
URLEncoder.encode(
new FormattedText(
"You already have a mentor (@%s)",
mentor
).asString(),
StandardCharsets.UTF_8.displayName()
)
)
)
)
)
);
}
#location 11
#vulnerability type RESOURCE_LEAK | #fixed code
@Test
@SuppressWarnings("unchecked")
public void showsThatUserAlreadyHasMentor() throws IOException {
final Farm farm = FkFarm.props();
final People people = new People(farm).bootstrap();
final String mentor = "yoda";
final String applicant = "luke";
people.touch(mentor);
people.touch(applicant);
people.invite(applicant, mentor, true);
MatcherAssert.assertThat(
new TkApp(farm).act(
new RqWithBody(
new RqWithUser(
farm,
new RqFake("GET", "/join-post"),
applicant
),
"personality=INTJ-A&stackoverflow=187242"
)
),
Matchers.allOf(
new HmRsStatus(HttpURLConnection.HTTP_SEE_OTHER),
new HmRsHeader("Location", "/join"),
new HmRsHeader(
"Set-Cookie",
Matchers.hasItems(
Matchers.containsString(
URLEncoder.encode(
new FormattedText(
"You already have a mentor (@%s)",
mentor
).asString(),
StandardCharsets.UTF_8.displayName()
)
)
)
)
)
);
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Override
public Response act(final Request req) throws IOException {
final JsonObject json = TkViber.json(
new InputStreamReader(req.body(), StandardCharsets.UTF_8)
);
if (json.isEmpty()) {
throw new RsForward(
new RsParFlash(
new Par(
"We expect this URL to be called by Viber",
"with JSON as body of the request"
).say(),
Level.WARNING
)
);
}
if (Objects.equals(json.getString("event"), "message")) {
this.reaction.react(
new VbBot(), this.farm, new VbEvent.Simple(json)
);
}
return new RsWithStatus(
HttpURLConnection.HTTP_OK
);
}
#location 12
#vulnerability type RESOURCE_LEAK | #fixed code
@Override
public Response act(final Request req) throws IOException {
final JsonObject callback = TkViber.json(
new InputStreamReader(req.body(), StandardCharsets.UTF_8)
);
if (callback.isEmpty()) {
throw new HttpException(HttpURLConnection.HTTP_BAD_REQUEST);
}
if (callback.getString("event").equals("message")) {
this.reaction.react(
this.bot, this.farm, new VbEvent.Simple(callback)
);
}
return new RsWithStatus(
HttpURLConnection.HTTP_OK
);
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Test
public void closesClaims() throws Exception {
final AtomicBoolean done = new AtomicBoolean();
final Project raw = new FkProject();
final Spin spin = new Spin(
raw,
Collections.singletonList((pkt, xml) -> done.set(true)),
Executors.newSingleThreadExecutor(new VerboseThreads())
);
final RvProject project = new RvProject(raw, spin);
try (final Claims claims = new Claims(project).lock()) {
claims.add(new ClaimOut().type("hello").token("tt"));
}
spin.close();
try (final Claims claims = new Claims(project).lock()) {
MatcherAssert.assertThat(
claims.iterate(),
Matchers.hasSize(0)
);
}
MatcherAssert.assertThat(done.get(), Matchers.is(true));
}
#location 13
#vulnerability type RESOURCE_LEAK | #fixed code
@Test
public void closesClaims() throws Exception {
final AtomicBoolean done = new AtomicBoolean();
final Project raw = new FkProject();
final Flush flush = new Flush(
raw,
Collections.singletonList((pkt, xml) -> done.set(true)),
Executors.newSingleThreadExecutor(new VerboseThreads())
);
final RvProject project = new RvProject(raw, flush);
try (final Claims claims = new Claims(project).lock()) {
claims.add(new ClaimOut().type("hello").token("tt"));
}
flush.close();
try (final Claims claims = new Claims(project).lock()) {
MatcherAssert.assertThat(
claims.iterate(),
Matchers.hasSize(0)
);
}
MatcherAssert.assertThat(done.get(), Matchers.is(true));
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Test
public void recordsChangesToClaims() throws Exception {
final Bucket bucket = new FkBucket(
Files.createTempDirectory("").toFile(),
"the-bucket"
);
try (final FakeMongo mongo = new FakeMongo().start()) {
final Project project = new SyncFarm(
new FtFarm(new S3Farm(bucket), mongo.client())
).find("@id='ABCZZFE03'").iterator().next();
final Claims claims = new Claims(project);
final AtomicLong cid = new AtomicLong(1L);
final int threads = 10;
MatcherAssert.assertThat(
inc -> {
final long num = cid.getAndIncrement();
new ClaimOut().cid(num).type("hello").postTo(project);
claims.remove(num);
return true;
},
new RunsInThreads<>(new AtomicInteger(), threads)
);
MatcherAssert.assertThat(
mongo.client().getDatabase("footprint")
.getCollection("claims")
.count(),
Matchers.equalTo((long) threads)
);
}
}
#location 24
#vulnerability type RESOURCE_LEAK | #fixed code
@Test
public void recordsChangesToClaims() throws Exception {
final Bucket bucket = new FkBucket(
Files.createTempDirectory("").toFile(),
"the-bucket"
);
final Farm farm = new SyncFarm(
new FtFarm(new PropsFarm(new S3Farm(bucket)))
);
final Project project = farm.find("@id='ABCZZFE03'").iterator().next();
final Claims claims = new Claims(project);
final AtomicLong cid = new AtomicLong(1L);
final int threads = 10;
MatcherAssert.assertThat(
inc -> {
final long num = cid.getAndIncrement();
new ClaimOut().cid(num).type("hello").postTo(project);
claims.remove(num);
return true;
},
new RunsInThreads<>(new AtomicInteger(), threads)
);
MatcherAssert.assertThat(
new Footprint(farm, project).collection().count(),
Matchers.equalTo((long) threads)
);
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Test
public void rechargeIsRequiredIfCashBalanceIsLessThanLocked()
throws Exception {
final Project project = new FkProject();
final String job = "gh:test/test#1";
new Wbs(project).bootstrap().add(job);
final PropsFarm farm = new PropsFarm();
new Orders(farm, project).bootstrap().assign(job, "perf", "0");
new Estimates(farm, project).bootstrap()
.update(job, new Cash.S("$100"));
new Ledger(farm, project).bootstrap().add(
new Ledger.Transaction(
new Cash.S("$10"),
"assets", "cash",
"income", "test",
"Recharge#required test"
)
);
MatcherAssert.assertThat(
new Recharge(new PropsFarm(), project).required(),
new IsEqual<>(true)
);
}
#location 20
#vulnerability type RESOURCE_LEAK | #fixed code
@Test
public void rechargeIsRequiredIfCashBalanceIsLessThanLocked()
throws Exception {
final Project project = new FkProject();
final String job = "gh:test/test#1";
new Wbs(project).bootstrap().add(job);
final PropsFarm farm = new PropsFarm();
new Orders(farm, project).bootstrap()
.assign(job, "perf", UUID.randomUUID().toString());
new Estimates(farm, project).bootstrap()
.update(job, new Cash.S("$100"));
new Ledger(farm, project).bootstrap().add(
new Ledger.Transaction(
new Cash.S("$10"),
"assets", "cash",
"income", "test",
"Recharge#required test"
)
);
MatcherAssert.assertThat(
new Recharge(new PropsFarm(), project).required(),
new IsEqual<>(true)
);
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Test
public void rendersIndexPage() throws Exception {
final Farm farm = new FtFarm(new PropsFarm(new FkFarm()));
MatcherAssert.assertThat(
XhtmlMatchers.xhtml(new View(farm, "/").xml()),
XhtmlMatchers.hasXPaths("/page/alive")
);
}
#location 5
#vulnerability type RESOURCE_LEAK | #fixed code
@Test
public void rendersIndexPage() throws Exception {
final Farm farm = FkFarm.props();
MatcherAssert.assertThat(
XhtmlMatchers.xhtml(new View(farm, "/").xml()),
XhtmlMatchers.hasXPaths("/page/alive")
);
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@SuppressWarnings("unchecked")
public void exec() throws IOException {
final Path temp = Paths.get("./s3farm").normalize();
if (!temp.toFile().mkdir()) {
throw new IllegalStateException(
String.format(
"Failed to mkdir \"%s\"", temp
)
);
}
Logger.info(this, "Farm is ready to start");
final ShutdownFarm.Hook shutdown = new ShutdownFarm.Hook();
final ClaimGuts cgts = new ClaimGuts();
final TestLocks locks = new TestLocks();
try (
final MessageSink farm = new MessageSink(
new ShutdownFarm(
new ClaimsFarm(
new TempFiles.Farm(
new SmartFarm(
new S3Farm(new ExtBucket().value(), locks),
locks
)
),
cgts
),
shutdown
),
shutdown
);
final SlackRadar radar = new SlackRadar(farm);
final ClaimsRoutine claims = new ClaimsRoutine(farm)
) {
new ExtMongobee(farm).apply();
farm.start(claims.messages());
cgts.add(claims.messages());
claims.start(shutdown);
new AsyncFunc<>(
input -> {
new ExtTelegram(farm).value();
}
).exec(null);
new AsyncFunc<>(
input -> {
radar.refresh();
}
).exec(null);
new GithubRoutine(farm).start();
new Pings(farm).start();
new FtCli(
new TkApp(
farm,
new FkRegex("/alias", new TkAlias(farm)),
new FkRegex("/slack", new TkSlack(farm, radar)),
new FkRegex("/viber", new TkViber(farm)),
new FkRegex(
"/ghook",
new TkMethods(
new TkSentry(farm, new TkGithub(farm)),
HttpMethod.POST
)
),
new FkRegex(
"/glhook",
new TkMethods(
new TkSentry(farm, new TkGitlab()),
HttpMethod.POST
)
),
new FkRegex(
"/zcallback",
new TkZoldCallback(farm)
)
),
this.arguments
).start(Exit.NEVER);
}
}
#location 21
#vulnerability type RESOURCE_LEAK | #fixed code
@SuppressWarnings("unchecked")
public void exec() throws IOException {
Logger.info(this, "Farm is ready to start");
final ShutdownFarm.Hook shutdown = new ShutdownFarm.Hook();
final ClaimGuts cgts = new ClaimGuts();
final TestLocks locks = new TestLocks();
try (
final MessageSink farm = new MessageSink(
new ShutdownFarm(
new ClaimsFarm(
new TempFiles.Farm(
new SmartFarm(
new S3Farm(new ExtBucket().value(), locks),
locks
)
),
cgts
),
shutdown
),
shutdown
);
final SlackRadar radar = new SlackRadar(farm);
final ClaimsRoutine claims = new ClaimsRoutine(farm)
) {
new ExtMongobee(farm).apply();
farm.start(claims.messages());
cgts.add(claims.messages());
claims.start(shutdown);
new AsyncFunc<>(
input -> {
new ExtTelegram(farm).value();
}
).exec(null);
new AsyncFunc<>(
input -> {
radar.refresh();
}
).exec(null);
new GithubRoutine(farm).start();
new Pings(farm).start();
new FtCli(
new TkApp(
farm,
new FkRegex("/alias", new TkAlias(farm)),
new FkRegex("/slack", new TkSlack(farm, radar)),
new FkRegex("/viber", new TkViber(farm)),
new FkRegex(
"/ghook",
new TkMethods(
new TkSentry(farm, new TkGithub(farm)),
HttpMethod.POST
)
),
new FkRegex(
"/glhook",
new TkMethods(
new TkSentry(farm, new TkGitlab()),
HttpMethod.POST
)
),
new FkRegex(
"/zcallback",
new TkZoldCallback(farm)
)
),
this.arguments
).start(Exit.NEVER);
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Override
public double take(final String login, final StringBuilder log)
throws IOException {
final int total = new Agenda(this.pmo, login).bootstrap().jobs().size();
final double rate;
final int max = new Options(this.pmo, login).bootstrap()
.maxJobsInAgenda();
if (total >= max) {
rate = 1.0d;
log.append(
new Par(
"%d job(s) already, maxJobsInAgenda option is %d"
).say(total, max)
);
} else {
rate = 0.0d;
log.append(
new Par(
"%d job(s) out of %d from maxJobsInAgenda option"
).say(total, max)
);
}
return rate;
}
#location 13
#vulnerability type RESOURCE_LEAK | #fixed code
@Override
public double take(final String login, final StringBuilder log)
throws IOException {
final int total = new Agenda(this.pmo, login).bootstrap().jobs().size();
final double rate;
final int max = new Options(this.pmo, login).bootstrap()
.maxJobsInAgenda();
if (total >= max) {
rate = 1.0d;
log.append(
String.format(
"%d job(s) already, maxJobsInAgenda option is %d",
total, max
)
);
} else {
rate = 0.0d;
log.append(
String.format(
"%d job(s) out of %d from maxJobsInAgenda option",
total, max
)
);
}
return rate;
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
public boolean pause(final String pid) throws IOException {
if (!this.exists(pid)) {
throw new IllegalArgumentException(
new Par("Project %s doesn't exist").say(pid)
);
}
try (final Item item = this.item()) {
return !Boolean.parseBoolean(
new Xocument(item.path()).xpath(
String.format(
"/catalog/project[@id='%s']/alive/text()",
pid
)
).get(0)
);
}
}
#location 4
#vulnerability type RESOURCE_LEAK | #fixed code
public boolean pause(final String pid) throws IOException {
this.checkExist(pid);
try (final Item item = this.item()) {
return !Boolean.parseBoolean(
new Xocument(item.path()).xpath(
String.format(
"/catalog/project[@id='%s']/alive/text()",
pid
)
).get(0)
);
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Test
public void modifiesProject() throws Exception {
final Item item = new FkItem();
final Catalog catalog = new Catalog(item);
catalog.bootstrap();
catalog.add("34EA54SW9", "2017/01/34EA54SW9/");
catalog.add("34EA54S87", "2017/01/34EA54S87/");
final String pfx = "2017/01/34EA54SZZ/";
catalog.add("34EA54SZZ", pfx);
final String prefix = "2017/01/44EAFFPW3/";
catalog.add("44EAFFPW3", prefix);
try (final Item citem = new CatalogItem(item, prefix)) {
new Xocument(citem.path()).modify(
new Directives()
.xpath("/catalog/project")
.add("link")
.attr("rel", "github")
.attr("href", "yegor256/pdd")
);
}
try (final Item citem = new CatalogItem(item, prefix)) {
MatcherAssert.assertThat(
new Xocument(citem.path()).xpath(
"//project/link[@rel]/@href"
),
Matchers.not(Matchers.emptyIterable())
);
}
try (final Item citem = new CatalogItem(item, pfx)) {
MatcherAssert.assertThat(
new Xocument(citem.path()).xpath(
"//project[not(link)]/id/text()"
),
Matchers.not(Matchers.emptyIterable())
);
}
}
#location 11
#vulnerability type RESOURCE_LEAK | #fixed code
@Test
public void modifiesProject() throws Exception {
final Item item = new FkItem();
final String pid = "34EA54SZZ";
try (final Catalog catalog = new Catalog(item)) {
catalog.bootstrap();
catalog.add("34EA54SW9");
catalog.add("34EA54S87");
catalog.add(pid);
catalog.add("34EA54S8F");
}
try (final Item citem = new CatalogItem(
item, String.format("//project[@id!='%s']", pid)
)) {
new Xocument(citem.path()).modify(
new Directives()
.xpath("/catalog/project")
.add("link")
.attr("rel", "github")
.attr("href", "yegor256/pdd")
);
}
try (final Item citem = new CatalogItem(
item, String.format("//project[@id!='%s' ]", pid)
)) {
MatcherAssert.assertThat(
new Xocument(citem.path()).xpath(
"//project/link[@rel]/@href"
),
Matchers.not(Matchers.emptyIterable())
);
}
MatcherAssert.assertThat(
new Xocument(item.path()).xpath(
"//project[not(link)]/@id"
),
Matchers.not(Matchers.emptyIterable())
);
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Test
public void removesImpediment() throws Exception {
final Project project = new FkProject();
final PropsFarm farm = new PropsFarm();
final Impediments imp = new Impediments(farm, project).bootstrap();
final String job = "gh:test/test#2";
new Wbs(project).bootstrap().add(job);
new Orders(farm, project).bootstrap().assign(job, "amihaiemil", "0");
imp.register(job, "reason");
MatcherAssert.assertThat(
imp.jobs(),
Matchers.contains(job)
);
MatcherAssert.assertThat(
imp.exists(job),
Matchers.is(true)
);
imp.remove(job);
MatcherAssert.assertThat(
imp.jobs(),
Matchers.not(Matchers.contains(job))
);
MatcherAssert.assertThat(
imp.exists(job),
Matchers.is(false)
);
}
#location 15
#vulnerability type RESOURCE_LEAK | #fixed code
@Test
public void removesImpediment() throws Exception {
final Project project = new FkProject();
final PropsFarm farm = new PropsFarm();
final Impediments imp = new Impediments(farm, project).bootstrap();
final String job = "gh:test/test#2";
new Wbs(project).bootstrap().add(job);
new Orders(farm, project).bootstrap()
.assign(job, "amihaiemil", UUID.randomUUID().toString());
imp.register(job, "reason");
MatcherAssert.assertThat(
imp.jobs(),
Matchers.contains(job)
);
MatcherAssert.assertThat(
imp.exists(job),
Matchers.is(true)
);
imp.remove(job);
MatcherAssert.assertThat(
imp.jobs(),
Matchers.not(Matchers.contains(job))
);
MatcherAssert.assertThat(
imp.exists(job),
Matchers.is(false)
);
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
public void wallet(final String uid, final String bank,
final String wallet) throws IOException {
if (!bank.matches("paypal")) {
throw new SoftException(
new Par(
"Bank name `%s` is invalid,",
"we accept only `paypal`, see §20"
).say(bank)
);
}
final Pattern email = Pattern.compile(
"\\b[\\w.%-]+@[-.\\w]+\\.[A-Za-z]{2,4}\\b"
);
if (!email.matcher(wallet).matches()) {
throw new SoftException(
String.format(
"Email `%s` is not valid",
wallet
)
);
}
try (final Item item = this.item()) {
new Xocument(item.path()).modify(
People.start(uid)
.addIf("wallet")
.set(wallet)
.attr("bank", bank)
);
}
}
#location 8
#vulnerability type RESOURCE_LEAK | #fixed code
public void wallet(final String uid, final String bank,
final String wallet) throws IOException {
if (!bank.matches("paypal|btc|bch|eth|ltc")) {
throw new SoftException(
new Par(
"Bank name `%s` is invalid, we accept only",
"`paypal`, `btc`, `bch`, `eth`, or `ltc`, see §20"
).say(bank)
);
}
if ("paypal".equals(wallet)
&& !wallet.matches("\\b[\\w.%-]+@[-.\\w]+\\.[A-Za-z]{2,4}\\b")) {
throw new SoftException(
new Par("Email `%s` is not valid").say(wallet)
);
}
if ("btc".equals(wallet)
&& !wallet.matches("(1|3|bc1)[a-zA-Z0-9]{20,40}")) {
throw new SoftException(
new Par("Bitcoin address is not valid: `%s`").say(wallet)
);
}
if ("bch".equals(wallet)
&& !wallet.matches("[pq]{41}")) {
throw new SoftException(
new Par("Bitcoin Cash address is not valid: `%s`").say(wallet)
);
}
if ("eth".equals(wallet)
&& !wallet.matches("[0-9a-f]{42}")) {
throw new SoftException(
new Par("Etherium address is not valid: `%s`").say(wallet)
);
}
if ("ltc".equals(wallet)
&& !wallet.matches("[0-9a-zA-Z]{35}")) {
throw new SoftException(
new Par("Litecoin address is not valid: `%s`").say(wallet)
);
}
try (final Item item = this.item()) {
new Xocument(item.path()).modify(
People.start(uid)
.addIf("wallet")
.set(wallet)
.attr("bank", bank)
);
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Test
public void rendersAllPossibleUrls() throws Exception {
final Take take = new TkApp(new PropsFarm(new FkFarm()));
MatcherAssert.assertThat(
this.url,
take.act(new RqFake("GET", this.url)),
Matchers.not(
new HmRsStatus(
HttpURLConnection.HTTP_NOT_FOUND
)
)
);
}
#location 3
#vulnerability type RESOURCE_LEAK | #fixed code
@Test
public void rendersAllPossibleUrls() throws Exception {
final Take take = new TkApp(FkFarm.props());
MatcherAssert.assertThat(
this.url,
take.act(new RqFake("GET", this.url)),
Matchers.not(
new HmRsStatus(
HttpURLConnection.HTTP_NOT_FOUND
)
)
);
} | 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.