output
stringlengths
64
73.2k
input
stringlengths
208
73.3k
instruction
stringclasses
1 value
#fixed code public void run() throws IOException { LOG.info("Data Deployer Daemon for ring group " + ringGroupName + " starting."); boolean claimedDataDeployer = false; try { ringGroup = coord.getRingGroup(ringGroupName); // attempt to claim the data deployer title if (ringGroup.claimDataDeployer()) { claimedDataDeployer = true; // we are now *the* data deployer 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 goingDown = false; try { while (!goingDown) { // take a snapshot of the current ring/domain group configs, since // they might get changed while we're processing the current update. RingGroup snapshotRingGroup; DomainGroup snapshotDomainGroup; synchronized (lock) { snapshotRingGroup = ringGroup; snapshotDomainGroup = domainGroup; } processUpdates(snapshotRingGroup, snapshotDomainGroup); Thread.sleep(config.getSleepInterval()); } } catch (InterruptedException e) { // daemon is going down. } } else { LOG.info("Attempted to claim data deployer status, but there was already a lock in place!"); } } catch (Throwable t) { LOG.fatal("unexpected exception!", t); } finally { if (claimedDataDeployer) { ringGroup.releaseDataDeployer(); } } LOG.info("Data Deployer Daemon for ring group " + ringGroupName + " shutting down."); }
#vulnerable code public void run() throws IOException { LOG.info("Data Deployer Daemon for ring group " + ringGroupName + " starting."); boolean claimedDataDeployer = false; try { ringGroupConfig = coord.getRingGroup(ringGroupName); // attempt to claim the data deployer title if (ringGroupConfig.claimDataDeployer()) { claimedDataDeployer = true; // we are now *the* data deployer for this ring group. domainGroup = ringGroupConfig.getDomainGroup(); // set a watch on the ring group ringGroupConfig.setListener(this); // set a watch on the domain group version domainGroup.setListener(this); // loop until we're taken down goingDown = false; try { while (!goingDown) { // take a snapshot of the current ring/domain group configs, since // they might get changed while we're processing the current update. RingGroup snapshotRingGroupConfig; DomainGroup snapshotDomainGroup; synchronized (lock) { snapshotRingGroupConfig = ringGroupConfig; snapshotDomainGroup = domainGroup; } processUpdates(snapshotRingGroupConfig, snapshotDomainGroup); Thread.sleep(config.getSleepInterval()); } } catch (InterruptedException e) { // daemon is going down. } } else { LOG.info("Attempted to claim data deployer status, but there was already a lock in place!"); } } catch (Throwable t) { LOG.fatal("unexpected exception!", t); } finally { if (claimedDataDeployer) { ringGroupConfig.releaseDataDeployer(); } } LOG.info("Data Deployer Daemon for ring group " + ringGroupName + " shutting down."); } #location 5 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public void getBulk(int domainId, List<ByteBuffer> keys, HostConnectionGetBulkCallback resultHandler) { try { client.getBulk(domainId, keys, resultHandler); } catch (TException e) { resultHandler.onError(e); } }
#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
Below is the vulnerable code, please generate the patch based on the following information.
#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(); }
#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
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public void get(int domainId, ByteBuffer key, HostConnectionGetCallback resultHandler) { try { client.get(domainId, key, resultHandler); } catch (TException e) { resultHandler.onError(e); } }
#vulnerable code public void get(int domainId, ByteBuffer key, HostConnectionGetCallback resultHandler) throws TException { client.get(domainId, key, resultHandler); } #location 2 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#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); }
#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 10 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public void addTask(GetTask task) { try { // TODO: remove trace //LOG.trace("Adding task with state " + task.state); if (task.startNanoTime == null) { task.startNanoTime = System.nanoTime(); } getTasks.put(task); //LOG.trace("Get Task is now " + getTasks.size()); } catch (InterruptedException e) { // Someone is trying to stop Dispatcher } }
#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
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public void run() throws IOException { hostConfig.setState(HostState.IDLE); processCommands(); while (!goingDown) { try { Thread.sleep(1000); } catch (InterruptedException e) { LOG.debug("Interrupted in run loop. Exiting."); break; } } hostConfig.setState(HostState.OFFLINE); }
#vulnerable code public void run() throws IOException { hostConfig.setState(HostState.IDLE); if (hostConfig.getCurrentCommand() != null) { processCurrentCommand(hostConfig, hostConfig.getCurrentCommand()); } while (!goingDown) { try { Thread.sleep(1000); } catch (InterruptedException e) { LOG.debug("Interrupted in run loop. Exiting."); break; } } hostConfig.setState(HostState.OFFLINE); } #location 5 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code protected void commitFiles(File sourceRoot, String destinationRoot) throws IOException { File[] files = sourceRoot.listFiles(); if (files == null) { throw new IOException("Failed to commit files from " + sourceRoot + " to " + destinationRoot + " since source is not a valid directory."); } for (File file : files) { // Skip non files if (!file.isFile()) { continue; } File targetFile = new File(destinationRoot + "/" + file.getName()); // If target file already exists, delete it if (targetFile.exists()) { if (!targetFile.delete()) { throw new IOException("Failed to overwrite file in destination root: " + targetFile.getAbsolutePath()); } } // Move file to destination if (!file.renameTo(targetFile)) { LOG.info("Committing " + file.getAbsolutePath() + " to " + targetFile.getAbsolutePath()); throw new IOException("Failed to rename source file: " + file.getAbsolutePath() + " to destination file: " + targetFile.getAbsolutePath()); } } }
#vulnerable code protected void commitFiles(File sourceRoot, String destinationRoot) throws IOException { for (File file : sourceRoot.listFiles()) { // Skip non files if (!file.isFile()) { continue; } File targetFile = new File(destinationRoot + "/" + file.getName()); // If target file already exists, delete it if (targetFile.exists()) { if (!targetFile.delete()) { throw new IOException("Failed to overwrite file in destination root: " + targetFile.getAbsolutePath()); } } // Move file to destination if (!file.renameTo(targetFile)) { LOG.info("Committing " + file.getAbsolutePath() + " to " + targetFile.getAbsolutePath()); throw new IOException("Failed to rename source file: " + file.getAbsolutePath() + " to destination file: " + targetFile.getAbsolutePath()); } } } #location 2 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Override public Ring addRing(int ringNum) throws IOException { try { Ring rc = ZkRing.create(zk, ringGroupPath, ringNum, this, isUpdating() ? getUpdatingToVersion() : getCurrentVersion()); ringsByNumber.put(rc.getRingNumber(), rc); return rc; } catch (Exception e) { throw new IOException(e); } }
#vulnerable code @Override public Ring addRing(int ringNum) throws IOException { try { Ring rc = ZkRing.create(zk, ringGroupPath, ringNum, this, isUpdating() ? getUpdatingToVersion() : getCurrentVersion()); ringsByNumber.put(rc.getRingNumber(), rc); return rc; } catch (Exception e) { throw new IOException(e); } } #location 4 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public static DomainGroupVersion createNewFastForwardVersion(DomainGroup domainGroup) throws IOException { Map<Domain, Integer> domainNameToVersion = new HashMap<Domain, Integer>(); // find the latest domain group version DomainGroupVersion dgv = DomainGroups.getLatestVersion(domainGroup); if (dgv == null) { throw new IllegalArgumentException( "Supplied domain group must have at least one version, but it did not: " + domainGroup); } // create map of new domains and versions for (DomainGroupVersionDomainVersion dgvdv : dgv.getDomainVersions()) { domainNameToVersion.put(dgvdv.getDomain(), Domains.getLatestVersionNotOpenNotDefunct(dgvdv.getDomain()).getVersionNumber()); } // call regular version creation method return domainGroup.createNewVersion(domainNameToVersion); }
#vulnerable code public static DomainGroupVersion createNewFastForwardVersion(DomainGroup domainGroup) throws IOException { Map<Domain, Integer> domainNameToVersion = new HashMap<Domain, Integer>(); // find the latest domain group version DomainGroupVersion dgv = DomainGroups.getLatestVersion(domainGroup); // create map of new domains and versions for (DomainGroupVersionDomainVersion dgvdv : dgv.getDomainVersions()) { domainNameToVersion.put(dgvdv.getDomain(), Domains.getLatestVersionNotOpenNotDefunct(dgvdv.getDomain()).getVersionNumber()); } // call regular version creation method return domainGroup.createNewVersion(domainNameToVersion); } #location 8 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public void get(int domainId, ByteBuffer key, HostConnectionGetCallback resultHandler) { try { client.get(domainId, key, resultHandler); } catch (TException e) { resultHandler.onError(e); } }
#vulnerable code public void get(int domainId, ByteBuffer key, HostConnectionGetCallback resultHandler) throws TException { client.get(domainId, key, resultHandler); } #location 2 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#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; // 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/domain group configs, since // they 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 if (snapshotRingGroup.getRingGroupConductorMode() == RingGroupConductorMode.ACTIVE) { 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 { if (claimedRingGroupConductor) { ringGroup.releaseRingGroupConductor(); claimedRingGroupConductor = false; } } LOG.info("Ring Group Conductor for ring group " + ringGroupName + " shutting down."); // Remove shutdown hook. We don't need it anymore removeShutdownHook(); }
#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/domain group configs, since // they might get changed while we're processing the current update. RingGroup snapshotRingGroup; DomainGroup snapshotDomainGroup; synchronized (lock) { snapshotRingGroup = ringGroup; snapshotDomainGroup = domainGroup; } // Only process updates if ring group conductor is configured to be active if (snapshotRingGroup.getRingGroupConductorMode() == RingGroupConductorMode.ACTIVE) { processUpdates(snapshotRingGroup, snapshotDomainGroup); } 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 { if (claimedRingGroupConductor) { ringGroup.releaseRingGroupConductor(); claimedRingGroupConductor = false; } } LOG.info("Ring Group Conductor for ring group " + ringGroupName + " shutting down."); // Remove shutdown hook. We don't need it anymore removeShutdownHook(); } #location 32 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#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); } }
#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 10 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code private void sendEmails(Set<String> emailTargets, String body) throws IOException, InterruptedException { LOG.info("Sending Monitor email to " + emailTargets.size() + " targets: " + emailTargets + " Email body: " + body); for (String emailTarget : emailTargets) { String[] command = {"/bin/mail", "-s", "Hank-Notification", emailTarget}; Process process = Runtime.getRuntime().exec(command); OutputStreamWriter writer = new OutputStreamWriter(process.getOutputStream()); writer.write(body); writer.close(); process.getOutputStream().close(); process.waitFor(); } }
#vulnerable code private void sendEmails(Set<String> emailTargets, String body) throws IOException { File temporaryEmailBody = File.createTempFile("_tmp_" + getClass().getSimpleName(), null); BufferedWriter writer = new BufferedWriter(new FileWriter(temporaryEmailBody, false)); writer.write(body); LOG.info("Sending Monitor email to " + emailTargets.size() + " targets: " + emailTargets + " Email body: " + body); for (String emailTarget : emailTargets) { Runtime.getRuntime().exec("cat " + temporaryEmailBody.getAbsolutePath() + " | mail -s 'Hank Notification' " + emailTarget); } if (!temporaryEmailBody.delete()) { throw new IOException("Could not delete " + temporaryEmailBody.getAbsolutePath()); } } #location 9 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#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(); }
#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
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Override public void copyToLocalRoot(String remoteSourceRelativePath, String localDestinationRoot) throws IOException { Path source = new Path(getAbsoluteRemotePath(remoteSourceRelativePath)); File destination = new File(localDestinationRoot + "/" + new Path(remoteSourceRelativePath).getName()); LOG.info("Copying remote file " + source + " to local file " + destination); InputStream inputStream = getInputStream(remoteSourceRelativePath); FileOutputStream fileOutputStream = new FileOutputStream(destination); try { IOStreamUtils.copy(inputStream, fileOutputStream); fileOutputStream.flush(); } finally { inputStream.close(); fileOutputStream.close(); } }
#vulnerable code @Override public void copyToLocalRoot(String remoteSourceRelativePath, String localDestinationRoot) throws IOException { Path source = new Path(getAbsoluteRemotePath(remoteSourceRelativePath)); File destination = new File(localDestinationRoot + "/" + new Path(remoteSourceRelativePath).getName()); LOG.info("Copying remote file " + source + " to local file " + destination); InputStream inputStream = getInputStream(remoteSourceRelativePath); FileOutputStream fileOutputStream = new FileOutputStream(destination); BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(fileOutputStream); // Use copyLarge (over 2GB) try { IOUtils.copyLarge(inputStream, bufferedOutputStream); bufferedOutputStream.flush(); fileOutputStream.flush(); } finally { inputStream.close(); bufferedOutputStream.close(); fileOutputStream.close(); } } #location 18 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public void stop() { stopping = true; }
#vulnerable code public void stop() { goingDown = true; } #location 2 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code Host getHost() { return host; }
#vulnerable code boolean isAvailable() { return state != HostConnectionState.STANDBY; } #location 2 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public void testBlockCompressionSnappy() throws Exception { doTestBlockCompression(BlockCompressionCodec.SNAPPY, EXPECTED_RECORD_FILE_BLOCK_COMPRESSED_SNAPPY); }
#vulnerable code public void testBlockCompressionSnappy() throws Exception { new File(TMP_TEST_CURLY_READER).mkdirs(); OutputStream s = new FileOutputStream(TMP_TEST_CURLY_READER + "/00000.base.curly"); s.write(EXPECTED_RECORD_FILE_BLOCK_COMPRESSED_SNAPPY); s.flush(); s.close(); MapReader keyfileReader = new MapReader(0, KEY1.array(), new byte[]{0, 0, 0, 0, 0}, KEY2.array(), new byte[]{0, 0, 0, 5, 0}, KEY3.array(), new byte[]{0, 0, 0, 10, 0} ); CurlyReader reader = new CurlyReader(CurlyReader.getLatestBase(TMP_TEST_CURLY_READER), 1024, keyfileReader, -1, BlockCompressionCodec.SNAPPY, 3, 2, true); ReaderResult result = new ReaderResult(); reader.get(KEY1, result); assertTrue(result.isFound()); assertEquals(VALUE1, result.getBuffer()); result.clear(); reader.get(KEY4, result); assertFalse(result.isFound()); result.clear(); reader.get(KEY3, result); assertTrue(result.isFound()); assertEquals(VALUE3, result.getBuffer()); result.clear(); reader.get(KEY2, result); assertTrue(result.isFound()); assertEquals(VALUE2, result.getBuffer()); result.clear(); } #location 14 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Override public boolean isDeletable() throws IOException { Boolean result; if (deletable != null) { result = deletable.get(); } else { try { result = WatchedBoolean.get(zk, ZkPath.append(path, DELETABLE_PATH_SEGMENT)); } catch (Exception e) { throw new IOException(e); } } if (result == null) { return false; } else { return result; } }
#vulnerable code @Override public boolean isDeletable() throws IOException { if (deletable != null) { return deletable.get(); } else { try { return WatchedBoolean.get(zk, ZkPath.append(path, DELETABLE_PATH_SEGMENT)); } catch (Exception e) { throw new IOException(e); } } } #location 7 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code Host getHost() { return host; }
#vulnerable code boolean isAvailable() { return state != HostConnectionState.STANDBY; } #location 2 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public void run() throws IOException, InterruptedException { // Add shutdown hook addShutdownHook(); // Initialize and process commands setStateSynchronized(HostState.IDLE); // In case of exception, server will stop and state will be coherent. // Wait for state to propagate while (host.getState() != HostState.IDLE) { LOG.info("Waiting for Host state " + HostState.IDLE + " to propagate."); Thread.sleep(100); } processCommandOnStartup(); while (!stopping) { try { HostCommand command = commandQueue.poll(MAIN_THREAD_STEP_SLEEP_MS, TimeUnit.MILLISECONDS); if (command != null) { try { processCommand(command, host.getState()); } catch (IOException e) { LOG.error("Failed to process command: " + command, e); break; } } } catch (InterruptedException e) { LOG.info("Interrupted in main loop. Exiting.", e); break; } } // Shuting down LOG.info("Partition server main thread is stopping."); // Stop serving data stopServingData(); // Stop updating if necessary stopUpdating(); // Signal OFFLINE setStateSynchronized(HostState.OFFLINE); // In case of exception, server will stop and state will be coherent. // Remove shutdown hook. We don't need it anymore as we just set the host state to OFFLINE removeShutdownHook(); }
#vulnerable code public void run() throws IOException, InterruptedException { // Add shutdown hook addShutdownHook(); // Initialize and process commands setStateSynchronized(HostState.IDLE); // In case of exception, server will stop and state will be coherent. // Wait for state to propagate while (host.getState() != HostState.IDLE) { LOG.info("Waiting for Host state " + HostState.IDLE + " to propagate."); Thread.sleep(100); } processCommandOnStartup(); while (!stopping) { try { Thread.sleep(MAIN_THREAD_STEP_SLEEP_MS); } catch (InterruptedException e) { LOG.info("Interrupted in run loop. Exiting.", e); break; } } // Shuting down LOG.info("Partition server main thread is stopping."); // Stop serving data stopServingData(); // Stop updating if necessary if (updateThread != null) { LOG.info("Update thread is still running. Interrupting and waiting for it to finish..."); updateThread.interrupt(); updateThread.join(); // In case of interrupt exception, server will stop and state will be coherent. } setStateSynchronized(HostState.OFFLINE); // In case of exception, server will stop and state will be coherent. // Remove shutdown hook. We don't need it anymore as we just set the host state to OFFLINE removeShutdownHook(); } #location 28 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public void run() throws IOException { LOG.info("Ring Group Conductor Daemon for ring group " + ringGroupName + " starting."); boolean claimedRingGroupConductor = false; try { ringGroup = coordinator.getRingGroup(ringGroupName); // attempt to claim the ring group conductor title if (ringGroup.claimRingGroupConductor()) { 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/domain group configs, since // they might get changed while we're processing the current update. RingGroup snapshotRingGroup; DomainGroup snapshotDomainGroup; synchronized (lock) { snapshotRingGroup = ringGroup; snapshotDomainGroup = domainGroup; } processUpdates(snapshotRingGroup, snapshotDomainGroup); 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 { if (claimedRingGroupConductor) { ringGroup.releaseRingGroupConductor(); } } LOG.info("Ring Group Conductor Daemon for ring group " + ringGroupName + " shutting down."); }
#vulnerable code public void run() throws IOException { LOG.info("Ring Group Conductor Daemon for ring group " + ringGroupName + " starting."); boolean claimedRingGroupConductor = false; try { ringGroup = coordinator.getRingGroup(ringGroupName); // attempt to claim the ring group conductor title if (ringGroup.claimRingGroupConductor()) { 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 goingDown = false; try { while (!goingDown) { // take a snapshot of the current ring/domain group configs, since // they might get changed while we're processing the current update. RingGroup snapshotRingGroup; DomainGroup snapshotDomainGroup; synchronized (lock) { snapshotRingGroup = ringGroup; snapshotDomainGroup = domainGroup; } processUpdates(snapshotRingGroup, snapshotDomainGroup); 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 { if (claimedRingGroupConductor) { ringGroup.releaseRingGroupConductor(); } } LOG.info("Ring Group Conductor Daemon for ring group " + ringGroupName + " shutting down."); } #location 21 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#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(); }
#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 81 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#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; // 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(); }
#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 { if (claimedRingGroupConductor) { ringGroup.releaseRingGroupConductor(); claimedRingGroupConductor = false; } } LOG.info("Ring Group Conductor for ring group " + ringGroupName + " shutting down."); // Remove shutdown hook. We don't need it anymore removeShutdownHook(); } #location 49 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#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())); }
#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 15 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public void testBlockCompressionGzip() throws Exception { doTestBlockCompression(BlockCompressionCodec.GZIP, EXPECTED_RECORD_FILE_BLOCK_COMPRESSED_GZIP); }
#vulnerable code public void testBlockCompressionGzip() throws Exception { new File(TMP_TEST_CURLY_READER).mkdirs(); OutputStream s = new FileOutputStream(TMP_TEST_CURLY_READER + "/00000.base.curly"); s.write(EXPECTED_RECORD_FILE_BLOCK_COMPRESSED_GZIP); s.flush(); s.close(); MapReader keyfileReader = new MapReader(0, KEY1.array(), new byte[]{0, 0, 0, 0, 0}, KEY2.array(), new byte[]{0, 0, 0, 5, 0}, KEY3.array(), new byte[]{0, 0, 0, 10, 0} ); CurlyReader reader = new CurlyReader(CurlyReader.getLatestBase(TMP_TEST_CURLY_READER), 1024, keyfileReader, -1, BlockCompressionCodec.GZIP, 3, 2, true); ReaderResult result = new ReaderResult(); reader.get(KEY1, result); assertTrue(result.isFound()); assertEquals(VALUE1, result.getBuffer()); result.clear(); reader.get(KEY4, result); assertFalse(result.isFound()); result.clear(); reader.get(KEY3, result); assertTrue(result.isFound()); assertEquals(VALUE3, result.getBuffer()); result.clear(); reader.get(KEY2, result); assertTrue(result.isFound()); assertEquals(VALUE2, result.getBuffer()); result.clear(); } #location 37 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public static ZkRingGroup create(ZooKeeperPlus zk, String path, ZkDomainGroup domainGroup, Coordinator coordinator) throws KeeperException, InterruptedException, IOException { if (domainGroup.getVersions().isEmpty()) { throw new IllegalStateException( "You cannot create a ring group for a domain group that has no versions!"); } zk.create(path, domainGroup.getName().getBytes()); zk.create(ZkPath.append(path, CURRENT_VERSION_PATH_SEGMENT), null); zk.create(ZkPath.append(path, UPDATING_TO_VERSION_PATH_SEGMENT), (Integer.toString(DomainGroupUtils.getLatestVersion(domainGroup).getVersionNumber())).getBytes()); return new ZkRingGroup(zk, path, domainGroup, coordinator); }
#vulnerable code public static ZkRingGroup create(ZooKeeperPlus zk, String path, ZkDomainGroup domainGroup, Coordinator coordinator) throws KeeperException, InterruptedException, IOException { if (domainGroup.getVersions().isEmpty()) { throw new IllegalStateException( "You cannot create a ring group for a domain group that has no versions!"); } zk.create(path, domainGroup.getName().getBytes()); zk.create(ZkPath.append(path, CURRENT_VERSION_PATH_SEGMENT), null); zk.create(ZkPath.append(path, UPDATING_TO_VERSION_PATH_SEGMENT), (Integer.toString(domainGroup.getLatestVersion().getVersionNumber())).getBytes()); return new ZkRingGroup(zk, path, domainGroup, coordinator); } #location 9 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Override public void updateComplete() throws IOException { try { currentVersionNumber.set(getUpdatingToVersionNumber()); updatingToVersionNumber.set(null); } catch (Exception e) { throw new IOException(e); } }
#vulnerable code @Override public void updateComplete() throws IOException { try { if (zk.exists(ringPath + CURRENT_VERSION_PATH_SEGMENT, false) != null) { zk.setData(ringPath + CURRENT_VERSION_PATH_SEGMENT, getUpdatingToVersionNumber().toString().getBytes(), -1); } else { zk.create(ringPath + CURRENT_VERSION_PATH_SEGMENT, getUpdatingToVersionNumber().toString().getBytes(), Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT); } zk.delete(ringPath + UPDATING_TO_VERSION_PATH_SEGMENT, -1); } catch (Exception e) { throw new IOException(e); } } #location 7 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Override protected void runUpdateCore(DomainVersion currentVersion, DomainVersion updatingToVersion, IncrementalUpdatePlan updatePlan, String updateWorkRoot) throws IOException { // Prepare Curly // Determine files from versions CurlyFilePath curlyBasePath = getCurlyFilePathForVersion(updatePlan.getBase(), currentVersion, true); List<CurlyFilePath> curlyDeltas = new ArrayList<CurlyFilePath>(); for (DomainVersion curlyDeltaVersion : updatePlan.getDeltasOrdered()) { // Only add to the delta list if the version is not empty if (!isEmptyVersion(curlyDeltaVersion)) { curlyDeltas.add(getCurlyFilePathForVersion(curlyDeltaVersion, currentVersion, false)); } } // Check that all required files are available CueballPartitionUpdater.checkRequiredFileExists(curlyBasePath.getPath()); for (CurlyFilePath curlyDelta : curlyDeltas) { CueballPartitionUpdater.checkRequiredFileExists(curlyDelta.getPath()); } // Prepare Cueball // Determine files from versions CueballFilePath cueballBasePath = CueballPartitionUpdater.getCueballFilePathForVersion(updatePlan.getBase(), currentVersion, localPartitionRoot, localPartitionRootCache, true); List<CueballFilePath> cueballDeltas = new ArrayList<CueballFilePath>(); for (DomainVersion cueballDelta : updatePlan.getDeltasOrdered()) { // Only add to the delta list if the version is not empty if (!CueballPartitionUpdater.isEmptyVersion(cueballDelta, partitionRemoteFileOps)) { cueballDeltas.add(CueballPartitionUpdater.getCueballFilePathForVersion(cueballDelta, currentVersion, localPartitionRoot, localPartitionRootCache, false)); } } // Check that all required files are available CueballPartitionUpdater.checkRequiredFileExists(cueballBasePath.getPath()); for (CueballFilePath cueballDelta : cueballDeltas) { CueballPartitionUpdater.checkRequiredFileExists(cueballDelta.getPath()); } // Determine new Curly base path CurlyFilePath newCurlyBasePath = new CurlyFilePath(updateWorkRoot + "/" + Curly.getName(updatingToVersion.getVersionNumber(), true)); // Determine new Cueball base path CueballFilePath newCueballBasePath = new CueballFilePath(updateWorkRoot + "/" + Cueball.getName(updatingToVersion.getVersionNumber(), true)); OutputStream newCurlyBaseOutputStream = new FileOutputStream(newCurlyBasePath.getPath()); OutputStream newCueballBaseOutputStream = new FileOutputStream(newCueballBasePath.getPath()); // Note: the Curly writer used to perform the compaction must not hash the passed-in key because // it will directly receive key hashes. This is because the actual key is unknown when compacting. CurlyWriter curlyWriter = curlyWriterFactory.getCurlyWriter(newCueballBaseOutputStream, newCurlyBaseOutputStream); IKeyFileStreamBufferMergeSort cueballStreamBufferMergeSort = cueballStreamBufferMergeSortFactory.getInstance(cueballBasePath, cueballDeltas); merger.merge(curlyBasePath, curlyDeltas, cueballStreamBufferMergeSort, curlyWriter); }
#vulnerable code @Override protected void runUpdateCore(DomainVersion currentVersion, DomainVersion updatingToVersion, IncrementalUpdatePlan updatePlan, String updateWorkRoot) throws IOException { // Prepare Curly // Determine files from versions CurlyFilePath curlyBasePath = getCurlyFilePathForVersion(updatePlan.getBase(), currentVersion, true); List<CurlyFilePath> curlyDeltas = new ArrayList<CurlyFilePath>(); for (DomainVersion curlyDeltaVersion : updatePlan.getDeltasOrdered()) { // Only add to the delta list if the version is not empty if (!isEmptyVersion(curlyDeltaVersion)) { curlyDeltas.add(getCurlyFilePathForVersion(curlyDeltaVersion, currentVersion, false)); } } // Check that all required files are available CueballPartitionUpdater.checkRequiredFileExists(curlyBasePath.getPath()); for (CurlyFilePath curlyDelta : curlyDeltas) { CueballPartitionUpdater.checkRequiredFileExists(curlyDelta.getPath()); } // Prepare Cueball // Determine files from versions CueballFilePath cueballBasePath = CueballPartitionUpdater.getCueballFilePathForVersion(updatePlan.getBase(), currentVersion, localPartitionRoot, localPartitionRootCache, true); List<CueballFilePath> cueballDeltas = new ArrayList<CueballFilePath>(); for (DomainVersion cueballDelta : updatePlan.getDeltasOrdered()) { // Only add to the delta list if the version is not empty if (!CueballPartitionUpdater.isEmptyVersion(cueballDelta, partitionRemoteFileOps)) { cueballDeltas.add(CueballPartitionUpdater.getCueballFilePathForVersion(cueballDelta, currentVersion, localPartitionRoot, localPartitionRootCache, false)); } } // Check that all required files are available CueballPartitionUpdater.checkRequiredFileExists(cueballBasePath.getPath()); for (CueballFilePath cueballDelta : cueballDeltas) { CueballPartitionUpdater.checkRequiredFileExists(cueballDelta.getPath()); } // Determine new Curly base path CurlyFilePath newCurlyBasePath = new CurlyFilePath(updateWorkRoot + "/" + Curly.getName(updatingToVersion.getVersionNumber(), true)); // Determine new Cueball base path CueballFilePath newCueballBasePath = new CueballFilePath(updateWorkRoot + "/" + Cueball.getName(updatingToVersion.getVersionNumber(), true)); OutputStream newCurlyBaseOutputStream = new FileOutputStream(newCurlyBasePath.getPath()); OutputStream newCueballBaseOutputStream = new FileOutputStream(newCueballBasePath.getPath()); // Note: the Cueball writer used to perform the compaction must not hash the passed-in key because // it will directly receive key hashes. This is because the actual key is unknown when compacting. // TODO: Using an identity hasher and actually copying the bytes is unnecessary and inefficient. // TODO: (continued) Adding the logic of writing directly a hash could be added to Cueball. CueballWriter cueballWriter = new CueballWriter(newCueballBaseOutputStream, keyHashSize, new IdentityHasher(), offsetSize, compressionCodec, hashIndexBits); CurlyWriter curlyWriter = new CurlyWriter(newCurlyBaseOutputStream, cueballWriter, offsetSize); merger.merge(curlyBasePath, curlyDeltas, cueballBasePath, cueballDeltas, curlyWriter); } #location 65 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public void run() throws IOException, InterruptedException { // Add shutdown hook addShutdownHook(); // Initialize and process commands setStateSynchronized(HostState.IDLE); // In case of exception, server will stop and state will be coherent. // Wait for state to propagate while (host.getState() != HostState.IDLE) { LOG.info("Waiting for Host state " + HostState.IDLE + " to propagate."); Thread.sleep(100); } processCommandOnStartup(); while (!stopping) { try { HostCommand command = commandQueue.poll(MAIN_THREAD_STEP_SLEEP_MS, TimeUnit.MILLISECONDS); if (command != null) { try { processCommand(command, host.getState()); } catch (IOException e) { LOG.error("Failed to process command: " + command, e); break; } } } catch (InterruptedException e) { LOG.info("Interrupted in main loop. Exiting.", e); break; } } // Shuting down LOG.info("Partition server main thread is stopping."); // Stop serving data stopServingData(); // Stop updating if necessary stopUpdating(); // Signal OFFLINE setStateSynchronized(HostState.OFFLINE); // In case of exception, server will stop and state will be coherent. // Remove shutdown hook. We don't need it anymore as we just set the host state to OFFLINE removeShutdownHook(); }
#vulnerable code public void run() throws IOException, InterruptedException { // Add shutdown hook addShutdownHook(); // Initialize and process commands setStateSynchronized(HostState.IDLE); // In case of exception, server will stop and state will be coherent. // Wait for state to propagate while (host.getState() != HostState.IDLE) { LOG.info("Waiting for Host state " + HostState.IDLE + " to propagate."); Thread.sleep(100); } processCommandOnStartup(); while (!stopping) { try { Thread.sleep(MAIN_THREAD_STEP_SLEEP_MS); } catch (InterruptedException e) { LOG.info("Interrupted in run loop. Exiting.", e); break; } } // Shuting down LOG.info("Partition server main thread is stopping."); // Stop serving data stopServingData(); // Stop updating if necessary if (updateThread != null) { LOG.info("Update thread is still running. Interrupting and waiting for it to finish..."); updateThread.interrupt(); updateThread.join(); // In case of interrupt exception, server will stop and state will be coherent. } setStateSynchronized(HostState.OFFLINE); // In case of exception, server will stop and state will be coherent. // Remove shutdown hook. We don't need it anymore as we just set the host state to OFFLINE removeShutdownHook(); } #location 23 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#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); } }
#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 10 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code private Flow build(Properties cascasdingProperties, TapOrTapMap sources) throws IOException { pipe = new DomainBuilderAssembly(properties.getDomainName(), pipe, keyFieldName, valueFieldName); // Open new version and check for success openNewVersion(); Flow flow = null; try { // Build flow flow = getFlow(cascasdingProperties, sources); // Set up job DomainBuilderOutputCommitter.setupJob(properties.getDomainName(), flow.getJobConf()); // Complete flow flow.complete(); // Commit job DomainBuilderOutputCommitter.commitJob(properties.getDomainName(), flow.getJobConf()); } catch (Exception e) { String exceptionMessage = "Failed at building version " + domainVersion.getVersionNumber() + " of domain " + properties.getDomainName() + ". Cancelling version."; // In case of failure, cancel this new version cancelNewVersion(); // Clean up job if (flow != null) { DomainBuilderOutputCommitter.cleanupJob(properties.getDomainName(), flow.getJobConf()); } e.printStackTrace(); throw new IOException(exceptionMessage, e); } // Close the new version closeNewVersion(); // Clean up job DomainBuilderOutputCommitter.cleanupJob(properties.getDomainName(), flow.getJobConf()); return flow; }
#vulnerable code private Flow build(Properties cascasdingProperties, TapOrTapMap sources) throws IOException { pipe = new DomainBuilderAssembly(properties.getDomainName(), pipe, keyFieldName, valueFieldName); // Open new version and check for success openNewVersion(); Flow flow = null; try { // Build flow flow = getFlow(cascasdingProperties, sources); // Set up job DomainBuilderOutputCommitter.setupJob(properties.getDomainName(), flow.getJobConf()); // Complete flow flow.complete(); // Commit job DomainBuilderOutputCommitter.commitJob(properties.getDomainName(), flow.getJobConf()); } catch (Exception e) { // In case of failure, cancel this new version cancelNewVersion(); // Clean up job if (flow != null) { DomainBuilderOutputCommitter.cleanupJob(properties.getDomainName(), flow.getJobConf()); } e.printStackTrace(); throw new IOException("Failed at building version " + domainVersion.getVersionNumber() + " of domain " + properties.getDomainName() + ". Cancelling version.", e); } // Close the new version closeNewVersion(); // Clean up job DomainBuilderOutputCommitter.cleanupJob(properties.getDomainName(), flow.getJobConf()); return flow; } #location 32 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#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(); }
#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 70 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public void run() throws IOException { LOG.info("Ring Group Conductor Daemon for ring group " + ringGroupName + " starting."); boolean claimedRingGroupConductor = false; try { ringGroup = coordinator.getRingGroup(ringGroupName); // attempt to claim the ring group conductor title if (ringGroup.claimRingGroupConductor()) { 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/domain group configs, since // they might get changed while we're processing the current update. RingGroup snapshotRingGroup; DomainGroup snapshotDomainGroup; synchronized (lock) { snapshotRingGroup = ringGroup; snapshotDomainGroup = domainGroup; } processUpdates(snapshotRingGroup, snapshotDomainGroup); 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 { if (claimedRingGroupConductor) { ringGroup.releaseRingGroupConductor(); } } LOG.info("Ring Group Conductor Daemon for ring group " + ringGroupName + " shutting down."); }
#vulnerable code public void run() throws IOException { LOG.info("Ring Group Conductor Daemon for ring group " + ringGroupName + " starting."); boolean claimedRingGroupConductor = false; try { ringGroup = coordinator.getRingGroup(ringGroupName); // attempt to claim the ring group conductor title if (ringGroup.claimRingGroupConductor()) { 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 goingDown = false; try { while (!goingDown) { // take a snapshot of the current ring/domain group configs, since // they might get changed while we're processing the current update. RingGroup snapshotRingGroup; DomainGroup snapshotDomainGroup; synchronized (lock) { snapshotRingGroup = ringGroup; snapshotDomainGroup = domainGroup; } processUpdates(snapshotRingGroup, snapshotDomainGroup); 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 { if (claimedRingGroupConductor) { ringGroup.releaseRingGroupConductor(); } } LOG.info("Ring Group Conductor Daemon for ring group " + ringGroupName + " shutting down."); } #location 23 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Override public void updateComplete() throws IOException { try { currentVersionNumber.set(getUpdatingToVersionNumber()); updatingToVersionNumber.set(null); } catch (Exception e) { throw new IOException(e); } }
#vulnerable code @Override public void updateComplete() throws IOException { try { if (zk.exists(ringPath + CURRENT_VERSION_PATH_SEGMENT, false) != null) { zk.setData(ringPath + CURRENT_VERSION_PATH_SEGMENT, getUpdatingToVersionNumber().toString().getBytes(), -1); } else { zk.create(ringPath + CURRENT_VERSION_PATH_SEGMENT, getUpdatingToVersionNumber().toString().getBytes(), Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT); } zk.delete(ringPath + UPDATING_TO_VERSION_PATH_SEGMENT, -1); } catch (Exception e) { throw new IOException(e); } } #location 5 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#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(); }
#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
Below is the vulnerable code, please generate the patch based on the following information.
#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(); }
#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
Below is the vulnerable code, please generate the patch based on the following information.
#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(); }
#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
Below is the vulnerable code, please generate the patch based on the following information.
#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())); }
#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
Below is the vulnerable code, please generate the patch based on the following information.
#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); }
#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
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public void getBulk(int domainId, List<ByteBuffer> keys, HostConnectionGetBulkCallback resultHandler) { try { client.getBulk(domainId, keys, resultHandler); } catch (TException e) { resultHandler.onError(e); } }
#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
Below is the vulnerable code, please generate the patch based on the following information.
#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; }
#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
Below is the vulnerable code, please generate the patch based on the following information.
#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(); }
#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
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public static void main(String[] args) throws Exception { String configPath = args[0]; String log4jprops = args[1]; DataDeployerConfigurator configurator = new YamlDataDeployerConfigurator(configPath); PropertyConfigurator.configure(log4jprops); new Daemon(configurator).run(); }
#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
Below is the vulnerable code, please generate the patch based on the following information.
#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(); }
#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
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public void addTask(GetTask task) { synchronized (getTasks) { task.startNanoTime = System.nanoTime(); getTasks.addLast(task); } //dispatcherThread.interrupt(); }
#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
Below is the vulnerable code, please generate the patch based on the following information.
#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); }
#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
Below is the vulnerable code, please generate the patch based on the following information.
#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); }
#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
Below is the vulnerable code, please generate the patch based on the following information.
#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; } }
#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
Below is the vulnerable code, please generate the patch based on the following information.
#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; }
#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
Below is the vulnerable code, please generate the patch based on the following information.
#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); }
#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
Below is the vulnerable code, please generate the patch based on the following information.
#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()); }
#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
Below is the vulnerable code, please generate the patch based on the following information.
#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; } }
#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
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Override public OAuthGrant getById(Long grantId) { OAuthGrant grant = find(grantId); if( grant != null) { grant = restoreRefs(grant, null, null); } return grant; }
#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
Below is the vulnerable code, please generate the patch based on the following information.
#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); }
#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
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Override public void start() { disruptor.handleEventsWith(eventHandler); disruptor.start(); RingBuffer<ServerEvent> ringBuffer = disruptor.getRingBuffer(); requestConsumer.startConsumers(ringBuffer); }
#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
Below is the vulnerable code, please generate the patch based on the following information.
#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); }
#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
Below is the vulnerable code, please generate the patch based on the following information.
#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; } }
#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
Below is the vulnerable code, please generate the patch based on the following information.
#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); }
#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
Below is the vulnerable code, please generate the patch based on the following information.
#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; }
#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
Below is the vulnerable code, please generate the patch based on the following information.
#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; }
#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
Below is the vulnerable code, please generate the patch based on the following information.
#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); }
#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
Below is the vulnerable code, please generate the patch based on the following information.
#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"); } }
#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
Below is the vulnerable code, please generate the patch based on the following information.
#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); } }
#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
Below is the vulnerable code, please generate the patch based on the following information.
#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); } }
#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
Below is the vulnerable code, please generate the patch based on the following information.
#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); }
#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
Below is the vulnerable code, please generate the patch based on the following information.
#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; }
#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
Below is the vulnerable code, please generate the patch based on the following information.
#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); }
#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
Below is the vulnerable code, please generate the patch based on the following information.
#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; }
#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
Below is the vulnerable code, please generate the patch based on the following information.
#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); }
#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
Below is the vulnerable code, please generate the patch based on the following information.
#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; }
#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
Below is the vulnerable code, please generate the patch based on the following information.
#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; }
#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
Below is the vulnerable code, please generate the patch based on the following information.
#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(); }
#vulnerable code public void close() { doClose(lbProxyBean, protobufRpcProxyList); super.close(); } #location 2 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#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); } }
#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
Below is the vulnerable code, please generate the patch based on the following information.
#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(); }
#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
Below is the vulnerable code, please generate the patch based on the following information.
#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); } }
#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
Below is the vulnerable code, please generate the patch based on the following information.
#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); } }
#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
Below is the vulnerable code, please generate the patch based on the following information.
#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); } }
#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
Below is the vulnerable code, please generate the patch based on the following information.
#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(); }
#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
Below is the vulnerable code, please generate the patch based on the following information.
#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(); } }
#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
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public static Database fromBlocking(@Nonnull ConnectionProvider cp) { return Database.from(new ConnectionProviderBlockingPool2(cp)); }
#vulnerable code public static Database fromBlocking(@Nonnull ConnectionProvider cp) { return Database.from(new ConnectionProviderBlockingPool(cp)); } #location 2 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#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(); } }
#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
Below is the vulnerable code, please generate the patch based on the following information.
#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(); } }
#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
Below is the vulnerable code, please generate the patch based on the following information.
#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); } }
#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
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public static Database from(String url, int maxPoolSize) { return Database.from( // Pools.nonBlocking() // .url(url) // .maxPoolSize(maxPoolSize) // .build()); }
#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
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public static Database create(int maxSize) { return Database.from(Pools.nonBlocking().connectionProvider(connectionProvider(nextUrl())) .maxPoolSize(maxSize).build()); }
#vulnerable code public static Database create(int maxSize) { return Database .from(new NonBlockingConnectionPool(connectionProvider(nextUrl()), maxSize, 1000)); } #location 3 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Test public void 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(); } }
#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
Below is the vulnerable code, please generate the patch based on the following information.
#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()); } }
#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
Below is the vulnerable code, please generate the patch based on the following information.
#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")); // } }
#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
Below is the vulnerable code, please generate the patch based on the following information.
#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(); } }
#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
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Test public void testCreate() { DatabaseCreator.create(1); }
#vulnerable code @Test public void testCreate() { Database db = DatabaseCreator.create(); } #location 3 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Test public void 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(); } }
#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
Below is the vulnerable code, please generate the patch based on the following information.
#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(); } }
#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
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Test @Ignore public void testCallableApi() { Database db = DatabaseCreator.createDerbyWithStoredProcs(1); db // .call("call getPersonCount(?,?)") // .in() // .out(Type.INTEGER, Integer.class) // .build() // .test() // .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // .assertValue(2) // .assertComplete(); }
#vulnerable code @Test @Ignore public void testCallableApi() { Database db = DatabaseCreator.createDerbyWithStoredProcs(1); db // .call("call getPersonCount(?,?)") // .in(0) // .out(Integer.class) // .build() // .test() // .awaitDone(TIMEOUT_SECONDS, TimeUnit.SECONDS) // .assertValue(2) // .assertComplete(); ; } #location 10 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Test public void 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(); } }
#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
Below is the vulnerable code, please generate the patch based on the following information.
#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(); } }
#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
Below is the vulnerable code, please generate the patch based on the following information.
#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); }
#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
Below is the vulnerable code, please generate the patch based on the following information.
#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(); } }
#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
Below is the vulnerable code, please generate the patch based on the following information.
#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(); } }
#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
Below is the vulnerable code, please generate the patch based on the following information.