output
stringlengths
79
30.1k
instruction
stringclasses
1 value
input
stringlengths
216
28.9k
#fixed code public void reputation(final String uid, final int rep) throws IOException { this.checkExisting(uid); try (final Item item = this.item()) { new Xocument(item.path()).modify( new Directives().xpath( String.format( "/people/person[@id='%s']", uid ) ).addIf("reputation").set(rep) ); } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public void reputation(final String uid, final int rep) throws IOException { if (!this.exists(uid)) { throw new IllegalArgumentException( new Par("Person @%s doesn't exist").say(uid) ); } try (final Item item = this.item()) { new Xocument(item.path()).modify( new Directives().xpath( String.format( "/people/person[@id='%s']", uid ) ).addIf("reputation").set(rep) ); } } #location 5 #vulnerability type RESOURCE_LEAK
#fixed code @Test public void rendersDebts() throws Exception { final Farm farm = FkFarm.props(); final Debts debts = new Debts(farm).bootstrap(); final String uid = "yegor256"; final String first = "details 1"; final String second = "details 2"; final String price = "$9.99"; final String amount = "$3.33"; final String reason = "reason"; debts.add(uid, new Cash.S(price), first, reason); debts.add(uid, new Cash.S(amount), second, reason); final String html = new View(farm, String.format("/u/%s", uid)).html(); MatcherAssert.assertThat( html, Matchers.allOf( XhtmlMatchers.hasXPaths( new FormattedText( "//xhtml:td[.='%s (%s)']", first, reason ).asString() ), XhtmlMatchers.hasXPaths( new FormattedText( "//xhtml:td[.='%s (%s)']", second, reason ).asString() ), XhtmlMatchers.hasXPaths( new FormattedText("//xhtml:td[.='%s']", price).asString() ), XhtmlMatchers.hasXPaths( new FormattedText("//xhtml:td[.='%s']", amount).asString() ) ) ); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void rendersDebts() throws Exception { final Farm farm = new PropsFarm(new FkFarm()); final Debts debts = new Debts(farm).bootstrap(); final String uid = "yegor256"; final String first = "details 1"; final String second = "details 2"; final String price = "$9.99"; final String amount = "$3.33"; final String reason = "reason"; debts.add(uid, new Cash.S(price), first, reason); debts.add(uid, new Cash.S(amount), second, reason); final String html = new View(farm, String.format("/u/%s", uid)).html(); MatcherAssert.assertThat( html, Matchers.allOf( XhtmlMatchers.hasXPaths( new FormattedText( "//xhtml:td[.='%s (%s)']", first, reason ).asString() ), XhtmlMatchers.hasXPaths( new FormattedText( "//xhtml:td[.='%s (%s)']", second, reason ).asString() ), XhtmlMatchers.hasXPaths( new FormattedText("//xhtml:td[.='%s']", price).asString() ), XhtmlMatchers.hasXPaths( new FormattedText("//xhtml:td[.='%s']", amount).asString() ) ) ); } #location 13 #vulnerability type RESOURCE_LEAK
#fixed code @Test public void receiveMessages() throws Exception { final Project project = new FkProject(); final Farm farm = new PropsFarm(new FkFarm(project)); final AmazonSQS sqs = new ExtSqs(farm).value(); final String queue = new ClaimsQueueUrl(farm).asString(); final ClaimsSqs claims = new ClaimsSqs(sqs, queue, project); final List<Message> messages = new CopyOnWriteArrayList<>(); final ClaimsRoutine routine = new ClaimsRoutine( farm, msgs -> { messages.addAll(msgs); new And( (Message msg) -> sqs.deleteMessage( queue, msg.getReceiptHandle() ), msgs ).value(); } ); routine.start(); TimeUnit.SECONDS.sleep((long) Tv.FIVE); final String type = "test"; new ClaimOut() .type(type) .param("nonce1", System.nanoTime()) .postTo(claims); new ClaimOut() .type("delayed") .until(Duration.ofMinutes(1L)) .param("nonce2", System.nanoTime()) .postTo(claims); TimeUnit.SECONDS.sleep((long) Tv.FIVE); routine.close(); MatcherAssert.assertThat( "expected one message", messages, Matchers.hasSize(1) ); final Message message = messages.get(0); MatcherAssert.assertThat( "invalid project", new SqsProject(farm, message).pid(), Matchers.equalTo(project.pid()) ); final ClaimIn claim = new ClaimIn( new XMLDocument(message.getBody()).nodes("//claim").get(0) ); MatcherAssert.assertThat( claim.type(), Matchers.equalTo(type) ); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void receiveMessages() throws Exception { final Project project = new FkProject(); final Farm farm = new PropsFarm(new FkFarm(project)); final AmazonSQS sqs = new ExtSqs(farm).value(); final String queue = new ClaimsQueueUrl(farm).asString(); final ClaimsSqs claims = new ClaimsSqs(sqs, queue, project); final List<Message> messages = new CopyOnWriteArrayList<>(); final ClaimsRoutine routine = new ClaimsRoutine( farm, msgs -> { messages.addAll(msgs); new And( (Message msg) -> sqs.deleteMessage( queue, msg.getReceiptHandle() ), msgs ).value(); } ); routine.start(); TimeUnit.SECONDS.sleep((long) Tv.FIVE); final String type = "test"; new ClaimOut() .type(type) .param("nonce", System.currentTimeMillis()) .postTo(claims); TimeUnit.SECONDS.sleep((long) Tv.FIVE); routine.close(); MatcherAssert.assertThat( "didn't receive", messages, Matchers.hasSize(1) ); final Message message = messages.get(0); MatcherAssert.assertThat( "invalid project", new SqsProject(farm, message).pid(), Matchers.equalTo(project.pid()) ); final ClaimIn claim = new ClaimIn( new XMLDocument(message.getBody()).nodes("//claim").get(0) ); MatcherAssert.assertThat( claim.type(), Matchers.equalTo(type) ); } #location 29 #vulnerability type RESOURCE_LEAK
#fixed code public boolean published(final String pid) throws IOException { this.checkExist(pid); try (final Item item = this.item()) { return Boolean.parseBoolean( new Xocument(item).xpath( String.format( "/catalog/project[@id='%s']/publish/text()", pid ) ).get(0) ); } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public boolean published(final String pid) throws IOException { if (!this.exists(pid)) { throw new IllegalArgumentException( new Par( "Project \"%s\" doesn't exist, can't check publish" ).say(pid) ); } try (final Item item = this.item()) { return Boolean.parseBoolean( new Xocument(item).xpath( String.format( "/catalog/project[@id='%s']/publish/text()", pid ) ).get(0) ); } } #location 6 #vulnerability type RESOURCE_LEAK
#fixed code Model(Matrix wi, Matrix wo, Args args, int seed) { hidden_ = new Vector(args.dim); output_ = new Vector(wo.m_); grad_ = new Vector(args.dim); random = new Random(seed); wi_ = wi; wo_ = wo; args_ = args; isz_ = wi.m_; osz_ = wo.m_; hsz_ = args.dim; negpos = 0; loss_ = 0.0f; nexamples_ = 1; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code float binaryLogistic(int target, boolean label, float lr) { float score = sigmoid(wo_.dotRow(hidden_, target)); float alpha = lr * (label ? 1f : 0f - score); grad_.addRow(wo_, target, alpha); synchronized (this) { wo_.addRow(hidden_, target, alpha); } if (label) { return -log(score); } else { return -log(1.0f - score); } } #location 6 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code Model(Matrix wi, Matrix wo, Args args, int seed) { hidden_ = new Vector(args.dim); output_ = new Vector(wo.m_); grad_ = new Vector(args.dim); random = new Random(seed); wi_ = wi; wo_ = wo; args_ = args; isz_ = wi.m_; osz_ = wo.m_; hsz_ = args.dim; negpos = 0; loss_ = 0.0f; nexamples_ = 1; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code int getNegative(int target) { int negative; do { negative = negatives[negpos]; negpos = (negpos + 1) % negatives.length; } while (target == negative); return negative; } #location 5 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code Model(Matrix wi, Matrix wo, Args args, int seed) { hidden_ = new Vector(args.dim); output_ = new Vector(wo.m_); grad_ = new Vector(args.dim); random = new Random(seed); wi_ = wi; wo_ = wo; args_ = args; isz_ = wi.m_; osz_ = wo.m_; hsz_ = args.dim; negpos = 0; loss_ = 0.0f; nexamples_ = 1; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code void update(int[] input, int target, float lr) { assert (target >= 0); assert (target < osz_); if (input.length == 0) return; computeHidden(input, hidden_); if (args_.loss == Args.loss_name.ns) { loss_ += negativeSampling(target, lr); } else if (args_.loss == Args.loss_name.hs) { loss_ += hierarchicalSoftmax(target, lr); } else { loss_ += softmax(target, lr); } nexamples_ += 1; if (args_.model == Args.model_name.sup) { grad_.mul(1.0f / input.length); } synchronized (this) { for (int i : input) { wi_.addRow(grad_, i, 1.0f); } } } #location 7 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code void internalClose() throws IOException { if (!closed) { closed = true; backend.rrdClose(); } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code void realClose() throws IOException { if (!closed) { closed = true; backend.rrdClose(); } } #location 3 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code private void testFile(String file, String version) throws IOException { URL url = getClass().getResource(file); RRDatabase rrd = new RRDatabase(url.getFile()); Assert.assertEquals("Invalid date", new Date(920808900000L), rrd.getLastUpdate()); Assert.assertEquals("Invalid number of archives", 2, rrd.getNumArchives()); Assert.assertEquals("Invalid number of datasources", 2, rrd.getDataSourcesName().size()); Assert.assertEquals("Invalid heartbeat for datasource 0", 600, rrd.getDataSource(0).getMinimumHeartbeat()); Assert.assertEquals("Invalid heartbeat for datasource 1", 600, rrd.getDataSource(1).getMinimumHeartbeat()); Assert.assertEquals("Invalid version", version, rrd.header.getVersion()); Assert.assertEquals("Invalid number of row", 24, rrd.getArchive(0).getRowCount()); Assert.assertEquals("Invalid number of row", 10, rrd.getArchive(1).getRowCount()); boolean b0 = "12405".equals(rrd.getDataSource(0).getPDPStatusBlock().lastReading); boolean b1 = "UNKN".equals(rrd.getDataSource(1).getPDPStatusBlock().lastReading); boolean b2 = "3".equals(rrd.getDataSource(1).getPDPStatusBlock().lastReading); Assert.assertTrue("Failed getting last reading", b0 && (b1 || b2)); if("0003".equals(version) ) { Assert.assertEquals("bad primary value", 1.43161853E7, rrd.getArchive(0).getCDPStatusBlock(0).primary_value, 1); } Assert.assertEquals("bad primary value", 1.4316557620000001E7, rrd.getArchive(1).getCDPStatusBlock(0).value, 1); rrd.rrdFile.seek( rrd.getArchive(0).dataOffset + 16 * rrd.getArchive(0).currentRow); double speed = readDouble(rrd.rrdFile); double weight = readDouble(rrd.rrdFile); Assert.assertEquals(1.4316185300e+07, speed, 1e-7); Assert.assertEquals(3, weight, 1e-7); DataChunk data = rrd.getData(ConsolidationFunctionType.AVERAGE, 920802300, 920808900, 300); Assert.assertEquals(0.02, data.toPlottable("speed").getValue(920802300), 1e-7); Assert.assertEquals(1.0, data.toPlottable("weight").getValue(920802300), 1e-7); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code private void testFile(String file, String version) throws IOException { URL url = getClass().getResource(file); RRDatabase rrd = new RRDatabase(url.getFile()); Assert.assertEquals("Invalid date", new Date(920808900000L), rrd.getLastUpdate()); Assert.assertEquals("Invalid number of archives", 2, rrd.getNumArchives()); Assert.assertEquals("Invalid number of datasources", 2, rrd.getDataSourcesName().size()); Assert.assertEquals("Invalid heartbeat for datasource 0", 600, rrd.getDataSource(0).getMinimumHeartbeat()); Assert.assertEquals("Invalid heartbeat for datasource 1", 600, rrd.getDataSource(1).getMinimumHeartbeat()); Assert.assertEquals("Invalid version", version, rrd.header.getVersion()); Assert.assertEquals("Invalid number of row", 24, rrd.getArchive(0).getRowCount()); Assert.assertEquals("Invalid number of row", 10, rrd.getArchive(1).getRowCount()); boolean b0 = "12405".equals(rrd.getDataSource(0).getPDPStatusBlock().lastReading); boolean b1 = "UNKN".equals(rrd.getDataSource(1).getPDPStatusBlock().lastReading); boolean b2 = "3".equals(rrd.getDataSource(1).getPDPStatusBlock().lastReading); Assert.assertTrue("Failed getting last reading", b0 && (b1 || b2)); if("0003".equals(version) ) { Assert.assertEquals("bad primary value", 1.43161853E7, rrd.getArchive(0).getCDPStatusBlock(0).primary_value, 1); } Assert.assertEquals("bad primary value", 1.4316557620000001E7, rrd.getArchive(1).getCDPStatusBlock(0).value, 1); rrd.rrdFile.ras.seek( rrd.getArchive(0).dataOffset + 16 * rrd.getArchive(0).currentRow); double speed = readDouble(rrd.rrdFile); double weight = readDouble(rrd.rrdFile); Assert.assertEquals(1.4316185300e+07, speed, 1e-7); Assert.assertEquals(3, weight, 1e-7); DataChunk data = rrd.getData(ConsolidationFunctionType.AVERAGE, 920802300, 920808900, 300); Assert.assertEquals(0.02, data.toPlottable("speed").getValue(920802300), 1e-7); Assert.assertEquals(1.0, data.toPlottable("weight").getValue(920802300), 1e-7); } #location 3 #vulnerability type RESOURCE_LEAK
#fixed code public RrdDb requestRrdDb(String path) throws IOException { RrdEntry ref = null; try { ref = getEntry(path, true); } catch (InterruptedException e) { throw new RuntimeException("request interrupted for " + path, e); } //Someone might have already open it, rechecks if(ref.count == 0) { try { ref.rrdDb = new RrdDb(path); } catch (IOException e) { //Don't forget to release the slot reserved earlier usage.decrementAndGet(); passNext(ACTION.DROP, ref); throw e; } } ref.count++; passNext(ACTION.SWAP, ref); return ref.rrdDb; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public RrdDb requestRrdDb(String path) throws IOException { RrdEntry ref = null; try { ref = getEntry(path, true); } catch (InterruptedException e) { throw new RuntimeException("request interrupted for " + path, e); } try { //Wait until the pool is not full and //Don't lock on anything while(ref.count == 0 && ! tryGetSlot()) { passNext(ACTION.SWAP, ref); countLock.lockInterruptibly(); full.await(); countLock.unlock(); ref = getEntry(path, true); } } catch (InterruptedException e) { passNext(ACTION.DROP, ref); throw new RuntimeException("request interrupted for " + path, e); } finally { if(countLock.isHeldByCurrentThread()) { countLock.unlock(); } } //Someone might have already open it, rechecks if(ref.count == 0) { try { ref.rrdDb = new RrdDb(path); } catch (IOException e) { //Don't forget to release the slot reserved earlier usage.decrementAndGet(); passNext(ACTION.DROP, ref); throw e; } } ref.count++; passNext(ACTION.SWAP, ref); return ref.rrdDb; } #location 29 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code @Test public void testBackendFactory() throws IOException { File rrdfile = testFolder.newFile("testfile"); try(RrdSafeFileBackendFactory factory = new RrdSafeFileBackendFactory()) { super.testBackendFactory(factory,rrdfile.getCanonicalPath()); } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void testBackendFactory() throws IOException { RrdRandomAccessFileBackendFactory factory = (RrdRandomAccessFileBackendFactory) RrdBackendFactory.getFactory("SAFE"); File rrdfile = testFolder.newFile("testfile"); RrdBackend be = factory.open(rrdfile.getCanonicalPath(), false); be.setLength(10); be.writeDouble(0, 0); be.close(); DataInputStream is = new DataInputStream(new FileInputStream(rrdfile)); Double d = is.readDouble(); Assert.assertEquals("write to random access file failed", 0, d, 1e-10); is.close(); } #location 15 #vulnerability type RESOURCE_LEAK
#fixed code @Test public void testEntriesNeg50To0InRrd() throws IOException, FontFormatException { createGaugeRrd(100); RrdDb rrd = RrdDb.getBuilder().setPath(jrbFileName).build(); for(int i=0; i<50; i++) { long timestamp = startTime + 1 + (i * 60); Sample sample = rrd.createSample(); sample.setAndUpdate(timestamp + ":" + (i -50)); } rrd.close(); prepareGraph(); expectMinorGridLines(2); expectMajorGridLine(" -40"); expectMinorGridLines(3); expectMajorGridLine(" -20"); expectMinorGridLines(3); run(); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void testEntriesNeg50To0InRrd() throws IOException, FontFormatException { createGaugeRrd(100); RrdDb rrd = new RrdDb(jrbFileName); for(int i=0; i<50; i++) { long timestamp = startTime + 1 + (i * 60); Sample sample = rrd.createSample(); sample.setAndUpdate(timestamp + ":" + (i -50)); } rrd.close(); prepareGraph(); expectMinorGridLines(2); expectMajorGridLine(" -40"); expectMinorGridLines(3); expectMajorGridLine(" -20"); expectMinorGridLines(3); run(); } #location 10 #vulnerability type RESOURCE_LEAK
#fixed code @Test public void testTwoEntriesInRrd() throws IOException, FontFormatException { createGaugeRrd(100); RrdDb rrd = RrdDb.getBuilder().setPath(jrbFileName).build(); for(int i=0; i<2; i++) { long timestamp = startTime + 1 + (i * 60); Sample sample = rrd.createSample(); sample.setAndUpdate(timestamp+":100"); } rrd.close(); prepareGraph(); expectMajorGridLine(" 90"); expectMinorGridLines(1); expectMajorGridLine(" 100"); expectMinorGridLines(1); expectMajorGridLine(" 110"); expectMinorGridLines(1); expectMajorGridLine(" 120"); expectMinorGridLines(1); run(); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void testTwoEntriesInRrd() throws IOException, FontFormatException { createGaugeRrd(100); RrdDb rrd = new RrdDb(jrbFileName); for(int i=0; i<2; i++) { long timestamp = startTime + 1 + (i * 60); Sample sample = rrd.createSample(); sample.setAndUpdate(timestamp+":100"); } rrd.close(); prepareGraph(); expectMajorGridLine(" 90"); expectMinorGridLines(1); expectMajorGridLine(" 100"); expectMinorGridLines(1); expectMajorGridLine(" 110"); expectMinorGridLines(1); expectMajorGridLine(" 120"); expectMinorGridLines(1); run(); } #location 10 #vulnerability type RESOURCE_LEAK
#fixed code @Test public void testEntriesZeroTo100InRrd() throws IOException, FontFormatException { createGaugeRrd(105); //Make sure all entries are recorded (5 is just a buffer for consolidation) RrdDb rrd = RrdDb.getBuilder().setPath(jrbFileName).build(); for(int i=0; i<100; i++) { long timestamp = startTime + 1 + (i * 60); Sample sample = rrd.createSample(); sample.setAndUpdate(timestamp + ":" + i); } rrd.close(); prepareGraph(); expectMinorGridLines(4); expectMajorGridLine(" 50"); expectMinorGridLines(4); expectMajorGridLine(" 100"); run(); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void testEntriesZeroTo100InRrd() throws IOException, FontFormatException { createGaugeRrd(105); //Make sure all entries are recorded (5 is just a buffer for consolidation) RrdDb rrd = new RrdDb(jrbFileName); for(int i=0; i<100; i++) { long timestamp = startTime + 1 + (i * 60); Sample sample = rrd.createSample(); sample.setAndUpdate(timestamp + ":" + i); } rrd.close(); prepareGraph(); expectMinorGridLines(4); expectMajorGridLine(" 50"); expectMinorGridLines(4); expectMajorGridLine(" 100"); run(); } #location 10 #vulnerability type RESOURCE_LEAK
#fixed code @Test public void testBackendFactoryDefaults() throws IOException { try (RrdNioBackendFactory factory = new RrdNioBackendFactory(0)) { File rrdfile = testFolder.newFile("testfile"); super.testBackendFactory(factory,rrdfile.getCanonicalPath()); } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void testBackendFactoryDefaults() throws IOException { // Don't close a default NIO, it will close the background sync threads executor @SuppressWarnings("resource") RrdNioBackendFactory factory = new RrdNioBackendFactory(); File rrdfile = testFolder.newFile("testfile"); super.testBackendFactory(factory,rrdfile.getCanonicalPath()); } #location 5 #vulnerability type RESOURCE_LEAK
#fixed code public void testXhtmlParsing() throws Exception { String path = "/test-documents/testXHTML.html"; Metadata metadata = new Metadata(); String content = Tika.parseToString( HtmlParserTest.class.getResourceAsStream(path), metadata); assertEquals("application/xhtml+xml", metadata.get(Metadata.CONTENT_TYPE)); assertEquals("XHTML test document", metadata.get(Metadata.TITLE)); assertEquals("Tika Developers", metadata.get("Author")); assertEquals("5", metadata.get("refresh")); assertTrue(content.contains("ability of Apache Tika")); assertTrue(content.contains("extract content")); assertTrue(content.contains("an XHTML document")); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public void testXhtmlParsing() throws Exception { Parser parser = new AutoDetectParser(); // Should auto-detect! ContentHandler handler = new BodyContentHandler(); Metadata metadata = new Metadata(); InputStream stream = HtmlParserTest.class.getResourceAsStream( "/test-documents/testXHTML.html"); try { parser.parse(stream, handler, metadata); } finally { stream.close(); } assertEquals("application/xhtml+xml", metadata.get(Metadata.CONTENT_TYPE)); assertEquals("XHTML test document", metadata.get(Metadata.TITLE)); String content = handler.toString(); assertEquals("Tika Developers", metadata.get("Author")); assertEquals("5", metadata.get("refresh")); assertTrue(content.contains("ability of Apache Tika")); assertTrue(content.contains("extract content")); assertTrue(content.contains("an XHTML document")); } #location 9 #vulnerability type NULL_DEREFERENCE
#fixed code @Before public void before() throws Throwable { save(new Properties() {{ setProperty("someValue", "10"); }}); reloadableConfig = ConfigFactory.create(ReloadableConfig.class); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Before public void before() throws Throwable { synchronized (target) { save(new Properties() {{ setProperty("someValue", "10"); }}); reloadableConfig = ConfigFactory.create(ReloadableConfig.class); } } #location 3 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code @Test public void testReload() throws Throwable { assertEquals(Integer.valueOf(10), reloadableConfig.someValue()); save(new Properties() {{ setProperty("someValue", "20"); }}); reloadableConfig.reload(); assertEquals(Integer.valueOf(20), reloadableConfig.someValue()); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void testReload() throws Throwable { assertEquals(Integer.valueOf(10), reloadableConfig.someValue()); synchronized (target) { save(new Properties() {{ setProperty("someValue", "20"); }}); reloadableConfig.reload(); } assertEquals(Integer.valueOf(20), reloadableConfig.someValue()); } #location 5 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code public static void save(File target, Properties p) throws IOException { File parent = target.getParentFile(); parent.mkdirs(); if (isWindows()) { store(target, p); } else { File tempFile = createTempFile(target.getName(), ".temp", parent); store(tempFile, p); rename(tempFile, target); } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public static void save(File target, Properties p) throws IOException { File parent = target.getParentFile(); parent.mkdirs(); if (isWindows()) { store(new FileOutputStream(target), p); } else { File tempFile = createTempFile(target.getName(), ".temp", parent); store(new FileOutputStream(tempFile), p); rename(tempFile, target); } } #location 8 #vulnerability type RESOURCE_LEAK
#fixed code LoadersManager() { registerLoader(new PropertiesLoader()); registerLoader(new XMLLoader()); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code InputStream getInputStream(URL url) throws IOException { URLConnection conn = url.openConnection(); if (conn == null) return null; return conn.getInputStream(); } #location 5 #vulnerability type RESOURCE_LEAK
#fixed code @Override public Object execute() { // Configure command before execution introspector.getHystrixProperties() .entrySet() .forEach(entry -> setProperty(entry.getKey(), entry.getValue())); // Ensure our internal state is consistent with Hystrix if (introspector.hasCircuitBreaker()) { breakerHelper.ensureConsistentState(); LOGGER.info("Enter: breaker for " + getCommandKey() + " in state " + breakerHelper.getState()); } // Record state of breaker boolean wasBreakerOpen = isCircuitBreakerOpen(); // Track invocation in a bulkhead if (introspector.hasBulkhead()) { bulkheadHelper.trackInvocation(this); } // Execute command Object result = null; Throwable throwable = null; long startNanos = System.nanoTime(); try { result = super.execute(); } catch (Throwable t) { throwable = t; } executionTime = System.nanoTime() - startNanos; boolean hasFailed = (throwable != null); if (introspector.hasCircuitBreaker()) { // Keep track of failure ratios breakerHelper.pushResult(throwable == null); // Query breaker states boolean breakerWillOpen = false; boolean isClosedNow = !isCircuitBreakerOpen(); /* * Special logic for MP circuit breakers to support failOn. If not a * throwable to fail on, restore underlying breaker and return. */ if (hasFailed) { final Throwable throwableFinal = throwable; Class<? extends Throwable>[] throwableClasses = introspector.getCircuitBreaker().failOn(); boolean failOn = Arrays.asList(throwableClasses) .stream() .anyMatch(c -> c.isAssignableFrom(throwableFinal.getClass())); if (!failOn) { restoreBreaker(); // clears Hystrix counters updateMetricsAfter(throwable, wasBreakerOpen, isClosedNow, breakerWillOpen); throw ExceptionUtil.wrapThrowable(throwable); } } /* * Special logic for MP circuit breakers to support an arbitrary success * threshold used to return a breaker back to its CLOSED state. Hystrix * only supports a threshold of 1 here, so additional logic is required. */ synchronized (breakerHelper.getSyncObject()) { // If failure ratio exceeded, then switch state to OPEN_MP if (breakerHelper.getState() == CircuitBreakerHelper.State.CLOSED_MP) { double failureRatio = breakerHelper.getFailureRatio(); if (failureRatio >= introspector.getCircuitBreaker().failureRatio()) { breakerWillOpen = true; breakerHelper.setState(CircuitBreakerHelper.State.OPEN_MP); runTripBreaker(); } } // If latest run failed, may need to switch state to OPEN_MP if (hasFailed) { if (breakerHelper.getState() == CircuitBreakerHelper.State.HALF_OPEN_MP) { // If failed and in HALF_OPEN_MP, we need to force breaker to open runTripBreaker(); breakerHelper.setState(CircuitBreakerHelper.State.OPEN_MP); } updateMetricsAfter(throwable, wasBreakerOpen, isClosedNow, breakerWillOpen); throw ExceptionUtil.wrapThrowable(throwable); } // Check next state of breaker based on outcome if (wasBreakerOpen && isClosedNow) { // Last called was successful breakerHelper.incSuccessCount(); // We stay in HALF_OPEN_MP until successThreshold is reached if (breakerHelper.getSuccessCount() < introspector.getCircuitBreaker().successThreshold()) { breakerHelper.setState(CircuitBreakerHelper.State.HALF_OPEN_MP); } else { breakerHelper.setState(CircuitBreakerHelper.State.CLOSED_MP); breakerHelper.resetCommandData(); } } } updateMetricsAfter(throwable, wasBreakerOpen, isClosedNow, breakerWillOpen); } // Untrack invocation in a bulkhead if (introspector.hasBulkhead()) { bulkheadHelper.untrackInvocation(this); } // Display circuit breaker state at exit if (introspector.hasCircuitBreaker()) { LOGGER.info("Exit: breaker for " + getCommandKey() + " in state " + breakerHelper.getState()); } // Outcome of execution if (throwable != null) { throw ExceptionUtil.wrapThrowable(throwable); } else { return result; } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Override public Object execute() { // Configure command before execution introspector.getHystrixProperties() .entrySet() .forEach(entry -> setProperty(entry.getKey(), entry.getValue())); // Ensure our internal state is consistent with Hystrix if (introspector.hasCircuitBreaker()) { breakerHelper.ensureConsistentState(); LOGGER.info("Enter: breaker for " + getCommandKey() + " in state " + breakerHelper.getState()); } // Record state of breaker boolean wasBreakerOpen = isCircuitBreakerOpen(); // Track invocation in a bulkhead if (introspector.hasBulkhead()) { bulkheadHelper.trackInvocation(this); } // Execute command Object result = null; Throwable throwable = null; long startNanos = System.nanoTime(); try { result = super.execute(); } catch (Throwable t) { throwable = t; } executionTime = System.nanoTime() - startNanos; boolean hasFailed = (throwable != null); if (introspector.hasCircuitBreaker()) { // Keep track of failure ratios breakerHelper.pushResult(throwable == null); // Query breaker states boolean breakerWillOpen = false; boolean isClosedNow = !isCircuitBreakerOpen(); /* * Special logic for MP circuit breakers to support failOn. If not a * throwable to fail on, restore underlying breaker and return. */ if (hasFailed) { final Throwable throwableFinal = throwable; Class<? extends Throwable>[] throwableClasses = introspector.getCircuitBreaker().failOn(); boolean failOn = Arrays.asList(throwableClasses) .stream() .anyMatch(c -> c.isAssignableFrom(throwableFinal.getClass())); if (!failOn) { restoreBreaker(); // clears Hystrix counters updateMetricsAfter(throwable, wasBreakerOpen, breakerWillOpen); throw ExceptionUtil.wrapThrowable(throwable); } } /* * Special logic for MP circuit breakers to support an arbitrary success * threshold used to return a breaker back to its CLOSED state. Hystrix * only supports a threshold of 1 here, so additional logic is required. */ synchronized (breakerHelper.getSyncObject()) { // If failure ratio exceeded, then switch state to OPEN_MP if (breakerHelper.getState() == CircuitBreakerHelper.State.CLOSED_MP) { double failureRatio = breakerHelper.getFailureRatio(); if (failureRatio >= introspector.getCircuitBreaker().failureRatio()) { breakerWillOpen = true; breakerHelper.setState(CircuitBreakerHelper.State.OPEN_MP); runTripBreaker(); } } // If latest run failed, may need to switch state to OPEN_MP if (hasFailed) { if (breakerHelper.getState() == CircuitBreakerHelper.State.HALF_OPEN_MP) { // If failed and in HALF_OPEN_MP, we need to force breaker to open runTripBreaker(); breakerHelper.setState(CircuitBreakerHelper.State.OPEN_MP); } updateMetricsAfter(throwable, wasBreakerOpen, breakerWillOpen); throw ExceptionUtil.wrapThrowable(throwable); } // Check next state of breaker based on outcome if (wasBreakerOpen && isClosedNow) { // Last called was successful breakerHelper.incSuccessCount(); // We stay in HALF_OPEN_MP until successThreshold is reached if (breakerHelper.getSuccessCount() < introspector.getCircuitBreaker().successThreshold()) { breakerHelper.setState(CircuitBreakerHelper.State.HALF_OPEN_MP); } else { breakerHelper.setState(CircuitBreakerHelper.State.CLOSED_MP); breakerHelper.resetCommandData(); } } } updateMetricsAfter(throwable, wasBreakerOpen, breakerWillOpen); } // Untrack invocation in a bulkhead if (introspector.hasBulkhead()) { bulkheadHelper.untrackInvocation(this); } // Display circuit breaker state at exit if (introspector.hasCircuitBreaker()) { LOGGER.info("Exit: breaker for " + getCommandKey() + " in state " + breakerHelper.getState()); } // Outcome of execution if (throwable != null) { throw ExceptionUtil.wrapThrowable(throwable); } else { return result; } } #location 32 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code @Override protected Optional<Instant> dataStamp() { // the URL may not be an HTTP URL try { URLConnection urlConnection = url.openConnection(); if (urlConnection instanceof HttpURLConnection) { HttpURLConnection connection = (HttpURLConnection) urlConnection; try { connection.setRequestMethod(HEAD_METHOD); if (connection.getLastModified() != 0) { return Optional.of(Instant.ofEpochMilli(connection.getLastModified())); } } finally { connection.disconnect(); } } } catch (IOException ex) { LOGGER.log(Level.FINE, ex, () -> "Configuration at url '" + url + "' HEAD is not accessible."); } Optional<Instant> timestamp = Optional.of(Instant.MAX); LOGGER.finer("Missing HEAD '" + url + "' response header 'Last-Modified'. Used time '" + timestamp + "' as a content timestamp."); return timestamp; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Override protected Optional<Instant> dataStamp() { try { HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod(HEAD_METHOD); if (connection.getLastModified() != 0) { return Optional.of(Instant.ofEpochMilli(connection.getLastModified())); } } catch (IOException ex) { LOGGER.log(Level.FINE, ex, () -> "Configuration at url '" + url + "' HEAD is not accessible."); } Optional<Instant> timestamp = Optional.of(Instant.MAX); LOGGER.finer("Missing HEAD '" + url + "' response header 'Last-Modified'. Used time '" + timestamp + "' as a content timestamp."); return timestamp; } #location 7 #vulnerability type RESOURCE_LEAK
#fixed code @Override public Object execute() { boolean lockRemoved = false; try { // Configure command before execution introspector.getHystrixProperties() .entrySet() .forEach(entry -> setProperty(entry.getKey(), entry.getValue())); // Get lock and check breaker delay if (introspector.hasCircuitBreaker()) { breakerHelper.lock(); // acquire exclusive access to command data // OPEN_MP -> HALF_OPEN_MP if (breakerHelper.getState() == State.OPEN_MP) { long delayNanos = TimeUtil.convertToNanos(introspector.getCircuitBreaker().delay(), introspector.getCircuitBreaker().delayUnit()); if (breakerHelper.getCurrentStateNanos() > delayNanos) { breakerHelper.setState(State.HALF_OPEN_MP); } } logCircuitBreakerState("Enter"); } // Record state of breaker boolean wasBreakerOpen = isCircuitBreakerOpen(); // Track invocation in a bulkhead if (introspector.hasBulkhead()) { bulkheadHelper.trackInvocation(this); } // Execute command Object result = null; Throwable throwable = null; long startNanos = System.nanoTime(); try { result = super.execute(); } catch (Throwable t) { throwable = t; } executionTime = System.nanoTime() - startNanos; boolean hasFailed = (throwable != null); if (introspector.hasCircuitBreaker()) { // Keep track of failure ratios breakerHelper.pushResult(throwable == null); // Query breaker states boolean breakerOpening = false; boolean isClosedNow = !wasBreakerOpen; /* * Special logic for MP circuit breakers to support failOn. If not a * throwable to fail on, restore underlying breaker and return. */ if (hasFailed) { final Throwable throwableFinal = throwable; Class<? extends Throwable>[] throwableClasses = introspector.getCircuitBreaker().failOn(); boolean failOn = Arrays.asList(throwableClasses) .stream() .anyMatch(c -> c.isAssignableFrom(throwableFinal.getClass())); if (!failOn) { updateMetricsAfter(throwable, wasBreakerOpen, isClosedNow, breakerOpening); logCircuitBreakerState("Exit 1"); throw ExceptionUtil.toWrappedException(throwable); } } // CLOSED_MP -> OPEN_MP if (breakerHelper.getState() == State.CLOSED_MP) { double failureRatio = breakerHelper.getFailureRatio(); if (failureRatio >= introspector.getCircuitBreaker().failureRatio()) { breakerHelper.setState(State.OPEN_MP); breakerOpening = true; } } // HALF_OPEN_MP -> OPEN_MP if (hasFailed) { if (breakerHelper.getState() == State.HALF_OPEN_MP) { breakerHelper.setState(State.OPEN_MP); } updateMetricsAfter(throwable, wasBreakerOpen, isClosedNow, breakerOpening); logCircuitBreakerState("Exit 2"); throw ExceptionUtil.toWrappedException(throwable); } // Otherwise, increment success count breakerHelper.incSuccessCount(); // HALF_OPEN_MP -> CLOSED_MP if (breakerHelper.getState() == State.HALF_OPEN_MP) { if (breakerHelper.getSuccessCount() == introspector.getCircuitBreaker().successThreshold()) { breakerHelper.setState(State.CLOSED_MP); breakerHelper.resetCommandData(); lockRemoved = true; isClosedNow = true; } } updateMetricsAfter(throwable, wasBreakerOpen, isClosedNow, breakerOpening); } // Untrack invocation in a bulkhead if (introspector.hasBulkhead()) { bulkheadHelper.untrackInvocation(this); } // Display circuit breaker state at exit logCircuitBreakerState("Exit 3"); // Outcome of execution if (throwable != null) { throw ExceptionUtil.toWrappedException(throwable); } else { return result; } } finally { // Free lock unless command data was reset if (introspector.hasCircuitBreaker() && !lockRemoved) { breakerHelper.unlock(); } } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Override public Object execute() { // Configure command before execution introspector.getHystrixProperties() .entrySet() .forEach(entry -> setProperty(entry.getKey(), entry.getValue())); // Ensure our internal state is consistent with Hystrix if (introspector.hasCircuitBreaker()) { breakerHelper.ensureConsistentState(); LOGGER.info("Enter: breaker for " + getCommandKey() + " in state " + breakerHelper.getState()); } // Record state of breaker boolean wasBreakerOpen = isCircuitBreakerOpen(); // Track invocation in a bulkhead if (introspector.hasBulkhead()) { bulkheadHelper.trackInvocation(this); } // Execute command Object result = null; Throwable throwable = null; long startNanos = System.nanoTime(); try { result = super.execute(); } catch (Throwable t) { throwable = t; } executionTime = System.nanoTime() - startNanos; boolean hasFailed = (throwable != null); if (introspector.hasCircuitBreaker()) { // Keep track of failure ratios breakerHelper.pushResult(throwable == null); // Query breaker states boolean breakerWillOpen = false; boolean isClosedNow = !isCircuitBreakerOpen(); /* * Special logic for MP circuit breakers to support failOn. If not a * throwable to fail on, restore underlying breaker and return. */ if (hasFailed) { final Throwable throwableFinal = throwable; Class<? extends Throwable>[] throwableClasses = introspector.getCircuitBreaker().failOn(); boolean failOn = Arrays.asList(throwableClasses) .stream() .anyMatch(c -> c.isAssignableFrom(throwableFinal.getClass())); if (!failOn) { restoreBreaker(); // clears Hystrix counters updateMetricsAfter(throwable, wasBreakerOpen, isClosedNow, breakerWillOpen); throw ExceptionUtil.toWrappedException(throwable); } } /* * Special logic for MP circuit breakers to support an arbitrary success * threshold used to return a breaker back to its CLOSED state. Hystrix * only supports a threshold of 1 here, so additional logic is required. */ synchronized (breakerHelper.getSyncObject()) { // If failure ratio exceeded, then switch state to OPEN_MP if (breakerHelper.getState() == CircuitBreakerHelper.State.CLOSED_MP) { double failureRatio = breakerHelper.getFailureRatio(); if (failureRatio >= introspector.getCircuitBreaker().failureRatio()) { breakerWillOpen = true; breakerHelper.setState(CircuitBreakerHelper.State.OPEN_MP); runTripBreaker(); } } // If latest run failed, may need to switch state to OPEN_MP if (hasFailed) { if (breakerHelper.getState() == CircuitBreakerHelper.State.HALF_OPEN_MP) { // If failed and in HALF_OPEN_MP, we need to force breaker to open runTripBreaker(); breakerHelper.setState(CircuitBreakerHelper.State.OPEN_MP); } updateMetricsAfter(throwable, wasBreakerOpen, isClosedNow, breakerWillOpen); throw ExceptionUtil.toWrappedException(throwable); } // Check next state of breaker based on outcome if (wasBreakerOpen && isClosedNow) { // Last called was successful breakerHelper.incSuccessCount(); // We stay in HALF_OPEN_MP until successThreshold is reached if (breakerHelper.getSuccessCount() < introspector.getCircuitBreaker().successThreshold()) { breakerHelper.setState(CircuitBreakerHelper.State.HALF_OPEN_MP); } else { breakerHelper.setState(CircuitBreakerHelper.State.CLOSED_MP); breakerHelper.resetCommandData(); } } } updateMetricsAfter(throwable, wasBreakerOpen, isClosedNow, breakerWillOpen); } // Untrack invocation in a bulkhead if (introspector.hasBulkhead()) { bulkheadHelper.untrackInvocation(this); } // Display circuit breaker state at exit if (introspector.hasCircuitBreaker()) { LOGGER.info("Exit: breaker for " + getCommandKey() + " in state " + breakerHelper.getState()); } // Outcome of execution if (throwable != null) { throw ExceptionUtil.toWrappedException(throwable); } else { return result; } } #location 68 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code static String checkModelForParametrizedValue(String seleniumVersion, Model model) { String version = getNamePropertyName(seleniumVersion); if (nonNull(model.getProperties())) { return model.getProperties().getProperty(version); } else if (nonNull(System.getProperty(version))) { return System.getProperty(version); } else if (nonNull(model.getProfiles()) && model.getProfiles().size() > 0) { return getVersionNameFromProfiles(version, model); } else { return null; } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code static String checkModelForParametrizedValue(String seleniumVersion, Model model) { String version = getNamePropertyName(seleniumVersion); String versionProp = null; if (nonNull(seleniumVersion) && nonNull(model.getProperties())) { versionProp = model.getProperties().getProperty(version); } else if (nonNull(seleniumVersion) && nonNull(System.getProperty(version))) { versionProp = System.getProperty(version); } else if (nonNull(seleniumVersion) && nonNull(model.getProfiles()) && model.getProfiles().size() > 0) { versionProp = model.getProfiles().stream() .filter(prof -> nonNull(prof.getProperties()) && nonNull(prof.getProperties().getProperty(version))) .findAny() .map(prof -> prof.getProperties().getProperty(version)) .orElse(null); } return versionProp; } #location 8 #vulnerability type NULL_DEREFERENCE
#fixed code @Test public void testGetTypeMap() { Result result = new Result(false, false, 1000, 2000, new BranchTrace(), vector, "unittest.id"); rule.onApply(result); vector.addModification(new AddMessageModification(new ServerHelloDoneMessage(), new SendAction())); rule.onApply(result); List<ModificationCounter> counterList= rule.getCounterList(); ModificationCounter counter = counterList.get(1); assertTrue(counter.getCounter() == 2); counter = counterList.get(0); assertTrue(counter.getCounter() == 3); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void testGetTypeMap() { Result result = new Result(false, false, 1000, 2000, new BranchTrace(), vector, "unittest.id"); rule.onApply(result); vector.addModification(new AddMessageModification(new ServerHelloDoneMessage(), new SendAction())); rule.onApply(result); HashMap<ModificationType, MutableInt> typeMap = rule.getTypeMap(); MutableInt val = typeMap.get(ModificationType.ADD_RECORD); assertTrue(val.getValue() == 2); val = typeMap.get(ModificationType.ADD_MESSAGE); assertTrue(val.getValue() == 3); } #location 9 #vulnerability type NULL_DEREFERENCE
#fixed code public void startTlsServer(TlsConfig config) { TlsContext tlsContext = new TlsContext(config); WorkflowExecutor workflowExecutor = WorkflowExecutorFactory.createWorkflowExecutor(config.getExecutorType(), tlsContext); try { workflowExecutor.executeWorkflow(); } catch (WorkflowExecutionException ex) { LOGGER.info("The TLS protocol flow was not executed completely, follow the debug messages for more information."); LOGGER.debug(ex.getLocalizedMessage(), ex); } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public void startTlsServer(TlsConfig config) { TlsContext tlsContext = new TlsContext(config); WorkflowExecutor workflowExecutor = WorkflowExecutorFactory.createWorkflowExecutor(config.getExecutorType(), tlsContext); try { workflowExecutor.executeWorkflow(); } catch (WorkflowExecutionException ex) { LOGGER.info("The TLS protocol flow was not executed completely, follow the debug messages for more information."); LOGGER.debug(ex.getLocalizedMessage(), ex); } if (config.getWorkflowOutput() != null && !config.getWorkflowOutput().isEmpty()) { FileOutputStream fos = null; try { fos = new FileOutputStream(config.getWorkflowOutput()); WorkflowTraceSerializer.write(fos, tlsContext.getWorkflowTrace()); } catch (JAXBException | IOException ex) { LOGGER.info("Could not serialize WorkflowTrace."); LOGGER.debug(ex); } finally { try { fos.close(); } catch (IOException ex) { LOGGER.info("Could not serialize WorkflowTrace."); LOGGER.debug(ex); } } } } #location 22 #vulnerability type NULL_DEREFERENCE
#fixed code private boolean testExecuteWorkflow(TlsConfig config) { // TODO ugly ConfigHandler configHandler = new ConfigHandler(); TransportHandler transportHandler = configHandler.initializeTransportHandler(config); TlsContext tlsContext = configHandler.initializeTlsContext(config); config.setWorkflowTraceType(WorkflowTraceType.FULL); WorkflowExecutor workflowExecutor = configHandler.initializeWorkflowExecutor(transportHandler, tlsContext); try { workflowExecutor.executeWorkflow(); } catch (Exception E) { E.printStackTrace(); } transportHandler.closeConnection(); boolean result = isWorkflowTraceReasonable(tlsContext.getWorkflowTrace()); if (!result) { LOGGER.log(Level.INFO, "Failed vanilla execution"); return result; } tlsContext.getWorkflowTrace().reset(); WorkflowTrace trace = tlsContext.getWorkflowTrace(); tlsContext = configHandler.initializeTlsContext(config); tlsContext.setWorkflowTrace(trace); transportHandler = configHandler.initializeTransportHandler(config); workflowExecutor = configHandler.initializeWorkflowExecutor(transportHandler, tlsContext); try { workflowExecutor.executeWorkflow(); } catch (Exception E) { E.printStackTrace(); } transportHandler.closeConnection(); result = isWorkflowTraceReasonable(tlsContext.getWorkflowTrace()); if (!result) { LOGGER.log(Level.INFO, "Failed reset execution"); return result; } tlsContext.getWorkflowTrace().reset(); tlsContext.getWorkflowTrace().makeGeneric(); trace = tlsContext.getWorkflowTrace(); tlsContext = configHandler.initializeTlsContext(config); tlsContext.setWorkflowTrace(trace); transportHandler = configHandler.initializeTransportHandler(config); workflowExecutor = configHandler.initializeWorkflowExecutor(transportHandler, tlsContext); try { workflowExecutor.executeWorkflow(); } catch (Exception E) { E.printStackTrace(); } transportHandler.closeConnection(); result = isWorkflowTraceReasonable(tlsContext.getWorkflowTrace()); if (!result) { LOGGER.log(Level.INFO, "Failed reset&generic execution"); } return result; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code private boolean testExecuteWorkflow(TlsConfig config) { // TODO ugly ConfigHandler configHandler = new ConfigHandler(); TransportHandler transportHandler = configHandler.initializeTransportHandler(config); TlsContext tlsContext = configHandler.initializeTlsContext(config); WorkflowExecutor workflowExecutor = configHandler.initializeWorkflowExecutor(transportHandler, tlsContext); try { workflowExecutor.executeWorkflow(); } catch (Exception E) { E.printStackTrace(); } transportHandler.closeConnection(); boolean result = isWorkflowTraceReasonable(tlsContext.getWorkflowTrace()); if (!result) { LOGGER.log(Level.INFO, "Failed vanilla execution"); return result; } tlsContext.getWorkflowTrace().reset(); WorkflowTrace trace = tlsContext.getWorkflowTrace(); tlsContext = configHandler.initializeTlsContext(config); tlsContext.setWorkflowTrace(trace); transportHandler = configHandler.initializeTransportHandler(config); workflowExecutor = configHandler.initializeWorkflowExecutor(transportHandler, tlsContext); try { workflowExecutor.executeWorkflow(); } catch (Exception E) { E.printStackTrace(); } transportHandler.closeConnection(); result = isWorkflowTraceReasonable(tlsContext.getWorkflowTrace()); if (!result) { LOGGER.log(Level.INFO, "Failed reset execution"); return result; } tlsContext.getWorkflowTrace().reset(); tlsContext.getWorkflowTrace().makeGeneric(); trace = tlsContext.getWorkflowTrace(); tlsContext = configHandler.initializeTlsContext(config); tlsContext.setWorkflowTrace(trace); transportHandler = configHandler.initializeTransportHandler(config); workflowExecutor = configHandler.initializeWorkflowExecutor(transportHandler, tlsContext); try { workflowExecutor.executeWorkflow(); } catch (Exception E) { E.printStackTrace(); } transportHandler.closeConnection(); result = isWorkflowTraceReasonable(tlsContext.getWorkflowTrace()); if (!result) { LOGGER.log(Level.INFO, "Failed reset&generic execution"); } return result; } #location 10 #vulnerability type NULL_DEREFERENCE
#fixed code @Override public void handle(Message<JsonObject> message) { String action = getMandatoryString("action", message); if (action == null) { sendError(message, "No action specified."); return; } switch (action) { case "receive": doReceive(message); break; default: sendError(message, String.format("Invalid action %s.", action)); } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Override public void handle(Message<JsonObject> message) { String action = getMandatoryString("action", message); if (action == null) { sendError(message, "No action specified."); } switch (action) { case "receive": doReceive(message); break; default: sendError(message, String.format("Invalid action %s.", action)); } } #location 8 #vulnerability type NULL_DEREFERENCE
#fixed code @Test public void testFieldsSelector() { Selector selector = new FieldsSelector("test"); JsonMessage test1 = DefaultJsonMessage.create(new JsonObject().putString("test", "a"), "auditor"); List<Connection> connections1 = selector.select(test1, testConnections); assertEquals(1, connections1.size()); List<Connection> connections2 = selector.select(test1, testConnections); assertEquals(1, connections2.size()); assertEquals(connections1.get(0), connections2.get(0)); JsonMessage test2 = DefaultJsonMessage.create(new JsonObject().putString("test", "a"), "auditor"); List<Connection> connections3 = selector.select(test2, testConnections); assertEquals(1, connections3.size()); List<Connection> connections4 = selector.select(test2, testConnections); assertEquals(1, connections4.size()); assertEquals(connections3.get(0), connections4.get(0)); JsonMessage test3 = DefaultJsonMessage.create(new JsonObject().putString("test", "a"), "auditor"); List<Connection> connections5 = selector.select(test3, testConnections); assertEquals(1, connections5.size()); List<Connection> connections6 = selector.select(test3, testConnections); assertEquals(1, connections6.size()); assertEquals(connections5.get(0), connections6.get(0)); Selector multiSelector = new FieldsSelector("test1", "test2"); JsonMessage test4 = DefaultJsonMessage.create(new JsonObject().putString("test1", "a"), "auditor"); List<Connection> connections7 = multiSelector.select(test4, testConnections); assertEquals(1, connections7.size()); List<Connection> connections8 = multiSelector.select(test4, testConnections); assertEquals(1, connections8.size()); assertEquals(connections7.get(0), connections8.get(0)); JsonMessage test5 = DefaultJsonMessage.create(new JsonObject().putString("test2", "ab"), "auditor"); List<Connection> connections9 = multiSelector.select(test5, testConnections); assertEquals(1, connections9.size()); List<Connection> connections10 = multiSelector.select(test5, testConnections); assertEquals(1, connections10.size()); assertEquals(connections9.get(0), connections10.get(0)); JsonMessage test6 = DefaultJsonMessage.create(new JsonObject().putString("test1", "ab").putString("test2", "abc"), "auditor"); List<Connection> connections11 = multiSelector.select(test6, testConnections); assertEquals(1, connections11.size()); List<Connection> connections12 = multiSelector.select(test6, testConnections); assertEquals(1, connections12.size()); assertEquals(connections11.get(0), connections12.get(0)); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void testFieldsSelector() { Selector selector = new FieldsSelector("test"); JsonMessage test1 = DefaultJsonMessage.create(new JsonObject().putString("test", "a"), "auditor"); List<Connection> connections1 = selector.select(test1, testConnections); assertEquals(1, connections1.size()); List<Connection> connections2 = selector.select(test1, testConnections); assertEquals(1, connections2.size()); assertEquals(connections1.get(0), connections2.get(0)); JsonMessage test2 = DefaultJsonMessage.create(new JsonObject().putString("test", "a"), "auditor"); List<Connection> connections3 = selector.select(test2, testConnections); assertEquals(1, connections3.size()); List<Connection> connections4 = selector.select(test2, testConnections); assertEquals(1, connections4.size()); assertEquals(connections3.get(0), connections4.get(0)); JsonMessage test3 = DefaultJsonMessage.create(new JsonObject().putString("test", "a"), "auditor"); List<Connection> connections5 = selector.select(test3, testConnections); assertEquals(1, connections5.size()); List<Connection> connections6 = selector.select(test3, testConnections); assertEquals(1, connections6.size()); assertEquals(connections5.get(0), connections6.get(0)); } #location 16 #vulnerability type NULL_DEREFERENCE