input
stringlengths 205
73.3k
| output
stringlengths 64
73.2k
| instruction
stringclasses 1
value |
---|---|---|
#vulnerable code
public void run() throws IOException {
// Add shutdown hook
addShutdownHook();
claimedRingGroupConductor = false;
LOG.info("Ring Group Conductor for ring group " + ringGroupName + " starting.");
try {
ringGroup = coordinator.getRingGroup(ringGroupName);
// attempt to claim the ring group conductor title
if (ringGroup.claimRingGroupConductor(configurator.getInitialMode())) {
claimedRingGroupConductor = true;
// we are now *the* ring group conductor for this ring group.
domainGroup = ringGroup.getDomainGroup();
// set a watch on the ring group
ringGroup.setListener(this);
// set a watch on the domain group version
domainGroup.setListener(this);
// loop until we're taken down
stopping = false;
try {
while (!stopping) {
// take a snapshot of the current ring, since it might get changed
// while we're processing the current update.
RingGroup snapshotRingGroup;
synchronized (lock) {
snapshotRingGroup = ringGroup;
}
// Only process updates if ring group conductor is configured to be active/proactive
if (snapshotRingGroup.getRingGroupConductorMode() == RingGroupConductorMode.ACTIVE ||
snapshotRingGroup.getRingGroupConductorMode() == RingGroupConductorMode.PROACTIVE) {
processUpdates(snapshotRingGroup);
}
Thread.sleep(configurator.getSleepInterval());
}
} catch (InterruptedException e) {
// daemon is going down.
}
} else {
LOG.info("Attempted to claim Ring Group Conductor status, but there was already a lock in place!");
}
} catch (Throwable t) {
LOG.fatal("unexpected exception!", t);
} finally {
releaseIfClaimed();
}
LOG.info("Ring Group Conductor for ring group " + ringGroupName + " shutting down.");
// Remove shutdown hook. We don't need it anymore
removeShutdownHook();
}
#location 14
#vulnerability type THREAD_SAFETY_VIOLATION | #fixed code
public void run() throws IOException {
// Add shutdown hook
addShutdownHook();
claimedRingGroupConductor = false;
LOG.info("Ring Group Conductor for ring group " + ringGroupName + " starting.");
try {
ringGroup = coordinator.getRingGroup(ringGroupName);
// attempt to claim the ring group conductor title
if (ringGroup.claimRingGroupConductor(configurator.getInitialMode())) {
claimedRingGroupConductor = true;
// loop until we're taken down
stopping = false;
try {
while (!stopping) {
// take a snapshot of the current ring, since it might get changed
// while we're processing the current update.
RingGroup snapshotRingGroup;
synchronized (lock) {
snapshotRingGroup = ringGroup;
}
// Only process updates if ring group conductor is configured to be active/proactive
if (snapshotRingGroup.getRingGroupConductorMode() == RingGroupConductorMode.ACTIVE ||
snapshotRingGroup.getRingGroupConductorMode() == RingGroupConductorMode.PROACTIVE) {
processUpdates(snapshotRingGroup);
}
Thread.sleep(configurator.getSleepInterval());
}
} catch (InterruptedException e) {
// daemon is going down.
}
} else {
LOG.info("Attempted to claim Ring Group Conductor status, but there was already a lock in place!");
}
} catch (Throwable t) {
LOG.fatal("unexpected exception!", t);
} finally {
releaseIfClaimed();
}
LOG.info("Ring Group Conductor for ring group " + ringGroupName + " shutting down.");
// Remove shutdown hook. We don't need it anymore
removeShutdownHook();
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
private ByteBuffer decompressBlock(ByteBuffer block) throws IOException {
Buffers buffers = threadLocalBuffers.get();
buffers.reset();
// Decompress the block
InputStream blockInputStream =
new ByteArrayInputStream(block.array(), block.arrayOffset() + block.position(), block.remaining());
// Build an InputStream corresponding to the compression codec
InputStream decompressedBlockInputStream = getBlockCompressionInputStream(blockInputStream);
// Decompress into the specialized result buffer
IOStreamUtils.copy(decompressedBlockInputStream, buffers.getDecompressionOutputStream(), buffers.getCopyBuffer());
decompressedBlockInputStream.close();
return buffers.getDecompressionOutputStream().getByteBuffer();
}
#location 12
#vulnerability type RESOURCE_LEAK | #fixed code
private ByteBuffer decompressBlock(ByteBuffer block) throws IOException {
Local local = threadLocal.get();
local.reset();
local.getBlockDecompressor().decompress(
block.array(),
block.arrayOffset() + block.position(),
block.remaining(),
local.getDecompressionOutputStream());
return local.getDecompressionOutputStream().getByteBuffer();
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
public void run() throws IOException {
// Add shutdown hook
addShutdownHook();
claimedRingGroupConductor = false;
LOG.info("Ring Group Conductor for ring group " + ringGroupName + " starting.");
try {
ringGroup = coordinator.getRingGroup(ringGroupName);
// attempt to claim the ring group conductor title
if (ringGroup.claimRingGroupConductor(configurator.getInitialMode())) {
claimedRingGroupConductor = true;
// we are now *the* ring group conductor for this ring group.
domainGroup = ringGroup.getDomainGroup();
// set a watch on the ring group
ringGroup.setListener(this);
// set a watch on the domain group version
domainGroup.setListener(this);
// loop until we're taken down
stopping = false;
try {
while (!stopping) {
// take a snapshot of the current ring, since it might get changed
// while we're processing the current update.
RingGroup snapshotRingGroup;
synchronized (lock) {
snapshotRingGroup = ringGroup;
}
// Only process updates if ring group conductor is configured to be active/proactive
if (snapshotRingGroup.getRingGroupConductorMode() == RingGroupConductorMode.ACTIVE ||
snapshotRingGroup.getRingGroupConductorMode() == RingGroupConductorMode.PROACTIVE) {
processUpdates(snapshotRingGroup);
}
Thread.sleep(configurator.getSleepInterval());
}
} catch (InterruptedException e) {
// daemon is going down.
}
} else {
LOG.info("Attempted to claim Ring Group Conductor status, but there was already a lock in place!");
}
} catch (Throwable t) {
LOG.fatal("unexpected exception!", t);
} finally {
releaseIfClaimed();
}
LOG.info("Ring Group Conductor for ring group " + ringGroupName + " shutting down.");
// Remove shutdown hook. We don't need it anymore
removeShutdownHook();
}
#location 20
#vulnerability type THREAD_SAFETY_VIOLATION | #fixed code
public void run() throws IOException {
// Add shutdown hook
addShutdownHook();
claimedRingGroupConductor = false;
LOG.info("Ring Group Conductor for ring group " + ringGroupName + " starting.");
try {
ringGroup = coordinator.getRingGroup(ringGroupName);
// attempt to claim the ring group conductor title
if (ringGroup.claimRingGroupConductor(configurator.getInitialMode())) {
claimedRingGroupConductor = true;
// loop until we're taken down
stopping = false;
try {
while (!stopping) {
// take a snapshot of the current ring, since it might get changed
// while we're processing the current update.
RingGroup snapshotRingGroup;
synchronized (lock) {
snapshotRingGroup = ringGroup;
}
// Only process updates if ring group conductor is configured to be active/proactive
if (snapshotRingGroup.getRingGroupConductorMode() == RingGroupConductorMode.ACTIVE ||
snapshotRingGroup.getRingGroupConductorMode() == RingGroupConductorMode.PROACTIVE) {
processUpdates(snapshotRingGroup);
}
Thread.sleep(configurator.getSleepInterval());
}
} catch (InterruptedException e) {
// daemon is going down.
}
} else {
LOG.info("Attempted to claim Ring Group Conductor status, but there was already a lock in place!");
}
} catch (Throwable t) {
LOG.fatal("unexpected exception!", t);
} finally {
releaseIfClaimed();
}
LOG.info("Ring Group Conductor for ring group " + ringGroupName + " shutting down.");
// Remove shutdown hook. We don't need it anymore
removeShutdownHook();
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
public void testGzipBlockCompression() throws Exception {
ByteArrayOutputStream s = new ByteArrayOutputStream();
MapWriter keyfileWriter = new MapWriter();
CurlyWriter writer = new CurlyWriter(s, keyfileWriter, 3, -1, BlockCompressionCodec.GZIP, 1024, 2);
writer.write(KEY1, VALUE1);
writer.write(KEY2, VALUE2);
writer.write(KEY3, VALUE3);
writer.close();
assertTrue(writer.getNumBytesWritten() > 0);
assertEquals(3, writer.getNumRecordsWritten());
// verify the keyfile looks as expected
assertTrue(keyfileWriter.entries.containsKey(KEY1));
System.out.println("k1=" + Bytes.bytesToHexString(keyfileWriter.entries.get(KEY1))); //TODO: remove
System.out.println("k2=" + Bytes.bytesToHexString(keyfileWriter.entries.get(KEY2))); //TODO: remove
System.out.println("k3=" + Bytes.bytesToHexString(keyfileWriter.entries.get(KEY3))); //TODO: remove
assertEquals(ByteBuffer.wrap(new byte[]{0, 0, 0, 0, 0}), keyfileWriter.entries.get(KEY1));
assertTrue(keyfileWriter.entries.containsKey(KEY2));
assertEquals(ByteBuffer.wrap(new byte[]{0, 0, 0, 5, 0}), keyfileWriter.entries.get(KEY2));
assertTrue(keyfileWriter.entries.containsKey(KEY3));
assertEquals(ByteBuffer.wrap(new byte[]{0, 0, 0, 10, 0}), keyfileWriter.entries.get(KEY3));
assertFalse(keyfileWriter.entries.containsKey(KEY4));
// verify that the record stream looks as expected
System.out.println(Bytes.bytesToHexString(ByteBuffer.wrap(s.toByteArray()))); //TODO: remove
assertEquals(ByteBuffer.wrap(EXPECTED_RECORD_FILE_BLOCK_COMPRESSED_GZIP), ByteBuffer.wrap(s.toByteArray()));
}
#location 16
#vulnerability type NULL_DEREFERENCE | #fixed code
public void testGzipBlockCompression() throws Exception {
ByteArrayOutputStream s = new ByteArrayOutputStream();
MapWriter keyfileWriter = new MapWriter();
CurlyWriter writer = new CurlyWriter(s, keyfileWriter, 3, -1, BlockCompressionCodec.GZIP, 1024, 2);
writer.write(KEY1, VALUE1);
writer.write(KEY2, VALUE2);
writer.write(KEY3, VALUE3);
writer.close();
assertTrue(writer.getNumBytesWritten() > 0);
assertEquals(3, writer.getNumRecordsWritten());
// verify the keyfile looks as expected
assertTrue(keyfileWriter.entries.containsKey(KEY1));
assertEquals(ByteBuffer.wrap(new byte[]{0, 0, 0, 0, 0}), keyfileWriter.entries.get(KEY1));
assertTrue(keyfileWriter.entries.containsKey(KEY2));
assertEquals(ByteBuffer.wrap(new byte[]{0, 0, 0, 5, 0}), keyfileWriter.entries.get(KEY2));
assertTrue(keyfileWriter.entries.containsKey(KEY3));
assertEquals(ByteBuffer.wrap(new byte[]{0, 0, 0, 10, 0}), keyfileWriter.entries.get(KEY3));
assertFalse(keyfileWriter.entries.containsKey(KEY4));
// verify that the record stream looks as expected
assertEquals(ByteBuffer.wrap(EXPECTED_RECORD_FILE_BLOCK_COMPRESSED_GZIP), ByteBuffer.wrap(s.toByteArray()));
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
public void aggregate(DoublePopulationStatisticsAggregator other) {
if (numValues == 0) {
// Copy deciles directly
System.arraycopy(other.deciles, 0, deciles, 0, 9);
} else if (other.numValues == 0) {
// Keep this deciles unchanged
} else {
// Aggregate both deciles
aggregateDeciles(this.deciles, this.numValues, this.getMaximum(),
other.deciles, other.numValues, other.getMaximum(),
this.deciles);
}
if (other.maximum > this.maximum) {
this.maximum = other.maximum;
}
if (other.minimum < this.minimum) {
this.minimum = other.minimum;
}
this.numValues += other.numValues;
this.total += other.total;
}
#location 9
#vulnerability type NULL_DEREFERENCE | #fixed code
public void aggregate(DoublePopulationStatisticsAggregator other) {
if (other.maximum > this.maximum) {
this.maximum = other.maximum;
}
if (other.minimum < this.minimum) {
this.minimum = other.minimum;
}
this.numValues += other.numValues;
this.total += other.total;
this.reservoirSample.sample(other.reservoirSample, random);
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
public void getBulk(int domainId, List<ByteBuffer> keys, HostConnectionGetBulkCallback resultHandler) throws TException {
client.getBulk(domainId, keys, resultHandler);
}
#location 2
#vulnerability type THREAD_SAFETY_VIOLATION | #fixed code
public void getBulk(int domainId, List<ByteBuffer> keys, HostConnectionGetBulkCallback resultHandler) {
try {
client.getBulk(domainId, keys, resultHandler);
} catch (TException e) {
resultHandler.onError(e);
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
private boolean isBalanced(Ring ring, Domain domain) throws IOException {
HostDomain maxHostDomain = getMaxHostDomain(ring, domain);
HostDomain minHostDomain = getMinHostDomain(ring, domain);
int maxDistance = Math.abs(maxHostDomain.getPartitions().size()
- minHostDomain.getPartitions().size());
return maxDistance <= 1;
}
#location 4
#vulnerability type NULL_DEREFERENCE | #fixed code
private boolean isBalanced(Ring ring, Domain domain) throws IOException {
HostDomain maxHostDomain = getMaxHostDomain(ring, domain);
HostDomain minHostDomain = getMinHostDomain(ring, domain);
if (maxHostDomain == null || minHostDomain == null) {
// If either maxHostDomain or minHostDomain is null, the domain is not balanced
return false;
}
int maxDistance = Math.abs(maxHostDomain.getPartitions().size() - minHostDomain.getPartitions().size());
return maxDistance <= 1;
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
public void merge(final CueballFilePath base,
final List<CueballFilePath> deltas,
final String newBasePath,
final int keyHashSize,
final int valueSize,
ValueTransformer transformer,
int hashIndexBits,
CompressionCodec compressionCodec) throws IOException {
// Perform merging
StreamBuffer[] sbs = new StreamBuffer[deltas.size() + 1];
// open the current base
StreamBuffer baseBuffer = new StreamBuffer(base.getPath(), 0,
keyHashSize, valueSize, hashIndexBits, compressionCodec);
sbs[0] = baseBuffer;
// open all the deltas
int i = 1;
for (CueballFilePath delta : deltas) {
StreamBuffer db = new StreamBuffer(delta.getPath(), i,
keyHashSize, valueSize, hashIndexBits, compressionCodec);
sbs[i++] = db;
}
// output stream for the new base to be written. intentionally unbuffered -
// the writer below will do that on its own.
OutputStream newBaseStream = new FileOutputStream(newBasePath);
// note that we intentionally omit the hasher here, since it will *not* be
// used
CueballWriter writer = new CueballWriter(newBaseStream, keyHashSize, null, valueSize, compressionCodec, hashIndexBits);
while (true) {
StreamBuffer least = null;
for (i = 0; i < sbs.length; i++) {
boolean remaining = sbs[i].anyRemaining();
if (remaining) {
if (least == null) {
least = sbs[i];
} else {
int comparison = least.compareTo(sbs[i]);
if (comparison == 0) {
least.consume();
least = sbs[i];
} else if (comparison == 1) {
least = sbs[i];
}
}
}
}
if (least == null) {
break;
}
if (transformer != null) {
transformer.transform(least.getBuffer(), least.getCurrentOffset() + keyHashSize, least.getIndex());
}
final ByteBuffer keyHash = ByteBuffer.wrap(least.getBuffer(), least.getCurrentOffset(), keyHashSize);
final ByteBuffer valueBytes = ByteBuffer.wrap(least.getBuffer(), least.getCurrentOffset() + keyHashSize, valueSize);
writer.writeHash(keyHash, valueBytes);
least.consume();
}
for (StreamBuffer sb : sbs) {
sb.close();
}
writer.close();
}
#location 44
#vulnerability type RESOURCE_LEAK | #fixed code
public void merge(final CueballFilePath base,
final List<CueballFilePath> deltas,
final String newBasePath,
final int keyHashSize,
final int valueSize,
ValueTransformer transformer,
int hashIndexBits,
CompressionCodec compressionCodec) throws IOException {
// Perform merging
CueballStreamBuffer[] sbs = new CueballStreamBuffer[deltas.size() + 1];
// open the current base
CueballStreamBuffer baseBuffer = new CueballStreamBuffer(base.getPath(), 0,
keyHashSize, valueSize, hashIndexBits, compressionCodec);
sbs[0] = baseBuffer;
// open all the deltas
int i = 1;
for (CueballFilePath delta : deltas) {
CueballStreamBuffer db = new CueballStreamBuffer(delta.getPath(), i,
keyHashSize, valueSize, hashIndexBits, compressionCodec);
sbs[i++] = db;
}
// output stream for the new base to be written. intentionally unbuffered -
// the writer below will do that on its own.
OutputStream newBaseStream = new FileOutputStream(newBasePath);
// note that we intentionally omit the hasher here, since it will *not* be
// used
CueballWriter writer = new CueballWriter(newBaseStream, keyHashSize, null, valueSize, compressionCodec, hashIndexBits);
while (true) {
CueballStreamBuffer least = null;
for (i = 0; i < sbs.length; i++) {
boolean remaining = sbs[i].anyRemaining();
if (remaining) {
if (least == null) {
least = sbs[i];
} else {
int comparison = least.compareTo(sbs[i]);
if (comparison == 0) {
least.consume();
least = sbs[i];
} else if (comparison == 1) {
least = sbs[i];
}
}
}
}
if (least == null) {
break;
}
if (transformer != null) {
transformer.transform(least.getBuffer(), least.getCurrentOffset() + keyHashSize, least.getIndex());
}
final ByteBuffer keyHash = ByteBuffer.wrap(least.getBuffer(), least.getCurrentOffset(), keyHashSize);
final ByteBuffer valueBytes = ByteBuffer.wrap(least.getBuffer(), least.getCurrentOffset() + keyHashSize, valueSize);
writer.writeHash(keyHash, valueBytes);
least.consume();
}
for (CueballStreamBuffer sb : sbs) {
sb.close();
}
writer.close();
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
private void sendEmails(Set<String> emailTargets, String body) throws IOException, InterruptedException {
for (String emailTarget : emailTargets) {
String[] command = {"/bin/mail", "-s", "Hank: " + name, emailTarget};
Process process = Runtime.getRuntime().exec(command);
OutputStreamWriter writer = new OutputStreamWriter(process.getOutputStream());
writer.write(body);
writer.close();
process.getOutputStream().close();
process.waitFor();
}
}
#location 9
#vulnerability type RESOURCE_LEAK | #fixed code
private void sendEmails(Set<String> emailTargets, String body) throws IOException, InterruptedException {
Session session = Session.getDefaultInstance(emailSessionProperties);
Message message = new MimeMessage(session);
try {
message.setSubject("Hank: " + name);
for (String emailTarget : emailTargets) {
message.addRecipient(Message.RecipientType.TO, new InternetAddress(emailTarget));
}
message.setText(body);
Transport.send(message);
} catch (MessagingException e) {
throw new RuntimeException("Failed to send notification email.", e);
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
public static void main(String[] args) throws Exception {
String configPath = args[0];
String log4jprops = args[1];
// PartDaemonConfigurator configurator = new YamlConfigurator(configPath);
PropertyConfigurator.configure(log4jprops);
new Daemon(null).run();
}
#location 7
#vulnerability type NULL_DEREFERENCE | #fixed code
public static void main(String[] args) throws Exception {
String configPath = args[0];
String log4jprops = args[1];
DataDeployerConfigurator configurator = new YamlDataDeployerConfigurator(configPath);
PropertyConfigurator.configure(log4jprops);
new Daemon(configurator).run();
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
public void merge(final CueballFilePath base,
final List<CueballFilePath> deltas,
final String newBasePath,
final int keyHashSize,
final int valueSize,
ValueTransformer transformer,
int hashIndexBits,
CompressionCodec compressionCodec) throws IOException {
// Array of stream buffers for the base and all deltas in order
CueballStreamBuffer[] cueballStreamBuffers = new CueballStreamBuffer[deltas.size() + 1];
// Open the current base
CueballStreamBuffer cueballBaseStreamBuffer = new CueballStreamBuffer(base.getPath(), 0,
keyHashSize, valueSize, hashIndexBits, compressionCodec);
cueballStreamBuffers[0] = cueballBaseStreamBuffer;
// Open all the deltas
int i = 1;
for (CueballFilePath delta : deltas) {
CueballStreamBuffer cueballStreamBuffer =
new CueballStreamBuffer(delta.getPath(), i, keyHashSize, valueSize, hashIndexBits, compressionCodec);
cueballStreamBuffers[i++] = cueballStreamBuffer;
}
// Output stream for the new base to be written. intentionally unbuffered, the writer below will do that on its own.
OutputStream newCueballBaseOutputStream = new FileOutputStream(newBasePath);
// Note that we intentionally omit the hasher here, since it will *not* be used
CueballWriter newCueballBaseWriter =
new CueballWriter(newCueballBaseOutputStream, keyHashSize, null, valueSize, compressionCodec, hashIndexBits);
while (true) {
// Find the stream buffer with the next smallest key hash
CueballStreamBuffer cueballStreamBufferToUse = null;
for (i = 0; i < cueballStreamBuffers.length; i++) {
if (cueballStreamBuffers[i].anyRemaining()) {
if (cueballStreamBufferToUse == null) {
cueballStreamBufferToUse = cueballStreamBuffers[i];
} else {
int comparison = cueballStreamBufferToUse.compareTo(cueballStreamBuffers[i]);
if (comparison == 0) {
// If two equal key hashes are found, use the most recent value (i.e. the one from the lastest delta)
// and skip (consume) the older ones
cueballStreamBufferToUse.consume();
cueballStreamBufferToUse = cueballStreamBuffers[i];
} else if (comparison == 1) {
// Found a stream buffer with a smaller key hash
cueballStreamBufferToUse = cueballStreamBuffers[i];
}
}
}
}
if (cueballStreamBufferToUse == null) {
// Nothing more to write
break;
}
// Transform if necessary
if (transformer != null) {
transformer.transform(cueballStreamBufferToUse.getBuffer(),
cueballStreamBufferToUse.getCurrentOffset() + keyHashSize,
cueballStreamBufferToUse.getIndex());
}
// Get next key hash and value
final ByteBuffer keyHash = ByteBuffer.wrap(cueballStreamBufferToUse.getBuffer(),
cueballStreamBufferToUse.getCurrentOffset(), keyHashSize);
final ByteBuffer valueBytes = ByteBuffer.wrap(cueballStreamBufferToUse.getBuffer(),
cueballStreamBufferToUse.getCurrentOffset() + keyHashSize, valueSize);
// Write next key hash and value
newCueballBaseWriter.writeHash(keyHash, valueBytes);
cueballStreamBufferToUse.consume();
}
// Close all buffers and the base writer
for (CueballStreamBuffer cueballStreamBuffer : cueballStreamBuffers) {
cueballStreamBuffer.close();
}
newCueballBaseWriter.close();
}
#location 44
#vulnerability type RESOURCE_LEAK | #fixed code
public void merge(final CueballFilePath base,
final List<CueballFilePath> deltas,
final String newBasePath,
final int keyHashSize,
final int valueSize,
ValueTransformer transformer,
int hashIndexBits,
CompressionCodec compressionCodec) throws IOException {
CueballStreamBufferMergeSort cueballStreamBufferMergeSort = new CueballStreamBufferMergeSort(base,
deltas,
keyHashSize,
hashIndexBits,
valueSize,
compressionCodec,
transformer);
// Output stream for the new base to be written. intentionally unbuffered, the writer below will do that on its own.
OutputStream newCueballBaseOutputStream = new FileOutputStream(newBasePath);
// Note that we intentionally omit the hasher here, since it will *not* be used
CueballWriter newCueballBaseWriter =
new CueballWriter(newCueballBaseOutputStream, keyHashSize, null, valueSize, compressionCodec, hashIndexBits);
while (true) {
CueballStreamBufferMergeSort.KeyHashValuePair keyValuePair = cueballStreamBufferMergeSort.nextKeyValuePair();
if (keyValuePair == null) {
break;
}
// Write next key hash and value
newCueballBaseWriter.writeHash(keyValuePair.keyHash, keyValuePair.value);
}
// Close all buffers and the base writer
cueballStreamBufferMergeSort.close();
newCueballBaseWriter.close();
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
public void addTask(GetTask task) {
synchronized (getTasks) {
task.startNanoTime = System.nanoTime();
getTasks.addLast(task);
}
dispatcherThread.interrupt();
}
#location 6
#vulnerability type THREAD_SAFETY_VIOLATION | #fixed code
public void addTask(GetTask task) {
synchronized (getTasks) {
task.startNanoTime = System.nanoTime();
getTasks.addLast(task);
}
//dispatcherThread.interrupt();
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
public static void main(String ... args) throws InterruptedException, ExecutionException, TimeoutException {
RpcServer server = createServer();
server.start();
RpcClient client = createClient();
Request request = Request.newBuilder()
.withContentType("text/plain")
.withBody("Johnny".getBytes(Charset.forName("UTF-8")))
.withCorrelationId(UUID.randomUUID().toString())
.build();
CompletableFuture<Response> future = client.call(request);
Response response = future.get(20, TimeUnit.SECONDS);
System.out.println("Responded -> " + new String(response.getBody()));
client.shutdown();
server.shutdown();
System.exit(0);
}
#location 22
#vulnerability type RESOURCE_LEAK | #fixed code
public static void main(String ... args) throws InterruptedException, ExecutionException, TimeoutException {
RequestHandler handler = request -> {
String reqStr = new String(request.getBody());
return Response.newBuilder()
.withBody(("Hello " + reqStr).getBytes())
.withContentType("text/plain")
.withLast(request.isSingleReplyExpected())
.withCorrelationId(request.getCorrelationId())
.buildSuccess();
};
RpcServer server = createServer(handler);
server.start();
RpcClient client = createClient();
Request request = Request.newBuilder()
.withContentType("text/plain")
.withBody("Johnny".getBytes(Charset.forName("UTF-8")))
.withCorrelationId(UUID.randomUUID().toString())
.build();
CompletableFuture<Response> future = new CompletableFuture<>();
client.call(request, future::complete);
Response response = future.get(20, TimeUnit.SECONDS);
System.out.println("Responded -> " + new String(response.getBody()));
client.shutdown();
server.shutdown();
System.exit(0);
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
public static void filterActions(AccessKeyAction allowedAction,
Set<AccessKeyPermission> permissions) {
Set<AccessKeyPermission> permissionsToRemove = new HashSet<>();
for (AccessKeyPermission currentPermission : permissions) {
boolean isCurrentPermissionAllowed = false;
Set<String> actions = currentPermission.getActionsAsSet();
if (currentPermission.getAccessKey() != null && currentPermission.getAccessKey().getUser().getRole() != UserRole.ADMIN) {
actions.removeAll(AvailableActions.getAdminActions());
}
if (actions != null) {
if (currentPermission.getAccessKey() != null && currentPermission.getAccessKey().getUser().getRole() != UserRole.ADMIN) {
actions.removeAll(AvailableActions.getAdminActions());
}
for (String accessKeyAction : actions) {
isCurrentPermissionAllowed = accessKeyAction.equalsIgnoreCase(allowedAction.getValue());
if (isCurrentPermissionAllowed) {
break;
}
}
if (!isCurrentPermissionAllowed) {
permissionsToRemove.add(currentPermission);
}
}
}
permissions.removeAll(permissionsToRemove);
}
#location 8
#vulnerability type NULL_DEREFERENCE | #fixed code
public static void filterActions(AccessKeyAction allowedAction,
Set<AccessKeyPermission> permissions) {
Set<AccessKeyPermission> permissionsToRemove = new HashSet<>();
for (AccessKeyPermission currentPermission : permissions) {
boolean isCurrentPermissionAllowed = false;
Set<String> actions = currentPermission.getActionsAsSet();
if (actions != null) {
if (currentPermission.getAccessKey() != null && currentPermission.getAccessKey().getUser().getRole() != UserRole.ADMIN) {
actions.removeAll(AvailableActions.getAdminActions());
}
for (String accessKeyAction : actions) {
isCurrentPermissionAllowed = accessKeyAction.equalsIgnoreCase(allowedAction.getValue());
if (isCurrentPermissionAllowed) {
break;
}
}
if (!isCurrentPermissionAllowed) {
permissionsToRemove.add(currentPermission);
}
}
}
permissions.removeAll(permissionsToRemove);
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@TransactionAttribute(TransactionAttributeType.NOT_SUPPORTED)
public Network getWithDevicesAndDeviceClasses(@NotNull Long networkId, @NotNull HivePrincipal principal) {
if (principal.getUser() != null) {
List<Network> found = networkDAO.getNetworkList(principal.getUser(), null, Arrays.asList(networkId));
if (found.isEmpty()) {
return null;
}
List<Device> devices = deviceService.getList(networkId, principal);
Network result = found.get(0);
result.setDevices(new HashSet<>(devices));
return result;
} else {
AccessKey key = principal.getKey();
User user = userService.findUserWithNetworks(key.getUser().getId());
List<Network> found = networkDAO.getNetworkList(user,
key.getPermissions(),
Arrays.asList(networkId));
Network result = found.isEmpty() ? null : found.get(0);
if (result == null) {
return result;
}
//to get proper devices 1) get access key with all permissions 2) get devices for required network
key = accessKeyService.find(key.getId(), principal.getKey().getUser().getId());
if (!CheckPermissionsHelper.checkAllPermissions(key, AllowedKeyAction.Action.GET_DEVICE)) {
result.setDevices(null);
return result;
}
Set<Device> devices =
new HashSet<>(deviceService.getList(result.getId(), principal));
result.setDevices(devices);
return result;
}
}
#location 24
#vulnerability type NULL_DEREFERENCE | #fixed code
@TransactionAttribute(TransactionAttributeType.NOT_SUPPORTED)
public Network getWithDevicesAndDeviceClasses(@NotNull Long networkId, @NotNull HivePrincipal principal) {
if (principal.getUser() != null) {
List<Network> found = networkDAO.getNetworkList(principal.getUser(), null, Arrays.asList(networkId));
if (found.isEmpty()) {
return null;
}
List<Device> devices = deviceService.getList(networkId, principal);
Network result = found.get(0);
result.setDevices(new HashSet<>(devices));
return result;
} else {
AccessKey key = principal.getKey();
User user = userService.findUserWithNetworks(key.getUser().getId());
List<Network> found = networkDAO.getNetworkList(user,
key.getPermissions(),
Arrays.asList(networkId));
Network result = found.isEmpty() ? null : found.get(0);
if (result == null) {
return result;
}
//to get proper devices 1) get access key with all permissions 2) get devices for required network
AccessKey currentKey = accessKeyDAO.getWithoutUser(user.getId(), key.getId());
Set<AccessKeyPermission> filtered = CheckPermissionsHelper.filterPermissions(key.getPermissions(), AllowedKeyAction.Action.GET_DEVICE, ThreadLocalVariablesKeeper.getClientIP(), ThreadLocalVariablesKeeper.getHostName());
if (filtered.isEmpty()) {
result.setDevices(null);
return result;
}
Set<Device> devices =
new HashSet<>(deviceService.getList(result.getId(), principal));
result.setDevices(devices);
return result;
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Action("notification/insert")
@RolesAllowed({HiveRoles.CLIENT, HiveRoles.ADMIN, HiveRoles.DEVICE, HiveRoles.KEY})
@AllowedKeyAction(action = CREATE_DEVICE_NOTIFICATION)
public WebSocketResponse processNotificationInsert(@WsParam(DEVICE_GUID) String deviceGuid,
@WsParam(NOTIFICATION)
@JsonPolicyApply(NOTIFICATION_FROM_DEVICE)
DeviceNotification notification,
Session session) {
logger.debug("notification/insert requested. Session {}. Guid {}", session, deviceGuid);
HivePrincipal principal = hiveSecurityContext.getHivePrincipal();
if (notification == null || notification.getNotification() == null) {
logger.debug(
"notification/insert proceed with error. Bad notification: notification is required.");
throw new HiveException(Messages.NOTIFICATION_REQUIRED, SC_BAD_REQUEST);
}
Device device;
if (deviceGuid == null) {
device = principal.getDevice();
} else {
device = deviceService.findByGuidWithPermissionsCheck(deviceGuid, principal);
}
if (device.getNetwork() == null) {
logger.debug(
"notification/insert. No network specified for device with guid = {}", deviceGuid);
throw new HiveException(Messages.DEVICE_IS_NOT_CONNECTED_TO_NETWORK, SC_FORBIDDEN);
}
deviceNotificationService.submitDeviceNotification(notification, device);
logger.debug("notification/insert proceed successfully. Session {}. Guid {}", session, deviceGuid);
WebSocketResponse response = new WebSocketResponse();
response.addValue(NOTIFICATION, notification, NOTIFICATION_TO_DEVICE);
return response;
}
#location 22
#vulnerability type NULL_DEREFERENCE | #fixed code
@Action("notification/insert")
@RolesAllowed({HiveRoles.CLIENT, HiveRoles.ADMIN, HiveRoles.DEVICE, HiveRoles.KEY})
@AllowedKeyAction(action = CREATE_DEVICE_NOTIFICATION)
public WebSocketResponse processNotificationInsert(@WsParam(DEVICE_GUID) String deviceGuid,
@WsParam(NOTIFICATION)
@JsonPolicyApply(NOTIFICATION_FROM_DEVICE)
DeviceNotification notification,
Session session) {
logger.debug("notification/insert requested. Session {}. Guid {}", session, deviceGuid);
HivePrincipal principal = hiveSecurityContext.getHivePrincipal();
if (notification == null || notification.getNotification() == null) {
logger.debug(
"notification/insert proceed with error. Bad notification: notification is required.");
throw new HiveException(Messages.NOTIFICATION_REQUIRED, SC_BAD_REQUEST);
}
Device device;
if (deviceGuid == null) {
device = principal.getDevice();
} else {
device = deviceService.findByGuidWithPermissionsCheck(deviceGuid, principal);
}
if (device == null){
logger.debug("notification/insert canceled for session: {}. Guid is not provided", session);
throw new HiveException(Messages.DEVICE_GUID_REQUIRED, SC_FORBIDDEN);
}
if (device.getNetwork() == null) {
logger.debug(
"notification/insert. No network specified for device with guid = {}", deviceGuid);
throw new HiveException(Messages.DEVICE_IS_NOT_CONNECTED_TO_NETWORK, SC_FORBIDDEN);
}
deviceNotificationService.submitDeviceNotification(notification, device);
logger.debug("notification/insert proceed successfully. Session {}. Guid {}", session, deviceGuid);
WebSocketResponse response = new WebSocketResponse();
response.addValue(NOTIFICATION, notification, NOTIFICATION_TO_DEVICE);
return response;
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Action(value = "notification/unsubscribe")
public JsonObject processNotificationUnsubscribe(JsonObject message, Session session) {
logger.debug("notification/unsubscribe action. Session " + session.getId());
Gson gson = GsonFactory.createGson();
List<UUID> list = gson.fromJson(message.get(JsonMessageBuilder.DEVICE_GUIDS), new TypeToken<List<UUID>>() {
}.getType());
try {
WebsocketSession.getNotificationSubscriptionsLock(session).lock();
List<Device> devices = null;
if (list != null && !list.isEmpty()) {
devices = deviceDAO.findByUUID(list);
}
logger.debug("notification/unsubscribe. found " + devices.size() +
" devices. " + "Session " + session.getId());
logger.debug("notification/unsubscribe. performing unsubscribing action");
localMessageBus.unsubscribeFromNotifications(session.getId(), devices);
} finally {
WebsocketSession.getNotificationSubscriptionsLock(session).unlock();
}
JsonObject jsonObject = JsonMessageBuilder.createSuccessResponseBuilder().build();
logger.debug("notification/unsubscribe completed for session " + session.getId());
return jsonObject;
}
#location 14
#vulnerability type NULL_DEREFERENCE | #fixed code
@Action(value = "notification/unsubscribe")
public JsonObject processNotificationUnsubscribe(JsonObject message, Session session) {
logger.debug("notification/unsubscribe action. Session " + session.getId());
Gson gson = GsonFactory.createGson();
List<UUID> list = gson.fromJson(message.get(JsonMessageBuilder.DEVICE_GUIDS), new TypeToken<List<UUID>>() {
}.getType());
try {
WebsocketSession.getNotificationSubscriptionsLock(session).lock();
List<Device> devices = null;
if (list != null && !list.isEmpty()) {
devices = deviceDAO.findByUUID(list);
logger.debug("notification/unsubscribe. found " + devices.size() +
" devices. " + "Session " + session.getId());
}
logger.debug("notification/unsubscribe. performing unsubscribing action");
localMessageBus.unsubscribeFromNotifications(session.getId(), devices);
} finally {
WebsocketSession.getNotificationSubscriptionsLock(session).unlock();
}
JsonObject jsonObject = JsonMessageBuilder.createSuccessResponseBuilder().build();
logger.debug("notification/unsubscribe completed for session " + session.getId());
return jsonObject;
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
public static void filterActions(AccessKeyAction allowedAction,
Set<AccessKeyPermission> permissions) {
Set<AccessKeyPermission> permissionsToRemove = new HashSet<>();
for (AccessKeyPermission currentPermission : permissions) {
boolean isCurrentPermissionAllowed = false;
Set<String> actions = currentPermission.getActionsAsSet();
if (currentPermission.getAccessKey() != null && currentPermission.getAccessKey().getUser().getRole() != UserRole.ADMIN) {
actions.removeAll(AvailableActions.getAdminActions());
}
if (actions != null) {
if (currentPermission.getAccessKey() != null && currentPermission.getAccessKey().getUser().getRole() != UserRole.ADMIN) {
actions.removeAll(AvailableActions.getAdminActions());
}
for (String accessKeyAction : actions) {
isCurrentPermissionAllowed = accessKeyAction.equalsIgnoreCase(allowedAction.getValue());
if (isCurrentPermissionAllowed) {
break;
}
}
if (!isCurrentPermissionAllowed) {
permissionsToRemove.add(currentPermission);
}
}
}
permissions.removeAll(permissionsToRemove);
}
#location 8
#vulnerability type NULL_DEREFERENCE | #fixed code
public static void filterActions(AccessKeyAction allowedAction,
Set<AccessKeyPermission> permissions) {
Set<AccessKeyPermission> permissionsToRemove = new HashSet<>();
for (AccessKeyPermission currentPermission : permissions) {
boolean isCurrentPermissionAllowed = false;
Set<String> actions = currentPermission.getActionsAsSet();
if (actions != null) {
if (currentPermission.getAccessKey() != null && currentPermission.getAccessKey().getUser().getRole() != UserRole.ADMIN) {
actions.removeAll(AvailableActions.getAdminActions());
}
for (String accessKeyAction : actions) {
isCurrentPermissionAllowed = accessKeyAction.equalsIgnoreCase(allowedAction.getValue());
if (isCurrentPermissionAllowed) {
break;
}
}
if (!isCurrentPermissionAllowed) {
permissionsToRemove.add(currentPermission);
}
}
}
permissions.removeAll(permissionsToRemove);
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Override
public void filter(ContainerRequestContext requestContext) throws IOException {
BeanManager beanManager = CDI.current().getBeanManager();
Context requestScope = beanManager.getContext(RequestScoped.class);
HiveSecurityContext hiveSecurityContext = null;
for (Bean<?> bean : beanManager.getBeans(HiveSecurityContext.class)) {
if (requestScope.get(bean) != null) {
hiveSecurityContext = (HiveSecurityContext) requestScope.get(bean);
}
}
for (String role : allowedRoles) {
if (hiveSecurityContext.isUserInRole(role)) {
return;
}
}
HivePrincipal hivePrincipal = hiveSecurityContext.getHivePrincipal();
if (hivePrincipal != null && hivePrincipal.getKey() != null) {
requestContext.abortWith(Response
.status(Response.Status.UNAUTHORIZED)
.header(HttpHeaders.AUTHORIZATION, Messages.OAUTH_REALM)
.entity(Messages.NOT_AUTHORIZED)
.build());
} else {
requestContext.abortWith(Response
.status(Response.Status.UNAUTHORIZED)
.header(HttpHeaders.AUTHORIZATION, Messages.BASIC_REALM)
.entity(Messages.NOT_AUTHORIZED)
.build());
}
}
#location 16
#vulnerability type NULL_DEREFERENCE | #fixed code
@Override
public void filter(ContainerRequestContext requestContext) throws IOException {
for (String role : allowedRoles) {
if (requestContext.getSecurityContext().isUserInRole(role)) {
return;
}
}
boolean isOauth = Constants.OAUTH_AUTH_SCEME.equals(requestContext.getSecurityContext().getAuthenticationScheme());
requestContext.abortWith(Response
.status(Response.Status.UNAUTHORIZED)
.header(HttpHeaders.WWW_AUTHENTICATE, isOauth ? Messages.OAUTH_REALM : Messages.BASIC_REALM)
.entity(Messages.NOT_AUTHORIZED)
.build());
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
public DeviceNotification deviceSave(DeviceUpdate deviceUpdate,
Set<Equipment> equipmentSet) {
Network network = networkService.createOrVeriryNetwork(deviceUpdate.getNetwork());
DeviceClass deviceClass = deviceClassService
.createOrUpdateDeviceClass(deviceUpdate.getDeviceClass(), equipmentSet);
Device existingDevice = deviceDAO.findByUUIDWithNetworkAndDeviceClass(deviceUpdate.getGuid().getValue());
if (existingDevice == null) {
Device device = deviceUpdate.convertTo();
if (deviceClass != null) {
device.setDeviceClass(deviceClass);
}
if (network != null) {
device.setNetwork(network);
}
existingDevice = deviceDAO.createDevice(device);
final DeviceNotification addDeviceNotification = ServerResponsesFactory.createNotificationForDevice
(existingDevice,
SpecialNotifications.DEVICE_ADD);
deviceNotificationService.submitDeviceNotification(addDeviceNotification, existingDevice.getGuid());
return addDeviceNotification;
} else {
if (deviceUpdate.getKey() == null || !existingDevice.getKey().equals(deviceUpdate.getKey().getValue())) {
LOGGER.error("Device update key {} doesn't equal to the authenticated device key {}",
deviceUpdate.getKey().getValue(), existingDevice.getKey());
throw new HiveException(Messages.INCORRECT_CREDENTIALS, UNAUTHORIZED.getStatusCode());
}
if (deviceUpdate.getDeviceClass() != null) {
existingDevice.setDeviceClass(deviceClass);
}
if (deviceUpdate.getStatus() != null) {
existingDevice.setStatus(deviceUpdate.getStatus().getValue());
}
if (deviceUpdate.getData() != null) {
existingDevice.setData(deviceUpdate.getData().getValue());
}
if (deviceUpdate.getNetwork() != null) {
existingDevice.setNetwork(network);
}
final DeviceNotification addDeviceNotification = ServerResponsesFactory.createNotificationForDevice
(existingDevice,
SpecialNotifications.DEVICE_UPDATE);
deviceNotificationService.submitDeviceNotification(addDeviceNotification, existingDevice.getGuid());
return addDeviceNotification;
}
}
#location 25
#vulnerability type NULL_DEREFERENCE | #fixed code
public DeviceNotification deviceSave(DeviceUpdate deviceUpdate,
Set<Equipment> equipmentSet) {
Network network = networkService.createOrVeriryNetwork(deviceUpdate.getNetwork());
DeviceClass deviceClass = deviceClassService
.createOrUpdateDeviceClass(deviceUpdate.getDeviceClass(), equipmentSet);
Device existingDevice = deviceDAO.findByUUIDWithNetworkAndDeviceClass(deviceUpdate.getGuid().getValue());
if (existingDevice == null) {
Device device = deviceUpdate.convertTo();
if (deviceClass != null) {
device.setDeviceClass(deviceClass);
}
if (network != null) {
device.setNetwork(network);
}
existingDevice = deviceDAO.createDevice(device);
final DeviceNotification addDeviceNotification = ServerResponsesFactory.createNotificationForDevice
(existingDevice,
SpecialNotifications.DEVICE_ADD);
deviceNotificationService.submitDeviceNotification(addDeviceNotification, existingDevice.getGuid());
return addDeviceNotification;
} else {
if (deviceUpdate.getKey() == null || !existingDevice.getKey().equals(deviceUpdate.getKey().getValue())) {
LOGGER.error("Device update key is null or doesn't equal to the authenticated device key {}", existingDevice.getKey());
throw new HiveException(Messages.INCORRECT_CREDENTIALS, UNAUTHORIZED.getStatusCode());
}
if (deviceUpdate.getDeviceClass() != null) {
existingDevice.setDeviceClass(deviceClass);
}
if (deviceUpdate.getStatus() != null) {
existingDevice.setStatus(deviceUpdate.getStatus().getValue());
}
if (deviceUpdate.getData() != null) {
existingDevice.setData(deviceUpdate.getData().getValue());
}
if (deviceUpdate.getNetwork() != null) {
existingDevice.setNetwork(network);
}
final DeviceNotification addDeviceNotification = ServerResponsesFactory.createNotificationForDevice
(existingDevice,
SpecialNotifications.DEVICE_UPDATE);
deviceNotificationService.submitDeviceNotification(addDeviceNotification, existingDevice.getGuid());
return addDeviceNotification;
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Override
public OAuthGrant getById(Long grantId) {
OAuthGrant grant = find(grantId);
grant = restoreRefs(grant, null, null);
return grant;
}
#location 4
#vulnerability type NULL_DEREFERENCE | #fixed code
@Override
public OAuthGrant getById(Long grantId) {
OAuthGrant grant = find(grantId);
if( grant != null) {
grant = restoreRefs(grant, null, null);
}
return grant;
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Override
public Response get(String guid) {
logger.debug("Device get requested. Guid {}", guid);
HivePrincipal principal = (HivePrincipal) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
Device device = deviceService.getDeviceWithNetworkAndDeviceClass(guid, principal);
if (principal.getRole().equals(HiveRoles.DEVICE)) {
logger.debug("Device get proceed successfully. Guid {}", guid);
return ResponseFactory.response(Response.Status.OK, device, DEVICE_PUBLISHED_DEVICE_AUTH);
}
logger.debug("Device get proceed successfully. Guid {}", guid);
return ResponseFactory.response(Response.Status.OK, device, DEVICE_PUBLISHED);
}
#location 9
#vulnerability type NULL_DEREFERENCE | #fixed code
@Override
public Response get(String guid) {
logger.debug("Device get requested. Guid {}", guid);
HivePrincipal principal = (HivePrincipal) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
Device device = deviceService.getDeviceWithNetworkAndDeviceClass(guid, principal);
logger.debug("Device get proceed successfully. Guid {}", guid);
return ResponseFactory.response(Response.Status.OK, device, DEVICE_PUBLISHED);
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Override
public void start() {
consumerWorkers = new ArrayList<>(consumerThreads);
CountDownLatch startupLatch = new CountDownLatch(consumerThreads);
for (int i = 0; i < consumerThreads; i++) {
KafkaConsumer<String, Request> consumer = new KafkaConsumer<>(consumerProps);
RequestConsumerWorker worker = new RequestConsumerWorker(topic, consumer, messageDispatcher, startupLatch);
consumerExecutor.submit(worker);
}
try {
startupLatch.await(5000, TimeUnit.MILLISECONDS);
} catch (InterruptedException e) {
logger.error("Error while waiting for server consumers to subscribe", e);
}
}
#location 8
#vulnerability type RESOURCE_LEAK | #fixed code
@Override
public void start() {
disruptor.handleEventsWith(eventHandler);
disruptor.start();
RingBuffer<ServerEvent> ringBuffer = disruptor.getRingBuffer();
requestConsumer.startConsumers(ringBuffer);
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Test
public void shouldSendRequestToServer() throws Exception {
CompletableFuture<Request> future = new CompletableFuture<>();
RequestHandler mockedHandler = request -> {
future.complete(request);
return Response.newBuilder()
.withCorrelationId(request.getCorrelationId())
.withBody("Response".getBytes())
.withLast(true)
.buildSuccess();
};
RpcServer server = buildServer(mockedHandler);
server.start();
RpcClient client = buildClient();
client.start();
Request request = Request.newBuilder()
.withCorrelationId(UUID.randomUUID().toString())
.withSingleReply(true)
.withBody("RequestResponseTest".getBytes())
.build();
TimeUnit.SECONDS.sleep(10);
client.push(request);
Request receivedRequest = future.get(20, TimeUnit.SECONDS);
assertEquals(request, receivedRequest);
}
#location 14
#vulnerability type RESOURCE_LEAK | #fixed code
@Test
public void shouldSendRequestToServer() throws Exception {
CompletableFuture<Request> future = new CompletableFuture<>();
RequestHandler handler = request -> {
future.complete(request);
return Response.newBuilder()
.withCorrelationId(request.getCorrelationId())
.withBody("Response".getBytes())
.withLast(true)
.buildSuccess();
};
handlerWrapper.setDelegate(handler);
Request request = Request.newBuilder()
.withCorrelationId(UUID.randomUUID().toString())
.withSingleReply(true)
.withBody("RequestResponseTest".getBytes())
.build();
client.push(request);
Request receivedRequest = future.get(10, TimeUnit.SECONDS);
assertEquals(request, receivedRequest);
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Override
public OAuthGrant getByIdAndUser(User user, Long grantId) {
OAuthGrant grant = getById(grantId);
if (grant.getUser().equals(user)) {
return grant;
} else {
return null;
}
}
#location 4
#vulnerability type NULL_DEREFERENCE | #fixed code
@Override
public OAuthGrant getByIdAndUser(User user, Long grantId) {
OAuthGrant grant = getById(grantId);
if (grant != null && user != null && grant.getUserId() == user.getId()) {
return restoreRefs(grant, user, null);
} else {
return null;
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Test
public void expirationDateTest() {
AccessKey key = new AccessKey();
CLIENT.setStatus(UserStatus.ACTIVE);
key.setUser(CLIENT);
Timestamp inPast = new Timestamp(0);
key.setExpirationDate(inPast);
HiveSecurityContext hiveSecurityContext = new HiveSecurityContext();
hiveSecurityContext.setHivePrincipal(new HivePrincipal(null, null, key));
AccessKeyInterceptor interceptor = new AccessKeyInterceptor();
interceptor.setHiveSecurityContext(hiveSecurityContext);
try {
interceptor.checkPermissions(null);
} catch (Exception e) {
if (e instanceof HiveException) {
HiveException hiveException = (HiveException) e;
assertEquals(401, hiveException.getCode().intValue());
} else {
fail("Hive exception expected");
}
}
}
#location 13
#vulnerability type NULL_DEREFERENCE | #fixed code
@Test
public void expirationDateTest() {
AccessKey key = new AccessKey();
CLIENT.setStatus(UserStatus.ACTIVE);
key.setUser(CLIENT);
Timestamp inPast = new Timestamp(0);
key.setExpirationDate(inPast);
HiveSecurityContext hiveSecurityContext = new HiveSecurityContext();
hiveSecurityContext.setHivePrincipal(new HivePrincipal(null, null, key));
RequestInterceptor interceptor = new RequestInterceptor();
interceptor.setHiveSecurityContext(hiveSecurityContext);
try {
interceptor.checkPermissions(null);
} catch (Exception e) {
if (e instanceof HiveException) {
HiveException hiveException = (HiveException) e;
assertEquals(401, hiveException.getCode().intValue());
} else {
fail("Hive exception expected");
}
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Override
public Response update(NetworkUpdate networkToUpdate, long id) {
logger.debug("Network update requested. Id : {}", id);
networkService.update(id, NetworkUpdate.convert(networkToUpdate));
logger.debug("Network has been updated successfully. Id : {}", id);
return ResponseFactory.response(NO_CONTENT);
}
#location 4
#vulnerability type NULL_DEREFERENCE | #fixed code
@Override
public Response update(NetworkUpdate networkToUpdate, long id) {
logger.debug("Network update requested. Id : {}", id);
networkService.update(id, networkToUpdate);
logger.debug("Network has been updated successfully. Id : {}", id);
return ResponseFactory.response(NO_CONTENT);
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Override
public User getWithNetworksById(long id) {
User user = find(id);
Set<Long> networkIds = userNetworkDao.findNetworksForUser(id);
Set<Network> networks = new HashSet<>();
for (Long networkId : networkIds) {
Network network = networkDao.find(networkId);
networks.add(network);
}
user.setNetworks(networks);
return user;
}
#location 7
#vulnerability type NULL_DEREFERENCE | #fixed code
@Override
public User getWithNetworksById(long id) {
User user = find(id);
Set<Long> networkIds = userNetworkDao.findNetworksForUser(id);
if (networkIds == null) {
return user;
}
Set<Network> networks = new HashSet<>();
for (Long networkId : networkIds) {
Network network = networkDao.find(networkId);
networks.add(network);
}
user.setNetworks(networks);
return user;
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Override
public List<Device> getDeviceList(List<String> guids, HivePrincipal principal) {
List<Device> deviceList = new ArrayList<>();
if (principal == null || principal.getRole().equals(HiveRoles.ADMIN)) {
for (String guid : guids) {
Device device = findByUUID(guid);
if (device != null) {
deviceList.add(device);
}
}
} else {
try {
BucketMapReduce.Builder builder = new BucketMapReduce.Builder()
.withNamespace(DEVICE_NS)
.withMapPhase(Function.newNamedJsFunction("Riak.mapValuesJson"));
String functionString =
"function(values, arg) {" +
"return values.filter(function(v) {" +
"var guid = v.guid;" +
"return arg.indexOf(guid) > -1;" +
"})" +
"}";
Function reduceFunction = Function.newAnonymousJsFunction(functionString);
builder.withReducePhase(reduceFunction, guids.toArray());
BucketMapReduce bmr = builder.build();
RiakFuture<MapReduce.Response, BinaryValue> future = client.executeAsync(bmr);
future.await();
MapReduce.Response response = future.get();
deviceList.addAll(response.getResultsFromAllPhases(Device.class));
if (principal.getUser() != null) {
Set<Long> networks = userNetworkDao.findNetworksForUser(principal.getUser().getId());
deviceList = deviceList
.stream()
.filter(d -> networks.contains(d.getNetwork().getId()))
.collect(Collectors.toList());
}
} catch (InterruptedException | ExecutionException e) {
logger.error("Exception accessing Riak Storage.", e);
throw new HivePersistenceLayerException("Cannot get list of devices for list of UUIDs and principal.", e);
}
}
return deviceList;
}
#location 5
#vulnerability type NULL_DEREFERENCE | #fixed code
@Override
public List<Device> getDeviceList(List<String> guids, HivePrincipal principal) {
List<Device> deviceList = new ArrayList<>();
for (String guid : guids) {
Device device = findByUUID(guid);
if (device != null) {
deviceList.add(device);
}
}
if (principal != null && principal.getUser() != null && !principal.getRole().equals(HiveRoles.ADMIN)) {
Set<Long> networks = userNetworkDao.findNetworksForUser(principal.getUser().getId());
deviceList = deviceList
.stream()
.filter(d -> networks.contains(d.getNetwork().getId()))
.collect(Collectors.toList());
} else if (principal != null && principal.getKey() != null && principal.getKey().getUser() != null) {
Set<Long> networks = userNetworkDao.findNetworksForUser(principal.getKey().getUser().getId());
deviceList = deviceList
.stream()
.filter(d -> networks.contains(d.getNetwork().getId()))
.collect(Collectors.toList());
}
return deviceList;
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
public static void filterActions(AllowedKeyAction.Action allowedAction,
Set<AccessKeyPermission> permissions) {
Set<AccessKeyPermission> permissionsToRemove = new HashSet<>();
for (AccessKeyPermission currentPermission : permissions) {
boolean isCurrentPermissionAllowed = false;
Set<String> actions = currentPermission.getActionsAsSet();
if (currentPermission.getAccessKey() != null && currentPermission.getAccessKey().getUser().getRole() != UserRole.ADMIN) {
actions.removeAll(AvailableActions.getAdminActions());
}
if (actions != null) {
for (String accessKeyAction : actions) {
isCurrentPermissionAllowed = accessKeyAction.equalsIgnoreCase(allowedAction.getValue());
if (isCurrentPermissionAllowed) {
break;
}
}
if (!isCurrentPermissionAllowed) {
permissionsToRemove.add(currentPermission);
}
}
}
permissions.removeAll(permissionsToRemove);
}
#location 8
#vulnerability type NULL_DEREFERENCE | #fixed code
public static void filterActions(AllowedKeyAction.Action allowedAction,
Set<AccessKeyPermission> permissions) {
Set<AccessKeyPermission> permissionsToRemove = new HashSet<>();
for (AccessKeyPermission currentPermission : permissions) {
boolean isCurrentPermissionAllowed = false;
Set<String> actions = currentPermission.getActionsAsSet();
if (actions != null) {
if (currentPermission.getAccessKey() != null && currentPermission.getAccessKey().getUser().getRole() != UserRole.ADMIN) {
actions.removeAll(AvailableActions.getAdminActions());
}
for (String accessKeyAction : actions) {
isCurrentPermissionAllowed = accessKeyAction.equalsIgnoreCase(allowedAction.getValue());
if (isCurrentPermissionAllowed) {
break;
}
}
if (!isCurrentPermissionAllowed) {
permissionsToRemove.add(currentPermission);
}
}
}
permissions.removeAll(permissionsToRemove);
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Test
public void userStatusTest() throws Exception {
AccessKey key = new AccessKey();
ADMIN.setStatus(UserStatus.DISABLED);
key.setUser(ADMIN);
HiveSecurityContext hiveSecurityContext = new HiveSecurityContext();
hiveSecurityContext.setHivePrincipal(new HivePrincipal(null, null, key));
AccessKeyInterceptor interceptor = new AccessKeyInterceptor();
interceptor.setHiveSecurityContext(hiveSecurityContext);
Exception thrown = null;
try {
interceptor.checkPermissions(null);
} catch (Exception e) {
thrown = e;
if (e instanceof HiveException) {
HiveException hiveException = (HiveException) e;
assertEquals(401, hiveException.getCode().intValue());
} else {
fail("Hive exception expected");
}
}
if (thrown == null) {
fail("Hive exception expected");
}
key = new AccessKey();
ADMIN.setStatus(UserStatus.LOCKED_OUT);
key.setUser(ADMIN);
hiveSecurityContext = new HiveSecurityContext();
hiveSecurityContext.setHivePrincipal(new HivePrincipal(null, null, key));
interceptor = new AccessKeyInterceptor();
interceptor.setHiveSecurityContext(hiveSecurityContext);
thrown = null;
try {
interceptor.checkPermissions(null);
} catch (Exception e) {
thrown = e;
if (e instanceof HiveException) {
HiveException hiveException = (HiveException) e;
assertEquals(401, hiveException.getCode().intValue());
} else {
fail("Hive exception expected");
}
}
if (thrown == null) {
fail("Hive exception expected");
}
key = new AccessKey();
ADMIN.setStatus(UserStatus.DELETED);
key.setUser(ADMIN);
hiveSecurityContext = new HiveSecurityContext();
hiveSecurityContext.setHivePrincipal(new HivePrincipal(null, null, key));
interceptor = new AccessKeyInterceptor();
interceptor.setHiveSecurityContext(hiveSecurityContext);
thrown = null;
try {
interceptor.checkPermissions(null);
} catch (Exception e) {
thrown = e;
if (e instanceof HiveException) {
HiveException hiveException = (HiveException) e;
assertEquals(401, hiveException.getCode().intValue());
} else {
fail("Hive exception expected");
}
}
if (thrown == null) {
fail("Hive exception expected");
}
}
#location 12
#vulnerability type NULL_DEREFERENCE | #fixed code
@Test
public void userStatusTest() throws Exception {
AccessKey key = new AccessKey();
ADMIN.setStatus(UserStatus.DISABLED);
key.setUser(ADMIN);
HiveSecurityContext hiveSecurityContext = new HiveSecurityContext();
hiveSecurityContext.setHivePrincipal(new HivePrincipal(null, null, key));
RequestInterceptor interceptor = new RequestInterceptor();
interceptor.setHiveSecurityContext(hiveSecurityContext);
Exception thrown = null;
try {
interceptor.checkPermissions(null);
} catch (Exception e) {
thrown = e;
if (e instanceof HiveException) {
HiveException hiveException = (HiveException) e;
assertEquals(401, hiveException.getCode().intValue());
} else {
fail("Hive exception expected");
}
}
if (thrown == null) {
fail("Hive exception expected");
}
key = new AccessKey();
ADMIN.setStatus(UserStatus.LOCKED_OUT);
key.setUser(ADMIN);
hiveSecurityContext = new HiveSecurityContext();
hiveSecurityContext.setHivePrincipal(new HivePrincipal(null, null, key));
interceptor = new RequestInterceptor();
interceptor.setHiveSecurityContext(hiveSecurityContext);
thrown = null;
try {
interceptor.checkPermissions(null);
} catch (Exception e) {
thrown = e;
if (e instanceof HiveException) {
HiveException hiveException = (HiveException) e;
assertEquals(401, hiveException.getCode().intValue());
} else {
fail("Hive exception expected");
}
}
if (thrown == null) {
fail("Hive exception expected");
}
key = new AccessKey();
ADMIN.setStatus(UserStatus.DELETED);
key.setUser(ADMIN);
hiveSecurityContext = new HiveSecurityContext();
hiveSecurityContext.setHivePrincipal(new HivePrincipal(null, null, key));
interceptor = new RequestInterceptor();
interceptor.setHiveSecurityContext(hiveSecurityContext);
thrown = null;
try {
interceptor.checkPermissions(null);
} catch (Exception e) {
thrown = e;
if (e instanceof HiveException) {
HiveException hiveException = (HiveException) e;
assertEquals(401, hiveException.getCode().intValue());
} else {
fail("Hive exception expected");
}
}
if (thrown == null) {
fail("Hive exception expected");
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Override
public List<NetworkVO> list(String name, String namePattern, String sortField, boolean sortOrderAsc, Integer take,
Integer skip, Optional<HivePrincipal> principalOptional) {
String sortFunc = sortMap.get(sortField);
if (sortFunc == null) {
sortFunc = sortMap.get("name");
}
BucketMapReduce.Builder builder = new BucketMapReduce.Builder()
.withNamespace(NETWORK_NS)
.withMapPhase(Function.newAnonymousJsFunction("function(riakObject, keyData, arg) { " +
" if(riakObject.values[0].metadata['X-Riak-Deleted']){ return []; } " +
" else { return Riak.mapValuesJson(riakObject, keyData, arg); }}"))
.withReducePhase(Function.newAnonymousJsFunction("function(values, arg) {" +
"return values.filter(function(v) {" +
"if (v === [] || v.name === null) { return false; }" +
"return true;" +
"})" +
"}"));
if (name != null) {
String func = String.format(
"function(values, arg) {" +
"return values.filter(function(v) {" +
"var name = v.name;" +
"return name == '%s';" +
"})" +
"}", name);
Function function = Function.newAnonymousJsFunction(func);
builder.withReducePhase(function);
} else if (namePattern != null) {
namePattern = namePattern.replace("%", "");
String func = String.format(
"function(values, arg) {" +
"return values.filter(function(v) {" +
"var name = v.name;" +
"if (name === null) { return false; }" +
"return name.indexOf('%s') > -1;" +
"})" +
"}", namePattern);
Function function = Function.newAnonymousJsFunction(func);
builder.withReducePhase(function);
}
if (principalOptional.isPresent()) {
HivePrincipal principal = principalOptional.get();
if (principal != null && !principal.getRole().equals(HiveRoles.ADMIN)) {
User user = principal.getUser();
if (user == null && principal.getKey() != null) {
user = principal.getKey().getUser();
}
if (user != null && !user.isAdmin()) {
Set<Long> networks = userNetworkDao.findNetworksForUser(user.getId());
String functionString =
"function(values, arg) {" +
"return values.filter(function(v) {" +
"var networkId = v.id;" +
"return arg.indexOf(networkId) > -1;" +
"})" +
"}";
Function reduceFunction = Function.newAnonymousJsFunction(functionString);
builder.withReducePhase(reduceFunction, networks);
}
if (principal.getKey() != null && principal.getKey().getPermissions() != null) {
Set<AccessKeyPermission> permissions = principal.getKey().getPermissions();
Set<Long> ids = new HashSet<>();
for (AccessKeyPermission permission : permissions) {
Set<Long> id = permission.getNetworkIdsAsSet();
if (id != null) {
ids.addAll(id);
}
}
String functionString =
"function(values, arg) {" +
"return values.filter(function(v) {" +
"return arg.indexOf(v.id) > -1;" +
"})" +
"}";
Function reduceFunction = Function.newAnonymousJsFunction(functionString);
if (!ids.isEmpty()) builder.withReducePhase(reduceFunction, ids);
} else if (principal.getDevice() != null) {
String functionString =
"function(values, arg) {" +
"return values.filter(function(v) {" +
"var devices = v.devices;" +
"if (devices == null) return false;" +
"return devices.indexOf(arg) > -1;" +
"})" +
"}";
Function reduceFunction = Function.newAnonymousJsFunction(functionString);
builder.withReducePhase(reduceFunction, principal.getDevice());
}
}
}
builder.withReducePhase(Function.newNamedJsFunction("Riak.reduceSort"),
String.format(sortFunc, sortOrderAsc ? ">" : "<"),
true);
if (take == null)
take = Constants.DEFAULT_TAKE;
if (skip == null)
skip = 0;
BucketMapReduce bmr = builder.build();
RiakFuture<MapReduce.Response, BinaryValue> future = client.executeAsync(bmr);
try {
MapReduce.Response response = future.get();
return response.getResultsFromAllPhases(NetworkVO.class).stream()
.skip(skip)
.limit(take)
.collect(Collectors.toList());
} catch (InterruptedException | ExecutionException e) {
throw new HivePersistenceLayerException("Cannot get list of networks.", e);
}
}
#location 47
#vulnerability type NULL_DEREFERENCE | #fixed code
@Override
public List<NetworkVO> list(String name, String namePattern, String sortField, boolean sortOrderAsc, Integer take,
Integer skip, Optional<HivePrincipal> principalOptional) {
String sortFunc = sortMap.get(sortField);
if (sortFunc == null) {
sortFunc = sortMap.get("name");
}
BucketMapReduce.Builder builder = new BucketMapReduce.Builder()
.withNamespace(NETWORK_NS)
.withMapPhase(Function.newAnonymousJsFunction("function(riakObject, keyData, arg) { " +
" if(riakObject.values[0].metadata['X-Riak-Deleted']){ return []; } " +
" else { return Riak.mapValuesJson(riakObject, keyData, arg); }}"))
.withReducePhase(Function.newAnonymousJsFunction("function(values, arg) {" +
"return values.filter(function(v) {" +
"if (v === [] || v.name === null) { return false; }" +
"return true;" +
"})" +
"}"));
if (name != null) {
String func = String.format(
"function(values, arg) {" +
"return values.filter(function(v) {" +
"var name = v.name;" +
"return name == '%s';" +
"})" +
"}", name);
Function function = Function.newAnonymousJsFunction(func);
builder.withReducePhase(function);
} else if (namePattern != null) {
namePattern = namePattern.replace("%", "");
String func = String.format(
"function(values, arg) {" +
"return values.filter(function(v) {" +
"var name = v.name;" +
"if (name === null) { return false; }" +
"return name.indexOf('%s') > -1;" +
"})" +
"}", namePattern);
Function function = Function.newAnonymousJsFunction(func);
builder.withReducePhase(function);
}
if (principalOptional.isPresent()) {
HivePrincipal principal = principalOptional.get();
if (principal != null && !principal.getRole().equals(HiveRoles.ADMIN)) {
User user = principal.getUser();
if (user == null && principal.getKey() != null) {
user = principal.getKey().getUser();
}
if (user != null && !user.isAdmin()) {
Set<Long> networks = userNetworkDao.findNetworksForUser(user.getId());
String functionString =
"function(values, arg) {" +
"return values.filter(function(v) {" +
"var networkId = v.id;" +
"return arg.indexOf(networkId) > -1;" +
"})" +
"}";
Function reduceFunction = Function.newAnonymousJsFunction(functionString);
builder.withReducePhase(reduceFunction, networks);
}
if (principal.getKey() != null && principal.getKey().getPermissions() != null) {
Set<AccessKeyPermission> permissions = principal.getKey().getPermissions();
Set<Long> ids = new HashSet<>();
for (AccessKeyPermission permission : permissions) {
Set<Long> id = permission.getNetworkIdsAsSet();
if (id != null) {
ids.addAll(id);
}
}
String functionString =
"function(values, arg) {" +
"return values.filter(function(v) {" +
"return arg.indexOf(v.id) > -1;" +
"})" +
"}";
Function reduceFunction = Function.newAnonymousJsFunction(functionString);
if (!ids.isEmpty()) builder.withReducePhase(reduceFunction, ids);
} else if (principal.getDevice() != null) {
String functionString =
"function(values, arg) {" +
"return values.filter(function(v) {" +
"var devices = v.devices;" +
"if (devices == null) return false;" +
"return devices.indexOf(arg) > -1;" +
"})" +
"}";
Function reduceFunction = Function.newAnonymousJsFunction(functionString);
builder.withReducePhase(reduceFunction, principal.getDevice());
}
}
}
builder.withReducePhase(Function.newNamedJsFunction("Riak.reduceSort"),
String.format(sortFunc, sortOrderAsc ? ">" : "<"),
true);
if (take == null)
take = Constants.DEFAULT_TAKE;
if (skip == null)
skip = 0;
BucketMapReduce bmr = builder.build();
RiakFuture<MapReduce.Response, BinaryValue> future = client.executeAsync(bmr);
try {
MapReduce.Response response = future.get();
List<RiakNetwork> result = response.getResultsFromAllPhases(RiakNetwork.class).stream()
.skip(skip)
.limit(take)
.collect(Collectors.toList());
return result.stream().map(RiakNetwork::convert).collect(Collectors.toList());
} catch (InterruptedException | ExecutionException e) {
throw new HivePersistenceLayerException("Cannot get list of networks.", e);
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Override
public AccessKey merge(AccessKey key) {
try {
long userId = key.getUserId();
User user = key.getUser();
Location location = new Location(USER_AND_LABEL_ACCESS_KEY_NS, String.valueOf(userId) + "n" + key.getLabel());
if (key.getId() == null) {
key.setId(getId(COUNTERS_LOCATION));
StoreValue storeValue = new StoreValue.Builder(key.getId()).withLocation(location).build();
client.execute(storeValue);
} else {
AccessKey existing = find(key.getId());
if (existing.getLabel().equals(key.getLabel())) {
DeleteValue delete = new DeleteValue.Builder(location).build();
client.execute(delete);
StoreValue storeValue = new StoreValue.Builder(key.getId()).withLocation(location).build();
client.execute(storeValue);
}
}
Location accessKeyLocation = new Location(ACCESS_KEY_NS, String.valueOf(key.getId()));
removeReferences(key);
StoreValue storeOp = new StoreValue.Builder(key).withLocation(accessKeyLocation).build();
client.execute(storeOp);
return restoreReferences(key, user);
} catch (ExecutionException | InterruptedException e) {
throw new HivePersistenceLayerException("Cannot store access key.", e);
}
}
#location 13
#vulnerability type NULL_DEREFERENCE | #fixed code
@Override
public AccessKey merge(AccessKey key) {
try {
long userId = key.getUserId();
User user = key.getUser();
Location location = new Location(USER_AND_LABEL_ACCESS_KEY_NS, String.valueOf(userId) + "n" + key.getLabel());
if (key.getId() == null) {
key.setId(getId(COUNTERS_LOCATION));
StoreValue storeValue = new StoreValue.Builder(key.getId()).withLocation(location).build();
client.execute(storeValue);
} else {
AccessKey existing = find(key.getId());
if (existing != null && existing.getLabel().equals(key.getLabel())) {
DeleteValue delete = new DeleteValue.Builder(location).build();
client.execute(delete);
}
StoreValue storeValue = new StoreValue.Builder(key.getId()).withLocation(location).build();
client.execute(storeValue);
}
Location accessKeyLocation = new Location(ACCESS_KEY_NS, String.valueOf(key.getId()));
removeReferences(key);
StoreValue storeOp = new StoreValue.Builder(key).withLocation(accessKeyLocation).build();
client.execute(storeOp);
return restoreReferences(key, user);
} catch (ExecutionException | InterruptedException e) {
throw new HivePersistenceLayerException("Cannot store access key.", e);
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
public static void filterActions(AllowedKeyAction.Action allowedAction,
Set<AccessKeyPermission> permissions) {
Set<AccessKeyPermission> permissionsToRemove = new HashSet<>();
for (AccessKeyPermission currentPermission : permissions) {
boolean isCurrentPermissionAllowed = false;
Set<String> actions = currentPermission.getActionsAsSet();
if (currentPermission.getAccessKey() != null && currentPermission.getAccessKey().getUser().getRole() != UserRole.ADMIN) {
actions.removeAll(AvailableActions.getAdminActions());
}
if (actions != null) {
for (String accessKeyAction : actions) {
isCurrentPermissionAllowed = accessKeyAction.equalsIgnoreCase(allowedAction.getValue());
if (isCurrentPermissionAllowed) {
break;
}
}
if (!isCurrentPermissionAllowed) {
permissionsToRemove.add(currentPermission);
}
}
}
permissions.removeAll(permissionsToRemove);
}
#location 8
#vulnerability type NULL_DEREFERENCE | #fixed code
public static void filterActions(AllowedKeyAction.Action allowedAction,
Set<AccessKeyPermission> permissions) {
Set<AccessKeyPermission> permissionsToRemove = new HashSet<>();
for (AccessKeyPermission currentPermission : permissions) {
boolean isCurrentPermissionAllowed = false;
Set<String> actions = currentPermission.getActionsAsSet();
if (actions != null) {
if (currentPermission.getAccessKey() != null && currentPermission.getAccessKey().getUser().getRole() != UserRole.ADMIN) {
actions.removeAll(AvailableActions.getAdminActions());
}
for (String accessKeyAction : actions) {
isCurrentPermissionAllowed = accessKeyAction.equalsIgnoreCase(allowedAction.getValue());
if (isCurrentPermissionAllowed) {
break;
}
}
if (!isCurrentPermissionAllowed) {
permissionsToRemove.add(currentPermission);
}
}
}
permissions.removeAll(permissionsToRemove);
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Override
public User getWithNetworksById(long id) {
User user = find(id);
Set<Long> networkIds = userNetworkDao.findNetworksForUser(id);
if (networkIds == null) {
return user;
}
Set<Network> networks = new HashSet<>();
for (Long networkId : networkIds) {
Network network = networkDao.find(networkId);
networks.add(network);
}
user.setNetworks(networks);
return user;
}
#location 14
#vulnerability type NULL_DEREFERENCE | #fixed code
@Override
public User getWithNetworksById(long id) {
User user = find(id);
if (user == null) {
return user;
}
Set<Long> networkIds = userNetworkDao.findNetworksForUser(id);
if (networkIds == null) {
return user;
}
Set<Network> networks = new HashSet<>();
for (Long networkId : networkIds) {
Network network = networkDao.find(networkId);
networks.add(network);
}
user.setNetworks(networks);
return user;
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Test
public void shouldSendRequestToServer() throws Exception {
CompletableFuture<Request> future = new CompletableFuture<>();
RequestHandler mockedHandler = request -> {
future.complete(request);
return Response.newBuilder()
.withCorrelationId(request.getCorrelationId())
.withBody("Response".getBytes())
.withLast(true)
.buildSuccess();
};
RpcServer server = buildServer(mockedHandler);
server.start();
RpcClient client = buildClient();
client.start();
Request request = Request.newBuilder()
.withCorrelationId(UUID.randomUUID().toString())
.withSingleReply(true)
.withBody("RequestResponseTest".getBytes())
.build();
TimeUnit.SECONDS.sleep(10);
client.push(request);
Request receivedRequest = future.get(20, TimeUnit.SECONDS);
assertEquals(request, receivedRequest);
}
#location 27
#vulnerability type RESOURCE_LEAK | #fixed code
@Test
public void shouldSendRequestToServer() throws Exception {
CompletableFuture<Request> future = new CompletableFuture<>();
RequestHandler handler = request -> {
future.complete(request);
return Response.newBuilder()
.withCorrelationId(request.getCorrelationId())
.withBody("Response".getBytes())
.withLast(true)
.buildSuccess();
};
handlerWrapper.setDelegate(handler);
Request request = Request.newBuilder()
.withCorrelationId(UUID.randomUUID().toString())
.withSingleReply(true)
.withBody("RequestResponseTest".getBytes())
.build();
client.push(request);
Request receivedRequest = future.get(10, TimeUnit.SECONDS);
assertEquals(request, receivedRequest);
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
public Device getDevice(UUID deviceId, User currentUser, Device currentDevice) {
Device device = deviceDAO.findByUUIDWithNetworkAndDeviceClass(deviceId);
device.getDeviceClass();//initializing properties
device.getNetwork();
if (device == null || !checkPermissions(device, currentUser, currentDevice)) {
throw new HiveException("Device Not found", NOT_FOUND.getStatusCode());
}
return device;
}
#location 4
#vulnerability type NULL_DEREFERENCE | #fixed code
public Device getDevice(UUID deviceId, User currentUser, Device currentDevice) {
Device device = deviceDAO.findByUUIDWithNetworkAndDeviceClass(deviceId);
if (device == null || !checkPermissions(device, currentUser, currentDevice)) {
throw new HiveException("Device Not found", NOT_FOUND.getStatusCode());
}
device.getDeviceClass();//initializing properties
device.getNetwork();
return device;
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
ProtobufRPC protobufPRC = method.getAnnotation(ProtobufRPC.class);
if (protobufPRC == null) {
throw new IllegalAccessError("Target method is not marked annotation @ProtobufPRC. method name :"
+ method.getDeclaringClass().getName() + "." + method.getName());
}
String serviceName = protobufPRC.serviceName();
String methodName = protobufPRC.methodName();
if (StringUtils.isEmpty(methodName)) {
methodName = method.getName();
}
String methodSignature = serviceName + '!' + methodName;
RpcMethodInfo rpcMethodInfo = cachedRpcMethods.get(methodSignature);
if (rpcMethodInfo == null) {
throw new IllegalAccessError("Can not invoke method '" + method.getName()
+ "' due to not a protbufRpc method.");
}
long onceTalkTimeout = rpcMethodInfo.getOnceTalkTimeout();
if (onceTalkTimeout <= 0) {
// use default once talk timeout
onceTalkTimeout = rpcClient.getRpcClientOptions().getOnceTalkTimeout();
}
BlockingRpcCallback callback = new BlockingRpcCallback();
RpcDataPackage rpcDataPackage = buildRequestDataPackage(rpcMethodInfo, args);
// set correlationId
rpcDataPackage.getRpcMeta().setCorrelationId(rpcClient.getNextCorrelationId());
rpcChannel.doTransport(rpcDataPackage, callback, onceTalkTimeout);
if (!callback.isDone()) {
synchronized (callback) {
while (!callback.isDone()) {
try {
callback.wait();
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
}
}
RpcDataPackage message = callback.getMessage();
RpcResponseMeta response = message.getRpcMeta().getResponse();
if (response != null) {
Integer errorCode = response.getErrorCode();
if (!ErrorCodes.isSuccess(errorCode)) {
String error = message.getRpcMeta().getResponse().getErrorText();
throw new Throwable("A error occurred: errorCode=" + errorCode + " errorMessage:" + error);
}
}
byte[] attachment = message.getAttachment();
if (attachment != null) {
ClientAttachmentHandler attachmentHandler = rpcMethodInfo.getClientAttachmentHandler();
if (attachmentHandler != null) {
attachmentHandler.handleResponse(attachment, serviceName, methodName, args);
}
}
// handle response data
byte[] data = message.getData();
if (data == null) {
return null;
}
return rpcMethodInfo.outputDecode(data);
}
#location 31
#vulnerability type THREAD_SAFETY_VIOLATION | #fixed code
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
ProtobufRPC protobufPRC = method.getAnnotation(ProtobufRPC.class);
if (protobufPRC == null) {
throw new IllegalAccessError("Target method is not marked annotation @ProtobufPRC. method name :"
+ method.getDeclaringClass().getName() + "." + method.getName());
}
String serviceName = protobufPRC.serviceName();
String methodName = protobufPRC.methodName();
if (StringUtils.isEmpty(methodName)) {
methodName = method.getName();
}
String methodSignature = serviceName + '!' + methodName;
RpcMethodInfo rpcMethodInfo = cachedRpcMethods.get(methodSignature);
if (rpcMethodInfo == null) {
throw new IllegalAccessError("Can not invoke method '" + method.getName()
+ "' due to not a protbufRpc method.");
}
long onceTalkTimeout = rpcMethodInfo.getOnceTalkTimeout();
if (onceTalkTimeout <= 0) {
// use default once talk timeout
onceTalkTimeout = rpcClient.getRpcClientOptions().getOnceTalkTimeout();
}
BlockingRpcCallback callback = new BlockingRpcCallback();
RpcDataPackage rpcDataPackage = buildRequestDataPackage(rpcMethodInfo, args);
// set correlationId
rpcDataPackage.getRpcMeta().setCorrelationId(rpcClient.getNextCorrelationId());
RpcChannel rpcChannel = rpcChannelMap.get(methodSignature);
if (rpcChannel == null) {
throw new RuntimeException("No rpcChannel bind with serviceSignature '" + methodSignature + "'");
}
rpcChannel.doTransport(rpcDataPackage, callback, onceTalkTimeout);
if (!callback.isDone()) {
synchronized (callback) {
while (!callback.isDone()) {
try {
callback.wait();
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
}
}
RpcDataPackage message = callback.getMessage();
RpcResponseMeta response = message.getRpcMeta().getResponse();
if (response != null) {
Integer errorCode = response.getErrorCode();
if (!ErrorCodes.isSuccess(errorCode)) {
String error = message.getRpcMeta().getResponse().getErrorText();
throw new Throwable("A error occurred: errorCode=" + errorCode + " errorMessage:" + error);
}
}
byte[] attachment = message.getAttachment();
if (attachment != null) {
ClientAttachmentHandler attachmentHandler = rpcMethodInfo.getClientAttachmentHandler();
if (attachmentHandler != null) {
attachmentHandler.handleResponse(attachment, serviceName, methodName, args);
}
}
// handle response data
byte[] data = message.getData();
if (data == null) {
return null;
}
return rpcMethodInfo.outputDecode(data);
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Override
public Object invoke(MethodInvocation invocation) throws Throwable {
if (instance == null) {
throw new NullPointerException("target instance is null may be not initial correct.");
}
Object result = invocation.getMethod().invoke(instance, invocation.getArguments());
return result;
}
#location 6
#vulnerability type THREAD_SAFETY_VIOLATION | #fixed code
@Override
public Object invoke(MethodInvocation invocation) throws Throwable {
Method method = invocation.getMethod();
ProtobufRPC protobufPRC = method.getAnnotation(ProtobufRPC.class);
if (protobufPRC == null) {
throw new IllegalAccessError("Target method is not marked annotation @ProtobufPRC. method name :"
+ method.getDeclaringClass().getName() + "." + method.getName());
}
String serviceName = protobufPRC.serviceName();
String methodName = protobufPRC.methodName();
if (StringUtils.isEmpty(methodName)) {
methodName = method.getName();
}
String methodSignature = serviceName + '!' + methodName;
Object instance = instancesMap.get(methodSignature);
if (instance == null) {
throw new NullPointerException("target instance is null may be not initial correct.");
}
Object result = invocation.getMethod().invoke(instance, invocation.getArguments());
return result;
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
public RpcData doHandle(RpcData data) throws Exception {
Object input = null;
Object[] param;
Object ret;
if (data.getData() != null && parseFromMethod != null) {
input = parseFromMethod.invoke(getInputClass(), new ByteArrayInputStream(data.getData()));;
param = new Object[] {input};
} else {
param = new Object[0];
}
RpcData retData = new RpcData();
// process attachment
if (getAttachmentHandler() != null) {
byte[] responseAttachment = getAttachmentHandler().handleAttachement(data.getAttachment(), getServiceName(), getMethodName(), param);
retData.setAttachment(responseAttachment);
}
ret = getMethod().invoke(getService(), param);
if (ret == null) {
return retData;
}
if (ret != null && ret instanceof GeneratedMessage) {
byte[] response = ((GeneratedMessage) input).toByteArray();
retData.setData(response);
}
return retData;
}
#location 27
#vulnerability type NULL_DEREFERENCE | #fixed code
public RpcData doHandle(RpcData data) throws Exception {
Object input = null;
Object[] param;
Object ret;
if (data.getData() != null && parseFromMethod != null) {
input = parseFromMethod.invoke(getInputClass(), new ByteArrayInputStream(data.getData()));;
param = new Object[] {input};
} else {
param = new Object[0];
}
RpcData retData = new RpcData();
// process attachment
if (getAttachmentHandler() != null) {
byte[] responseAttachment = getAttachmentHandler().handleAttachement(data.getAttachment(), getServiceName(), getMethodName(), param);
retData.setAttachment(responseAttachment);
}
ret = getMethod().invoke(getService(), param);
if (ret == null) {
return retData;
}
if (ret != null && ret instanceof GeneratedMessage) {
byte[] response = ((GeneratedMessage) ret).toByteArray();
retData.setData(response);
}
return retData;
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
public void close() {
doClose(lbProxyBean, protobufRpcProxyList);
super.close();
}
#location 2
#vulnerability type THREAD_SAFETY_VIOLATION | #fixed code
public void close() {
Collection<List<ProtobufRpcProxy<T>>> values = protobufRpcProxyListMap.values();
for (List<ProtobufRpcProxy<T>> list : values) {
doClose(null, list);
}
Collection<LoadBalanceProxyFactoryBean> lbs = lbMap.values();
for (LoadBalanceProxyFactoryBean loadBalanceProxyFactoryBean : lbs) {
doClose(loadBalanceProxyFactoryBean, null);
}
super.close();
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Override
protected void reInit(final String service, final List<InetSocketAddress> list) throws Exception {
// store old
LoadBalanceProxyFactoryBean oldLbProxyBean = lbMap.get(service);
List<ProtobufRpcProxy<T>> oldProtobufRpcProxyList =
new ArrayList<ProtobufRpcProxy<T>>(protobufRpcProxyListMap.get(service));
// reinit naming service
loadBalanceStrategy.doReInit(service, new NamingService() {
@Override
public Map<String, List<InetSocketAddress>> list(Set<String> serviceSignatures) throws Exception {
Map<String, List<InetSocketAddress>> ret = new HashMap<String, List<InetSocketAddress>>();
ret.put(service, list);
return ret;
}
});
// create a new instance
doProxy(service, list);
try {
// try to close old
doClose(oldLbProxyBean, oldProtobufRpcProxyList);
} catch (Exception e) {
LOGGER.fatal(e.getMessage(), e);
}
}
#location 9
#vulnerability type THREAD_SAFETY_VIOLATION | #fixed code
@Override
protected void reInit(final String service, final List<InetSocketAddress> list) throws Exception {
// store old
LoadBalanceProxyFactoryBean oldLbProxyBean = lbMap.get(service);
List<ProtobufRpcProxy<T>> oldProtobufRpcProxyList =
new ArrayList<ProtobufRpcProxy<T>>(protobufRpcProxyListMap.get(service));
// create a new instance
doProxy(service, list);
try {
// try to close old
doClose(oldLbProxyBean, oldProtobufRpcProxyList);
} catch (Exception e) {
LOGGER.fatal(e.getMessage(), e);
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
public void close() {
if (rpcChannel != null) {
rpcChannel.close();
}
}
#location 3
#vulnerability type THREAD_SAFETY_VIOLATION | #fixed code
public void close() {
Collection<RpcChannel> rpcChannels = rpcChannelMap.values();
for (RpcChannel rpcChann : rpcChannels) {
try {
rpcChann.close();
} catch (Exception e) {
LOG.log(Level.SEVERE, e.getMessage(), e.getCause());
}
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Test
public void testExecuteAndFetch(){
createAndFillUserTable();
Date before = new Date();
List<User> allUsers = sql2o.createQuery("select * from User").executeAndFetch(User.class);
Date after = new Date();
long span = after.getTime() - before.getTime();
System.out.println(String.format("Fetched %s user: %s ms", insertIntoUsers, span));
// repeat this
before = new Date();
allUsers = sql2o.createQuery("select * from User").executeAndFetch(User.class);
after = new Date();
span = after.getTime() - before.getTime();
System.out.println(String.format("Again Fetched %s user: %s ms", insertIntoUsers, span));
assertTrue(allUsers.size() == insertIntoUsers);
deleteUserTable();
}
#location 13
#vulnerability type RESOURCE_LEAK | #fixed code
@Test
public void testExecuteAndFetch(){
createAndFillUserTable();
try (Connection con = sql2o.open()) {
Date before = new Date();
List<User> allUsers = con.createQuery("select * from User").executeAndFetch(User.class);
assertNotNull(allUsers);
Date after = new Date();
long span = after.getTime() - before.getTime();
System.out.println(String.format("Fetched %s user: %s ms", insertIntoUsers, span));
// repeat this
before = new Date();
allUsers = con.createQuery("select * from User").executeAndFetch(User.class);
after = new Date();
span = after.getTime() - before.getTime();
System.out.println(String.format("Again Fetched %s user: %s ms", insertIntoUsers, span));
assertTrue(allUsers.size() == insertIntoUsers);
}
deleteUserTable();
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Test
public void testExecuteAndFetchWithNulls(){
String sql =
"create table testExecWithNullsTbl (" +
"id int identity primary key, " +
"text varchar(255), " +
"aNumber int, " +
"aLongNumber bigint)";
sql2o.createQuery(sql, "testExecuteAndFetchWithNulls").executeUpdate();
Connection connection = sql2o.beginTransaction();
Query insQuery = connection.createQuery("insert into testExecWithNullsTbl (text, aNumber, aLongNumber) values(:text, :number, :lnum)");
insQuery.addParameter("text", "some text").addParameter("number", 2).addParameter("lnum", 10L).executeUpdate();
insQuery.addParameter("text", "some text").addParameter("number", (Integer)null).addParameter("lnum", 10L).executeUpdate();
insQuery.addParameter("text", (String)null).addParameter("number", 21).addParameter("lnum", (Long)null).executeUpdate();
insQuery.addParameter("text", "some text").addParameter("number", 1221).addParameter("lnum", 10).executeUpdate();
insQuery.addParameter("text", "some text").addParameter("number", 2311).addParameter("lnum", 12).executeUpdate();
connection.commit();
List<Entity> fetched = sql2o.createQuery("select * from testExecWithNullsTbl").executeAndFetch(Entity.class);
assertTrue(fetched.size() == 5);
assertNull(fetched.get(2).text);
assertNotNull(fetched.get(3).text);
assertNull(fetched.get(1).aNumber);
assertNotNull(fetched.get(2).aNumber);
assertNull(fetched.get(2).aLongNumber);
assertNotNull(fetched.get(3).aLongNumber);
}
#location 19
#vulnerability type RESOURCE_LEAK | #fixed code
@Test
public void testExecuteAndFetchWithNulls(){
String sql =
"create table testExecWithNullsTbl (" +
"id int identity primary key, " +
"text varchar(255), " +
"aNumber int, " +
"aLongNumber bigint)";
try (Connection con = sql2o.open()) {
con.createQuery(sql, "testExecuteAndFetchWithNulls").executeUpdate();
Connection connection = sql2o.beginTransaction();
Query insQuery = connection.createQuery("insert into testExecWithNullsTbl (text, aNumber, aLongNumber) values(:text, :number, :lnum)");
insQuery.addParameter("text", "some text").addParameter("number", 2).addParameter("lnum", 10L).executeUpdate();
insQuery.addParameter("text", "some text").addParameter("number", (Integer) null).addParameter("lnum", 10L).executeUpdate();
insQuery.addParameter("text", (String) null).addParameter("number", 21).addParameter("lnum", (Long) null).executeUpdate();
insQuery.addParameter("text", "some text").addParameter("number", 1221).addParameter("lnum", 10).executeUpdate();
insQuery.addParameter("text", "some text").addParameter("number", 2311).addParameter("lnum", 12).executeUpdate();
connection.commit();
List<Entity> fetched = con.createQuery("select * from testExecWithNullsTbl").executeAndFetch(Entity.class);
assertTrue(fetched.size() == 5);
assertNull(fetched.get(2).text);
assertNotNull(fetched.get(3).text);
assertNull(fetched.get(1).aNumber);
assertNotNull(fetched.get(2).aNumber);
assertNull(fetched.get(2).aLongNumber);
assertNotNull(fetched.get(3).aLongNumber);
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
public Query createQueryWithParams(String queryText, Object... paramValues){
return createQuery(queryText, null)
.withParams(paramValues);
}
#location 3
#vulnerability type RESOURCE_LEAK | #fixed code
public Query createQueryWithParams(String queryText, Object... paramValues){
Query query = createQuery(queryText, null);
boolean destroy = true;
try {
query.withParams(paramValues);
destroy = false;
return query;
} finally {
// instead of re-wrapping exception
// just keep it as-is
// but kill a query
if(destroy) query.close();
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Test
public void testExecuteAndFetchWithNulls(){
String sql =
"create table testExecWithNullsTbl (" +
"id int identity primary key, " +
"text varchar(255), " +
"aNumber int, " +
"aLongNumber bigint)";
sql2o.createQuery(sql, "testExecuteAndFetchWithNulls").executeUpdate();
Connection connection = sql2o.beginTransaction();
Query insQuery = connection.createQuery("insert into testExecWithNullsTbl (text, aNumber, aLongNumber) values(:text, :number, :lnum)");
insQuery.addParameter("text", "some text").addParameter("number", 2).addParameter("lnum", 10L).executeUpdate();
insQuery.addParameter("text", "some text").addParameter("number", (Integer)null).addParameter("lnum", 10L).executeUpdate();
insQuery.addParameter("text", (String)null).addParameter("number", 21).addParameter("lnum", (Long)null).executeUpdate();
insQuery.addParameter("text", "some text").addParameter("number", 1221).addParameter("lnum", 10).executeUpdate();
insQuery.addParameter("text", "some text").addParameter("number", 2311).addParameter("lnum", 12).executeUpdate();
connection.commit();
List<Entity> fetched = sql2o.createQuery("select * from testExecWithNullsTbl").executeAndFetch(Entity.class);
assertTrue(fetched.size() == 5);
assertNull(fetched.get(2).text);
assertNotNull(fetched.get(3).text);
assertNull(fetched.get(1).aNumber);
assertNotNull(fetched.get(2).aNumber);
assertNull(fetched.get(2).aLongNumber);
assertNotNull(fetched.get(3).aLongNumber);
}
#location 9
#vulnerability type RESOURCE_LEAK | #fixed code
@Test
public void testExecuteAndFetchWithNulls(){
String sql =
"create table testExecWithNullsTbl (" +
"id int identity primary key, " +
"text varchar(255), " +
"aNumber int, " +
"aLongNumber bigint)";
try (Connection con = sql2o.open()) {
con.createQuery(sql, "testExecuteAndFetchWithNulls").executeUpdate();
Connection connection = sql2o.beginTransaction();
Query insQuery = connection.createQuery("insert into testExecWithNullsTbl (text, aNumber, aLongNumber) values(:text, :number, :lnum)");
insQuery.addParameter("text", "some text").addParameter("number", 2).addParameter("lnum", 10L).executeUpdate();
insQuery.addParameter("text", "some text").addParameter("number", (Integer) null).addParameter("lnum", 10L).executeUpdate();
insQuery.addParameter("text", (String) null).addParameter("number", 21).addParameter("lnum", (Long) null).executeUpdate();
insQuery.addParameter("text", "some text").addParameter("number", 1221).addParameter("lnum", 10).executeUpdate();
insQuery.addParameter("text", "some text").addParameter("number", 2311).addParameter("lnum", 12).executeUpdate();
connection.commit();
List<Entity> fetched = con.createQuery("select * from testExecWithNullsTbl").executeAndFetch(Entity.class);
assertTrue(fetched.size() == 5);
assertNull(fetched.get(2).text);
assertNotNull(fetched.get(3).text);
assertNull(fetched.get(1).aNumber);
assertNotNull(fetched.get(2).aNumber);
assertNull(fetched.get(2).aLongNumber);
assertNotNull(fetched.get(3).aLongNumber);
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Test
public void testExecuteAndFetchWithNulls(){
String sql =
"create table testExecWithNullsTbl (" +
"id int identity primary key, " +
"text varchar(255), " +
"aNumber int, " +
"aLongNumber bigint)";
sql2o.createQuery(sql, "testExecuteAndFetchWithNulls").executeUpdate();
Connection connection = sql2o.beginTransaction();
Query insQuery = connection.createQuery("insert into testExecWithNullsTbl (text, aNumber, aLongNumber) values(:text, :number, :lnum)");
insQuery.addParameter("text", "some text").addParameter("number", 2).addParameter("lnum", 10L).executeUpdate();
insQuery.addParameter("text", "some text").addParameter("number", (Integer)null).addParameter("lnum", 10L).executeUpdate();
insQuery.addParameter("text", (String)null).addParameter("number", 21).addParameter("lnum", (Long)null).executeUpdate();
insQuery.addParameter("text", "some text").addParameter("number", 1221).addParameter("lnum", 10).executeUpdate();
insQuery.addParameter("text", "some text").addParameter("number", 2311).addParameter("lnum", 12).executeUpdate();
connection.commit();
List<Entity> fetched = sql2o.createQuery("select * from testExecWithNullsTbl").executeAndFetch(Entity.class);
assertTrue(fetched.size() == 5);
assertNull(fetched.get(2).text);
assertNotNull(fetched.get(3).text);
assertNull(fetched.get(1).aNumber);
assertNotNull(fetched.get(2).aNumber);
assertNull(fetched.get(2).aLongNumber);
assertNotNull(fetched.get(3).aLongNumber);
}
#location 21
#vulnerability type RESOURCE_LEAK | #fixed code
@Test
public void testExecuteAndFetchWithNulls(){
String sql =
"create table testExecWithNullsTbl (" +
"id int identity primary key, " +
"text varchar(255), " +
"aNumber int, " +
"aLongNumber bigint)";
try (Connection con = sql2o.open()) {
con.createQuery(sql, "testExecuteAndFetchWithNulls").executeUpdate();
Connection connection = sql2o.beginTransaction();
Query insQuery = connection.createQuery("insert into testExecWithNullsTbl (text, aNumber, aLongNumber) values(:text, :number, :lnum)");
insQuery.addParameter("text", "some text").addParameter("number", 2).addParameter("lnum", 10L).executeUpdate();
insQuery.addParameter("text", "some text").addParameter("number", (Integer) null).addParameter("lnum", 10L).executeUpdate();
insQuery.addParameter("text", (String) null).addParameter("number", 21).addParameter("lnum", (Long) null).executeUpdate();
insQuery.addParameter("text", "some text").addParameter("number", 1221).addParameter("lnum", 10).executeUpdate();
insQuery.addParameter("text", "some text").addParameter("number", 2311).addParameter("lnum", 12).executeUpdate();
connection.commit();
List<Entity> fetched = con.createQuery("select * from testExecWithNullsTbl").executeAndFetch(Entity.class);
assertTrue(fetched.size() == 5);
assertNull(fetched.get(2).text);
assertNotNull(fetched.get(3).text);
assertNull(fetched.get(1).aNumber);
assertNotNull(fetched.get(2).aNumber);
assertNull(fetched.get(2).aLongNumber);
assertNotNull(fetched.get(3).aLongNumber);
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Test
public void testExecuteAndFetch(){
createAndFillUserTable();
Date before = new Date();
List<User> allUsers = sql2o.createQuery("select * from User").executeAndFetch(User.class);
Date after = new Date();
long span = after.getTime() - before.getTime();
System.out.println(String.format("Fetched %s user: %s ms", insertIntoUsers, span));
// repeat this
before = new Date();
allUsers = sql2o.createQuery("select * from User").executeAndFetch(User.class);
after = new Date();
span = after.getTime() - before.getTime();
System.out.println(String.format("Again Fetched %s user: %s ms", insertIntoUsers, span));
assertTrue(allUsers.size() == insertIntoUsers);
deleteUserTable();
}
#location 6
#vulnerability type RESOURCE_LEAK | #fixed code
@Test
public void testExecuteAndFetch(){
createAndFillUserTable();
try (Connection con = sql2o.open()) {
Date before = new Date();
List<User> allUsers = con.createQuery("select * from User").executeAndFetch(User.class);
assertNotNull(allUsers);
Date after = new Date();
long span = after.getTime() - before.getTime();
System.out.println(String.format("Fetched %s user: %s ms", insertIntoUsers, span));
// repeat this
before = new Date();
allUsers = con.createQuery("select * from User").executeAndFetch(User.class);
after = new Date();
span = after.getTime() - before.getTime();
System.out.println(String.format("Again Fetched %s user: %s ms", insertIntoUsers, span));
assertTrue(allUsers.size() == insertIntoUsers);
}
deleteUserTable();
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Test
public void testSelectUsingNameNotGiven() {
db() //
.select("select score from person where name=:name and name<>:name2") //
.parameter("name", "FRED") //
.parameter("name", "JOSEPH") //
.getAs(Integer.class) //
.test() //
.awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) //
.assertError(NamedParameterMissingException.class) //
.assertNoValues();
}
#location 7
#vulnerability type RESOURCE_LEAK | #fixed code
@Test
public void testSelectUsingNameNotGiven() {
try (Database db = db()) {
db //
.select("select score from person where name=:name and name<>:name2") //
.parameter("name", "FRED") //
.parameter("name", "JOSEPH") //
.getAs(Integer.class) //
.test() //
.awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) //
.assertError(NamedParameterMissingException.class) //
.assertNoValues();
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
public static Database fromBlocking(@Nonnull ConnectionProvider cp) {
return Database.from(new ConnectionProviderBlockingPool(cp));
}
#location 2
#vulnerability type RESOURCE_LEAK | #fixed code
public static Database fromBlocking(@Nonnull ConnectionProvider cp) {
return Database.from(new ConnectionProviderBlockingPool2(cp));
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Test
public void testUpdateWithParameter() {
db().update("update person set score=20 where name=?") //
.parameter("FRED").counts() //
.test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) //
.assertValue(1) //
.assertComplete();
}
#location 4
#vulnerability type RESOURCE_LEAK | #fixed code
@Test
public void testUpdateWithParameter() {
try (Database db = db()) {
db.update("update person set score=20 where name=?") //
.parameter("FRED").counts() //
.test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) //
.assertValue(1) //
.assertComplete();
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Test
public void testInsertClobAndReadClobAsString() {
Database db = db();
db.update("insert into person_clob(name,document) values(?,?)") //
.parameters("FRED", "some text here") //
.counts() //
.test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) //
.assertValue(1) //
.assertComplete();
db.select("select document from person_clob where name='FRED'") //
.getAs(String.class) //
.test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // .assertValue("some
// text
// here")
// //
.assertComplete();
}
#location 11
#vulnerability type RESOURCE_LEAK | #fixed code
@Test
public void testInsertClobAndReadClobAsString() {
try (Database db = db()) {
db.update("insert into person_clob(name,document) values(?,?)") //
.parameters("FRED", "some text here") //
.counts() //
.test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) //
.assertValue(1) //
.assertComplete();
db.select("select document from person_clob where name='FRED'") //
.getAs(String.class) //
.test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // .assertValue("some
// text
// here")
// //
.assertComplete();
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Test
public void testAutoMapToInterfaceWithExplicitColumnNameThatDoesNotExist() {
db() //
.select("select name, score from person order by name") //
.autoMap(Person4.class) //
.firstOrError() //
.map(Person4::examScore) //
.test() //
.awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) //
.assertNoValues() //
.assertError(ColumnNotFoundException.class);
}
#location 5
#vulnerability type RESOURCE_LEAK | #fixed code
@Test
public void testAutoMapToInterfaceWithExplicitColumnNameThatDoesNotExist() {
try (Database db = db()) {
db //
.select("select name, score from person order by name") //
.autoMap(Person4.class) //
.firstOrError() //
.map(Person4::examScore) //
.test() //
.awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) //
.assertNoValues() //
.assertError(ColumnNotFoundException.class);
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
public static Database from(String url, int maxPoolSize) {
return Database.from(new NonBlockingConnectionPool(Util.connectionProvider(url), maxPoolSize, 1000));
}
#location 2
#vulnerability type RESOURCE_LEAK | #fixed code
public static Database from(String url, int maxPoolSize) {
return Database.from( //
Pools.nonBlocking() //
.url(url) //
.maxPoolSize(maxPoolSize) //
.build());
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
public static Database create(int maxSize) {
return Database
.from(new NonBlockingConnectionPool(connectionProvider(nextUrl()), maxSize, 1000));
}
#location 3
#vulnerability type RESOURCE_LEAK | #fixed code
public static Database create(int maxSize) {
return Database.from(Pools.nonBlocking().connectionProvider(connectionProvider(nextUrl()))
.maxPoolSize(maxSize).build());
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Test
public void testUpdateTimeParameter() {
Database db = db();
Time t = new Time(1234);
db.update("update person set registered=?") //
.parameter(t) //
.counts() //
.test() //
.awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) //
.assertValue(3) //
.assertComplete();
db.select("select registered from person") //
.getAs(Long.class) //
.firstOrError() //
.test() //
.awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) //
.assertValue(1234L) //
.assertComplete();
}
#location 13
#vulnerability type RESOURCE_LEAK | #fixed code
@Test
public void testUpdateTimeParameter() {
try (Database db = db()) {
Time t = new Time(1234);
db.update("update person set registered=?") //
.parameter(t) //
.counts() //
.test() //
.awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) //
.assertValue(3) //
.assertComplete();
db.select("select registered from person") //
.getAs(Long.class) //
.firstOrError() //
.test() //
.awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) //
.assertValue(1234L) //
.assertComplete();
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Test
public void testConnectionPoolRecylesMany() throws SQLException {
TestScheduler s = new TestScheduler();
Database db = DatabaseCreator.create(2, s);
TestSubscriber<Connection> ts = db //
.connection() //
.repeat() //
.test(4); //
s.triggerActions();
ts.assertNoErrors() //
.assertValueCount(2) //
.assertNotTerminated();
List<Connection> list = new ArrayList<>(ts.values());
list.get(1).close(); // should release a connection
s.triggerActions();
{
List<Object> values = ts.assertValueCount(3) //
.assertNotTerminated() //
.getEvents().get(0);
assertEquals(list.get(0).hashCode(), values.get(0).hashCode());
assertEquals(list.get(1).hashCode(), values.get(1).hashCode());
assertEquals(list.get(1).hashCode(), values.get(2).hashCode());
}
// .assertValues(list.get(0), list.get(1), list.get(1));
list.get(0).close();
s.triggerActions();
{
List<Object> values = ts.assertValueCount(4) //
.assertNotTerminated() //
.getEvents().get(0);
assertEquals(list.get(0).hashCode(), values.get(0).hashCode());
assertEquals(list.get(1).hashCode(), values.get(1).hashCode());
assertEquals(list.get(1).hashCode(), values.get(2).hashCode());
assertEquals(list.get(0).hashCode(), values.get(3).hashCode());
}
}
#location 6
#vulnerability type RESOURCE_LEAK | #fixed code
@Test
public void testConnectionPoolRecylesMany() throws SQLException {
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<Member<Integer>> ts = new FlowableSingleDeferUntilRequest<>(pool.member()) //
.repeat() //
.test(4); //
s.triggerActions();
ts.assertNoErrors() //
.assertValueCount(2) //
.assertNotTerminated();
List<Member<Integer>> list = new ArrayList<>(ts.values());
list.get(1).checkin(); // should release a connection
s.triggerActions();
{
List<Object> values = ts.assertValueCount(3) //
.assertNotTerminated() //
.getEvents().get(0);
assertEquals(list.get(0).hashCode(), values.get(0).hashCode());
assertEquals(list.get(1).hashCode(), values.get(1).hashCode());
assertEquals(list.get(1).hashCode(), values.get(2).hashCode());
}
// .assertValues(list.get(0), list.get(1), list.get(1));
list.get(0).checkin();
s.triggerActions();
{
List<Object> values = ts.assertValueCount(4) //
.assertNotTerminated() //
.getEvents().get(0);
assertEquals(list.get(0).hashCode(), values.get(0).hashCode());
assertEquals(list.get(1).hashCode(), values.get(1).hashCode());
assertEquals(list.get(1).hashCode(), values.get(2).hashCode());
assertEquals(list.get(0).hashCode(), values.get(3).hashCode());
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Test
public void testTuple7() {
db() //
.select("select name, score, name, score, name, score, name from person order by name") //
.getAs(String.class, Integer.class, String.class, Integer.class, String.class,
Integer.class, String.class) //
.firstOrError() //
.test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) //
.assertComplete()
.assertValue(Tuple7.create("FRED", 21, "FRED", 21, "FRED", 21, "FRED")); //
}
#location 5
#vulnerability type RESOURCE_LEAK | #fixed code
@Test
public void testTuple7() {
try (Database db = db()) {
db //
.select("select name, score, name, score, name, score, name from person order by name") //
.getAs(String.class, Integer.class, String.class, Integer.class, String.class,
Integer.class, String.class) //
.firstOrError() //
.test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) //
.assertComplete()
.assertValue(Tuple7.create("FRED", 21, "FRED", 21, "FRED", 21, "FRED")); //
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Test
public void testUpdateTimestampAsZonedDateTime() {
Database db = db();
db.update("update person set registered=? where name='FRED'") //
.parameter(ZonedDateTime.ofInstant(Instant.ofEpochMilli(FRED_REGISTERED_TIME),
ZoneOffset.UTC.normalized())) //
.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 12
#vulnerability type RESOURCE_LEAK | #fixed code
@Test
public void testUpdateTimestampAsZonedDateTime() {
try (Database db = db()) {
db.update("update person set registered=? where name='FRED'") //
.parameter(ZonedDateTime.ofInstant(Instant.ofEpochMilli(FRED_REGISTERED_TIME),
ZoneOffset.UTC.normalized())) //
.counts() //
.test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) //
.assertValue(1) //
.assertComplete();
db.select("select registered from person where name='FRED'") //
.getAs(Long.class) //
.test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) //
.assertValue(FRED_REGISTERED_TIME) //
.assertComplete();
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Test
public void testCreate() {
Database db = DatabaseCreator.create();
}
#location 3
#vulnerability type RESOURCE_LEAK | #fixed code
@Test
public void testCreate() {
DatabaseCreator.create(1);
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Test
public void testInsertNullClobAndReadClobAsTuple2() {
Database db = db();
insertNullClob(db);
db.select("select document, document from person_clob where name='FRED'") //
.getAs(String.class, String.class) //
.test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) //
.assertValue(Tuple2.create(null, null)) //
.assertComplete();
}
#location 6
#vulnerability type RESOURCE_LEAK | #fixed code
@Test
public void testInsertNullClobAndReadClobAsTuple2() {
try (Database db = db()) {
insertNullClob(db);
db.select("select document, document from person_clob where name='FRED'") //
.getAs(String.class, String.class) //
.test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) //
.assertValue(Tuple2.create(null, null)) //
.assertComplete();
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
private void testHealthCheck(Predicate<Connection> healthy) throws InterruptedException {
TestScheduler scheduler = new TestScheduler();
NonBlockingConnectionPool2 pool = Pools //
.nonBlocking() //
.connectionProvider(DatabaseCreator.connectionProvider()) //
.maxIdleTime(10, TimeUnit.MINUTES) //
.idleTimeBeforeHealthCheck(0, TimeUnit.MINUTES) //
.healthy(healthy) //
.returnToPoolDelayAfterHealthCheckFailure(1, TimeUnit.MINUTES) //
.scheduler(scheduler) //
.maxPoolSize(1) //
.build();
try (Database db = Database.from(pool)) {
TestSubscriber<Integer> ts0 = db.select( //
"select score from person where name=?") //
.parameter("FRED") //
.getAs(Integer.class) //
.test();
ts0.assertValueCount(0) //
.assertNotComplete();
scheduler.advanceTimeBy(1, TimeUnit.MINUTES);
ts0.assertValueCount(1) //
.assertComplete();
TestSubscriber<Integer> ts = db.select( //
"select score from person where name=?") //
.parameter("FRED") //
.getAs(Integer.class) //
.test() //
.assertValueCount(0);
System.out.println("done2");
scheduler.advanceTimeBy(1, TimeUnit.MINUTES);
Thread.sleep(200);
ts.assertValueCount(1);
Thread.sleep(200);
ts.assertValue(21) //
.assertComplete();
}
}
#location 15
#vulnerability type RESOURCE_LEAK | #fixed code
private void testHealthCheck(Predicate<Connection> healthy) throws InterruptedException {
TestScheduler scheduler = new TestScheduler();
NonBlockingConnectionPool pool = Pools //
.nonBlocking() //
.connectionProvider(DatabaseCreator.connectionProvider()) //
.maxIdleTime(10, TimeUnit.MINUTES) //
.idleTimeBeforeHealthCheck(0, TimeUnit.MINUTES) //
.healthy(healthy) //
.returnToPoolDelayAfterHealthCheckFailure(1, TimeUnit.MINUTES) //
.scheduler(scheduler) //
.maxPoolSize(1) //
.build();
try (Database db = Database.from(pool)) {
TestSubscriber<Integer> ts0 = db.select( //
"select score from person where name=?") //
.parameter("FRED") //
.getAs(Integer.class) //
.test();
ts0.assertValueCount(0) //
.assertNotComplete();
scheduler.advanceTimeBy(1, TimeUnit.MINUTES);
ts0.assertValueCount(1) //
.assertComplete();
TestSubscriber<Integer> ts = db.select( //
"select score from person where name=?") //
.parameter("FRED") //
.getAs(Integer.class) //
.test() //
.assertValueCount(0);
System.out.println("done2");
scheduler.advanceTimeBy(1, TimeUnit.MINUTES);
Thread.sleep(200);
ts.assertValueCount(1);
Thread.sleep(200);
ts.assertValue(21) //
.assertComplete();
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Test
@Ignore
public void testCallableApi() {
Database db = DatabaseCreator.createDerbyWithStoredProcs(1);
db //
.call("call getPersonCount(?,?)") //
.in(0) //
.out(Integer.class) //
.build() //
.test() //
.awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) //
.assertValue(2) //
.assertComplete();
;
}
#location 10
#vulnerability type NULL_DEREFERENCE | #fixed 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();
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Test
public void testCountsInTransaction() {
db().update("update person set score = -3") //
.transacted() //
.counts() //
.doOnNext(System.out::println) //
.toList() //
.test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) //
.assertValue(list -> list.get(0).isValue() && list.get(0).value() == 3
&& list.get(1).isComplete() && list.size() == 2) //
.assertComplete();
}
#location 5
#vulnerability type RESOURCE_LEAK | #fixed code
@Test
public void testCountsInTransaction() {
try (Database db = db()) {
db.update("update person set score = -3") //
.transacted() //
.counts() //
.doOnNext(System.out::println) //
.toList() //
.test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) //
.assertValue(list -> list.get(0).isValue() && list.get(0).value() == 3
&& list.get(1).isComplete() && list.size() == 2) //
.assertComplete();
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Test
public void testSelectTransactedCount() {
db() //
.select("select name, score, name, score, name, score, name from person where name=?") //
.parameters("FRED") //
.transacted() //
.count() //
.test() //
.awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) //
.assertValueCount(1) //
.assertComplete();
}
#location 5
#vulnerability type RESOURCE_LEAK | #fixed code
@Test
public void testSelectTransactedCount() {
try (Database db = db()) {
db //
.select("select name, score, name, score, name, score, name from person where name=?") //
.parameters("FRED") //
.transacted() //
.count() //
.test() //
.awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) //
.assertValueCount(1) //
.assertComplete();
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Test
public void testSelectAutomappedAnnotatedTransacted() {
db() //
.select(Person10.class) //
.transacted() //
.valuesOnly() //
.get().test() //
.awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) //
.assertValueCount(3) //
.assertComplete();
}
#location 7
#vulnerability type RESOURCE_LEAK | #fixed code
@Test
public void testSelectAutomappedAnnotatedTransacted() {
try (Database db = db()) {
db //
.select(Person10.class) //
.transacted() //
.valuesOnly() //
.get().test() //
.awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) //
.assertValueCount(3) //
.assertComplete();
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Test
public void testCallableStatement() {
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(
"call sqlj.install_jar('target/rxjava2-jdbc-stored-procedure.jar', 'APP.examples',0)");
String sql = "CREATE PROCEDURE APP.GETPERSONCOUNT" //
+ " (IN MIN_SCORE INTEGER," //
+ " OUT COUNT INTEGER)" //
+ " PARAMETER STYLE JAVA" //
+ " LANGUAGE JAVA" //
+ " EXTERNAL NAME" //
+ " 'org.davidmoten.rx.jdbc.StoredProcExample.getPersonCount'";
stmt.execute(sql);
stmt.execute("CALL SYSCS_UTIL.SYSCS_SET_DATABASE_PROPERTY("
+ "'derby.database.classpath', 'APP.examples')");
CallableStatement st = con.prepareCall("call getPersonCount(?, ?)");
st.setInt(1, 0);
st.registerOutParameter(2, Types.INTEGER);
st.execute();
assertEquals(0, st.getInt(2));
}
}).blockingAwait(TIMEOUT_SECONDS, TimeUnit.SECONDS);
}
#location 4
#vulnerability type RESOURCE_LEAK | #fixed code
@Test
public void testCallableStatement() {
Database db = DatabaseCreator.createDerbyWithStoredProcs(1);
db.apply(con -> {
try (Statement stmt = con.createStatement()) {
CallableStatement st = con.prepareCall("call getPersonCount(?, ?)");
st.setInt(1, 0);
st.registerOutParameter(2, Types.INTEGER);
st.execute();
assertEquals(2, st.getInt(2));
}
}).blockingAwait(TIMEOUT_SECONDS, TimeUnit.SECONDS);
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Test
public void testSelectTransactedGetAs() {
db() //
.select("select name from person") //
.transacted() //
.getAs(String.class) //
.test() //
.awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) //
.assertValueCount(4) //
.assertComplete();
}
#location 6
#vulnerability type RESOURCE_LEAK | #fixed code
@Test
public void testSelectTransactedGetAs() {
try (Database db = db()) {
db //
.select("select name from person") //
.transacted() //
.getAs(String.class) //
.test() //
.awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) //
.assertValueCount(4) //
.assertComplete();
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Test(expected = QueryAnnotationMissingException.class)
public void testAutoMapWithoutQueryInAnnotation() {
db().select(Person.class);
}
#location 3
#vulnerability type RESOURCE_LEAK | #fixed code
@Test(expected = QueryAnnotationMissingException.class)
public void testAutoMapWithoutQueryInAnnotation() {
try (Database db = db()) {
db.select(Person.class);
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Test
public void testSelectTransacted() {
System.out.println("testSelectTransacted");
db() //
.select("select score from person where name=?") //
.parameters("FRED", "JOSEPH") //
.transacted() //
.getAs(Integer.class) //
.doOnNext(tx -> System.out.println(tx.isComplete() ? "complete" : tx.value())) //
.test() //
.awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) //
.assertValueCount(3) //
.assertComplete();
}
#location 6
#vulnerability type RESOURCE_LEAK | #fixed code
@Test
public void testSelectTransacted() {
try (Database db = db()) {
db //
.select("select score from person where name=?") //
.parameters("FRED", "JOSEPH") //
.transacted() //
.getAs(Integer.class) //
.doOnNext(tx -> System.out.println(tx.isComplete() ? "complete" : tx.value())) //
.test() //
.awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) //
.assertValueCount(3) //
.assertComplete();
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Test
public void testUpdateAllWithParameterFourRuns() {
db().update("update person set score=?") //
.parameters(1, 2, 3, 4) //
.counts() //
.test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) //
.assertValues(3, 3, 3, 3) //
.assertComplete();
}
#location 4
#vulnerability type RESOURCE_LEAK | #fixed code
@Test
public void testUpdateAllWithParameterFourRuns() {
try (Database db = db()) {
db.update("update person set score=?") //
.parameters(1, 2, 3, 4) //
.counts() //
.test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) //
.assertValues(3, 3, 3, 3) //
.assertComplete();
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Test
public void 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 | #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();
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Test
public void testAutoMapToInterfaceWithExplicitColumnName() {
db() //
.select("select name, score from person order by name") //
.autoMap(Person3.class) //
.firstOrError() //
.map(Person3::examScore) //
.test() //
.awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) //
.assertValue(21) //
.assertComplete();
}
#location 5
#vulnerability type RESOURCE_LEAK | #fixed code
@Test
public void testAutoMapToInterfaceWithExplicitColumnName() {
try (Database db = db()) {
db //
.select("select name, score from person order by name") //
.autoMap(Person3.class) //
.firstOrError() //
.map(Person3::examScore) //
.test() //
.awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) //
.assertValue(21) //
.assertComplete();
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Test
public void 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 | #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());
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Test
public void testSelectDependsOnCompletable() {
Database db = db();
Completable a = db.update("update person set score=100 where name=?") //
.parameter("FRED") //
.counts().ignoreElements();
db.select("select score from person where name=?") //
.parameter("FRED") //
.dependsOn(a) //
.getAs(Integer.class)//
.test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) //
.assertValues(100) //
.assertComplete();
}
#location 5
#vulnerability type RESOURCE_LEAK | #fixed code
@Test
public void testSelectDependsOnCompletable() {
try (Database db = db()) {
Completable a = db.update("update person set score=100 where name=?") //
.parameter("FRED") //
.counts().ignoreElements();
db.select("select score from person where name=?") //
.parameter("FRED") //
.dependsOn(a) //
.getAs(Integer.class)//
.test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) //
.assertValues(100) //
.assertComplete();
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Test
public void testFewerColumnsMappedThanAvailable() {
db().select("select name, score from person where name='FRED'") //
.getAs(String.class) //
.test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) //
.assertValues("FRED") //
.assertComplete();
}
#location 4
#vulnerability type RESOURCE_LEAK | #fixed code
@Test
public void testFewerColumnsMappedThanAvailable() {
try (Database db = db()) {
db.select("select name, score from person where name='FRED'") //
.getAs(String.class) //
.test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) //
.assertValues("FRED") //
.assertComplete();
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Test
public void testTuple4() {
db() //
.select("select name, score, name, score from person order by name") //
.getAs(String.class, Integer.class, String.class, Integer.class) //
.firstOrError() //
.test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) //
.assertComplete() //
.assertValue(Tuple4.create("FRED", 21, "FRED", 21)); //
}
#location 5
#vulnerability type RESOURCE_LEAK | #fixed code
@Test
public void testTuple4() {
try (Database db = db()) {
db //
.select("select name, score, name, score from person order by name") //
.getAs(String.class, Integer.class, String.class, Integer.class) //
.firstOrError() //
.test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) //
.assertComplete() //
.assertValue(Tuple4.create("FRED", 21, "FRED", 21)); //
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
public static Database test(int maxPoolSize) {
return Database.from(new NonBlockingConnectionPool(testConnectionProvider(), maxPoolSize, 1000));
}
#location 2
#vulnerability type RESOURCE_LEAK | #fixed code
public static Database test(int maxPoolSize) {
return Database.from( //
Pools.nonBlocking() //
.connectionProvider(testConnectionProvider()) //
.maxPoolSize(maxPoolSize) //
.build());
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Test
public void testAutoMapToInterfaceWithIndex() {
db() //
.select("select name, score from person order by name") //
.autoMap(Person5.class) //
.firstOrError() //
.map(Person5::examScore) //
.test() //
.awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) //
.assertValue(21) //
.assertComplete();
}
#location 5
#vulnerability type RESOURCE_LEAK | #fixed code
@Test
public void testAutoMapToInterfaceWithIndex() {
try (Database db = db()) {
db //
.select("select name, score from person order by name") //
.autoMap(Person5.class) //
.firstOrError() //
.map(Person5::examScore) //
.test() //
.awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) //
.assertValue(21) //
.assertComplete();
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Test
public void testUpdateWithParameterTwoRuns() {
db().update("update person set score=20 where name=?") //
.parameters("FRED", "JOSEPH").counts() //
.test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) //
.assertValues(1, 1) //
.assertComplete();
}
#location 4
#vulnerability type RESOURCE_LEAK | #fixed code
@Test
public void testUpdateWithParameterTwoRuns() {
try (Database db = db()) {
db.update("update person set score=20 where name=?") //
.parameters("FRED", "JOSEPH").counts() //
.test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) //
.assertValues(1, 1) //
.assertComplete();
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Test
@Ignore
// TODO fix test
public void testMaxIdleTime() throws InterruptedException {
TestScheduler s = new TestScheduler();
AtomicInteger count = new AtomicInteger();
AtomicInteger disposed = new AtomicInteger();
MemberFactory2<Integer, NonBlockingPool2<Integer>> memberFactory = pool -> new NonBlockingMember2<Integer>(pool,
null);
Pool2<Integer> pool = NonBlockingPool2.factory(() -> count.incrementAndGet()) //
.healthy(n -> true) //
.disposer(n -> {
}) //
.maxSize(3) //
.maxIdleTime(1, TimeUnit.MINUTES) //
.returnToPoolDelayAfterHealthCheckFailure(1, TimeUnit.SECONDS) //
.disposer(n -> disposed.incrementAndGet()) //
.memberFactory(memberFactory) //
.scheduler(s) //
.build();
TestSubscriber<Member2<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());
}
#location 22
#vulnerability type RESOURCE_LEAK | #fixed code
@Test
@Ignore
// TODO fix test
public void testMaxIdleTime() throws InterruptedException {
TestScheduler s = new TestScheduler();
AtomicInteger count = new AtomicInteger();
AtomicInteger disposed = new AtomicInteger();
MemberFactory<Integer, NonBlockingPool<Integer>> memberFactory = pool -> new NonBlockingMember<Integer>(pool,
null);
Pool<Integer> pool = NonBlockingPool.factory(() -> count.incrementAndGet()) //
.healthy(n -> true) //
.disposer(n -> {
}) //
.maxSize(3) //
.maxIdleTime(1, TimeUnit.MINUTES) //
.returnToPoolDelayAfterHealthCheckFailure(1, TimeUnit.SECONDS) //
.disposer(n -> disposed.incrementAndGet()) //
.memberFactory(memberFactory) //
.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());
} | Below is the vulnerable code, please generate the patch based on the following information. |
#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 | #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();
} | Below is the vulnerable code, please generate the patch based on the following information. |
#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 | #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();
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#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 | #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();
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
private void testHealthCheck(Predicate<Connection> healthy) throws InterruptedException {
TestScheduler scheduler = new TestScheduler();
NonBlockingConnectionPool pool = Pools //
.nonBlocking() //
.connectionProvider(DatabaseCreator.connectionProvider()) //
.maxIdleTime(10, TimeUnit.MINUTES) //
.idleTimeBeforeHealthCheck(0, TimeUnit.MINUTES) //
.healthy(healthy) //
.returnToPoolDelayAfterHealthCheckFailure(1, TimeUnit.MINUTES) //
.scheduler(scheduler) //
.maxPoolSize(1) //
.build();
try (Database db = Database.from(pool)) {
TestSubscriber<Integer> ts0 = db.select( //
"select score from person where name=?") //
.parameter("FRED") //
.getAs(Integer.class) //
.test();
ts0.assertValueCount(0) //
.assertNotComplete();
scheduler.advanceTimeBy(1, TimeUnit.MINUTES);
ts0.assertValueCount(1) //
.assertComplete();
TestSubscriber<Integer> ts = db.select( //
"select score from person where name=?") //
.parameter("FRED") //
.getAs(Integer.class) //
.test() //
.assertValueCount(0);
System.out.println("done2");
scheduler.advanceTimeBy(1, TimeUnit.MINUTES);
Thread.sleep(200);
ts.assertValueCount(1);
Thread.sleep(200);
ts.assertValue(21) //
.assertComplete();
}
}
#location 15
#vulnerability type RESOURCE_LEAK | #fixed code
private void testHealthCheck(Predicate<Connection> healthy) throws InterruptedException {
TestScheduler scheduler = new TestScheduler();
NonBlockingConnectionPool2 pool = Pools //
.nonBlocking() //
.connectionProvider(DatabaseCreator.connectionProvider()) //
.maxIdleTime(10, TimeUnit.MINUTES) //
.idleTimeBeforeHealthCheck(0, TimeUnit.MINUTES) //
.healthy(healthy) //
.returnToPoolDelayAfterHealthCheckFailure(1, TimeUnit.MINUTES) //
.scheduler(scheduler) //
.maxPoolSize(1) //
.build();
try (Database db = Database.from(pool)) {
TestSubscriber<Integer> ts0 = db.select( //
"select score from person where name=?") //
.parameter("FRED") //
.getAs(Integer.class) //
.test();
ts0.assertValueCount(0) //
.assertNotComplete();
scheduler.advanceTimeBy(1, TimeUnit.MINUTES);
ts0.assertValueCount(1) //
.assertComplete();
TestSubscriber<Integer> ts = db.select( //
"select score from person where name=?") //
.parameter("FRED") //
.getAs(Integer.class) //
.test() //
.assertValueCount(0);
System.out.println("done2");
scheduler.advanceTimeBy(1, TimeUnit.MINUTES);
Thread.sleep(200);
ts.assertValueCount(1);
Thread.sleep(200);
ts.assertValue(21) //
.assertComplete();
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#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 | #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());
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Test
public void testUpdateClobWithReader() throws FileNotFoundException {
Database db = db();
Reader reader = new FileReader(new File("src/test/resources/big.txt"));
insertNullClob(db);
db //
.update("update person_clob set document = :doc") //
.parameter("doc", reader) //
.counts() //
.test() //
.awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) //
.assertValue(1) //
.assertComplete();
}
#location 9
#vulnerability type RESOURCE_LEAK | #fixed code
@Test
public void testUpdateClobWithReader() throws FileNotFoundException {
try (Database db = db()) {
Reader reader = new FileReader(new File("src/test/resources/big.txt"));
insertNullClob(db);
db //
.update("update person_clob set document = :doc") //
.parameter("doc", reader) //
.counts() //
.test() //
.awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) //
.assertValue(1) //
.assertComplete();
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Test
public void testUpdateClobWithNull() {
Database db = db();
insertNullClob(db);
db //
.update("update person_clob set document = :doc") //
.parameter("doc", Database.NULL_CLOB) //
.counts() //
.test() //
.awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) //
.assertValue(1) //
.assertComplete();
}
#location 8
#vulnerability type RESOURCE_LEAK | #fixed code
@Test
public void testUpdateClobWithNull() {
try (Database db = db()) {
insertNullClob(db);
db //
.update("update person_clob set document = :doc") //
.parameter("doc", Database.NULL_CLOB) //
.counts() //
.test() //
.awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) //
.assertValue(1) //
.assertComplete();
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Test
public void testInsertBlobAndReadBlobAsInputStream() {
Database db = db();
byte[] bytes = "some text here".getBytes();
db.update("insert into person_blob(name,document) values(?,?)") //
.parameters("FRED", new ByteArrayInputStream(bytes)) //
.counts() //
.test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) //
.assertValue(1) //
.assertComplete();
db.select("select document from person_blob where name='FRED'") //
.getAs(InputStream.class) //
.map(is -> read(is)) //
.map(b -> new String(b)) //
.test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) //
.assertValue("some text here") //
.assertComplete();
}
#location 12
#vulnerability type RESOURCE_LEAK | #fixed code
@Test
public void testInsertBlobAndReadBlobAsInputStream() {
try (Database db = db()) {
byte[] bytes = "some text here".getBytes();
db.update("insert into person_blob(name,document) values(?,?)") //
.parameters("FRED", new ByteArrayInputStream(bytes)) //
.counts() //
.test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) //
.assertValue(1) //
.assertComplete();
db.select("select document from person_blob where name='FRED'") //
.getAs(InputStream.class) //
.map(is -> read(is)) //
.map(b -> new String(b)) //
.test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) //
.assertValue("some text here") //
.assertComplete();
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Test
public void testUpdateWithBatchSize3GreaterThanNumRecords() {
db().update("update person set score=?") //
.batchSize(3) //
.parameters(1, 2, 3, 4) //
.counts() //
.test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) //
.assertValues(3, 3, 3, 3) //
.assertComplete();
}
#location 5
#vulnerability type RESOURCE_LEAK | #fixed code
@Test
public void testUpdateWithBatchSize3GreaterThanNumRecords() {
try (Database db = db()) {
db.update("update person set score=?") //
.batchSize(3) //
.parameters(1, 2, 3, 4) //
.counts() //
.test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) //
.assertValues(3, 3, 3, 3) //
.assertComplete();
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Test
public void testTuple3() {
db() //
.select("select name, score, name from person order by name") //
.getAs(String.class, Integer.class, String.class) //
.firstOrError() //
.test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) //
.assertComplete() //
.assertValue(Tuple3.create("FRED", 21, "FRED")); //
}
#location 5
#vulnerability type RESOURCE_LEAK | #fixed code
@Test
public void testTuple3() {
try (Database db = db()) {
db //
.select("select name, score, name from person order by name") //
.getAs(String.class, Integer.class, String.class) //
.firstOrError() //
.test().awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) //
.assertComplete() //
.assertValue(Tuple3.create("FRED", 21, "FRED")); //
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Test
public void testAutoMapToInterfaceWithIndexTooLarge() {
db() //
.select("select name, score from person order by name") //
.autoMap(Person6.class) //
.firstOrError() //
.map(Person6::examScore) //
.test() //
.awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) //
.assertNoValues() //
.assertError(ColumnIndexOutOfRangeException.class);
}
#location 5
#vulnerability type RESOURCE_LEAK | #fixed code
@Test
public void testAutoMapToInterfaceWithIndexTooLarge() {
try (Database db = db()) {
db //
.select("select name, score from person order by name") //
.autoMap(Person6.class) //
.firstOrError() //
.map(Person6::examScore) //
.test() //
.awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) //
.assertNoValues() //
.assertError(ColumnIndexOutOfRangeException.class);
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Test
public void 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 | #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();
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#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 | #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());
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Test
public void testUpdateBlobWithNull() {
Database db = db();
insertPersonBlob(db);
db //
.update("update person_blob set document = :doc") //
.parameter("doc", Database.NULL_BLOB) //
.counts() //
.test() //
.awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) //
.assertValue(1) //
.assertComplete();
}
#location 8
#vulnerability type RESOURCE_LEAK | #fixed code
@Test
public void testUpdateBlobWithNull() {
try (Database db = db()) {
insertPersonBlob(db);
db //
.update("update person_blob set document = :doc") //
.parameter("doc", Database.NULL_BLOB) //
.counts() //
.test() //
.awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) //
.assertValue(1) //
.assertComplete();
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Test
public void 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 | #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();
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#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 | #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());
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#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 | #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);
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#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 | #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)); //
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.