input
stringlengths
205
73.3k
output
stringlengths
64
73.2k
instruction
stringclasses
1 value
#vulnerable code public void handle(Invocation inv) { try { if (inv.operation == OP_RESPONSE) { handleResponse(inv); } else if (inv.operation == OP_BIND) { Address addressEndPoint = (Address) inv.getValueObject(); ConnectionManager.get().bind(addressEndPoint, inv.conn); inv.returnToContainer(); } else if (inv.operation == OP_REMOTELY_PROCESS_AND_RESPONSE) { Data data = inv.doTake(inv.data); RemotelyProcessable rp = (RemotelyProcessable) ThreadContext.get().toObject(data); rp.setConnection(inv.conn); rp.process(); sendResponse(inv); } else if (inv.operation == OP_REMOTELY_PROCESS) { Data data = inv.doTake(inv.data); RemotelyProcessable rp = (RemotelyProcessable) ThreadContext.get().toObject(data); rp.setConnection(inv.conn); rp.process(); inv.returnToContainer(); } else throw new RuntimeException("Unhandled message " + inv.name); } catch (Exception e) { log(e); e.printStackTrace(); } } #location 7 #vulnerability type NULL_DEREFERENCE
#fixed code public void handle(Invocation inv) { try { if (inv.operation == OP_RESPONSE) { handleResponse(inv); } else if (inv.operation == OP_REMOTELY_PROCESS_AND_RESPONSE) { Data data = inv.doTake(inv.data); RemotelyProcessable rp = (RemotelyProcessable) ThreadContext.get().toObject(data); rp.setConnection(inv.conn); rp.process(); sendResponse(inv); } else if (inv.operation == OP_REMOTELY_PROCESS) { Data data = inv.doTake(inv.data); RemotelyProcessable rp = (RemotelyProcessable) ThreadContext.get().toObject(data); rp.setConnection(inv.conn); rp.process(); inv.returnToContainer(); } else throw new RuntimeException("Unhandled message " + inv.name); } catch (Exception e) { log(e); e.printStackTrace(); } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public V get(Object key) { // MapGetCall mGet = new MapGetCall(); Packet request = createRequestPacket(); request.setOperation(ClusterOperation.CONCURRENT_MAP_GET); request.setKey(Serializer.toByte(key)); Packet response = callAndGetResult(request); if(response.getValue()!=null){ return (V)Serializer.toObject(response.getValue()); } return null; } #location 9 #vulnerability type NULL_DEREFERENCE
#fixed code public V get(Object key) { return (V)doOp(ClusterOperation.CONCURRENT_MAP_GET, Serializer.toByte(key), null); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public void run() { while (running) { Object obj = null; try { lsBuffer.clear(); queue.drainTo(lsBuffer); int size = lsBuffer.size(); if (size > 0) { for (int i = 0; i < size; i++) { obj = lsBuffer.get(i); process(obj); } lsBuffer.clear(); } else { obj = queue.take(); process(obj); } } catch (InterruptedException e) { Node.get().handleInterruptedException(Thread.currentThread(), e); } catch (Throwable e) { if (DEBUG) { System.out.println(e + ", message: " + e + ", obj=" + obj); } e.printStackTrace(System.out); } } } #location 11 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code public void run() { while (running) { Object obj = null; try { lsBuffer.clear(); queue.drainTo(lsBuffer); int size = lsBuffer.size(); if (size > 0) { for (int i = 0; i < size; i++) { obj = lsBuffer.get(i); checkHeartbeat(); process(obj); } lsBuffer.clear(); } else { obj = queue.poll(100, TimeUnit.MILLISECONDS); checkHeartbeat(); if (obj != null) { process(obj); } } } catch (InterruptedException e) { Node.get().handleInterruptedException(Thread.currentThread(), e); } catch (Throwable e) { if (DEBUG) { System.out.println(e + ", message: " + e + ", obj=" + obj); } e.printStackTrace(System.out); } } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code protected Packet callAndGetResult(Packet request) { Call c = createCall(request); synchronized (c) { try { out.enQueue(c); c.wait(); } catch (InterruptedException e) { e.printStackTrace(); } } Packet response = c.getResponse(); return response; } #location 2 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code protected Packet callAndGetResult(Packet request) { Call c = createCall(request); return doCall(c); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public void readData(DataInput in) throws IOException { mapPuts.set(in.readLong()); mapGets.set(in.readLong()); mapRemoves.set(in.readLong()); startTime = in.readLong(); endTime = in.readLong(); } #location 6 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code public void readData(DataInput in) throws IOException { numberOfPuts = in.readLong(); numberOfGets = in.readLong(); numberOfRemoves = in.readLong(); numberOfOtherOperations = in.readLong(); periodStart = in.readLong(); periodEnd = in.readLong(); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public void run() { boolean readPackets = false; boolean readProcessables = false; while (running) { readPackets = (dequeuePackets() != 0); readProcessables = (dequeueProcessables() != 0); if (!readPackets && !readProcessables) { enqueueLock.lock(); try { notEmpty.await(100, TimeUnit.MILLISECONDS); checkPeriodics(); } catch (InterruptedException e) { node.handleInterruptedException(Thread.currentThread(), e); } finally { enqueueLock.unlock(); } } } packetQueue.clear(); processableQueue.clear(); } #location 11 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code public void run() { boolean readPackets = false; boolean readProcessables = false; while (running) { readPackets = (dequeuePackets() != 0); readProcessables = (dequeueProcessables() != 0); if (!readPackets && !readProcessables) { try { synchronized (notEmptyLock) { notEmptyLock.wait(100); } checkPeriodics(); } catch (InterruptedException e) { node.handleInterruptedException(Thread.currentThread(), e); } } } packetQueue.clear(); processableQueue.clear(); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code void migrateBlock(final Block blockInfo) { if (!concurrentMapManager.isBlockInfoValid(blockInfo)) { return; } if (!thisAddress.equals(blockInfo.getOwner())) { throw new RuntimeException(); } if (!blockInfo.isMigrating()) { throw new RuntimeException(); } if (blockInfo.getOwner().equals(blockInfo.getMigrationAddress())) { throw new RuntimeException(); } Block blockReal = blocks[blockInfo.getBlockId()]; if (blockReal.isMigrating()) { if (!blockInfo.getMigrationAddress().equals(blockReal.getMigrationAddress())) { logger.log(Level.WARNING, blockReal + ". Already migrating blockInfo is migrating again to " + blockInfo); } else { logger.log(Level.WARNING, blockInfo + " migration unknown " + blockReal); } return; } blockReal.setOwner(blockInfo.getOwner()); blockReal.setMigrationAddress(blockInfo.getMigrationAddress()); logger.log(Level.FINEST, "migrate blockInfo " + blockInfo); if (!node.isActive() || node.factory.restarted) { return; } if (concurrentMapManager.isSuperClient()) { return; } List<Record> lsRecordsToMigrate = new ArrayList<Record>(1000); Collection<CMap> cmaps = concurrentMapManager.maps.values(); for (final CMap cmap : cmaps) { if (cmap.locallyOwnedMap != null) { cmap.locallyOwnedMap.reset(); } final Object[] records = cmap.ownedRecords.toArray(); for (Object recObj : records) { final Record rec = (Record) recObj; if (rec.isActive()) { if (rec.getKey() == null || rec.getKey().size() == 0) { throw new RuntimeException("Record.key is null or empty " + rec.getKey()); } if (rec.getBlockId() == blockInfo.getBlockId()) { lsRecordsToMigrate.add(rec); cmap.markAsRemoved(rec); } } } } final CountDownLatch latch = new CountDownLatch(lsRecordsToMigrate.size()); for (final Record rec : lsRecordsToMigrate) { final CMap cmap = concurrentMapManager.getMap(rec.getName()); node.executorManager.executeMigrationTask(new FallThroughRunnable() { public void doRun() { try { concurrentMapManager.migrateRecord(cmap, rec); } finally { latch.countDown(); } } }); } node.executorManager.executeMigrationTask(new FallThroughRunnable() { public void doRun() { try { logger.log(Level.FINEST, "migrate blockInfo " + blockInfo + " await "); latch.await(10, TimeUnit.SECONDS); concurrentMapManager.enqueueAndReturn(new Processable() { public void process() { Block blockReal = blocks[blockInfo.getBlockId()]; logger.log(Level.FINEST, "migrate completing [" + blockInfo + "] realBlock " + blockReal); blockReal.setOwner(blockReal.getMigrationAddress()); blockReal.setMigrationAddress(null); logger.log(Level.FINEST, "migrate complete [" + blockInfo.getMigrationAddress() + "] now realBlock " + blockReal); for (MemberImpl member : concurrentMapManager.lsMembers) { if (!member.localMember()) { concurrentMapManager.sendBlockInfo(new Block(blockReal), member.getAddress()); } } } }); } catch (InterruptedException ignored) { } } }); } #location 5 #vulnerability type NULL_DEREFERENCE
#fixed code void reArrangeBlocks() { if (concurrentMapManager.isMaster()) { Map<Address, Integer> addressBlocks = getCurrentMemberBlocks(); if (addressBlocks.size() == 0) { return; } List<Block> lsBlocksToRedistribute = new ArrayList<Block>(); int aveBlockOwnCount = BLOCK_COUNT / (addressBlocks.size()); for (Block blockReal : blocks) { if (blockReal.getOwner() == null) { logger.log(Level.SEVERE, "Master cannot have null block owner " + blockReal); return; } if (blockReal.isMigrating()) { logger.log(Level.SEVERE, "Cannot have migrating block " + blockReal); return; } Integer countInt = addressBlocks.get(blockReal.getOwner()); int count = (countInt == null) ? 0 : countInt; if (count >= aveBlockOwnCount) { lsBlocksToRedistribute.add(new Block(blockReal)); } else { addressBlocks.put(blockReal.getOwner(), ++count); } } Collection<Address> allAddress = addressBlocks.keySet(); lsBlocksToMigrate.clear(); for (Address address : allAddress) { Integer countInt = addressBlocks.get(address); int count = (countInt == null) ? 0 : countInt; while (count < aveBlockOwnCount && lsBlocksToRedistribute.size() > 0) { Block blockToMigrate = lsBlocksToRedistribute.remove(0); if (!blockToMigrate.getOwner().equals(address)) { blockToMigrate.setMigrationAddress(address); lsBlocksToMigrate.add(blockToMigrate); } count++; } } Collections.shuffle(lsBlocksToMigrate); } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code void doPublish(Request req) { Q q = getQ(req.name); if (q.blCurrentPut == null) { q.setCurrentPut(); } int index = q.publish(req); req.longValue = index; req.response = Boolean.TRUE; } #location 3 #vulnerability type NULL_DEREFERENCE
#fixed code void syncForDead(Address addressDead) { MemberImpl member = getNextMemberBeforeSync(addressDead, true, 1); if (DEBUG) { log(addressDead + " is dead and its backup was " + member); } Address addressNewOwner = (member == null) ? thisAddress : member.getAddress(); Collection<Q> queues = mapQueues.values(); for (Q q : queues) { List<Block> lsBlocks = q.lsBlocks; for (Block block : lsBlocks) { if (block.address.equals(addressDead)) { // set the new owner block.address = addressNewOwner; block.resetAddIndex(); if (lsMembers.size() > 1) { if (addressNewOwner.equals(thisAddress)) { // I am the new owner so backup to next member int indexUpto = block.size() - 1; if (DEBUG) { log("IndexUpto " + indexUpto); } if (indexUpto > -1) { executeLocally(new BlockBackupSyncRunner(new BlockBackupSync(q, block, indexUpto))); } } } } else if (block.address.equals(thisAddress)) { // If I am/was the owner of this block // did my backup change.. // if so backup to the new next if (lsMembers.size() > 1) { MemberImpl memberBackupWas = getNextMemberBeforeSync(thisAddress, true, 1); if (memberBackupWas == null || memberBackupWas.getAddress().equals(addressDead)) { int indexUpto = block.size() - 1; if (indexUpto > -1) { executeLocally(new BlockBackupSyncRunner(new BlockBackupSync(q, block, indexUpto))); } } } } } // packetalidate the dead member's scheduled actions List<ScheduledPollAction> scheduledPollActions = q.lsScheduledPollActions; for (ScheduledPollAction scheduledAction : scheduledPollActions) { if (addressDead.equals(scheduledAction.request.caller)) { scheduledAction.setValid(false); ClusterManager.get().deregisterScheduledAction(scheduledAction); } } List<ScheduledOfferAction> scheduledOfferActions = q.lsScheduledOfferActions; for (ScheduledOfferAction scheduledAction : scheduledOfferActions) { if (addressDead.equals(scheduledAction.request.caller)) { scheduledAction.setValid(false); ClusterManager.get().deregisterScheduledAction(scheduledAction); } } } doResetBlockSizes(); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code void migrateBlock(final Block block) { if (!concurrentMapManager.isBlockInfoValid(block)) { return; } if (!thisAddress.equals(block.getOwner())) { throw new RuntimeException(); } if (block.getMigrationAddress() == null) { throw new RuntimeException(); } if (block.getOwner().equals(block.getMigrationAddress())) { throw new RuntimeException(); } Block blockReal = blocks[block.getBlockId()]; if (blockReal.isMigrating()) { if (!block.getOwner().equals(blockReal.getOwner()) || !block.getMigrationAddress().equals(blockReal.getMigrationAddress())) { logger.log(Level.WARNING, blockReal + ". Already migrating block is migrating again to " + block); } return; } blockReal.setOwner(block.getOwner()); blockReal.setMigrationAddress(block.getMigrationAddress()); logger.log(Level.FINEST, "migrate block " + block); if (!node.isActive() || node.factory.restarted) { return; } if (concurrentMapManager.isSuperClient()) { return; } blockMigrating = block; List<Record> lsRecordsToMigrate = new ArrayList<Record>(1000); Collection<CMap> cmaps = concurrentMapManager.maps.values(); for (final CMap cmap : cmaps) { if (cmap.locallyOwnedMap != null) { cmap.locallyOwnedMap.reset(); } final Object[] records = cmap.ownedRecords.toArray(); for (Object recObj : records) { final Record rec = (Record) recObj; if (rec.isActive()) { if (rec.getKey() == null || rec.getKey().size() == 0) { throw new RuntimeException("Record.key is null or empty " + rec.getKey()); } if (rec.getBlockId() == block.getBlockId()) { lsRecordsToMigrate.add(rec); cmap.markAsRemoved(rec); } } } } final CountDownLatch latch = new CountDownLatch(lsRecordsToMigrate.size()); for (final Record rec : lsRecordsToMigrate) { final CMap cmap = concurrentMapManager.getMap(rec.getName()); node.executorManager.executeMigrationTask(new FallThroughRunnable() { public void doRun() { try { concurrentMapManager.migrateRecord(cmap, rec); } finally { latch.countDown(); } } }); } node.executorManager.executeMigrationTask(new FallThroughRunnable() { public void doRun() { try { logger.log(Level.FINEST, "migrate block " + block + " await "); latch.await(10, TimeUnit.SECONDS); concurrentMapManager.enqueueAndReturn(new Processable() { public void process() { Block blockReal = blocks[block.getBlockId()]; logger.log(Level.FINEST, "migrate completing [" + block+ "] realBlock " + blockReal); blockReal.setOwner(blockReal.getMigrationAddress()); blockReal.setMigrationAddress(null); logger.log(Level.FINEST, "migrate complete [" + block.getMigrationAddress() + "] now realBlock " + blockReal); for (MemberImpl member : concurrentMapManager.lsMembers) { if (!member.localMember()) { concurrentMapManager.sendBlockInfo(blockReal, member.getAddress()); } } } }); } catch (InterruptedException ignored) { } } }); } #location 5 #vulnerability type NULL_DEREFERENCE
#fixed code void reArrangeBlocks() { if (concurrentMapManager.isMaster()) { List<MemberImpl> lsMembers = concurrentMapManager.lsMembers; // make sue that all blocks are actually created for (int i = 0; i < BLOCK_COUNT; i++) { Block block = blocks[i]; if (block == null) { concurrentMapManager.getOrCreateBlock(i); } } List<Block> lsBlocksToRedistribute = new ArrayList<Block>(); Map<Address, Integer> addressBlocks = new HashMap<Address, Integer>(); int storageEnabledMemberCount = 0; for (MemberImpl member : lsMembers) { if (!member.isSuperClient()) { addressBlocks.put(member.getAddress(), 0); storageEnabledMemberCount++; } } if (storageEnabledMemberCount == 0) { return; } int aveBlockOwnCount = BLOCK_COUNT / (storageEnabledMemberCount); for (Block block : blocks) { if (block.getOwner() == null) { lsBlocksToRedistribute.add(new Block(block)); } else { if (!block.isMigrating()) { Integer countInt = addressBlocks.get(block.getOwner()); int count = (countInt == null) ? 0 : countInt; if (count >= aveBlockOwnCount) { lsBlocksToRedistribute.add(new Block(block)); } else { count++; addressBlocks.put(block.getOwner(), count); } } } } Set<Address> allAddress = addressBlocks.keySet(); lsBlocksToMigrate.clear(); setNewMembers: for (Address address : allAddress) { Integer countInt = addressBlocks.get(address); int count = (countInt == null) ? 0 : countInt; while (count < aveBlockOwnCount) { if (lsBlocksToRedistribute.size() > 0) { Block blockToMigrate = lsBlocksToRedistribute.remove(0); if (blockToMigrate.getOwner() == null) { blockToMigrate.setOwner(address); } else { blockToMigrate.setMigrationAddress(address); if (blockToMigrate.getOwner().equals(blockToMigrate.getMigrationAddress())) { blockToMigrate.setMigrationAddress(null); } } lsBlocksToMigrate.add(blockToMigrate); count++; } else { break setNewMembers; } } } int addressIndex = 0; final Address[] addresses = addressBlocks.keySet().toArray(new Address[]{}); final int addressLength = addresses.length; for (int i = 0; i < BLOCK_COUNT; i++) { Block block = blocks[i]; if (block.getOwner() == null) { block = new Block(block); int index = addressIndex++ % addressLength; block.setOwner(addresses[index]); lsBlocksToRedistribute.add(block); } } } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public void writeData(DataOutput out) throws IOException { out.writeLong(mapPuts.get()); out.writeLong(mapGets.get()); out.writeLong(mapRemoves.get()); out.writeLong(startTime); out.writeLong(endTime); } #location 6 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code public void writeData(DataOutput out) throws IOException { out.writeLong(numberOfPuts); out.writeLong(numberOfGets); out.writeLong(numberOfRemoves); out.writeLong(numberOfOtherOperations); out.writeLong(periodStart); out.writeLong(periodEnd); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public void readFrom(DataInputStream dis) throws IOException { System.out.println("Available:" + dis.available()); headerSize = dis.readInt(); keySize = dis.readInt(); valueSize = dis.readInt(); headerInBytes = new byte[headerSize]; dis.read(headerInBytes); ByteArrayInputStream bis = new ByteArrayInputStream(headerInBytes); DataInputStream dis2 = new DataInputStream(bis); this.operation = ClusterOperation.create(dis2.readInt()); this.blockId = dis2.readInt(); this.threadId = dis2.readInt(); this.lockCount = dis2.readInt(); this.timeout = dis2.readLong(); this.txnId = dis2.readLong(); this.longValue = dis2.readLong(); this.recordId = dis2.readLong(); this.version = dis2.readLong(); this.callId = (int) dis2.readLong(); this.client = dis2.readByte()==1; this.responseType = dis2.readByte(); int nameLength = dis2.readInt(); byte[] b = new byte[nameLength]; dis2.read(b); this.name = new String(b); this.lockAddressIsNull = dis2.readBoolean(); key = new byte[keySize]; dis.read(key); value = new byte[valueSize]; dis.read(value); } #location 33 #vulnerability type RESOURCE_LEAK
#fixed code public void readFrom(DataInputStream dis) throws IOException { headerSize = dis.readInt(); keySize = dis.readInt(); valueSize = dis.readInt(); headerInBytes = new byte[headerSize]; dis.read(headerInBytes); ByteArrayInputStream bis = new ByteArrayInputStream(headerInBytes); DataInputStream dis2 = new DataInputStream(bis); this.operation = ClusterOperation.create(dis2.readInt()); this.blockId = dis2.readInt(); this.threadId = dis2.readInt(); this.lockCount = dis2.readInt(); this.timeout = dis2.readLong(); this.txnId = dis2.readLong(); this.longValue = dis2.readLong(); this.recordId = dis2.readLong(); this.version = dis2.readLong(); this.callId = (int) dis2.readLong(); this.client = dis2.readByte()==1; this.responseType = dis2.readByte(); int nameLength = dis2.readInt(); byte[] b = new byte[nameLength]; dis2.read(b); this.name = new String(b); this.lockAddressIsNull = dis2.readBoolean(); indexCount = dis2.readByte(); for (int i=0; i<indexCount ; i++) { indexes[i] = dis2.readLong(); indexTypes[i] = dis2.readByte(); } key = new byte[keySize]; dis.read(key); value = new byte[valueSize]; dis.read(value); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code void doAddTopicListener(Request req) { for (MemberImpl member : lsMembers) { if (member.localMember()) { handleListenerRegisterations(true, req.name, req.key, req.caller, true); } else if (!member.getAddress().equals(req.caller)) { sendProcessableTo(new TopicListenerRegistration(req.name, true, req.caller), member .getAddress()); } } Q q = getQ(req.name); if (q.blCurrentPut == null) { q.setCurrentPut(); } req.recordId = q.getRecordId(q.blCurrentPut.blockId, q.blCurrentPut.addIndex); } #location 11 #vulnerability type NULL_DEREFERENCE
#fixed code void syncForDead(Address addressDead) { MemberImpl member = getNextMemberBeforeSync(addressDead, true, 1); if (DEBUG) { log(addressDead + " is dead and its backup was " + member); } Address addressNewOwner = (member == null) ? thisAddress : member.getAddress(); Collection<Q> queues = mapQueues.values(); for (Q q : queues) { List<Block> lsBlocks = q.lsBlocks; for (Block block : lsBlocks) { if (block.address.equals(addressDead)) { // set the new owner block.address = addressNewOwner; block.resetAddIndex(); if (lsMembers.size() > 1) { if (addressNewOwner.equals(thisAddress)) { // I am the new owner so backup to next member int indexUpto = block.size() - 1; if (DEBUG) { log("IndexUpto " + indexUpto); } if (indexUpto > -1) { executeLocally(new BlockBackupSyncRunner(new BlockBackupSync(q, block, indexUpto))); } } } } else if (block.address.equals(thisAddress)) { // If I am/was the owner of this block // did my backup change.. // if so backup to the new next if (lsMembers.size() > 1) { MemberImpl memberBackupWas = getNextMemberBeforeSync(thisAddress, true, 1); if (memberBackupWas == null || memberBackupWas.getAddress().equals(addressDead)) { int indexUpto = block.size() - 1; if (indexUpto > -1) { executeLocally(new BlockBackupSyncRunner(new BlockBackupSync(q, block, indexUpto))); } } } } } // packetalidate the dead member's scheduled actions List<ScheduledPollAction> scheduledPollActions = q.lsScheduledPollActions; for (ScheduledPollAction scheduledAction : scheduledPollActions) { if (addressDead.equals(scheduledAction.request.caller)) { scheduledAction.setValid(false); ClusterManager.get().deregisterScheduledAction(scheduledAction); } } List<ScheduledOfferAction> scheduledOfferActions = q.lsScheduledOfferActions; for (ScheduledOfferAction scheduledAction : scheduledOfferActions) { if (addressDead.equals(scheduledAction.request.caller)) { scheduledAction.setValid(false); ClusterManager.get().deregisterScheduledAction(scheduledAction); } } } doResetBlockSizes(); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code void initiateMigration() { for (int i = 0; i < BLOCK_COUNT; i++) { Block block = blocks[i]; if (block == null) { block = concurrentMapManager.getOrCreateBlock(i); block.setOwner(thisAddress); } } if (concurrentMapManager.getMembers().size() < 2) { return; } if (lsBlocksToMigrate.size() == 0) { reArrangeBlocks(); } if (lsBlocksToMigrate.size() > 0) { Block block = lsBlocksToMigrate.remove(0); if (concurrentMapManager.isBlockInfoValid(block)) { if (thisAddress.equals(block.getOwner())) { concurrentMapManager.doBlockInfo(block); } else { concurrentMapManager.sendBlockInfo(block, block.getOwner()); } } } } #location 18 #vulnerability type NULL_DEREFERENCE
#fixed code void reArrangeBlocks() { if (concurrentMapManager.isMaster()) { Map<Address, Integer> addressBlocks = getCurrentMemberBlocks(); if (addressBlocks.size() == 0) { return; } List<Block> lsBlocksToRedistribute = new ArrayList<Block>(); int aveBlockOwnCount = BLOCK_COUNT / (addressBlocks.size()); for (Block blockReal : blocks) { if (blockReal.getOwner() == null) { logger.log(Level.SEVERE, "Master cannot have null block owner " + blockReal); return; } if (blockReal.isMigrating()) { logger.log(Level.SEVERE, "Cannot have migrating block " + blockReal); return; } Integer countInt = addressBlocks.get(blockReal.getOwner()); int count = (countInt == null) ? 0 : countInt; if (count >= aveBlockOwnCount) { lsBlocksToRedistribute.add(new Block(blockReal)); } else { addressBlocks.put(blockReal.getOwner(), ++count); } } Collection<Address> allAddress = addressBlocks.keySet(); lsBlocksToMigrate.clear(); for (Address address : allAddress) { Integer countInt = addressBlocks.get(address); int count = (countInt == null) ? 0 : countInt; while (count < aveBlockOwnCount && lsBlocksToRedistribute.size() > 0) { Block blockToMigrate = lsBlocksToRedistribute.remove(0); if (!blockToMigrate.getOwner().equals(address)) { blockToMigrate.setMigrationAddress(address); lsBlocksToMigrate.add(blockToMigrate); } count++; } } Collections.shuffle(lsBlocksToMigrate); } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public void readFrom(DataInputStream dis) throws IOException { System.out.println("Available:" + dis.available()); headerSize = dis.readInt(); keySize = dis.readInt(); valueSize = dis.readInt(); headerInBytes = new byte[headerSize]; dis.read(headerInBytes); ByteArrayInputStream bis = new ByteArrayInputStream(headerInBytes); DataInputStream dis2 = new DataInputStream(bis); this.operation = ClusterOperation.create(dis2.readInt()); this.blockId = dis2.readInt(); this.threadId = dis2.readInt(); this.lockCount = dis2.readInt(); this.timeout = dis2.readLong(); this.txnId = dis2.readLong(); this.longValue = dis2.readLong(); this.recordId = dis2.readLong(); this.version = dis2.readLong(); this.callId = (int) dis2.readLong(); this.client = dis2.readByte()==1; this.responseType = dis2.readByte(); int nameLength = dis2.readInt(); byte[] b = new byte[nameLength]; dis2.read(b); this.name = new String(b); this.lockAddressIsNull = dis2.readBoolean(); key = new byte[keySize]; dis.read(key); value = new byte[valueSize]; dis.read(value); } #location 28 #vulnerability type RESOURCE_LEAK
#fixed code public void readFrom(DataInputStream dis) throws IOException { headerSize = dis.readInt(); keySize = dis.readInt(); valueSize = dis.readInt(); headerInBytes = new byte[headerSize]; dis.read(headerInBytes); ByteArrayInputStream bis = new ByteArrayInputStream(headerInBytes); DataInputStream dis2 = new DataInputStream(bis); this.operation = ClusterOperation.create(dis2.readInt()); this.blockId = dis2.readInt(); this.threadId = dis2.readInt(); this.lockCount = dis2.readInt(); this.timeout = dis2.readLong(); this.txnId = dis2.readLong(); this.longValue = dis2.readLong(); this.recordId = dis2.readLong(); this.version = dis2.readLong(); this.callId = (int) dis2.readLong(); this.client = dis2.readByte()==1; this.responseType = dis2.readByte(); int nameLength = dis2.readInt(); byte[] b = new byte[nameLength]; dis2.read(b); this.name = new String(b); this.lockAddressIsNull = dis2.readBoolean(); indexCount = dis2.readByte(); for (int i=0; i<indexCount ; i++) { indexes[i] = dis2.readLong(); indexTypes[i] = dis2.readByte(); } key = new byte[keySize]; dis.read(key); value = new byte[valueSize]; dis.read(value); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public long getPeriodEnd() { return endTime; } #location 2 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code public long getPeriodEnd() { return periodEnd; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public void process(Object obj) { long processStart = System.nanoTime(); if (obj instanceof Invocation) { Invocation inv = (Invocation) obj; MemberImpl memberFrom = getMember(inv.conn.getEndPoint()); if (memberFrom != null) { memberFrom.didRead(); } int operation = inv.operation; if (operation < 50) { ClusterManager.get().handle(inv); } else if (operation < 300) { ListenerManager.get().handle(inv); } else if (operation < 400) { ExecutorManager.get().handle(inv); } else if (operation < 500) { BlockingQueueManager.get().handle(inv); } else if (operation < 600) { ConcurrentMapManager.get().handle(inv); } else throw new RuntimeException("Unknown operation " + operation); } else if (obj instanceof Processable) { ((Processable) obj).process(); } else if (obj instanceof Runnable) { synchronized (obj) { ((Runnable) obj).run(); obj.notify(); } } else throw new RuntimeException("Unkown obj " + obj); long processEnd = System.nanoTime(); long elipsedTime = processEnd - processStart; totalProcessTime += elipsedTime; long duration = (processEnd - start); if (duration > TimeUnit.SECONDS.toNanos(10)) { if (DEBUG) { System.out.println("ServiceProcessUtilization: " + ((totalProcessTime * 100) / duration) + " %"); } start = processEnd; totalProcessTime = 0; } } #location 9 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code public void process(Object obj) { long processStart = System.nanoTime(); if (obj instanceof Invocation) { Invocation inv = (Invocation) obj; MemberImpl memberFrom = getMember(inv.conn.getEndPoint()); if (memberFrom != null) { memberFrom.didRead(); } int operation = inv.operation; if (operation < 50) { ClusterManager.get().handle(inv); } else if (operation < 300) { ListenerManager.get().handle(inv); } else if (operation < 400) { ExecutorManager.get().handle(inv); } else if (operation < 500) { BlockingQueueManager.get().handle(inv); } else if (operation < 600) { ConcurrentMapManager.get().handle(inv); } else throw new RuntimeException("Unknown operation " + operation); } else if (obj instanceof Processable) { ((Processable) obj).process(); } else if (obj instanceof Runnable) { synchronized (obj) { ((Runnable) obj).run(); obj.notify(); } } else throw new RuntimeException("Unkown obj " + obj); long processEnd = System.nanoTime(); long elipsedTime = processEnd - processStart; totalProcessTime += elipsedTime; long duration = (processEnd - start); if (duration > UTILIZATION_CHECK_INTERVAL) { if (DEBUG) { System.out.println("ServiceProcessUtilization: " + ((totalProcessTime * 100) / duration) + " %"); } start = processEnd; totalProcessTime = 0; } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void describeAsAdditionalInfo_notEmpty() { Correspondence.ExceptionStore exceptions = Correspondence.ExceptionStore.forIterable(); addCompareException(exceptions); assertExpectedFacts( exceptions.describeAsAdditionalInfo().asIterable(), "additionally, one or more exceptions were thrown while comparing elements"); } #location 6 #vulnerability type NULL_DEREFERENCE
#fixed code @Test public void describeAsAdditionalInfo_notEmpty() { Correspondence.ExceptionStore exceptions = Correspondence.ExceptionStore.forIterable(); addCompareException(exceptions); assertExpectedFacts( exceptions.describeAsAdditionalInfo(), "additionally, one or more exceptions were thrown while comparing elements"); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public void hasField(String fieldName) { if (getSubject() == null) { failWithoutSubject("<null> has a field named <" + fieldName + ">"); } Class<?> clazz = getSubject().getClass(); try { clazz.getField(fieldName); } catch (NoSuchFieldException e) { StringBuilder message = new StringBuilder("Not true that "); message.append("<").append(getSubject().getClass().getSimpleName()).append(">"); message.append(" has a field named <").append(fieldName).append(">"); failureStrategy.fail(message.toString()); } } #location 5 #vulnerability type NULL_DEREFERENCE
#fixed code public void hasField(String fieldName) { if (getSubject() == null) { failureStrategy.fail("Cannot determine a field name from a null object."); return; // not all failures throw exceptions. } check().that(getSubject().getClass()).hasField(fieldName); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void describeAsAdditionalInfo_empty() { Correspondence.ExceptionStore exceptions = Correspondence.ExceptionStore.forIterable(); assertThat(exceptions.describeAsAdditionalInfo().asIterable()).isEmpty(); } #location 4 #vulnerability type NULL_DEREFERENCE
#fixed code @Test public void describeAsAdditionalInfo_empty() { Correspondence.ExceptionStore exceptions = Correspondence.ExceptionStore.forIterable(); assertThat(exceptions.describeAsAdditionalInfo()).isEmpty(); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public String getConceptNetUrl() { String urlFromConfigOrDefault = getConfiguration().getSettingValueFor(CONFIG_KEY_URL).toString(); return urlFromConfigOrDefault == null ? DEFAULT_CONCEPTNET_URL : urlFromConfigOrDefault; } #location 2 #vulnerability type NULL_DEREFERENCE
#fixed code public String getConceptNetUrl() { String urlFromConfigOrDefault = (String)getConfiguration().getSettingValueFor(CONFIG_KEY_URL); return urlFromConfigOrDefault == null ? DEFAULT_CONCEPTNET_URL : urlFromConfigOrDefault; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public SingleResult process(TextRankRequest request) { TextRank textrank = new TextRank(getDatabase(), getNLPManager().getConfiguration()); if (request.getStopWords() != null && !request.getStopWords().isEmpty()) { textrank.setStopwords(request.getStopWords()); } textrank.removeStopWords(request.isDoStopwords()); textrank.respectDirections(request.isRespectDirections()); textrank.respectSentences(request.isRespectSentences()); textrank.useTfIdfWeights(request.isUseTfIdfWeights()); textrank.useDependencies(request.isUseDependencies()); textrank.setCooccurrenceWindow(request.getCooccurrenceWindow()); Map<Long, Map<Long, CoOccurrenceItem>> coOccurrence = textrank.createCooccurrences(request.getNode()); boolean res = textrank.evaluate(request.getNode(), coOccurrence, request.getIterations(), request.getDamp(), request.getThreshold()); if (!res) { return SingleResult.fail(); } LOG.info("AnnotatedText with ID " + request.getNode().getId() + " processed."); return SingleResult.success(); } #location 16 #vulnerability type NULL_DEREFERENCE
#fixed code public SingleResult process(TextRankRequest request) { TextRank textrank = new TextRank(getDatabase(), getNLPManager().getConfiguration()); if (request.getStopWords() != null && !request.getStopWords().isEmpty()) { textrank.setStopwords(request.getStopWords()); } textrank.removeStopWords(request.isDoStopwords()); textrank.respectDirections(request.isRespectDirections()); textrank.respectSentences(request.isRespectSentences()); textrank.useTfIdfWeights(request.isUseTfIdfWeights()); textrank.useDependencies(request.isUseDependencies()); textrank.setCooccurrenceWindow(request.getCooccurrenceWindow()); textrank.setMaxSingleKeywords(request.getMaxSingleKeywords()); textrank.setKeywordLabel(request.getKeywordLabel()); Map<Long, Map<Long, CoOccurrenceItem>> coOccurrence = textrank.createCooccurrences(request.getNode()); boolean res = textrank.evaluate(request.getNode(), coOccurrence, request.getIterations(), request.getDamp(), request.getThreshold()); if (!res) { return SingleResult.fail(); } LOG.info("AnnotatedText with ID " + request.getNode().getId() + " processed."); return SingleResult.success(); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public Map<Long, Map<Long, CoOccurrenceItem>> createCooccurrences(Node annotatedText) { Map<String, Object> params = new HashMap<>(); params.put("id", annotatedText.getId()); String query; if (respectSentences) { query = COOCCURRENCE_QUERY_BY_SENTENCE; } else { query = COOCCURRENCE_QUERY; } Result res = null; try (Transaction tx = database.beginTx();) { res = database.execute(query, params); tx.success(); } catch (Exception e) { LOG.error("Error while creating co-occurrences: ", e); } List<CoOccurrenceItem> prelim = new ArrayList<>(); while (res != null && res.hasNext()) { Map<String, Object> next = res.next(); Long tag1 = toLong(next.get("tag1")); Long tag2 = toLong(next.get("tag2")); String tagVal1 = (String) next.get("tag1_val"); String tagVal2 = (String) next.get("tag2_val"); int tag1Start = (toLong(next.get("sourceStartPosition"))).intValue(); int tag2Start = (toLong(next.get("destinationStartPosition"))).intValue(); List<String> pos1 = Arrays.asList((String[]) next.get("pos1")); List<String> pos2 = Arrays.asList((String[]) next.get("pos2")); // check whether POS of both tags are admitted boolean bPOS1 = pos1.stream().filter(pos -> admittedPOSs.contains(pos)).count() != 0 || pos1.size() == 0; boolean bPOS2 = pos2.stream().filter(pos -> admittedPOSs.contains(pos)).count() != 0 || pos2.size() == 0; // fill tag co-occurrences (adjacency matrix) if (bPOS1 && bPOS2) { prelim.add(new CoOccurrenceItem(tag1, tag1Start, tag2, tag2Start)); } // for logging purposses and for `handleNamedEntities()` idToValue.put(tag1, tagVal1); idToValue.put(tag2, tagVal2); } Map<Long, List<Pair<Long, Long>>> neExp = expandNamedEntities(); neExpanded = neExp.entrySet().stream() .collect(Collectors.toMap( Map.Entry::getKey, e -> e.getValue().stream().map(p -> p.second()).collect(Collectors.toList()) )); Map<Long, Map<Long, CoOccurrenceItem>> results = new HashMap<>(); long neVisited = 0L; for (CoOccurrenceItem it: prelim) { Long tag1 = it.getSource(); Long tag2 = it.getDestination(); int tag1Start = it.getSourceStartingPositions().get(0).first().intValue(); int tag2Start = it.getSourceStartingPositions().get(0).second().intValue(); if (neExp.containsKey(tag1)) { if (neVisited == 0L || neVisited != tag1.longValue()) { connectTagsInNE(results, neExp.get(tag1), tag1Start); neVisited = 0L; } tag1Start += neExp.get(tag1).get( neExp.get(tag1).size() - 1 ).first().intValue(); tag1 = neExp.get(tag1).get( neExp.get(tag1).size() - 1 ).second(); } if (neExp.containsKey(tag2)) { connectTagsInNE(results, neExp.get(tag2), tag2Start); neVisited = tag2; tag2 = neExp.get(tag2).get(0).second(); } else neVisited = 0L; addTagToCoOccurrence(results, tag1, tag1Start, tag2, tag2Start); if (!directionsMatter) { // when direction of co-occurrence relationships is not important addTagToCoOccurrence(results, tag2, tag2Start, tag1, tag1Start); } } return results; } #location 62 #vulnerability type NULL_DEREFERENCE
#fixed code public Map<Long, Map<Long, CoOccurrenceItem>> createCooccurrences(Node annotatedText) { Map<String, Object> params = new HashMap<>(); params.put("id", annotatedText.getId()); String query; if (respectSentences) { query = COOCCURRENCE_QUERY_BY_SENTENCE; } else { query = COOCCURRENCE_QUERY; } Result res = null; try (Transaction tx = database.beginTx();) { res = database.execute(query, params); tx.success(); } catch (Exception e) { LOG.error("Error while creating co-occurrences: ", e); } List<CoOccurrenceItem> prelim = new ArrayList<>(); while (res != null && res.hasNext()) { Map<String, Object> next = res.next(); Long tag1 = toLong(next.get("tag1")); Long tag2 = toLong(next.get("tag2")); String tagVal1 = (String) next.get("tag1_val"); String tagVal2 = (String) next.get("tag2_val"); int tag1Start = (toLong(next.get("sourceStartPosition"))).intValue(); int tag2Start = (toLong(next.get("destinationStartPosition"))).intValue(); List<String> pos1 = next.get("pos1") != null ? Arrays.asList((String[]) next.get("pos1")) : new ArrayList<>(); List<String> pos2 = next.get("pos2") != null ? Arrays.asList((String[]) next.get("pos2")) : new ArrayList<>(); // check whether POS of both tags are admitted boolean bPOS1 = pos1.stream().filter(pos -> admittedPOSs.contains(pos)).count() != 0 || pos1.size() == 0; boolean bPOS2 = pos2.stream().filter(pos -> admittedPOSs.contains(pos)).count() != 0 || pos2.size() == 0; // fill tag co-occurrences (adjacency matrix) if (bPOS1 && bPOS2) { prelim.add(new CoOccurrenceItem(tag1, tag1Start, tag2, tag2Start)); } // for logging purposses and for `expandNamedEntities()` idToValue.put(tag1, tagVal1); idToValue.put(tag2, tagVal2); } Map<Long, List<Pair<Long, Long>>> neExp; if (expandNEs) { // process named entities: split them into individual tokens by calling ga.nlp.annotate(), assign them IDs and create co-occurrences neExp = expandNamedEntities(); neExpanded = neExp.entrySet().stream() .collect(Collectors.toMap( Map.Entry::getKey, e -> e.getValue().stream().map(p -> p.second()).collect(Collectors.toList()) )); } else neExp = new HashMap<>(); Map<Long, Map<Long, CoOccurrenceItem>> results = new HashMap<>(); long neVisited = 0L; for (CoOccurrenceItem it: prelim) { Long tag1 = it.getSource(); Long tag2 = it.getDestination(); int tag1Start = it.getSourceStartingPositions().get(0).first().intValue(); int tag2Start = it.getSourceStartingPositions().get(0).second().intValue(); if (expandNEs) { if (neExp.containsKey(tag1)) { if (neVisited == 0L || neVisited != tag1.longValue()) { connectTagsInNE(results, neExp.get(tag1), tag1Start); neVisited = 0L; } tag1Start += neExp.get(tag1).get( neExp.get(tag1).size() - 1 ).first().intValue(); tag1 = neExp.get(tag1).get( neExp.get(tag1).size() - 1 ).second(); } if (neExp.containsKey(tag2)) { connectTagsInNE(results, neExp.get(tag2), tag2Start); neVisited = tag2; tag2 = neExp.get(tag2).get(0).second(); } else neVisited = 0L; } addTagToCoOccurrence(results, tag1, tag1Start, tag2, tag2Start); if (!directionsMatter) { // when direction of co-occurrence relationships is not important addTagToCoOccurrence(results, tag2, tag2Start, tag1, tag1Start); } } return results; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code private Map<Long, Float> createFeatureMapWithCN5New(long firstNode) throws QueryExecutionException { Map<String, Object> params = new HashMap<>(); params.put("id", firstNode); Result res = database.execute("MATCH (doc:AnnotatedText)\n" + "WITH count(doc) as documentsCount\n" + "MATCH (document:AnnotatedText)-[:CONTAINS_SENTENCE]->(s:Sentence)-[ht:HAS_TAG]->(tag:Tag)\n" + "WHERE id(document) = {id} and not any (p in tag.pos where p in [\"CC\", \"CD\", \"DT\", \"IN\", \"MD\", \"PRP\", \"PRP$\", \"UH\", \"WDT\", \"WP\", \"WRB\", \"TO\", \"PDT\", \"RP\", \"WP$\"])\n" // JJR, JJS ? + "WITH tag, sum(ht.tf) as tf, documentsCount, document.numTerms as nTerms\n" + "OPTIONAL MATCH (tag)-[rt:IS_RELATED_TO]->(t2_l1:Tag)\n" + "WHERE id(t2_l1) = tag.idMaxConcept and exists(t2_l1.word2vec) and com.graphaware.nlp.ml.similarity.cosine(tag.word2vec, t2_l1.word2vec)>0.2\n" + "WITH tag, tf, nTerms, id(t2_l1) as cn5_l1_tag, rt.weight as cn5_l1_tag_w, documentsCount\n" + "MATCH (a:AnnotatedText)-[:CONTAINS_SENTENCE]->(s:Sentence)-[ht:HAS_TAG]->(tag)\n" + "RETURN id(tag) as tagId, tf, (1.0f*documentsCount)/count(distinct a) as idf, nTerms, (case cn5_l1_tag when null then -1 else cn5_l1_tag end) as cn5_l1_tag, cn5_l1_tag_w\n" + "ORDER BY tagId, cn5_l1_tag", params); Map<Long, Float> result = new HashMap<>(); Map<Long, Float> result_idf = new HashMap<>(); while (res != null && res.hasNext()) { Map<String, Object> next = res.next(); long id = (long) next.get("tagId"); int nTerms = (int) next.get("nTerms"); //float tf = getFloatValue(next.get("tf")); float tf = getFloatValue(next.get("tf")) / nTerms; float idf = Double.valueOf(Math.log10(Float.valueOf(getFloatValue(next.get("idf"))).doubleValue())).floatValue(); // ConceptNet5 Level_1 tags //long cn5_tag = Long.valueOf((String) next.get("cn5_l1_tag")); long cn5_tag = (long) next.get("cn5_l1_tag"); float cn5_tag_w = getFloatValue(next.get("cn5_l1_tag_w")); if (cn5_tag>-1) { if (!result.containsKey(cn5_tag)) { result.put(cn5_tag, tf); result_idf.put(cn5_tag, idf); } else { result.put(cn5_tag, result.get(cn5_tag) + tf); if (result_idf.get(cn5_tag) < idf) // use the highest idf result_idf.put(cn5_tag, idf); } } else { result.put(id, tf); result_idf.put(id, idf); } } for (Long key: result.keySet()) { result.put(key, result.get(key) * result_idf.get(key)); } return result; } #location 46 #vulnerability type NULL_DEREFERENCE
#fixed code private Map<Long, Float> createFeatureMapWithCN5New(long firstNode) throws QueryExecutionException { Map<String, Object> params = new HashMap<>(); params.put("id", firstNode); Result res = database.execute(DEFAULT_VECTOR_QUERY_WITH_CONCEPT, params); Map<Long, Float> result = new HashMap<>(); Map<Long, Float> result_idf = new HashMap<>(); while (res != null && res.hasNext()) { Map<String, Object> next = res.next(); long id = (long) next.get("tagId"); int nTerms = (int) next.get("nTerms"); //float tf = getFloatValue(next.get("tf")); float tf = getFloatValue(next.get("tf")) / nTerms; float idf = Double.valueOf(Math.log10(Float.valueOf(getFloatValue(next.get("idf"))).doubleValue())).floatValue(); // ConceptNet5 Level_1 tags //long cn5_tag = Long.valueOf((String) next.get("cn5_l1_tag")); long cn5_tag = (long) next.get("cn5_l1_tag"); float cn5_tag_w = getFloatValue(next.get("cn5_l1_tag_w")); if (cn5_tag > -1) { if (!result.containsKey(cn5_tag)) { result.put(cn5_tag, tf); result_idf.put(cn5_tag, idf); } else { result.put(cn5_tag, result.get(cn5_tag) + tf); if (result_idf.get(cn5_tag) < idf) // use the highest idf { result_idf.put(cn5_tag, idf); } } } else { result.put(id, tf); result_idf.put(id, idf); } } result.keySet().forEach((key) -> { result.put(key, result.get(key) * result_idf.get(key)); }); return result; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public SingleResult process(TextRankRequest request) { TextRank.Builder textrankBuilder = new TextRank.Builder(getDatabase(), getNLPManager().getConfiguration()); if (request.getStopWords() != null && !request.getStopWords().isEmpty()) { textrankBuilder.setStopwords(request.getStopWords()); } textrankBuilder.removeStopWords(request.isDoStopwords()) .respectDirections(request.isRespectDirections()) .respectSentences(request.isRespectSentences()) .useDependencies(request.isUseDependencies()) .useDependenciesForCooccurrences(request.isUseDependenciesForCooccurrences()) //.setCooccurrenceWindow(request.getCooccurrenceWindow()) .setTopXTags(request.getTopXTags()) .setCleanKeywords(request.isCleanKeywords()) .setKeywordLabel(request.getKeywordLabel()); TextRank textRank = textrankBuilder.build(); boolean res = textRank.evaluate(request.getNode(), request.getIterations(), request.getDamp(), request.getThreshold()); LOG.info("AnnotatedText with ID " + request.getNode().getId() + " processed. Result: " + res); return res ? SingleResult.success() : SingleResult.fail(); } #location 2 #vulnerability type NULL_DEREFERENCE
#fixed code public SingleResult process(TextRankRequest request) { TextRankResult result = compute(request); TextRankPersister persister = new TextRankPersister(Label.label(request.getKeywordLabel())); persister.peristKeywords(result.getResult(), request.getNode()); return result.getStatus().equals(TextRankResult.TextRankStatus.SUCCESS) ? SingleResult.success() : SingleResult.fail(); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public boolean evaluate(Node annotatedText, int iter, double damp, double threshold) { Map<Long, Map<Long, CoOccurrenceItem>> coOccurrence = createCooccurrences(annotatedText); PageRank pageRank = new PageRank(database); if (useTfIdfWeights) { pageRank.setNodeWeights(initializeNodeWeights_TfIdf(annotatedText, coOccurrence)); } Map<Long, Double> pageRanks = pageRank.run(coOccurrence, iter, damp, threshold); int n_oneThird = (int) (pageRanks.size() * phrasesTopxWords); List<Long> topThird = getTopX(pageRanks, n_oneThird); LOG.info("Top " + n_oneThird + " tags: " + topThird.stream().map(id -> idToValue.get(id)).collect(Collectors.joining(", "))); Map<String, Object> params = new HashMap<>(); params.put("id", annotatedText.getId()); params.put("nodeList", topThird); params.put("posList", admittedPOSs); List<KeywordExtractedItem> keywordsOccurrences = new ArrayList<>(); Map<Long, KeywordExtractedItem> keywordMap = new HashMap<>(); try (Transaction tx = database.beginTx()) { Result res = database.execute(GET_TAG_QUERY, params); while (res != null && res.hasNext()) { Map<String, Object> next = res.next(); long tagId = (long) next.get("tagId"); KeywordExtractedItem item = new KeywordExtractedItem(tagId); item.setStartPosition(((Number) next.get("sP")).intValue()); item.setValue(((String) next.get("tag"))); item.setEndPosition(((Number) next.get("eP")).intValue()); item.setRelatedTags(iterableToList((Iterable<String>) next.get("rel_tags"))); item.setRelTagStartingPoints(iterableToList((Iterable<Number>) next.get("rel_tos"))); item.setRelTagEndingPoints(iterableToList((Iterable<Number>) next.get("rel_toe"))); item.setRelevance(pageRanks.get(tagId)); keywordsOccurrences.add(item); if (!keywordMap.containsKey(tagId)) { keywordMap.put(tagId, item); } } if (res != null) { res.close(); } tx.success(); } catch (Exception e) { LOG.error("Error while running TextRank evaluation: ", e); return false; } Map<String, Keyword> results = new HashMap<>(); while (!keywordsOccurrences.isEmpty()) { final AtomicReference<KeywordExtractedItem> keywordOccurrence = new AtomicReference<>(keywordsOccurrences.remove(0)); final AtomicReference<String> currValue = new AtomicReference<>(keywordOccurrence.get().getValue()); final AtomicReference<Double> currRelevance = new AtomicReference<>(keywordOccurrence.get().getRelevance()); //System.out.println("> " + currValue.get() + " - " + keywordOccurrence.get().getStartPosition()); Map<String, Keyword> localResults; do { long tagId = keywordOccurrence.get().getTagId(); //System.out.println("cur: " + currValue.get() + " examinating next level"); localResults = checkNextKeyword(tagId, keywordOccurrence.get(), coOccurrence, keywordMap); if (localResults.size() > 0) { localResults.entrySet().stream().forEach((item) -> { KeywordExtractedItem nextKeyword = keywordsOccurrences.get(0); if (nextKeyword != null && nextKeyword.value.equalsIgnoreCase(item.getKey())) { String newCurrValue = currValue.get().split("_")[0] + " " + item.getKey(); //System.out.println(">> " + newCurrValue); double newCurrRelevance = currRelevance.get() + item.getValue().getRelevance(); currValue.set(newCurrValue); currRelevance.set(newCurrRelevance); keywordOccurrence.set(nextKeyword); keywordsOccurrences.remove(0); } else { LOG.warn("Next keyword not found!"); keywordOccurrence.set(null); } }); } } while (!localResults.isEmpty() && keywordOccurrence.get() != null); addToResults(currValue.get(), currRelevance.get(), results, 1); //System.out.println("< " + currValue.get()); } // add named entities that contain at least some of the top 1/3 of words /*neExpanded.entrySet().stream() .filter(en -> { long n = en.getValue().stream().filter(v -> topThird.contains(v)).count(); return n > 0; //return n >= en.getValue().size() / 3.0f || (n > 0 && en.getValue().size() == 2); }) .forEach(en -> { final String key = idToValue.get(en.getKey()) + "_en"; // + lang; results.put(key, new Keyword(key)); // TO DO: handle counters exactMatch and total });*/ for (Long key: neExpanded.keySet()) { if (neExpanded.get(key).stream().filter(v -> topThird.contains(v)).count() == 0) continue; String keystr = idToValue.get(key) + "_en"; // + lang; results.put(keystr, new Keyword(keystr)); // TO DO: handle counters exactMatch and total } computeTotalOccurrence(results); if (cleanSingleWordKeyword) { results = cleanSingleWordKeyword(results); } peristKeyword(results, annotatedText); return true; } #location 93 #vulnerability type NULL_DEREFERENCE
#fixed code public boolean evaluate(Node annotatedText, int iter, double damp, double threshold) { Map<Long, Map<Long, CoOccurrenceItem>> coOccurrence = createCooccurrences(annotatedText); PageRank pageRank = new PageRank(database); if (useTfIdfWeights) { pageRank.setNodeWeights(initializeNodeWeights_TfIdf(annotatedText, coOccurrence)); } Map<Long, Double> pageRanks = pageRank.run(coOccurrence, iter, damp, threshold); int n_oneThird = (int) (pageRanks.size() * phrasesTopxWords); List<Long> topThird = getTopX(pageRanks, n_oneThird); LOG.info("Top " + n_oneThird + " tags: " + topThird.stream().map(id -> idToValue.get(id)).collect(Collectors.joining(", "))); Map<String, Object> params = new HashMap<>(); params.put("id", annotatedText.getId()); //params.put("nodeList", topThird); // new (also changed the GET_TAG_QUERY) params.put("posList", admittedPOSs); List<KeywordExtractedItem> keywordsOccurrences = new ArrayList<>(); Map<Long, KeywordExtractedItem> keywordMap = new HashMap<>(); try (Transaction tx = database.beginTx()) { Result res = database.execute(GET_TAG_QUERY, params); while (res != null && res.hasNext()) { Map<String, Object> next = res.next(); long tagId = (long) next.get("tagId"); KeywordExtractedItem item = new KeywordExtractedItem(tagId); item.setStartPosition(((Number) next.get("sP")).intValue()); item.setValue(((String) next.get("tag"))); item.setEndPosition(((Number) next.get("eP")).intValue()); item.setRelatedTags(iterableToList((Iterable<String>) next.get("rel_tags"))); item.setRelTagStartingPoints(iterableToList((Iterable<Number>) next.get("rel_tos"))); item.setRelTagEndingPoints(iterableToList((Iterable<Number>) next.get("rel_toe"))); item.setRelevance(pageRanks.containsKey(tagId) ? pageRanks.get(tagId) : 0); keywordsOccurrences.add(item); if (!keywordMap.containsKey(tagId)) { keywordMap.put(tagId, item); } } if (res != null) { res.close(); } tx.success(); } catch (Exception e) { LOG.error("Error while running TextRank evaluation: ", e); return false; } Map<String, Long> valToId = idToValue.entrySet().stream().collect(Collectors.toMap(Map.Entry::getValue, Map.Entry::getKey)); Map<String, Keyword> results = new HashMap<>(); while (!keywordsOccurrences.isEmpty()) { final AtomicReference<KeywordExtractedItem> keywordOccurrence = new AtomicReference<>(keywordsOccurrences.remove(0)); final AtomicReference<String> currValue = new AtomicReference<>(keywordOccurrence.get().getValue()); final AtomicReference<Double> currRelevance = new AtomicReference<>(keywordOccurrence.get().getRelevance()); List<Long> relTagIDs = keywordOccurrence.get().getRelatedTags().stream().map(el -> valToId.get(el)).collect(Collectors.toList()); // new relTagIDs.retainAll(topThird); // new if (!topThird.contains(keywordOccurrence.get().getTagId()) && relTagIDs.size()==0) // new continue; //System.out.println("\n> " + currValue.get() + " - " + keywordOccurrence.get().getStartPosition()); Map<String, Keyword> localResults; do { long tagId = keywordOccurrence.get().getTagId(); //System.out.println(" cur: " + currValue.get() + ". Examining next level"); localResults = checkNextKeyword(tagId, keywordOccurrence.get(), coOccurrence, keywordMap); if (localResults.size() > 0) { //System.out.println(" related tags: " + localResults.entrySet().stream().map(en -> en.getKey()).collect(Collectors.joining(", "))); localResults.entrySet().stream().forEach((item) -> { KeywordExtractedItem nextKeyword = keywordsOccurrences.get(0); if (nextKeyword != null && nextKeyword.value.equalsIgnoreCase(item.getKey())) { String newCurrValue = currValue.get().split("_")[0] + " " + item.getKey(); //System.out.println(">> " + newCurrValue); double newCurrRelevance = currRelevance.get() + item.getValue().getRelevance(); currValue.set(newCurrValue); currRelevance.set(newCurrRelevance); keywordOccurrence.set(nextKeyword); keywordsOccurrences.remove(0); } else { LOG.warn("Next keyword not found!"); keywordOccurrence.set(null); } }); } } while (!localResults.isEmpty() && keywordOccurrence.get() != null); addToResults(currValue.get(), currRelevance.get(), results, 1); //System.out.println("< " + currValue.get()); } // add named entities that contain at least some of the top 1/3 of words for (Long key: neExpanded.keySet()) { if (neExpanded.get(key).stream().filter(v -> topThird.contains(v)).count() == 0) continue; String keystr = idToValue.get(key) + "_en"; // + lang; addToResults(keystr, pageRanks.containsKey(key) ? pageRanks.get(key) : 0, results, 1); } computeTotalOccurrence(results); if (cleanSingleWordKeyword) { results = cleanSingleWordKeyword(results); } peristKeyword(results, annotatedText); return true; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public SingleResult process(PageRankRequest request) { String nodeType = request.getNodeType(); String relType = request.getRelationshipType(); String relWeight = request.getRelationshipWeight(); int iter = request.getIteration().intValue(); double damp = request.getDamp(); double threshold = request.getThreshold(); boolean respectDirections = request.getRespectDirections(); PageRank pagerank = new PageRank(getDatabase()); pagerank.respectDirections(respectDirections); Map<Long, Map<Long, CoOccurrenceItem>> coOccurrences = pagerank.processGraph(nodeType, relType, relWeight); if (coOccurrences.isEmpty()) { return SingleResult.fail(); } Map<Long, Double> pageranks = pagerank.run(coOccurrences, iter, damp, threshold); if (pageranks.isEmpty()) { return SingleResult.fail(); } pageranks.entrySet().stream().forEach(en -> LOG.info("PR(" + en.getKey() + ") = " + en.getValue())); LOG.info("Sum of PageRanks: " + pageranks.values().stream().mapToDouble(Number::doubleValue).sum()); pagerank.storeOnGraph(pageranks, nodeType); return SingleResult.success(); } #location 12 #vulnerability type NULL_DEREFERENCE
#fixed code public SingleResult process(PageRankRequest request) { String query = request.getQuery(); int iter = request.getIteration().intValue(); double damp = request.getDamp(); double threshold = request.getThreshold(); boolean respectDirections = request.getRespectDirections(); PageRank pagerank = new PageRank(getDatabase()); Map<Long, Map<Long, CoOccurrenceItem>> coOccurrences = pagerank.createGraph(query, respectDirections); if (coOccurrences.isEmpty()) { return SingleResult.fail(); } Map<Long, Double> pageranks = pagerank.run(coOccurrences, iter, damp, threshold); if (pageranks.isEmpty()) { return SingleResult.fail(); } pageranks.entrySet().stream().forEach(en -> LOG.info("PR(" + en.getKey() + ") = " + en.getValue())); LOG.info("Sum of PageRanks: " + pageranks.values().stream().mapToDouble(Number::doubleValue).sum()); pagerank.storeOnGraph(pageranks); return SingleResult.success(); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public Tag annotateTag(String text, String language) { PipelineSpecification spec = getDefaultPipeline(language); TextProcessor processor = getTextProcessor(spec.getTextProcessor()); return processor.annotateTag(text, spec); } #location 3 #vulnerability type NULL_DEREFERENCE
#fixed code public Tag annotateTag(String text, String language) { PipelineSpecification spec = getDefaultPipeline(language); if (spec == null) { LOG.warn("No default annotator for language: " + language); return null; } TextProcessor processor = getTextProcessor(spec.getTextProcessor()); return processor.annotateTag(text, spec); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code private void initializePipelineWithoutNEs() { //System.out.println(" >>> default processor: " + NLPManager.getInstance().getTextProcessorsManager().getDefaultProcessor().getAlias()); Map<String, Object> params = new HashMap<>(); params.put("tokenize", true); params.put("ner", false); PipelineSpecification ps = new PipelineSpecification(PIPELINE_WITHOUT_NER, null); ps.setProcessingSteps(params); NLPManager.getInstance().getTextProcessorsManager().getDefaultProcessor() .createPipeline(ps); } #location 8 #vulnerability type NULL_DEREFERENCE
#fixed code private void initializePipelineWithoutNEs() { if (!NLPManager.getInstance().hasPipeline(PIPELINE_WITHOUT_NER)) { Map<String, Object> params = new HashMap<>(); params.put("tokenize", true); params.put("ner", false); String processor = NLPManager.getInstance().getTextProcessorsManager().getDefaultProcessor().getClass().getName(); PipelineSpecification ps = new PipelineSpecification(PIPELINE_WITHOUT_NER, processor); ps.setProcessingSteps(params); NLPManager.getInstance().addPipeline(ps); } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public String getDefaultModelWorkdir() { String p = configuration.getSettingValueFor(SettingsConstants.DEFAULT_MODEL_WORKDIR).toString(); if (p == null) { throw new RuntimeException("No default model wordking directory set in configuration"); } return p; } #location 2 #vulnerability type NULL_DEREFERENCE
#fixed code public String getDefaultModelWorkdir() { Object p = configuration.getSettingValueFor(SettingsConstants.DEFAULT_MODEL_WORKDIR); if (p == null) { return getRawConfig().get(IMPORT_DIR_CONF_KEY); } return p.toString(); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Procedure(name = "ga.nlp.parser.powerpoint") public Stream<Page> parsePowerpoint(@Name("file") String filename, @Name(value = "filterPatterns", defaultValue = "") List<String> filterPatterns) { PowerpointParser parser = (PowerpointParser) getNLPManager().getExtension(PowerpointParser.class); List<String> filters = filterPatterns.equals("") ? new ArrayList<>() : filterPatterns; try { List<Page> pages = parser.parse(filename, filters); return pages.stream(); } catch (Exception e) { throw new RuntimeException(e); } } #location 6 #vulnerability type NULL_DEREFERENCE
#fixed code @Procedure(name = "ga.nlp.parser.powerpoint") public Stream<Page> parsePowerpoint(@Name("file") String filename, @Name(value = "filterPatterns", defaultValue = "") List<String> filterPatterns) { PowerpointParser parser = (PowerpointParser) getNLPManager().getExtension(PowerpointParser.class); return getPages(parser, filename, filterPatterns).stream(); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code private Map<String, Keyword> checkNextKeyword(long tagId, KeywordExtractedItem keywordOccurrence, Map<Long, Map<Long, CoOccurrenceItem>> coOccurrences, Map<Long, KeywordExtractedItem> keywords) { Map<String, Keyword> results = new HashMap<>(); if (!coOccurrences.containsKey(tagId)) return results; Map<Integer, Set<Long>> mapStartId = createThisMapping(coOccurrences.get(tagId), tagId); Set<Long> coOccurrence = mapStartId.get(keywordOccurrence.startPosition); if (coOccurrence == null) { return results; } Iterator<Long> iterator = coOccurrence.stream() .filter((ccEntry) -> ccEntry != tagId) .filter((ccEntry) -> keywords.containsKey(ccEntry)).iterator(); while (iterator.hasNext()) { Long ccEntry = iterator.next(); String relValue = keywords.get(ccEntry).getValue(); //System.out.println("checkNextKeyword >> " + relValue); //if (!useDependencies || keywordOccurrence.getRelatedTags().contains(relValue.split("_")[0])) { List<String> merged = new ArrayList<>(keywords.get(tagId).getRelatedTags()); // new merged.retainAll(keywordOccurrence.getRelatedTags()); // new //System.out.println(" related tag = " + idToValue.get(ccEntry) + ", related tags = " + keywords.get(tagId).getRelatedTags().stream().collect(Collectors.joining(", "))); //System.out.println(" merged = " + merged.stream().collect(Collectors.joining(", "))); if (!useDependencies || keywordOccurrence.getRelatedTags().contains(relValue.split("_")[0]) || merged.size()>0) { // new //System.out.println("checkNextKeyword >>> " + relValue); addToResults(relValue, keywords.get(ccEntry).getRelevance(), results, 1); } } return results; } #location 21 #vulnerability type NULL_DEREFERENCE
#fixed code private Map<String, Keyword> checkNextKeyword(long tagId, KeywordExtractedItem keywordOccurrence, Map<Long, Map<Long, CoOccurrenceItem>> coOccurrences, Map<Long, KeywordExtractedItem> keywords) { Map<String, Keyword> results = new HashMap<>(); if (!coOccurrences.containsKey(tagId)) return results; Map<Integer, Set<Long>> mapStartId = createThisMapping(coOccurrences.get(tagId), tagId); Set<Long> coOccurrence = mapStartId.get(keywordOccurrence.startPosition); if (coOccurrence == null) { return results; } Iterator<Long> iterator = coOccurrence.stream() .filter((ccEntry) -> ccEntry != tagId) .filter((ccEntry) -> keywords.containsKey(ccEntry)).iterator(); while (iterator.hasNext()) { Long ccEntry = iterator.next(); String relValue = keywords.get(ccEntry).getValue(); //System.out.println("checkNextKeyword >> " + relValue); //if (!useDependencies || keywordOccurrence.getRelatedTags().contains(relValue.split("_")[0])) { List<String> merged = new ArrayList<>(keywords.get(ccEntry).getRelatedTags()); // new merged.retainAll(keywordOccurrence.getRelatedTags()); // new //System.out.println(" co-occurring tag = " + idToValue.get(ccEntry) + ", related tags = " + keywords.get(ccEntry).getRelatedTags().stream().collect(Collectors.joining(", "))); //System.out.println(" merged = " + merged.stream().collect(Collectors.joining(", "))); if (!useDependencies || keywordOccurrence.getRelatedTags().contains(relValue.split("_")[0]) || merged.size()>0) { // new //System.out.println("checkNextKeyword >>> " + relValue); addToResults(relValue, keywords.get(ccEntry).getRelevance(), results, 1); } } return results; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Procedure(name = "ga.nlp.parser.pdf") public Stream<Page> parsePdf(@Name("file") String filename, @Name(value = "filterPatterns", defaultValue = "") List<String> filterPatterns) { TikaPDFParser parser = (TikaPDFParser) getNLPManager().getExtension(TikaPDFParser.class); List<String> filters = filterPatterns.equals("") ? new ArrayList<>() : filterPatterns; try { List<Page> pages = parser.parse(filename, filters); return pages.stream(); } catch (Exception e) { throw new RuntimeException(e); } } #location 6 #vulnerability type NULL_DEREFERENCE
#fixed code @Procedure(name = "ga.nlp.parser.pdf") public Stream<Page> parsePdf(@Name("file") String filename, @Name(value = "filterPatterns", defaultValue = "") List<String> filterPatterns) { TikaPDFParser parser = (TikaPDFParser) getNLPManager().getExtension(TikaPDFParser.class); return getPages(parser, filename, filterPatterns).stream(); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code private Map<Long, Float> createFeatureMapWithCN5New(long firstNode) throws QueryExecutionException { Map<String, Object> params = new HashMap<>(); params.put("id", firstNode); Result res = database.execute("MATCH (doc:AnnotatedText)\n" + "WITH count(doc) as documentsCount\n" + "MATCH (document:AnnotatedText)-[:CONTAINS_SENTENCE]->(s:Sentence)-[ht:HAS_TAG]->(tag:Tag)\n" + "WHERE id(document) = {id} and not any (p in tag.pos where p in [\"CC\", \"CD\", \"DT\", \"IN\", \"MD\", \"PRP\", \"PRP$\", \"UH\", \"WDT\", \"WP\", \"WRB\", \"TO\", \"PDT\", \"RP\", \"WP$\"])\n" // JJR, JJS ? + "WITH tag, sum(ht.tf) as tf, documentsCount, document.numTerms as nTerms\n" + "OPTIONAL MATCH (tag)-[rt:IS_RELATED_TO]->(t2_l1:Tag)\n" + "WHERE id(t2_l1) = tag.idMaxConcept and exists(t2_l1.word2vec) and com.graphaware.nlp.ml.similarity.cosine(tag.word2vec, t2_l1.word2vec)>0.2\n" + "WITH tag, tf, nTerms, id(t2_l1) as cn5_l1_tag, rt.weight as cn5_l1_tag_w, documentsCount\n" + "MATCH (a:AnnotatedText)-[:CONTAINS_SENTENCE]->(s:Sentence)-[ht:HAS_TAG]->(tag)\n" + "RETURN id(tag) as tagId, tf, (1.0f*documentsCount)/count(distinct a) as idf, nTerms, (case cn5_l1_tag when null then -1 else cn5_l1_tag end) as cn5_l1_tag, cn5_l1_tag_w\n" + "ORDER BY tagId, cn5_l1_tag", params); Map<Long, Float> result = new HashMap<>(); Map<Long, Float> result_idf = new HashMap<>(); while (res != null && res.hasNext()) { Map<String, Object> next = res.next(); long id = (long) next.get("tagId"); int nTerms = (int) next.get("nTerms"); //float tf = getFloatValue(next.get("tf")); float tf = getFloatValue(next.get("tf")) / nTerms; float idf = Double.valueOf(Math.log10(Float.valueOf(getFloatValue(next.get("idf"))).doubleValue())).floatValue(); // ConceptNet5 Level_1 tags //long cn5_tag = Long.valueOf((String) next.get("cn5_l1_tag")); long cn5_tag = (long) next.get("cn5_l1_tag"); float cn5_tag_w = getFloatValue(next.get("cn5_l1_tag_w")); if (cn5_tag>-1) { if (!result.containsKey(cn5_tag)) { result.put(cn5_tag, tf); result_idf.put(cn5_tag, idf); } else { result.put(cn5_tag, result.get(cn5_tag) + tf); if (result_idf.get(cn5_tag) < idf) // use the highest idf result_idf.put(cn5_tag, idf); } } else { result.put(id, tf); result_idf.put(id, idf); } } for (Long key: result.keySet()) { result.put(key, result.get(key) * result_idf.get(key)); } return result; } #location 46 #vulnerability type NULL_DEREFERENCE
#fixed code private Map<Long, Float> createFeatureMapWithCN5New(long firstNode) throws QueryExecutionException { Map<String, Object> params = new HashMap<>(); params.put("id", firstNode); Result res = database.execute(DEFAULT_VECTOR_QUERY_WITH_CONCEPT, params); Map<Long, Float> result = new HashMap<>(); Map<Long, Float> result_idf = new HashMap<>(); while (res != null && res.hasNext()) { Map<String, Object> next = res.next(); long id = (long) next.get("tagId"); int nTerms = (int) next.get("nTerms"); //float tf = getFloatValue(next.get("tf")); float tf = getFloatValue(next.get("tf")) / nTerms; float idf = Double.valueOf(Math.log10(Float.valueOf(getFloatValue(next.get("idf"))).doubleValue())).floatValue(); // ConceptNet5 Level_1 tags //long cn5_tag = Long.valueOf((String) next.get("cn5_l1_tag")); long cn5_tag = (long) next.get("cn5_l1_tag"); float cn5_tag_w = getFloatValue(next.get("cn5_l1_tag_w")); if (cn5_tag > -1) { if (!result.containsKey(cn5_tag)) { result.put(cn5_tag, tf); result_idf.put(cn5_tag, idf); } else { result.put(cn5_tag, result.get(cn5_tag) + tf); if (result_idf.get(cn5_tag) < idf) // use the highest idf { result_idf.put(cn5_tag, idf); } } } else { result.put(id, tf); result_idf.put(id, idf); } } result.keySet().forEach((key) -> { result.put(key, result.get(key) * result_idf.get(key)); }); return result; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Override public boolean handle(LoginPacket packet) { // Check for supported protocol int index = Arrays.binarySearch(DragonProxy.BEDROCK_SUPPORTED_PROTOCOLS, packet.getProtocolVersion()); if (index < 0) { session.getBedrockSession().disconnect(); return true; } session.getBedrockSession().setPacketCodec(DragonProxy.BEDROCK_SUPPORTED_CODECS[index]); try { // Get chain data that contains identity info JSONObject chainData = (JSONObject) JSONValue.parse(packet.getChainData().array()); JSONArray chainArray = (JSONArray) chainData.get("chain"); Object identityObject = chainArray.get(chainArray.size() - 1); JWSObject identity = JWSObject.parse((String) identityObject); JSONObject extraData = (JSONObject) identity.getPayload().toJSONObject().get("extraData"); session.setAuthData(new AuthData( extraData.getAsString("displayName"), extraData.getAsString("identity"), extraData.getAsString("XUID") )); session.setUsername(session.getAuthData().getDisplayName()); } catch (ParseException | ClassCastException | NullPointerException e) { // Invalid chain data session.getBedrockSession().disconnect(); return true; } // Tell the Bedrock client login was successful. PlayStatusPacket playStatus = new PlayStatusPacket(); playStatus.setStatus(PlayStatusPacket.Status.LOGIN_SUCCESS); session.getBedrockSession().sendPacketImmediately(playStatus); // Start Resource pack handshake ResourcePacksInfoPacket resourcePacksInfo = new ResourcePacksInfoPacket(); session.getBedrockSession().sendPacketImmediately(resourcePacksInfo); return true; } #location 16 #vulnerability type NULL_DEREFERENCE
#fixed code @Override public boolean handle(LoginPacket packet) { // Check for supported protocol int index = Arrays.binarySearch(DragonProxy.BEDROCK_SUPPORTED_PROTOCOLS, packet.getProtocolVersion()); if (index < 0) { session.getBedrockSession().disconnect(); return true; } session.getBedrockSession().setPacketCodec(DragonProxy.BEDROCK_SUPPORTED_CODECS[index]); JsonNode certData; try { certData = DragonProxy.JSON_MAPPER.readTree(packet.getChainData().toByteArray()); } catch (IOException ex) { throw new RuntimeException("Certificate JSON could not be read"); } JsonNode certChainData = certData.get("chain"); if (certChainData.getNodeType() != JsonNodeType.ARRAY) { throw new RuntimeException("Certificate data is not valid"); } boolean validChain; try { validChain = BedrockLoginUtils.validateChainData(certChainData); JWSObject jwt = JWSObject.parse(certChainData.get(certChainData.size() - 1).asText()); JsonNode payload = DragonProxy.JSON_MAPPER.readTree(jwt.getPayload().toBytes()); if (payload.get("extraData").getNodeType() != JsonNodeType.OBJECT) { throw new RuntimeException("AuthData was not found!"); } JSONObject extraData = (JSONObject) jwt.getPayload().toJSONObject().get("extraData"); session.setAuthData(DragonProxy.JSON_MAPPER.convertValue(extraData, AuthData.class)); if (payload.get("identityPublicKey").getNodeType() != JsonNodeType.STRING) { throw new RuntimeException("Identity Public Key was not found!"); } if(!validChain) { if(proxy.getConfiguration().isXboxAuth()) { session.disconnect("You must be authenticated with xbox live"); return true; } session.getAuthData().setXuid(null); // TODO: ideally the class should be immutable } ECPublicKey identityPublicKey = EncryptionUtils.generateKey(payload.get("identityPublicKey").textValue()); JWSObject clientJwt = JWSObject.parse(packet.getSkinData().toString()); EncryptionUtils.verifyJwt(clientJwt, identityPublicKey); JsonNode clientPayload = DragonProxy.JSON_MAPPER.readTree(clientJwt.getPayload().toBytes()); session.setClientData(DragonProxy.JSON_MAPPER.convertValue(clientPayload, ClientData.class)); session.setUsername(session.getAuthData().getDisplayName()); if (EncryptionUtils.canUseEncryption()) { //BedrockLoginUtils.startEncryptionHandshake(session, identityPublicKey); } } catch (Exception ex) { session.disconnect("disconnectionScreen.internalError.cantConnect"); throw new RuntimeException("Unable to complete login", ex); } // Tell the Bedrock client login was successful PlayStatusPacket playStatus = new PlayStatusPacket(); playStatus.setStatus(PlayStatusPacket.Status.LOGIN_SUCCESS); session.getBedrockSession().sendPacketImmediately(playStatus); // Start Resource pack handshake ResourcePacksInfoPacket resourcePacksInfo = new ResourcePacksInfoPacket(); session.getBedrockSession().sendPacketImmediately(resourcePacksInfo); return true; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public static com.nukkitx.nbt.tag.CompoundTag translateItemNBT(CompoundTag tag) { CompoundTagBuilder root = CompoundTagBuilder.builder(); CompoundTagBuilder display = CompoundTagBuilder.builder(); if(tag.contains("name")) { display.stringTag("Name", (String) tag.get("name").getValue()); tag.remove("name"); } if(tag.contains("lore")) { com.nukkitx.nbt.tag.ListTag list = (com.nukkitx.nbt.tag.ListTag) translateRawNBT(tag.get("lore")); display.listTag("Lore", com.nukkitx.nbt.tag.StringTag.class, list.getValue()); // TODO: fix unchecked assignment tag.remove("lore"); } root.tag(display.build("display")); if(tag.getValue() != null && !tag.getValue().isEmpty()) { for(String tagName : tag.getValue().keySet()) { com.nukkitx.nbt.tag.Tag bedrockTag = translateRawNBT(tag.get(tagName)); if(bedrockTag == null) { continue; } root.tag(bedrockTag); } } return root.buildRootTag(); } #location 11 #vulnerability type NULL_DEREFERENCE
#fixed code public static com.nukkitx.nbt.tag.CompoundTag translateItemNBT(CompoundTag tag) { CompoundTagBuilder root = CompoundTagBuilder.builder(); if(!tag.contains("display")) { CompoundTagBuilder display = CompoundTagBuilder.builder(); if (tag.contains("name")) { display.stringTag("Name", Message.fromString((String) tag.get("name").getValue()).getFullText()); tag.remove("name"); } if (tag.contains("lore")) { //com.nukkitx.nbt.tag.ListTag list = (com.nukkitx.nbt.tag.ListTag) translateRawNBT(tag.get("lore")); //display.listTag("Lore", com.nukkitx.nbt.tag.StringTag.class, list.getValue()); // TODO: fix unchecked assignment tag.remove("lore"); } root.tag(display.build("display")); } if(tag.getValue() != null && !tag.getValue().isEmpty()) { for(String tagName : tag.getValue().keySet()) { com.nukkitx.nbt.tag.Tag bedrockTag = translateRawNBT(tag.get(tagName)); if(bedrockTag == null) { continue; } root.tag(bedrockTag); } } return root.buildRootTag(); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Override public boolean handle(LoginPacket packet) { // TODO: move out of here? idk UpstreamSession session = new UpstreamSession(this.session); this.session.setPlayer(session); try { // Get chain data that contains identity info JSONObject chainData = (JSONObject) JSONValue.parse(packet.getChainData().array()); JSONArray chainArray = (JSONArray) chainData.get("chain"); Object identityObject = chainArray.get(chainArray.size() - 1); JWSObject identity = JWSObject.parse((String) identityObject); JSONObject extraData = (JSONObject) identity.getPayload().toJSONObject().get("extraData"); this.session.setAuthData(new AuthDataImpl( extraData.getAsString("displayName"), extraData.getAsString("identity"), extraData.getAsString("XUID") )); } catch (ParseException | ClassCastException | NullPointerException e) { // Invalid chain data this.session.disconnect(); return true; } session.setRemoteServer(new RemoteServer("local", proxy.getConfiguration().getRemoteAddress(), proxy.getConfiguration().getRemotePort())); return true; } #location 29 #vulnerability type RESOURCE_LEAK
#fixed code @Override public boolean handle(LoginPacket packet) { // Check for supported protocol int index = Arrays.binarySearch(DragonProxy.BEDROCK_SUPPORTED_PROTOCOLS, packet.getProtocolVersion()); if (index < 0) { upstream.disconnect(); return true; } upstream.setPacketCodec(DragonProxy.BEDROCK_SUPPORTED_CODECS[index]); try { // Get chain data that contains identity info JSONObject chainData = (JSONObject) JSONValue.parse(packet.getChainData().array()); JSONArray chainArray = (JSONArray) chainData.get("chain"); Object identityObject = chainArray.get(chainArray.size() - 1); JWSObject identity = JWSObject.parse((String) identityObject); JSONObject extraData = (JSONObject) identity.getPayload().toJSONObject().get("extraData"); this.upstream.setAuthData(new AuthDataImpl( extraData.getAsString("displayName"), extraData.getAsString("identity"), extraData.getAsString("XUID") )); } catch (ParseException | ClassCastException | NullPointerException e) { // Invalid chain data this.upstream.disconnect(); return true; } // Tell the Bedrock client login was successful. PlayStatusPacket playStatus = new PlayStatusPacket(); playStatus.setStatus(PlayStatusPacket.Status.LOGIN_SUCCESS); upstream.sendPacketImmediately(playStatus); // Start Resource pack handshake ResourcePacksInfoPacket resourcePacksInfo = new ResourcePacksInfoPacket(); upstream.sendPacketImmediately(resourcePacksInfo); return true; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Override public boolean handle(LoginPacket packet) { // Check for supported protocol int index = Arrays.binarySearch(DragonProxy.BEDROCK_SUPPORTED_PROTOCOLS, packet.getProtocolVersion()); if (index < 0) { session.getBedrockSession().disconnect(); return true; } session.getBedrockSession().setPacketCodec(DragonProxy.BEDROCK_SUPPORTED_CODECS[index]); try { // Get chain data that contains identity info JSONObject chainData = (JSONObject) JSONValue.parse(packet.getChainData().array()); JSONArray chainArray = (JSONArray) chainData.get("chain"); Object identityObject = chainArray.get(chainArray.size() - 1); JWSObject identity = JWSObject.parse((String) identityObject); JSONObject extraData = (JSONObject) identity.getPayload().toJSONObject().get("extraData"); session.setAuthData(new AuthData( extraData.getAsString("displayName"), extraData.getAsString("identity"), extraData.getAsString("XUID") )); session.setUsername(session.getAuthData().getDisplayName()); } catch (ParseException | ClassCastException | NullPointerException e) { // Invalid chain data session.getBedrockSession().disconnect(); return true; } // Tell the Bedrock client login was successful. PlayStatusPacket playStatus = new PlayStatusPacket(); playStatus.setStatus(PlayStatusPacket.Status.LOGIN_SUCCESS); session.getBedrockSession().sendPacketImmediately(playStatus); // Start Resource pack handshake ResourcePacksInfoPacket resourcePacksInfo = new ResourcePacksInfoPacket(); session.getBedrockSession().sendPacketImmediately(resourcePacksInfo); return true; } #location 22 #vulnerability type NULL_DEREFERENCE
#fixed code @Override public boolean handle(LoginPacket packet) { // Check for supported protocol int index = Arrays.binarySearch(DragonProxy.BEDROCK_SUPPORTED_PROTOCOLS, packet.getProtocolVersion()); if (index < 0) { session.getBedrockSession().disconnect(); return true; } session.getBedrockSession().setPacketCodec(DragonProxy.BEDROCK_SUPPORTED_CODECS[index]); JsonNode certData; try { certData = DragonProxy.JSON_MAPPER.readTree(packet.getChainData().toByteArray()); } catch (IOException ex) { throw new RuntimeException("Certificate JSON could not be read"); } JsonNode certChainData = certData.get("chain"); if (certChainData.getNodeType() != JsonNodeType.ARRAY) { throw new RuntimeException("Certificate data is not valid"); } boolean validChain; try { validChain = BedrockLoginUtils.validateChainData(certChainData); JWSObject jwt = JWSObject.parse(certChainData.get(certChainData.size() - 1).asText()); JsonNode payload = DragonProxy.JSON_MAPPER.readTree(jwt.getPayload().toBytes()); if (payload.get("extraData").getNodeType() != JsonNodeType.OBJECT) { throw new RuntimeException("AuthData was not found!"); } JSONObject extraData = (JSONObject) jwt.getPayload().toJSONObject().get("extraData"); session.setAuthData(DragonProxy.JSON_MAPPER.convertValue(extraData, AuthData.class)); if (payload.get("identityPublicKey").getNodeType() != JsonNodeType.STRING) { throw new RuntimeException("Identity Public Key was not found!"); } if(!validChain) { if(proxy.getConfiguration().isXboxAuth()) { session.disconnect("You must be authenticated with xbox live"); return true; } session.getAuthData().setXuid(null); // TODO: ideally the class should be immutable } ECPublicKey identityPublicKey = EncryptionUtils.generateKey(payload.get("identityPublicKey").textValue()); JWSObject clientJwt = JWSObject.parse(packet.getSkinData().toString()); EncryptionUtils.verifyJwt(clientJwt, identityPublicKey); JsonNode clientPayload = DragonProxy.JSON_MAPPER.readTree(clientJwt.getPayload().toBytes()); session.setClientData(DragonProxy.JSON_MAPPER.convertValue(clientPayload, ClientData.class)); session.setUsername(session.getAuthData().getDisplayName()); if (EncryptionUtils.canUseEncryption()) { //BedrockLoginUtils.startEncryptionHandshake(session, identityPublicKey); } } catch (Exception ex) { session.disconnect("disconnectionScreen.internalError.cantConnect"); throw new RuntimeException("Unable to complete login", ex); } // Tell the Bedrock client login was successful PlayStatusPacket playStatus = new PlayStatusPacket(); playStatus.setStatus(PlayStatusPacket.Status.LOGIN_SUCCESS); session.getBedrockSession().sendPacketImmediately(playStatus); // Start Resource pack handshake ResourcePacksInfoPacket resourcePacksInfo = new ResourcePacksInfoPacket(); session.getBedrockSession().sendPacketImmediately(resourcePacksInfo); return true; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public static void main(String[] args) { log.info("Starting DragonProxy..."); // Check the java version if (Float.parseFloat(System.getProperty("java.class.version")) < 52.0) { log.error("DragonProxy requires Java 8! Current version: " + System.getProperty("java.version")); return; } // Define command-line options OptionParser optionParser = new OptionParser(); optionParser.accepts("version", "Displays the proxy version"); OptionSpec<String> bedrockPortOption = optionParser.accepts("bedrockPort", "Overrides the bedrock UDP bind port").withRequiredArg(); OptionSpec<String> javaPortOption = optionParser.accepts("javaPort", "Overrides the java TCP bind port").withRequiredArg(); optionParser.accepts("help", "Display help/usage information").forHelp(); // Handle command-line options OptionSet options = optionParser.parse(args); if (options.has("version")) { log.info("Version: " + Bootstrap.class.getPackage().getImplementationVersion()); return; } int bedrockPort = options.has(bedrockPortOption) ? Integer.parseInt(options.valueOf(bedrockPortOption)) : -1; int javaPort = options.has(javaPortOption) ? Integer.parseInt(options.valueOf(bedrockPortOption)) : -1; long startTime = System.currentTimeMillis(); DragonProxy proxy = new DragonProxy(bedrockPort, javaPort); Runtime.getRuntime().addShutdownHook(new Thread(proxy::shutdown, "Shutdown thread")); double bootTime = (System.currentTimeMillis() - startTime) / 1000d; log.info("Done ({}s)!", new DecimalFormat("#.##").format(bootTime)); proxy.getConsole().start(); } #location 35 #vulnerability type NULL_DEREFERENCE
#fixed code public static void main(String[] args) { log.info("Starting DragonProxy..."); // Check the java version if (Float.parseFloat(System.getProperty("java.class.version")) < 52.0) { log.error("DragonProxy requires Java 8! Current version: " + System.getProperty("java.version")); return; } // Define command-line options OptionParser optionParser = new OptionParser(); optionParser.accepts("version", "Displays the proxy version"); OptionSpec<String> bedrockPortOption = optionParser.accepts("bedrockPort", "Overrides the bedrock UDP bind port").withRequiredArg(); OptionSpec<String> javaPortOption = optionParser.accepts("javaPort", "Overrides the java TCP bind port").withRequiredArg(); optionParser.accepts("help", "Display help/usage information").forHelp(); // Handle command-line options OptionSet options = optionParser.parse(args); if (options.has("version")) { log.info("Version: " + Bootstrap.class.getPackage().getImplementationVersion()); return; } int bedrockPort = options.has(bedrockPortOption) ? Integer.parseInt(options.valueOf(bedrockPortOption)) : -1; int javaPort = options.has(javaPortOption) ? Integer.parseInt(options.valueOf(bedrockPortOption)) : -1; DragonProxy proxy = new DragonProxy(bedrockPort, javaPort); Runtime.getRuntime().addShutdownHook(new Thread(proxy::shutdown, "Shutdown thread")); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code private void initialize() throws Exception { if(!RELEASE) { logger.warn("This is a development build. It may contain bugs. Do not use in production."); } // Create injector, provide elements from the environment and register providers // TODO: Remove injector = new InjectorBuilder() .addDefaultHandlers("org.dragonet.proxy") .create(); injector.register(DragonProxy.class, this); injector.register(Logger.class, logger); injector.provide(ProxyFolder.class, getFolder()); // Initiate console console = injector.getSingleton(DragonConsole.class); // Load configuration // TODO: Tidy this up File fileConfig = new File("config.yml"); if (!fileConfig.exists()) { // Create default config FileOutputStream fos = new FileOutputStream(fileConfig); InputStream ins = DragonProxy.class.getResourceAsStream("/config.yml"); int data; while ((data = ins.read()) != -1) { fos.write(data); } ins.close(); fos.close(); } ObjectMapper mapper = new ObjectMapper(new YAMLFactory()); configuration = mapper.readValue(new FileInputStream(fileConfig), DragonConfiguration.class); generalThreadPool = Executors.newScheduledThreadPool(configuration.getThreadPoolSize()); paletteManager = new PaletteManager(); pingPassthroughThread = new PingPassthroughThread(this); if(configuration.isPingPassthrough()) { generalThreadPool.scheduleAtFixedRate(pingPassthroughThread, 1, 1, TimeUnit.SECONDS); logger.info("Ping passthrough enabled"); } BedrockServer server = new BedrockServer(new InetSocketAddress(configuration.getBindAddress(), configuration.getBindPort())); server.setHandler(new ProxyServerEventListener(this)); server.bind().whenComplete((aVoid, throwable) -> { if (throwable == null) { logger.info("RakNet server started on {}", configuration.getBindAddress()); } else { logger.error("RakNet server failed to bind to {}, {}", configuration.getBindAddress(), throwable.getMessage()); } }).join(); } #location 4 #vulnerability type RESOURCE_LEAK
#fixed code private void initialize() throws Exception { if(!RELEASE) { logger.warn("This is a development build. It may contain bugs. Do not use in production."); } // Create injector, provide elements from the environment and register providers // TODO: Remove injector = new InjectorBuilder() .addDefaultHandlers("org.dragonet.proxy") .create(); injector.register(DragonProxy.class, this); injector.register(Logger.class, logger); injector.provide(ProxyFolder.class, getFolder()); // Initiate console console = injector.getSingleton(DragonConsole.class); // Load configuration try { if(!Files.exists(Paths.get("config.yml"))) { Files.copy(getClass().getResourceAsStream("/config.yml"), Paths.get("config.yml"), StandardCopyOption.REPLACE_EXISTING); } } catch (IOException ex) { logger.error("Failed to copy config file: " + ex.getMessage()); } ObjectMapper mapper = new ObjectMapper(new YAMLFactory()); configuration = mapper.readValue(new FileInputStream("config.yml"), DragonConfiguration.class); generalThreadPool = Executors.newScheduledThreadPool(configuration.getThreadPoolSize()); paletteManager = new PaletteManager(); pingPassthroughThread = new PingPassthroughThread(this); if(configuration.isPingPassthrough()) { generalThreadPool.scheduleAtFixedRate(pingPassthroughThread, 1, 1, TimeUnit.SECONDS); logger.info("Ping passthrough enabled"); } BedrockServer server = new BedrockServer(new InetSocketAddress(configuration.getBindAddress(), configuration.getBindPort())); server.setHandler(new ProxyServerEventListener(this)); server.bind().whenComplete((aVoid, throwable) -> { if (throwable == null) { logger.info("RakNet server started on {}", configuration.getBindAddress()); } else { logger.error("RakNet server failed to bind to {}, {}", configuration.getBindAddress(), throwable.getMessage()); } }).join(); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public static void main(String... args) throws InterruptedException { Config config = getConfig(args); Dispatcher dispatcher; switch (config.getCommand()) { case INSERT: dispatcher = new InsertDispatcher(config); break; case SELECT: dispatcher = new SelectDispatcher(config); break; default: throw new RuntimeException("Unknown command enum; Report as bug!!"); } dispatcher.go(); dispatcher.printReport(); System.exit(0); } #location 6 #vulnerability type NULL_DEREFERENCE
#fixed code public static void main(String... args) throws InterruptedException { // Manually grok the command argument in order to conditionally apply different options. if (args.length < 1) { System.err.println("Missing command argument."); printCmdUsage(System.err); System.exit(1); } Config.Command command = null; try { command = Config.Command.valueOf(args[0].toUpperCase()); } catch (IllegalArgumentException ex) { System.err.println("Unknown command: " + args[0]); printCmdUsage(System.err); System.exit(1); } Config config; Dispatcher dispatcher; switch (command) { case INSERT: config = new InsertConfig(); parseArguments(config, args); dispatcher = new InsertDispatcher((InsertConfig) config); break; case SELECT: config = new SelectConfig(); parseArguments(config, args); dispatcher = new SelectDispatcher((SelectConfig) config); break; default: throw new RuntimeException("Unknown command enum; Report as bug!!"); } dispatcher.go(); dispatcher.printReport(); System.exit(0); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Override public Row<Measurement> next() { if (!hasNext()) throw new NoSuchElementException(); Row<Measurement> output = new Row<>(m_timestamps.next(), m_resource); while (m_current != null) { accumulate(m_current, output.getTimestamp()); if (m_current.getTimestamp().gte(output.getTimestamp())) { break; } if (m_input.hasNext()) { m_current = m_input.next(); } else m_current = null; } // Go time; We've accumulated enough to produce the output row for (String name : m_metrics) { Accumulation accumulation = m_accumulation.get(name); // Add sample with accumulated value to output row output.addElement(new Measurement( output.getTimestamp(), output.getResource(), name, accumulation.average().doubleValue())); // If input is greater than row, accumulate remainder for next row if (m_current != null) { accumulation.reset(); Sample sample = m_current.getElement(name); if (sample == null) { continue; } if (m_current.getTimestamp().gt(output.getTimestamp())) { Duration elapsed = m_current.getTimestamp().minus(output.getTimestamp()); if (elapsed.lt(getHeartbeat(name))) { accumulation.known = elapsed.asMillis(); accumulation.value = sample.getValue().times(elapsed.asMillis()); } else { accumulation.unknown = elapsed.asMillis(); } } } } return output; } #location 32 #vulnerability type NULL_DEREFERENCE
#fixed code @Override public Row<Measurement> next() { if (!hasNext()) throw new NoSuchElementException(); Row<Measurement> output = new Row<>(m_timestamps.next(), m_resource); while (m_current != null) { accumulate(m_current, output.getTimestamp()); if (m_current.getTimestamp().gte(output.getTimestamp())) { break; } if (m_input.hasNext()) { m_current = m_input.next(); } else m_current = null; } // Go time; We've accumulated enough to produce the output row for (String name : m_metrics) { Accumulation accumulation = m_accumulation.get(name); // Add sample with accumulated value to output row output.addElement(new Measurement( output.getTimestamp(), output.getResource(), name, accumulation.average())); // If input is greater than row, accumulate remainder for next row if (m_current != null) { accumulation.reset(); Sample sample = m_current.getElement(name); if (sample == null) { continue; } if (m_current.getTimestamp().gt(output.getTimestamp())) { Duration elapsed = m_current.getTimestamp().minus(output.getTimestamp()); if (elapsed.lt(getHeartbeat(name))) { accumulation.known = elapsed.asMillis(); accumulation.value = sample.getValue().times(elapsed.asMillis()); } else { accumulation.unknown = elapsed.asMillis(); } } } } return output; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code private int go(String[] args) { m_parser.setUsageWidth(80); try { m_parser.parseArgument(args); } catch (CmdLineException e) { System.err.println(e.getMessage()); printUsage(System.err); return 1; } if (m_needsHelp) { printUsage(System.out); return 0; } if (m_resource == null || m_metric == null) { System.err.println("Missing required argument(s)"); printUsage(System.err); return 1; } System.out.printf("timestamp,%s%n", m_metric); for (Results.Row<Sample> row : m_repository.select(m_resource, timestamp(m_start), timestamp(m_end))) { System.out.printf("%s,%.2f%n", row.getTimestamp().asDate(), row.getElement(m_metric).getValue()); } return 0; } #location 28 #vulnerability type CHECKERS_PRINTF_ARGS
#fixed code private int go(String[] args) { m_parser.setUsageWidth(80); try { m_parser.parseArgument(args); } catch (CmdLineException e) { System.err.println(e.getMessage()); printUsage(System.err); return 1; } if (m_needsHelp) { printUsage(System.out); return 0; } if (m_resource == null || m_metric == null) { System.err.println("Missing required argument(s)"); printUsage(System.err); return 1; } System.out.printf("timestamp,%s%n", m_metric); for (Results.Row<Sample> row : m_repository.select(m_resource, timestamp(m_start), timestamp(m_end))) { System.out.printf("%s,%.2f%n", row.getTimestamp().asDate(), row.getElement(m_metric).getValue().doubleValue()); } return 0; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test(expected = ReflectionException.class) public void shouldFailGetter() { PojoField pojoField = getPrivateStringField(); pojoField.invokeGetter(null); } #location 4 #vulnerability type NULL_DEREFERENCE
#fixed code @Test(expected = ReflectionException.class) public void shouldFailGetter() { PojoField pojoField = getPrivateStringField(); assert pojoField != null; pojoField.invokeGetter(null); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public Object doGenerate(final Class<?> type) { PojoClass pojoClass = PojoClassFactory.getPojoClass(type); PojoMethod valuesPojoMethod = null; for (PojoMethod pojoMethod : pojoClass.getPojoMethods()) { if (pojoMethod.getName().equals("values")) { valuesPojoMethod = pojoMethod; break; } } Enum<?>[] values = (Enum<?>[]) valuesPojoMethod.invoke(null, (Object[]) null); return values[RANDOM.nextInt(values.length)]; } #location 11 #vulnerability type NULL_DEREFERENCE
#fixed code public Object doGenerate(final Class<?> type) { PojoClass pojoClass = PojoClassFactory.getPojoClass(type); Enum<?>[] values = getValues(pojoClass); if (values == null) { throw RandomGeneratorException.getInstance(MessageFormatter.format("Failed to enumerate possible values of Enum [{0}]", type)); } return values[RANDOM.nextInt(values.length)]; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public Object doGenerate(Parameterizable parameterizedType) { List returnedList = (List) RandomFactory.getRandomValue(parameterizedType.getType()); returnedList.clear(); CollectionHelper.buildCollections(returnedList, parameterizedType.getParameterTypes().get(0)); return returnedList; } #location 3 #vulnerability type NULL_DEREFERENCE
#fixed code public Object doGenerate(Parameterizable parameterizedType) { return CollectionHelper.buildCollections((Collection) doGenerate(parameterizedType.getType()), parameterizedType.getParameterTypes() .get(0)); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public List<PojoPackage> getPojoSubPackages() { List<PojoPackage> pojoPackageSubPackages = new LinkedList<PojoPackage>(); File directory = PackageHelper.getPackageAsDirectory(packageName); for (File entry : directory.listFiles()) { if (entry.isDirectory()) { String subPackageName = packageName + PACKAGE_DELIMETER + entry.getName(); pojoPackageSubPackages.add(new PojoPackageImpl(subPackageName)); } } return pojoPackageSubPackages; } #location 5 #vulnerability type NULL_DEREFERENCE
#fixed code public List<PojoPackage> getPojoSubPackages() { List<PojoPackage> pojoPackageSubPackages = new LinkedList<PojoPackage>(); List<File> paths = PackageHelper.getPackageDirectories(packageName); for (File path : paths) { for (File entry : path.listFiles()) { if (entry.isDirectory()) { String subPackageName = packageName + PACKAGE_DELIMETER + entry.getName(); pojoPackageSubPackages.add(new PojoPackageImpl(subPackageName)); } } } return pojoPackageSubPackages; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test(expected = ReflectionException.class) public void shouldFailSetter() { PojoField pojoField = getPrivateStringField(); pojoField.invokeSetter(null, RandomFactory.getRandomValue(pojoField.getType())); } #location 4 #vulnerability type NULL_DEREFERENCE
#fixed code @Test(expected = ReflectionException.class) public void shouldFailSetter() { PojoField pojoField = getPrivateStringField(); assert pojoField != null; pojoField.invokeSetter(null, RandomFactory.getRandomValue(pojoField.getType())); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public Object doGenerate(Parameterizable parameterizedType) { Queue returnedQueue = (Queue) RandomFactory.getRandomValue(parameterizedType.getType()); returnedQueue.clear(); CollectionHelper.buildCollections(returnedQueue, parameterizedType.getParameterTypes().get(0)); return returnedQueue; } #location 3 #vulnerability type NULL_DEREFERENCE
#fixed code public Object doGenerate(Parameterizable parameterizedType) { Queue returnedQueue = (Queue) RandomFactory.getRandomValue(parameterizedType.getType()); CollectionHelper.buildCollections(returnedQueue, parameterizedType.getParameterTypes().get(0)); return returnedQueue; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test(expected = ReflectionException.class) public void shouldFailGet() { PojoField pojoField = getPrivateStringField(); pojoField.get(null); } #location 4 #vulnerability type NULL_DEREFERENCE
#fixed code @Test(expected = ReflectionException.class) public void shouldFailGet() { PojoField pojoField = getPrivateStringField(); assert pojoField != null; pojoField.get(null); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public void run(final PojoClass pojoClass) { IdentityFactory.registerIdentityHandler(identityHandlerStub); firstPojoClassInstance = ValidationHelper.getMostCompleteInstance(pojoClass); secondPojoClassInstance = ValidationHelper.getMostCompleteInstance(pojoClass); // check one way identityHandlerStub.areEqualReturn = RandomFactory.getRandomValue(Boolean.class); checkEquality(); identityHandlerStub.areEqualReturn = !identityHandlerStub.areEqualReturn; checkEquality(); identityHandlerStub.doGenerateReturn = RandomFactory.getRandomValue(Integer.class); checkHashCode(); identityHandlerStub.doGenerateReturn = RandomFactory.getRandomValue(Integer.class); checkHashCode(); IdentityFactory.unregisterIdentityHandler(identityHandlerStub); } #location 8 #vulnerability type NULL_DEREFERENCE
#fixed code public void run(final PojoClass pojoClass) { Object instance1 = ValidationHelper.getMostCompleteInstance(pojoClass); Object instance2 = ValidationHelper.getMostCompleteInstance(pojoClass); IdentityHandlerStub identityHandlerStub = new IdentityHandlerStub(instance1, instance2); IdentityFactory.registerIdentityHandler(identityHandlerStub); // check one way identityHandlerStub.areEqualReturn = RandomFactory.getRandomValue(Boolean.class); checkEquality(instance1, instance2, identityHandlerStub); identityHandlerStub.areEqualReturn = !identityHandlerStub.areEqualReturn; checkEquality(instance1, instance2, identityHandlerStub); identityHandlerStub.doGenerateReturn = RandomFactory.getRandomValue(Integer.class); checkHashCode(instance1, identityHandlerStub); identityHandlerStub.doGenerateReturn = RandomFactory.getRandomValue(Integer.class); checkHashCode(instance1, identityHandlerStub); IdentityFactory.unregisterIdentityHandler(identityHandlerStub); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public Object doGenerate(final Class<?> type) { if (type == boolean.class || type == Boolean.class) { return RANDOM.nextBoolean(); } if (type == int.class || type == Integer.class) { return RANDOM.nextInt(); } if (type == BigInteger.class) { return BigInteger.valueOf(RANDOM.nextLong()); } if (type == float.class || type == Float.class) { return RANDOM.nextFloat(); } if (type == double.class || type == Double.class) { return RANDOM.nextDouble(); } if (type == BigDecimal.class) { return BigDecimal.valueOf(RANDOM.nextDouble()); } if (type == long.class || type == Long.class) { return RANDOM.nextLong(); } if (type == short.class || type == Short.class) { return (short) (RANDOM.nextInt(Short.MAX_VALUE + 1) * (RANDOM.nextBoolean() ? 1 : -1)); } if (type == byte.class || type == Byte.class) { final byte[] randombyte = new byte[1]; RANDOM.nextBytes(randombyte); return randombyte[0]; } if (type == char.class || type == Character.class) { return CHARACTERS[RANDOM.nextInt(CHARACTERS.length)]; } if (type == String.class) { String randomString = ""; /* prevent zero length string lengths */ for (int count = 0; count < RANDOM.nextInt(MAX_RANDOM_STRING_LENGTH + 1) + 1; count++) { randomString += RandomFactory.getRandomValue(Character.class); } return randomString; } if (type == Date.class) { return new Date(RandomFactory.getRandomValue(Long.class)); } if (type == Calendar.class) { final Calendar calendar = Calendar.getInstance(); calendar.setTimeInMillis(RandomFactory.getRandomValue(Long.class)); return calendar; } return null; } #location 60 #vulnerability type NULL_DEREFERENCE
#fixed code public Object doGenerate(final Class<?> type) { if (type == boolean.class || type == Boolean.class) { return RANDOM.nextBoolean(); } if (type == int.class || type == Integer.class) { return RANDOM.nextInt(); } if (type == BigInteger.class) { return BigInteger.valueOf(RANDOM.nextLong()); } if (type == float.class || type == Float.class) { return RANDOM.nextFloat(); } if (type == double.class || type == Double.class) { return RANDOM.nextDouble(); } if (type == BigDecimal.class) { return BigDecimal.valueOf(RANDOM.nextDouble()); } if (type == long.class || type == Long.class) { return RANDOM.nextLong(); } if (type == short.class || type == Short.class) { return (short) (RANDOM.nextInt(Short.MAX_VALUE + 1) * (RANDOM.nextBoolean() ? 1 : -1)); } if (type == byte.class || type == Byte.class) { final byte[] randomByte = new byte[1]; RANDOM.nextBytes(randomByte); return randomByte[0]; } if (type == char.class || type == Character.class) { return CHARACTERS[RANDOM.nextInt(CHARACTERS.length)]; } if (type == String.class) { String randomString = ""; /* prevent zero length string lengths */ for (int count = 0; count < RANDOM.nextInt(MAX_RANDOM_STRING_LENGTH + 1) + 1; count++) { randomString += RandomFactory.getRandomValue(Character.class); } return randomString; } if (type == Date.class) { return new Date(RANDOM.nextLong()); } if (type == Calendar.class) { final Calendar calendar = Calendar.getInstance(); calendar.setTimeInMillis(RANDOM.nextLong()); return calendar; } return null; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test(expected = ReflectionException.class) public void shouldFailSet() { PojoField pojoField = getPrivateStringField(); pojoField.set(null, RandomFactory.getRandomValue(pojoField.getType())); } #location 4 #vulnerability type NULL_DEREFERENCE
#fixed code @Test(expected = ReflectionException.class) public void shouldFailSet() { PojoField pojoField = getPrivateStringField(); assert pojoField != null; pojoField.set(null, RandomFactory.getRandomValue(pojoField.getType())); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public Object doGenerate(final Class<?> type) { if (type == boolean.class || type == Boolean.class) { return RANDOM.nextBoolean(); } if (type == int.class || type == Integer.class) { return RANDOM.nextInt(); } if (type == BigInteger.class) { return BigInteger.valueOf(RANDOM.nextLong()); } if (type == float.class || type == Float.class) { return RANDOM.nextFloat(); } if (type == double.class || type == Double.class) { return RANDOM.nextDouble(); } if (type == BigDecimal.class) { return BigDecimal.valueOf(RANDOM.nextDouble()); } if (type == long.class || type == Long.class) { return RANDOM.nextLong(); } if (type == short.class || type == Short.class) { return (short) (RANDOM.nextInt(Short.MAX_VALUE + 1) * (RANDOM.nextBoolean() ? 1 : -1)); } if (type == byte.class || type == Byte.class) { final byte[] randombyte = new byte[1]; RANDOM.nextBytes(randombyte); return randombyte[0]; } if (type == char.class || type == Character.class) { return CHARACTERS[RANDOM.nextInt(CHARACTERS.length)]; } if (type == String.class) { String randomString = ""; /* prevent zero length string lengths */ for (int count = 0; count < RANDOM.nextInt(MAX_RANDOM_STRING_LENGTH + 1) + 1; count++) { randomString += RandomFactory.getRandomValue(Character.class); } return randomString; } if (type == Date.class) { return new Date(RandomFactory.getRandomValue(Long.class)); } if (type == Calendar.class) { final Calendar calendar = Calendar.getInstance(); calendar.setTimeInMillis(RandomFactory.getRandomValue(Long.class)); return calendar; } return null; } #location 55 #vulnerability type NULL_DEREFERENCE
#fixed code public Object doGenerate(final Class<?> type) { if (type == boolean.class || type == Boolean.class) { return RANDOM.nextBoolean(); } if (type == int.class || type == Integer.class) { return RANDOM.nextInt(); } if (type == BigInteger.class) { return BigInteger.valueOf(RANDOM.nextLong()); } if (type == float.class || type == Float.class) { return RANDOM.nextFloat(); } if (type == double.class || type == Double.class) { return RANDOM.nextDouble(); } if (type == BigDecimal.class) { return BigDecimal.valueOf(RANDOM.nextDouble()); } if (type == long.class || type == Long.class) { return RANDOM.nextLong(); } if (type == short.class || type == Short.class) { return (short) (RANDOM.nextInt(Short.MAX_VALUE + 1) * (RANDOM.nextBoolean() ? 1 : -1)); } if (type == byte.class || type == Byte.class) { final byte[] randomByte = new byte[1]; RANDOM.nextBytes(randomByte); return randomByte[0]; } if (type == char.class || type == Character.class) { return CHARACTERS[RANDOM.nextInt(CHARACTERS.length)]; } if (type == String.class) { String randomString = ""; /* prevent zero length string lengths */ for (int count = 0; count < RANDOM.nextInt(MAX_RANDOM_STRING_LENGTH + 1) + 1; count++) { randomString += RandomFactory.getRandomValue(Character.class); } return randomString; } if (type == Date.class) { return new Date(RANDOM.nextLong()); } if (type == Calendar.class) { final Calendar calendar = Calendar.getInstance(); calendar.setTimeInMillis(RANDOM.nextLong()); return calendar; } return null; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void defaultRandomGeneratorServicePrePopulated() { // JDK 5 only supports 42 of the 44 possible types. (java.util.ArrayDeque does not exist in JDK5). String javaVersion = System.getProperty("java.version"); if (javaVersion.startsWith("1.6") || javaVersion.startsWith("1.7") || javaVersion.startsWith("1.8")) { System.out.println("Found that many types: " + expectedDefaultTypes.size()); for (Class<?> expectedEntry : expectedDefaultTypes) { boolean found = false; for (Class<?> foundEntry : randomGeneratorService.getRegisteredTypes()) { if (expectedEntry == foundEntry) found = true; } if (!found) System.out.println("\"" + expectedEntry.getName() + "\""); } System.out.println("Registered and not in the expected list!!"); for (Class<?> foundEntry : randomGeneratorService.getRegisteredTypes()) { boolean found = false; for (Class<?> expectedEntry : expectedDefaultTypes) { if (expectedEntry == foundEntry) found = true; } if (!found) System.out.println("\"" + foundEntry.getName() + "\""); } Affirm.affirmEquals("Types added / removed?", expectedTypes, randomGeneratorService.getRegisteredTypes().size()); } else { if (javaVersion.startsWith("1.5")) { Affirm.affirmEquals("Types added / removed?", expectedTypes - 1, // (java.util.ArrayDeque does not exist // in JDK5), randomGeneratorService.getRegisteredTypes().size()); } else { Affirm.fail("Unknown java version found " + System.getProperty("java.version") + " please check the " + "correct number of expected registered classes and register type here - (found " + randomGeneratorService .getRegisteredTypes().size() + ")"); } } } #location 5 #vulnerability type NULL_DEREFERENCE
#fixed code @Test public void defaultRandomGeneratorServicePrePopulated() { reportDifferences(); Affirm.affirmEquals("Types added / removed?", expectedTypes, randomGeneratorService.getRegisteredTypes().size()); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public static List<Class<?>> getClasses(final String packageName) { List<Class<?>> classes = new LinkedList<Class<?>>(); File directory = getPackageAsDirectory(packageName); for (File entry : directory.listFiles()) { if (isClass(entry.getName())) { Class<?> clazz = getPathEntryAsClass(packageName, entry.getName()); classes.add(clazz); } } return classes; } #location 6 #vulnerability type NULL_DEREFERENCE
#fixed code public static List<Class<?>> getClasses(final String packageName) { List<Class<?>> classes = new LinkedList<Class<?>>(); List<File> paths = getPackageDirectories(packageName); for (File path : paths) { for (File entry : path.listFiles()) { if (isClass(entry.getName())) { Class<?> clazz = getPathEntryAsClass(packageName, entry.getName()); classes.add(clazz); } } } return classes; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public int find(int[] numbers, int position) { validateInput(numbers, position); Integer result = null; Map<Integer, Integer> counter = new HashMap<Integer, Integer>(); for (int i : numbers) { if (counter.get(i) == null) { counter.put(i, 1); } else { counter.put(i, counter.get(i) + 1); } } for (Integer candidate : counter.keySet()) { if (counter.get(candidate) == position) { result = candidate; break; } } validateResult(result); return result; } #location 9 #vulnerability type NULL_DEREFERENCE
#fixed code public int find(int[] numbers, int position) { validateInput(numbers, position); Integer result = null; Map<Integer, Integer> counter = new LinkedHashMap<Integer, Integer>(); for (int i : numbers) { if (counter.get(i) == null) { counter.put(i, 1); } else { counter.put(i, counter.get(i) + 1); } } for (Integer candidate : counter.keySet()) { if (counter.get(candidate) == position) { result = candidate; break; } } validateResult(result); return result; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code private ElementSerializer startDoc( XmlSerializer serializer, Object element, boolean errorOnUnknown, String extraNamespace) throws IOException { serializer.startDocument(null, null); SortedSet<String> aliases = new TreeSet<String>(); computeAliases(element, aliases); boolean foundExtra = extraNamespace == null; for (String alias : aliases) { String uri = getUriForAlias(alias); serializer.setPrefix(alias, uri); if (!foundExtra && uri.equals(extraNamespace)) { foundExtra = true; } } if (!foundExtra) { for (Map.Entry<String, String> entry : getAliasToUriMap().entrySet()) { if (extraNamespace.equals(entry.getValue())) { serializer.setPrefix(entry.getKey(), extraNamespace); break; } } } return new ElementSerializer(element, errorOnUnknown); } #location 11 #vulnerability type NULL_DEREFERENCE
#fixed code private ElementSerializer startDoc( XmlSerializer serializer, Object element, boolean errorOnUnknown, String extraNamespace) throws IOException { serializer.startDocument(null, null); SortedSet<String> aliases = new TreeSet<String>(); computeAliases(element, aliases); boolean foundExtra = extraNamespace == null; for (String alias : aliases) { String uri = getNamespaceUriForAliasHandlingUnknown(errorOnUnknown, alias); serializer.setPrefix(alias, uri); if (!foundExtra && uri.equals(extraNamespace)) { foundExtra = true; } } if (!foundExtra) { for (Map.Entry<String, String> entry : getAliasToUriMap().entrySet()) { if (extraNamespace.equals(entry.getValue())) { serializer.setPrefix(entry.getKey(), extraNamespace); break; } } } return new ElementSerializer(element, errorOnUnknown); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @SuppressWarnings("unchecked") public static void parse(String content, Object data) { Class<?> clazz = data.getClass(); ClassInfo classInfo = ClassInfo.of(clazz); GenericData genericData = GenericData.class.isAssignableFrom(clazz) ? (GenericData) data : null; @SuppressWarnings("unchecked") Map<Object, Object> map = Map.class.isAssignableFrom(clazz) ? (Map<Object, Object>) data : null; int cur = 0; int length = content.length(); int nextEquals = content.indexOf('='); while (cur < length) { int amp = content.indexOf('&', cur); if (amp == -1) { amp = length; } String name; String stringValue; if (nextEquals != -1 && nextEquals < amp) { name = content.substring(cur, nextEquals); stringValue = CharEscapers.decodeUri(content.substring(nextEquals + 1, amp)); nextEquals = content.indexOf('=', amp + 1); } else { name = content.substring(cur, amp); stringValue = ""; } name = CharEscapers.decodeUri(name); // get the field from the type information FieldInfo fieldInfo = classInfo.getFieldInfo(name); if (fieldInfo != null) { Class<?> type = fieldInfo.type; if (Collection.class.isAssignableFrom(type)) { Collection<Object> collection = (Collection<Object>) fieldInfo.getValue(data); if (collection == null) { collection = ClassInfo.newCollectionInstance(type); fieldInfo.setValue(data, collection); } Class<?> subFieldClass = ClassInfo.getCollectionParameter(fieldInfo.field); collection.add(FieldInfo.parsePrimitiveValue(subFieldClass, stringValue)); } else { fieldInfo.setValue(data, FieldInfo.parsePrimitiveValue(type, stringValue)); } } else { ArrayList<String> listValue = (ArrayList<String>) map.get(name); if (listValue == null) { listValue = new ArrayList<String>(); if (genericData != null) { genericData.set(name, listValue); } else { map.put(name, listValue); } } listValue.add(stringValue); } cur = amp + 1; } } #location 43 #vulnerability type NULL_DEREFERENCE
#fixed code @SuppressWarnings("unchecked") public static void parse(String content, Object data) { Class<?> clazz = data.getClass(); ClassInfo classInfo = ClassInfo.of(clazz); GenericData genericData = GenericData.class.isAssignableFrom(clazz) ? (GenericData) data : null; @SuppressWarnings("unchecked") Map<Object, Object> map = Map.class.isAssignableFrom(clazz) ? (Map<Object, Object>) data : null; int cur = 0; int length = content.length(); int nextEquals = content.indexOf('='); while (cur < length) { int amp = content.indexOf('&', cur); if (amp == -1) { amp = length; } String name; String stringValue; if (nextEquals != -1 && nextEquals < amp) { name = content.substring(cur, nextEquals); stringValue = CharEscapers.decodeUri(content.substring(nextEquals + 1, amp)); nextEquals = content.indexOf('=', amp + 1); } else { name = content.substring(cur, amp); stringValue = ""; } name = CharEscapers.decodeUri(name); // get the field from the type information FieldInfo fieldInfo = classInfo.getFieldInfo(name); if (fieldInfo != null) { Class<?> type = fieldInfo.type; if (Collection.class.isAssignableFrom(type)) { Collection<Object> collection = (Collection<Object>) fieldInfo.getValue(data); if (collection == null) { collection = ClassInfo.newCollectionInstance(type); fieldInfo.setValue(data, collection); } Class<?> subFieldClass = ClassInfo.getCollectionParameter(fieldInfo.field); collection.add(FieldInfo.parsePrimitiveValue(subFieldClass, stringValue)); } else { fieldInfo.setValue(data, FieldInfo.parsePrimitiveValue(type, stringValue)); } } else if (map != null) { ArrayList<String> listValue = (ArrayList<String>) map.get(name); if (listValue == null) { listValue = new ArrayList<String>(); if (genericData != null) { genericData.set(name, listValue); } else { map.put(name, listValue); } } listValue.add(stringValue); } cur = amp + 1; } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public static void parse(String content, Object data) { if (content == null) { return; } Class<?> clazz = data.getClass(); ClassInfo classInfo = ClassInfo.of(clazz); GenericData genericData = GenericData.class.isAssignableFrom(clazz) ? (GenericData) data : null; @SuppressWarnings("unchecked") Map<Object, Object> map = Map.class.isAssignableFrom(clazz) ? (Map<Object, Object>) data : null; int cur = 0; int length = content.length(); int nextEquals = content.indexOf('='); while (cur < length) { int amp = content.indexOf('&', cur); if (amp == -1) { amp = length; } String name; String stringValue; if (nextEquals != -1 && nextEquals < amp) { name = content.substring(cur, nextEquals); stringValue = CharEscapers.decodeUri(content.substring(nextEquals + 1, amp)); nextEquals = content.indexOf('=', amp + 1); } else { name = content.substring(cur, amp); stringValue = ""; } name = CharEscapers.decodeUri(name); // get the field from the type information FieldInfo fieldInfo = classInfo.getFieldInfo(name); if (fieldInfo != null) { Class<?> type = fieldInfo.type; if (Collection.class.isAssignableFrom(type)) { @SuppressWarnings("unchecked") Collection<Object> collection = (Collection<Object>) fieldInfo.getValue(data); if (collection == null) { collection = ClassInfo.newCollectionInstance(type); fieldInfo.setValue(data, collection); } Class<?> subFieldClass = ClassInfo.getCollectionParameter(fieldInfo.field); collection.add(FieldInfo.parsePrimitiveValue(subFieldClass, stringValue)); } else { fieldInfo.setValue(data, FieldInfo.parsePrimitiveValue(type, stringValue)); } } else { @SuppressWarnings("unchecked") ArrayList<String> listValue = (ArrayList<String>) map.get(name); if (listValue == null) { listValue = new ArrayList<String>(); if (genericData != null) { genericData.set(name, listValue); } else { map.put(name, listValue); } } listValue.add(stringValue); } cur = amp + 1; } } #location 47 #vulnerability type NULL_DEREFERENCE
#fixed code public static void parse(String content, Object data) { if (content == null) { return; } Class<?> clazz = data.getClass(); ClassInfo classInfo = ClassInfo.of(clazz); GenericData genericData = GenericData.class.isAssignableFrom(clazz) ? (GenericData) data : null; @SuppressWarnings("unchecked") Map<Object, Object> map = Map.class.isAssignableFrom(clazz) ? (Map<Object, Object>) data : null; int cur = 0; int length = content.length(); int nextEquals = content.indexOf('='); while (cur < length) { int amp = content.indexOf('&', cur); if (amp == -1) { amp = length; } String name; String stringValue; if (nextEquals != -1 && nextEquals < amp) { name = content.substring(cur, nextEquals); stringValue = CharEscapers.decodeUri(content.substring(nextEquals + 1, amp)); nextEquals = content.indexOf('=', amp + 1); } else { name = content.substring(cur, amp); stringValue = ""; } name = CharEscapers.decodeUri(name); // get the field from the type information FieldInfo fieldInfo = classInfo.getFieldInfo(name); if (fieldInfo != null) { Class<?> type = fieldInfo.type; if (Collection.class.isAssignableFrom(type)) { @SuppressWarnings("unchecked") Collection<Object> collection = (Collection<Object>) fieldInfo.getValue(data); if (collection == null) { collection = ClassInfo.newCollectionInstance(type); fieldInfo.setValue(data, collection); } Class<?> subFieldClass = ClassInfo.getCollectionParameter(fieldInfo.field); collection.add(FieldInfo.parsePrimitiveValue(subFieldClass, stringValue)); } else { fieldInfo.setValue(data, FieldInfo.parsePrimitiveValue(type, stringValue)); } } else if (map != null) { @SuppressWarnings("unchecked") ArrayList<String> listValue = (ArrayList<String>) map.get(name); if (listValue == null) { listValue = new ArrayList<String>(); if (genericData != null) { genericData.set(name, listValue); } else { map.put(name, listValue); } } listValue.add(stringValue); } cur = amp + 1; } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void should_run_post_build() { ConfigSection afterRunSection = new AfterRunSection(configListOrSingleValue("spec integration1", "spec integration2")); Combination combination = new Combination(ImmutableMap.of("script", "post_build")); assertTrue(afterRunSection.toScript(combination, BuildType.BareMetal).toShellScript().contains("spec integration1")); } #location 6 #vulnerability type NULL_DEREFERENCE
#fixed code @Test public void should_run_post_build() { ConfigSection afterRunSection = new AfterRunSection(configListOrSingleValue("spec integration1", "spec integration2")); Combination combination = new Combination(ImmutableMap.of("script", "post_build")); assertTrue(afterRunSection.toScript(combination).toShellScript().contains("spec integration1")); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public Run getPreviousFinishedBuildOfSameBranch(BuildListener listener) { return new DynamicBuildRepository().getPreviousFinishedBuildOfSameBranch(this, getCurrentBranch().toString()); } #location 2 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code public Run getPreviousFinishedBuildOfSameBranch(BuildListener listener) { return SetupConfig.get().getDynamicBuildRepository() .getPreviousFinishedBuildOfSameBranch(this, getCurrentBranch().toString()); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public static byte[] loadBytes(String filename) { InputStream input = classLoader().getResourceAsStream(filename); if (input == null) { File file = new File(filename); if (file.exists()) { try { input = new FileInputStream(filename); } catch (FileNotFoundException e) { throw U.rte(e); } } } return input != null ? loadBytes(input) : null; } #location 16 #vulnerability type RESOURCE_LEAK
#fixed code public static byte[] loadBytes(String filename) { InputStream input = null; try { input = classLoader().getResourceAsStream(filename); if (input == null) { File file = new File(filename); if (file.exists()) { try { input = new FileInputStream(filename); } catch (FileNotFoundException e) { throw U.rte(e); } } } return input != null ? loadBytes(input) : null; } finally { close(input, true); } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Override public Object handle(HttpExchange x) throws Exception { String code = x.param("code"); String state = x.param("state"); U.debug("Received OAuth code", "code", code, "state", state); if (code != null && state != null) { U.must(stateCheck.isValidState(state, clientSecret, x.sessionId()), "Invalid OAuth state!"); String redirectUrl = oauthDomain != null ? oauthDomain + callbackPath : x.constructUrl(callbackPath); TokenRequestBuilder reqBuilder = OAuthClientRequest.tokenLocation(provider.getTokenEndpoint()) .setGrantType(GrantType.AUTHORIZATION_CODE).setClientId(clientId).setClientSecret(clientSecret) .setRedirectURI(redirectUrl).setCode(code); OAuthClientRequest request = paramsInBody() ? reqBuilder.buildBodyMessage() : reqBuilder.buildBodyMessage(); OAuthClient oAuthClient = new OAuthClient(new URLConnectionClient()); String accessToken = token(request, oAuthClient); String profileUrl = U.fillIn(provider.getProfileEndpoint(), "token", accessToken); OAuthClientRequest bearerClientRequest = new OAuthBearerClientRequest(profileUrl).setAccessToken( accessToken).buildQueryMessage(); OAuthResourceResponse res = oAuthClient.resource(bearerClientRequest, org.apache.oltu.oauth2.common.OAuth.HttpMethod.GET, OAuthResourceResponse.class); U.must(res.getResponseCode() == 200, "OAuth response error!"); Map<String, Object> auth = JSON.parseMap(res.getBody()); String firstName = (String) U.or(auth.get("firstName"), U.or(auth.get("first_name"), auth.get("given_name"))); String lastName = (String) U.or(auth.get("lastName"), U.or(auth.get("last_name"), auth.get("family_name"))); UserInfo user = new UserInfo(); user.name = U.or((String) auth.get("name"), firstName + " " + lastName); user.oauthProvider = provider.getName(); user.email = (String) U.or(auth.get("email"), auth.get("emailAddress")); user.username = user.email; user.oauthId = String.valueOf(auth.get("id")); user.display = user.email.substring(0, user.email.indexOf('@')); x.sessionSet("_user", user); U.must(x.user() == user); return x.redirect("/"); } else { String error = x.param("error"); if (error != null) { U.warn("OAuth error", "error", error); throw U.rte("OAuth error!"); } } throw U.rte("OAuth error!"); } #location 46 #vulnerability type NULL_DEREFERENCE
#fixed code @Override public Object handle(HttpExchange x) throws Exception { String code = x.param("code"); String state = x.param("state"); U.debug("Received OAuth code", "code", code, "state", state); if (code != null && state != null) { U.must(stateCheck.isValidState(state, clientSecret, x.sessionId()), "Invalid OAuth state!"); String redirectUrl = oauthDomain != null ? oauthDomain + callbackPath : x.constructUrl(callbackPath); TokenRequestBuilder reqBuilder = OAuthClientRequest.tokenLocation(provider.getTokenEndpoint()) .setGrantType(GrantType.AUTHORIZATION_CODE).setClientId(clientId).setClientSecret(clientSecret) .setRedirectURI(redirectUrl).setCode(code); OAuthClientRequest request = paramsInBody() ? reqBuilder.buildBodyMessage() : reqBuilder.buildBodyMessage(); OAuthClient oAuthClient = new OAuthClient(new URLConnectionClient()); String accessToken = token(request, oAuthClient); String profileUrl = U.fillIn(provider.getProfileEndpoint(), "token", accessToken); OAuthClientRequest bearerClientRequest = new OAuthBearerClientRequest(profileUrl).setAccessToken( accessToken).buildQueryMessage(); OAuthResourceResponse res = oAuthClient.resource(bearerClientRequest, org.apache.oltu.oauth2.common.OAuth.HttpMethod.GET, OAuthResourceResponse.class); U.must(res.getResponseCode() == 200, "OAuth response error!"); Map<String, Object> auth = JSON.parseMap(res.getBody()); String firstName = (String) U.or(auth.get("firstName"), U.or(auth.get("first_name"), auth.get("given_name"))); String lastName = (String) U.or(auth.get("lastName"), U.or(auth.get("last_name"), auth.get("family_name"))); UserInfo user = new UserInfo(); user.name = U.or((String) auth.get("name"), firstName + " " + lastName); user.oauthProvider = provider.getName(); user.email = (String) U.or(auth.get("email"), auth.get("emailAddress")); user.username = user.email; user.oauthId = String.valueOf(auth.get("id")); x.sessionSet("_user", user); U.must(x.user() == user); return x.redirect("/"); } else { String error = x.param("error"); if (error != null) { U.warn("OAuth error", "error", error); throw U.rte("OAuth error!"); } } throw U.rte("OAuth error!"); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; ScanParams that = (ScanParams) o; if (!Arrays.equals(packages, that.packages)) return false; if (matching != null ? !matching.equals(that.matching) : that.matching != null) return false; if (!Arrays.equals(annotated, that.annotated)) return false; return classLoader != null ? classLoader.equals(that.classLoader) : that.classLoader == null; } #location 8 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; ScanParams that = (ScanParams) o; if (!Arrays.equals(packages, that.packages)) return false; if (matching != null ? !matching.equals(that.matching) : that.matching != null) return false; if (!Arrays.equals(annotated, that.annotated)) return false; if (classLoader != null ? !classLoader.equals(that.classLoader) : that.classLoader != null) return false; if (!Arrays.equals(classpath, that.classpath)) return false; return bytecodeFilter != null ? bytecodeFilter.equals(that.bytecodeFilter) : that.bytecodeFilter == null; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Override public void reset() { super.reset(); isGet.value = false; isKeepAlive.value = false; verb.reset(); uri.reset(); path.reset(); query.reset(); protocol.reset(); body.reset(); multipartBoundary.reset(); params.reset(); headersKV.reset(); headers.reset(); cookies.reset(); data.reset(); files.reset(); parsedParams = false; parsedHeaders = false; parsedBody = false; total = -1; writesBody = false; bodyPos = -1; hasContentType = false; responses = null; responseCode = -1; } #location 28 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code @Override public void reset() { super.reset(); isGet.value = false; isKeepAlive.value = false; verb.reset(); uri.reset(); path.reset(); query.reset(); protocol.reset(); body.reset(); multipartBoundary.reset(); params.reset(); headersKV.reset(); headers.reset(); cookies.reset(); data.reset(); files.reset(); parsedParams = false; parsedHeaders = false; parsedBody = false; resetResponse(); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Override public void reset() { super.reset(); isGet.value = false; isKeepAlive.value = false; verb.reset(); uri.reset(); path.reset(); query.reset(); protocol.reset(); body.reset(); multipartBoundary.reset(); params.reset(); headersKV.reset(); headers.reset(); cookies.reset(); data.reset(); files.reset(); parsedParams = false; parsedHeaders = false; parsedBody = false; total = -1; writesBody = false; bodyPos = -1; hasContentType = false; responses = null; responseCode = -1; } #location 30 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code @Override public void reset() { super.reset(); isGet.value = false; isKeepAlive.value = false; verb.reset(); uri.reset(); path.reset(); query.reset(); protocol.reset(); body.reset(); multipartBoundary.reset(); params.reset(); headersKV.reset(); headers.reset(); cookies.reset(); data.reset(); files.reset(); parsedParams = false; parsedHeaders = false; parsedBody = false; resetResponse(); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Override public Object getParamValue(Req req, Class<?> paramType, String paramName, Map<String, Object> properties) throws Exception { return Customization.of(req).jackson().convertValue(properties, paramType); } #location 3 #vulnerability type NULL_DEREFERENCE
#fixed code @Override public Object getParamValue(Req req, Class<?> paramType, String paramName, Map<String, Object> properties) throws Exception { return Customization.of(req).objectMapper().convertValue(properties, paramType); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Override public void reset() { super.reset(); isGet.value = false; isKeepAlive.value = false; verb.reset(); uri.reset(); path.reset(); query.reset(); protocol.reset(); body.reset(); multipartBoundary.reset(); params.reset(); headersKV.reset(); headers.reset(); cookies.reset(); data.reset(); files.reset(); parsedParams = false; parsedHeaders = false; parsedBody = false; total = -1; writesBody = false; bodyPos = -1; hasContentType = false; responses = null; startedResponse = false; responseCode = -1; } #location 32 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code @Override public void reset() { super.reset(); isGet.value = false; isKeepAlive.value = false; verb.reset(); uri.reset(); path.reset(); query.reset(); protocol.reset(); body.reset(); multipartBoundary.reset(); params.reset(); headersKV.reset(); headers.reset(); cookies.reset(); data.reset(); files.reset(); parsedParams = false; parsedHeaders = false; parsedBody = false; total = -1; writesBody = false; bodyPos = -1; hasContentType = false; responses = null; responseCode = -1; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public static Db db() { assert U.must(defaultDb != null, "Database not initialized!"); return defaultDb; } #location 3 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code public static Db db() { assert U.must(db != null, "Database not initialized!"); return db; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code private Set<String> userRoles(Req req, String username) { if (username != null) { try { return req.routes().custom().rolesProvider().getRolesForUser(req, username); } catch (Exception e) { throw U.rte(e); } } else { return Collections.emptySet(); } } #location 4 #vulnerability type NULL_DEREFERENCE
#fixed code private Set<String> userRoles(Req req, String username) { if (username != null) { try { return Customization.of(req).rolesProvider().getRolesForUser(req, username); } catch (Exception e) { throw U.rte(e); } } else { return Collections.emptySet(); } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Override public int hashCode() { int result = Arrays.hashCode(packages); result = 31 * result + (matching != null ? matching.hashCode() : 0); result = 31 * result + Arrays.hashCode(annotated); result = 31 * result + (classLoader != null ? classLoader.hashCode() : 0); return result; } #location 6 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code @Override public int hashCode() { int result = Arrays.hashCode(packages); result = 31 * result + (matching != null ? matching.hashCode() : 0); result = 31 * result + Arrays.hashCode(annotated); result = 31 * result + (classLoader != null ? classLoader.hashCode() : 0); result = 31 * result + Arrays.hashCode(classpath); result = 31 * result + (bytecodeFilter != null ? bytecodeFilter.hashCode() : 0); return result; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Override public void renderJson(Req req, Object value, OutputStream out) throws Exception { req.custom().jackson().writeValue(out, value); } #location 3 #vulnerability type NULL_DEREFERENCE
#fixed code @Override public void renderJson(Req req, Object value, OutputStream out) throws Exception { Customization.of(req).jackson().writeValue(out, value); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test(timeout = 30000) public void testJDBCWithTextConfig() { Conf.JDBC.set("driver", "org.h2.Driver"); Conf.JDBC.set("url", "jdbc:h2:mem:mydb"); Conf.JDBC.set("username", "sa"); Conf.C3P0.set("maxPoolSize", "123"); JDBC.defaultApi().pooled(); JdbcClient jdbc = JDBC.defaultApi(); eq(jdbc.driver(), "org.h2.Driver"); C3P0ConnectionPool pool = (C3P0ConnectionPool) JDBC.defaultApi().pool(); ComboPooledDataSource c3p0 = pool.pool(); eq(c3p0.getMinPoolSize(), 5); eq(c3p0.getMaxPoolSize(), 123); JDBC.execute("create table abc (id int, name varchar)"); JDBC.execute("insert into abc values (?, ?)", 123, "xyz"); final Map<String, ?> expected = U.map("id", 123, "name", "xyz"); Msc.benchmarkMT(100, "select", 100000, () -> { Map<String, Object> record = U.single(JDBC.query("select id, name from abc")); record = Msc.lowercase(record); eq(record, expected); }); } #location 15 #vulnerability type NULL_DEREFERENCE
#fixed code @Test(timeout = 30000) public void testJDBCWithTextConfig() { Conf.JDBC.set("driver", "org.h2.Driver"); Conf.JDBC.set("url", "jdbc:h2:mem:mydb"); Conf.JDBC.set("username", "sa"); Conf.C3P0.set("maxPoolSize", "123"); JdbcClient jdbc = JDBC.defaultApi(); eq(jdbc.driver(), "org.h2.Driver"); C3P0ConnectionPool pool = (C3P0ConnectionPool) JDBC.defaultApi().init().pool(); ComboPooledDataSource c3p0 = pool.pool(); eq(c3p0.getMinPoolSize(), 5); eq(c3p0.getMaxPoolSize(), 123); JDBC.execute("create table abc (id int, name varchar)"); JDBC.execute("insert into abc values (?, ?)", 123, "xyz"); final Map<String, ?> expected = U.map("id", 123, "name", "xyz"); Msc.benchmarkMT(100, "select", 100000, () -> { Map<String, Object> record = U.single(JDBC.query("select id, name from abc")); record = Msc.lowercase(record); eq(record, expected); }); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public void complete(Channel ctx, boolean isKeepAlive, Req req, Object result) { if (result == null) { http.notFound(ctx, isKeepAlive, this, req); return; // not found } if (result instanceof HttpStatus) { complete(ctx, isKeepAlive, req, U.rte("HttpStatus result is not supported!")); return; } if (result instanceof Throwable) { HttpIO.errorAndDone(req, (Throwable) result, Customization.of(req).errorHandler()); return; } else { HttpUtils.resultToResponse(req, result); } // the Req object will do the rendering if (!req.isAsync()) { req.done(); } } #location 14 #vulnerability type NULL_DEREFERENCE
#fixed code public void complete(Channel ctx, boolean isKeepAlive, Req req, Object result) { if (result == null) { http.notFound(ctx, isKeepAlive, this, req); return; // not found } if (result instanceof HttpStatus) { complete(ctx, isKeepAlive, req, U.rte("HttpStatus result is not supported!")); return; } if (result instanceof Throwable) { HttpIO.errorAndDone(req, (Throwable) result); return; } else { HttpUtils.resultToResponse(req, result); } // the Req object will do the rendering if (!req.isAsync()) { req.done(); } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test(timeout = 30000) public void testHikariPool() { JdbcClient jdbc = JDBC.api(); jdbc.h2("hikari-test"); jdbc.pool(new HikariConnectionPool(jdbc)); jdbc.execute("create table abc (id int, name varchar)"); jdbc.execute("insert into abc values (?, ?)", 123, "xyz"); final Map<String, ?> expected = U.map("id", 123, "name", "xyz"); Msc.benchmarkMT(100, "select", 100000, () -> { Map<String, Object> record = U.single(JDBC.query("select id, name from abc").all()); record = Msc.lowercase(record); eq(record, expected); }); isTrue(jdbc.pool() instanceof HikariConnectionPool); } #location 6 #vulnerability type RESOURCE_LEAK
#fixed code @Test(timeout = 30000) public void testHikariPool() { Conf.HIKARI.set("maximumPoolSize", 234); JdbcClient jdbc = JDBC.api(); jdbc.h2("hikari-test"); jdbc.dataSource(HikariFactory.createDataSourceFor(jdbc)); jdbc.execute("create table abc (id int, name varchar)"); jdbc.execute("insert into abc values (?, ?)", 123, "xyz"); final Map<String, ?> expected = U.map("id", 123, "name", "xyz"); Msc.benchmarkMT(100, "select", 100000, () -> { Map<String, Object> record = U.single(JDBC.query("select id, name from abc").all()); record = Msc.lowercase(record); eq(record, expected); }); HikariDataSource hikari = (HikariDataSource) jdbc.dataSource(); eq(hikari.getMaximumPoolSize(), 234); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Override public void reset() { super.reset(); isGet.value = false; isKeepAlive.value = false; verb.reset(); uri.reset(); path.reset(); query.reset(); protocol.reset(); body.reset(); multipartBoundary.reset(); params.reset(); headersKV.reset(); headers.reset(); cookies.reset(); data.reset(); files.reset(); parsedParams = false; parsedHeaders = false; parsedBody = false; total = -1; writesBody = false; bodyPos = -1; hasContentType = false; responses = null; responseCode = -1; } #location 29 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code @Override public void reset() { super.reset(); isGet.value = false; isKeepAlive.value = false; verb.reset(); uri.reset(); path.reset(); query.reset(); protocol.reset(); body.reset(); multipartBoundary.reset(); params.reset(); headersKV.reset(); headers.reset(); cookies.reset(); data.reset(); files.reset(); parsedParams = false; parsedHeaders = false; parsedBody = false; resetResponse(); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; ScanParams that = (ScanParams) o; if (!Arrays.equals(packages, that.packages)) return false; if (matching != null ? !matching.equals(that.matching) : that.matching != null) return false; if (!Arrays.equals(annotated, that.annotated)) return false; return classLoader != null ? classLoader.equals(that.classLoader) : that.classLoader == null; } #location 9 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; ScanParams that = (ScanParams) o; if (!Arrays.equals(packages, that.packages)) return false; if (matching != null ? !matching.equals(that.matching) : that.matching != null) return false; if (!Arrays.equals(annotated, that.annotated)) return false; if (classLoader != null ? !classLoader.equals(that.classLoader) : that.classLoader != null) return false; if (!Arrays.equals(classpath, that.classpath)) return false; return bytecodeFilter != null ? bytecodeFilter.equals(that.bytecodeFilter) : that.bytecodeFilter == null; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public static Object emit(HttpExchange x) { int event = U.num(x.data("event")); TagContext ctx = x.session(SESSION_CTX, null); // if the context has been lost, reload the page if (ctx == null) { return changes(x, PAGE_RELOAD); } Cmd cmd = ctx.getEventCmd(event); if (cmd != null) { Map<Integer, Object> inp = Pages.inputs(x); ctx.emitValues(inp); } else { U.warn("Invalid event!", "event", event); } Object page = U.newInstance(currentPage(x)); Pages.load(x, page); callCmdHandler(x, page, cmd); ctx = Tags.context(); x.sessionSet(Pages.SESSION_CTX, ctx); Object content = Pages.contentOf(x, page); if (content == null || content instanceof HttpExchange) { return content; } String html = PageRenderer.get().toHTML(ctx, content, x); Pages.store(x, page); return changes(x, html); } #location 23 #vulnerability type NULL_DEREFERENCE
#fixed code public static Object emit(HttpExchange x) { int event = U.num(x.data("event")); TagContext ctx = x.session(SESSION_CTX, null); // if the context has been lost, reload the page if (ctx == null) { return changes(x, PAGE_RELOAD); } Cmd cmd = ctx.getEventCmd(event); if (cmd != null) { Map<Integer, Object> inp = Pages.inputs(x); ctx.emitValues(inp); } else { U.warn("Invalid event!", "event", event); } Object page = U.newInstance(currentPage(x)); Pages.load(x, page); if (cmd != null) { callCmdHandler(x, page, cmd); } ctx = Tags.context(); x.sessionSet(Pages.SESSION_CTX, ctx); Object content = Pages.contentOf(x, page); if (content == null || content instanceof HttpExchange) { return content; } String html = PageRenderer.get().toHTML(ctx, content, x); Pages.store(x, page); return changes(x, html); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Override public String get() { return count > 0 ? String.format("[%s..%s..%s]/%s", min, sum / count, max, count) : null; } #location 3 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code @Override public String get() { return count > 0 ? String.format("%s:[%s..%s..%s]#%s", sum, min, sum / count, max, count) : "" + ticks; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public void complete(Channel ctx, boolean isKeepAlive, Req req, Object result) { if (result == null) { http.notFound(ctx, isKeepAlive, this, req); return; // not found } if (result instanceof HttpStatus) { complete(ctx, isKeepAlive, req, U.rte("HttpStatus result is not supported!")); return; } if (result instanceof Throwable) { HttpIO.errorAndDone(req, (Throwable) result, req.routes().custom().errorHandler()); return; } else { HttpUtils.resultToResponse(req, result); } // the Req object will do the rendering if (!req.isAsync()) { req.done(); } } #location 14 #vulnerability type NULL_DEREFERENCE
#fixed code public void complete(Channel ctx, boolean isKeepAlive, Req req, Object result) { if (result == null) { http.notFound(ctx, isKeepAlive, this, req); return; // not found } if (result instanceof HttpStatus) { complete(ctx, isKeepAlive, req, U.rte("HttpStatus result is not supported!")); return; } if (result instanceof Throwable) { HttpIO.errorAndDone(req, (Throwable) result, Customization.of(req).errorHandler()); return; } else { HttpUtils.resultToResponse(req, result); } // the Req object will do the rendering if (!req.isAsync()) { req.done(); } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Override public HttpExchangeBody goBack(int steps) { List<String> stack = session(SESSION_PAGE_STACK, null); String dest = !stack.isEmpty() ? stack.get(stack.size() - 1) : "/"; for (int i = 0; i < steps; i++) { if (stack != null && !stack.isEmpty()) { stack.remove(stack.size() - 1); if (!stack.isEmpty()) { dest = stack.remove(stack.size() - 1); } } } return redirect(dest); } #location 5 #vulnerability type NULL_DEREFERENCE
#fixed code @Override public HttpExchangeBody goBack(int steps) { String dest = "/"; List<String> stack = session(SESSION_PAGE_STACK, null); if (stack != null) { if (!stack.isEmpty()) { dest = stack.get(stack.size() - 1); } for (int i = 0; i < steps; i++) { if (!stack.isEmpty()) { stack.remove(stack.size() - 1); if (!stack.isEmpty()) { dest = stack.remove(stack.size() - 1); } } } } return redirect(dest); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code private byte[] responseToBytes() { try { return response.renderToBytes(); } catch (Throwable e) { HttpIO.error(this, e, Customization.of(this).errorHandler()); try { return response.renderToBytes(); } catch (Exception e1) { Log.error("Internal rendering error!", e1); return HttpUtils.getErrorMessageAndSetCode(response, e1).getBytes(); } } } #location 6 #vulnerability type NULL_DEREFERENCE
#fixed code private byte[] responseToBytes() { try { return response.renderToBytes(); } catch (Throwable e) { HttpIO.error(this, e); try { return response.renderToBytes(); } catch (Exception e1) { Log.error("Internal rendering error!", e1); return HttpUtils.getErrorMessageAndSetCode(response, e1).getBytes(); } } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public Future<byte[]> get(String uri, Callback<byte[]> callback) { HttpGet req = new HttpGet(uri); Log.debug("Starting HTTP GET request", "request", req.getRequestLine()); return execute(client, req, callback); } #location 6 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code public Future<byte[]> get(String uri, Callback<byte[]> callback) { return request("GET", uri, null, null, null, null, null, callback); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public void process(Channel ctx) { if (ctx.isInitial()) { return; } Buf buf = ctx.input(); RapidoidHelper helper = ctx.helper(); Range[] ranges = helper.ranges1.ranges; Ranges hdrs = helper.ranges2; BoolWrap isGet = helper.booleans[0]; BoolWrap isKeepAlive = helper.booleans[1]; Range verb = ranges[ranges.length - 1]; Range uri = ranges[ranges.length - 2]; Range path = ranges[ranges.length - 3]; Range query = ranges[ranges.length - 4]; Range protocol = ranges[ranges.length - 5]; Range body = ranges[ranges.length - 6]; HTTP_PARSER.parse(buf, isGet, isKeepAlive, body, verb, uri, path, query, protocol, hdrs, helper); HttpStatus status = HttpStatus.NOT_FOUND; FastHttpHandler handler = findFandler(ctx, buf, isGet, verb, path); if (handler != null) { Map<String, Object> params = null; if (handler.needsParams()) { params = U.map(); KeyValueRanges paramsKV = helper.pairs1.reset(); KeyValueRanges headersKV = helper.pairs2.reset(); HTTP_PARSER.parseParams(buf, paramsKV, query); // parse URL parameters as data Map<String, Object> data = U.cast(paramsKV.toMap(buf, true, true)); if (!isGet.value) { KeyValueRanges postedKV = helper.pairs3.reset(); KeyValueRanges filesKV = helper.pairs4.reset(); // parse posted body as data HTTP_PARSER.parsePosted(buf, headersKV, body, postedKV, filesKV, helper, data); } // filter special data values Map<String, Object> special = findSpecialData(data); if (special != null) { data.keySet().removeAll(special.keySet()); } else { special = U.cast(Collections.EMPTY_MAP); } // put all data directly as parameters params.putAll(data); params.put(DATA, data); params.put(SPECIAL, special); // finally, the HTTP info params.put(VERB, verb.str(buf)); params.put(URI, uri.str(buf)); params.put(PATH, path.str(buf)); params.put(CLIENT_ADDRESS, ctx.address()); if (handler.needsHeadersAndCookies()) { KeyValueRanges cookiesKV = helper.pairs5.reset(); HTTP_PARSER.parseHeadersIntoKV(buf, hdrs, headersKV, cookiesKV, helper); Map<String, Object> headers = U.cast(headersKV.toMap(buf, true, true)); Map<String, Object> cookies = U.cast(cookiesKV.toMap(buf, true, true)); params.put(HEADERS, headers); params.put(COOKIES, cookies); params.put(HOST, U.get(headers, "Host", null)); params.put(FORWARDED_FOR, U.get(headers, "X-Forwarded-For", null)); } } status = handler.handle(ctx, isKeepAlive.value, params); } if (status == HttpStatus.NOT_FOUND) { ctx.write(HTTP_404_NOT_FOUND); } if (status != HttpStatus.ASYNC) { ctx.closeIf(!isKeepAlive.value); } } #location 26 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code public void process(Channel ctx) { if (ctx.isInitial()) { return; } Buf buf = ctx.input(); RapidoidHelper helper = ctx.helper(); Range[] ranges = helper.ranges1.ranges; Ranges hdrs = helper.ranges2; BoolWrap isGet = helper.booleans[0]; BoolWrap isKeepAlive = helper.booleans[1]; Range verb = ranges[ranges.length - 1]; Range uri = ranges[ranges.length - 2]; Range path = ranges[ranges.length - 3]; Range query = ranges[ranges.length - 4]; Range protocol = ranges[ranges.length - 5]; Range body = ranges[ranges.length - 6]; HTTP_PARSER.parse(buf, isGet, isKeepAlive, body, verb, uri, path, query, protocol, hdrs, helper); // the listener may override all the request dispatching and handler execution if (!listener.request(this, ctx, isGet, isKeepAlive, body, verb, uri, path, query, protocol, hdrs)) { return; } HttpStatus status = HttpStatus.NOT_FOUND; FastHttpHandler handler = findFandler(ctx, buf, isGet, verb, path); if (handler != null) { Map<String, Object> params = null; if (handler.needsParams()) { params = U.map(); KeyValueRanges paramsKV = helper.pairs1.reset(); KeyValueRanges headersKV = helper.pairs2.reset(); HTTP_PARSER.parseParams(buf, paramsKV, query); // parse URL parameters as data Map<String, Object> data = U.cast(paramsKV.toMap(buf, true, true)); if (!isGet.value) { KeyValueRanges postedKV = helper.pairs3.reset(); KeyValueRanges filesKV = helper.pairs4.reset(); // parse posted body as data HTTP_PARSER.parsePosted(buf, headersKV, body, postedKV, filesKV, helper, data); } // filter special data values Map<String, Object> special = findSpecialData(data); if (special != null) { data.keySet().removeAll(special.keySet()); } else { special = U.cast(Collections.EMPTY_MAP); } // put all data directly as parameters params.putAll(data); params.put(DATA, data); params.put(SPECIAL, special); // finally, the HTTP info params.put(VERB, verb.str(buf)); params.put(URI, uri.str(buf)); params.put(PATH, path.str(buf)); params.put(CLIENT_ADDRESS, ctx.address()); if (handler.needsHeadersAndCookies()) { KeyValueRanges cookiesKV = helper.pairs5.reset(); HTTP_PARSER.parseHeadersIntoKV(buf, hdrs, headersKV, cookiesKV, helper); Map<String, Object> headers = U.cast(headersKV.toMap(buf, true, true)); Map<String, Object> cookies = U.cast(cookiesKV.toMap(buf, true, true)); params.put(HEADERS, headers); params.put(COOKIES, cookies); params.put(HOST, U.get(headers, "Host", null)); params.put(FORWARDED_FOR, U.get(headers, "X-Forwarded-For", null)); } } status = handler.handle(ctx, isKeepAlive.value, params); } if (status == HttpStatus.NOT_FOUND) { ctx.write(HTTP_404_NOT_FOUND); listener.notFound(this, ctx, isGet, isKeepAlive, body, verb, uri, path, query, protocol, hdrs); } if (status != HttpStatus.ASYNC) { ctx.closeIf(!isKeepAlive.value); } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code private void addInfo(List<Object> info, final GroupOf<?> group, List<? extends Manageable> items, List<String> columns) { columns.add("(Actions)"); final String groupName = group.name(); String type = U.first(items).getManageableType(); info.add(breadcrumb(type, groupName)); Grid grid = grid(items) .columns(columns) .headers(columns) .toUri(new Mapper<Manageable, String>() { @Override public String map(Manageable handle) throws Exception { return Msc.uri("_manageables", handle.getClass().getSimpleName(), Msc.urlEncode(handle.id())); } }) .pageSize(20); info.add(grid); } #location 5 #vulnerability type NULL_DEREFERENCE
#fixed code private void addInfo(List<Object> info, final GroupOf<?> group, List<? extends Manageable> items, List<String> columns) { columns.add("(Actions)"); final String groupName = group.name(); final String kind = group.kind(); info.add(breadcrumb(kind, groupName)); Grid grid = grid(items) .columns(columns) .headers(columns) .toUri(new Mapper<Manageable, String>() { @Override public String map(Manageable handle) throws Exception { return Msc.specialUri("manageables", kind, Msc.urlEncode(handle.id())); } }) .pageSize(20); info.add(grid); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; ScanParams that = (ScanParams) o; if (!Arrays.equals(packages, that.packages)) return false; if (matching != null ? !matching.equals(that.matching) : that.matching != null) return false; if (!Arrays.equals(annotated, that.annotated)) return false; return classLoader != null ? classLoader.equals(that.classLoader) : that.classLoader == null; } #location 10 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; ScanParams that = (ScanParams) o; if (!Arrays.equals(packages, that.packages)) return false; if (matching != null ? !matching.equals(that.matching) : that.matching != null) return false; if (!Arrays.equals(annotated, that.annotated)) return false; if (classLoader != null ? !classLoader.equals(that.classLoader) : that.classLoader != null) return false; if (!Arrays.equals(classpath, that.classpath)) return false; return bytecodeFilter != null ? bytecodeFilter.equals(that.bytecodeFilter) : that.bytecodeFilter == null; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code private static List<Class<?>> getClassesFromJAR(String jarName, List<Class<?>> classes, String pkg, Pattern regex, Predicate<Class<?>> filter, Class<? extends Annotation> annotated, ClassLoader classLoader) { try { String pkgPath = pkgToPath(pkg); ZipInputStream zip = new ZipInputStream(new URL("file://" + jarName).openStream()); ZipEntry e; while ((e = zip.getNextEntry()) != null) { if (!e.isDirectory()) { String name = e.getName(); if (!ignore(name)) { if (U.isEmpty(pkg) || name.startsWith(pkgPath)) { scanFile(classes, regex, filter, annotated, classLoader, name); } } } } } catch (Exception e) { throw U.rte(e); } return classes; } #location 20 #vulnerability type RESOURCE_LEAK
#fixed code private static List<Class<?>> getClassesFromJAR(String jarName, List<Class<?>> classes, String pkg, Pattern regex, Predicate<Class<?>> filter, Class<? extends Annotation> annotated, ClassLoader classLoader) { ZipInputStream zip = null; try { String pkgPath = pkgToPath(pkg); File jarFile = new File(jarName); FileInputStream jarInputStream = new FileInputStream(jarFile); zip = new ZipInputStream(jarInputStream); ZipEntry e; while ((e = zip.getNextEntry()) != null) { if (!e.isDirectory()) { String name = e.getName(); if (!ignore(name)) { if (U.isEmpty(pkg) || name.startsWith(pkgPath)) { scanFile(classes, regex, filter, annotated, classLoader, name); } } } } } catch (Exception e) { Log.error("Cannot scan JAR: " + jarName, e); } finally { if (zip != null) { try { zip.close(); } catch (IOException e) { Log.error("Couldn't close the ZIP stream!", e); } } } return classes; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public static String load(String filename) { return new String(loadBytes(filename)); } #location 2 #vulnerability type NULL_DEREFERENCE
#fixed code public static String load(String filename) { byte[] bytes = loadBytes(filename); return bytes != null ? new String(bytes) : null; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @SuppressWarnings("unchecked") public static WebApp bootstrap(WebApp app, String[] args, Object... config) { Log.info("Starting Rapidoid...", "version", RapidoidInfo.version()); ConfigHelp.processHelp(args); // FIXME make optional // print internal state // LoggerContext lc = (LoggerContext) LoggerFactory.getILoggerFactory(); Conf.init(args, config); Log.info("Working directory is: " + System.getProperty("user.dir")); inferAndSetRootPackage(); if (app == null) { app = AppTool.createRootApp(); } registerDefaultPlugins(); Set<String> configArgs = U.set(args); for (Object arg : config) { processArg(configArgs, arg); } String[] configArgsArr = configArgs.toArray(new String[configArgs.size()]); Conf.args(configArgsArr); Log.args(configArgsArr); AOP.reset(); AOP.intercept(new AuthInterceptor(), Admin.class, Manager.class, Moderator.class, LoggedIn.class, DevMode.class, Role.class, HasRole.class); return app; } #location 26 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code @SuppressWarnings("unchecked") public static WebApp bootstrap(WebApp app, String[] args, Object... config) { Log.info("Starting Rapidoid...", "version", RapidoidInfo.version()); ConfigHelp.processHelp(args); // FIXME make optional // print internal state // LoggerContext lc = (LoggerContext) LoggerFactory.getILoggerFactory(); Conf.init(args, config); Log.info("Working directory is: " + System.getProperty("user.dir")); inferAndSetRootPackage(); if (app == null) { app = AppTool.createRootApp(); } registerDefaultPlugins(); Set<String> configArgs = U.set(args); for (Object arg : config) { processArg(configArgs, arg); } String[] configArgsArr = configArgs.toArray(new String[configArgs.size()]); Conf.args(configArgsArr); Log.args(configArgsArr); AOP.reset(); AOP.intercept(new AuthInterceptor(), Admin.class, Manager.class, Moderator.class, LoggedIn.class, DevMode.class, Role.class, HasRole.class); return app; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Override public Object call() throws Exception { List<Object> info = U.list(); for (GroupOf<?> group : Groups.all()) { List<? extends Manageable> items = group.items(); if (U.notEmpty(items)) { List<String> columns = U.first(items).getManageableProperties(); if (U.notEmpty(columns)) { addInfo(info, group, items, columns); } } } info.add(autoRefresh(2000)); return multi(info); } #location 9 #vulnerability type NULL_DEREFERENCE
#fixed code @Override public Object call() throws Exception { List<Object> info = U.list(); Collection<? extends GroupOf<?>> targetGroups = groups != null ? groups : Groups.all(); for (GroupOf<?> group : targetGroups) { List<? extends Manageable> items = group.items(); List<String> nav = U.list(group.kind()); info.add(h2(group.kind())); addInfo(baseUri, info, nav, items); } info.add(autoRefresh(2000)); return multi(info); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void shouldParseRequest1() { ReqData req = parse(REQ1); BufGroup bufs = new BufGroup(2); Buf reqbuf = bufs.from(REQ1, "r2"); eq(REQ1, req.rVerb, "GET"); eq(REQ1, req.rPath, "/foo/bar"); eqs(REQ1, req.params, "a", "5", "b", "", "n", "%20"); eq(req.params.toMap(reqbuf, true, true, false), U.map("a", "5", "b", "", "n", " ")); eq(REQ1, req.rProtocol, "HTTP/1.1"); eqs(REQ1, req.headersKV, "Host", "www.test.com", "Set-Cookie", "aaa=2"); isNone(req.rBody); } #location 11 #vulnerability type RESOURCE_LEAK
#fixed code @Test public void shouldParseRequest1() { RapidoidHelper req = parse(REQ1); BufGroup bufs = new BufGroup(2); Buf reqbuf = bufs.from(REQ1, "r2"); eq(REQ1, req.verb, "GET"); eq(REQ1, req.path, "/foo/bar"); eqs(REQ1, req.params, "a", "5", "b", "", "n", "%20"); eq(req.params.toMap(reqbuf, true, true, false), U.map("a", "5", "b", "", "n", " ")); eq(REQ1, req.protocol, "HTTP/1.1"); eqs(REQ1, req.headersKV, "Host", "www.test.com", "Set-Cookie", "aaa=2"); isNone(req.body); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code private static void generateIndex(String path) { System.out.println(); System.out.println(); System.out.println("*************** " + path); System.out.println(); System.out.println(); List<Map<String, ?>> examples = U.list(); IntWrap nn = new IntWrap(); List<String> eglist = IO.loadLines("examples.txt"); List<String> processed = processAll(examples, nn, eglist); System.out.println("Processed: " + processed); Map<String, ?> model = U.map("examples", examples); String html = Templates.fromFile("docs.html").render(model); IO.save(path + "index.html", html); } #location 13 #vulnerability type NULL_DEREFERENCE
#fixed code private static void generateIndex(String path) { System.out.println(); System.out.println(); System.out.println("*************** " + path); System.out.println(); System.out.println(); List<Map<String, ?>> examplesl = U.list(); IntWrap nl = new IntWrap(); List<String> eglistl = IO.loadLines("examplesl.txt"); processAll(examplesl, nl, eglistl); List<Map<String, ?>> examplesh = U.list(); IntWrap nh = new IntWrap(); List<String> eglisth = IO.loadLines("examplesh.txt"); processAll(examplesh, nh, eglisth); Map<String, ?> model = U.map("examplesh", examplesh, "examplesl", examplesl, "version", UTILS.version() .replace("-SNAPSHOT", "")); String html = Templates.fromFile("docs.html").render(model); IO.save(path + "index.html", html); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Override public int hashCode() { int result = Arrays.hashCode(packages); result = 31 * result + (matching != null ? matching.hashCode() : 0); result = 31 * result + Arrays.hashCode(annotated); result = 31 * result + (classLoader != null ? classLoader.hashCode() : 0); return result; } #location 3 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code @Override public int hashCode() { int result = Arrays.hashCode(packages); result = 31 * result + (matching != null ? matching.hashCode() : 0); result = 31 * result + Arrays.hashCode(annotated); result = 31 * result + (classLoader != null ? classLoader.hashCode() : 0); result = 31 * result + Arrays.hashCode(classpath); result = 31 * result + (bytecodeFilter != null ? bytecodeFilter.hashCode() : 0); return result; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Override public void render(Req req, Object value, OutputStream out) throws Exception { Customization.of(req).jacksonXml().writeValue(out, value); } #location 3 #vulnerability type NULL_DEREFERENCE
#fixed code @Override public void render(Req req, Object value, OutputStream out) throws Exception { Customization.of(req).xmlMapper().writeValue(out, value); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Override protected void doProcessing() { long now = U.time(); int connectingN = connecting.size(); for (int i = 0; i < connectingN; i++) { ConnectionTarget target = connecting.poll(); assert target != null; if (target.retryAfter < now) { Log.debug("connecting", "address", target.addr); try { SelectionKey newKey = target.socketChannel.register(selector, SelectionKey.OP_CONNECT); newKey.attach(target); } catch (ClosedChannelException e) { Log.warn("Closed channel", e); } } else { connecting.add(target); } } RapidoidChannel channel; while ((channel = connected.poll()) != null) { SocketChannel socketChannel = channel.socketChannel; Log.debug("connected", "address", socketChannel.socket().getRemoteSocketAddress()); try { SelectionKey newKey = socketChannel.register(selector, SelectionKey.OP_READ); RapidoidConnection conn = attachConn(newKey, channel.protocol); conn.setClient(channel.isClient); try { processNext(conn, true); } finally { conn.setInitial(false); } } catch (ClosedChannelException e) { Log.warn("Closed channel", e); } } RapidoidConnection restartedConn; while ((restartedConn = restarting.poll()) != null) { Log.debug("restarting", "connection", restartedConn); processNext(restartedConn, true); } synchronized (done) { for (int i = 0; i < done.size(); i++) { RapidoidConnection conn = done.get(i); if (conn.key != null && conn.key.isValid()) { conn.key.interestOps(SelectionKey.OP_WRITE); } } done.clear(); } } #location 38 #vulnerability type NULL_DEREFERENCE
#fixed code @Override protected void doProcessing() { long now = U.time(); int connectingN = connecting.size(); for (int i = 0; i < connectingN; i++) { ConnectionTarget target = connecting.poll(); assert target != null; if (target.retryAfter < now) { Log.debug("connecting", "address", target.addr); try { SelectionKey newKey = target.socketChannel.register(selector, SelectionKey.OP_CONNECT); newKey.attach(target); } catch (ClosedChannelException e) { Log.warn("Closed channel", e); } } else { connecting.add(target); } } RapidoidChannel channel; while ((channel = connected.poll()) != null) { SocketChannel socketChannel = channel.socketChannel; Log.debug("connected", "address", socketChannel.socket().getRemoteSocketAddress()); try { SelectionKey newKey = socketChannel.register(selector, SelectionKey.OP_READ); U.notNull(channel.protocol, "protocol"); RapidoidConnection conn = attachConn(newKey, channel.protocol); conn.setClient(channel.isClient); try { processNext(conn, true); } finally { conn.setInitial(false); } } catch (ClosedChannelException e) { Log.warn("Closed channel", e); } } RapidoidConnection restartedConn; while ((restartedConn = restarting.poll()) != null) { Log.debug("restarting", "connection", restartedConn); processNext(restartedConn, true); } synchronized (done) { for (int i = 0; i < done.size(); i++) { RapidoidConnection conn = done.get(i); if (conn.key != null && conn.key.isValid()) { conn.key.interestOps(SelectionKey.OP_WRITE); } } done.clear(); } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code protected void verifyCase(String info, String actual, String testCaseName) { String s = File.separator; String resname = "results" + s + testName() + s + getTestMethodName() + s + testCaseName; String filename = "src" + s + "test" + s + "resources" + s + resname; if (ADJUST_RESULTS) { File testDir = new File(filename).getParentFile(); if (!testDir.exists()) { testDir.mkdirs(); } FileOutputStream out = null; try { out = new FileOutputStream(filename); out.write(actual.getBytes()); out.close(); } catch (IOException e) { throw new RuntimeException(e); } } else { byte[] bytes = loadRes(resname); String expected = bytes != null ? new String(bytes) : ""; check(info, actual, expected); } } #location 18 #vulnerability type RESOURCE_LEAK
#fixed code protected void verifyCase(String info, String actual, String testCaseName) { String s = File.separator; String resname = "results" + s + testName() + s + getTestMethodName() + s + testCaseName; String filename = "src" + s + "test" + s + "resources" + s + resname; if (ADJUST_RESULTS) { File testDir = new File(filename).getParentFile(); if (!testDir.exists()) { if (!testDir.mkdirs()) { throw new RuntimeException("Couldn't create the test result folder: " + testDir.getAbsolutePath()); } } FileOutputStream out; try { out = new FileOutputStream(filename); out.write(actual.getBytes()); out.close(); } catch (IOException e) { throw new RuntimeException(e); } } else { byte[] bytes = loadRes(resname); String expected = bytes != null ? new String(bytes) : ""; check(info, actual, expected); } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code private boolean handleError(Channel channel, boolean isKeepAlive, ReqImpl req, MediaType contentType, Throwable e) { if (req != null) { if (!req.isStopped()) { HttpIO.errorAndDone(req, e); } return true; } else { Log.error("Low-level HTTP handler error!", e); HttpIO.startResponse(channel, 500, isKeepAlive, contentType); byte[] bytes = HttpUtils.responseToBytes(req, "Internal Server Error!", contentType, routes()[0].custom().jsonResponseRenderer()); HttpIO.writeContentLengthAndBody(channel, bytes); HttpIO.done(channel, isKeepAlive); } return false; } #location 11 #vulnerability type NULL_DEREFERENCE
#fixed code private boolean handleError(Channel channel, boolean isKeepAlive, ReqImpl req, MediaType contentType, Throwable e) { if (req != null) { if (!req.isStopped()) { try { HttpIO.errorAndDone(req, e); } catch (Exception e1) { Log.error("HTTP error handler error!", e1); internalServerError(channel, isKeepAlive, req, contentType); } } return true; } else { Log.error("Low-level HTTP handler error!", e); internalServerError(channel, isKeepAlive, req, contentType); } return false; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Override public int hashCode() { int result = Arrays.hashCode(packages); result = 31 * result + (matching != null ? matching.hashCode() : 0); result = 31 * result + Arrays.hashCode(annotated); result = 31 * result + (classLoader != null ? classLoader.hashCode() : 0); return result; } #location 4 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code @Override public int hashCode() { int result = Arrays.hashCode(packages); result = 31 * result + (matching != null ? matching.hashCode() : 0); result = 31 * result + Arrays.hashCode(annotated); result = 31 * result + (classLoader != null ? classLoader.hashCode() : 0); result = 31 * result + Arrays.hashCode(classpath); result = 31 * result + (bytecodeFilter != null ? bytecodeFilter.hashCode() : 0); return result; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test(timeout = 30000) public void testHikariPool() { JdbcClient jdbc = JDBC.api(); jdbc.h2("hikari-test"); jdbc.pool(new HikariConnectionPool(jdbc)); jdbc.execute("create table abc (id int, name varchar)"); jdbc.execute("insert into abc values (?, ?)", 123, "xyz"); final Map<String, ?> expected = U.map("id", 123, "name", "xyz"); Msc.benchmarkMT(100, "select", 100000, () -> { Map<String, Object> record = U.single(JDBC.query("select id, name from abc").all()); record = Msc.lowercase(record); eq(record, expected); }); isTrue(jdbc.pool() instanceof HikariConnectionPool); } #location 19 #vulnerability type RESOURCE_LEAK
#fixed code @Test(timeout = 30000) public void testHikariPool() { Conf.HIKARI.set("maximumPoolSize", 234); JdbcClient jdbc = JDBC.api(); jdbc.h2("hikari-test"); jdbc.dataSource(HikariFactory.createDataSourceFor(jdbc)); jdbc.execute("create table abc (id int, name varchar)"); jdbc.execute("insert into abc values (?, ?)", 123, "xyz"); final Map<String, ?> expected = U.map("id", 123, "name", "xyz"); Msc.benchmarkMT(100, "select", 100000, () -> { Map<String, Object> record = U.single(JDBC.query("select id, name from abc").all()); record = Msc.lowercase(record); eq(record, expected); }); HikariDataSource hikari = (HikariDataSource) jdbc.dataSource(); eq(hikari.getMaximumPoolSize(), 234); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code private static <T> void invokePostConstruct(T target) { List<Method> methods = Cls.getMethodsAnnotated(target.getClass(), Init.class); for (Method method : methods) { Cls.invoke(null, method, target); } } #location 5 #vulnerability type NULL_DEREFERENCE
#fixed code private static <T> void invokePostConstruct(T target) { List<Method> methods = Cls.getMethodsAnnotated(target.getClass(), Init.class); for (Method method : methods) { Cls.invoke(method, target); } }
Below is the vulnerable code, please generate the patch based on the following information.