output
stringlengths
64
73.2k
input
stringlengths
208
73.3k
instruction
stringclasses
1 value
#fixed code private InstanceSet buildInstanceList(String file) throws IOException { System.out.print("生成训练数据 ..."); FNLPReader reader = new FNLPReader(file); FNLPReader preReader = new FNLPReader(file); InstanceSet instset = new InstanceSet(); LabelAlphabet la = factory.DefaultLabelAlphabet(); IFeatureAlphabet fa = factory.DefaultFeatureAlphabet(); int count = 0; //preReader为了把ysize定下来 la.lookupIndex("S"); while(preReader.hasNext()){ Sentence sent = (Sentence) preReader.next(); Target targets = (Target)sent.getTarget(); for(int i=0; i<sent.length(); i++){ String label; if(targets.getHead(i) != -1){ if(targets.getHead(i) < i){ label = "L" + targets.getDepClass(i); } //else if(targets.getHead(i) > i){ else{ label = "R" + targets.getDepClass(i); } la.lookupIndex(label); } } } int ysize = la.size(); la.setStopIncrement(true); while (reader.hasNext()) { Sentence sent = (Sentence) reader.next(); // int[] heads = (int[]) instance.getTarget(); String depClass = null; Target targets = (Target)sent.getTarget(); JointParsingState state = new JointParsingState(sent); while (!state.isFinalState()) { // 左右焦点词在句子中的位置 int[] lr = state.getFocusIndices(); ArrayList<String> features = state.getFeatures(); JointParsingState.Action action = getAction(lr[0], lr[1], targets); switch (action) { case LEFT: depClass = targets.getDepClass(lr[1]); break; case RIGHT: depClass = targets.getDepClass(lr[0]); break; default: } state.next(action,depClass); if (action == JointParsingState.Action.LEFT) targets.setHeads(lr[1],-1); if (action == JointParsingState.Action.RIGHT) targets.setHeads(lr[0],-1); String label = ""; switch (action) { case LEFT: label += "L"+sent.getDepClass(lr[1]); break; case RIGHT: label+="R"+sent.getDepClass(lr[0]); break; default: label = "S"; } int id = la.lookupIndex(label); Instance inst = new Instance(); inst.setTarget(id); int[] idx = JointParser.addFeature(fa, features, ysize); inst.setData(idx); instset.add(inst); } count++; // System.out.println(count); } instset.setAlphabetFactory(factory); System.out.printf("共生成实例:%d个\n", count); return instset; }
#vulnerable code private InstanceSet buildInstanceList(String file) throws IOException { System.out.print("生成训练数据 ..."); FNLPReader reader = new FNLPReader(file); InstanceSet instset = new InstanceSet(); LabelAlphabet la = factory.DefaultLabelAlphabet(); int count = 0; while (reader.hasNext()) { Sentence sent = (Sentence) reader.next(); // int[] heads = (int[]) instance.getTarget(); String depClass = null; Target targets = (Target)sent.getTarget(); JointParsingState state = new JointParsingState(sent); while (!state.isFinalState()) { // 左右焦点词在句子中的位置 int[] lr = state.getFocusIndices(); ArrayList<String> features = state.getFeatures(); JointParsingState.Action action = getAction(lr[0], lr[1], targets); switch (action) { case LEFT: depClass = targets.getDepClass(lr[1]); break; case RIGHT: depClass = targets.getDepClass(lr[0]); break; default: } state.next(action,depClass); if (action == JointParsingState.Action.LEFT) targets.setHeads(lr[1],-1); if (action == JointParsingState.Action.RIGHT) targets.setHeads(lr[0],-1); String label = ""; switch (action) { case LEFT: label += "L"+sent.getDepClass(lr[1]); break; case RIGHT: label+="R"+sent.getDepClass(lr[0]); break; default: label = "S"; } int id = la.lookupIndex(label); Instance inst = new Instance(); inst.setTarget(id); inst.setData(features); instset.add(inst); } count++; // System.out.println(count); } la.setStopIncrement(true); //重新生成特征 int ysize = la.size(); IFeatureAlphabet fa = factory.DefaultFeatureAlphabet(); for(Instance inst:instset){ ArrayList<String> data = (ArrayList<String>) inst.getData(); int[] idx = JointParser.addFeature(fa, data, ysize); inst.setData(idx); } instset.setAlphabetFactory(factory); System.out.printf("共生成实例:%d个\n", count); return instset; } #location 14 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public static void main(String[] args) { try { String ls_1; Process process =null; // File handle = new File("../tmp/ctb_v1/data"); File handle = new File("../tmp/ctb_v6/data/bracketed"); BufferedWriter bout = new BufferedWriter(new OutputStreamWriter( new FileOutputStream("../tmp/malt.train"), "UTF-8")); for (File sub : Arrays.asList(handle.listFiles())){ String file = sub.getAbsolutePath(); if(!file.endsWith(".fid")) continue; clean(file); process = Runtime.getRuntime().exec("cmd /c java -jar ../tmp/Penn2Malt.jar "+file+" ../tmp/headrules.txt 3 2 chtb"); BufferedReader bufferedReader = new BufferedReader( new InputStreamReader(process.getInputStream())); while ( (ls_1=bufferedReader.readLine()) != null) { System.out.println(ls_1); } bufferedReader = new BufferedReader( new InputStreamReader(process.getErrorStream())); while ( (ls_1=bufferedReader.readLine()) != null) { System.out.println(ls_1); } } } catch(IOException e) { System.err.println(e); } }
#vulnerable code public static void main(String[] args) { try { String ls_1; Process process =null; File handle = new File("./tmpdata/ctb/data3"); BufferedWriter bout = new BufferedWriter(new OutputStreamWriter( new FileOutputStream("./tmpdata/malt.train"), "UTF-8")); for (File sub : Arrays.asList(handle.listFiles())){ String str = sub.getAbsolutePath(); process = Runtime.getRuntime().exec("cmd /c java -jar ./tmpdata/ctb/Penn2Malt.jar "+str+" ./tmpdata/ctb/headrules.txt 3 2 chtb"); BufferedReader bufferedReader = new BufferedReader( new InputStreamReader(process.getInputStream())); while ( (ls_1=bufferedReader.readLine()) != null) { System.out.println(ls_1); } } } catch(IOException e) { System.err.println(e); } } #location 14 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public void train(String dataFile, int maxite, float c) throws IOException { InstanceSet instset = buildInstanceList(dataFile); SFGenerator generator = new SFGenerator(); LabelAlphabet la = factory.DefaultLabelAlphabet(); int ysize = la.size(); System.out.printf("开始训练"); LinearMax solver = new LinearMax(generator, ysize); ZeroOneLoss loss = new ZeroOneLoss(); Update update = new LinearMaxPAUpdate(loss); OnlineTrainer trainer = new OnlineTrainer(solver, update, loss, factory, maxite, c); Linear models = trainer.train(instset, null); instset = null; solver = null; loss = null; trainer = null; System.out.println(); factory.setStopIncrement(true); models.saveTo(modelfile); }
#vulnerable code public void train(String dataFile, int maxite, float c) throws IOException { InstanceSet instset = buildInstanceList(dataFile); IFeatureAlphabet features = factory.DefaultFeatureAlphabet(); SFGenerator generator = new SFGenerator(); int fsize = features.size(); LabelAlphabet la = factory.DefaultLabelAlphabet(); int ysize = la.size(); System.out.printf("开始训练"); LinearMax solver = new LinearMax(generator, ysize); ZeroOneLoss loss = new ZeroOneLoss(); Update update = new LinearMaxPAUpdate(loss); OnlineTrainer trainer = new OnlineTrainer(solver, update, loss, fsize, maxite, c); Linear models = trainer.train(instset, null); instset = null; solver = null; loss = null; trainer = null; System.out.println(); factory.setStopIncrement(true); models.saveTo(modelfile); } #location 7 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Test public void testStartNewSpanSampleNullNotPartOfExistingSpan() { final ServerSpan mockServerSpan = mock(ServerSpan.class); when(mockServerSpan.getSpan()).thenReturn(null); when(mockState.sample()).thenReturn(null); when(mockState.getCurrentServerSpan()).thenReturn(mockServerSpan); when(mockRandom.nextLong()).thenReturn(TRACE_ID).thenReturn(2l); final SpanId newSpanId = clientTracer.startNewSpan(REQUEST_NAME); assertNotNull(newSpanId); assertEquals(TRACE_ID, newSpanId.getTraceId()); assertEquals(TRACE_ID, newSpanId.getSpanId()); assertNull(newSpanId.getParentSpanId()); final Span expectedSpan = new Span(); expectedSpan.setTrace_id(TRACE_ID); expectedSpan.setId(TRACE_ID); expectedSpan.setName(REQUEST_NAME); verify(mockState).sample(); verify(mockTraceFilter).trace(TRACE_ID, REQUEST_NAME); verify(mockTraceFilter2).trace(TRACE_ID, REQUEST_NAME); verify(mockRandom, times(1)).nextLong(); verify(mockState).getCurrentServerSpan(); verify(mockState).setCurrentClientSpan(expectedSpan); verifyNoMoreInteractions(mockState, mockRandom, mockCollector, mockTraceFilter, mockTraceFilter2); }
#vulnerable code @Test public void testStartNewSpanSampleNullNotPartOfExistingSpan() { final ServerSpan mockServerSpan = mock(ServerSpan.class); when(mockServerSpan.getSpan()).thenReturn(null); when(mockState.sample()).thenReturn(null); when(mockState.getCurrentServerSpan()).thenReturn(mockServerSpan); when(mockRandom.nextLong()).thenReturn(1l).thenReturn(2l); final SpanId newSpanId = clientTracer.startNewSpan(REQUEST_NAME); assertNotNull(newSpanId); assertEquals(1l, newSpanId.getTraceId()); assertEquals(1l, newSpanId.getSpanId()); assertNull(newSpanId.getParentSpanId()); final Span expectedSpan = new Span(); expectedSpan.setTrace_id(1); expectedSpan.setId(1); expectedSpan.setName(REQUEST_NAME); verify(mockState).sample(); verify(mockTraceFilter).trace(REQUEST_NAME); verify(mockTraceFilter2).trace(REQUEST_NAME); verify(mockRandom, times(1)).nextLong(); verify(mockState).getCurrentServerSpan(); verify(mockState).setCurrentClientSpan(expectedSpan); verifyNoMoreInteractions(mockState, mockRandom, mockCollector, mockTraceFilter, mockTraceFilter2); } #location 12 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Test public void finishSpan() { Span finished = new Span().setName("foo").setTimestamp(1000L); // set in start span finished.startTick = 500000L; // set in start span state.setCurrentLocalSpan(finished); PowerMockito.when(System.nanoTime()).thenReturn(1000000L); localTracer.finishSpan(); verify(mockReporter).report(finished.toZipkin()); verifyNoMoreInteractions(mockReporter); assertEquals(500L, finished.getDuration().longValue()); }
#vulnerable code @Test public void finishSpan() { Span finished = new Span().setTimestamp(1000L); // set in start span finished.startTick = 500000L; // set in start span state.setCurrentLocalSpan(finished); PowerMockito.when(System.nanoTime()).thenReturn(1000000L); localTracer.finishSpan(); verify(mockCollector).collect(finished); verifyNoMoreInteractions(mockCollector); assertEquals(500L, finished.getDuration().longValue()); } #location 14 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Override public T call() throws Exception { serverSpanThreadBinder().setCurrentSpan(currentServerSpan()); return wrappedCallable().call(); }
#vulnerable code @Override public T call() throws Exception { serverSpanThreadBinder().setCurrentSpan(currentServerSpan()); final long start = System.currentTimeMillis(); try { return wrappedCallable().call(); } finally { final long duration = System.currentTimeMillis() - start; currentServerSpan().incThreadDuration(duration); } } #location 9 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code private void recordClientSentAnnotations(Endpoint serverAddress) { if (serverAddress == null) { clientTracer.setClientSent(); } else { clientTracer.setClientSent(serverAddress); } }
#vulnerable code private void recordClientSentAnnotations(Endpoint serverAddress) { if (serverAddress == null) { clientTracer.setClientSent(); } else { clientTracer.setClientSent(serverAddress.ipv4, serverAddress.port, serverAddress.service_name); } } #location 5 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Test public void finishSpan_userSuppliedTimestamp() { Span finished = new Span().setName("foo").setTimestamp(1000L); // Set by user state.setCurrentLocalSpan(finished); PowerMockito.when(System.currentTimeMillis()).thenReturn(2L); localTracer.finishSpan(); verify(mockReporter).report(finished.toZipkin()); verifyNoMoreInteractions(mockReporter); assertEquals(1000L, finished.getDuration().longValue()); }
#vulnerable code @Test public void finishSpan_userSuppliedTimestamp() { Span finished = new Span().setTimestamp(1000L); // Set by user state.setCurrentLocalSpan(finished); PowerMockito.when(System.currentTimeMillis()).thenReturn(2L); localTracer.finishSpan(); verify(mockCollector).collect(finished); verifyNoMoreInteractions(mockCollector); assertEquals(1000L, finished.getDuration().longValue()); } #location 13 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Test public void finishSpan_userSuppliedTimestampAndDuration() { Span finished = new Span().setName("foo").setTimestamp(1000L); // Set by user state.setCurrentLocalSpan(finished); localTracer.finishSpan(500L); verify(mockReporter).report(finished.toZipkin()); verifyNoMoreInteractions(mockReporter); assertEquals(500L, finished.getDuration().longValue()); }
#vulnerable code @Test public void finishSpan_userSuppliedTimestampAndDuration() { Span finished = new Span().setTimestamp(1000L); // Set by user state.setCurrentLocalSpan(finished); localTracer.finishSpan(500L); verify(mockCollector).collect(finished); verifyNoMoreInteractions(mockCollector); assertEquals(500L, finished.getDuration().longValue()); } #location 11 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Test public void finishSpan_lessThanMicrosRoundUp() { Span finished = new Span().setName("foo").setTimestamp(1000L); // set in start span finished.startTick = 500L; // set in start span state.setCurrentLocalSpan(finished); PowerMockito.when(System.nanoTime()).thenReturn(1000L); localTracer.finishSpan(); verify(mockReporter).report(finished.toZipkin()); verifyNoMoreInteractions(mockReporter); assertEquals(1L, finished.getDuration().longValue()); }
#vulnerable code @Test public void finishSpan_lessThanMicrosRoundUp() { Span finished = new Span().setTimestamp(1000L); // set in start span finished.startTick = 500L; // set in start span state.setCurrentLocalSpan(finished); PowerMockito.when(System.nanoTime()).thenReturn(1000L); localTracer.finishSpan(); verify(mockCollector).collect(finished); verifyNoMoreInteractions(mockCollector); assertEquals(1L, finished.getDuration().longValue()); } #location 14 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Test public void finishSpan_userSuppliedDuration() { Span finished = new Span().setName("foo").setTimestamp(1000L); // set in start span finished.startTick = 500L; // set in start span state.setCurrentLocalSpan(finished); localTracer.finishSpan(500L); verify(mockReporter).report(finished.toZipkin()); verifyNoMoreInteractions(mockReporter); assertEquals(500L, finished.getDuration().longValue()); }
#vulnerable code @Test public void finishSpan_userSuppliedDuration() { Span finished = new Span().setTimestamp(1000L); // set in start span finished.startTick = 500L; // set in start span state.setCurrentLocalSpan(finished); localTracer.finishSpan(500L); verify(mockCollector).collect(finished); verifyNoMoreInteractions(mockCollector); assertEquals(500L, finished.getDuration().longValue()); } #location 12 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Override public void run() { serverSpanThreadBinder().setCurrentSpan(currentServerSpan()); wrappedRunnable().run(); }
#vulnerable code @Override public void run() { serverSpanThreadBinder().setCurrentSpan(currentServerSpan()); final long start = System.currentTimeMillis(); try { wrappedRunnable().run(); } finally { final long duration = System.currentTimeMillis() - start; currentServerSpan().incThreadDuration(duration); } } #location 9 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code protected boolean checkQuiesceLock() { final String methodName = "checkQuiesceLock"; // if (quiescing && actualInFlight == 0 && pendingFlows.size() == 0 && // inFlightPubRels == 0 && callback.isQuiesced()) { int tokC = tokenStore.count(); if (quiescing && tokC == 0 && pendingFlows.size() == 0 && callback.isQuiesced()) { // @TRACE 626=quiescing={0} actualInFlight={1} pendingFlows={2} // inFlightPubRels={3} callbackQuiesce={4} tokens={5} log.fine(CLASS_NAME, methodName, "626", new Object[] { Boolean.valueOf(quiescing), Integer.valueOf(actualInFlight), Integer.valueOf(pendingFlows.size()), Integer.valueOf(inFlightPubRels), Boolean.valueOf(callback.isQuiesced()), Integer.valueOf(tokC) }); synchronized (quiesceLock) { quiesceLock.notifyAll(); } return true; } return false; }
#vulnerable code protected boolean checkQuiesceLock() { final String methodName = "checkQuiesceLock"; // if (quiescing && actualInFlight == 0 && pendingFlows.size() == 0 && // inFlightPubRels == 0 && callback.isQuiesced()) { int tokC = tokenStore.count(); if (quiescing && tokC == 0 && pendingFlows.size() == 0 && callback.isQuiesced()) { // @TRACE 626=quiescing={0} actualInFlight={1} pendingFlows={2} // inFlightPubRels={3} callbackQuiesce={4} tokens={5} log.fine(CLASS_NAME, methodName, "626", new Object[] { new Boolean(quiescing), Integer.valueOf(actualInFlight), Integer.valueOf(pendingFlows.size()), Integer.valueOf(inFlightPubRels), Boolean.valueOf(callback.isQuiesced()), Integer.valueOf(tokC) }); synchronized (quiesceLock) { quiesceLock.notifyAll(); } return true; } return false; } #location 10 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Test public void testGetStructure() { try { long now = System.currentTimeMillis(); long bytes = Long.MAX_VALUE; SimpleFormatter sf = new SimpleFormatter(); log.info(sf.getSize(bytes)); log.info(sf.getRate(now, bytes)); log.info(sf.getTime(now)); String delimiter = "/"; String bucket = "maven.kuali.org"; AmazonS3Client client = getClient(); KualiMavenBucketBaseCase baseCase1 = new KualiMavenBucketBaseCase(); baseCase1.setDelimiter(delimiter); baseCase1.setToken("latest"); JavaxServletOnlyBaseCase baseCase2 = new JavaxServletOnlyBaseCase(); baseCase2.setDelimiter(delimiter); baseCase2.setToken("latest"); long start = System.currentTimeMillis(); List<String> prefixes = new ArrayList<String>(); buildPrefixList(client, bucket, prefixes, null, delimiter, baseCase2); long elapsed = System.currentTimeMillis() - start; DefaultMutableTreeNode node = buildTree(prefixes, delimiter); List<DefaultMutableTreeNode> leaves = getLeaves(node); log.info("Total Prefixes: " + prefixes.size()); log.info("Total Time: " + sf.getTime(elapsed)); log.info("Leaves: " + leaves.size()); } catch (Exception e) { e.printStackTrace(); } }
#vulnerable code @Test public void testGetStructure() { try { SimpleFormatter sf = new SimpleFormatter(); String delimiter = "/"; String bucket = "maven.kuali.org"; AmazonS3Client client = getClient(); KualiMavenBucketBaseCase baseCase1 = new KualiMavenBucketBaseCase(); baseCase1.setDelimiter(delimiter); baseCase1.setToken("latest"); JavaxServletOnlyBaseCase baseCase2 = new JavaxServletOnlyBaseCase(); baseCase2.setDelimiter(delimiter); baseCase2.setToken("latest"); long start = System.currentTimeMillis(); List<String> prefixes = new ArrayList<String>(); buildPrefixList(client, bucket, prefixes, null, delimiter, baseCase2); long elapsed = System.currentTimeMillis() - start; DefaultMutableTreeNode node = buildTree(prefixes, delimiter); List<DefaultMutableTreeNode> leaves = getLeaves(node); log.info("Total Prefixes: " + prefixes.size()); log.info("Total Time: " + sf.getTime(elapsed)); log.info("Leaves: " + leaves.size()); } catch (Exception e) { e.printStackTrace(); } } #location 20 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Override public void transitionInto(RunState state) { switch (state.state()) { case SUBMITTING: try { final String executionId = dockerRunnerStart(state); // this is racy final Event submitted = Event.submitted(state.workflowInstance(), executionId); try { stateManager.receive(submitted); } catch (StateManager.IsClosed isClosed) { LOG.warn("Could not send 'created' event", isClosed); } } catch (ResourceNotFoundException e) { LOG.error("Unable to start docker procedure.", e); stateManager.receiveIgnoreClosed(Event.halt(state.workflowInstance())); } catch (IOException e) { try { LOG.error("Failed the docker starting procedure for " + state.workflowInstance().toKey(), e); stateManager.receive(Event.runError(state.workflowInstance(), e.getMessage())); } catch (StateManager.IsClosed isClosed) { LOG.warn("Failed to send 'runError' event", isClosed); } } break; case TERMINATED: case FAILED: case ERROR: if (state.executionId().isPresent()) { final String executionId = state.executionId().get(); LOG.info("Cleaning up {} pod: {}", state.workflowInstance().toKey(), executionId); dockerRunner.cleanup(executionId); } break; default: // do nothing } }
#vulnerable code @Override public void transitionInto(RunState state) { switch (state.state()) { case SUBMITTING: try { final String executionId = dockerRunnerStart(state); // this is racy final Event submitted = Event.submitted(state.workflowInstance(), executionId); try { stateManager.receive(submitted); } catch (StateManager.IsClosed isClosed) { LOG.warn("Could not send 'created' event", isClosed); } } catch (Exception e) { LOG.warn("Failed the docker starting procedure for " + state.workflowInstance().toKey(), e); stateManager.receiveIgnoreClosed(Event.halt(state.workflowInstance())); } break; case TERMINATED: case FAILED: case ERROR: if (state.executionId().isPresent()) { final String executionId = state.executionId().get(); LOG.info("Cleaning up {} pod: {}", state.workflowInstance().toKey(), executionId); dockerRunner.cleanup(executionId); } break; default: // do nothing } } #location 15 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Override public Map<WorkflowInstance, RunState> activeStates() { return states.entrySet().stream() .collect(Collectors.toMap(Map.Entry::getKey, (entry) -> entry.getValue().runState)); }
#vulnerable code @Override public Map<WorkflowInstance, RunState> activeStates() { final ImmutableMap.Builder<WorkflowInstance, RunState> builder = ImmutableMap.builder(); states.entrySet().forEach(entry -> builder.put(entry.getKey(), entry.getValue().runState)); return builder.build(); } #location 2 #vulnerability type CHECKERS_IMMUTABLE_CAST
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code BigtableStorage(Connection connection, Duration retryBaseDelay) { this.connection = Objects.requireNonNull(connection); this.retryBaseDelay = Objects.requireNonNull(retryBaseDelay); }
#vulnerable code Map<WorkflowInstance, Long> readActiveWorkflowInstances() throws IOException { final Table activeStatesTable = connection.getTable(ACTIVE_STATES_TABLE_NAME); final ImmutableMap.Builder<WorkflowInstance, Long> map = ImmutableMap.builder(); for (Result result : activeStatesTable.getScanner(STATE_CF, STATE_QUALIFIER)) { final WorkflowInstance workflowInstance = WorkflowInstance.parseKey(Bytes.toString(result.getRow())); final long counter = Long.parseLong(Bytes.toString(result.value())); map.put(workflowInstance, counter); } return map.build(); } #location 1 #vulnerability type CHECKERS_IMMUTABLE_CAST
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code private static KubernetesClient getKubernetesClient(Config config, String id) { try { final HttpTransport httpTransport = GoogleNetHttpTransport.newTrustedTransport(); final JsonFactory jsonFactory = Utils.getDefaultJsonFactory(); final GoogleCredential credential = GoogleCredential.getApplicationDefault(httpTransport, jsonFactory) .createScoped(ContainerScopes.all()); final Container gke = new Container.Builder(httpTransport, jsonFactory, credential) .setApplicationName(SERVICE_NAME) .build(); final String projectKey = GKE_CLUSTER_PREFIX + id + GKE_CLUSTER_PROJECT_ID; final String zoneKey = GKE_CLUSTER_PREFIX + id + GKE_CLUSTER_ZONE; final String clusterIdKey = GKE_CLUSTER_PREFIX + id + GKE_CLUSTER_ID; final Cluster cluster = gke.projects().zones().clusters() .get(config.getString(projectKey), config.getString(zoneKey), config.getString(clusterIdKey)).execute(); final io.fabric8.kubernetes.client.Config kubeConfig = new ConfigBuilder() .withMasterUrl("https://" + cluster.getEndpoint()) .withCaCertData(cluster.getMasterAuth().getClusterCaCertificate()) .withClientCertData(cluster.getMasterAuth().getClientCertificate()) .withClientKeyData(cluster.getMasterAuth().getClientKey()) .build(); return new DefaultKubernetesClient(kubeConfig); } catch (GeneralSecurityException | IOException e) { throw Throwables.propagate(e); } }
#vulnerable code private static KubernetesClient getKubernetesClient(Config config, String id) { try { final HttpTransport httpTransport = GoogleNetHttpTransport.newTrustedTransport(); final JsonFactory jsonFactory = Utils.getDefaultJsonFactory(); final GoogleCredential credential = GoogleCredential.getApplicationDefault(httpTransport, jsonFactory) .createScoped(ContainerScopes.all()); final Container gke = new Container.Builder(httpTransport, jsonFactory, credential) .setApplicationName(SERVICE_NAME) .build(); final String projectKey = GKE_CLUSTER_PREFIX + id + GKE_CLUSTER_PROJECT_ID; final String zoneKey = GKE_CLUSTER_PREFIX + id + GKE_CLUSTER_ZONE; final String clusterIdKey = GKE_CLUSTER_PREFIX + id + GKE_CLUSTER_ID; final Cluster cluster = gke.projects().zones().clusters() .get(config.getString(projectKey), config.getString(zoneKey), config.getString(clusterIdKey)).execute(); final io.fabric8.kubernetes.client.Config kubeConfig = new ConfigBuilder() .withMasterUrl("https://" + cluster.getEndpoint()) .withCaCertData(cluster.getMasterAuth().getClusterCaCertificate()) .withClientCertData(cluster.getMasterAuth().getClientCertificate()) .withClientKeyData(cluster.getMasterAuth().getClientKey()) .build(); return new AutoAdaptableKubernetesClient(kubeConfig).inNamespace(KUBERNETES_NAMESPACE); } catch (GeneralSecurityException | IOException e) { throw Throwables.propagate(e); } } #location 28 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code DatastoreStorage(Datastore datastore, Duration retryBaseDelay) { this.datastore = Objects.requireNonNull(datastore); this.retryBaseDelay = Objects.requireNonNull(retryBaseDelay); this.componentKeyFactory = datastore.newKeyFactory().kind(KIND_COMPONENT); this.globalConfigKey = datastore.newKeyFactory().kind(KIND_STYX_CONFIG).newKey(KEY_GLOBAL_CONFIG); }
#vulnerable code List<Backfill> getBackfills() { final EntityQuery query = Query.entityQueryBuilder().kind(KIND_BACKFILL).build(); final QueryResults<Entity> results = datastore.run(query); final ImmutableList.Builder<Backfill> resources = ImmutableList.builder(); while (results.hasNext()) { resources.add(entityToBackfill(results.next())); } return resources.build(); } #location 1 #vulnerability type CHECKERS_IMMUTABLE_CAST
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Override public void transitionInto(RunState state) { switch (state.state()) { case SUBMITTING: // Perform rate limited submission on a separate thread pool to avoid blocking the caller. executor.submit(() -> { rateLimiter.acquire(); try { final String executionId = dockerRunnerStart(state); // this is racy final Event submitted = Event.submitted(state.workflowInstance(), executionId); try { stateManager.receive(submitted); } catch (StateManager.IsClosed isClosed) { LOG.warn("Could not send 'created' event", isClosed); } } catch (ResourceNotFoundException e) { LOG.error("Unable to start docker procedure.", e); stateManager.receiveIgnoreClosed(Event.halt(state.workflowInstance())); } catch (Throwable e) { try { LOG.error("Failed the docker starting procedure for " + state.workflowInstance().toKey(), e); stateManager.receive(Event.runError(state.workflowInstance(), e.getMessage())); } catch (StateManager.IsClosed isClosed) { LOG.warn("Failed to send 'runError' event", isClosed); } } }); break; case TERMINATED: case FAILED: case ERROR: if (state.data().executionId().isPresent()) { final String executionId = state.data().executionId().get(); boolean debugEnabled = false; try { debugEnabled = storage.debugEnabled(); } catch (IOException e) { LOG.info("Couldn't fetch debug flag. Will clean up pod anyway."); } if (!debugEnabled) { LOG.info("Cleaning up {} pod: {}", state.workflowInstance().toKey(), executionId); dockerRunner.cleanup(executionId); } else { LOG.info("Keeping {} pod: {}", state.workflowInstance().toKey(), executionId); } } break; default: // do nothing } }
#vulnerable code @Override public void transitionInto(RunState state) { switch (state.state()) { case SUBMITTING: try { final String executionId = dockerRunnerStart(state); // this is racy final Event submitted = Event.submitted(state.workflowInstance(), executionId); try { stateManager.receive(submitted); } catch (StateManager.IsClosed isClosed) { LOG.warn("Could not send 'created' event", isClosed); } } catch (ResourceNotFoundException e) { LOG.error("Unable to start docker procedure.", e); stateManager.receiveIgnoreClosed(Event.halt(state.workflowInstance())); } catch (Throwable e) { try { LOG.error("Failed the docker starting procedure for " + state.workflowInstance().toKey(), e); stateManager.receive(Event.runError(state.workflowInstance(), e.getMessage())); } catch (StateManager.IsClosed isClosed) { LOG.warn("Failed to send 'runError' event", isClosed); } } break; case TERMINATED: case FAILED: case ERROR: if (state.data().executionId().isPresent()) { final String executionId = state.data().executionId().get(); boolean debugEnabled = false; try { debugEnabled = storage.debugEnabled(); } catch (IOException e) { LOG.info("Couldn't fetch debug flag. Will clean up pod anyway."); } if (!debugEnabled) { LOG.info("Cleaning up {} pod: {}", state.workflowInstance().toKey(), executionId); dockerRunner.cleanup(executionId); } else { LOG.info("Keeping {} pod: {}", state.workflowInstance().toKey(), executionId); } } break; default: // do nothing } } #location 19 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code DatastoreStorage(Datastore datastore, Duration retryBaseDelay) { this.datastore = Objects.requireNonNull(datastore); this.retryBaseDelay = Objects.requireNonNull(retryBaseDelay); this.componentKeyFactory = datastore.newKeyFactory().kind(KIND_COMPONENT); this.globalConfigKey = datastore.newKeyFactory().kind(KIND_STYX_CONFIG).newKey(KEY_GLOBAL_CONFIG); }
#vulnerable code Map<WorkflowInstance, Long> allActiveStates() throws IOException { final EntityQuery activeStatesQuery = Query.entityQueryBuilder() .kind(KIND_ACTIVE_STATE) .build(); final ImmutableMap.Builder<WorkflowInstance, Long> mapBuilder = ImmutableMap.builder(); final QueryResults<Entity> results = datastore.run(activeStatesQuery); while (results.hasNext()) { final Entity activeState = results.next(); final WorkflowInstance instance = parseWorkflowInstance(activeState); final long counter = activeState.getLong(PROPERTY_ACTIVE_STATE_COUNTER); mapBuilder.put(instance, counter); } return mapBuilder.build(); } #location 1 #vulnerability type CHECKERS_IMMUTABLE_CAST
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Override protected void doRequest(ServletTransaction transaction) throws ServletException { try { HttpServletRequest request = transaction.getServletRequest(); Client client = ClientCatalog .getClient(request.getParameter("use")); String report = request.getParameter("report"); String emails = request.getParameter("emails"); if (emails == null) return; HtmlEmail htmlEmail = client.getMailer().getHtmlEmail(emails, null); StringWriter sw = new StringWriter(); PrintWriter pw = new PrintWriter(sw); if ("statistics".equals(report)) { htmlEmail.setSubject("OpenSearchServer statistics report"); doStatistics(client, request.getParameter("stat"), request .getParameter("period"), pw); } pw.close(); sw.close(); String html = sw.toString(); if (html == null || html.length() == 0) { transaction.addXmlResponse("Result", "Nothing to send"); } else { htmlEmail.setHtmlMsg(sw.toString()); htmlEmail .setTextMsg("Your email client does not support HTML messages"); htmlEmail.send(); } transaction.addXmlResponse("MailSent", emails); } catch (Exception e) { throw new ServletException(e); } }
#vulnerable code @Override protected void doRequest(ServletTransaction transaction) throws ServletException { try { HttpServletRequest request = transaction.getServletRequest(); Client client = ClientCatalog .getClient(request.getParameter("use")); String report = request.getParameter("report"); String emails = request.getParameter("emails"); if (emails == null) return; HtmlEmail htmlEmail = client.getMailer().getHtmlEmail(emails, null); StringWriter sw = new StringWriter(); PrintWriter pw = new PrintWriter(sw); if ("statistics".equals(report)) { htmlEmail.setSubject("OpenSearchServer statistics report"); doStatistics(client, request.getParameter("stat"), request .getParameter("period"), pw); } htmlEmail.setHtmlMsg(sw.toString()); htmlEmail.send(); transaction.addXmlResponse("MailSent", emails); } catch (Exception e) { throw new ServletException(e); } } #location 15 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public void deleteUrl(String sUrl) throws SearchLibException { try { targetClient.deleteDocument(sUrl); urlDbClient.deleteDocument(sUrl); } catch (CorruptIndexException e) { throw new SearchLibException(e); } catch (LockObtainFailedException e) { throw new SearchLibException(e); } catch (IOException e) { throw new SearchLibException(e); } catch (URISyntaxException e) { throw new SearchLibException(e); } catch (InstantiationException e) { throw new SearchLibException(e); } catch (IllegalAccessException e) { throw new SearchLibException(e); } catch (ClassNotFoundException e) { throw new SearchLibException(e); } }
#vulnerable code public void deleteUrl(String sUrl) throws SearchLibException { try { client.deleteDocument(sUrl); } catch (CorruptIndexException e) { throw new SearchLibException(e); } catch (LockObtainFailedException e) { throw new SearchLibException(e); } catch (IOException e) { throw new SearchLibException(e); } catch (URISyntaxException e) { throw new SearchLibException(e); } catch (InstantiationException e) { throw new SearchLibException(e); } catch (IllegalAccessException e) { throw new SearchLibException(e); } catch (ClassNotFoundException e) { throw new SearchLibException(e); } } #location 3 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Override protected void reloadPage() { synchronized (this) { fieldLeft = null; selectedFacet = null; super.reloadPage(); } }
#vulnerable code @Override protected void reloadPage() { fieldLeft = null; selectedFacet = null; super.reloadPage(); } #location 3 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException { super.readExternal(in); fragmenter = External.readObject(in); tag = External.readUTF(in); maxDocChar = in.readInt(); separator = External.readUTF(in); maxSnippetSize = in.readInt(); maxSnippetNumber = in.readInt(); searchTerms = External.readStringArray(in); }
#vulnerable code public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException { super.readExternal(in); fragmenter = External.readObject(in); tag = External.readUTF(in); maxDocChar = in.readInt(); separator = External.readUTF(in); maxSnippetSize = in.readInt(); maxSnippetNumber = in.readInt(); int l = in.readInt(); if (l > 0) { searchTerms = new String[l]; External.readArray(in, searchTerms); } else searchTerms = null; } #location 13 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public void onUpload() throws InterruptedException, XPathExpressionException, NoSuchAlgorithmException, ParserConfigurationException, SAXException, IOException, URISyntaxException, SearchLibException, InstantiationException, IllegalAccessException, ClassNotFoundException { Media media = Fileupload.get(); if (media == null) return; synchronized (this) { setCurrentDocument(null); ParserSelector parserSelector = getClient().getParserSelector(); Parser parser = null; String contentType = media.getContentType(); if (contentType != null) parser = parserSelector.getParserFromMimeType(contentType); if (parser == null) { String extension = FileUtils.getFileNameExtension(media .getName()); parser = parserSelector.getParserFromExtension(extension); } if (parser == null) { Messagebox.show("No parser found for that document type (" + contentType + " - " + media.getName() + ')'); return; } BasketDocument basketDocument = parser.getBasketDocument(); basketDocument.addIfNoEmpty("filename", media.getName()); basketDocument.addIfNoEmpty("content_type", contentType); if (media.inMemory()) { if (media.isBinary()) parser.parseContent(media.getByteData()); else parser.parseContent(media.getStringData()); } else { if (media.isBinary()) parser.parseContent(media.getStreamData()); else parser.parseContent(media.getReaderData()); } setCurrentDocument(basketDocument); reloadPage(); } }
#vulnerable code public void onUpload() throws InterruptedException, XPathExpressionException, NoSuchAlgorithmException, ParserConfigurationException, SAXException, IOException, URISyntaxException, SearchLibException, InstantiationException, IllegalAccessException, ClassNotFoundException { Media media = Fileupload.get(); if (media == null) return; setCurrentDocument(null); ParserSelector parserSelector = getClient().getParserSelector(); Parser parser = null; String contentType = media.getContentType(); if (contentType != null) parser = parserSelector.getParserFromMimeType(contentType); if (parser == null) { String extension = FileUtils.getFileNameExtension(media.getName()); parser = parserSelector.getParserFromExtension(extension); } if (parser == null) { Messagebox.show("No parser found for that document type (" + contentType + " - " + media.getName() + ')'); return; } BasketDocument basketDocument = parser.getBasketDocument(); setCurrentDocument(basketDocument); basketDocument.addIfNoEmpty("filename", media.getName()); basketDocument.addIfNoEmpty("content_type", contentType); synchronized (this) { if (media.inMemory()) { if (media.isBinary()) parser.parseContent(media.getByteData()); else parser.parseContent(media.getStringData()); } else { if (media.isBinary()) parser.parseContent(media.getStreamData()); else parser.parseContent(media.getReaderData()); } reloadPage(); } } #location 28 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Override protected void reloadPage() { synchronized (this) { fieldLeft = null; selectedFacet = null; super.reloadPage(); } }
#vulnerable code @Override protected void reloadPage() { fieldLeft = null; selectedFacet = null; super.reloadPage(); } #location 4 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Override protected void doRequest(ServletTransaction transaction) throws ServletException { try { Client client = Client.getWebAppInstance(); HttpServletRequest request = transaction.getServletRequest(); String indexName = request.getParameter("index"); String uniq = request.getParameter("uniq"); String docId = request.getParameter("docId"); boolean byId = request.getParameter("byId") != null; Object result = null; if (uniq != null) result = deleteUniqDoc(client, indexName, uniq); else if (docId != null) result = deleteDocById(client, indexName, Integer .parseInt(docId)); else result = doObjectRequest(request, indexName, byId); PrintWriter pw = transaction.getWriter("UTF-8"); pw.println(result); } catch (Exception e) { throw new ServletException(e); } }
#vulnerable code @Override protected void doRequest(ServletTransaction transaction) throws ServletException { try { Client client = Client.getWebAppInstance(); HttpServletRequest request = transaction.getServletRequest(); String indexName = request.getParameter("index"); String uniq = request.getParameter("uniq"); Object result = null; if (uniq != null) result = deleteDoc(client, indexName, uniq); else result = doObjectRequest(request, indexName); PrintWriter pw = transaction.getWriter("UTF-8"); pw.println(result); } catch (Exception e) { throw new ServletException(e); } } #location 11 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public void reload(boolean optimize) throws IOException, URISyntaxException, SearchLibException, InstantiationException, IllegalAccessException, ClassNotFoundException { if (optimize) { urlDbClient.reload(null); urlDbClient.getIndex().optimize(null); targetClient.reload(null); targetClient.getIndex().optimize(null); } urlDbClient.reload(null); targetClient.reload(null); }
#vulnerable code public void reload(boolean optimize) throws IOException, URISyntaxException, SearchLibException, InstantiationException, IllegalAccessException, ClassNotFoundException { if (optimize) { client.reload(null); client.getIndex().optimize(null); } client.reload(null); } #location 5 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public void deleteUrls(Collection<String> workDeleteUrlList) throws SearchLibException { try { targetClient.deleteDocuments(workDeleteUrlList); urlDbClient.deleteDocuments(workDeleteUrlList); } catch (CorruptIndexException e) { throw new SearchLibException(e); } catch (LockObtainFailedException e) { throw new SearchLibException(e); } catch (IOException e) { throw new SearchLibException(e); } catch (URISyntaxException e) { throw new SearchLibException(e); } catch (InstantiationException e) { throw new SearchLibException(e); } catch (IllegalAccessException e) { throw new SearchLibException(e); } catch (ClassNotFoundException e) { throw new SearchLibException(e); } }
#vulnerable code public void deleteUrls(Collection<String> workDeleteUrlList) throws SearchLibException { try { client.deleteDocuments(workDeleteUrlList); } catch (CorruptIndexException e) { throw new SearchLibException(e); } catch (LockObtainFailedException e) { throw new SearchLibException(e); } catch (IOException e) { throw new SearchLibException(e); } catch (URISyntaxException e) { throw new SearchLibException(e); } catch (InstantiationException e) { throw new SearchLibException(e); } catch (IllegalAccessException e) { throw new SearchLibException(e); } catch (ClassNotFoundException e) { throw new SearchLibException(e); } } #location 4 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public void writeXmlConfig(XmlWriter xmlWriter) throws SAXException, SearchLibException, SecurityException, IOException { xmlWriter.startElement("system"); xmlWriter.startElement("availableProcessors", "value", Integer .toString(getAvailableProcessors())); xmlWriter.endElement(); xmlWriter.startElement("freeMemory", "value", Long .toString(getFreeMemory()), "rate", Double .toString(getMemoryRate())); xmlWriter.endElement(); xmlWriter.startElement("maxMemory", "value", Long .toString(getMaxMemory())); xmlWriter.endElement(); xmlWriter.startElement("totalMemory", "value", Long .toString(getTotalMemory())); xmlWriter.endElement(); xmlWriter.startElement("indexCount", "value", Integer .toString(getIndexCount())); xmlWriter.endElement(); Double rate = getDiskRate(); if (rate == null) xmlWriter.startElement("freeDiskSpace", "value", getFreeDiskSpace() .toString()); else xmlWriter.startElement("freeDiskSpace", "value", getFreeDiskSpace() .toString(), "rate", rate.toString()); xmlWriter.endElement(); xmlWriter.startElement("dataDirectoryPath", "value", getDataDirectoryPath()); xmlWriter.endElement(); xmlWriter.endElement(); xmlWriter.startElement("properties"); for (Entry<Object, Object> prop : getProperties()) { xmlWriter.startElement("property", "name", prop.getKey().toString(), "value", prop.getValue() .toString()); xmlWriter.endElement(); } xmlWriter.endElement(); }
#vulnerable code public void writeXmlConfig(XmlWriter xmlWriter) throws SAXException, SearchLibException { xmlWriter.startElement("system"); xmlWriter.startElement("availableProcessors", "value", Integer .toString(getAvailableProcessors())); xmlWriter.endElement(); xmlWriter.startElement("freeMemory", "value", Long .toString(getFreeMemory()), "rate", Double .toString(getMemoryRate())); xmlWriter.endElement(); xmlWriter.startElement("maxMemory", "value", Long .toString(getMaxMemory())); xmlWriter.endElement(); xmlWriter.startElement("totalMemory", "value", Long .toString(getTotalMemory())); xmlWriter.endElement(); xmlWriter.startElement("indexCount", "value", Integer .toString(getIndexCount())); xmlWriter.endElement(); xmlWriter.startElement("freeDiskSpace", "value", getFreeDiskSpace() .toString()); xmlWriter.endElement(); xmlWriter.startElement("dataDirectoryPath", "value", getDataDirectoryPath()); xmlWriter.endElement(); xmlWriter.endElement(); xmlWriter.startElement("properties"); for (Entry<Object, Object> prop : getProperties()) { xmlWriter.startElement("property", "name", prop.getKey().toString(), "value", prop.getValue() .toString()); xmlWriter.endElement(); } xmlWriter.endElement(); } #location 27 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public void onAdd() throws SearchLibException, UnsupportedEncodingException, ParseException, InterruptedException { synchronized (this) { if (getSelectedFile() != null) { // Already In if (getClient().getFilePathManager().getFilePaths( getSelectedFile().getPath(), 0, 0, null) > 0) { Messagebox .show("Already In.", "Jaeksoft OpenSearchServer", Messagebox.OK, org.zkoss.zul.Messagebox.INFORMATION); } else { /* * List<FilePathItem> list = FilePathManager( * getSelectedFile().getPath(), getSelectedFile() * .isDirectory() && isSelectedFileCheck()); * * if (list.size() > 0) { * getClient().getFilePathManager().addList(list, false); } */ pathList = null; setSelectedFileCheck(false); setSelectedFilePath(null); reloadPage(); } } } }
#vulnerable code public void onAdd() throws SearchLibException, UnsupportedEncodingException, ParseException, InterruptedException { synchronized (this) { if (getSelectedFile() != null) { // Already In if (getClient().getFilePathManager().getStrictPaths( getSelectedFile().getPath(), 0, 0, null) > 0) { Messagebox .show("Already In.", "Jaeksoft OpenSearchServer", Messagebox.OK, org.zkoss.zul.Messagebox.INFORMATION); } else { List<PathItem> list = FilePathManager.addPath( getSelectedFile().getPath(), getSelectedFile() .isDirectory() && isSelectedFileCheck()); if (list.size() > 0) { getClient().getFilePathManager().addList(list, false); } pathList = null; setSelectedFileCheck(false); setSelectedFilePath(null); reloadPage(); } } } } #location 18 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public void getNewUrlToFetch(NamedItem host, long limit, List<UrlItem> urlList) throws SearchLibException, ParseException, IOException, SyntaxError, URISyntaxException, ClassNotFoundException, InterruptedException, InstantiationException, IllegalAccessException { SearchRequest searchRequest = urlDbClient .getNewSearchRequest("urlSearch"); searchRequest.addFilter("host:\"" + SearchRequest.escapeQuery(host.getName()) + "\""); searchRequest.setQueryString("*:*"); filterQueryToFetchNew(searchRequest); searchRequest.setRows((int) limit); Result result = urlDbClient.search(searchRequest); for (ResultDocument item : result) urlList.add(new UrlItem(item)); }
#vulnerable code public void getNewUrlToFetch(NamedItem host, long limit, List<UrlItem> urlList) throws SearchLibException, ParseException, IOException, SyntaxError, URISyntaxException, ClassNotFoundException, InterruptedException, InstantiationException, IllegalAccessException { SearchRequest searchRequest = client.getNewSearchRequest("urlSearch"); searchRequest.addFilter("host:\"" + SearchRequest.escapeQuery(host.getName()) + "\""); searchRequest.setQueryString("*:*"); filterQueryToFetchNew(searchRequest); searchRequest.setRows((int) limit); Result result = client.search(searchRequest); for (ResultDocument item : result) urlList.add(new UrlItem(item)); } #location 12 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public void updateUrlItems(List<UrlItem> urlItems) throws SearchLibException { try { List<IndexDocument> documents = new ArrayList<IndexDocument>( urlItems.size()); for (UrlItem urlItem : urlItems) { IndexDocument indexDocument = new IndexDocument(); urlItem.populate(indexDocument); documents.add(indexDocument); } urlDbClient.updateDocuments(documents); } catch (NoSuchAlgorithmException e) { throw new SearchLibException(e); } catch (IOException e) { throw new SearchLibException(e); } catch (URISyntaxException e) { throw new SearchLibException(e); } catch (InstantiationException e) { throw new SearchLibException(e); } catch (IllegalAccessException e) { throw new SearchLibException(e); } catch (ClassNotFoundException e) { throw new SearchLibException(e); } }
#vulnerable code public void updateUrlItems(List<UrlItem> urlItems) throws SearchLibException { try { List<IndexDocument> documents = new ArrayList<IndexDocument>( urlItems.size()); for (UrlItem urlItem : urlItems) { IndexDocument indexDocument = new IndexDocument(); urlItem.populate(indexDocument); documents.add(indexDocument); } client.updateDocuments(documents); } catch (NoSuchAlgorithmException e) { throw new SearchLibException(e); } catch (IOException e) { throw new SearchLibException(e); } catch (URISyntaxException e) { throw new SearchLibException(e); } catch (InstantiationException e) { throw new SearchLibException(e); } catch (IllegalAccessException e) { throw new SearchLibException(e); } catch (ClassNotFoundException e) { throw new SearchLibException(e); } } #location 11 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public void getStartingWith(String queryString, Field field, String start, int limit, List<NamedItem> list) throws ParseException, IOException, SyntaxError, URISyntaxException, ClassNotFoundException, InterruptedException, SearchLibException, InstantiationException, IllegalAccessException { SearchRequest searchRequest = urlDbClient.getNewSearchRequest(field + "Facet"); searchRequest.setQueryString(queryString); searchRequest.getFilterList().add(field + ":" + start + "*", Source.REQUEST); getFacetLimit(field, searchRequest, limit, list); }
#vulnerable code public void getStartingWith(String queryString, Field field, String start, int limit, List<NamedItem> list) throws ParseException, IOException, SyntaxError, URISyntaxException, ClassNotFoundException, InterruptedException, SearchLibException, InstantiationException, IllegalAccessException { SearchRequest searchRequest = client.getNewSearchRequest(field + "Facet"); searchRequest.setQueryString(queryString); searchRequest.getFilterList().add(field + ":" + start + "*", Source.REQUEST); getFacetLimit(field, searchRequest, limit, list); } #location 11 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public long getUrls(SearchRequest searchRequest, Field orderBy, boolean orderAsc, long start, long rows, List<UrlItem> list) throws SearchLibException { searchRequest.setStart((int) start); searchRequest.setRows((int) rows); try { if (orderBy != null) searchRequest.addSort(orderBy.name, !orderAsc); Result result = urlDbClient.search(searchRequest); if (list != null) for (ResultDocument doc : result) list.add(new UrlItem(doc)); return result.getNumFound(); } catch (ParseException e) { throw new SearchLibException(e); } catch (IOException e) { throw new SearchLibException(e); } catch (RuntimeException e) { throw new SearchLibException(e); } catch (SyntaxError e) { throw new SearchLibException(e); } catch (URISyntaxException e) { throw new SearchLibException(e); } catch (ClassNotFoundException e) { throw new SearchLibException(e); } catch (InterruptedException e) { throw new SearchLibException(e); } catch (InstantiationException e) { throw new SearchLibException(e); } catch (IllegalAccessException e) { throw new SearchLibException(e); } }
#vulnerable code public long getUrls(SearchRequest searchRequest, Field orderBy, boolean orderAsc, long start, long rows, List<UrlItem> list) throws SearchLibException { searchRequest.setStart((int) start); searchRequest.setRows((int) rows); try { if (orderBy != null) searchRequest.addSort(orderBy.name, !orderAsc); Result result = client.search(searchRequest); if (list != null) for (ResultDocument doc : result) list.add(new UrlItem(doc)); return result.getNumFound(); } catch (ParseException e) { throw new SearchLibException(e); } catch (IOException e) { throw new SearchLibException(e); } catch (RuntimeException e) { throw new SearchLibException(e); } catch (SyntaxError e) { throw new SearchLibException(e); } catch (URISyntaxException e) { throw new SearchLibException(e); } catch (ClassNotFoundException e) { throw new SearchLibException(e); } catch (InterruptedException e) { throw new SearchLibException(e); } catch (InstantiationException e) { throw new SearchLibException(e); } catch (IllegalAccessException e) { throw new SearchLibException(e); } } #location 9 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code private void renderDocument(int pos) throws CorruptIndexException, IOException, ParseException, SyntaxError { writer.print("\t<doc score=\""); writer.print(result.getScore(pos)); writer.print("\" pos=\""); writer.print(pos); writer.println("\">"); ResultDocument doc = result.getDocument(pos); for (Field field : searchRequest.getReturnFieldList()) renderField(doc, field); for (HighlightField field : searchRequest.getHighlightFieldList()) renderHighlightValue(doc, field); int cc = result.getCollapseCount(pos); if (cc > 0) { writer.print("\t\t<collapseCount>"); writer.print(cc); writer.println("</collapseCount>"); } writer.println("\t</doc>"); }
#vulnerable code private void renderDocument(int pos) throws CorruptIndexException, IOException, ParseException, SyntaxError { writer.print("\t<doc score=\""); writer.print(result.getDocs()[pos].score); writer.print("\" pos=\""); writer.print(pos); writer.println("\">"); ResultDocument doc = result.getDocument(pos); for (Field field : searchRequest.getReturnFieldList()) renderField(doc, field); for (HighlightField field : searchRequest.getHighlightFieldList()) renderHighlightValue(doc, field); int cc = result.getCollapseCount(pos); if (cc > 0) { writer.print("\t\t<collapseCount>"); writer.print(cc); writer.println("</collapseCount>"); } writer.println("\t</doc>"); } #location 10 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Override protected void reloadPage() { synchronized (this) { highlightFieldLeft = null; selectedHighlight = null; super.reloadPage(); } }
#vulnerable code @Override protected void reloadPage() { highlightFieldLeft = null; selectedHighlight = null; super.reloadPage(); } #location 4 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public void getOldUrlToFetch(NamedItem host, Date fetchIntervalDate, long limit, List<UrlItem> urlList) throws SearchLibException, ParseException, IOException, SyntaxError, URISyntaxException, ClassNotFoundException, InterruptedException, InstantiationException, IllegalAccessException { SearchRequest searchRequest = urlDbClient .getNewSearchRequest("urlSearch"); searchRequest.addFilter("host:\"" + SearchRequest.escapeQuery(host.getName()) + "\""); searchRequest.setQueryString("*:*"); filterQueryToFetchOld(searchRequest, fetchIntervalDate); searchRequest.setRows((int) limit); Result result = urlDbClient.search(searchRequest); for (ResultDocument item : result) urlList.add(new UrlItem(item)); }
#vulnerable code public void getOldUrlToFetch(NamedItem host, Date fetchIntervalDate, long limit, List<UrlItem> urlList) throws SearchLibException, ParseException, IOException, SyntaxError, URISyntaxException, ClassNotFoundException, InterruptedException, InstantiationException, IllegalAccessException { SearchRequest searchRequest = client.getNewSearchRequest("urlSearch"); searchRequest.addFilter("host:\"" + SearchRequest.escapeQuery(host.getName()) + "\""); searchRequest.setQueryString("*:*"); filterQueryToFetchOld(searchRequest, fetchIntervalDate); searchRequest.setRows((int) limit); Result result = client.search(searchRequest); for (ResultDocument item : result) urlList.add(new UrlItem(item)); } #location 12 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Override protected void reloadPage() { synchronized (this) { selectedSort = null; sortFieldLeft = null; super.reloadPage(); } }
#vulnerable code @Override protected void reloadPage() { selectedSort = null; sortFieldLeft = null; super.reloadPage(); } #location 4 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public void reload(boolean optimize) throws IOException, URISyntaxException, SearchLibException, InstantiationException, IllegalAccessException, ClassNotFoundException { if (optimize) { urlDbClient.reload(null); urlDbClient.getIndex().optimize(null); targetClient.reload(null); targetClient.getIndex().optimize(null); } urlDbClient.reload(null); targetClient.reload(null); }
#vulnerable code public void reload(boolean optimize) throws IOException, URISyntaxException, SearchLibException, InstantiationException, IllegalAccessException, ClassNotFoundException { if (optimize) { client.reload(null); client.getIndex().optimize(null); } client.reload(null); } #location 5 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public void run(ResultScoreDoc[] fetchedDocs, int fetchLength) throws IOException { collapsedDoc = null; if (fetchedDocs == null) return; if (fetchLength > fetchedDocs.length) fetchLength = fetchedDocs.length; collapse(fetchedDocs, fetchLength); }
#vulnerable code public void run(ResultScoreDoc[] fetchedDocs, int fetchLength) throws IOException { collapsedDoc = null; if (fetchedDocs == null) return; if (fetchLength > fetchedDocs.length) fetchLength = fetchedDocs.length; OpenBitSet collapsedSet = new OpenBitSet(fetchLength); String lastTerm = null; int adjacent = 0; collapsedDocCount = 0; for (int i = 0; i < fetchLength; i++) { String term = fetchedDocs[i].collapseTerm; if (term != null && term.equals(lastTerm)) { if (++adjacent >= collapseMax) collapsedSet.set(i); } else { lastTerm = term; adjacent = 0; } } collapsedDocCount = (int) collapsedSet.cardinality(); collapsedDoc = new ResultScoreDoc[fetchLength - collapsedDocCount]; int currentPos = 0; ResultScoreDoc collapseDoc = null; for (int i = 0; i < fetchLength; i++) { if (!collapsedSet.get(i)) { collapseDoc = fetchedDocs[i]; collapseDoc.collapseCount = 0; collapsedDoc[currentPos++] = collapseDoc; } else { collapseDoc.collapseCount++; } } } #location 39 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code final protected void getFragments(String originalText, FragmentList fragments, int vectorOffset) { originalTextLength = originalText.length(); if (splitPos == null) splitPos = new TreeSet<Integer>(); splitPos.clear(); check(originalText); Iterator<Integer> splitIterator = splitPos.iterator(); int pos = 0; Fragment lastFragment = null; while (splitIterator.hasNext()) { int nextSplitPos = splitIterator.next(); lastFragment = fragments.addOriginalText(originalText.substring( pos, nextSplitPos), vectorOffset, lastFragment == null); pos = nextSplitPos; } if (pos < originalText.length()) lastFragment = fragments.addOriginalText(originalText .substring(pos), vectorOffset, lastFragment == null); if (lastFragment != null) lastFragment.setEdge(true); }
#vulnerable code final protected void getFragments(String originalText, FragmentList fragments, int vectorOffset) { originalTextLength = originalText.length(); if (splitPos == null) splitPos = new TreeSet<Integer>(); splitPos.clear(); check(originalText); Iterator<Integer> splitIterator = splitPos.iterator(); int pos = 0; Fragment lastFragment = null; while (splitIterator.hasNext()) { int nextSplitPos = splitIterator.next(); lastFragment = fragments.addOriginalText(originalText.substring( pos, nextSplitPos), vectorOffset, lastFragment == null); pos = nextSplitPos; } if (pos < originalText.length()) lastFragment = fragments.addOriginalText(originalText .substring(pos), vectorOffset, lastFragment == null); lastFragment.setEdge(true); } #location 20 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public static HTMLDocument fetch(final URL url) throws IOException { final URLConnection conn = url.openConnection(); final String ct = conn.getContentType(); Charset cs = Charset.forName("Cp1252"); if (ct != null) { Matcher m = PAT_CHARSET.matcher(ct); if(m.find()) { final String charset = m.group(1); try { cs = Charset.forName(charset); } catch (UnsupportedCharsetException e) { // keep default } } } InputStream in = conn.getInputStream(); final String encoding = conn.getContentEncoding(); if(encoding != null) { if("gzip".equalsIgnoreCase(encoding)) { in = new GZIPInputStream(in); } else { System.err.println("WARN: unsupported Content-Encoding: "+encoding); } } ByteArrayOutputStream bos = new ByteArrayOutputStream(); byte[] buf = new byte[4096]; int r; while ((r = in.read(buf)) != -1) { bos.write(buf, 0, r); } in.close(); final byte[] data = bos.toByteArray(); return new HTMLDocument(data, cs); }
#vulnerable code public static HTMLDocument fetch(final URL url) throws IOException { final URLConnection conn = url.openConnection(); final String charset = conn.getContentEncoding(); Charset cs = Charset.forName("Cp1252"); if (charset != null) { try { cs = Charset.forName(charset); } catch (UnsupportedCharsetException e) { // keep default } } InputStream in = conn.getInputStream(); final String encoding = conn.getContentEncoding(); if(encoding != null) { if("gzip".equalsIgnoreCase(encoding)) { in = new GZIPInputStream(in); } else { System.err.println("WARN: unsupported Content-Encoding: "+encoding); } } ByteArrayOutputStream bos = new ByteArrayOutputStream(); byte[] buf = new byte[4096]; int r; while ((r = in.read(buf)) != -1) { bos.write(buf, 0, r); } in.close(); final byte[] data = bos.toByteArray(); return new HTMLDocument(data, cs); } #location 35 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public String getText(final URL url) throws BoilerpipeProcessingException { try { return getText(HTMLFetcher.fetch(url).toInputSource()); } catch (IOException e) { throw new BoilerpipeProcessingException(e); } }
#vulnerable code public String getText(final URL url) throws BoilerpipeProcessingException { try { final URLConnection conn = url.openConnection(); final String encoding = conn.getContentEncoding(); Charset cs = Charset.forName("Cp1252"); if (encoding != null) { try { cs = Charset.forName(encoding); } catch (UnsupportedCharsetException e) { // keep default } } final InputStream in = conn.getInputStream(); InputSource is = new InputSource(in); if(cs != null) { is.setEncoding(cs.name()); } final String text = getText(is); in.close(); return text; } catch (IOException e) { throw new BoilerpipeProcessingException(e); } } #location 15 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public static HTMLDocument fetch(final URL url) throws IOException { final URLConnection conn = url.openConnection(); final String ct = conn.getContentType(); Charset cs = Charset.forName("Cp1252"); if (ct != null) { Matcher m = PAT_CHARSET.matcher(ct); if(m.find()) { final String charset = m.group(1); try { cs = Charset.forName(charset); } catch (UnsupportedCharsetException e) { // keep default } } } InputStream in = conn.getInputStream(); final String encoding = conn.getContentEncoding(); if(encoding != null) { if("gzip".equalsIgnoreCase(encoding)) { in = new GZIPInputStream(in); } else { System.err.println("WARN: unsupported Content-Encoding: "+encoding); } } ByteArrayOutputStream bos = new ByteArrayOutputStream(); byte[] buf = new byte[4096]; int r; while ((r = in.read(buf)) != -1) { bos.write(buf, 0, r); } in.close(); final byte[] data = bos.toByteArray(); return new HTMLDocument(data, cs); }
#vulnerable code public static HTMLDocument fetch(final URL url) throws IOException { final URLConnection conn = url.openConnection(); final String charset = conn.getContentEncoding(); Charset cs = Charset.forName("Cp1252"); if (charset != null) { try { cs = Charset.forName(charset); } catch (UnsupportedCharsetException e) { // keep default } } InputStream in = conn.getInputStream(); final String encoding = conn.getContentEncoding(); if(encoding != null) { if("gzip".equalsIgnoreCase(encoding)) { in = new GZIPInputStream(in); } else { System.err.println("WARN: unsupported Content-Encoding: "+encoding); } } ByteArrayOutputStream bos = new ByteArrayOutputStream(); byte[] buf = new byte[4096]; int r; while ((r = in.read(buf)) != -1) { bos.write(buf, 0, r); } in.close(); final byte[] data = bos.toByteArray(); return new HTMLDocument(data, cs); } #location 35 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code private void insertLoginLog(String username) { UmsAdmin admin = getAdminByUsername(username); if(admin==null) return; UmsAdminLoginLog loginLog = new UmsAdminLoginLog(); loginLog.setAdminId(admin.getId()); loginLog.setCreateTime(new Date()); ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes(); HttpServletRequest request = attributes.getRequest(); loginLog.setIp(request.getRemoteAddr()); loginLogMapper.insert(loginLog); }
#vulnerable code private void insertLoginLog(String username) { UmsAdmin admin = getAdminByUsername(username); UmsAdminLoginLog loginLog = new UmsAdminLoginLog(); loginLog.setAdminId(admin.getId()); loginLog.setCreateTime(new Date()); ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes(); HttpServletRequest request = attributes.getRequest(); loginLog.setIp(request.getRemoteAddr()); loginLogMapper.insert(loginLog); } #location 4 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public String getUserNameFromToken(String token) { String username; try { Claims claims = getClaimsFromToken(token); username = claims.getSubject(); } catch (Exception e) { username = null; } return username; }
#vulnerable code public String getUserNameFromToken(String token) { String username; try { Claims claims = getClaimsFromToken(token); username = claims.getSubject(); } catch (Exception e) { e.printStackTrace(); username = null; } return username; } #location 5 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code private Date getExpiredDateFromToken(String token) { Claims claims = getClaimsFromToken(token); return claims.getExpiration(); }
#vulnerable code private Date getExpiredDateFromToken(String token) { Date expiredDate = null; try { Claims claims = getClaimsFromToken(token); expiredDate = claims.getExpiration(); } catch (Exception e) { e.printStackTrace(); } return expiredDate; } #location 5 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Override public void onHttpFinish(QQHttpResponse response) { try { LOG.debug(response.getContentType()); String type = response.getContentType(); if(type!=null && (type.startsWith("application/x-javascript") || type.startsWith("application/json") || type.indexOf("text") >= 0 ) && response.getContentLength() > 0){ LOG.debug(response.getResponseString()); } if(response.getResponseCode() == QQHttpResponse.S_OK){ onHttpStatusOK(response); }else{ onHttpStatusError(response); } } catch (QQException e) { notifyActionEvent(QQActionEvent.Type.EVT_ERROR, e); } catch (JSONException e) { notifyActionEvent(QQActionEvent.Type.EVT_ERROR, new QQException(QQErrorCode.JSON_ERROR, e)); } catch (Throwable e){ notifyActionEvent(QQActionEvent.Type.EVT_ERROR, new QQException(QQErrorCode.UNKNOWN_ERROR, e)); } }
#vulnerable code @Override public void onHttpFinish(QQHttpResponse response) { try { LOG.debug(response.getContentType()); String type = response.getContentType(); if((type.startsWith("application/x-javascript") || type.startsWith("application/json") || type.indexOf("text") >= 0 ) && response.getContentLength() > 0){ LOG.debug(response.getResponseString()); } if(response.getResponseCode() == QQHttpResponse.S_OK){ onHttpStatusOK(response); }else{ onHttpStatusError(response); } } catch (QQException e) { notifyActionEvent(QQActionEvent.Type.EVT_ERROR, e); } catch (JSONException e) { notifyActionEvent(QQActionEvent.Type.EVT_ERROR, new QQException(QQErrorCode.JSON_ERROR, e)); } catch (Throwable e){ notifyActionEvent(QQActionEvent.Type.EVT_ERROR, new QQException(QQErrorCode.UNKNOWN_ERROR, e)); } } #location 6 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Test public void progressCallbackSend() throws Exception { final AtomicReference<String> body = new AtomicReference<String>(); handler = new RequestHandler() { @Override public void handle(Request request, HttpServletResponse response) { body.set(new String(read())); response.setStatus(HTTP_OK); } }; final File file = File.createTempFile("post", ".txt"); new FileWriter(file).append("hello").close(); final AtomicInteger tx = new AtomicInteger(0); ProgressCallback progress = new ProgressCallback() { public void onProgress(int transferred, int total) { assertEquals(file.length(), total); assertEquals(tx.incrementAndGet(), transferred); } }; post(url).bufferSize(1).progress(progress).send(file).code(); assertEquals(file.length(), tx.get()); }
#vulnerable code @Test public void progressCallbackSend() throws Exception { final AtomicReference<String> body = new AtomicReference<String>(); handler = new RequestHandler() { @Override public void handle(Request request, HttpServletResponse response) { body.set(new String(read())); response.setStatus(HTTP_OK); } }; final File file = File.createTempFile("post", ".txt"); new FileWriter(file).append("hello").close(); final AtomicInteger tx = new AtomicInteger(0); ProgressCallback progress = new ProgressCallback() { public void onProgress(int transferred, int total) { assertEquals(file.length(), total); assertEquals(tx.incrementAndGet(), transferred); } }; post(url).bufferSize(1).progress(progress).send(file); assertEquals(file.length(), tx.get()); } #location 22 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Test public void progressCallbackSendInputStream() throws Exception { final AtomicReference<String> body = new AtomicReference<String>(); handler = new RequestHandler() { @Override public void handle(Request request, HttpServletResponse response) { body.set(new String(read())); response.setStatus(HTTP_OK); } }; File file = File.createTempFile("post", ".txt"); new FileWriter(file).append("hello").close(); InputStream input = new FileInputStream(file); final AtomicInteger tx = new AtomicInteger(0); ProgressCallback progress = new ProgressCallback() { public void onProgress(int transferred, int total) { assertEquals(0, total); assertEquals(tx.incrementAndGet(), transferred); } }; post(url).bufferSize(1).progress(progress).send(input).code(); assertEquals(file.length(), tx.get()); }
#vulnerable code @Test public void progressCallbackSendInputStream() throws Exception { final AtomicReference<String> body = new AtomicReference<String>(); handler = new RequestHandler() { @Override public void handle(Request request, HttpServletResponse response) { body.set(new String(read())); response.setStatus(HTTP_OK); } }; File file = File.createTempFile("post", ".txt"); new FileWriter(file).append("hello").close(); InputStream input = new FileInputStream(file); final AtomicInteger tx = new AtomicInteger(0); ProgressCallback progress = new ProgressCallback() { public void onProgress(int transferred, int total) { assertEquals(0, total); assertEquals(tx.incrementAndGet(), transferred); } }; post(url).bufferSize(1).progress(progress).send(input); assertEquals(file.length(), tx.get()); } #location 22 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @org.junit.Test public void test() throws InterruptedException, IOException { Node node = new StandbyNode(); node.join(); new BufferedReader(new InputStreamReader(System.in)).readLine(); }
#vulnerable code @org.junit.Test public void test() throws InterruptedException, IOException { Node node = new StandbyNode(new Configuration("com.zuoxiaolong.niubi.job.jobs"), "localhost:2181,localhost:3181,localhost:4181"); node.join(); new BufferedReader(new InputStreamReader(System.in)).readLine(); } #location 4 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @org.junit.Test public void test() throws InterruptedException, IOException { Node node = new StandbyNode("localhost:2181,localhost:3181,localhost:4181", "http://localhost:8080/job", StringHelper.emptyArray()); node.join(); new BufferedReader(new InputStreamReader(System.in)).readLine(); }
#vulnerable code @org.junit.Test public void test() throws InterruptedException, IOException { Node node = new StandbyNode("localhost:2181,localhost:3181,localhost:4181", "http://localhost:8080/job"); node.join(); new BufferedReader(new InputStreamReader(System.in)).readLine(); } #location 4 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @org.junit.Test public void test() throws InterruptedException, IOException { Node node = new MasterSlaveNode(); node.join(); new BufferedReader(new InputStreamReader(System.in)).readLine(); }
#vulnerable code @org.junit.Test public void test() throws InterruptedException, IOException { Node node = new MasterSlaveNode(new Configuration("com.zuoxiaolong.niubi.job.jobs"), "localhost:2181,localhost:3181,localhost:4181"); node.join(); new BufferedReader(new InputStreamReader(System.in)).readLine(); } #location 4 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @org.junit.Test public void test() throws InterruptedException, IOException { Node node = new StandbyNode(); node.join(); new BufferedReader(new InputStreamReader(System.in)).readLine(); }
#vulnerable code @org.junit.Test public void test() throws InterruptedException, IOException { Node node = new StandbyNode(new Configuration("com.zuoxiaolong.niubi.job.jobs"), "localhost:2181,localhost:3181,localhost:4181"); node.join(); new BufferedReader(new InputStreamReader(System.in)).readLine(); } #location 5 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Override public List<MasterSlaveNodeData> getAllNodes() { List<ChildData> childDataList = getChildren(PathHelper.getParentPath(getMasterSlavePathApi().getNodePath())); if (ListHelper.isEmpty(childDataList)) { return null; } List<MasterSlaveNodeData> masterSlaveNodeDataList = childDataList.stream().map(MasterSlaveNodeData::new).collect(Collectors.toList()); return masterSlaveNodeDataList; }
#vulnerable code @Override public List<MasterSlaveNodeData> getAllNodes() { List<ChildData> childDataList = getChildren(PathHelper.getParentPath(getMasterSlavePathApi().getNodePath())); List<MasterSlaveNodeData> masterSlaveNodeDataList = childDataList.stream().map(MasterSlaveNodeData::new).collect(Collectors.toList()); return masterSlaveNodeDataList; } #location 4 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @org.junit.Test public void test() throws InterruptedException, IOException { Node node = new StandbyNode("localhost:2181,localhost:3181,localhost:4181", "http://localhost:8080/job", StringHelper.emptyArray()); node.join(); new BufferedReader(new InputStreamReader(System.in)).readLine(); }
#vulnerable code @org.junit.Test public void test() throws InterruptedException, IOException { Node node = new StandbyNode("localhost:2181,localhost:3181,localhost:4181", "http://localhost:8080/job"); node.join(); new BufferedReader(new InputStreamReader(System.in)).readLine(); } #location 5 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Override public List<StandbyNodeData> getAllNodes() { List<ChildData> childDataList = getChildren(PathHelper.getParentPath(getStandbyPathApi().getNodePath())); if (ListHelper.isEmpty(childDataList)) { return null; } List<StandbyNodeData> standbyNodeDataList = childDataList.stream().map(StandbyNodeData::new).collect(Collectors.toList()); return standbyNodeDataList; }
#vulnerable code @Override public List<StandbyNodeData> getAllNodes() { List<ChildData> childDataList = getChildren(PathHelper.getParentPath(getStandbyPathApi().getNodePath())); List<StandbyNodeData> standbyNodeDataList = childDataList.stream().map(StandbyNodeData::new).collect(Collectors.toList()); return standbyNodeDataList; } #location 4 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @org.junit.Test public void test() throws InterruptedException, IOException { Node node = new MasterSlaveNode(); node.join(); new BufferedReader(new InputStreamReader(System.in)).readLine(); }
#vulnerable code @org.junit.Test public void test() throws InterruptedException, IOException { Node node = new MasterSlaveNode(new Configuration("com.zuoxiaolong.niubi.job.jobs"), "localhost:2181,localhost:3181,localhost:4181"); node.join(); new BufferedReader(new InputStreamReader(System.in)).readLine(); } #location 5 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Override public List<Pair<String, String>> getColumns(String schema, String table) throws VerdictDBDbmsException { List<Pair<String, String>> columns = new ArrayList<>(); DbmsQueryResult queryResult = execute(syntax.getColumnsCommand(schema, table)); while (queryResult.next()) { String type = (String) queryResult.getValue(syntax.getColumnTypeColumnIndex()); type = type.toLowerCase(); columns.add( new ImmutablePair<>((String) queryResult.getValue(syntax.getColumnNameColumnIndex()), type)); } return columns; }
#vulnerable code @Override public List<Pair<String, String>> getColumns(String schema, String table) throws VerdictDBDbmsException { List<Pair<String, String>> columns = new ArrayList<>(); DbmsQueryResult queryResult = execute(syntax.getColumnsCommand(schema, table)); JdbcResultSet jdbcResultSet = new JdbcResultSet(queryResult); try { while (queryResult.next()) { String type = jdbcResultSet.getString(syntax.getColumnTypeColumnIndex()+1); type = type.toLowerCase(); // // remove the size of type // type = type.replaceAll("\\(.*\\)", ""); columns.add( new ImmutablePair<>(jdbcResultSet.getString(syntax.getColumnNameColumnIndex()+1), type)); } } catch (SQLException e) { throw new VerdictDBDbmsException(e); } finally { jdbcResultSet.close(); } return columns; } #location 5 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public List<String> getSchemas() throws SQLException { if (!schemaCache.isEmpty()){ return schemaCache; } schemaCache.addAll(connection.getSchemas()); return schemaCache; }
#vulnerable code public List<String> getSchemas() throws SQLException { if (!schemaCache.isEmpty()){ return schemaCache; } DbmsQueryResult queryResult = connection.executeQuery(syntax.getSchemaCommand()); JdbcResultSet jdbcQueryResult = new JdbcResultSet(queryResult); while (queryResult.next()) { schemaCache.add(jdbcQueryResult.getString(syntax.getSchemaNameColumnIndex())); } return schemaCache; } #location 3 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Override public ExactRelation rewriteWithSubsampledErrorBounds() { ExactRelation r = rewriteWithPartition(true); // construct a new list of select elements. the last element is __vpart, which should be omitted. // newElems and newAggs hold almost the same info; just replicate them to follow the structure // of AggregatedRelation-ProjectedRelation. List<SelectElem> newElems = new ArrayList<SelectElem>(); List<Expr> newAggs = new ArrayList<Expr>(); List<SelectElem> elems = ((ProjectedRelation) r).getSelectElems(); for (int i = 0; i < elems.size() - 1; i++) { SelectElem elem = elems.get(i); if (!elem.isagg()) { newElems.add(new SelectElem(ColNameExpr.from(elem.getAlias()), elem.getAlias())); } else { if (elem.getAlias().equals(partitionSizeAlias)) { continue; } ColNameExpr est = new ColNameExpr(elem.getAlias(), r.getAliasName()); ColNameExpr psize = new ColNameExpr(partitionSizeAlias, r.getAliasName()); // average estimate Expr averaged = null; if (elem.getExpr().isCountDistinct()) { // for count-distinct (i.e., universe samples), weighted average should not be used. averaged = FuncExpr.round(FuncExpr.avg(est)); } else { // weighted average averaged = BinaryOpExpr.from(FuncExpr.sum(BinaryOpExpr.from(est, psize, "*")), FuncExpr.sum(psize), "/"); if (elem.getExpr().isCount()) { averaged = FuncExpr.round(averaged); } } newElems.add(new SelectElem(averaged, elem.getAlias())); newAggs.add(averaged); // error estimation // scale by sqrt(subsample size) / sqrt(sample size) Expr error = BinaryOpExpr.from( BinaryOpExpr.from(FuncExpr.stddev(est), FuncExpr.sqrt(FuncExpr.avg(psize)), "*"), FuncExpr.sqrt(FuncExpr.sum(psize)), "/"); error = BinaryOpExpr.from(error, ConstantExpr.from(confidenceIntervalMultiplier()), "*"); newElems.add(new SelectElem(error, Relation.errorBoundColumn(elem.getAlias()))); newAggs.add(error); } } // this extra aggregation stage should be grouped by non-agg elements except for __vpart List<Expr> newGroupby = new ArrayList<Expr>(); for (SelectElem elem : elems) { if (!elem.isagg() && !elem.getAlias().equals(partitionColumnName())) { newGroupby.add(ColNameExpr.from(elem.getAlias())); } } r = new GroupedRelation(vc, r, newGroupby); r = new AggregatedRelation(vc, r, newAggs); r = new ProjectedRelation(vc, r, newElems); return r; }
#vulnerable code @Override public ExactRelation rewriteWithSubsampledErrorBounds() { ExactRelation newSource = source.rewriteWithSubsampledErrorBounds(); List<SelectElem> sourceElems = null; // newSource.getSelectList(); Set<String> colAliases = new HashSet<String>(); for (SelectElem e : sourceElems) { if (e.aliasPresent()) { // we're only interested in the columns for which aliases are present. // note that every column with aggregate function must have an alias (enforced by ColNameExpr class). colAliases.add(e.getAlias()); } } // we search for error bound columns based on the assumption that the error bound columns have the suffix attached // to the original agg columns. The suffix is obtained from the ApproxRelation#errColSuffix() method. // ApproxAggregatedRelation#rewriteWithSubsampledErrorBounds() method is responsible for having those columns. List<SelectElem> elemsWithErr = new ArrayList<SelectElem>(); for (SelectElem e : elems) { elemsWithErr.add(e); String errColName = errColName(e.getExpr().getText()); if (colAliases.contains(errColName)) { elemsWithErr.add(new SelectElem(new ColNameExpr(errColName), errColName)); } } ExactRelation r = new ProjectedRelation(vc, newSource, elemsWithErr); r.setAliasName(getAliasName()); return r; } #location 6 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Override public String visitQuery_specification(VerdictSQLParser.Query_specificationContext ctx) { StringBuilder sql = new StringBuilder(2000); // this statement computes the mean value AnalyticSelectStatementRewriter meanRewriter = new AnalyticSelectStatementRewriter(vc, queryString); meanRewriter.setDepth(depth+1); meanRewriter.setIndentLevel(defaultIndent + 6); String mainSql = meanRewriter.visit(ctx); cumulativeReplacedTableSources.putAll(meanRewriter.getCumulativeSampleTables()); // this statement computes the standard deviation BootstrapSelectStatementRewriter varianceRewriter = new BootstrapSelectStatementRewriter(vc, queryString); varianceRewriter.setDepth(depth+1); varianceRewriter.setIndentLevel(defaultIndent + 6); String subSql = varianceRewriter.varianceComputationStatement(ctx); String leftAlias = genAlias(); String rightAlias = genAlias(); // we combine those two statements using join. List<Pair<String, String>> thisColumnName2Aliases = new ArrayList<Pair<String, String>>(); List<Pair<String, String>> leftColName2Aliases = meanRewriter.getColName2Aliases(); // List<Boolean> leftAggColIndicator = meanRewriter.getAggregateColumnIndicator(); List<Pair<String, String>> rightColName2Aliases = varianceRewriter.getColName2Aliases(); // List<Boolean> rightAggColIndicator = varianceRewriter.getAggregateColumnIndicator(); sql.append(String.format("%sSELECT", indentString)); int leftSelectElemIndex = 0; int totalSelectElemIndex = 0; for (Pair<String, String> colName2Alias : leftColName2Aliases) { leftSelectElemIndex++; if (leftSelectElemIndex == 1) sql.append(" "); else sql.append(", "); if (meanRewriter.isAggregateColumn(leftSelectElemIndex)) { // mean totalSelectElemIndex++; String alias = genAlias(); sql.append(String.format("%s.%s AS %s", leftAlias, colName2Alias.getRight(), alias)); thisColumnName2Aliases.add(Pair.of(colName2Alias.getLeft(), alias)); // error (standard deviation * 1.96 (for 95% confidence interval)) totalSelectElemIndex++; alias = genAlias(); String matchingAliasName = null; for (Pair<String, String> r : rightColName2Aliases) { if (colName2Alias.getLeft().equals(r.getLeft())) { matchingAliasName = r.getRight(); } } sql.append(String.format(", %s.%s AS %s", rightAlias, matchingAliasName, alias)); thisColumnName2Aliases.add(Pair.of(colName2Alias.getLeft(), alias)); meanColIndex2ErrColIndex.put(totalSelectElemIndex-1, totalSelectElemIndex); } else { totalSelectElemIndex++; sql.append(String.format("%s.%s AS %s", leftAlias, colName2Alias.getRight(), colName2Alias.getRight())); thisColumnName2Aliases.add(Pair.of(colName2Alias.getLeft(), colName2Alias.getRight())); } } colName2Aliases = thisColumnName2Aliases; sql.append(String.format("\n%sFROM (\n", indentString)); sql.append(mainSql); sql.append(String.format("\n%s ) AS %s", indentString, leftAlias)); sql.append(" LEFT JOIN (\n"); sql.append(subSql); sql.append(String.format("%s) AS %s", indentString, rightAlias)); sql.append(String.format(" ON %s.l_shipmode = %s.l_shipmode", leftAlias, rightAlias)); return sql.toString(); }
#vulnerable code @Override public String visitQuery_specification(VerdictSQLParser.Query_specificationContext ctx) { List<Pair<String, String>> subqueryColName2Aliases = null; BootstrapSelectStatementRewriter singleRewriter = null; StringBuilder unionedFrom = new StringBuilder(2000); int trialNum = vc.getConf().getInt("bootstrap_trial_num"); for (int i = 0; i < trialNum; i++) { singleRewriter = new BootstrapSelectStatementRewriter(vc, queryString); singleRewriter.setIndentLevel(2); singleRewriter.setDepth(1); String singleTrialQuery = singleRewriter.visitQuery_specificationForSingleTrial(ctx); if (i == 0) { subqueryColName2Aliases = singleRewriter.getColName2Aliases(); } if (i > 0) unionedFrom.append("\n UNION\n"); unionedFrom.append(singleTrialQuery); } StringBuilder sql = new StringBuilder(2000); sql.append("SELECT"); int selectElemIndex = 0; for (Pair<String, String> e : subqueryColName2Aliases) { selectElemIndex++; sql.append((selectElemIndex > 1)? ", " : " "); if (singleRewriter.isAggregateColumn(selectElemIndex)) { String alias = genAlias(); sql.append(String.format("AVG(%s) AS %s", e.getRight(), alias)); colName2Aliases.add(Pair.of(e.getLeft(), alias)); } else { if (e.getLeft().equals(e.getRight())) sql.append(e.getLeft()); else sql.append(String.format("%s AS %s", e.getLeft(), e.getRight())); colName2Aliases.add(Pair.of(e.getLeft(), e.getRight())); } } sql.append("\nFROM (\n"); sql.append(unionedFrom.toString()); sql.append("\n) AS t"); sql.append("\nGROUP BY"); for (int colIndex = 1; colIndex <= subqueryColName2Aliases.size(); colIndex++) { if (!singleRewriter.isAggregateColumn(colIndex)) { if (colIndex > 1) { sql.append(String.format(", %s", subqueryColName2Aliases.get(colIndex-1).getRight())); } else { sql.append(String.format(" %s", subqueryColName2Aliases.get(colIndex-1).getRight())); } } } return sql.toString(); } #location 23 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public List<String> getPartitionColumns(String schema, String table) throws SQLException { if (!syntax.doesSupportTablePartitioning()) { throw new SQLException("Database does not support table partitioning"); } if (!partitionCache.isEmpty()){ return partitionCache; } partitionCache.addAll(getPartitionColumns(schema, table)); return partitionCache; }
#vulnerable code public List<String> getPartitionColumns(String schema, String table) throws SQLException { if (!syntax.doesSupportTablePartitioning()) { throw new SQLException("Database does not support table partitioning"); } if (!partitionCache.isEmpty()){ return partitionCache; } DbmsQueryResult queryResult = connection.executeQuery(syntax.getPartitionCommand(schema, table)); JdbcResultSet jdbcQueryResult = new JdbcResultSet(queryResult); while (queryResult.next()) { partitionCache.add(jdbcQueryResult.getString(0)); } return partitionCache; } #location 6 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Override public ExactRelation rewriteWithSubsampledErrorBounds() { ExactRelation r = rewriteWithPartition(); // List<SelectElem> selectElems = r.selectElemsWithAggregateSource(); List<SelectElem> selectElems = ((AggregatedRelation) r).getAggList(); // another wrapper to combine all subsampled aggregations. List<SelectElem> finalAgg = new ArrayList<SelectElem>(); for (int i = 0; i < selectElems.size() - 1; i++) { // excluding the last one which is psize // odd columns are for mean estimation // even columns are for err estimation if (i%2 == 1) continue; SelectElem meanElem = selectElems.get(i); SelectElem errElem = selectElems.get(i+1); ColNameExpr est = new ColNameExpr(meanElem.getAlias(), r.getAliasName()); ColNameExpr errEst = new ColNameExpr(errElem.getAlias(), r.getAliasName()); ColNameExpr psize = new ColNameExpr(partitionSizeAlias, r.getAliasName()); Expr originalAggExpr = elems.get(i/2).getExpr(); // average estimate Expr meanEstExpr = null; if (originalAggExpr.isCountDistinct()) { meanEstExpr = FuncExpr.round(FuncExpr.avg(est)); } else { meanEstExpr = BinaryOpExpr.from(FuncExpr.sum(BinaryOpExpr.from(est, psize, "*")), FuncExpr.sum(psize), "/"); if (originalAggExpr.isCount()) { meanEstExpr = FuncExpr.round(meanEstExpr); } } finalAgg.add(new SelectElem(meanEstExpr, meanElem.getAlias())); // error estimation Expr errEstExpr = BinaryOpExpr.from( BinaryOpExpr.from(FuncExpr.stddev(errEst), FuncExpr.sqrt(FuncExpr.avg(psize)), "*"), FuncExpr.sqrt(FuncExpr.sum(psize)), "/"); finalAgg.add(new SelectElem(errEstExpr, errElem.getAlias())); } /* * Example input query: * select category, avg(col) * from t * group by category * * Transformed query: * select category, sum(est * psize) / sum(psize) AS final_est * from ( * select category, avg(col) AS est, count(*) as psize * from t * group by category, verdict_partition) AS vt1 * group by category * * where t1 was obtained by rewriteWithPartition(). */ if (source instanceof ApproxGroupedRelation) { List<ColNameExpr> groupby = ((ApproxGroupedRelation) source).getGroupby(); List<ColNameExpr> groupbyInNewSource = new ArrayList<ColNameExpr>(); for (ColNameExpr g : groupby) { groupbyInNewSource.add(new ColNameExpr(g.getCol(), r.getAliasName())); } r = new GroupedRelation(vc, r, groupbyInNewSource); } r = new AggregatedRelation(vc, r, finalAgg); r.setAliasName(getAliasName()); return r; }
#vulnerable code @Override public ExactRelation rewriteWithSubsampledErrorBounds() { ExactRelation r = rewriteWithPartition(); // List<SelectElem> selectElems = r.selectElemsWithAggregateSource(); List<SelectElem> selectElems = ((AggregatedRelation) r).getAggList(); // another wrapper to combine all subsampled aggregations. List<SelectElem> finalAgg = new ArrayList<SelectElem>(); for (int i = 0; i < selectElems.size() - 1; i++) { // excluding the last one which is psize SelectElem e = selectElems.get(i); ColNameExpr est = new ColNameExpr(e.getAlias(), r.getAliasName()); ColNameExpr psize = new ColNameExpr(partitionSizeAlias, r.getAliasName()); // average estimate // Expr meanEst = BinaryOpExpr.from( // FuncExpr.sum(BinaryOpExpr.from(est, psize, "*")), // FuncExpr.sum(psize), "/"); Expr meanEst = FuncExpr.avg(est); Expr originalAggExpr = elems.get(i).getExpr(); if (originalAggExpr instanceof FuncExpr) { if (((FuncExpr) originalAggExpr).getFuncName().equals(FuncExpr.FuncName.COUNT) || ((FuncExpr) originalAggExpr).getFuncName().equals(FuncExpr.FuncName.COUNT_DISTINCT)) { meanEst = FuncExpr.round(meanEst); } } finalAgg.add(new SelectElem(meanEst, e.getAlias())); // error estimation finalAgg.add(new SelectElem( BinaryOpExpr.from( BinaryOpExpr.from(FuncExpr.stddev(est), FuncExpr.sqrt(FuncExpr.avg(psize)), "*"), FuncExpr.sqrt(FuncExpr.sum(psize)), "/"), e.getAlias() + errColSuffix())); } /* * Example input query: * select category, avg(col) * from t * group by category * * Transformed query: * select category, sum(est * psize) / sum(psize) AS final_est * from ( * select category, avg(col) AS est, count(*) as psize * from t * group by category, verdict_partition) AS vt1 * group by category * * where t1 was obtained by rewriteWithPartition(). */ if (source instanceof ApproxGroupedRelation) { List<ColNameExpr> groupby = ((ApproxGroupedRelation) source).getGroupby(); List<ColNameExpr> groupbyInNewSource = new ArrayList<ColNameExpr>(); for (ColNameExpr g : groupby) { groupbyInNewSource.add(new ColNameExpr(g.getCol(), r.getAliasName())); } r = new GroupedRelation(vc, r, groupbyInNewSource); } r = new AggregatedRelation(vc, r, finalAgg); r.setAliasName(getAliasName()); return r; } #location 12 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public List<Pair<String, Integer>> getColumns(String schema, String table) throws SQLException { if (!columnsCache.isEmpty()){ return columnsCache; } columnsCache.addAll(connection.getColumns(schema, table)); return columnsCache; }
#vulnerable code public List<Pair<String, Integer>> getColumns(String schema, String table) throws SQLException { if (!columnsCache.isEmpty()){ return columnsCache; } DbmsQueryResult queryResult = connection.executeQuery(syntax.getColumnsCommand(schema, table)); JdbcResultSet jdbcQueryResult = new JdbcResultSet(queryResult); while (queryResult.next()) { String type = jdbcQueryResult.getString(syntax.getColumnTypeColumnIndex()); // remove the size of type type = type.replaceAll("\\(.*\\)", ""); columnsCache.add(new ImmutablePair<>(jdbcQueryResult.getString(syntax.getColumnNameColumnIndex()), DataTypeConverter.typeInt(type))); } return columnsCache; } #location 3 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code void addParent(QueryExecutionNode parent) { parents.add(parent); }
#vulnerable code void print(int indentSpace) { StringBuilder builder = new StringBuilder(); for (int i = 0; i < indentSpace; i++) { builder.append(" "); } builder.append(this.toString()); System.out.println(builder.toString()); for (QueryExecutionNode dep : dependents) { dep.print(indentSpace + 2); } } #location 6 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public List<String> getTables(String schema) throws SQLException { if (!tablesCache.isEmpty()){ return tablesCache; } tablesCache.addAll(connection.getTables(schema)); return tablesCache; }
#vulnerable code public List<String> getTables(String schema) throws SQLException { if (!tablesCache.isEmpty()){ return tablesCache; } DbmsQueryResult queryResult = connection.executeQuery(syntax.getTableCommand(schema)); JdbcResultSet jdbcQueryResult = new JdbcResultSet(queryResult); while (queryResult.next()) { tablesCache.add(jdbcQueryResult.getString(syntax.getTableNameColumnIndex())); } return tablesCache; } #location 3 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Test public void testConvertFlatToProgressiveAgg() throws VerdictDBValueException { SelectQuery aggQuery = SelectQuery.create( new AliasedColumn(ColumnOp.count(), "agg"), new BaseTable(newSchema, newTable, "t")); AggExecutionNode aggnode = AggExecutionNode.create(aggQuery, newSchema); AggExecutionNodeBlock block = new AggExecutionNodeBlock(aggnode); QueryExecutionNode converted = block.convertToProgressiveAgg(newSchema, scrambleMeta); converted.print(); converted.execute(new JdbcConnection(conn, new H2Syntax())); }
#vulnerable code @Test public void testConvertFlatToProgressiveAgg() throws VerdictDBValueException { SelectQuery aggQuery = SelectQuery.create( ColumnOp.count(), new BaseTable("myschema", "mytable", "t")); AggExecutionNode aggnode = AggExecutionNode.create(aggQuery, "myschema"); AggExecutionNodeBlock block = new AggExecutionNodeBlock(aggnode); ScrambleMeta scrambleMeta = generateTestScrambleMeta(); QueryExecutionNode converted = block.convertToProgressiveAgg(scrambleMeta); converted.print(); } #location 10 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Override public ExactRelation rewriteWithSubsampledErrorBounds() { // if this is not an approximate relation effectively, we don't need any special rewriting. if (!doesIncludeSample()) { return getOriginalRelation(); } ExactRelation r = rewriteWithPartition(true); // String newAlias = genTableAlias(); // put another layer to combine per-partition aggregates List<SelectElem> newElems = new ArrayList<SelectElem>(); List<SelectElem> oldElems = ((AggregatedRelation) r).getElemList(); List<Expr> newGroupby = new ArrayList<Expr>(); for (int i = 0; i < oldElems.size(); i++) { SelectElem elem = oldElems.get(i); // used to identify the original aggregation type Optional<SelectElem> originalElem = Optional.absent(); if (i < this.elems.size()) { originalElem = Optional.fromNullable(this.elems.get(i)); } if (!elem.isagg()) { // skip the partition number if (elem.aliasPresent() && elem.getAlias().equals(partitionColumnName())) { continue; } SelectElem newElem = null; Expr newExpr = null; if (elem.getAlias() == null) { newExpr = elem.getExpr().withTableSubstituted(r.getAlias()); newElem = new SelectElem(vc, newExpr, elem.getAlias()); } else { newExpr = new ColNameExpr(vc, elem.getAlias(), r.getAlias()); newElem = new SelectElem(vc, newExpr, elem.getAlias()); } // groupby element may not be present in the select list. if (originalElem.isPresent()) { newElems.add(newElem); } newGroupby.add(newExpr); } else { // skip the partition size column if (elem.getAlias().equals(partitionSizeAlias)) { continue; } // skip the extra columns inserted if (!originalElem.isPresent()) { continue; } ColNameExpr est = new ColNameExpr(vc, elem.getAlias(), r.getAlias()); ColNameExpr psize = new ColNameExpr(vc, partitionSizeAlias, r.getAlias()); // average estimate Expr averaged = null; Expr originalExpr = originalElem.get().getExpr(); if (originalExpr.isCountDistinct()) { // for count-distinct (i.e., universe samples), weighted average should not be used. averaged = FuncExpr.round(FuncExpr.avg(est)); } else if (originalExpr.isMax()) { averaged = FuncExpr.max(est); } else if (originalExpr.isMin()) { averaged = FuncExpr.min(est); } else { // weighted average averaged = BinaryOpExpr.from(vc, FuncExpr.sum(BinaryOpExpr.from(vc, est, psize, "*")), FuncExpr.sum(psize), "/"); if (originalElem.get().getExpr().isCount()) { averaged = FuncExpr.round(averaged); } } newElems.add(new SelectElem(vc, averaged, elem.getAlias())); // error estimation // scale by sqrt(subsample size) / sqrt(sample size) if (originalExpr.isMax() || originalExpr.isMin()) { // no error estimations for extreme statistics } else { Expr error = BinaryOpExpr.from(vc, BinaryOpExpr.from(vc, FuncExpr.stddev(est), FuncExpr.sqrt(FuncExpr.avg(psize)), "*"), FuncExpr.sqrt(FuncExpr.sum(psize)), "/"); error = BinaryOpExpr.from(vc, error, ConstantExpr.from(vc, confidenceIntervalMultiplier()), "*"); newElems.add(new SelectElem(vc, error, Relation.errorBoundColumn(elem.getAlias()))); } } } // this extra aggregation stage should be grouped by non-agg elements except for __vpart // List<Expr> newGroupby = new ArrayList<Expr>(); // if (source instanceof ApproxGroupedRelation) { // for (Expr g : ((ApproxGroupedRelation) source).getGroupby()) { // if (g instanceof ColNameExpr && ((ColNameExpr) g).getCol().equals(partitionColumnName())) { // continue; // } else { // newGroupby.add(g.withTableSubstituted(r.getAlias())); // } // } // } // for (SelectElem elem : elems) { // if (!elem.isagg()) { // if (elem.aliasPresent()) { // if (!elem.getAlias().equals(partitionColumnName())) { // newGroupby.add(new ColNameExpr(vc, elem.getAlias(), r.getAlias())); // } // } else { // does not happen // if (!elem.getExpr().toString().equals(partitionColumnName())) { // newGroupby.add(elem.getExpr().withTableSubstituted(r.getAlias())); // } // } // } // } if (newGroupby.size() > 0) { r = new GroupedRelation(vc, r, newGroupby); } r = new AggregatedRelation(vc, r, newElems); r.setAlias(getAlias()); return r; }
#vulnerable code @Override public ExactRelation rewriteWithSubsampledErrorBounds() { // if this is not an approximate relation effectively, we don't need any special rewriting. if (!doesIncludeSample()) { return getOriginalRelation(); } ExactRelation r = rewriteWithPartition(true); // String newAlias = genTableAlias(); // put another layer to combine per-partition aggregates List<SelectElem> newElems = new ArrayList<SelectElem>(); List<SelectElem> oldElems = ((AggregatedRelation) r).getElemList(); List<Expr> newGroupby = new ArrayList<Expr>(); for (int i = 0; i < oldElems.size(); i++) { SelectElem elem = oldElems.get(i); // used to identify the original aggregation type Optional<SelectElem> originalElem = Optional.absent(); if (i < this.elems.size()) { originalElem = Optional.fromNullable(this.elems.get(i)); } if (!elem.isagg()) { // skip the partition number if (elem.aliasPresent() && elem.getAlias().equals(partitionColumnName())) { continue; } SelectElem newElem = null; Expr newExpr = null; if (elem.getAlias() == null) { newExpr = elem.getExpr().withTableSubstituted(r.getAlias()); newElem = new SelectElem(vc, newExpr, elem.getAlias()); } else { newExpr = new ColNameExpr(vc, elem.getAlias(), r.getAlias()); newElem = new SelectElem(vc, newExpr, elem.getAlias()); } // groupby element may not be present in the select list. if (originalElem.isPresent()) { newElems.add(newElem); } newGroupby.add(newExpr); } else { // skip the partition size column if (elem.getAlias().equals(partitionSizeAlias)) { continue; } // skip the extra columns inserted if (!originalElem.isPresent()) { continue; } ColNameExpr est = new ColNameExpr(vc, elem.getAlias(), r.getAlias()); ColNameExpr psize = new ColNameExpr(vc, partitionSizeAlias, r.getAlias()); // average estimate Expr averaged = null; Expr originalExpr = originalElem.get().getExpr(); if (originalExpr.isCountDistinct()) { // for count-distinct (i.e., universe samples), weighted average should not be used. averaged = FuncExpr.round(FuncExpr.avg(est)); } else if (originalExpr.isMax()) { averaged = FuncExpr.max(est); } else if (originalExpr.isMin()) { averaged = FuncExpr.min(est); } else { // weighted average averaged = BinaryOpExpr.from(vc, FuncExpr.sum(BinaryOpExpr.from(vc, est, psize, "*")), FuncExpr.sum(psize), "/"); if (originalElem.get().getExpr().isCount()) { averaged = FuncExpr.round(averaged); } } newElems.add(new SelectElem(vc, averaged, elem.getAlias())); // error estimation // scale by sqrt(subsample size) / sqrt(sample size) if (originalExpr.isMax() || originalExpr.isMin()) { // no error estimations for extreme statistics } else { Expr error = BinaryOpExpr.from(vc, BinaryOpExpr.from(vc, FuncExpr.stddev(est), FuncExpr.sqrt(FuncExpr.avg(psize)), "*"), FuncExpr.sqrt(FuncExpr.sum(psize)), "/"); error = BinaryOpExpr.from(vc, error, ConstantExpr.from(vc, confidenceIntervalMultiplier()), "*"); newElems.add(new SelectElem(vc, error, Relation.errorBoundColumn(elem.getAlias()))); } } } // this extra aggregation stage should be grouped by non-agg elements except for __vpart // List<Expr> newGroupby = new ArrayList<Expr>(); // if (source instanceof ApproxGroupedRelation) { // for (Expr g : ((ApproxGroupedRelation) source).getGroupby()) { // if (g instanceof ColNameExpr && ((ColNameExpr) g).getCol().equals(partitionColumnName())) { // continue; // } else { // newGroupby.add(g.withTableSubstituted(r.getAlias())); // } // } // } for (SelectElem elem : elems) { if (!elem.isagg()) { if (elem.aliasPresent()) { if (!elem.getAlias().equals(partitionColumnName())) { newGroupby.add(new ColNameExpr(vc, elem.getAlias(), r.getAlias())); } } else { if (!elem.getExpr().toString().equals(partitionColumnName())) { newGroupby.add(elem.getExpr().withTableSubstituted(r.getAlias())); } } } } if (newGroupby.size() > 0) { r = new GroupedRelation(vc, r, newGroupby); } r = new AggregatedRelation(vc, r, newElems); r.setAlias(getAlias()); return r; } #location 112 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Override public List<String> getTables(String schema) throws VerdictDBDbmsException { List<String> tables = new ArrayList<>(); DbmsQueryResult queryResult = execute(syntax.getTableCommand(schema)); while (queryResult.next()) { tables.add((String) queryResult.getValue(syntax.getTableNameColumnIndex())); } return tables; }
#vulnerable code @Override public List<String> getTables(String schema) throws VerdictDBDbmsException { List<String> tables = new ArrayList<>(); DbmsQueryResult queryResult = execute(syntax.getTableCommand(schema)); JdbcResultSet jdbcResultSet = new JdbcResultSet(queryResult); try { while (queryResult.next()) { tables.add(jdbcResultSet.getString(syntax.getTableNameColumnIndex()+1)); } } catch (SQLException e) { throw new VerdictDBDbmsException(e); } finally { jdbcResultSet.close(); } return tables; } #location 5 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public List<Pair<String, Integer>> getColumns(String schema, String table) throws SQLException { if (!columnsCache.isEmpty()){ return columnsCache; } columnsCache.addAll(connection.getColumns(schema, table)); return columnsCache; }
#vulnerable code public List<Pair<String, Integer>> getColumns(String schema, String table) throws SQLException { if (!columnsCache.isEmpty()){ return columnsCache; } DbmsQueryResult queryResult = connection.executeQuery(syntax.getColumnsCommand(schema, table)); JdbcResultSet jdbcQueryResult = new JdbcResultSet(queryResult); while (queryResult.next()) { String type = jdbcQueryResult.getString(syntax.getColumnTypeColumnIndex()); // remove the size of type type = type.replaceAll("\\(.*\\)", ""); columnsCache.add(new ImmutablePair<>(jdbcQueryResult.getString(syntax.getColumnNameColumnIndex()), DataTypeConverter.typeInt(type))); } return columnsCache; } #location 3 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Test public void testExecuteNode() throws VerdictDBException { BaseTable base = new BaseTable(originalSchema, originalTable, "t"); SelectQuery query = SelectQuery.create(Arrays.<SelectItem>asList(new AsteriskColumn()), base); QueryExecutionNode root = CreateTableAsSelectExecutionNode.create(query, "newschema"); // ExecutionInfoToken token = new ExecutionInfoToken(); ExecutionInfoToken newTableName = root.executeNode(conn, Arrays.<ExecutionInfoToken>asList()); // no information to pass String schemaName = (String) newTableName.getValue("schemaName"); String tableName = (String) newTableName.getValue("tableName"); conn.executeUpdate(String.format("DROP TABLE \"%s\".\"%s\"", schemaName, tableName)); }
#vulnerable code @Test public void testExecuteNode() throws VerdictDBException { BaseTable base = new BaseTable(originalSchema, originalTable, "t"); SelectQuery query = SelectQuery.create(Arrays.<SelectItem>asList(new AsteriskColumn()), base); QueryExecutionNode root = CreateTableAsSelectExecutionNode.create(query, "newschema"); // LinkedBlockingDeque<ExecutionResult> resultQueue = new LinkedBlockingDeque<>(); root.executeNode(conn, null); // no information to pass conn.executeUpdate(String.format("DROP TABLE \"%s\".\"%s\"", newSchema, "verdictdbtemptable_0")); } #location 7 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public List<String> getTables(String schema) throws SQLException { if (!tablesCache.isEmpty()){ return tablesCache; } tablesCache.addAll(connection.getTables(schema)); return tablesCache; }
#vulnerable code public List<String> getTables(String schema) throws SQLException { if (!tablesCache.isEmpty()){ return tablesCache; } DbmsQueryResult queryResult = connection.executeQuery(syntax.getTableCommand(schema)); JdbcResultSet jdbcQueryResult = new JdbcResultSet(queryResult); while (queryResult.next()) { tablesCache.add(jdbcQueryResult.getString(syntax.getTableNameColumnIndex())); } return tablesCache; } #location 3 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Override protected Map<TableUniqueName, String> tableSubstitution() { return source.tableSubstitution(); }
#vulnerable code @Override protected Map<TableUniqueName, String> tableSubstitution() { return ImmutableMap.of(); } #location 2 #vulnerability type CHECKERS_IMMUTABLE_CAST
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Override public List<String> getSchemas() throws VerdictDBDbmsException { List<String> schemas = new ArrayList<>(); DbmsQueryResult queryResult = execute(syntax.getSchemaCommand()); while (queryResult.next()) { schemas.add((String) queryResult.getValue(syntax.getSchemaNameColumnIndex())); } return schemas; }
#vulnerable code @Override public List<String> getSchemas() throws VerdictDBDbmsException { List<String> schemas = new ArrayList<>(); DbmsQueryResult queryResult = execute(syntax.getSchemaCommand()); JdbcResultSet jdbcResultSet = new JdbcResultSet(queryResult); try { while (queryResult.next()) { schemas.add(jdbcResultSet.getString(syntax.getSchemaNameColumnIndex()+1)); } } catch (SQLException e) { throw new VerdictDBDbmsException(e); } finally { jdbcResultSet.close(); } return schemas; } #location 5 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public List<String> getPartitionColumns(String schema, String table) throws SQLException { if (!syntax.doesSupportTablePartitioning()) { throw new SQLException("Database does not support table partitioning"); } if (!partitionCache.isEmpty()){ return partitionCache; } partitionCache.addAll(getPartitionColumns(schema, table)); return partitionCache; }
#vulnerable code public List<String> getPartitionColumns(String schema, String table) throws SQLException { if (!syntax.doesSupportTablePartitioning()) { throw new SQLException("Database does not support table partitioning"); } if (!partitionCache.isEmpty()){ return partitionCache; } DbmsQueryResult queryResult = connection.executeQuery(syntax.getPartitionCommand(schema, table)); JdbcResultSet jdbcQueryResult = new JdbcResultSet(queryResult); while (queryResult.next()) { partitionCache.add(jdbcQueryResult.getString(0)); } return partitionCache; } #location 6 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public List<String> getSchemas() throws SQLException { if (!schemaCache.isEmpty()){ return schemaCache; } schemaCache.addAll(connection.getSchemas()); return schemaCache; }
#vulnerable code public List<String> getSchemas() throws SQLException { if (!schemaCache.isEmpty()){ return schemaCache; } DbmsQueryResult queryResult = connection.executeQuery(syntax.getSchemaCommand()); JdbcResultSet jdbcQueryResult = new JdbcResultSet(queryResult); while (queryResult.next()) { schemaCache.add(jdbcQueryResult.getString(syntax.getSchemaNameColumnIndex())); } return schemaCache; } #location 3 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Test public void testSingleAggCombiningWithH2() throws VerdictDBDbmsException, VerdictDBException { QueryExecutionPlan plan = new QueryExecutionPlan("newschema"); BaseTable base = new BaseTable(originalSchema, originalTable, "t"); SelectQuery leftQuery = SelectQuery.create(new AliasedColumn(ColumnOp.count(), "mycount"), base); leftQuery.addFilterByAnd(ColumnOp.lessequal(new BaseColumn("t", "value"), ConstantColumn.valueOf(5.0))); SelectQuery rightQuery = SelectQuery.create(new AliasedColumn(ColumnOp.count(), "mycount"), base); rightQuery.addFilterByAnd(ColumnOp.greater(new BaseColumn("t", "value"), ConstantColumn.valueOf(5.0))); AggExecutionNode leftNode = AggExecutionNode.create(plan, leftQuery); AggExecutionNode rightNode = AggExecutionNode.create(plan, rightQuery); // ExecutionTokenQueue queue = new ExecutionTokenQueue(); AggCombinerExecutionNode combiner = AggCombinerExecutionNode.create(plan, leftNode, rightNode); combiner.print(); ExecutionTokenReader reader = ExecutablePlanRunner.getTokenReader( conn, new SimpleTreePlan(combiner)); // combiner.addBroadcastingQueue(queue); // combiner.executeAndWaitForTermination(conn); ExecutionInfoToken token = reader.next(); String schemaName = (String) token.getValue("schemaName"); String tableName = (String) token.getValue("tableName"); DbmsQueryResult result = conn.execute(QueryToSql.convert( new H2Syntax(), SelectQuery.create(ColumnOp.count(), base))); result.next(); int expectedCount = Integer.valueOf(result.getValue(0).toString()); DbmsQueryResult result2 = conn.execute(QueryToSql.convert( new H2Syntax(), SelectQuery.create(new AsteriskColumn(), new BaseTable(schemaName, tableName, "t")))); result2.next(); int actualCount = Integer.valueOf(result2.getValue(0).toString()); assertEquals(expectedCount, actualCount); conn.execute(QueryToSql.convert( new H2Syntax(), DropTableQuery.create(schemaName, tableName))); }
#vulnerable code @Test public void testSingleAggCombiningWithH2() throws VerdictDBDbmsException, VerdictDBException { QueryExecutionPlan plan = new QueryExecutionPlan("newschema"); BaseTable base = new BaseTable(originalSchema, originalTable, "t"); SelectQuery leftQuery = SelectQuery.create(new AliasedColumn(ColumnOp.count(), "mycount"), base); leftQuery.addFilterByAnd(ColumnOp.lessequal(new BaseColumn("t", "value"), ConstantColumn.valueOf(5.0))); SelectQuery rightQuery = SelectQuery.create(new AliasedColumn(ColumnOp.count(), "mycount"), base); rightQuery.addFilterByAnd(ColumnOp.greater(new BaseColumn("t", "value"), ConstantColumn.valueOf(5.0))); AggExecutionNode leftNode = AggExecutionNode.create(plan, leftQuery); AggExecutionNode rightNode = AggExecutionNode.create(plan, rightQuery); // ExecutionTokenQueue queue = new ExecutionTokenQueue(); AggCombinerExecutionNode combiner = AggCombinerExecutionNode.create(plan, leftNode, rightNode); combiner.print(); ExecutionTokenReader reader = ExecutablePlanRunner.getTokenReader( conn, new SimpleTreePlan(combiner)); // combiner.addBroadcastingQueue(queue); // combiner.executeAndWaitForTermination(conn); ExecutionInfoToken token = reader.next(); String schemaName = (String) token.getValue("schemaName"); String tableName = (String) token.getValue("tableName"); conn.execute(QueryToSql.convert( new H2Syntax(), SelectQuery.create(ColumnOp.count(), base))); DbmsQueryResult result = conn.getResult(); result.next(); int expectedCount = Integer.valueOf(result.getValue(0).toString()); conn.execute(QueryToSql.convert( new H2Syntax(), SelectQuery.create(new AsteriskColumn(), new BaseTable(schemaName, tableName, "t")))); DbmsQueryResult result2 = conn.getResult(); result2.next(); int actualCount = Integer.valueOf(result2.getValue(0).toString()); assertEquals(expectedCount, actualCount); conn.execute(QueryToSql.convert( new H2Syntax(), DropTableQuery.create(schemaName, tableName))); } #location 25 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Override public String visitSelect_list_elem(VerdictSQLParser.Select_list_elemContext ctx) { select_list_elem_num++; String newSelectListElem = null; Pair<String, Alias> colName2Alias = null; if (ctx.getText().equals("*")) { // TODO: replace * with all columns in the (joined) source table. newSelectListElem = "*"; } else { StringBuilder elem = new StringBuilder(); // We use a baseRewriter to prevent that "COUNT(*)" is rewritten to "COUNT(*) * (1/sample_ratio)" SelectStatementBaseRewriter baseRewriter = new SelectStatementBaseRewriter(queryString); String tabColName = baseRewriter.visit(ctx.expression()); String tabName = NameHelpers.tabNameOfColName(tabColName); TableUniqueName tabUniqueName = NameHelpers.tabUniqueNameOfColName(vc, tabColName); String colName = NameHelpers.colNameOfColName(tabColName); // if a table name is specified, we change it to its alias name. if (tableAliases.containsKey(tabUniqueName)) { tabName = tableAliases.get(tabUniqueName).toString(); } // if there was derived table(s), we may need to substitute aliased name for the colName. for (Map.Entry<String, Map<String, Alias>> e : derivedTableColName2Aliases.entrySet()) { String derivedTabName = e.getKey(); if (tabName.length() > 0 && !tabName.equals(derivedTabName)) { // this is the case where there are more than one derived tables, and a user specifically referencing // a column in one of those derived tables. continue; } if (e.getValue().containsKey(colName)) { Alias alias = e.getValue().get(colName); if (alias.autoGenerated()) { colName = alias.toString(); } } } if (tabName.length() > 0) { elem.append(String.format("%s.%s", tabName, colName)); } else { elem.append(colName); } if (ctx.column_alias() != null) { Alias alias = new Alias(colName, ctx.column_alias().getText()); elem.append(String.format(" AS %s", alias)); colName2Alias = Pair.of(colName, alias); } else { // We add a pseudo column alias Alias alias = Alias.genAlias(depth, colName); elem.append(String.format(" AS %s", alias)); colName2Alias = Pair.of(baseRewriter.visit(ctx.expression()), alias); } newSelectListElem = elem.toString(); } colName2Aliases.add(Pair.of(colName2Alias.getKey(), colName2Alias.getValue())); return newSelectListElem; }
#vulnerable code @Override public String visitSelect_list_elem(VerdictSQLParser.Select_list_elemContext ctx) { select_list_elem_num++; String newSelectListElem = null; Pair<String, Alias> colName2Alias = null; if (ctx.getText().equals("*")) { // TODO: replace * with all columns in the (joined) source table. newSelectListElem = "*"; } else { StringBuilder elem = new StringBuilder(); elem.append(visit(ctx.expression())); SelectStatementBaseRewriter baseRewriter = new SelectStatementBaseRewriter(queryString); String colName = baseRewriter.visit(ctx.expression()); if (ctx.column_alias() != null) { Alias alias = new Alias(colName, ctx.column_alias().getText()); elem.append(String.format(" AS %s", alias)); colName2Alias = Pair.of(colName, alias); } else { // We add a pseudo column alias Alias alias = Alias.genAlias(depth, colName); elem.append(String.format(" AS %s", alias)); colName2Alias = Pair.of(baseRewriter.visit(ctx.expression()), alias); } newSelectListElem = elem.toString(); } colName2Aliases.add(Pair.of(colName2Alias.getKey(), colName2Alias.getValue())); return newSelectListElem; } #location 31 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public static void main(String[] a) throws Exception { PropertyConfigurator.configure(FoxCfg.LOG_FILE); String in = "University of Leipzig in Leipzig.."; String query = "select * from search.termextract where context="; URIBuilder builder = new URIBuilder(); builder.setScheme("http").setHost("query.yahooapis.com").setPath("/v1/public/yql").setParameter("diagnostics", "false").setParameter("q", query + "'" + in + "'"); HttpGet httpget = new HttpGet(builder.build()); System.out.println(httpget.getURI()); HttpClient httpclient = HttpClientBuilder.create().build(); HttpResponse response = httpclient.execute(httpget); HttpEntity entity = response.getEntity(); if (entity != null) { InputStream instream = entity.getContent(); try { String myString = IOUtils.toString(instream, "UTF-8"); System.out.println(myString); } finally { instream.close(); } } }
#vulnerable code public static void main(String[] a) throws Exception { PropertyConfigurator.configure(FoxCfg.LOG_FILE); String in = "University of Leipzig in Leipzig.."; String query = "select * from search.termextract where context="; URIBuilder builder = new URIBuilder(); builder.setScheme("http").setHost("query.yahooapis.com").setPath("/v1/public/yql").setParameter("diagnostics", "false").setParameter("q", query + "'" + in + "'"); HttpGet httpget = new HttpGet(builder.build()); System.out.println(httpget.getURI()); HttpClient httpclient = new DefaultHttpClient(); HttpResponse response = httpclient.execute(httpget); HttpEntity entity = response.getEntity(); if (entity != null) { InputStream instream = entity.getContent(); try { String myString = IOUtils.toString(instream, "UTF-8"); System.out.println(myString); } finally { instream.close(); } } } #location 14 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Override public Swagger read(Set<Class<?>> classes) throws GenerateException { //relate all methods to one base request mapping if multiple controllers exist for that mapping //get all methods from each controller & find their request mapping //create map - resource string (after first slash) as key, new SpringResource as value Map<String, SpringResource> resourceMap = generateResourceMap(classes); for (String str : resourceMap.keySet()) { SpringResource resource = resourceMap.get(str); read(resource); } return swagger; }
#vulnerable code @Override public Swagger read(Set<Class<?>> classes) throws GenerateException { //relate all methods to one base request mapping if multiple controllers exist for that mapping //get all methods from each controller & find their request mapping //create map - resource string (after first slash) as key, new SpringResource as value Map<String, SpringResource> resourceMap = generateResourceMap(classes); for (String str : resourceMap.keySet()) { SpringResource resource = resourceMap.get(str); swagger = read(resource); } return swagger; } #location 9 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code protected List<Parameter> getParameters(Type type, List<Annotation> annotations) { Iterator<SwaggerExtension> chain = SwaggerExtensions.chain(); List<Parameter> parameters = new ArrayList<Parameter>(); LOG.info("Looking for path/query/header/form/cookie params in" + type.getClass().getName()); Set<Type> typesToSkip = new HashSet<Type>(); if (chain.hasNext()) { SwaggerExtension extension = chain.next(); LOG.info("trying extension " + extension); parameters = extension.extractParameters(annotations, type, typesToSkip, chain); } if (parameters.size() > 0) { for (Parameter parameter : parameters) { ParameterProcessor.applyAnnotations(swagger, parameter, type, annotations); } } else { // look for body parameters LOG.info("Looking for body params in" + type.getClass().getName()); if (typesToSkip.contains(type) == false) { Parameter param = ParameterProcessor.applyAnnotations(swagger, null, type, annotations); if (param != null) { parameters.add(param); } } } return parameters; }
#vulnerable code protected List<Parameter> getParameters(Type type, List<Annotation> annotations) { // look for path, query Iterator<SwaggerExtension> chain = SwaggerExtensions.chain(); List<Parameter> parameters = null; LOG.info("getParameters for " + type.getClass().getName()); Set<Type> typesToSkip = new HashSet<Type>(); if (chain.hasNext()) { SwaggerExtension extension = chain.next(); LOG.info("trying extension " + extension); parameters = extension.extractParameters(annotations, type, typesToSkip, chain); } if (parameters.size() > 0) { for (Parameter parameter : parameters) { ParameterProcessor.applyAnnotations(swagger, parameter, type, annotations); } } else { LOG.info("no parameter found, looking at body params"); if (typesToSkip.contains(type) == false) { Parameter param = null; param = ParameterProcessor.applyAnnotations(swagger, null, type, annotations); if (param != null) { for (Annotation annotation : annotations) { if (annotation instanceof ApiParam) { ApiParam apiParam = (ApiParam) annotation; param.setRequired(apiParam.required()); break; } } parameters.add(param); } } } return parameters; } #location 14 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public void toDocuments() throws GenerateException { if (outputTemplate == null) { prepareMustacheTemplate(); } if (outputTemplate.getApiDocuments().isEmpty()) { LOG.warn("nothing to write."); return; } LOG.info("Writing doc to " + outputPath + "..."); FileOutputStream fileOutputStream = null; try { fileOutputStream = new FileOutputStream(outputPath); } catch (FileNotFoundException e) { throw new GenerateException(e); } OutputStreamWriter writer = new OutputStreamWriter(fileOutputStream, Charset.forName("UTF-8")); MustacheFactory mf = new DefaultMustacheFactory(); URI uri = null; try { uri = new URI(templatePath); } catch (URISyntaxException e) { throw new GenerateException(e); } if (!uri.isAbsolute()) { File file = new File(templatePath); if (!file.exists()) { throw new GenerateException("Template " + file.getAbsoluteFile() + " not found. You can go to https://github.com/kongchen/api-doc-template to get templates."); } else { uri = new File(templatePath).toURI(); } } URL url = null; try { url = uri.toURL(); InputStreamReader reader = new InputStreamReader(url.openStream(), Charset.forName("UTF-8")); Mustache mustache = mf.compile(reader, templatePath); mustache.execute(writer, outputTemplate).flush(); writer.close(); LOG.info("Done!"); } catch (MalformedURLException e) { throw new GenerateException(e); } catch (IOException e) { throw new GenerateException(e); } }
#vulnerable code public void toDocuments() throws GenerateException { if (outputTemplate == null) { prepareMustacheTemplate(); } if (outputTemplate.getApiDocuments().isEmpty()) { LOG.warn("nothing to write."); return; } LOG.info("Writing doc to " + outputPath + "..."); FileOutputStream fileOutputStream = null; try { fileOutputStream = new FileOutputStream(outputPath); } catch (FileNotFoundException e) { throw new GenerateException(e); } OutputStreamWriter writer = new OutputStreamWriter(fileOutputStream, Charset.forName("UTF-8")); try { URL url = getTemplateUri().toURL(); InputStreamReader reader = new InputStreamReader(url.openStream(), Charset.forName("UTF-8")); Mustache mustache = getMustacheFactory().compile(reader, templatePath); mustache.execute(writer, outputTemplate).flush(); writer.close(); LOG.info("Done!"); } catch (MalformedURLException e) { throw new GenerateException(e); } catch (IOException e) { throw new GenerateException(e); } } #location 27 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public Swagger read(SpringResource resource) { if (swagger == null) { swagger = new Swagger(); } String description; List<Method> methods = resource.getMethods(); Map<String, Tag> tags = new HashMap<String, Tag>(); List<SecurityRequirement> resourceSecurities = new ArrayList<SecurityRequirement>(); // Add the description from the controller api Class<?> controller = resource.getControllerClass(); RequestMapping controllerRM = controller.getAnnotation(RequestMapping.class); String[] controllerProduces = new String[0]; String[] controllerConsumes = new String[0]; if (controllerRM != null) { controllerConsumes = controllerRM.consumes(); controllerProduces = controllerRM.produces(); } if (controller != null && controller.isAnnotationPresent(Api.class)) { Api api = controller.getAnnotation(Api.class); if (!canReadApi(false, api)) { return swagger; } tags = updateTagsForApi(null, api); resourceSecurities = getSecurityRequirements(api); description = api.description(); } resourcePath = resource.getControllerMapping(); //collect api from method with @RequestMapping Map<String, List<Method>> apiMethodMap = collectApisByRequestMapping(methods); for (String path : apiMethodMap.keySet()) { for (Method method : apiMethodMap.get(path)) { RequestMapping requestMapping = method.getAnnotation(RequestMapping.class); if (requestMapping == null) { continue; } ApiOperation apiOperation = method.getAnnotation(ApiOperation.class); if (apiOperation == null) { continue; } String httpMethod = null; Map<String, String> regexMap = new HashMap<String, String>(); String operationPath = parseOperationPath(path, regexMap); //http method if (requestMapping.method() != null && requestMapping.method().length != 0) { httpMethod = requestMapping.method()[0].toString().toLowerCase(); if (httpMethod == null) { continue; } } Operation operation = parseMethod(method); updateOperationParameters(new ArrayList<Parameter>(), regexMap, operation); updateOperationProtocols(apiOperation, operation); String[] apiProduces = requestMapping.produces(); String[] apiConsumes = requestMapping.consumes(); apiProduces = (apiProduces == null || apiProduces.length == 0 ) ? controllerProduces : apiProduces; apiConsumes = (apiConsumes == null || apiProduces.length == 0 ) ? controllerConsumes : apiConsumes; apiConsumes = updateOperationConsumes(new String[0], apiConsumes, operation); apiProduces = updateOperationProduces(new String[0], apiProduces, operation); ApiOperation op = method.getAnnotation(ApiOperation.class); updateTagsForOperation(operation, op); updateOperation(apiConsumes, apiProduces, tags, resourceSecurities, operation); updatePath(operationPath, httpMethod, operation); } } return swagger; }
#vulnerable code public Swagger read(SpringResource resource) { if (swagger == null) { swagger = new Swagger(); } List<Method> methods = resource.getMethods(); Map<String, Tag> tags = new HashMap<String, Tag>(); List<SecurityRequirement> resourceSecurities = new ArrayList<SecurityRequirement>(); // Add the description from the controller api Class<?> controller = resource.getControllerClass(); RequestMapping apiPath = controller.getAnnotation(RequestMapping.class); if (controller != null && controller.isAnnotationPresent(Api.class)) { Api api = controller.getAnnotation(Api.class); if (!canReadApi(false, api)) { return null; } tags = updateTagsForApi(null, api); resourceSecurities = getSecurityRequirements(api); // description = api.description(); // position = api.position(); } resourcePath = resource.getControllerMapping(); Map<String, List<Method>> apiMethodMap = new HashMap<String, List<Method>>(); //collect api from method with @RequestMapping collectApisByRequestMapping(methods, apiMethodMap); for (String p : apiMethodMap.keySet()) { List<Operation> operations = new ArrayList<Operation>(); for (Method method : apiMethodMap.get(p)) { RequestMapping requestMapping = method.getAnnotation(RequestMapping.class); ApiOperation apiOperation = method.getAnnotation(ApiOperation.class); String operationPath = p; //getPath(apiPath, requestMapping, ""); String operationId; String httpMethod = null; if (operationPath != null && apiOperation != null) { Map<String, String> regexMap = new HashMap<String, String>(); operationPath = parseOperationPath(operationPath, regexMap); //http method if (requestMapping.method() != null && requestMapping.method().length != 0) { httpMethod = requestMapping.method()[0].toString().toLowerCase(); } Operation operation = parseMethod(method); updateOperationParameters(new ArrayList<Parameter>(), regexMap, operation); updateOperationProtocols(apiOperation, operation); String[] apiConsumes = new String[0]; String[] apiProduces = new String[0]; RequestMapping rm = controller.getAnnotation(RequestMapping.class); String[] pps = new String[0]; String[] pcs = new String[0]; if (rm != null) { pcs = rm.consumes(); pps = rm.produces(); } apiConsumes = updateOperationConsumes(method, pcs, apiConsumes, operation); apiProduces = updateOperationProduces(method, pps, apiProduces, operation); // can't continue without a valid http method // httpMethod = httpMethod == null ? parentMethod : httpMethod; ApiOperation op = method.getAnnotation(ApiOperation.class); updateTagsForOperation(operation, op); updateOperation(apiConsumes, apiProduces, tags, resourceSecurities, operation); updatePath(operationPath, httpMethod, operation); } } } return swagger; } #location 38 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code private Map<String, List<Method>> collectApisByRequestMapping(List<Method> methods) { Map<String, List<Method>> apiMethodMap = new HashMap<String, List<Method>>(); for (Method method : methods) { if (method.isAnnotationPresent(RequestMapping.class)) { RequestMapping requestMapping = AnnotationUtils.findAnnotation(method, RequestMapping.class); String path = ""; if (requestMapping.value() != null && requestMapping.value().length != 0) { path = generateFullPath(requestMapping.value()[0]); } else { path = resourcePath; } if (apiMethodMap.containsKey(path)) { apiMethodMap.get(path).add(method); } else { List<Method> ms = new ArrayList<Method>(); ms.add(method); apiMethodMap.put(path, ms); } } } return apiMethodMap; }
#vulnerable code private Map<String, List<Method>> collectApisByRequestMapping(List<Method> methods) { Map<String, List<Method>> apiMethodMap = new HashMap<String, List<Method>>(); for (Method method : methods) { if (method.isAnnotationPresent(RequestMapping.class)) { RequestMapping requestMapping = Annotations.get(method, RequestMapping.class); String path = ""; if (requestMapping.value() != null && requestMapping.value().length != 0) { path = generateFullPath(requestMapping.value()[0]); } else { path = resourcePath; } if (apiMethodMap.containsKey(path)) { apiMethodMap.get(path).add(method); } else { List<Method> ms = new ArrayList<Method>(); ms.add(method); apiMethodMap.put(path, ms); } } } return apiMethodMap; } #location 7 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public Operation parseMethod(String httpMethod, Method method) { int responseCode = 200; Operation operation = new Operation(); ApiOperation apiOperation = AnnotationUtils.findAnnotation(method, ApiOperation.class); String operationId = getOperationId(method, httpMethod); String responseContainer = null; Type responseClassType = null; Map<String, Property> defaultResponseHeaders = null; if (apiOperation != null) { if (apiOperation.hidden()) { return null; } if (!apiOperation.nickname().isEmpty()) { operationId = apiOperation.nickname(); } defaultResponseHeaders = parseResponseHeaders(apiOperation.responseHeaders()); operation.summary(apiOperation.value()).description(apiOperation.notes()); Map<String, Object> customExtensions = BaseReaderUtils.parseExtensions(apiOperation.extensions()); operation.setVendorExtensions(customExtensions); if (!apiOperation.response().equals(Void.class) && !apiOperation.response().equals(void.class)) { responseClassType = apiOperation.response(); } if (!apiOperation.responseContainer().isEmpty()) { responseContainer = apiOperation.responseContainer(); } List<SecurityRequirement> securities = new ArrayList<>(); for (Authorization auth : apiOperation.authorizations()) { if (!auth.value().isEmpty()) { SecurityRequirement security = new SecurityRequirement(); security.setName(auth.value()); for (AuthorizationScope scope : auth.scopes()) { if (!scope.scope().isEmpty()) { security.addScope(scope.scope()); } } securities.add(security); } } for (SecurityRequirement sec : securities) { operation.security(sec); } } operation.operationId(operationId); if (responseClassType == null) { // pick out response from method declaration LOGGER.debug("picking up response class from method " + method); responseClassType = method.getGenericReturnType(); } boolean hasApiAnnotation = false; if (responseClassType instanceof Class) { hasApiAnnotation = AnnotationUtils.findAnnotation((Class) responseClassType, Api.class) != null; } if ((responseClassType != null) && !responseClassType.equals(Void.class) && !responseClassType.equals(void.class) && !responseClassType.equals(javax.ws.rs.core.Response.class) && !hasApiAnnotation && !isSubResource(httpMethod, method)) { if (isPrimitive(responseClassType)) { Property property = ModelConverters.getInstance().readAsProperty(responseClassType); if (property != null) { Property responseProperty = RESPONSE_CONTAINER_CONVERTER.withResponseContainer(responseContainer, property); operation.response(responseCode, new Response() .description("successful operation") .schema(responseProperty) .headers(defaultResponseHeaders)); } } else if (!responseClassType.equals(Void.class) && !responseClassType.equals(void.class)) { Map<String, Model> models = ModelConverters.getInstance().read(responseClassType); if (models.isEmpty()) { Property p = ModelConverters.getInstance().readAsProperty(responseClassType); operation.response(responseCode, new Response() .description("successful operation") .schema(p) .headers(defaultResponseHeaders)); } for (String key : models.keySet()) { Property responseProperty = RESPONSE_CONTAINER_CONVERTER.withResponseContainer(responseContainer, new RefProperty().asDefault(key)); operation.response(responseCode, new Response() .description("successful operation") .schema(responseProperty) .headers(defaultResponseHeaders)); swagger.model(key, models.get(key)); } } Map<String, Model> models = readAllModels(responseClassType); for (Map.Entry<String, Model> entry : models.entrySet()) { swagger.model(entry.getKey(), entry.getValue()); } } Consumes consumes = AnnotationUtils.findAnnotation(method, Consumes.class); if (consumes != null) { for (String mediaType : consumes.value()) { operation.consumes(mediaType); } } Produces produces = AnnotationUtils.findAnnotation(method, Produces.class); if (produces != null) { for (String mediaType : produces.value()) { operation.produces(mediaType); } } ApiResponses responseAnnotation = AnnotationUtils.findAnnotation(method, ApiResponses.class); if (responseAnnotation != null) { updateApiResponse(operation, responseAnnotation); } if (AnnotationUtils.findAnnotation(method, Deprecated.class) != null) { operation.deprecated(true); } // process parameters Class<?>[] parameterTypes = method.getParameterTypes(); Type[] genericParameterTypes = method.getGenericParameterTypes(); Annotation[][] paramAnnotations = findParamAnnotations(method); for (int i = 0; i < parameterTypes.length; i++) { Type type = genericParameterTypes[i]; List<Annotation> annotations = Arrays.asList(paramAnnotations[i]); List<Parameter> parameters = getParameters(type, annotations); for (Parameter parameter : parameters) { if (hasCommonParameter(parameter)) { Parameter refParameter = new RefParameter(RefType.PARAMETER.getInternalPrefix() + parameter.getName()); operation.parameter(refParameter); } else { parameter = replaceArrayModelForOctetStream(operation, parameter); operation.parameter(parameter); } } } if (operation.getResponses() == null) { operation.defaultResponse(new Response().description("successful operation")); } // Process @ApiImplicitParams this.readImplicitParameters(method, operation); processOperationDecorator(operation, method); return operation; }
#vulnerable code public Operation parseMethod(String httpMethod, Method method) { int responseCode = 200; Operation operation = new Operation(); ApiOperation apiOperation = AnnotationUtils.findAnnotation(method, ApiOperation.class); String operationId = getOperationId(method, httpMethod); String responseContainer = null; Type responseClassType = null; Map<String, Property> defaultResponseHeaders = null; if (apiOperation != null) { if (apiOperation.hidden()) { return null; } if (!apiOperation.nickname().isEmpty()) { operationId = apiOperation.nickname(); } defaultResponseHeaders = parseResponseHeaders(apiOperation.responseHeaders()); operation.summary(apiOperation.value()).description(apiOperation.notes()); Map<String, Object> customExtensions = BaseReaderUtils.parseExtensions(apiOperation.extensions()); operation.setVendorExtensions(customExtensions); if (!apiOperation.response().equals(Void.class) && !apiOperation.response().equals(void.class)) { responseClassType = apiOperation.response(); } if (!apiOperation.responseContainer().isEmpty()) { responseContainer = apiOperation.responseContainer(); } List<SecurityRequirement> securities = new ArrayList<>(); for (Authorization auth : apiOperation.authorizations()) { if (!auth.value().isEmpty()) { SecurityRequirement security = new SecurityRequirement(); security.setName(auth.value()); for (AuthorizationScope scope : auth.scopes()) { if (!scope.scope().isEmpty()) { security.addScope(scope.scope()); } } securities.add(security); } } for (SecurityRequirement sec : securities) { operation.security(sec); } } operation.operationId(operationId); if (responseClassType == null) { // pick out response from method declaration LOGGER.debug("picking up response class from method " + method); responseClassType = method.getGenericReturnType(); } boolean hasApiAnnotation = false; if (responseClassType instanceof Class) { hasApiAnnotation = AnnotationUtils.findAnnotation((Class) responseClassType, Api.class) != null; } if ((responseClassType != null) && !responseClassType.equals(Void.class) && !responseClassType.equals(void.class) && !responseClassType.equals(javax.ws.rs.core.Response.class) && !hasApiAnnotation && !isSubResource(httpMethod, method)) { if (isPrimitive(responseClassType)) { Property property = ModelConverters.getInstance().readAsProperty(responseClassType); if (property != null) { Property responseProperty = RESPONSE_CONTAINER_CONVERTER.withResponseContainer(responseContainer, property); operation.response(responseCode, new Response() .description("successful operation") .schema(responseProperty) .headers(defaultResponseHeaders)); } } else if (!responseClassType.equals(Void.class) && !responseClassType.equals(void.class)) { Map<String, Model> models = readModels(responseClassType); if (models.isEmpty()) { Property p = ModelConverters.getInstance().readAsProperty(responseClassType); operation.response(responseCode, new Response() .description("successful operation") .schema(p) .headers(defaultResponseHeaders)); } for (String key : models.keySet()) { Property responseProperty = RESPONSE_CONTAINER_CONVERTER.withResponseContainer(responseContainer, new RefProperty().asDefault(key)); operation.response(responseCode, new Response() .description("successful operation") .schema(responseProperty) .headers(defaultResponseHeaders)); swagger.model(key, models.get(key)); } } Map<String, Model> models = readAllModels(responseClassType); for (Map.Entry<String, Model> entry : models.entrySet()) { swagger.model(entry.getKey(), entry.getValue()); } } Consumes consumes = AnnotationUtils.findAnnotation(method, Consumes.class); if (consumes != null) { for (String mediaType : consumes.value()) { operation.consumes(mediaType); } } Produces produces = AnnotationUtils.findAnnotation(method, Produces.class); if (produces != null) { for (String mediaType : produces.value()) { operation.produces(mediaType); } } ApiResponses responseAnnotation = AnnotationUtils.findAnnotation(method, ApiResponses.class); if (responseAnnotation != null) { updateApiResponse(operation, responseAnnotation); } if (AnnotationUtils.findAnnotation(method, Deprecated.class) != null) { operation.deprecated(true); } // process parameters Class<?>[] parameterTypes = method.getParameterTypes(); Type[] genericParameterTypes = method.getGenericParameterTypes(); Annotation[][] paramAnnotations = findParamAnnotations(method); for (int i = 0; i < parameterTypes.length; i++) { Type type = genericParameterTypes[i]; List<Annotation> annotations = Arrays.asList(paramAnnotations[i]); List<Parameter> parameters = getParameters(type, annotations); for (Parameter parameter : parameters) { if (hasCommonParameter(parameter)) { Parameter refParameter = new RefParameter(RefType.PARAMETER.getInternalPrefix() + parameter.getName()); operation.parameter(refParameter); } else { parameter = replaceArrayModelForOctetStream(operation, parameter); operation.parameter(parameter); } } } if (operation.getResponses() == null) { operation.defaultResponse(new Response().description("successful operation")); } // Process @ApiImplicitParams this.readImplicitParameters(method, operation); processOperationDecorator(operation, method); return operation; } #location 80 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code private Operation parseMethod(Method method) { Operation operation = new Operation(); RequestMapping requestMapping = AnnotationUtils.findAnnotation(method, RequestMapping.class); Class<?> responseClass = null; List<String> produces = new ArrayList<String>(); List<String> consumes = new ArrayList<String>(); String responseContainer = null; String operationId = method.getName(); Map<String, Property> defaultResponseHeaders = null; Set<Map<String, Object>> customExtensions = null; ApiOperation apiOperation = AnnotationUtils.findAnnotation(method, ApiOperation.class); if (apiOperation.hidden()) return null; if (!"".equals(apiOperation.nickname())) operationId = apiOperation.nickname(); defaultResponseHeaders = parseResponseHeaders(apiOperation.responseHeaders()); operation.summary(apiOperation.value()).description(apiOperation.notes()); customExtensions = parseCustomExtensions(apiOperation.extensions()); if (customExtensions != null) { for (Map<String, Object> extension : customExtensions) { if (extension != null) { for (Map.Entry<String, Object> map : extension.entrySet()) { operation.setVendorExtension(map.getKey().startsWith("x-") ? map.getKey() : "x-" + map.getKey(), map.getValue()); } } } } if (apiOperation.response() != null && !Void.class.equals(apiOperation.response())) responseClass = apiOperation.response(); if (!"".equals(apiOperation.responseContainer())) responseContainer = apiOperation.responseContainer(); ///security if (apiOperation.authorizations() != null) { List<SecurityRequirement> securities = new ArrayList<SecurityRequirement>(); for (Authorization auth : apiOperation.authorizations()) { if (auth.value() != null && !"".equals(auth.value())) { SecurityRequirement security = new SecurityRequirement(); security.setName(auth.value()); AuthorizationScope[] scopes = auth.scopes(); for (AuthorizationScope scope : scopes) { if (scope.scope() != null && !"".equals(scope.scope())) { security.addScope(scope.scope()); } } securities.add(security); } } if (securities.size() > 0) { for (SecurityRequirement sec : securities) operation.security(sec); } } if (responseClass == null) { // pick out response from method declaration LOG.info("picking up response class from method " + method); Type t = method.getGenericReturnType(); responseClass = method.getReturnType(); if (responseClass.equals(ResponseEntity.class)) { responseClass = getGenericSubtype(method.getReturnType(), method.getGenericReturnType()); } if (!responseClass.equals(Void.class) && !"void".equals(responseClass.toString()) && AnnotationUtils.findAnnotation(responseClass, Api.class) == null) { LOG.info("reading model " + responseClass); Map<String, Model> models = ModelConverters.getInstance().readAll(t); } } if (responseClass != null && !responseClass.equals(Void.class) && !responseClass.equals(ResponseEntity.class) && AnnotationUtils.findAnnotation(responseClass, Api.class) == null) { if (isPrimitive(responseClass)) { Property responseProperty = null; Property property = ModelConverters.getInstance().readAsProperty(responseClass); if (property != null) { if ("list".equalsIgnoreCase(responseContainer)) responseProperty = new ArrayProperty(property); else if ("map".equalsIgnoreCase(responseContainer)) responseProperty = new MapProperty(property); else responseProperty = property; operation.response(apiOperation.code(), new Response() .description("successful operation") .schema(responseProperty) .headers(defaultResponseHeaders)); } } else if (!responseClass.equals(Void.class) && !"void".equals(responseClass.toString())) { Map<String, Model> models = ModelConverters.getInstance().read(responseClass); if (models.size() == 0) { Property pp = ModelConverters.getInstance().readAsProperty(responseClass); operation.response(apiOperation.code(), new Response() .description("successful operation") .schema(pp) .headers(defaultResponseHeaders)); } for (String key : models.keySet()) { Property responseProperty = null; if ("list".equalsIgnoreCase(responseContainer)) responseProperty = new ArrayProperty(new RefProperty().asDefault(key)); else if ("map".equalsIgnoreCase(responseContainer)) responseProperty = new MapProperty(new RefProperty().asDefault(key)); else responseProperty = new RefProperty().asDefault(key); operation.response(apiOperation.code(), new Response() .description("successful operation") .schema(responseProperty) .headers(defaultResponseHeaders)); swagger.model(key, models.get(key)); } models = ModelConverters.getInstance().readAll(responseClass); for (String key : models.keySet()) { swagger.model(key, models.get(key)); } } } operation.operationId(operationId); if (requestMapping.produces() != null) { for (String str : Arrays.asList(requestMapping.produces())) { if (!produces.contains(str)) { produces.add(str); } } } if (requestMapping.consumes() != null) { for (String str : Arrays.asList(requestMapping.consumes())) { if (!consumes.contains(str)) { consumes.add(str); } } } ApiResponses responseAnnotation = AnnotationUtils.findAnnotation(method, ApiResponses.class); if (responseAnnotation != null) { updateApiResponse(operation, responseAnnotation); } else { ResponseStatus responseStatus = AnnotationUtils.findAnnotation(method, ResponseStatus.class); if (responseStatus != null) { operation.response(responseStatus.value().value(), new Response().description(responseStatus.reason())); } } Deprecated annotation = AnnotationUtils.findAnnotation(method, Deprecated.class); if (annotation != null) operation.deprecated(true); // FIXME `hidden` is never used boolean hidden = false; if (apiOperation != null) hidden = apiOperation.hidden(); // process parameters Class[] parameterTypes = method.getParameterTypes(); Type[] genericParameterTypes = method.getGenericParameterTypes(); Annotation[][] paramAnnotations = method.getParameterAnnotations(); // paramTypes = method.getParameterTypes // genericParamTypes = method.getGenericParameterTypes for (int i = 0; i < parameterTypes.length; i++) { Type type = genericParameterTypes[i]; List<Annotation> annotations = Arrays.asList(paramAnnotations[i]); List<Parameter> parameters = getParameters(type, annotations); for (Parameter parameter : parameters) { operation.parameter(parameter); } } if (operation.getResponses() == null) { operation.defaultResponse(new Response().description("successful operation")); } // Process @ApiImplicitParams this.readImplicitParameters(method, operation); return operation; }
#vulnerable code private Operation parseMethod(Method method) { Operation operation = new Operation(); RequestMapping requestMapping = Annotations.get(method, RequestMapping.class); Class<?> responseClass = null; List<String> produces = new ArrayList<String>(); List<String> consumes = new ArrayList<String>(); String responseContainer = null; String operationId = method.getName(); Map<String, Property> defaultResponseHeaders = null; Set<Map<String, Object>> customExtensions = null; ApiOperation apiOperation = Annotations.get(method, ApiOperation.class); if (apiOperation.hidden()) return null; if (!"".equals(apiOperation.nickname())) operationId = apiOperation.nickname(); defaultResponseHeaders = parseResponseHeaders(apiOperation.responseHeaders()); operation.summary(apiOperation.value()).description(apiOperation.notes()); customExtensions = parseCustomExtensions(apiOperation.extensions()); if (customExtensions != null) { for (Map<String, Object> extension : customExtensions) { if (extension != null) { for (Map.Entry<String, Object> map : extension.entrySet()) { operation.setVendorExtension(map.getKey().startsWith("x-") ? map.getKey() : "x-" + map.getKey(), map.getValue()); } } } } if (apiOperation.response() != null && !Void.class.equals(apiOperation.response())) responseClass = apiOperation.response(); if (!"".equals(apiOperation.responseContainer())) responseContainer = apiOperation.responseContainer(); ///security if (apiOperation.authorizations() != null) { List<SecurityRequirement> securities = new ArrayList<SecurityRequirement>(); for (Authorization auth : apiOperation.authorizations()) { if (auth.value() != null && !"".equals(auth.value())) { SecurityRequirement security = new SecurityRequirement(); security.setName(auth.value()); AuthorizationScope[] scopes = auth.scopes(); for (AuthorizationScope scope : scopes) { if (scope.scope() != null && !"".equals(scope.scope())) { security.addScope(scope.scope()); } } securities.add(security); } } if (securities.size() > 0) { for (SecurityRequirement sec : securities) operation.security(sec); } } if (responseClass == null) { // pick out response from method declaration LOG.info("picking up response class from method " + method); Type t = method.getGenericReturnType(); responseClass = method.getReturnType(); if (responseClass.equals(ResponseEntity.class)) { responseClass = getGenericSubtype(method.getReturnType(), method.getGenericReturnType()); } if (!responseClass.equals(Void.class) && !"void".equals(responseClass.toString()) && Annotations.get(responseClass, Api.class) == null) { LOG.info("reading model " + responseClass); Map<String, Model> models = ModelConverters.getInstance().readAll(t); } } if (responseClass != null && !responseClass.equals(Void.class) && !responseClass.equals(ResponseEntity.class) && Annotations.get(responseClass, Api.class) == null) { if (isPrimitive(responseClass)) { Property responseProperty = null; Property property = ModelConverters.getInstance().readAsProperty(responseClass); if (property != null) { if ("list".equalsIgnoreCase(responseContainer)) responseProperty = new ArrayProperty(property); else if ("map".equalsIgnoreCase(responseContainer)) responseProperty = new MapProperty(property); else responseProperty = property; operation.response(apiOperation.code(), new Response() .description("successful operation") .schema(responseProperty) .headers(defaultResponseHeaders)); } } else if (!responseClass.equals(Void.class) && !"void".equals(responseClass.toString())) { Map<String, Model> models = ModelConverters.getInstance().read(responseClass); if (models.size() == 0) { Property pp = ModelConverters.getInstance().readAsProperty(responseClass); operation.response(apiOperation.code(), new Response() .description("successful operation") .schema(pp) .headers(defaultResponseHeaders)); } for (String key : models.keySet()) { Property responseProperty = null; if ("list".equalsIgnoreCase(responseContainer)) responseProperty = new ArrayProperty(new RefProperty().asDefault(key)); else if ("map".equalsIgnoreCase(responseContainer)) responseProperty = new MapProperty(new RefProperty().asDefault(key)); else responseProperty = new RefProperty().asDefault(key); operation.response(apiOperation.code(), new Response() .description("successful operation") .schema(responseProperty) .headers(defaultResponseHeaders)); swagger.model(key, models.get(key)); } models = ModelConverters.getInstance().readAll(responseClass); for (String key : models.keySet()) { swagger.model(key, models.get(key)); } } } operation.operationId(operationId); if (requestMapping.produces() != null) { for (String str : Arrays.asList(requestMapping.produces())) { if (!produces.contains(str)) { produces.add(str); } } } if (requestMapping.consumes() != null) { for (String str : Arrays.asList(requestMapping.consumes())) { if (!consumes.contains(str)) { consumes.add(str); } } } ApiResponses responseAnnotation = Annotations.get(method, ApiResponses.class); if (responseAnnotation != null) { updateApiResponse(operation, responseAnnotation); } else { ResponseStatus responseStatus = Annotations.get(method, ResponseStatus.class); if (responseStatus != null) { operation.response(responseStatus.value().value(), new Response().description(responseStatus.reason())); } } Deprecated annotation = Annotations.get(method, Deprecated.class); if (annotation != null) operation.deprecated(true); // FIXME `hidden` is never used boolean hidden = false; if (apiOperation != null) hidden = apiOperation.hidden(); // process parameters Class[] parameterTypes = method.getParameterTypes(); Type[] genericParameterTypes = method.getGenericParameterTypes(); Annotation[][] paramAnnotations = method.getParameterAnnotations(); // paramTypes = method.getParameterTypes // genericParamTypes = method.getGenericParameterTypes for (int i = 0; i < parameterTypes.length; i++) { Type type = genericParameterTypes[i]; List<Annotation> annotations = Arrays.asList(paramAnnotations[i]); List<Parameter> parameters = getParameters(type, annotations); for (Parameter parameter : parameters) { operation.parameter(parameter); } } if (operation.getResponses() == null) { operation.defaultResponse(new Response().description("successful operation")); } // Process @ApiImplicitParams this.readImplicitParameters(method, operation); return operation; } #location 15 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Test public void testGeneratedDoc() throws Exception { mojo.execute(); FileInputStream swaggerJson = null; BufferedReader swaggerReader = null; try { File actual = docOutput; File expected = new File(this.getClass().getResource("/sample-springmvc.html").getFile()); String exptectedFileContent = CharMatcher.breakingWhitespace().removeFrom(Files.toString(expected, Charset.forName("UTF-8"))); String actualFileContent = CharMatcher.breakingWhitespace().removeFrom(Files.toString(actual, Charset.forName("UTF-8"))); assertEquals(exptectedFileContent, actualFileContent); swaggerJson = new FileInputStream(new File(swaggerOutputDir, "swagger.json")); swaggerReader = new BufferedReader(new InputStreamReader(swaggerJson)); String s = swaggerReader.readLine(); while (s != null) { if (s.contains("\"parameters\" : [ ],")) { fail("should not have null parameters"); } s = swaggerReader.readLine(); } } finally { if (swaggerJson != null) { swaggerJson.close(); } if (swaggerReader != null) { swaggerReader.close(); } } }
#vulnerable code @Test public void testGeneratedDoc() throws Exception { mojo.execute(); BufferedReader actualReader = null; BufferedReader expectReader = null; FileInputStream swaggerJson = null; BufferedReader swaggerReader = null; try { File actual = docOutput; File expected = new File(this.getClass().getResource("/sample-springmvc.html").getFile()); FileAssert.assertEquals(expected, actual); swaggerJson = new FileInputStream(new File(swaggerOutputDir, "swagger.json")); swaggerReader = new BufferedReader(new InputStreamReader(swaggerJson)); String s = swaggerReader.readLine(); while (s != null) { if (s.contains("\"parameters\" : [ ],")) { assertFalse("should not have null parameters", true); } s = swaggerReader.readLine(); } } finally { if (actualReader != null) { actualReader.close(); } if (expectReader != null) { expectReader.close(); } if (swaggerJson != null) { swaggerJson.close(); } if (swaggerReader != null) { swaggerReader.close(); } } } #location 21 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public void toDocuments() throws GenerateException { if (outputTemplate == null) { prepareMustacheTemplate(); } if (outputTemplate.getApiDocuments().isEmpty()) { LOG.warn("nothing to write."); return; } LOG.info("Writing doc to " + outputPath + "..."); FileOutputStream fileOutputStream = null; try { fileOutputStream = new FileOutputStream(outputPath); } catch (FileNotFoundException e) { throw new GenerateException(e); } OutputStreamWriter writer = new OutputStreamWriter(fileOutputStream, Charset.forName("UTF-8")); try { URL url = getTemplateUri().toURL(); InputStreamReader reader = new InputStreamReader(url.openStream(), Charset.forName("UTF-8")); Mustache mustache = getMustacheFactory().compile(reader, templatePath); mustache.execute(writer, outputTemplate).flush(); writer.close(); LOG.info("Done!"); } catch (MalformedURLException e) { throw new GenerateException(e); } catch (IOException e) { throw new GenerateException(e); } }
#vulnerable code public void toDocuments() throws GenerateException { if (outputTemplate == null) { prepareMustacheTemplate(); } if (outputTemplate.getApiDocuments().isEmpty()) { LOG.warn("nothing to write."); return; } LOG.info("Writing doc to " + outputPath + "..."); FileOutputStream fileOutputStream = null; try { fileOutputStream = new FileOutputStream(outputPath); } catch (FileNotFoundException e) { throw new GenerateException(e); } OutputStreamWriter writer = new OutputStreamWriter(fileOutputStream, Charset.forName("UTF-8")); MustacheFactory mf = new DefaultMustacheFactory(); URI uri = null; try { uri = new URI(templatePath); } catch (URISyntaxException e) { throw new GenerateException(e); } if (!uri.isAbsolute()) { File file = new File(templatePath); if (!file.exists()) { throw new GenerateException("Template " + file.getAbsoluteFile() + " not found. You can go to https://github.com/kongchen/api-doc-template to get templates."); } else { uri = new File(templatePath).toURI(); } } URL url = null; try { url = uri.toURL(); InputStreamReader reader = new InputStreamReader(url.openStream(), Charset.forName("UTF-8")); Mustache mustache = mf.compile(reader, templatePath); mustache.execute(writer, outputTemplate).flush(); writer.close(); LOG.info("Done!"); } catch (MalformedURLException e) { throw new GenerateException(e); } catch (IOException e) { throw new GenerateException(e); } } #location 30 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code private boolean stopUsingMysqldadmin() { boolean retValue = false; Reader stdOut = null; Reader stdErr = null; LogFileProcessor processor = null; Set<String> successPatterns = Sets.newHashSet( "'Can't connect to MySQL server on 'localhost'", Platform.detect() == Windows ? "mysqld.exe: Shutdown complete" : "mysqld: Shutdown complete"); try { String cmd = Paths.get(getExecutable().getFile().generatedBaseDir().getAbsolutePath(), "bin", "mysqladmin").toString(); Process p = Runtime.getRuntime().exec(new String[] { cmd, "--no-defaults", "--protocol=tcp", String.format("-u%s", MysqldConfig.SystemDefaults.USERNAME), "shutdown"}); retValue = p.waitFor() == 0; OutputWatchStreamProcessor outputWatch = new OutputWatchStreamProcessor( successPatterns, Sets.newHashSet("[ERROR]"), StreamToLineProcessor.wrap(getRuntimeConfig().getProcessOutput().getOutput())); processor = new LogFileProcessor(new File(this.getExecutable().executable.generatedBaseDir() + "/data/error.log"), outputWatch); stdOut = new InputStreamReader(p.getInputStream()); stdErr = new InputStreamReader(p.getErrorStream()); if (retValue) { outputWatch.waitForResult(getConfig().getTimeout()); if (!outputWatch.isInitWithSuccess()) { logger.error("mysql shutdown failed. Expected to find in output: 'Shutdown complete', got: " + outputWatch.getFailureFound()); retValue = false; } } else { String errOutput = CharStreams.toString(stdErr); if (errOutput.contains("Can't connect to MySQL server on")) { logger.warn("mysql was already shutdown - no need to add extra shutdown hook - process does it out of the box."); retValue = true; } else { logger.error("mysql shutdown failed with error code: " + p.waitFor() + " and message: " + CharStreams.toString(stdErr)); } } } catch (InterruptedException e) { logger.warn("Encountered error why shutting down process.", e); } catch (IOException e) { logger.warn("Encountered error why shutting down process.", e); } finally { closeCloseables(stdOut, stdErr); if (processor != null) processor.shutdown(); } return retValue; }
#vulnerable code private boolean stopUsingMysqldadmin() { boolean retValue = false; Reader stdOut = null; Reader stdErr = null; LogFileProcessor processor = null; Set<String> successPatterns = Sets.newHashSet( "'Can't connect to MySQL server on 'localhost'", Platform.detect() == Windows ? "mysqld.exe: Shutdown complete" : "mysqld: Shutdown complete"); try { String cmd = Paths.get(getExecutable().getFile().generatedBaseDir().getAbsolutePath(), "bin", "mysqladmin").toString(); Process p = Runtime.getRuntime().exec(new String[] { cmd, "--no-defaults", "--protocol=tcp", String.format("-u%s", MysqldConfig.SystemDefaults.USERNAME), "shutdown"}); retValue = p.waitFor() == 0; OutputWatchStreamProcessor outputWatch = new OutputWatchStreamProcessor( successPatterns, Sets.newHashSet("[ERROR]"), StreamToLineProcessor.wrap(getRuntimeConfig().getProcessOutput().getOutput())); processor = new LogFileProcessor(new File(this.getExecutable().executable.generatedBaseDir() + "/data/error.log"), outputWatch); stdOut = new InputStreamReader(p.getInputStream()); stdErr = new InputStreamReader(p.getErrorStream()); if (retValue) { outputWatch.waitForResult(getConfig().getTimeout()); if (!outputWatch.isInitWithSuccess()) { logger.error("mysql shutdown failed. Expected to find in output: 'Shutdown complete', got: " + outputWatch.getFailureFound()); retValue = false; } } else { logger.error("mysql shutdown failed with error code: " + p.waitFor() + " and message: " + CharStreams.toString(stdErr)); } } catch (InterruptedException e) { logger.warn("Encountered error why shutting down process.", e); } catch (IOException e) { logger.warn("Encountered error why shutting down process.", e); } finally { closeCloseables(stdOut, stdErr); if (processor != null) processor.shutdown(); } return retValue; } #location 39 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code private void execute(final String sql) { String command = (Platform.detect() == Windows) ? format("\"%s\"", sql) : sql; try { Process p = new ProcessBuilder(new String[]{ Paths.get(executable.getBaseDir().getAbsolutePath(), "bin", "mysql").toString(), "--protocol=tcp", format("--user=%s", SystemDefaults.USERNAME), format("--port=%s", config.getPort()), schemaName}).start(); IOUtils.copy(new StringReader(sql), p.getOutputStream(), Charset.defaultCharset()); p.getOutputStream().close(); if (p.waitFor() != 0) { String out = IOUtils.toString(p.getInputStream()); String err = IOUtils.toString(p.getErrorStream()); if (isNullOrEmpty(out)) throw new CommandFailedException(command, schemaName, p.waitFor(), err); else throw new CommandFailedException(command, schemaName, p.waitFor(), out); } } catch (IOException | InterruptedException e) { throw new CommandFailedException(command, schemaName, e.getMessage(), e); } }
#vulnerable code private void execute(final String sql) { String command = (Platform.detect() == Windows) ? format("\"%s\"", sql) : sql; try { Process p = Runtime.getRuntime().exec(new String[]{ Paths.get(executable.getBaseDir().getAbsolutePath(), "bin", "mysql").toString(), "--protocol=tcp", format("--user=%s", SystemDefaults.USERNAME), format("--port=%s", config.getPort()), "-e", command, schemaName}); if (p.waitFor() != 0) { String out = IOUtils.toString(p.getInputStream()); String err = IOUtils.toString(p.getErrorStream()); if (isNullOrEmpty(out)) throw new CommandFailedException(command, schemaName, p.waitFor(), err); else throw new CommandFailedException(command, schemaName, p.waitFor(), out); } } catch (IOException | InterruptedException e) { throw new CommandFailedException(command, schemaName, e.getMessage(), e); } } #location 18 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code private boolean stopUsingMysqldadmin() { ResultMatchingListener shutdownListener = outputWatch.addListener(new ResultMatchingListener(": Shutdown complete")); boolean retValue = false; Reader stdErr = null; try { String cmd = Paths.get(getExecutable().getFile().baseDir().getAbsolutePath(), "bin", "mysqladmin").toString(); Process p = Runtime.getRuntime().exec(new String[]{ cmd, "--no-defaults", "--protocol=tcp", format("-u%s", MysqldConfig.SystemDefaults.USERNAME), format("--port=%s", getConfig().getPort()), "shutdown"}); retValue = p.waitFor() == 0; stdErr = new InputStreamReader(p.getErrorStream()); if (retValue) { shutdownListener.waitForResult(getConfig().getTimeout()); if (!shutdownListener.isInitWithSuccess()) { logger.error("mysql shutdown failed. Expected to find in output: 'Shutdown complete', got: " + shutdownListener.getFailureFound()); retValue = false; } else { retValue = true; } } else { String errOutput = CharStreams.toString(stdErr); if (errOutput.contains("Can't connect to MySQL server on")) { logger.warn("mysql was already shutdown - no need to add extra shutdown hook - process does it out of the box."); retValue = true; } else { logger.error("mysql shutdown failed with error code: " + p.waitFor() + " and message: " + errOutput); } } } catch (InterruptedException | IOException e) { logger.warn("Encountered error why shutting down process.", e); } finally { closeCloseables(stdErr); } return retValue; }
#vulnerable code private boolean stopUsingMysqldadmin() { boolean retValue = false; Reader stdOut = null; Reader stdErr = null; LogFileProcessor processor = null; Set<String> successPatterns = Sets.newHashSet( "'Can't connect to MySQL server on 'localhost'", Platform.detect() == Windows ? "mysqld.exe: Shutdown complete" : "mysqld: Shutdown complete"); try { String cmd = Paths.get(getExecutable().getFile().baseDir().getAbsolutePath(), "bin", "mysqladmin").toString(); Process p = Runtime.getRuntime().exec(new String[] { cmd, "--no-defaults", "--protocol=tcp", format("-u%s", MysqldConfig.SystemDefaults.USERNAME), format("--port=%s", getConfig().getPort()), "shutdown"}); retValue = p.waitFor() == 0; OutputWatchStreamProcessor outputWatch = new OutputWatchStreamProcessor(successPatterns, "[ERROR]", StreamToLineProcessor.wrap(getRuntimeConfig().getProcessOutput().getOutput())); processor = new LogFileProcessor(new File(this.getExecutable().getBaseDir() + "/data/error.log"), outputWatch); stdOut = new InputStreamReader(p.getInputStream()); stdErr = new InputStreamReader(p.getErrorStream()); if (retValue) { outputWatch.waitForResult(getConfig().getTimeout()); if (!outputWatch.isInitWithSuccess()) { logger.error("mysql shutdown failed. Expected to find in output: 'Shutdown complete', got: " + outputWatch.getFailureFound()); retValue = false; } } else { String errOutput = CharStreams.toString(stdErr); if (errOutput.contains("Can't connect to MySQL server on")) { logger.warn("mysql was already shutdown - no need to add extra shutdown hook - process does it out of the box."); retValue = true; } else { logger.error("mysql shutdown failed with error code: " + p.waitFor() + " and message: " + CharStreams.toString(stdErr)); } } } catch (InterruptedException | IOException e) { logger.warn("Encountered error why shutting down process.", e); } finally { closeCloseables(stdOut, stdErr); if (processor != null) processor.shutdown(); } return retValue; } #location 51 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code private void execute(final String sql) { String command = (Platform.detect() == Windows) ? format("\"%s\"", sql) : sql; try { Process p = new ProcessBuilder(new String[]{ Paths.get(executable.getBaseDir().getAbsolutePath(), "bin", "mysql").toString(), "--protocol=tcp", format("--user=%s", SystemDefaults.USERNAME), format("--port=%s", config.getPort()), schemaName}).start(); IOUtils.copy(new StringReader(sql), p.getOutputStream(), Charset.defaultCharset()); p.getOutputStream().close(); if (p.waitFor() != 0) { String out = IOUtils.toString(p.getInputStream()); String err = IOUtils.toString(p.getErrorStream()); if (isNullOrEmpty(out)) throw new CommandFailedException(command, schemaName, p.waitFor(), err); else throw new CommandFailedException(command, schemaName, p.waitFor(), out); } } catch (IOException | InterruptedException e) { throw new CommandFailedException(command, schemaName, e.getMessage(), e); } }
#vulnerable code private void execute(final String sql) { String command = (Platform.detect() == Windows) ? format("\"%s\"", sql) : sql; try { Process p = Runtime.getRuntime().exec(new String[]{ Paths.get(executable.getBaseDir().getAbsolutePath(), "bin", "mysql").toString(), "--protocol=tcp", format("--user=%s", SystemDefaults.USERNAME), format("--port=%s", config.getPort()), "-e", command, schemaName}); if (p.waitFor() != 0) { String out = IOUtils.toString(p.getInputStream()); String err = IOUtils.toString(p.getErrorStream()); if (isNullOrEmpty(out)) throw new CommandFailedException(command, schemaName, p.waitFor(), err); else throw new CommandFailedException(command, schemaName, p.waitFor(), out); } } catch (IOException | InterruptedException e) { throw new CommandFailedException(command, schemaName, e.getMessage(), e); } } #location 21 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code private void execute(final String sql) { String command = (Platform.detect() == Windows) ? format("\"%s\"", sql) : sql; try { Process p = new ProcessBuilder(new String[]{ Paths.get(executable.getBaseDir().getAbsolutePath(), "bin", "mysql").toString(), "--protocol=tcp", format("--user=%s", SystemDefaults.USERNAME), format("--port=%s", config.getPort()), schemaName}).start(); IOUtils.copy(new StringReader(sql), p.getOutputStream(), Charset.defaultCharset()); p.getOutputStream().close(); if (p.waitFor() != 0) { String out = IOUtils.toString(p.getInputStream()); String err = IOUtils.toString(p.getErrorStream()); if (isNullOrEmpty(out)) throw new CommandFailedException(command, schemaName, p.waitFor(), err); else throw new CommandFailedException(command, schemaName, p.waitFor(), out); } } catch (IOException | InterruptedException e) { throw new CommandFailedException(command, schemaName, e.getMessage(), e); } }
#vulnerable code private void execute(final String sql) { String command = (Platform.detect() == Windows) ? format("\"%s\"", sql) : sql; try { Process p = Runtime.getRuntime().exec(new String[]{ Paths.get(executable.getBaseDir().getAbsolutePath(), "bin", "mysql").toString(), "--protocol=tcp", format("--user=%s", SystemDefaults.USERNAME), format("--port=%s", config.getPort()), "-e", command, schemaName}); if (p.waitFor() != 0) { String out = IOUtils.toString(p.getInputStream()); String err = IOUtils.toString(p.getErrorStream()); if (isNullOrEmpty(out)) throw new CommandFailedException(command, schemaName, p.waitFor(), err); else throw new CommandFailedException(command, schemaName, p.waitFor(), out); } } catch (IOException | InterruptedException e) { throw new CommandFailedException(command, schemaName, e.getMessage(), e); } } #location 20 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code private boolean stopUsingMysqldadmin() { boolean retValue = false; Reader stdOut = null; Reader stdErr = null; LogFileProcessor processor = null; Set<String> successPatterns = Sets.newHashSet( "'Can't connect to MySQL server on 'localhost'", Platform.detect() == Windows ? "mysqld.exe: Shutdown complete" : "mysqld: Shutdown complete"); try { String cmd = Paths.get(getExecutable().getFile().generatedBaseDir().getAbsolutePath(), "bin", "mysqladmin").toString(); Process p = Runtime.getRuntime().exec(new String[] { cmd, "--no-defaults", "--protocol=tcp", String.format("-u%s", MysqldConfig.SystemDefaults.USERNAME), "shutdown"}); retValue = p.waitFor() == 0; OutputWatchStreamProcessor outputWatch = new OutputWatchStreamProcessor( successPatterns, Sets.newHashSet("[ERROR]"), StreamToLineProcessor.wrap(getRuntimeConfig().getProcessOutput().getOutput())); processor = new LogFileProcessor(new File(this.getExecutable().executable.generatedBaseDir() + "/data/error.log"), outputWatch); stdOut = new InputStreamReader(p.getInputStream()); stdErr = new InputStreamReader(p.getErrorStream()); if (retValue) { outputWatch.waitForResult(getConfig().getTimeout()); if (!outputWatch.isInitWithSuccess()) { logger.error("mysql shutdown failed. Expected to find in output: 'Shutdown complete', got: " + outputWatch.getFailureFound()); retValue = false; } } else { logger.error("mysql shutdown failed with error code: " + p.waitFor() + " and message: " + CharStreams.toString(stdErr)); } } catch (InterruptedException e) { logger.warn("Encountered error why shutting down process.", e); } catch (IOException e) { logger.warn("Encountered error why shutting down process.", e); } finally { closeCloseables(stdOut, stdErr); if (processor != null) processor.shutdown(); } return retValue; }
#vulnerable code private boolean stopUsingMysqldadmin() { boolean retValue = false; Reader stdOut = null; Reader stdErr = null; LogFileProcessor processor = null; Set<String> successPatterns = Sets.newHashSet("'Can't connect to MySQL server on 'localhost'"); try { Process p; if (Platform.detect() == Platform.Windows) { String cmd = Paths.get(getExecutable().getFile().generatedBaseDir().getAbsolutePath(), "bin", "mysqladmin.exe").toString(); successPatterns.add("mysqld.exe: Shutdown complete"); p = Runtime.getRuntime().exec(new String[] { cmd, "--no-defaults", "--protocol=tcp", String.format("-u%s", MysqldConfig.SystemDefaults.USERNAME), "shutdown"}); } else { String cmd = Paths.get(getExecutable().getFile().generatedBaseDir().getAbsolutePath(), "bin", "mysqladmin").toString(); successPatterns.add("mysqld: Shutdown complete"); p = Runtime.getRuntime().exec(new String[] { cmd, "--no-defaults", "--protocol=tcp", String.format("-u%s", MysqldConfig.SystemDefaults.USERNAME), //String.format("--socket=%s", sockFile(getExecutable().executable)), "shutdown"}); } retValue = p.waitFor() == 0; OutputWatchStreamProcessor outputWatch = new OutputWatchStreamProcessor( successPatterns, Sets.newHashSet("[ERROR]"), StreamToLineProcessor.wrap(unsafeRuntimeConfig.getProcessOutput().getOutput())); processor = new LogFileProcessor(new File(this.getExecutable().executable.generatedBaseDir() + "/data/error.log"), outputWatch); stdOut = new InputStreamReader(p.getInputStream()); stdErr = new InputStreamReader(p.getErrorStream()); if (retValue) { outputWatch.waitForResult(getConfig().getTimeout()); if (!outputWatch.isInitWithSuccess()) { logger.error("mysql shutdown failed. Expected to find in output: 'Shutdown complete', got: " + outputWatch.getFailureFound()); retValue = false; } } else { logger.error("mysql shutdown failed with error code: " + p.waitFor() + " and message: " + CharStreams.toString(stdErr)); } } catch (InterruptedException e) { logger.warn("Encountered error why shutting down process.", e); } catch (IOException e) { logger.warn("Encountered error why shutting down process.", e); } finally { closeCloseable(stdOut); closeCloseable(stdErr); if (processor != null) processor.shutdown(); } return retValue; } #location 60 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code protected SettableBeanProperty _resolvedObjectIdProperty(DeserializationContext ctxt, SettableBeanProperty prop) throws JsonMappingException { ObjectIdInfo objectIdInfo = prop.getObjectIdInfo(); JsonDeserializer<Object> valueDeser = prop.getValueDeserializer(); ObjectIdReader objectIdReader = (valueDeser == null) ? null : valueDeser.getObjectIdReader(); if (objectIdInfo == null && objectIdReader == null) { return prop; } return new ObjectIdReferenceProperty(prop, objectIdInfo); }
#vulnerable code protected SettableBeanProperty _resolvedObjectIdProperty(DeserializationContext ctxt, SettableBeanProperty prop) throws JsonMappingException { ObjectIdInfo objectIdInfo = prop.getObjectIdInfo(); JsonDeserializer<Object> valueDeser = prop.getValueDeserializer(); ObjectIdReader objectIdReader = valueDeser.getObjectIdReader(); if (objectIdInfo == null && objectIdReader == null) { return prop; } return new ObjectIdReferenceProperty(prop, objectIdInfo); } #location 6 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code void runOnce(int round, int max) throws Exception { final ObjectMapper mapper = getObjectMapper(); Callable<String> writeJson = new Callable<String>() { @Override public String call() throws Exception { Wrapper wrapper = new Wrapper(new TypeOne("test")); return mapper.writeValueAsString(wrapper); } }; int numThreads = 4; ExecutorService executor = Executors.newFixedThreadPool(numThreads); List<Future<String>> jsonFutures = new ArrayList<Future<String>>(); for (int i = 0; i < numThreads; i++) { jsonFutures.add(executor.submit(writeJson)); } executor.shutdown(); executor.awaitTermination(5, TimeUnit.SECONDS); for (Future<String> jsonFuture : jsonFutures) { String json = jsonFuture.get(); JsonNode tree = mapper.readTree(json); JsonNode wrapped = tree.get("hasSubTypes"); if (!wrapped.has("one")) { System.out.println("JSON wrong: "+json); throw new IllegalStateException("Round #"+round+"/"+max+" ; missing property 'one', source: "+json); } System.out.println("JSON fine: "+json); } }
#vulnerable code void runOnce() throws Exception { final ObjectMapper mapper = getObjectMapper(); Callable<String> writeJson = new Callable<String>() { @Override public String call() throws Exception { Wrapper wrapper = new Wrapper(new TypeOne("test")); return mapper.writeValueAsString(wrapper); } }; int numThreads = 4; ExecutorService executor = Executors.newFixedThreadPool(numThreads); List<Future<String>> jsonFutures = new ArrayList<Future<String>>(); for (int i = 0; i < numThreads; i++) { jsonFutures.add(executor.submit(writeJson)); } executor.shutdown(); executor.awaitTermination(5, TimeUnit.SECONDS); for (Future<String> jsonFuture : jsonFutures) { String json = jsonFuture.get(); JsonNode tree = mapper.readTree(json); JsonNode wrapped = tree.get("hasSubTypes"); if (!wrapped.has("one")) { throw new IllegalStateException("Missing 'one', source: "+json); } } } #location 26 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public void testDeepPrefixedUnwrappingDeserialize() throws Exception { DeepPrefixUnwrap bean = MAPPER.readValue("{\"u.name\":\"Bubba\",\"u._x\":2,\"u._y\":3}", DeepPrefixUnwrap.class); assertNotNull(bean.unwrapped); assertNotNull(bean.unwrapped.location); assertEquals(2, bean.unwrapped.location.x); assertEquals(3, bean.unwrapped.location.y); assertEquals("Bubba", bean.unwrapped.name); }
#vulnerable code public void testDeepPrefixedUnwrappingDeserialize() throws Exception { DeepPrefixUnwrap bean = mapper.readValue("{\"u.name\":\"Bubba\",\"u._x\":2,\"u._y\":3}", DeepPrefixUnwrap.class); assertNotNull(bean.unwrapped); assertNotNull(bean.unwrapped.location); assertEquals(2, bean.unwrapped.location.x); assertEquals(3, bean.unwrapped.location.y); assertEquals("Bubba", bean.unwrapped.name); } #location 5 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.