instruction
stringclasses 1
value | output
stringlengths 64
69.4k
| input
stringlengths 205
32.4k
|
---|---|---|
Below is the vulnerable code, please generate the patch based on the following information. | #fixed code
@Test
public void testSelectTransactedChained() throws Exception {
try (Database db = db()) {
db //
.select("select score from person where name=?") //
.parameters("FRED", "JOSEPH") //
.transacted() //
.transactedValuesOnly() //
.getAs(Integer.class) //
.doOnNext(tx -> log
.debug(tx.isComplete() ? "complete" : String.valueOf(tx.value())))//
.flatMap(tx -> tx //
.select("select name from person where score = ?") //
.parameter(tx.value()) //
.valuesOnly() //
.getAs(String.class)) //
.test() //
.awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) //
.assertNoErrors() //
.assertValues("FRED", "JOSEPH") //
.assertComplete();
}
} | #vulnerable code
@Test
public void testSelectTransactedChained() throws Exception {
Database db = db();
db //
.select("select score from person where name=?") //
.parameters("FRED", "JOSEPH") //
.transacted() //
.transactedValuesOnly() //
.getAs(Integer.class) //
.doOnNext(
tx -> log.debug(tx.isComplete() ? "complete" : String.valueOf(tx.value())))//
.flatMap(tx -> tx //
.select("select name from person where score = ?") //
.parameter(tx.value()) //
.valuesOnly() //
.getAs(String.class)) //
.test() //
.awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) //
.assertNoErrors() //
.assertValues("FRED", "JOSEPH") //
.assertComplete();
}
#location 6
#vulnerability type RESOURCE_LEAK |
Below is the vulnerable code, please generate the patch based on the following information. | #fixed code
@Test
public void testSelectTransactedTuple4() {
try (Database db = db()) {
Tx<Tuple4<String, Integer, String, Integer>> t = db //
.select("select name, score, name, score from person where name=?") //
.parameters("FRED") //
.transacted() //
.getAs(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());
}
} | #vulnerable code
@Test
public void testSelectTransactedTuple4() {
Tx<Tuple4<String, Integer, String, Integer>> t = db() //
.select("select name, score, name, score from person where name=?") //
.parameters("FRED") //
.transacted() //
.getAs(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());
}
#location 5
#vulnerability type RESOURCE_LEAK |
Below is the vulnerable code, please generate the patch based on the following information. | #fixed code
public static Database test(int maxPoolSize) {
return Database.from( //
Pools.nonBlocking() //
.connectionProvider(testConnectionProvider()) //
.maxPoolSize(maxPoolSize) //
.build());
} | #vulnerable code
public static Database test(int maxPoolSize) {
return Database.from(new NonBlockingConnectionPool(testConnectionProvider(), maxPoolSize, 1000));
}
#location 2
#vulnerability type RESOURCE_LEAK |
Below is the vulnerable code, please generate the patch based on the following information. | #fixed code
@Test
@Ignore
public void testCallableApi() {
Database db = DatabaseCreator.createDerbyWithStoredProcs(1);
db //
.call("call getPersonCount(?,?)") //
.in() //
.out(Type.INTEGER, Integer.class) //
.in(0, 10, 20) //
.build() //
.test() //
.awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) //
.assertValue(2) //
.assertComplete();
} | #vulnerable code
@Test
@Ignore
public void testCallableApi() {
Database db = DatabaseCreator.createDerbyWithStoredProcs(1);
db //
.call("call getPersonCount(?,?)") //
.in() //
.out(Type.INTEGER, Integer.class) //
.build() //
.test() //
.awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) //
.assertValue(2) //
.assertComplete();
}
#location 10
#vulnerability type NULL_DEREFERENCE |
Below is the vulnerable code, please generate the patch based on the following information. | #fixed code
@Test
public void testSelectWithFetchSize() {
try (Database db = db()) {
db.select("select score from person order by name") //
.fetchSize(2) //
.getAs(Integer.class) //
.test() //
.awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) //
.assertNoErrors() //
.assertValues(21, 34, 25) //
.assertComplete();
}
} | #vulnerable code
@Test
public void testSelectWithFetchSize() {
db().select("select score from person order by name") //
.fetchSize(2) //
.getAs(Integer.class) //
.test() //
.awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) //
.assertNoErrors() //
.assertValues(21, 34, 25) //
.assertComplete();
}
#location 5
#vulnerability type RESOURCE_LEAK |
Below is the vulnerable code, please generate the patch based on the following information. | #fixed code
@Test
public void testSelectAutomappedTransactedValuesOnly() {
try (Database db = db()) {
db //
.select("select name, score from person") //
.transacted() //
.valuesOnly() //
.autoMap(Person2.class) //
.test() //
.awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) //
.assertValueCount(3) //
.assertComplete();
}
} | #vulnerable code
@Test
public void testSelectAutomappedTransactedValuesOnly() {
db() //
.select("select name, score from person") //
.transacted() //
.valuesOnly() //
.autoMap(Person2.class) //
.test() //
.awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) //
.assertValueCount(3) //
.assertComplete();
}
#location 7
#vulnerability type RESOURCE_LEAK |
Below is the vulnerable code, please generate the patch based on the following information. | #fixed code
@Test
public void testSelectTransactedTuple5() {
try (Database db = db()) {
Tx<Tuple5<String, Integer, String, Integer, String>> t = db //
.select("select name, score, name, score, name from person where name=?") //
.parameters("FRED") //
.transacted() //
.getAs(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());
}
} | #vulnerable code
@Test
public void testSelectTransactedTuple5() {
Tx<Tuple5<String, Integer, String, Integer, String>> t = db() //
.select("select name, score, name, score, name from person where name=?") //
.parameters("FRED") //
.transacted() //
.getAs(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());
}
#location 5
#vulnerability type RESOURCE_LEAK |
Below is the vulnerable code, please generate the patch based on the following information. | #fixed code
@Test
public void testSelectUsingNamedParameterList() {
try (Database db = db()) {
db.select("select score from person where name=:name") //
.parameters(Parameter.named("name", "FRED").value("JOSEPH").list()) //
.getAs(Integer.class) //
.test() //
.awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) //
.assertNoErrors() //
.assertValues(21, 34) //
.assertComplete();
}
} | #vulnerable code
@Test
public void testSelectUsingNamedParameterList() {
db().select("select score from person where name=:name") //
.parameters(Parameter.named("name", "FRED").value("JOSEPH").list()) //
.getAs(Integer.class) //
.test() //
.awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) //
.assertNoErrors() //
.assertValues(21, 34) //
.assertComplete();
}
#location 4
#vulnerability type RESOURCE_LEAK |
Below is the vulnerable code, please generate the patch based on the following information. | #fixed code
public static Database from(@Nonnull String url, int maxPoolSize) {
Preconditions.checkNotNull(url, "url cannot be null");
Preconditions.checkArgument(maxPoolSize > 0, "maxPoolSize must be greater than 0");
return Database.from( //
Pools.nonBlocking() //
.url(url) //
.maxPoolSize(maxPoolSize) //
.build());
} | #vulnerable code
public static Database from(@Nonnull String url, int maxPoolSize) {
Preconditions.checkNotNull(url, "url cannot be null");
Preconditions.checkArgument(maxPoolSize > 0, "maxPoolSize must be greater than 0");
return Database.from( //
Pools.nonBlocking() //
.url(url) //
.maxPoolSize(maxPoolSize) //
.scheduler(Schedulers.from(Executors.newFixedThreadPool(maxPoolSize))) //
.build());
}
#location 4
#vulnerability type RESOURCE_LEAK |
Below is the vulnerable code, please generate the patch based on the following information. | #fixed code
@Test
public void testComplete() throws InterruptedException {
try (Database db = db(1)) {
Completable a = db //
.update("update person set score=-3 where name='FRED'") //
.complete();
db.update("update person set score=-4 where score = -3") //
.dependsOn(a) //
.counts() //
.test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) //
.assertValue(1) //
.assertComplete();
}
} | #vulnerable code
@Test
public void testComplete() throws InterruptedException {
Database db = db(1);
Completable a = db //
.update("update person set score=-3 where name='FRED'") //
.complete();
db.update("update person set score=-4 where score = -3") //
.dependsOn(a) //
.counts() //
.test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) //
.assertValue(1) //
.assertComplete();
}
#location 8
#vulnerability type RESOURCE_LEAK |
Below is the vulnerable code, please generate the patch based on the following information. | #fixed code
@Test
public void testSelectTransactedTupleN() {
try (Database db = db()) {
List<Tx<TupleN<Object>>> list = db //
.select("select name, score from person where name=?") //
.parameters("FRED") //
.transacted() //
.getTupleN() //
.test() //
.awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) //
.assertValueCount(2) //
.assertComplete() //
.values();
assertEquals("FRED", list.get(0).value().values().get(0));
assertEquals(21, (int) list.get(0).value().values().get(1));
assertTrue(list.get(1).isComplete());
assertEquals(2, list.size());
}
} | #vulnerable code
@Test
public void testSelectTransactedTupleN() {
List<Tx<TupleN<Object>>> list = db() //
.select("select name, score from person where name=?") //
.parameters("FRED") //
.transacted() //
.getTupleN() //
.test() //
.awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) //
.assertValueCount(2) //
.assertComplete() //
.values();
assertEquals("FRED", list.get(0).value().values().get(0));
assertEquals(21, (int) list.get(0).value().values().get(1));
assertTrue(list.get(1).isComplete());
assertEquals(2, list.size());
}
#location 5
#vulnerability type RESOURCE_LEAK |
Below is the vulnerable code, please generate the patch based on the following information. | #fixed code
@Test
public void testMoreColumnsMappedThanAvailable() {
try (Database db = db()) {
db //
.select("select name, score from person where name='FRED'") //
.getAs(String.class, Integer.class, String.class) //
.test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) //
.assertNoValues() //
.assertError(MoreColumnsRequestedThanExistException.class);
}
} | #vulnerable code
@Test
public void testMoreColumnsMappedThanAvailable() {
db() //
.select("select name, score from person where name='FRED'") //
.getAs(String.class, Integer.class, String.class) //
.test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) //
.assertNoValues() //
.assertError(MoreColumnsRequestedThanExistException.class);
}
#location 5
#vulnerability type RESOURCE_LEAK |
Below is the vulnerable code, please generate the patch based on the following information. | #fixed code
@Test
public void testTuple6() {
try (Database db = db()) {
db //
.select("select name, score, name, score, name, score from person order by name") //
.getAs(String.class, Integer.class, String.class, Integer.class, String.class,
Integer.class) //
.firstOrError() //
.test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) //
.assertComplete()
.assertValue(Tuple6.create("FRED", 21, "FRED", 21, "FRED", 21)); //
}
} | #vulnerable code
@Test
public void testTuple6() {
db() //
.select("select name, score, name, score, name, score from person order by name") //
.getAs(String.class, Integer.class, String.class, Integer.class, String.class,
Integer.class) //
.firstOrError() //
.test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) //
.assertComplete().assertValue(Tuple6.create("FRED", 21, "FRED", 21, "FRED", 21)); //
}
#location 5
#vulnerability type RESOURCE_LEAK |
Below is the vulnerable code, please generate the patch based on the following information. | #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();
}
} | #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 |
Below is the vulnerable code, please generate the patch based on the following information. | #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();
}
} | #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 |
Below is the vulnerable code, please generate the patch based on the following information. | #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);
}
} | #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 |
Below is the vulnerable code, please generate the patch based on the following information. | #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();
}
} | #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 |
Below is the vulnerable code, please generate the patch based on the following information. | #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());
} | #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 |
Below is the vulnerable code, please generate the patch based on the following information. | #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");
}
} | #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 |
Below is the vulnerable code, please generate the patch based on the following information. | #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());
}
} | #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 |
Below is the vulnerable code, please generate the patch based on the following information. | #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();
}
} | #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 |
Below is the vulnerable code, please generate the patch based on the following information. | #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();
}
} | #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 |
Below is the vulnerable code, please generate the patch based on the following information. | #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")); //
}
} | #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 |
Below is the vulnerable code, please generate the patch based on the following information. | #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();
}
} | #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 |
Below is the vulnerable code, please generate the patch based on the following information. | #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();
}
} | #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 |
Below is the vulnerable code, please generate the patch based on the following information. | #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);
} | #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 |
Below is the vulnerable code, please generate the patch based on the following information. | #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");
}
} | #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 |
Below is the vulnerable code, please generate the patch based on the following information. | #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();
}
} | #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 |
Below is the vulnerable code, please generate the patch based on the following information. | #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));
} | #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 |
Below is the vulnerable code, please generate the patch based on the following information. | #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);
} | #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 |
Below is the vulnerable code, please generate the patch based on the following information. | #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();
}
} | #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 |
Below is the vulnerable code, please generate the patch based on the following information. | #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());
}
} | #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 |
Below is the vulnerable code, please generate the patch based on the following information. | #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);
});
} | #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 |
Below is the vulnerable code, please generate the patch based on the following information. | #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);
} | #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 |
Below is the vulnerable code, please generate the patch based on the following information. | #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);
}
} | #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 |
Below is the vulnerable code, please generate the patch based on the following information. | #fixed code
@Test
public void testSelectWithoutWhereClause() {
try (Database db = db()) {
Assert.assertEquals(3, (long) db.select("select name from person") //
.count() //
.blockingGet());
}
} | #vulnerable code
@Test
public void testSelectWithoutWhereClause() {
Assert.assertEquals(3, (long) db().select("select name from person") //
.count() //
.blockingGet());
}
#location 4
#vulnerability type RESOURCE_LEAK |
Below is the vulnerable code, please generate the patch based on the following information. | #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();
}
} | #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 |
Below is the vulnerable code, please generate the patch based on the following information. | #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();
}
} | #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 |
Below is the vulnerable code, please generate the patch based on the following information. | #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();
}
} | #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 |
Below is the vulnerable code, please generate the patch based on the following information. | #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();
}
} | #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 |
Below is the vulnerable code, please generate the patch based on the following information. | #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());
}
} | #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 |
Below is the vulnerable code, please generate the patch based on the following information. | #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();
}
} | #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 |
Below is the vulnerable code, please generate the patch based on the following information. | #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")); //
}
} | #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 |
Below is the vulnerable code, please generate the patch based on the following information. | #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();
}
} | #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 |
Below is the vulnerable code, please generate the patch based on the following information. | #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());
}
} | #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 |
Below is the vulnerable code, please generate the patch based on the following information. | #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();
}
} | #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 |
Below is the vulnerable code, please generate the patch based on the following information. | #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();
}
} | #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 |
Below is the vulnerable code, please generate the patch based on the following information. | #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));
}
} | #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 |
Below is the vulnerable code, please generate the patch based on the following information. | #fixed code
public List<String> tabComplete(CommandIssuer issuer, String commandLabel, String[] args) {
return tabComplete(issuer, commandLabel, args, false);
} | #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 |
Below is the vulnerable code, please generate the patch based on the following information. | #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");
}
} | #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 |
Below is the vulnerable code, please generate the patch based on the following information. | #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);
} | #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 |
Below is the vulnerable code, please generate the patch based on the following information. | #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");
}
} | #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 |
Below is the vulnerable code, please generate the patch based on the following information. | #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");
}
} | #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 |
Below is the vulnerable code, please generate the patch based on the following information. | #fixed code
void sendPresenceExtension(ExtensionElement extension)
{
if (mucRoom != null)
{
// Send presence update
OperationSetJitsiMeetTools jitsiMeetTools
= xmppProvider.getOperationSet(
OperationSetJitsiMeetTools.class);
jitsiMeetTools.sendPresenceExtension(mucRoom, extension);
}
} | #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 |
Below is the vulnerable code, please generate the patch based on the following information. | #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);
} | #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 |
Below is the vulnerable code, please generate the patch based on the following information. | #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");
}
} | #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 |
Below is the vulnerable code, please generate the patch based on the following information. | #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");
}
} | #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 |
Below is the vulnerable code, please generate the patch based on the following information. | #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);
}
} | #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 |
Below is the vulnerable code, please generate the patch based on the following information. | #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)
// )
//);
} | #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 |
Below is the vulnerable code, please generate the patch based on the following information. | #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()
)
)
)
)
)
);
} | #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 |
Below is the vulnerable code, please generate the patch based on the following information. | #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)
);
} | #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 |
Below is the vulnerable code, please generate the patch based on the following information. | #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
)
)
);
} | #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 |
Below is the vulnerable code, please generate the patch based on the following information. | #fixed code
public Cash fee(final String pid) throws IOException {
this.checkExist(pid);
try (final Item item = this.item()) {
final Iterator<String> fees = new Xocument(item.path()).xpath(
String.format("/catalog/project[@id='%s']/fee/text()", pid)
).iterator();
final Cash fee;
if (fees.hasNext()) {
fee = new Cash.S(fees.next());
} else {
fee = Cash.ZERO;
}
return fee;
}
} | #vulnerable code
public Cash fee(final String pid) throws IOException {
if (!this.exists(pid)) {
throw new IllegalArgumentException(
new Par(
"Project %s doesn't exist, can't get fee"
).say(pid)
);
}
try (final Item item = this.item()) {
final Iterator<String> fees = new Xocument(item.path()).xpath(
String.format("/catalog/project[@id='%s']/fee/text()", pid)
).iterator();
final Cash fee;
if (fees.hasNext()) {
fee = new Cash.S(fees.next());
} else {
fee = Cash.ZERO;
}
return fee;
}
}
#location 6
#vulnerability type RESOURCE_LEAK |
Below is the vulnerable code, please generate the patch based on the following information. | #fixed code
@Test
public void parsesJson() throws Exception {
final Farm farm = new PropsFarm(new FkFarm());
final Take take = new TkGithub(
farm, (frm, github, event) -> "nothing"
);
MatcherAssert.assertThat(
take.act(
new RqWithBody(
new RqFake("POST", "/"),
String.format(
"payload=%s",
URLEncoder.encode(
"{\"foo\": \"bar\"}",
StandardCharsets.UTF_8.displayName()
)
)
)
),
new HmRsStatus(HttpURLConnection.HTTP_OK)
);
} | #vulnerable code
@Test
public void parsesJson() throws Exception {
MatcherAssert.assertThat(
new TkGithub(
new PropsFarm(),
new Rebound.Fake("nothing")
).act(
new RqWithBody(
new RqFake("POST", "/"),
String.format(
"payload=%s",
URLEncoder.encode(
"{\"foo\": \"bar\"}",
StandardCharsets.UTF_8.displayName()
)
)
)
),
new HmRsStatus(HttpURLConnection.HTTP_OK)
);
}
#location 7
#vulnerability type RESOURCE_LEAK |
Below is the vulnerable code, please generate the patch based on the following information. | #fixed code
@Test
public void rendersHtmlAwardsPageForFirefox() throws Exception {
final Farm farm = FkFarm.props();
final String user = "yegor256";
final int points = 1234;
new Awards(farm, user).bootstrap()
.add(new FkProject(), points, "none", "reason");
final String html = new View(
farm, String.format("/u/%s/awards", user)
).html();
MatcherAssert.assertThat(
html,
XhtmlMatchers.hasXPaths("//xhtml:html")
);
MatcherAssert.assertThat(
html,
Matchers.containsString(String.format("+%d", points))
);
} | #vulnerable code
@Test
public void rendersHtmlAwardsPageForFirefox() throws Exception {
final Farm farm = new PropsFarm(new FkFarm());
final String user = "yegor256";
final int points = 1234;
new Awards(farm, user).bootstrap()
.add(new FkProject(), points, "none", "reason");
final String html = new View(
farm, String.format("/u/%s/awards", user)
).html();
MatcherAssert.assertThat(
html,
XhtmlMatchers.hasXPaths("//xhtml:html")
);
MatcherAssert.assertThat(
html,
Matchers.containsString(String.format("+%d", points))
);
}
#location 10
#vulnerability type RESOURCE_LEAK |
Below is the vulnerable code, please generate the patch based on the following information. | #fixed code
@Test
public void retrievesProps() throws Exception {
MatcherAssert.assertThat(
new Props(FkFarm.props()).get("/props/testing"),
Matchers.equalTo("yes")
);
} | #vulnerable code
@Test
public void retrievesProps() throws Exception {
MatcherAssert.assertThat(
new Props(new PropsFarm(new FkFarm())).get("/props/testing"),
Matchers.equalTo("yes")
);
}
#location 3
#vulnerability type RESOURCE_LEAK |
Below is the vulnerable code, please generate the patch based on the following information. | #fixed code
public void fee(final String pid, final Cash fee) throws IOException {
this.checkExist(pid);
try (final Item item = this.item()) {
new Xocument(item.path()).modify(
new Directives().xpath(
String.format("/catalog/project[@id='%s']/fee", pid)
).strict(1).set(fee)
);
}
} | #vulnerable code
public void fee(final String pid, final Cash fee) throws IOException {
if (!this.exists(pid)) {
throw new IllegalArgumentException(
new Par(
"Project %s doesn't exist, can't set fee"
).say(pid)
);
}
try (final Item item = this.item()) {
new Xocument(item.path()).modify(
new Directives().xpath(
String.format("/catalog/project[@id='%s']/fee", pid)
).strict(1).set(fee)
);
}
}
#location 6
#vulnerability type RESOURCE_LEAK |
Below is the vulnerable code, please generate the patch based on the following information. | #fixed code
@Test
public void givesBonus() throws Exception {
final Speed speed = new Speed(
new FkFarm(new FkProject()), "amihaiemil"
).bootstrap();
final String job = "gh:bonus/fast#1";
speed.add("TST100006", job, Duration.ofDays(1).toMinutes());
MatcherAssert.assertThat(speed.bonus(job), Matchers.equalTo(Tv.FIVE));
} | #vulnerable code
@Test
public void givesBonus() throws Exception {
final FkProject project = new FkProject();
final FkFarm farm = new FkFarm(project);
final Speed speed = new Speed(farm, "amihaiemil").bootstrap();
final String job = "gh:bonus/fast#1";
speed.add("TST100006", job, Tv.THOUSAND);
MatcherAssert.assertThat(speed.bonus(job), Matchers.equalTo(Tv.FIVE));
}
#location 5
#vulnerability type RESOURCE_LEAK |
Below is the vulnerable code, please generate the patch based on the following information. | #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)
);
} | #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 10
#vulnerability type RESOURCE_LEAK |
Below is the vulnerable code, please generate the patch based on the following information. | #fixed code
@Test
public void rejectsIfAlreadyApplied() throws Exception {
final Farm farm = new PropsFarm(new FkFarm());
final People people = new People(farm).bootstrap();
final String uid = "yegor256";
people.touch(uid);
people.apply(uid, Instant.now());
final RqWithUser req = new RqWithUser(
farm,
new RqFake("POST", "/join-post")
);
people.breakup(uid);
MatcherAssert.assertThat(
new TkApp(farm).act(
new RqWithBody(
req,
"personality=INTJ-A&stackoverflow=187241"
)
),
new HmRsHeader("Set-Cookie", Matchers.iterableWithSize(2))
);
} | #vulnerable code
@Test
public void rejectsIfAlreadyApplied() throws Exception {
final Farm farm = new PropsFarm(new FkFarm());
final People people = new People(farm).bootstrap();
final String uid = "yegor256";
people.touch(uid);
people.apply(uid, new Date());
final RqWithUser req = new RqWithUser(
farm,
new RqFake("POST", "/join-post")
);
people.breakup(uid);
MatcherAssert.assertThat(
new TkApp(farm).act(
new RqWithBody(
req,
"personality=INTJ-A&stackoverflow=187241"
)
),
new HmRsHeader("Set-Cookie", Matchers.iterableWithSize(2))
);
}
#location 13
#vulnerability type RESOURCE_LEAK |
Below is the vulnerable code, please generate the patch based on the following information. | #fixed code
@SuppressWarnings("unchecked")
public void exec() throws IOException {
final Props props = new Props();
if (props.has("//testing")) {
throw new IllegalStateException(
"Hey, we are in the testing mode!"
);
}
Sentry.init(props.get("//sentry/dsn", ""));
final Path temp = Paths.get("./s3farm").normalize();
if (!temp.toFile().mkdir()) {
throw new IllegalStateException(
String.format(
"Failed to mkdir \"%s\"", temp
)
);
}
try (
final Farm farm = new SmartFarm(
new S3Farm(new ExtBucket().value(), temp)
).value();
final SlackRadar radar = new SlackRadar(farm)
) {
new ExtMongobee(farm).apply();
new ExtTelegram(farm).value();
radar.refresh();
new GithubRoutine(farm).start();
new FtCli(
new TkApp(
farm,
new FkRegex("/slack", new TkSlack(farm, radar)),
new FkRegex("/alias", new TkAlias(farm)),
new FkRegex(
"/ghook",
new TkMethods(new TkGithub(farm), "POST")
)
),
this.arguments
).start(Exit.NEVER);
}
} | #vulnerable code
@SuppressWarnings("unchecked")
public void exec() throws IOException {
final Props props = new Props();
if (props.has("//testing")) {
throw new IllegalStateException(
"Hey, we are in the testing mode!"
);
}
Sentry.init(props.get("//sentry/dsn", ""));
try (
final Farm farm = new SmartFarm(
new S3Farm(new ExtBucket().value())
).value();
final SlackRadar radar = new SlackRadar(farm)
) {
new ExtMongobee(farm).apply();
new ExtTelegram(farm).value();
radar.refresh();
new GithubRoutine(farm).start();
new FtCli(
new TkApp(
farm,
new FkRegex("/slack", new TkSlack(farm, radar)),
new FkRegex("/alias", new TkAlias(farm)),
new FkRegex(
"/ghook",
new TkMethods(new TkGithub(farm), "POST")
)
),
this.arguments
).start(Exit.NEVER);
}
}
#location 12
#vulnerability type RESOURCE_LEAK |
Below is the vulnerable code, please generate the patch based on the following information. | #fixed code
@Test
public void rejectsIfAlreadyApplied() throws Exception {
final Farm farm = FkFarm.props();
final People people = new People(farm).bootstrap();
final String uid = "yegor256";
people.touch(uid);
people.apply(uid, Instant.now());
final Request req = new RqWithUser.WithInit(
farm,
new RqFake("POST", "/join-post")
);
people.breakup(uid);
MatcherAssert.assertThat(
new TkApp(farm).act(
new RqWithBody(
req,
"personality=INTJ-A&stackoverflow=187241"
)
),
new HmRsHeader("Set-Cookie", Matchers.iterableWithSize(2))
);
} | #vulnerable code
@Test
public void rejectsIfAlreadyApplied() throws Exception {
final Farm farm = new PropsFarm(new FkFarm());
final People people = new People(farm).bootstrap();
final String uid = "yegor256";
people.touch(uid);
people.apply(uid, Instant.now());
final Request req = new RqWithUser.WithInit(
farm,
new RqFake("POST", "/join-post")
);
people.breakup(uid);
MatcherAssert.assertThat(
new TkApp(farm).act(
new RqWithBody(
req,
"personality=INTJ-A&stackoverflow=187241"
)
),
new HmRsHeader("Set-Cookie", Matchers.iterableWithSize(2))
);
}
#location 13
#vulnerability type RESOURCE_LEAK |
Below is the vulnerable code, please generate the patch based on the following information. | #fixed code
@Test
public void parsesJson() throws Exception {
final Farm farm = new PropsFarm(new FkFarm());
final Take take = new TkGithub(
farm, (frm, github, event) -> "nothing"
);
MatcherAssert.assertThat(
take.act(
new RqWithBody(
new RqFake("POST", "/"),
String.format(
"payload=%s",
URLEncoder.encode(
"{\"foo\": \"bar\"}",
StandardCharsets.UTF_8.displayName()
)
)
)
),
new HmRsStatus(HttpURLConnection.HTTP_OK)
);
} | #vulnerable code
@Test
public void parsesJson() throws Exception {
MatcherAssert.assertThat(
new TkGithub(
new PropsFarm(),
new Rebound.Fake("nothing")
).act(
new RqWithBody(
new RqFake("POST", "/"),
String.format(
"payload=%s",
URLEncoder.encode(
"{\"foo\": \"bar\"}",
StandardCharsets.UTF_8.displayName()
)
)
)
),
new HmRsStatus(HttpURLConnection.HTTP_OK)
);
}
#location 7
#vulnerability type RESOURCE_LEAK |
Below is the vulnerable code, please generate the patch based on the following information. | #fixed code
@Test
public void removesOrder() 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());
orders.remove(job);
MatcherAssert.assertThat(
"Order not removed",
orders.iterate(),
new IsEmptyCollection<>()
);
} | #vulnerable code
@Test
public void removesOrder() 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");
orders.remove(job);
MatcherAssert.assertThat(
"Order not removed",
orders.iterate(),
new IsEmptyCollection<>()
);
}
#location 11
#vulnerability type RESOURCE_LEAK |
Below is the vulnerable code, please generate the patch based on the following information. | #fixed code
@Test
public void rendersReport() throws Exception {
final Farm farm = new FtFarm(new PropsFarm(new FkFarm()));
final String uid = "yegor256";
new ClaimOut()
.type("Order was given")
.param("login", uid)
.postTo(farm.find("@id='C00000000'").iterator().next());
MatcherAssert.assertThat(
XhtmlMatchers.xhtml(
new View(
farm,
"/report/C00000000?report=orders-given-by-week"
).xml()
),
XhtmlMatchers.hasXPaths("/page/rows/row[week]")
);
} | #vulnerable code
@Test
public void rendersReport() throws Exception {
final Farm farm = new FtFarm(new PropsFarm(new FkFarm()));
final String uid = "yegor256";
new ClaimOut()
.type("Order was given")
.param("login", uid)
.postTo(farm.find("@id='C00000000'").iterator().next());
MatcherAssert.assertThat(
XhtmlMatchers.xhtml(
new RsPrint(
new TkApp(farm).act(
new RqWithHeaders(
new RqWithUser(
farm,
new RqFake(
"GET",
// @checkstyle LineLength (1 line)
"/report/C00000000?report=orders-given-by-week"
)
),
"Accept: application/vnd.zerocracy+xml"
)
)
).printBody()
),
XhtmlMatchers.hasXPaths("/page/rows/row[week]")
);
}
#location 9
#vulnerability type RESOURCE_LEAK |
Below is the vulnerable code, please generate the patch based on the following information. | #fixed code
@Override
public Response act(final Request req) throws IOException {
final JsonObject callback = TkViber.json(
new TextOf(req.body()).asString()
);
if (callback.isEmpty()) {
throw new HttpException(HttpURLConnection.HTTP_BAD_REQUEST);
}
if (Objects.equals(callback.getString("event"), "message")) {
this.reaction.react(
this.bot, this.farm, new VbEvent.Simple(callback)
);
}
return new RsWithStatus(
HttpURLConnection.HTTP_OK
);
} | #vulnerable 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 (Objects.equals(callback.getString("event"), "message")) {
this.reaction.react(
this.bot, this.farm, new VbEvent.Simple(callback)
);
}
return new RsWithStatus(
HttpURLConnection.HTTP_OK
);
}
#location 3
#vulnerability type RESOURCE_LEAK |
Below is the vulnerable code, please generate the patch based on the following information. | #fixed code
@Test
public void rendersHomePage() throws Exception {
final Farm farm = new PropsFarm(new FkFarm());
MatcherAssert.assertThat(
XhtmlMatchers.xhtml(
new RsPrint(
new TkApp(farm).act(
new RqWithUser(
farm,
new RqFake(
"GET",
"/a/C00000000?a=pm/staff/roles"
)
)
)
).printBody()
),
XhtmlMatchers.hasXPaths("//xhtml:table")
);
} | #vulnerable code
@Test
public void rendersHomePage() throws Exception {
final Farm farm = new PropsFarm(new FkFarm());
final Catalog catalog = new Catalog(new Pmo(farm)).bootstrap();
final String pid = "A1B2C3D4F";
catalog.add(pid, String.format("2017/07/%s/", pid));
final Roles roles = new Roles(
farm.find(String.format("@id='%s'", pid)).iterator().next()
).bootstrap();
final String uid = "yegor256";
new People(new Pmo(farm)).bootstrap().invite(uid, "mentor");
roles.assign(uid, "PO");
final Take take = new TkApp(farm);
MatcherAssert.assertThat(
XhtmlMatchers.xhtml(
new RsPrint(
take.act(
new RqWithHeaders(
new RqFake(
"GET",
String.format("/a/%s?a=pm/staff/roles", pid)
),
// @checkstyle LineLength (1 line)
"Cookie: PsCookie=0975A5A5-F6DB193E-AF18000A-75726E3A-74657374-3A310005-6C6F6769-6E000879-65676F72-323536AE"
)
)
).printBody()
),
XhtmlMatchers.hasXPaths("//xhtml:table")
);
}
#location 13
#vulnerability type RESOURCE_LEAK |
Below is the vulnerable code, please generate the patch based on the following information. | #fixed code
@Override
public double vote(final String login, final StringBuilder log)
throws IOException {
final int mine = this.jobs.value().get(login);
final int smaller = new Filtered<>(
speed -> speed < mine,
this.jobs.value().values()
).size();
log.append(
Logger.format(
"Workload of %d jobs is no.%d",
mine, smaller + 1
)
);
return 1.0d - (double) smaller / (double) this.jobs.value().size();
} | #vulnerable code
@Override
public double vote(final String login, final StringBuilder log)
throws IOException {
final int jobs = new LengthOf(
new Agenda(this.pmo, login).jobs()
).intValue();
log.append(
new Par(
"%d out of %d job(s) in agenda"
).say(jobs, this.max)
);
return (double) (this.max - Math.min(jobs, this.max))
/ (double) this.max;
}
#location 10
#vulnerability type RESOURCE_LEAK |
Below is the vulnerable code, please generate the patch based on the following information. | #fixed code
@Test
@SuppressWarnings("unchecked")
public void 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()
)
)
)
)
)
);
} | #vulnerable 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()
)
)
)
)
)
);
}
#location 11
#vulnerability type RESOURCE_LEAK |
Below is the vulnerable code, please generate the patch based on the following information. | #fixed code
public void pause(final String pid,
final boolean pause) throws IOException {
this.checkExist(pid);
try (final Item item = this.item()) {
new Xocument(item.path()).modify(
new Directives().xpath(
String.format("/catalog/project[@id='%s']/alive", pid)
).strict(1).set(!pause)
);
}
} | #vulnerable code
public void pause(final String pid,
final boolean pause) throws IOException {
if (!this.exists(pid)) {
throw new IllegalArgumentException(
new Par("Project %s doesn't exist, can't pause").say(pid)
);
}
try (final Item item = this.item()) {
new Xocument(item.path()).modify(
new Directives().xpath(
String.format("/catalog/project[@id='%s']/alive", pid)
).strict(1).set(!pause)
);
}
}
#location 5
#vulnerability type RESOURCE_LEAK |
Below is the vulnerable code, please generate the patch based on the following information. | #fixed code
public String adviser(final String pid) throws IOException {
this.checkExist(pid);
try (final Item item = this.item()) {
return new Xocument(item.path()).xpath(
String.format(
"/catalog/project[@id = '%s']/adviser/text()",
pid
)
).get(0);
}
} | #vulnerable code
public String adviser(final String pid) throws IOException {
if (!this.exists(pid)) {
throw new IllegalArgumentException(
new Par(
"Project %s doesn't exist, can't get adviser"
).say(pid)
);
}
try (final Item item = this.item()) {
return new Xocument(item.path()).xpath(
String.format(
"/catalog/project[@id = '%s']/adviser/text()",
pid
)
).get(0);
}
}
#location 6
#vulnerability type RESOURCE_LEAK |
Below is the vulnerable code, please generate the patch based on the following information. | #fixed code
public double speed(final String uid) throws IOException {
this.checkExisting(uid);
try (final Item item = this.item()) {
return new NumberOf(
new Xocument(item.path()).xpath(
String.format(
"/people/person[@id='%s']/speed/text()",
uid
),
"0.0"
)
).doubleValue();
}
} | #vulnerable code
public double speed(final String uid) throws IOException {
if (!this.exists(uid)) {
throw new IllegalArgumentException(
new Par("Person @%s doesn't exist").say(uid)
);
}
try (final Item item = this.item()) {
return new NumberOf(
new Xocument(item.path()).xpath(
String.format(
"/people/person[@id='%s']/speed/text()",
uid
),
"0.0"
)
).doubleValue();
}
}
#location 4
#vulnerability type RESOURCE_LEAK |
Below is the vulnerable code, please generate the patch based on the following information. | #fixed code
public Collection<String> links(final String pid, final String rel)
throws IOException {
this.checkExist(pid);
try (final Item item = this.item()) {
return new Xocument(item).xpath(
String.format(
"/catalog/project[@id='%s']/links/link[@rel='%s']/@href",
pid, rel
)
);
}
} | #vulnerable code
public Collection<String> links(final String pid, final String rel)
throws IOException {
if (!this.exists(pid)) {
throw new IllegalArgumentException(
new Par(
"Project %s doesn't exist, can't get links"
).say(pid)
);
}
try (final Item item = this.item()) {
return new Xocument(item).xpath(
String.format(
"/catalog/project[@id='%s']/links/link[@rel='%s']/@href",
pid, rel
)
);
}
}
#location 7
#vulnerability type RESOURCE_LEAK |
Below is the vulnerable code, please generate the patch based on the following information. | #fixed code
@Test
public void rendersProfilePageWithRateInFirefox() throws Exception {
final Farm farm = FkFarm.props();
final double rate = 99.99;
final People people = new People(farm).bootstrap();
people.rate(
"yegor256", new Cash.S(String.format("USD %f", rate))
);
MatcherAssert.assertThat(
new View(farm, "/u/yegor256").html(),
Matchers.containsString(
String.format(
"rate</a> is <span style=\"color:darkgreen\">$%.2f</span>",
rate
)
)
);
} | #vulnerable code
@Test
public void rendersProfilePageWithRateInFirefox() throws Exception {
final Farm farm = new PropsFarm(new FkFarm());
final double rate = 99.99;
final People people = new People(farm).bootstrap();
people.rate(
"yegor256", new Cash.S(String.format("USD %f", rate))
);
MatcherAssert.assertThat(
new View(farm, "/u/yegor256").html(),
Matchers.containsString(
String.format(
"rate</a> is <span style=\"color:darkgreen\">$%.2f</span>",
rate
)
)
);
}
#location 10
#vulnerability type RESOURCE_LEAK |
Below is the vulnerable code, please generate the patch based on the following information. | #fixed code
@Override
public Response act(final Request request) throws IOException {
return new RsWithType(
new RsWithBody(
new BufferedInputStream(
new HeapDump(this.bucket.value(), "").load()
)
),
"application/octet-stream"
);
} | #vulnerable code
@Override
public Response act(final Request request) throws IOException {
return new RsWithType(
new RsWithBody(
new BufferedInputStream(
new HeapDump(new ExtBucket().value(), "").load()
)
),
"application/octet-stream"
);
}
#location 6
#vulnerability type RESOURCE_LEAK |
Below is the vulnerable code, please generate the patch based on the following information. | #fixed code
public int jobs(final String uid) throws IOException {
this.checkExisting(uid);
try (final Item item = this.item()) {
return new NumberOf(
new Xocument(item.path()).xpath(
String.format(
"/people/person[@id='%s']/jobs/text()",
uid
),
"0"
)
).intValue();
}
} | #vulnerable code
public int jobs(final String uid) throws IOException {
if (!this.exists(uid)) {
throw new IllegalArgumentException(
new Par("Person @%s doesn't exist").say(uid)
);
}
try (final Item item = this.item()) {
return new NumberOf(
new Xocument(item.path()).xpath(
String.format(
"/people/person[@id='%s']/jobs/text()",
uid
),
"0"
)
).intValue();
}
}
#location 4
#vulnerability type RESOURCE_LEAK |
Below is the vulnerable code, please generate the patch based on the following information. | #fixed code
@Test
public void redirectsWhenAccessingNonexistentUsersAgenda()
throws Exception {
final Farm farm = new PropsFarm(new FkFarm());
new People(farm).bootstrap().touch("yegor256");
MatcherAssert.assertThat(
new RsPrint(
new TkApp(farm).act(
new RqWithUser.WithInit(
farm,
new RqFake("GET", "/u/foo-user/agenda")
)
)
),
new HmRsStatus(HttpURLConnection.HTTP_SEE_OTHER)
);
} | #vulnerable code
@Test
public void redirectsWhenAccessingNonexistentUsersAgenda()
throws Exception {
final Farm farm = new PropsFarm(new FkFarm());
new People(farm).bootstrap().touch("yegor256");
MatcherAssert.assertThat(
new RsPrint(
new TkApp(farm).act(
new RqWithUser(
farm,
new RqFake("GET", "/u/foo-user/agenda")
)
)
),
new HmRsStatus(HttpURLConnection.HTTP_SEE_OTHER)
);
}
#location 6
#vulnerability type RESOURCE_LEAK |
Below is the vulnerable code, please generate the patch based on the following information. | #fixed code
@Test
public void findsBasicNumbers() throws Exception {
MatcherAssert.assertThat(
new Policy(FkFarm.props()).get("1.min-rep", "???"),
Matchers.startsWith("??")
);
} | #vulnerable code
@Test
public void findsBasicNumbers() throws Exception {
MatcherAssert.assertThat(
new Policy(new PropsFarm(new FkFarm())).get("1.min-rep", "???"),
Matchers.startsWith("??")
);
}
#location 3
#vulnerability type RESOURCE_LEAK |
Below is the vulnerable code, please generate the patch based on the following information. | #fixed code
@Test
public void rendersSingleArtifact() throws Exception {
final Farm farm = FkFarm.props();
MatcherAssert.assertThat(
XhtmlMatchers.xhtml(
new RsPrint(
new TkApp(farm).act(
new RqWithUser.WithInit(
farm,
new RqFake(
"GET",
"/xml/C00000000?file=roles.xml"
)
)
)
).printBody()
),
XhtmlMatchers.hasXPaths("/roles")
);
} | #vulnerable code
@Test
public void rendersSingleArtifact() throws Exception {
final Farm farm = new PropsFarm(new FkFarm());
MatcherAssert.assertThat(
XhtmlMatchers.xhtml(
new RsPrint(
new TkApp(farm).act(
new RqWithUser.WithInit(
farm,
new RqFake(
"GET",
"/xml/C00000000?file=roles.xml"
)
)
)
).printBody()
),
XhtmlMatchers.hasXPaths("/roles")
);
}
#location 4
#vulnerability type RESOURCE_LEAK |
Below is the vulnerable code, please generate the patch based on the following information. | #fixed code
@Test
public void acceptIfNeverApplied() throws Exception {
final Farm farm = new PropsFarm(new FkFarm());
final People people = new People(farm).bootstrap();
final String uid = "yegor256";
people.touch(uid);
final Request req = new RqWithUser(
farm,
new RqFake("POST", "/join-post"),
uid
);
people.breakup(uid);
MatcherAssert.assertThat(
new TkApp(farm).act(
new RqWithBody(
req,
// @checkstyle LineLength (1 line)
"personality=INTJ-A&stackoverflow=187241&telegram=123&about=txt"
)
),
Matchers.allOf(
new HmRsStatus(HttpURLConnection.HTTP_SEE_OTHER),
new HmRsHeader("Location", "/")
)
);
} | #vulnerable code
@Test
public void acceptIfNeverApplied() throws Exception {
final Farm farm = new PropsFarm(new FkFarm());
final People people = new People(farm).bootstrap();
final String uid = "yegor256";
people.touch(uid);
final RqWithUser req = new RqWithUser(
farm,
new RqFake("POST", "/join-post")
);
people.breakup(uid);
MatcherAssert.assertThat(
new TkApp(farm).act(
new RqWithBody(
req,
// @checkstyle LineLength (1 line)
"personality=INTJ-A&stackoverflow=187241&telegram=123&about=txt"
)
),
Matchers.allOf(
new HmRsStatus(HttpURLConnection.HTTP_SEE_OTHER),
new HmRsHeader("Location", "/")
)
);
}
#location 25
#vulnerability type RESOURCE_LEAK |
Below is the vulnerable code, please generate the patch based on the following information. | #fixed code
@Test
public void renderClaimXml() throws Exception {
final Farm farm = new FtFarm(new PropsFarm(new FkFarm()));
final long cid = 42L;
final ClaimOut claim = new ClaimOut().type("test").cid(cid);
claim.postTo(farm.find("@id='C00000000'").iterator().next());
MatcherAssert.assertThat(
XhtmlMatchers.xhtml(
new RsPrint(
new TkApp(farm).act(
new RqWithHeaders(
new RqWithUser(
farm,
new RqFake(
"GET",
String.format(
"/footprint/C00000000/%d", cid
)
)
),
"Accept: application/xml"
)
)
).printBody()
),
XhtmlMatchers.hasXPaths(
String.format("/page/claim/cid[text() = %d]", cid)
)
);
} | #vulnerable code
@Test
public void renderClaimXml() throws Exception {
final Farm farm = new FtFarm(new PropsFarm(new FkFarm()));
final Catalog catalog = new Catalog(new Pmo(farm)).bootstrap();
final String pid = "A1B2C3D4F";
catalog.add(pid, String.format("2017/07/%s/", pid));
final Project pkt = farm.find(String.format("@id='%s'", pid))
.iterator().next();
final Roles roles = new Roles(
pkt
).bootstrap();
final String uid = "yegor256";
new People(new Pmo(farm)).bootstrap().invite(uid, "mentor");
roles.assign(uid, "PO");
final Take take = new TkApp(farm);
final long cid = 42L;
final ClaimOut claim = new ClaimOut().type("test").cid(cid);
claim.postTo(pkt);
MatcherAssert.assertThat(
XhtmlMatchers.xhtml(
new RsPrint(
take.act(
new RqWithHeaders(
new RqFake(
"GET",
String.format("/footprint/%s/%d", pid, cid)
),
// @checkstyle LineLength (1 line)
"Cookie: PsCookie=0975A5A5-F6DB193E-AF18000A-75726E3A-74657374-3A310005-6C6F6769-6E000879-65676F72-323536AE",
"Accept: application/xml"
)
)
).printBody()
),
XhtmlMatchers.hasXPaths(
String.format("/page/claim/cid[text() = %d]", cid)
)
);
}
#location 15
#vulnerability type RESOURCE_LEAK |
Below is the vulnerable code, please generate the patch based on the following information. | #fixed code
@SuppressWarnings("unchecked")
public void exec() throws IOException {
final Props props = new Props();
if (props.has("//testing")) {
throw new IllegalStateException(
"Hey, we are in the testing mode!"
);
}
Sentry.init(props.get("//sentry/dsn", ""));
final Path temp = Paths.get("./s3farm").normalize();
if (!temp.toFile().mkdir()) {
throw new IllegalStateException(
String.format(
"Failed to mkdir \"%s\"", temp
)
);
}
try (
final Farm farm = new SmartFarm(
new S3Farm(new ExtBucket().value(), temp)
).value();
final SlackRadar radar = new SlackRadar(farm)
) {
new ExtMongobee(farm).apply();
new ExtTelegram(farm).value();
radar.refresh();
new GithubRoutine(farm).start();
new FtCli(
new TkApp(
farm,
new FkRegex("/slack", new TkSlack(farm, radar)),
new FkRegex("/alias", new TkAlias(farm)),
new FkRegex(
"/ghook",
new TkMethods(new TkGithub(farm), "POST")
)
),
this.arguments
).start(Exit.NEVER);
}
} | #vulnerable code
@SuppressWarnings("unchecked")
public void exec() throws IOException {
final Props props = new Props();
if (props.has("//testing")) {
throw new IllegalStateException(
"Hey, we are in the testing mode!"
);
}
Sentry.init(props.get("//sentry/dsn", ""));
try (
final Farm farm = new SmartFarm(
new S3Farm(new ExtBucket().value())
).value();
final SlackRadar radar = new SlackRadar(farm)
) {
new ExtMongobee(farm).apply();
new ExtTelegram(farm).value();
radar.refresh();
new GithubRoutine(farm).start();
new FtCli(
new TkApp(
farm,
new FkRegex("/slack", new TkSlack(farm, radar)),
new FkRegex("/alias", new TkAlias(farm)),
new FkRegex(
"/ghook",
new TkMethods(new TkGithub(farm), "POST")
)
),
this.arguments
).start(Exit.NEVER);
}
}
#location 12
#vulnerability type RESOURCE_LEAK |
Below is the vulnerable code, please generate the patch based on the following information. | #fixed code
@Test
public void 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
)
)
);
} | #vulnerable 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
)
)
);
}
#location 3
#vulnerability type RESOURCE_LEAK |
Below is the vulnerable code, please generate the patch based on the following information. | #fixed code
public void adviser(final String pid, final String adviser)
throws IOException {
this.checkExist(pid);
try (final Item item = this.item()) {
new Xocument(item.path()).modify(
new Directives().xpath(
String.format(
"/catalog/project[@id = '%s']",
pid
)
).addIf("adviser").set(adviser)
);
}
} | #vulnerable code
public void adviser(final String pid, final String adviser)
throws IOException {
if (!this.exists(pid)) {
throw new IllegalArgumentException(
new Par(
"Project %s doesn't exist, can't get adviser"
).say(pid)
);
}
try (final Item item = this.item()) {
new Xocument(item.path()).modify(
new Directives().xpath(
String.format(
"/catalog/project[@id = '%s']",
pid
)
).addIf("adviser").set(adviser)
);
}
}
#location 7
#vulnerability type RESOURCE_LEAK |
Below is the vulnerable code, please generate the patch based on the following information. | #fixed code
@Test
public void handlesPullRequest() throws IOException {
final MkGithub github = new MkGithub("smith");
final FkProject pkt = new FkProject();
final Roles roles = new Roles(pkt).bootstrap();
roles.assign("jeff", "ARC");
roles.assign("john", "REV");
MatcherAssert.assertThat(
new RbPingArchitect().react(
new FkFarm(pkt.pid(), pkt),
github,
RbPingArchitectTest.event(false, github)
),
Matchers.is("Some REV will pick it up")
);
} | #vulnerable code
@Test
public void handlesPullRequest() throws IOException {
final MkGithub github = new MkGithub("jeff");
final JsonObjectBuilder builder =
RbPingArchitectTest.event(false, github, "smith");
final FkProject pkt = new FkProject();
final FkFarm farm = new FkFarm(pkt.pid(), pkt);
final Roles roles = new Roles(pkt).bootstrap();
roles.assign("jeff", "ARC");
roles.assign("john", "REV");
MatcherAssert.assertThat(
new RbPingArchitect().react(farm, github, builder.build()),
Matchers.is("Some REV will pick it up")
);
}
#location 12
#vulnerability type RESOURCE_LEAK |
Below is the vulnerable code, please generate the patch based on the following information. | #fixed code
@Loggable
@SuppressWarnings("PMD.AvoidCatchingThrowable")
public static void main(final String... args) throws IOException {
final Props props = new Props();
if (props.has("//testing")) {
throw new IllegalStateException(
"Hey, we are in the testing mode!"
);
}
final long start = System.currentTimeMillis();
try {
new Main(args).exec();
} catch (final Throwable ex) {
new SafeSentry(new PropsFarm()).capture(ex);
Logger.error(Main.class, "The main app crashed: %[exception]s", ex);
throw new IOException(ex);
} finally {
Logger.info(
Main.class, "Finished after %[ms]s of activity",
System.currentTimeMillis() - start
);
}
} | #vulnerable code
@Loggable
@SuppressWarnings("PMD.AvoidCatchingThrowable")
public static void main(final String... args) throws IOException {
final Props props = new Props();
if (props.has("//testing")) {
throw new IllegalStateException(
"Hey, we are in the testing mode!"
);
}
final long start = System.currentTimeMillis();
try {
Runtime.getRuntime()
.exec("ping -c1 data.0crat.com.s3.amazonaws.com")
.waitFor();
new Main(args).exec();
} catch (final Throwable ex) {
new SafeSentry(new PropsFarm()).capture(ex);
Logger.error(Main.class, "The main app crashed: %[exception]s", ex);
throw new IOException(ex);
} finally {
Logger.info(
Main.class, "Finished after %[ms]s of activity",
System.currentTimeMillis() - start
);
}
}
#location 17
#vulnerability type RESOURCE_LEAK |
Below is the vulnerable code, please generate the patch based on the following information. | #fixed code
public void title(final String pid, final String title)
throws IOException {
this.checkExist(pid);
try (final Item item = this.item()) {
new Xocument(item.path()).modify(
new Directives()
.xpath(String.format("/catalog/project[@id = '%s']", pid))
.strict(1)
.addIf(Catalog.PRJ_TITLE)
.set(title)
);
}
} | #vulnerable code
public void title(final String pid, final String title)
throws IOException {
if (!this.exists(pid)) {
throw new IllegalArgumentException(
new Par(
"Project %s doesn't exist, can't change title"
).say(pid)
);
}
try (final Item item = this.item()) {
new Xocument(item.path()).modify(
new Directives()
.xpath(String.format("/catalog/project[@id = '%s']", pid))
.strict(1)
.addIf(Catalog.PRJ_TITLE)
.set(title)
);
}
}
#location 7
#vulnerability type RESOURCE_LEAK |
Below is the vulnerable code, please generate the patch based on the following information. | #fixed code
@Override
public Response act(final RqRegex req) throws IOException {
final Project project = new RqProject(this.farm, req, "PO");
final RqFormSmart form = new RqFormSmart(new RqGreedy(req));
final String email = form.single("email");
final Cash amount = new Cash.S(
String.format(
"USD %.2f",
// @checkstyle MagicNumber (1 line)
Double.parseDouble(form.single("cents")) / 100.0d
)
);
final Stripe stripe = new Stripe(this.farm);
final String customer;
final String pid;
try {
customer = stripe.register(
form.single("token"), email
);
pid = stripe.charge(
customer, amount,
new Par(this.farm, "Project %s funded").say(project.pid())
);
} catch (final Stripe.PaymentException ex) {
throw new RsForward(
new RsParFlash(ex),
String.format("/p/%s", project.pid())
);
}
final String user = new RqUser(this.farm, req).value();
new ClaimOut()
.type("Funded by Stripe")
.param("amount", amount)
.param("stripe_customer", customer)
.param("payment_id", pid)
.param("email", email)
.author(user)
.postTo(project);
new ClaimOut().type("Notify PMO").param(
"message", new Par(
"Project %s was funded for %s by @%s;",
"customer `%s`, payment `%s`"
).say(project.pid(), amount, user, customer, pid)
).postTo(this.farm);
return new RsForward(
new RsParFlash(
new Par(
"The project %s was successfully funded for %s;",
"the ledger will be updated in a few minutes;",
"payment ID is `%s`"
).say(project.pid(), amount, pid),
Level.INFO
),
String.format("/p/%s", project.pid())
);
} | #vulnerable code
@Override
public Response act(final RqRegex req) throws IOException {
final Project project = new RqProject(this.farm, req, "PO");
final RqFormSmart form = new RqFormSmart(new RqGreedy(req));
final String email = form.single("email");
final String customer;
try {
customer = new Stripe(this.farm).pay(
form.single("token"),
email,
String.format(
"%s/%s",
project.pid(),
new Catalog(this.farm).title(project.pid())
)
);
} catch (final Stripe.PaymentException ex) {
throw new RsForward(
new RsParFlash(ex),
String.format("/p/%s", project.pid())
);
}
final Cash amount = new Cash.S(
String.format(
"USD %.2f",
// @checkstyle MagicNumber (1 line)
Double.parseDouble(form.single("cents")) / 100.0d
)
);
final String user = new RqUser(this.farm, req).value();
new ClaimOut()
.type("Funded by Stripe")
.param("amount", amount)
.param("stripe_customer", customer)
.param("email", email)
.author(user)
.postTo(project);
new ClaimOut().type("Notify PMO").param(
"message", new Par(
"Project %s was funded for %s by @%s"
).say(project.pid(), amount, user)
).postTo(this.farm);
return new RsForward(
new RsParFlash(
new Par(
"The project %s was successfully funded for %s.",
"The ledger will be updated in a few minutes."
).say(project.pid(), amount),
Level.INFO
),
String.format("/p/%s", project.pid())
);
}
#location 48
#vulnerability type RESOURCE_LEAK |
Below is the vulnerable code, please generate the patch based on the following information. | #fixed code
public void reputation(final String uid, final int rep)
throws IOException {
this.checkExisting(uid);
try (final Item item = this.item()) {
new Xocument(item.path()).modify(
new Directives().xpath(
String.format(
"/people/person[@id='%s']",
uid
)
).addIf("reputation").set(rep)
);
}
} | #vulnerable code
public void reputation(final String uid, final int rep)
throws IOException {
if (!this.exists(uid)) {
throw new IllegalArgumentException(
new Par("Person @%s doesn't exist").say(uid)
);
}
try (final Item item = this.item()) {
new Xocument(item.path()).modify(
new Directives().xpath(
String.format(
"/people/person[@id='%s']",
uid
)
).addIf("reputation").set(rep)
);
}
}
#location 5
#vulnerability type RESOURCE_LEAK |
Below is the vulnerable code, please generate the patch based on the following information. | #fixed code
@Test
public void addsClaims() throws Exception {
final Farm farm = new PropsFarm();
final Project project = farm.find("@id='FOOTPRNTX'").iterator().next();
new ClaimOut().type("hello").postTo(project);
final XML xml = new Claims(project).iterate().iterator().next();
try (final Footprint footprint = new Footprint(farm, project)) {
footprint.open(xml);
footprint.close(xml);
MatcherAssert.assertThat(
footprint.collection().find(
Filters.eq("project", project.pid())
),
Matchers.iterableWithSize(1)
);
}
} | #vulnerable code
@Test
public void addsClaims() throws Exception {
final Farm farm = new PropsFarm();
final Project project = new Pmo(farm);
new ClaimOut().type("hello").postTo(project);
final XML xml = new Claims(project).iterate().iterator().next();
try (final Footprint footprint = new Footprint(farm, project)) {
footprint.open(xml);
footprint.close(xml);
MatcherAssert.assertThat(
footprint.collection().find(
Filters.eq("project", project.pid())
),
Matchers.iterableWithSize(1)
);
}
}
#location 7
#vulnerability type RESOURCE_LEAK |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.