instruction
stringclasses
1 value
output
stringlengths
64
69.4k
input
stringlengths
205
32.4k
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public VanillaMappedBytes put(T key, File path, long size, long index) { DataHolder data = this.cache.get(key); if(data != null) { data.close(); } else { data = new DataHolder(); } try { cleanup(); data.recycle( VanillaMappedFile.readWrite(path, size), 0, size, index); this.cache.put(key,data); } catch(IOException e) { LOGGER.warn("",e); } return data.bytes(); }
#vulnerable code public VanillaMappedBytes put(T key, File path, long size, long index) { DataHolder data = this.cache.get(key); if(data != null) { data.close(); } else { data = new DataHolder(); } try { final Iterator<Map.Entry<T,DataHolder>> it = this.cache.entrySet().iterator(); while(it.hasNext()) { Map.Entry<T,DataHolder> entry = it.next(); if(entry.getValue().bytes().unmapped()) { entry.getValue().close(); it.remove(); } } data.recycle( VanillaMappedFile.readWrite(path, size), 0, size, index); this.cache.put(key,data); } catch(IOException e) { LOGGER.warn("",e); } return data.bytes(); } #location 13 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code private static void manyLongToggles(@NotNull DirectStore store1, int lockCount, int from, int to) { long id = Thread.currentThread().getId(); assertEquals(0, id >>> 32); System.out.println("Thread " + id); DirectBytes slice1 = store1.bytes(); int records = 64; for (int i = 0; i < lockCount; i += records) { for (long j = 0; j < records * 64; j += 64) { slice1.positionAndSize(j, 64); boolean condition = false; for (int k = 0; k < 20; k++) { condition = slice1.tryLockLong(0L) || slice1.tryLockNanosLong(0L, 5 * 1000 * 1000); if (condition) break; if (k > 0) System.out.println("k: " + (5 + k * 5)); } if (!condition) assertTrue("i= " + i, condition); long toggle1 = slice1.readLong(8); if (toggle1 == from) { slice1.writeLong(8L, to); } else { // noinspection AssignmentToForLoopParameter,AssignmentToForLoopParameter i--; } slice1.unlockLong(0L); System.currentTimeMillis(); // small delay } } }
#vulnerable code private static void manyLongToggles(@NotNull DirectStore store1, int lockCount, int from, int to) { long id = Thread.currentThread().getId(); assertEquals(0, id >>> 32); System.out.println("Thread " + id); DirectBytes slice1 = store1.createSlice(); int records = 64; for (int i = 0; i < lockCount; i += records) { for (long j = 0; j < records * 64; j += 64) { slice1.positionAndSize(j, 64); boolean condition = false; for (int k = 0; k < 20; k++) { condition = slice1.tryLockLong(0L) || slice1.tryLockNanosLong(0L, 5 * 1000 * 1000); if (condition) break; if (k > 0) System.out.println("k: " + (5 + k * 5)); } if (!condition) assertTrue("i= " + i, condition); long toggle1 = slice1.readLong(8); if (toggle1 == from) { slice1.writeLong(8L, to); } else { // noinspection AssignmentToForLoopParameter,AssignmentToForLoopParameter i--; } slice1.unlockLong(0L); System.currentTimeMillis(); // small delay } } } #location 19 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Test public void testToString() { NativeBytes bytes = new DirectStore(32).bytes(); assertEquals("[pos: 0, lim: 32, cap: 32 ] ٠٠٠٠٠٠٠٠٠٠٠٠٠٠٠٠٠٠٠٠٠٠٠٠٠٠٠٠٠٠٠٠", bytes.toString()); bytes.writeByte(1); assertEquals("[pos: 1, lim: 32, cap: 32 ] ⒈‖٠٠٠٠٠٠٠٠٠٠٠٠٠٠٠٠٠٠٠٠٠٠٠٠٠٠٠٠٠٠٠", bytes.toString()); bytes.writeByte(2); assertEquals("[pos: 2, lim: 32, cap: 32 ] ⒈⒉‖٠٠٠٠٠٠٠٠٠٠٠٠٠٠٠٠٠٠٠٠٠٠٠٠٠٠٠٠٠٠", bytes.toString()); bytes.writeByte(3); assertEquals("[pos: 3, lim: 32, cap: 32 ] ⒈⒉⒊‖٠٠٠٠٠٠٠٠٠٠٠٠٠٠٠٠٠٠٠٠٠٠٠٠٠٠٠٠٠", bytes.toString()); bytes.writeByte(4); assertEquals("[pos: 4, lim: 32, cap: 32 ] ⒈⒉⒊⒋‖٠٠٠٠٠٠٠٠٠٠٠٠٠٠٠٠٠٠٠٠٠٠٠٠٠٠٠٠", bytes.toString()); bytes.writeByte(5); assertEquals("[pos: 5, lim: 32, cap: 32 ] ⒈⒉⒊⒋⒌‖٠٠٠٠٠٠٠٠٠٠٠٠٠٠٠٠٠٠٠٠٠٠٠٠٠٠٠", bytes.toString()); bytes.writeByte(6); assertEquals("[pos: 6, lim: 32, cap: 32 ] ⒈⒉⒊⒋⒌⒍‖٠٠٠٠٠٠٠٠٠٠٠٠٠٠٠٠٠٠٠٠٠٠٠٠٠٠", bytes.toString()); bytes.writeByte(7); assertEquals("[pos: 7, lim: 32, cap: 32 ] ⒈⒉⒊⒋⒌⒍⒎‖٠٠٠٠٠٠٠٠٠٠٠٠٠٠٠٠٠٠٠٠٠٠٠٠٠", bytes.toString()); bytes.writeByte(8); assertEquals("[pos: 8, lim: 32, cap: 32 ] ⒈⒉⒊⒋⒌⒍⒎⒏‖٠٠٠٠٠٠٠٠٠٠٠٠٠٠٠٠٠٠٠٠٠٠٠٠", bytes.toString()); }
#vulnerable code @Test public void testToString() { NativeBytes bytes = new DirectStore(32).createSlice(); assertEquals("[pos: 0, lim: 32, cap: 32 ] ٠٠٠٠٠٠٠٠٠٠٠٠٠٠٠٠٠٠٠٠٠٠٠٠٠٠٠٠٠٠٠٠", bytes.toString()); bytes.writeByte(1); assertEquals("[pos: 1, lim: 32, cap: 32 ] ⒈‖٠٠٠٠٠٠٠٠٠٠٠٠٠٠٠٠٠٠٠٠٠٠٠٠٠٠٠٠٠٠٠", bytes.toString()); bytes.writeByte(2); assertEquals("[pos: 2, lim: 32, cap: 32 ] ⒈⒉‖٠٠٠٠٠٠٠٠٠٠٠٠٠٠٠٠٠٠٠٠٠٠٠٠٠٠٠٠٠٠", bytes.toString()); bytes.writeByte(3); assertEquals("[pos: 3, lim: 32, cap: 32 ] ⒈⒉⒊‖٠٠٠٠٠٠٠٠٠٠٠٠٠٠٠٠٠٠٠٠٠٠٠٠٠٠٠٠٠", bytes.toString()); bytes.writeByte(4); assertEquals("[pos: 4, lim: 32, cap: 32 ] ⒈⒉⒊⒋‖٠٠٠٠٠٠٠٠٠٠٠٠٠٠٠٠٠٠٠٠٠٠٠٠٠٠٠٠", bytes.toString()); bytes.writeByte(5); assertEquals("[pos: 5, lim: 32, cap: 32 ] ⒈⒉⒊⒋⒌‖٠٠٠٠٠٠٠٠٠٠٠٠٠٠٠٠٠٠٠٠٠٠٠٠٠٠٠", bytes.toString()); bytes.writeByte(6); assertEquals("[pos: 6, lim: 32, cap: 32 ] ⒈⒉⒊⒋⒌⒍‖٠٠٠٠٠٠٠٠٠٠٠٠٠٠٠٠٠٠٠٠٠٠٠٠٠٠", bytes.toString()); bytes.writeByte(7); assertEquals("[pos: 7, lim: 32, cap: 32 ] ⒈⒉⒊⒋⒌⒍⒎‖٠٠٠٠٠٠٠٠٠٠٠٠٠٠٠٠٠٠٠٠٠٠٠٠٠", bytes.toString()); bytes.writeByte(8); assertEquals("[pos: 8, lim: 32, cap: 32 ] ⒈⒉⒊⒋⒌⒍⒎⒏‖٠٠٠٠٠٠٠٠٠٠٠٠٠٠٠٠٠٠٠٠٠٠٠٠", bytes.toString()); } #location 20 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @NotNull @Override public String readLine() { StringBuilder input = acquireStringBuilder(); EOL: while (position() < capacity()) { int c = readUnsignedByteOrThrow(); switch (c) { case END_OF_BUFFER: case '\n': break EOL; case '\r': long cur = position(); if (cur < capacity() && readByte(cur) == '\n') position(cur + 1); break EOL; default: input.append((char) c); break; } } return SI.intern(input); }
#vulnerable code @NotNull @Override public String readLine() { StringBuilder input = acquireStringBuilder(); EOL: while (position() < capacity()) { int c = readUnsignedByteOrThrow(); switch (c) { case END_OF_BUFFER: case '\n': break EOL; case '\r': long cur = position(); if (cur < capacity() && readByte(cur) == '\n') position(cur + 1); break EOL; default: input.append((char) c); break; } } return stringInterner().intern(input); } #location 22 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Test public void testLocking() { // a page long start = System.nanoTime(); final DirectStore store1 = DirectStore.allocate(1 << 12); final int lockCount = 20 * 1000 * 1000; new Thread(new Runnable() { @Override public void run() { manyToggles(store1, lockCount, 1, 0); } }).start(); manyToggles(store1, lockCount, 0, 1); store1.free(); long time = System.nanoTime() - start; System.out.printf("Contended lock rate was %,d per second%n", (int) (lockCount * 2 * 1e9 / time)); }
#vulnerable code @Test public void testLocking() throws Exception { // a page long start = System.nanoTime(); final DirectStore store1 = DirectStore.allocate(1 << 12); final int lockCount = 20 * 1000000; Thread t = new Thread(new Runnable() { @Override public void run() { long id = Thread.currentThread().getId(); System.out.println("Thread " + id); assertEquals(0, id >>> 24); try { DirectBytes slice1 = store1.createSlice(); for (int i = 0; i < lockCount; i++) { slice1.busyLockInt(0); int toggle1 = slice1.readInt(4); if (toggle1 == 1) { slice1.writeInt(4, 0); } else { i--; } slice1.unlockInt(0); } } catch (InterruptedException e) { e.printStackTrace(); } } }); t.start(); long id = Thread.currentThread().getId(); assertEquals(0, id >>> 24); System.out.println("Thread " + id); DirectBytes slice1 = store1.createSlice(); for (int i = 0; i < lockCount; i++) { slice1.busyLockInt(0); int toggle1 = slice1.readInt(4); if (toggle1 == 0) { slice1.writeInt(4, 1); } else { i--; } slice1.unlockInt(0); } store1.free(); long time = System.nanoTime() - start; System.out.printf("Contended lock rate was %,d per second%n", (int) (lockCount * 2 * 1e9 / time)); } #location 50 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public static void readXml(String fname) throws CoreException { printX("Loading "+fname+"\n"); resetErrors(); resetWarnings(); // close existing subtitleStream if (subtitleStream != null) { subtitleStream.close(); } supXml = new SupXml(fname); subtitleStream = supXml; inMode = InputMode.XML; // decode first frame subtitleStream.decode(0); subVobTrg = new SubPictureDVD(); // automatically set luminance thresholds for VobSub conversion int maxLum = subtitleStream.getPalette().getY()[subtitleStream.getPrimaryColorIndex()] & 0xff; int[] luminanceThreshold = new int[2]; configuration.setLuminanceThreshold(luminanceThreshold); if (maxLum > 30) { luminanceThreshold[0] = maxLum*2/3; luminanceThreshold[1] = maxLum/3; } else { luminanceThreshold[0] = 210; luminanceThreshold[1] = 160; } // find language idx for (int i=0; i < LANGUAGES.length; i++) { if (LANGUAGES[i][2].equalsIgnoreCase(supXml.getLanguage())) { configuration.setLanguageIdx(i); break; } } // set frame rate configuration.setFpsSrc(supXml.getFps()); configuration.setFpsSrcCertain(true); if (Core.keepFps) { configuration.setFpsTrg(configuration.getFPSSrc()); } }
#vulnerable code public static void readXml(String fname) throws CoreException { printX("Loading "+fname+"\n"); resetErrors(); resetWarnings(); // close existing substream if (substream != null) { substream.close(); } supXml = new SupXml(fname); substream = supXml; inMode = InputMode.XML; // decode first frame substream.decode(0); subVobTrg = new SubPictureDVD(); // automatically set luminance thresholds for VobSub conversion int maxLum = substream.getPalette().getY()[substream.getPrimaryColorIndex()] & 0xff; int[] luminanceThreshold = new int[2]; configuration.setLuminanceThreshold(luminanceThreshold); if (maxLum > 30) { luminanceThreshold[0] = maxLum*2/3; luminanceThreshold[1] = maxLum/3; } else { luminanceThreshold[0] = 210; luminanceThreshold[1] = 160; } // find language idx for (int i=0; i < LANGUAGES.length; i++) { if (LANGUAGES[i][2].equalsIgnoreCase(supXml.getLanguage())) { configuration.setLanguageIdx(i); break; } } // set frame rate configuration.setFpsSrc(supXml.getFps()); configuration.setFpsSrcCertain(true); if (Core.keepFps) { configuration.setFpsTrg(configuration.getFPSSrc()); } } #location 22 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public static void setCurSrcDVDPalette(Palette pal) { currentSourceDVDPalette = pal; DvdSubtitleStream substreamDvd = null; if (inMode == InputMode.VOBSUB) { substreamDvd = subDVD; } else if (inMode == InputMode.SUPIFO) { substreamDvd = supDVD; } substreamDvd.setSrcPalette(currentSourceDVDPalette); }
#vulnerable code public static void setCurSrcDVDPalette(Palette pal) { currentSourceDVDPalette = pal; SubstreamDVD substreamDVD = null; if (inMode == InputMode.VOBSUB) { substreamDVD = subDVD; } else if (inMode == InputMode.SUPIFO) { substreamDVD = supDVD; } substreamDVD.setSrcPalette(currentSourceDVDPalette); } #location 11 #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) throws IOException, ParseException { if (args.length != 1) { System.err.println("Usage: SearchTimeUtil <indexDir>"); System.err.println("indexDir: index directory"); System.exit(1); } String[] topics = {"topics.web.1-50.txt", "topics.web.51-100.txt", "topics.web.101-150.txt", "topics.web.151-200.txt", "topics.web.201-250.txt", "topics.web.251-300.txt"}; SearchWebCollection searcher = new SearchWebCollection(args[0]); for (String topicFile : topics) { Path topicsFile = Paths.get("src/resources/topics-and-qrels/", topicFile); SortedMap<Integer, String> queries = SearchWebCollection.readWebTrackQueries(topicsFile); for (int i = 1; i <= 3; i++) { final long start = System.nanoTime(); String submissionFile = File.createTempFile(topicFile + "_" + i, ".tmp").getAbsolutePath(); searcher.search(queries, submissionFile, new BM25Similarity(0.9f, 0.4f), 1000); final long durationMillis = TimeUnit.MILLISECONDS.convert(System.nanoTime() - start, TimeUnit.NANOSECONDS); System.out.println(topicFile + "_" + i + " search completed in " + DurationFormatUtils.formatDuration(durationMillis, "mm:ss:SSS")); } } searcher.close(); }
#vulnerable code public static void main(String[] args) throws IOException, ParseException { if (args.length != 1) { System.err.println("Usage: SearchTimeUtil <indexDir>"); System.err.println("indexDir: index directory"); System.exit(1); } String[] topics = {"topics.web.1-50.txt", "topics.web.51-100.txt", "topics.web.101-150.txt", "topics.web.151-200.txt", "topics.web.201-250.txt", "topics.web.251-300.txt"}; SearchClueWeb09b searcher = new SearchClueWeb09b(args[0]); for (String topicFile : topics) { Path topicsFile = Paths.get("src/resources/topics-and-qrels/", topicFile); SortedMap<Integer, String> queries = SearchClueWeb09b.readWebTrackQueries(topicsFile); for (int i = 1; i <= 3; i++) { final long start = System.nanoTime(); String submissionFile = File.createTempFile(topicFile + "_" + i, ".tmp").getAbsolutePath(); searcher.search(queries, submissionFile, new BM25Similarity(0.9f, 0.4f), 1000); final long durationMillis = TimeUnit.MILLISECONDS.convert(System.nanoTime() - start, TimeUnit.NANOSECONDS); System.out.println(topicFile + "_" + i + " search completed in " + DurationFormatUtils.formatDuration(durationMillis, "mm:ss:SSS")); } } searcher.close(); } #location 7 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public static void main(String[] args) throws Exception { long curTime = System.nanoTime(); SearchArgs searchArgs = new SearchArgs(); CmdLineParser parser = new CmdLineParser(searchArgs, ParserProperties.defaults().withUsageWidth(90)); try { parser.parseArgument(args); } catch (CmdLineException e) { System.err.println(e.getMessage()); parser.printUsage(System.err); System.err.println("Example: SearchGov2" + parser.printExample(OptionHandlerFilter.REQUIRED)); return; } Path topicsFile = Paths.get(searchArgs.topics); LOG.info("Reading index at " + searchArgs.index); Directory dir; if (searchArgs.inmem) { LOG.info("Using MMapDirectory with preload"); dir = new MMapDirectory(Paths.get(searchArgs.index)); ((MMapDirectory) dir).setPreload(true); } else { LOG.info("Using default FSDirectory"); dir = FSDirectory.open(Paths.get(searchArgs.index)); } IndexReader reader = DirectoryReader.open(dir); IndexSearcher searcher = new IndexSearcher(reader); if (searchArgs.ql) { LOG.info("Using QL scoring model"); searcher.setSimilarity(new LMDirichletSimilarity(2500.0f)); } else if (searchArgs.rm3) { LOG.info("Using RM3 query expansion"); searcher.setSimilarity(new BM25Similarity(0.9f, 0.4f)); } else if (searchArgs.bm25) { LOG.info("Using BM25 scoring model"); searcher.setSimilarity(new BM25Similarity(0.9f, 0.4f)); } else { LOG.error("Error: Must specify scoring model!"); System.exit(-1); } int maxResults = 1000; TrecTopicsReader qReader = new TrecTopicsReader(); QualityQuery qqs[] = qReader.readQueries(Files.newBufferedReader(topicsFile, StandardCharsets.UTF_8)); PrintStream out = new PrintStream(new FileOutputStream(new File(searchArgs.output))); LOG.info("Writing output to " + searchArgs.output); LOG.info("Initialized complete! (elapsed time = " + (System.nanoTime()-curTime)/1000000 + "ms)"); long totalTime = 0; for (QualityQuery qq : qqs) { long curQueryTime = System.nanoTime(); Query query = AnalyzerUtils.buildBagOfWordsQuery("body", new EnglishAnalyzer(), qq.getValue("title")); TopDocs rs = searcher.search(query, maxResults); RerankerContext context = new RerankerContext(searcher, query, qq.getValue("title"), null); RerankerCascade cascade = new RerankerCascade(context); if (searchArgs.rm3) { cascade.add(new Rm3Reranker(new EnglishAnalyzer(), "body")); } else { cascade.add(new IdentityReranker()); } ScoredDocuments docs = cascade.run(ScoredDocuments.fromTopDocs(rs, searcher)); for (int i=0; i<docs.documents.length; i++) { String qid = qq.getQueryID(); out.println(String.format("%s Q0 %s %d %f %s", qid, docs.documents[i].getField("docid").stringValue(), (i+1), docs.scores[i], "Lucene")); } long qtime = (System.nanoTime()-curQueryTime)/1000000; LOG.info("Query " + qq.getQueryID() + " (elapsed time = " + qtime + "ms)"); totalTime += qtime; } LOG.info("All queries completed!"); LOG.info("Total elapsed time = " + totalTime + "ms"); LOG.info("Average query latency = " + (totalTime/qqs.length) + "ms"); reader.close(); dir.close(); out.close(); }
#vulnerable code public static void main(String[] args) throws Exception { if (args.length < 4 || args.length > 5) { System.err.println("Usage: QueryDriver <topicsFile> <qrelsFile> <submissionFile> <indexDir> [querySpec]"); System.err.println("topicsFile: input file containing queries"); System.err.println("qrelsFile: input file containing relevance judgements"); System.err.println("submissionFile: output submission file for trec_eval"); System.err.println("indexDir: index directory"); System.err.println("querySpec: string composed of fields to use in query consisting of T=title,D=description,N=narrative:"); System.err.println("\texample: TD (query on Title + Description). The default is T (title only)"); System.exit(1); } Path topicsFile = Paths.get(args[0]); Path qrelsFile = Paths.get(args[1]); Path submissionFile = Paths.get(args[2]); SubmissionReport submitLog = new SubmissionReport(new PrintWriter(Files.newBufferedWriter(submissionFile, StandardCharsets.UTF_8)), "lucene"); MMapDirectory dir = new MMapDirectory(Paths.get(args[3])); dir.setPreload(true); String fieldSpec = args.length == 5 ? args[4] : "T"; // default to Title-only if not specified. IndexReader reader = DirectoryReader.open(dir); IndexSearcher searcher = new IndexSearcher(reader); searcher.setSimilarity(new BM25Similarity(0.9f, 0.4f)); //searcher.setSimilarity(new LMDirichletSimilarity(2500.0f)); int maxResults = 1000; String docNameField = "docid"; PrintWriter logger = new PrintWriter(new OutputStreamWriter(System.out, Charset.defaultCharset()), true); // use trec utilities to read trec topics into quality queries TrecTopicsReader qReader = new TrecTopicsReader(); QualityQuery qqs[] = qReader.readQueries(Files.newBufferedReader(topicsFile, StandardCharsets.UTF_8)); // prepare judge, with trec utilities that read from a QRels file //Judge judge = new TrecJudge(Files.newBufferedReader(qrelsFile, StandardCharsets.UTF_8)); // validate topics & judgments match each other //judge.validateData(qqs, logger); Set<String> fieldSet = new HashSet<>(); if (fieldSpec.indexOf('T') >= 0) fieldSet.add("title"); if (fieldSpec.indexOf('D') >= 0) fieldSet.add("description"); if (fieldSpec.indexOf('N') >= 0) fieldSet.add("narrative"); // set the parsing of quality queries into Lucene queries. QualityQueryParser qqParser = new EnglishQQParser(fieldSet.toArray(new String[0]), "body"); PrintStream out = new PrintStream(System.out, true, "UTF-8"); for (QualityQuery qq : qqs) { //System.out.println(qq.getValue("title")); Query query = AnalyzerUtils.buildBagOfWordsQuery("body", new EnglishAnalyzer(), qq.getValue("title")); //System.out.println(query); TopDocs rs = searcher.search(query, maxResults); RerankerContext context = new RerankerContext(searcher, query, qq.getValue("title"), null); RerankerCascade cascade = new RerankerCascade(context); cascade.add(new Rm3Reranker(new EnglishAnalyzer(), "body")); ScoredDocuments docs = cascade.run(ScoredDocuments.fromTopDocs(rs, searcher)); for (int i=0; i<docs.documents.length; i++) { String qid = qq.getQueryID(); out.println(String.format("%s Q0 %s %d %f %s", qid, docs.documents[i].getField("docid").stringValue(), (i+1), docs.scores[i], "Lucene")); } } // // run the benchmark // QualityBenchmark qrun = new QualityBenchmark(qqs, qqParser, searcher, docNameField); // qrun.setMaxResults(maxResults); // QualityStats stats[] = qrun.execute(judge, submitLog, logger); // // // print an avarage sum of the results // QualityStats avg = QualityStats.average(stats); // avg.log("SUMMARY", 2, logger, " "); reader.close(); dir.close(); out.close(); } #location 30 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public static void main(String[] args) throws IOException, ParseException { long curTime = System.nanoTime(); SearchArgs searchArgs = new SearchArgs(); CmdLineParser parser = new CmdLineParser(searchArgs, ParserProperties.defaults().withUsageWidth(90)); try { parser.parseArgument(args); } catch (CmdLineException e) { System.err.println(e.getMessage()); parser.printUsage(System.err); System.err.println("Example: SearchGov2" + parser.printExample(OptionHandlerFilter.REQUIRED)); return; } LOG.info("Reading index at " + searchArgs.index); Directory dir; if (searchArgs.inmem) { LOG.info("Using MMapDirectory with preload"); dir = new MMapDirectory(Paths.get(searchArgs.index)); ((MMapDirectory) dir).setPreload(true); } else { LOG.info("Using default FSDirectory"); dir = FSDirectory.open(Paths.get(searchArgs.index)); } Similarity similarity = null; if (searchArgs.ql) { LOG.info("Using QL scoring model"); similarity = new LMDirichletSimilarity(searchArgs.mu); } else if (searchArgs.bm25) { LOG.info("Using BM25 scoring model"); similarity = new BM25Similarity(searchArgs.k1, searchArgs.b); } else { LOG.error("Error: Must specify scoring model!"); System.exit(-1); } RerankerCascade cascade = new RerankerCascade(); if (searchArgs.rm3) { cascade.add(new Rm3Reranker(new EnglishAnalyzer(), "body", "src/main/resources/io/anserini/rerank/rm3/rm3-stoplist.gov2.txt")); } else { cascade.add(new IdentityReranker()); } Path topicsFile = Paths.get(searchArgs.topics); if (!Files.exists(topicsFile) || !Files.isRegularFile(topicsFile) || !Files.isReadable(topicsFile)) { throw new IllegalArgumentException("Topics file : " + topicsFile + " does not exist or is not a (readable) file."); } SortedMap<Integer, String> topics = io.anserini.document.Collection.GOV2.equals(searchArgs.collection) ? readTeraByteTackQueries(topicsFile) : readWebTrackQueries(topicsFile); SearchClueWeb09b searcher = new SearchClueWeb09b(searchArgs.index); searcher.search(topics, searchArgs.output, similarity); searcher.close(); }
#vulnerable code public static void main(String[] args) throws IOException, ParseException { if (args.length != 3) { System.err.println("Usage: SearcherCW09B <topicsFile> <submissionFile> <indexDir>"); System.err.println("topicsFile: input file containing queries. One of: topics.web.1-50.txt topics.web.51-100.txt topics.web.101-150.txt topics.web.151-200.txt"); System.err.println("submissionFile: redirect stdout to capture the submission file for trec_eval or gdeval.pl"); System.err.println("indexDir: index directory"); System.exit(1); } String topicsFile = args[0]; String submissionFile = args[1]; String indexDir = args[2]; SearchClueWeb09b searcher = new SearchClueWeb09b(indexDir); searcher.search(topicsFile, submissionFile, QueryParser.Operator.OR); searcher.close(); } #location 9 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Test(expected = NoSuchElementException.class) public void test1() throws Exception { Freebase freebase = new Freebase(Paths.get("src/test/resources/freebase-rdf-head100.gz")); FreebaseNode node; Iterator<FreebaseNode> iter = freebase.iterator(); assertTrue(iter.hasNext()); node = iter.next(); assertEquals("<http://rdf.freebase.com/ns/american_football.football_player.footballdb_id>", node.uri()); assertEquals(9, node.getPredicateValues().size()); assertEquals("fb:american_football.football_player.footballdb_id", FreebaseNode.cleanUri("fb:american_football.football_player.footballdb_id")); assertEquals("fb:type.object.name", FreebaseNode.cleanUri(node.getPredicateValues().keySet().iterator().next())); assertTrue(iter.hasNext()); node = iter.next(); assertEquals("<http://rdf.freebase.com/ns/astronomy.astronomical_observatory.discoveries>", node.uri()); assertEquals(9, node.getPredicateValues().size()); assertTrue(iter.hasNext()); node = iter.next(); assertEquals("<http://rdf.freebase.com/ns/automotive.body_style.fuel_tank_capacity>", node.uri()); assertEquals(9, node.getPredicateValues().size()); assertTrue(iter.hasNext()); node = iter.next(); assertEquals("<http://rdf.freebase.com/ns/automotive.engine.engine_type>", node.uri()); assertEquals(10, node.getPredicateValues().size()); assertTrue(iter.hasNext()); node = iter.next(); assertEquals("<http://rdf.freebase.com/ns/automotive.trim_level.max_passengers>", node.uri()); assertEquals(9, node.getPredicateValues().size()); assertTrue(iter.hasNext()); node = iter.next(); assertEquals("<http://rdf.freebase.com/ns/aviation.aircraft.first_flight>", node.uri()); assertEquals(9, node.getPredicateValues().size()); assertTrue(iter.hasNext()); node = iter.next(); assertEquals("<http://rdf.freebase.com/ns/award.award_winner>", node.uri()); Map<String, List<String>> map = node.getPredicateValues(); assertEquals(1, node.getPredicateValues().size()); assertEquals(45, map.get("<http://rdf.freebase.com/ns/type.type.instance>").size()); assertFalse(iter.hasNext()); iter.next(); }
#vulnerable code @Test(expected = NoSuchElementException.class) public void test1() throws Exception { Freebase freebase = new Freebase(Paths.get("src/test/resources/freebase-rdf-head100.gz")); FreebaseNode node; Iterator<FreebaseNode> iter = freebase.iterator(); assertTrue(iter.hasNext()); node = iter.next(); assertEquals("<http://rdf.freebase.com/ns/american_football.football_player.footballdb_id>", node.uri()); assertEquals(9, node.getPredicateValues().size()); assertTrue(iter.hasNext()); node = iter.next(); assertEquals("<http://rdf.freebase.com/ns/astronomy.astronomical_observatory.discoveries>", node.uri()); assertEquals(9, node.getPredicateValues().size()); assertTrue(iter.hasNext()); node = iter.next(); assertEquals("<http://rdf.freebase.com/ns/automotive.body_style.fuel_tank_capacity>", node.uri()); assertEquals(9, node.getPredicateValues().size()); assertTrue(iter.hasNext()); node = iter.next(); assertEquals("<http://rdf.freebase.com/ns/automotive.engine.engine_type>", node.uri()); assertEquals(10, node.getPredicateValues().size()); assertTrue(iter.hasNext()); node = iter.next(); assertEquals("<http://rdf.freebase.com/ns/automotive.trim_level.max_passengers>", node.uri()); assertEquals(9, node.getPredicateValues().size()); assertTrue(iter.hasNext()); node = iter.next(); assertEquals("<http://rdf.freebase.com/ns/aviation.aircraft.first_flight>", node.uri()); assertEquals(9, node.getPredicateValues().size()); assertTrue(iter.hasNext()); node = iter.next(); assertEquals("<http://rdf.freebase.com/ns/award.award_winner>", node.uri()); Map<String, List<String>> map = node.getPredicateValues(); assertEquals(1, node.getPredicateValues().size()); assertEquals(45, map.get("<http://rdf.freebase.com/ns/type.type.instance>").size()); assertFalse(iter.hasNext()); iter.next(); } #location 45 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public static void main(String[] args) throws Exception { Args searchArgs = new Args(); CmdLineParser parser = new CmdLineParser(searchArgs, ParserProperties.defaults().withUsageWidth(90)); try { parser.parseArgument(args); } catch (CmdLineException e) { System.err.println(e.getMessage()); parser.printUsage(System.err); System.err.println("Example: "+ LookupNode.class.getSimpleName() + parser.printExample(OptionHandlerFilter.REQUIRED)); return; } LookupNode lookup = new LookupNode(searchArgs.index); lookup.search(searchArgs.subject); lookup.close(); }
#vulnerable code public static void main(String[] args) throws Exception { Args searchArgs = new Args(); // Parse args CmdLineParser parser = new CmdLineParser(searchArgs, ParserProperties.defaults().withUsageWidth(90)); try { parser.parseArgument(args); } catch (CmdLineException e) { System.err.println(e.getMessage()); parser.printUsage(System.err); System.err.println("Example command: "+ LookupNode.class.getSimpleName() + parser.printExample(OptionHandlerFilter.REQUIRED)); return; } new LookupNode(searchArgs.index).search(searchArgs.subject, searchArgs.predicate); } #location 18 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public static void main(String[] args) throws Exception { long curTime = System.nanoTime(); SearchArgs searchArgs = new SearchArgs(); CmdLineParser parser = new CmdLineParser(searchArgs, ParserProperties.defaults().withUsageWidth(90)); try { parser.parseArgument(args); } catch (CmdLineException e) { System.err.println(e.getMessage()); parser.printUsage(System.err); System.err.println("Example: SearchGov2" + parser.printExample(OptionHandlerFilter.REQUIRED)); return; } Path topicsFile = Paths.get(searchArgs.topics); LOG.info("Reading index at " + searchArgs.index); Directory dir; if (searchArgs.inmem) { LOG.info("Using MMapDirectory with preload"); dir = new MMapDirectory(Paths.get(searchArgs.index)); ((MMapDirectory) dir).setPreload(true); } else { LOG.info("Using default FSDirectory"); dir = FSDirectory.open(Paths.get(searchArgs.index)); } IndexReader reader = DirectoryReader.open(dir); IndexSearcher searcher = new IndexSearcher(reader); if (searchArgs.ql) { LOG.info("Using QL scoring model"); searcher.setSimilarity(new LMDirichletSimilarity(2500.0f)); } else if (searchArgs.rm3) { LOG.info("Using RM3 query expansion"); searcher.setSimilarity(new BM25Similarity(0.9f, 0.4f)); } else if (searchArgs.bm25) { LOG.info("Using BM25 scoring model"); searcher.setSimilarity(new BM25Similarity(0.9f, 0.4f)); } else { LOG.error("Error: Must specify scoring model!"); System.exit(-1); } int maxResults = 1000; TrecTopicsReader qReader = new TrecTopicsReader(); QualityQuery qqs[] = qReader.readQueries(Files.newBufferedReader(topicsFile, StandardCharsets.UTF_8)); PrintStream out = new PrintStream(new FileOutputStream(new File(searchArgs.output))); LOG.info("Writing output to " + searchArgs.output); LOG.info("Initialized complete! (elapsed time = " + (System.nanoTime()-curTime)/1000000 + "ms)"); long totalTime = 0; for (QualityQuery qq : qqs) { long curQueryTime = System.nanoTime(); Query query = AnalyzerUtils.buildBagOfWordsQuery("body", new EnglishAnalyzer(), qq.getValue("title")); TopDocs rs = searcher.search(query, maxResults); RerankerContext context = new RerankerContext(searcher, query, qq.getValue("title"), null); RerankerCascade cascade = new RerankerCascade(context); if (searchArgs.rm3) { cascade.add(new Rm3Reranker(new EnglishAnalyzer(), "body")); } else { cascade.add(new IdentityReranker()); } ScoredDocuments docs = cascade.run(ScoredDocuments.fromTopDocs(rs, searcher)); for (int i=0; i<docs.documents.length; i++) { String qid = qq.getQueryID(); out.println(String.format("%s Q0 %s %d %f %s", qid, docs.documents[i].getField("docid").stringValue(), (i+1), docs.scores[i], "Lucene")); } long qtime = (System.nanoTime()-curQueryTime)/1000000; LOG.info("Query " + qq.getQueryID() + " (elapsed time = " + qtime + "ms)"); totalTime += qtime; } LOG.info("All queries completed!"); LOG.info("Total elapsed time = " + totalTime + "ms"); LOG.info("Average query latency = " + (totalTime/qqs.length) + "ms"); reader.close(); dir.close(); out.close(); }
#vulnerable code public static void main(String[] args) throws Exception { if (args.length < 4 || args.length > 5) { System.err.println("Usage: QueryDriver <topicsFile> <qrelsFile> <submissionFile> <indexDir> [querySpec]"); System.err.println("topicsFile: input file containing queries"); System.err.println("qrelsFile: input file containing relevance judgements"); System.err.println("submissionFile: output submission file for trec_eval"); System.err.println("indexDir: index directory"); System.err.println("querySpec: string composed of fields to use in query consisting of T=title,D=description,N=narrative:"); System.err.println("\texample: TD (query on Title + Description). The default is T (title only)"); System.exit(1); } Path topicsFile = Paths.get(args[0]); Path qrelsFile = Paths.get(args[1]); Path submissionFile = Paths.get(args[2]); SubmissionReport submitLog = new SubmissionReport(new PrintWriter(Files.newBufferedWriter(submissionFile, StandardCharsets.UTF_8)), "lucene"); MMapDirectory dir = new MMapDirectory(Paths.get(args[3])); dir.setPreload(true); String fieldSpec = args.length == 5 ? args[4] : "T"; // default to Title-only if not specified. IndexReader reader = DirectoryReader.open(dir); IndexSearcher searcher = new IndexSearcher(reader); searcher.setSimilarity(new BM25Similarity(0.9f, 0.4f)); //searcher.setSimilarity(new LMDirichletSimilarity(2500.0f)); int maxResults = 1000; String docNameField = "docid"; PrintWriter logger = new PrintWriter(new OutputStreamWriter(System.out, Charset.defaultCharset()), true); // use trec utilities to read trec topics into quality queries TrecTopicsReader qReader = new TrecTopicsReader(); QualityQuery qqs[] = qReader.readQueries(Files.newBufferedReader(topicsFile, StandardCharsets.UTF_8)); // prepare judge, with trec utilities that read from a QRels file //Judge judge = new TrecJudge(Files.newBufferedReader(qrelsFile, StandardCharsets.UTF_8)); // validate topics & judgments match each other //judge.validateData(qqs, logger); Set<String> fieldSet = new HashSet<>(); if (fieldSpec.indexOf('T') >= 0) fieldSet.add("title"); if (fieldSpec.indexOf('D') >= 0) fieldSet.add("description"); if (fieldSpec.indexOf('N') >= 0) fieldSet.add("narrative"); // set the parsing of quality queries into Lucene queries. QualityQueryParser qqParser = new EnglishQQParser(fieldSet.toArray(new String[0]), "body"); PrintStream out = new PrintStream(System.out, true, "UTF-8"); for (QualityQuery qq : qqs) { //System.out.println(qq.getValue("title")); Query query = AnalyzerUtils.buildBagOfWordsQuery("body", new EnglishAnalyzer(), qq.getValue("title")); //System.out.println(query); TopDocs rs = searcher.search(query, maxResults); RerankerContext context = new RerankerContext(searcher, query, qq.getValue("title"), null); RerankerCascade cascade = new RerankerCascade(context); cascade.add(new Rm3Reranker(new EnglishAnalyzer(), "body")); ScoredDocuments docs = cascade.run(ScoredDocuments.fromTopDocs(rs, searcher)); for (int i=0; i<docs.documents.length; i++) { String qid = qq.getQueryID(); out.println(String.format("%s Q0 %s %d %f %s", qid, docs.documents[i].getField("docid").stringValue(), (i+1), docs.scores[i], "Lucene")); } } // // run the benchmark // QualityBenchmark qrun = new QualityBenchmark(qqs, qqParser, searcher, docNameField); // qrun.setMaxResults(maxResults); // QualityStats stats[] = qrun.execute(judge, submitLog, logger); // // // print an avarage sum of the results // QualityStats avg = QualityStats.average(stats); // avg.log("SUMMARY", 2, logger, " "); reader.close(); dir.close(); out.close(); } #location 55 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code private OMElement efetuaConsulta(final OMElement omElementConsulta, final NotaFiscalChaveParser notaFiscalChaveParser) throws AxisFault, RemoteException { final NfeConsulta2Stub.NfeCabecMsg cabec = new NfeConsulta2Stub.NfeCabecMsg(); cabec.setCUF(notaFiscalChaveParser.getNFUnidadeFederativa().getCodigoIbge()); cabec.setVersaoDados("2.01"); final NfeConsulta2Stub.NfeCabecMsgE cabecE = new NfeConsulta2Stub.NfeCabecMsgE(); cabecE.setNfeCabecMsg(cabec); final NfeConsulta2Stub.NfeDadosMsg dados = new NfeConsulta2Stub.NfeDadosMsg(); dados.setExtraElement(omElementConsulta); final NfeConsultaNF2Result consultaNF2Result = new NfeConsulta2Stub(NFAutorizador.valueOfCodigoUF(notaFiscalChaveParser.getNFUnidadeFederativa()).getNfeConsultaProtocolo(this.config.getAmbiente())).nfeConsultaNF2(dados, cabecE); return consultaNF2Result.getExtraElement(); }
#vulnerable code private OMElement efetuaConsulta(final OMElement omElementConsulta, final NotaFiscalChaveParser notaFiscalChaveParser) throws AxisFault, RemoteException { final NfeConsulta2Stub.NfeCabecMsg cabec = new NfeConsulta2Stub.NfeCabecMsg(); cabec.setCUF(notaFiscalChaveParser.getNFUnidadeFederativa().getCodigoIbge()); cabec.setVersaoDados("2.01"); final NfeConsulta2Stub.NfeCabecMsgE cabecE = new NfeConsulta2Stub.NfeCabecMsgE(); cabecE.setNfeCabecMsg(cabec); final NfeConsulta2Stub.NfeDadosMsg dados = new NfeConsulta2Stub.NfeDadosMsg(); dados.setExtraElement(omElementConsulta); final NfeConsultaNF2Result consultaNF2Result = new NfeConsulta2Stub(NFAutorizador.valueOfCodigoUF(this.config.getCUF()).getNfeConsultaProtocolo(this.config.getAmbiente())).nfeConsultaNF2(dados, cabecE); return consultaNF2Result.getExtraElement(); } #location 11 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @EventHandler public void onExplode(EntityExplodeEvent event) { List<Block> destroyed = event.blockList(); Location loc = event.getLocation(); Settings s = Settings.getInstance(); List<Location> sphere = SpaceUtils.sphere(loc, s.explodeRadius, s.explodeRadius, false, true, 0); Map<Material, Double> materials = s.explodeMaterials; if (RegionUtils.isIn(loc)) { Region region = RegionUtils.getAt(loc); Guild guild = region.getGuild(); if (guild.isValid()) { event.setCancelled(true); return; } Location protect = region.getCenter().getBlock().getRelative(BlockFace.DOWN).getLocation(); destroyed.removeIf(block -> block.getLocation().equals(protect)); guild.setBuild(System.currentTimeMillis() + Settings.getInstance().regionExplode * 1000L); for (User user : guild.getMembers()) { Player player = this.plugin.getServer().getPlayer(user.getName()); if (player != null) { player.sendMessage(Messages.getInstance().getMessage("regionExplode") .replace("{TIME}", Integer.toString(Settings.getInstance().regionExplode))); } } } for (Location l : sphere) { Material material = l.getBlock().getType(); if (!materials.containsKey(material)) { continue; } if (material == Material.WATER || material == Material.LAVA) { if (RandomizationUtils.chance(materials.get(material))) { l.getBlock().setType(Material.AIR); } } else { if (RandomizationUtils.chance(materials.get(material))) { l.getBlock().breakNaturally(); } } } }
#vulnerable code @EventHandler public void onExplode(EntityExplodeEvent event) { List<Block> destroyed = event.blockList(); Location loc = event.getLocation(); Settings s = Settings.getInstance(); List<Location> sphere = SpaceUtils.sphere(loc, s.explodeRadius, s.explodeRadius, false, true, 0); Map<Material, Double> materials = s.explodeMaterials; for (Location l : sphere) { Material material = l.getBlock().getType(); if (!materials.containsKey(material)) { continue; } if (material == Material.WATER || material == Material.LAVA) { if (RandomizationUtils.chance(materials.get(material))) { l.getBlock().setType(Material.AIR); } } else { if (RandomizationUtils.chance(materials.get(material))) { l.getBlock().breakNaturally(); } } } if (!RegionUtils.isIn(loc)) { return; } Region region = RegionUtils.getAt(loc); Location protect = region.getCenter().getBlock().getRelative(BlockFace.DOWN).getLocation(); Iterator<Block> it = destroyed.iterator(); while (it.hasNext()) { if (it.next().getLocation().equals(protect)) { it.remove(); } } Guild guild = region.getGuild(); guild.setBuild(System.currentTimeMillis() + Settings.getInstance().regionExplode * 1000L); for (User user : guild.getMembers()) { Player player = this.plugin.getServer().getPlayer(user.getName()); if (player != null) { player.sendMessage(Messages.getInstance().getMessage("regionExplode") .replace("{TIME}", Integer.toString(Settings.getInstance().regionExplode))); } } } #location 31 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public static IndependentThread getInstance() { if (instance == null) { new IndependentThread().start(); } return instance; }
#vulnerable code public static IndependentThread getInstance() { if (instance == null) { new IndependentThread().start(); } return instance; } #location 3 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Override public void execute(CommandSender sender, String[] args) { MessagesConfig messages = Messages.getInstance(); PluginConfig config = Settings.getConfig(); if (args.length < 1) { sender.sendMessage(messages.generalNoTagGiven); return; } else if (args.length < 2) { sender.sendMessage(messages.adminNoValidityTimeGiven); return; } Guild guild = GuildUtils.byTag(args[0]); if (guild == null) { sender.sendMessage(messages.generalNoGuildFound); return; } if (guild.isBanned()) { sender.sendMessage(messages.adminGuildBanned); return; } long time = Parser.parseTime(args[1]); if (time < 1) { sender.sendMessage(messages.adminTimeError); return; } long validity = guild.getValidity(); if (validity == 0) { validity = System.currentTimeMillis(); } validity += time; guild.setValidity(validity); String date = config.dateFormat.format(new Date(validity)); sender.sendMessage(messages.adminNewValidity.replace("{GUILD}", guild.getName()).replace("{VALIDITY}", date)); }
#vulnerable code @Override public void execute(CommandSender sender, String[] args) { MessagesConfig messages = Messages.getInstance(); if (args.length < 1) { sender.sendMessage(messages.generalNoTagGiven); return; } else if (args.length < 2) { sender.sendMessage(messages.adminNoValidityTimeGiven); return; } if (!GuildUtils.tagExists(args[0])) { sender.sendMessage(messages.generalNoGuildFound); return; } Guild guild = GuildUtils.byTag(args[0]); if (guild.isBanned()) { sender.sendMessage(messages.adminGuildBanned); return; } long time = Parser.parseTime(args[1]); if (time < 1) { sender.sendMessage(messages.adminTimeError); return; } long validity = guild.getValidity(); if (validity == 0) { validity = System.currentTimeMillis(); } validity += time; guild.setValidity(validity); sender.sendMessage(messages.adminNewValidity.replace("{GUILD}", guild.getName()).replace("{VALIDITY}", Settings.getConfig().dateFormat.format(new Date(validity)))); } #location 19 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Override public void execute(CommandSender sender, String[] args) { MessagesConfig messages = Messages.getInstance(); if (args.length < 1) { sender.sendMessage(messages.generalNoTagGiven); return; } Guild guild = GuildUtils.byTag(args[0]); if (guild == null) { sender.sendMessage(messages.generalNoGuildFound); return; } if (!guild.isBanned()) { sender.sendMessage(messages.adminGuildNotBanned); return; } BanUtils.unban(guild); MessageTranslator translator = new MessageTranslator() .register("{GUILD}", guild.getName()) .register("{TAG}", guild.getName()) .register("{ADMIN}", sender.getName()); sender.sendMessage(translator.translate(messages.adminGuildUnban)); Bukkit.broadcastMessage(translator.translate(messages.broadcastUnban)); }
#vulnerable code @Override public void execute(CommandSender sender, String[] args) { MessagesConfig messages = Messages.getInstance(); if (args.length < 1) { sender.sendMessage(messages.generalNoTagGiven); return; } if (!GuildUtils.tagExists(args[0])) { sender.sendMessage(messages.generalNoGuildFound); return; } Guild guild = GuildUtils.byTag(args[0]); if (!guild.isBanned()) { sender.sendMessage(messages.adminGuildNotBanned); return; } BanUtils.unban(guild); sender.sendMessage(messages.adminGuildUnban.replace("{GUILD}", guild.getName())); Bukkit.broadcastMessage(Messages.getInstance().broadcastUnban.replace("{GUILD}", guild.getName()).replace("{TAG}", guild.getTag())); } #location 16 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public static RankManager getInstance() { return INSTANCE; }
#vulnerable code public static RankManager getInstance() { if (instance == null) { new RankManager(); } return instance; } #location 3 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code private int[] getEloValues(int vP, int aP) { PluginConfig config = Settings.getConfig(); int[] rankChanges = new int[2]; int aC = IntegerRange.inRange(aP, config.eloConstants, "ELO_CONSTANTS"); int vC = IntegerRange.inRange(vP, config.eloConstants, "ELO_CONSTANTS"); rankChanges[0] = (int) Math.round(aC * (1 - (1.0D / (1.0D + Math.pow(config.eloExponent, (vP - aP) / config.eloDivider))))); rankChanges[1] = (int) Math.round(vC * (0 - (1.0D / (1.0D + Math.pow(config.eloExponent, (aP - vP) / config.eloDivider)))) * -1); return rankChanges; }
#vulnerable code private int[] getEloValues(int vP, int aP) { PluginConfig config = Settings.getConfig(); int[] rankChanges = new int[2]; int aC = IntegerRange.inRange(aP, config.eloConstants); int vC = IntegerRange.inRange(vP, config.eloConstants); rankChanges[0] = (int) Math.round(aC * (1 - (1.0D / (1.0D + Math.pow(config.eloExponent, (vP - aP) / config.eloDivider))))); rankChanges[1] = (int) Math.round(vC * (0 - (1.0D / (1.0D + Math.pow(config.eloExponent, (aP - vP) / config.eloDivider)))) * -1); return rankChanges; } #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 execute(CommandSender sender, String[] args) { MessagesConfig messages = Messages.getInstance(); if (args.length < 1) { sender.sendMessage(messages.generalNoTagGiven); return; } if (args.length < 2) { sender.sendMessage(messages.adminNoLivesGiven); return; } Guild guild = GuildUtils.byTag(args[0]); if (guild == null) { sender.sendMessage(messages.generalNoGuildFound); return; } int lives; try { lives = Integer.valueOf(args[1]); } catch (NumberFormatException e) { sender.sendMessage(messages.adminErrorInNumber.replace("{ERROR}", args[1])); return; } guild.setLives(lives); sender.sendMessage(messages.adminLivesChanged.replace("{GUILD}", guild.getTag()).replace("{LIVES}", Integer.toString(lives))); }
#vulnerable code @Override public void execute(CommandSender sender, String[] args) { MessagesConfig messages = Messages.getInstance(); if (args.length < 1) { sender.sendMessage(messages.generalNoTagGiven); return; } if (args.length < 2) { sender.sendMessage(messages.adminNoLivesGiven); return; } if (!GuildUtils.tagExists(args[0])) { sender.sendMessage(messages.generalNoGuildFound); return; } Guild guild = GuildUtils.byTag(args[0]); int lives; try { lives = Integer.valueOf(args[1]); } catch (NumberFormatException e) { sender.sendMessage(messages.adminErrorInNumber.replace("{ERROR}", args[1]));; return; } guild.setLives(lives); sender.sendMessage(messages.adminLivesChanged.replace("{GUILD}", guild.getTag()).replace("{LIVES}", Integer.toString(lives))); } #location 30 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public void update(User user) { if (! this.users.contains(user.getRank())) { this.users.add(user.getRank()); } Collections.sort(users); if (user.hasGuild()) { update(user.getGuild()); } for (int i = 0; i < users.size(); i++) { Rank rank = users.get(i); rank.setPosition(i + 1); } }
#vulnerable code public void update(User user) { if (!this.users.contains(user.getRank())) { this.users.add(user.getRank()); } synchronized (users) { Collections.sort(users); } if (user.hasGuild()) { update(user.getGuild()); } for (int i = 0; i < users.size(); i++) { Rank rank = users.get(i); rank.setPosition(i + 1); } } #location 16 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Override public void execute(CommandSender sender, String[] args) { PluginConfig config = Settings.getConfig(); MessagesConfig messages = Messages.getInstance(); Player player = (Player) sender; User user = User.get(player); Guild guild = user.getGuild(); if (!user.hasGuild()) { player.sendMessage(messages.validityHasNotGuild); return; } if (!user.isOwner() && !user.isDeputy()) { player.sendMessage(messages.validityIsNotOwner); return; } if (config.validityWhen != 0) { long c = guild.getValidity(); long d = c - System.currentTimeMillis(); if (d > config.validityWhen) { long when = d - config.validityWhen; player.sendMessage(messages.validityWhen.replace("{TIME}", TimeUtils.getDurationBreakdown(when))); return; } } List<ItemStack> itemsList = config.validityItems; for (ItemStack itemStack : itemsList) { if (!player.getInventory().containsAtLeast(itemStack, itemStack.getAmount())) { String msg = messages.validityItems; if (msg.contains("{ITEM}")) { StringBuilder sb = new StringBuilder(); sb.append(itemStack.getAmount()); sb.append(" "); sb.append(itemStack.getType().toString().toLowerCase()); msg = msg.replace("{ITEM}", sb.toString()); } if (msg.contains("{ITEMS}")) { ArrayList<String> list = new ArrayList<String>(); for (ItemStack it : itemsList) { StringBuilder sb = new StringBuilder(); sb.append(it.getAmount()); sb.append(" "); sb.append(it.getType().toString().toLowerCase()); list.add(sb.toString()); } msg = msg.replace("{ITEMS}", StringUtils.toString(list, true)); } player.sendMessage(msg); return; } player.getInventory().removeItem(itemStack); } long c = guild.getValidity(); if (c == 0) { c = System.currentTimeMillis(); } c += config.validityTime; guild.setValidity(c); player.sendMessage(messages.validityDone.replace("{DATE}", config.dateFormat.format(new Date(c)))); }
#vulnerable code @Override public void execute(CommandSender sender, String[] args) { PluginConfig pc = Settings.getConfig(); MessagesConfig m = Messages.getInstance(); Player p = (Player) sender; User user = User.get(p); Guild guild = user.getGuild(); if (!user.hasGuild()) { p.sendMessage(m.validityHasNotGuild); return; } if (!user.isOwner() && !user.isDeputy()) { p.sendMessage(m.validityIsNotOwner); return; } if (pc.validityWhen != 0) { long c = guild.getValidity(); long d = c - System.currentTimeMillis(); if (d > pc.validityWhen) { long when = d - pc.validityWhen; p.sendMessage(m.validityWhen.replace("{TIME}", TimeUtils.getDurationBreakdown(when))); return; } } List<ItemStack> itemsList = pc.validityItems; for (ItemStack itemStack : itemsList) { if (!p.getInventory().containsAtLeast(itemStack, itemStack.getAmount())) { String msg = m.validityItems; if (msg.contains("{ITEM}")) { StringBuilder sb = new StringBuilder(); sb.append(itemStack.getAmount()); sb.append(" "); sb.append(itemStack.getType().toString().toLowerCase()); msg = msg.replace("{ITEM}", sb.toString()); } if (msg.contains("{ITEMS}")) { ArrayList<String> list = new ArrayList<String>(); for (ItemStack it : itemsList) { StringBuilder sb = new StringBuilder(); sb.append(it.getAmount()); sb.append(" "); sb.append(it.getType().toString().toLowerCase()); list.add(sb.toString()); } msg = msg.replace("{ITEMS}", StringUtils.toString(list, true)); } p.sendMessage(msg); return; } p.getInventory().removeItem(itemStack); } long c = guild.getValidity(); if (c == 0) { c = System.currentTimeMillis(); } c += pc.validityTime; guild.setValidity(c); p.sendMessage(m.validityDone.replace("{DATE}", pc.dateFormat.format(new Date(c)))); } #location 10 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Override public void execute(CommandSender sender, String[] args) { MessagesConfig messages = Messages.getInstance(); if (args.length < 1) { sender.sendMessage(messages.generalNoTagGiven); return; } else if (args.length < 2) { sender.sendMessage(messages.adminNoNewNameGiven); return; } Guild guild = GuildUtils.byTag(args[0]); if (guild == null) { sender.sendMessage(messages.generalNoGuildFound); return; } if (GuildUtils.nameExists(args[1])) { sender.sendMessage(messages.createNameExists); return; } Manager.getInstance().stop(); PluginConfig.DataType dataType = Settings.getConfig().dataType; Region region = RegionUtils.get(guild.getRegion()); if (dataType.flat) { Flat.getGuildFile(guild).delete(); Flat.getRegionFile(region).delete(); } if (dataType.mysql) { new DatabaseGuild(guild).delete(); new DatabaseRegion(region).delete(); } guild.setName(args[1]); region.setName(args[1]); Manager.getInstance().start(); sender.sendMessage(messages.adminNameChanged.replace("{GUILD}", guild.getName())); }
#vulnerable code @Override public void execute(CommandSender sender, String[] args) { MessagesConfig messages = Messages.getInstance(); if (args.length < 1) { sender.sendMessage(messages.generalNoTagGiven); return; } else if (args.length < 2) { sender.sendMessage(messages.adminNoNewNameGiven); return; } if (!GuildUtils.tagExists(args[0])) { sender.sendMessage(messages.generalNoGuildFound); return; } if (GuildUtils.nameExists(args[1])) { sender.sendMessage(messages.createNameExists); return; } Guild guild = GuildUtils.byTag(args[0]); Region region = RegionUtils.get(guild.getRegion()); PluginConfig.DataType dataType = Settings.getConfig().dataType; Manager.getInstance().stop(); if (dataType.flat) { Flat.getGuildFile(guild).delete(); Flat.getRegionFile(region).delete(); } if (dataType.mysql) { new DatabaseGuild(guild).delete(); new DatabaseRegion(region).delete(); } guild.setName(args[1]); region.setName(args[1]); Manager.getInstance().start(); sender.sendMessage(messages.adminNameChanged.replace("{GUILD}", guild.getName())); } #location 24 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Override public void execute(CommandSender sender, String[] args) { MessagesConfig messages = Messages.getInstance(); if (args.length < 1) { sender.sendMessage(messages.generalNoTagGiven); return; } else if (args.length < 2) { sender.sendMessage(messages.adminNoBanTimeGiven); return; } else if (args.length < 3) { sender.sendMessage(messages.adminNoReasonGiven); return; } Guild guild = GuildUtils.get(args[0]); if (guild == null) { sender.sendMessage(messages.generalNoGuildFound); return; } if (guild.isBanned()) { sender.sendMessage(messages.adminGuildBanned); return; } long time = Parser.parseTime(args[1]); if (time < 1) { sender.sendMessage(messages.adminTimeError); return; } StringBuilder reasonBuilder = new StringBuilder(); for (int i = 2; i < args.length; i++) { reasonBuilder.append(args[i]); reasonBuilder.append(" "); } String reason = reasonBuilder.toString(); BanUtils.ban(guild, time, reason); MessageTranslator translator = new MessageTranslator() .register("{GUILD", guild.getName()) .register("{TAG}", guild.getTag()) .register("{TIME}", args[1]) .register("{REASON}", StringUtils.colored(reason)); sender.sendMessage(translator.translate(messages.adminGuildBan)); Bukkit.broadcastMessage(translator.translate(messages.broadcastBan)); }
#vulnerable code @Override public void execute(CommandSender sender, String[] args) { MessagesConfig messages = Messages.getInstance(); if (args.length < 1) { sender.sendMessage(messages.generalNoTagGiven); return; } else if (args.length < 2) { sender.sendMessage(messages.adminNoBanTimeGiven); return; } else if (args.length < 3) { sender.sendMessage(messages.adminNoReasonGiven); return; } if (!GuildUtils.tagExists(args[0])) { sender.sendMessage(messages.generalNoGuildFound); return; } Guild guild = GuildUtils.byTag(args[0]); if (guild.isBanned()) { sender.sendMessage(messages.adminGuildBanned); return; } long time = Parser.parseTime(args[1]); if (time < 1) { sender.sendMessage(messages.adminTimeError); return; } StringBuilder sb = new StringBuilder(); for (int i = 2; i < args.length; i++) { sb.append(args[i]); sb.append(" "); } String reason = sb.toString(); BanUtils.ban(guild, time, reason); sender.sendMessage(messages.adminGuildBan.replace("{GUILD}", guild.getName()).replace("{TIME}", args[1])); Bukkit.broadcastMessage(Messages.getInstance().broadcastBan.replace("{GUILD}", guild.getName()) .replace("{TAG}", guild.getTag()).replace("{REASON}", StringUtils.colored(reason)).replace("{TIME}", args[1])); } #location 22 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Override public void execute(CommandSender sender, String[] args) { MessagesConfig messages = Messages.getInstance(); Player player = (Player) sender; User user = User.get(player); if (!user.hasGuild()) { player.sendMessage(messages.kickHasNotGuild); return; } if (!user.isOwner() && !user.isDeputy()) { player.sendMessage(messages.kickIsNotOwner); return; } if (args.length < 1) { player.sendMessage(messages.kickPlayer); return; } User formerUser = User.get(args[0]); OfflineUser formerOffline = formerUser.getOfflineUser(); if (!formerUser.hasGuild()) { player.sendMessage(messages.kickToHasNotGuild); return; } if (!user.getGuild().equals(formerUser.getGuild())) { player.sendMessage(messages.kickOtherGuild); return; } if (formerUser.isOwner()) { player.sendMessage(messages.kickOwner); return; } Guild guild = user.getGuild(); IndependentThread.action(ActionType.PREFIX_GLOBAL_REMOVE_PLAYER, formerOffline); guild.removeMember(formerUser); formerUser.removeGuild(); if (formerOffline.isOnline()) { IndependentThread.action(ActionType.PREFIX_GLOBAL_UPDATE_PLAYER, player); } MessageTranslator translator = new MessageTranslator() .register("{PLAYER}", formerUser.getName()) .register("{GUILD}", guild.getName()) .register("{TAG}", guild.getTag()); player.sendMessage(translator.translate(messages.kickToOwner)); Bukkit.broadcastMessage(translator.translate(messages.broadcastKick)); Player formerPlayer = formerUser.getPlayer(); if (formerPlayer != null) { formerPlayer.sendMessage(translator.translate(messages.kickToPlayer)); } }
#vulnerable code @Override public void execute(CommandSender sender, String[] args) { MessagesConfig m = Messages.getInstance(); Player p = (Player) sender; User u = User.get(p); if (!u.hasGuild()) { p.sendMessage(m.kickHasNotGuild); return; } if (!u.isOwner() && !u.isDeputy()) { p.sendMessage(m.kickIsNotOwner); return; } if (args.length < 1) { p.sendMessage(m.kickPlayer); return; } User uk = User.get(args[0]); OfflineUser up = uk.getOfflineUser(); if (!uk.hasGuild()) { p.sendMessage(m.kickToHasNotGuild); return; } if (!u.getGuild().equals(uk.getGuild())) { p.sendMessage(m.kickOtherGuild); return; } if (uk.isOwner()) { p.sendMessage(m.kickOwner); return; } Guild guild = u.getGuild(); IndependentThread.action(ActionType.PREFIX_GLOBAL_REMOVE_PLAYER, up); guild.removeMember(uk); uk.removeGuild(); if (up.isOnline()) { IndependentThread.action(ActionType.PREFIX_GLOBAL_UPDATE_PLAYER, p); } p.sendMessage(m.kickToOwner.replace("{PLAYER}", uk.getName())); Player pk = uk.getPlayer(); if (pk != null) { pk.sendMessage(m.kickToPlayer.replace("{GUILD}", guild.getName())); } Bukkit.broadcastMessage(m.broadcastKick.replace("{PLAYER}", uk.getName()).replace("{GUILD}", guild.getName()).replace("{TAG}", guild.getTag())); } #location 8 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public void remove(Guild guild) { this.guilds.remove(guild.getRank()); Collections.sort(this.guilds); }
#vulnerable code public void remove(Guild guild) { this.guilds.remove(guild.getRank()); synchronized (guilds) { Collections.sort(this.guilds); } } #location 2 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public void update(Guild guild) { if (! this.guilds.contains(guild.getRank())) { this.guilds.add(guild.getRank()); } Collections.sort(guilds); for (int i = 0; i < guilds.size(); i++) { Rank rank = guilds.get(i); rank.setPosition(i + 1); } }
#vulnerable code public void update(Guild guild) { if (!this.guilds.contains(guild.getRank())) { this.guilds.add(guild.getRank()); } else { synchronized (guilds) { Collections.sort(guilds); } for (int i = 0; i < guilds.size(); i++) { Rank rank = guilds.get(i); rank.setPosition(i + 1); } } } #location 11 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Override public void execute(CommandSender sender, String[] args) { PluginConfig config = Settings.getConfig(); MessagesConfig messages = Messages.getInstance(); Player player = (Player) sender; User user = User.get(player); if (!config.baseEnable) { player.sendMessage(messages.baseTeleportationDisabled); return; } if (!user.hasGuild()) { player.sendMessage(messages.baseHasNotGuild); return; } Guild guild = user.getGuild(); if (user.getTeleportation() != null) { player.sendMessage(messages.baseIsTeleportation); return; } ItemStack[] items = Settings.getConfig().baseItems.toArray(new ItemStack[0]); for (ItemStack is : items) { if (!player.getInventory().containsAtLeast(is, is.getAmount())) { String msg = messages.baseItems; if (msg.contains("{ITEM}")) { StringBuilder sb = new StringBuilder(); sb.append(is.getAmount()); sb.append(" "); sb.append(is.getType().toString().toLowerCase()); msg = msg.replace("{ITEM}", sb.toString()); } if (msg.contains("{ITEMS}")) { ArrayList<String> list = new ArrayList<String>(); for (ItemStack it : items) { StringBuilder sb = new StringBuilder(); sb.append(it.getAmount()); sb.append(" "); sb.append(it.getType().toString().toLowerCase()); list.add(sb.toString()); } msg = msg.replace("{ITEMS}", StringUtils.toString(list, true)); } player.sendMessage(msg); return; } } player.getInventory().removeItem(items); int time = Settings.getConfig().baseDelay; if (time < 1) { player.teleport(guild.getHome()); player.sendMessage(messages.baseTeleport); return; } player.sendMessage(messages.baseDontMove.replace("{TIME}", Integer.toString(time))); Location before = player.getLocation(); AtomicInteger i = new AtomicInteger(1); user.setTeleportation(Bukkit.getScheduler().runTaskTimer(FunnyGuilds.getInstance(), () -> { if (!player.isOnline()) { user.getTeleportation().cancel(); user.setTeleportation(null); return; } if (!LocationUtils.equals(player.getLocation(), before)) { user.getTeleportation().cancel(); player.sendMessage(messages.baseMove); user.setTeleportation(null); player.getInventory().addItem(items); return; } if (i.getAndIncrement() > time) { user.getTeleportation().cancel(); player.sendMessage(messages.baseTeleport); player.teleport(guild.getHome()); user.setTeleportation(null); } }, 0L, 20L)); }
#vulnerable code @Override public void execute(CommandSender sender, String[] args) { PluginConfig c = Settings.getConfig(); MessagesConfig m = Messages.getInstance(); Player p = (Player) sender; User user = User.get(p); if (!c.baseEnable) { p.sendMessage(m.baseTeleportationDisabled); return; } if (!user.hasGuild()) { p.sendMessage(m.baseHasNotGuild); return; } Guild guild = user.getGuild(); if (user.getTeleportation() != null) { p.sendMessage(m.baseIsTeleportation); return; } ItemStack[] items = Settings.getConfig().baseItems.toArray(new ItemStack[0]); for (ItemStack is : items) { if (!p.getInventory().containsAtLeast(is, is.getAmount())) { String msg = m.baseItems; if (msg.contains("{ITEM}")) { StringBuilder sb = new StringBuilder(); sb.append(is.getAmount()); sb.append(" "); sb.append(is.getType().toString().toLowerCase()); msg = msg.replace("{ITEM}", sb.toString()); } if (msg.contains("{ITEMS}")) { ArrayList<String> list = new ArrayList<String>(); for (ItemStack it : items) { StringBuilder sb = new StringBuilder(); sb.append(it.getAmount()); sb.append(" "); sb.append(it.getType().toString().toLowerCase()); list.add(sb.toString()); } msg = msg.replace("{ITEMS}", StringUtils.toString(list, true)); } p.sendMessage(msg); return; } } p.getInventory().removeItem(items); int time = Settings.getConfig().baseDelay; if (time < 1) { p.teleport(guild.getHome()); p.sendMessage(m.baseTeleport); return; } p.sendMessage(m.baseDontMove.replace("{TIME}", Integer.toString(time))); Location before = p.getLocation(); AtomicInteger i = new AtomicInteger(1); user.setTeleportation(Bukkit.getScheduler().runTaskTimer(FunnyGuilds.getInstance(), () -> { if (!p.isOnline()) { user.getTeleportation().cancel(); user.setTeleportation(null); return; } if (!LocationUtils.equals(p.getLocation(), before)) { user.getTeleportation().cancel(); p.sendMessage(m.baseMove); user.setTeleportation(null); p.getInventory().addItem(items); return; } if (i.getAndIncrement() > time) { user.getTeleportation().cancel(); p.sendMessage(m.baseTeleport); p.teleport(guild.getHome()); user.setTeleportation(null); } }, 0L, 20L)); } #location 9 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public static int getPing(Player player) { int ping = 0; if (player == null) { return ping; } try { Object cp = craftPlayerClass.cast(player); Object handle = getHandleMethod.invoke(cp); ping = (int) pingField.get(handle); } catch (Exception e) { if (FunnyGuildsLogger.exception(e.getCause())) { e.printStackTrace(); } } return ping; }
#vulnerable code public static int getPing(Player player) { int ping = 0; if (player == null) { return ping; } try { Class<?> craftPlayer = Reflections.getCraftBukkitClass("entity.CraftPlayer"); Object cp = craftPlayer.cast(player); Object handle = craftPlayer.getMethod("getHandle").invoke(cp); ping = (int) handle.getClass().getField("ping").get(handle); } catch (Exception e) { if (FunnyGuildsLogger.exception(e.getCause())) { e.printStackTrace(); } } return ping; } #location 10 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public synchronized Scoreboard getScoreboard() { return this.scoreboard; }
#vulnerable code public synchronized Scoreboard getScoreboard() { if (this.scoreboard == null) { this.scoreboard = Bukkit.getScoreboardManager().getNewScoreboard(); } return this.scoreboard; } #location 3 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public static String parseRank(User source, String var) { if (! var.contains("TOP-")) { return null; } int i = getIndex(var); if (i <= 0) { FunnyGuilds.getInstance().getPluginLogger().error("Index in TOP- must be greater or equal to 1!"); return null; } PluginConfiguration config = FunnyGuilds.getInstance().getPluginConfiguration(); if (var.contains("GTOP")) { Guild guild; int positionIdx = i; do { guild = RankManager.getInstance().getGuild(positionIdx++); if (guild == null) { return StringUtils.replace(var, "{GTOP-" + i + '}', FunnyGuilds.getInstance().getMessageConfiguration().gtopNoValue); } } while (guild.getMembers().size() < config.minMembersToInclude); int points = guild.getRank().getPoints(); String pointsFormat = config.gtopPoints; if (!pointsFormat.isEmpty()) { pointsFormat = pointsFormat.replace("{POINTS-FORMAT}", IntegerRange.inRange(points, config.pointsFormat, "POINTS")); pointsFormat = pointsFormat.replace("{POINTS}", String.valueOf(points)); } String guildTag = guild.getTag(); if (config.playerListUseRelationshipColors) { guildTag = StringUtils.replace(config.prefixOther, "{TAG}", guild.getTag()); if (source != null && source.hasGuild()) { Guild sourceGuild = source.getGuild(); if (sourceGuild.getAllies().contains(guild)) { guildTag = StringUtils.replace(config.prefixAllies, "{TAG}", guild.getTag()); } else if (sourceGuild.getUUID().equals(guild.getUUID())) { guildTag = StringUtils.replace(config.prefixOur, "{TAG}", guild.getTag()); } } } return StringUtils.replace(var, "{GTOP-" + i + '}', guildTag + pointsFormat); } else if (var.contains("PTOP")) { User user = RankManager.getInstance().getUser(i); if (user == null) { return StringUtils.replace(var, "{PTOP-" + i + '}', FunnyGuilds.getInstance().getMessageConfiguration().ptopNoValue); } int points = user.getRank().getPoints(); String pointsFormat = config.ptopPoints; if (!pointsFormat.isEmpty()) { pointsFormat = pointsFormat.replace("{POINTS-FORMAT}", IntegerRange.inRange(points, config.pointsFormat, "POINTS")); pointsFormat = pointsFormat.replace("{POINTS}", String.valueOf(points)); } return StringUtils.replace(var, "{PTOP-" + i + '}', (user.isOnline() ? config.ptopOnline : config.ptopOffline) + user.getName() + pointsFormat); } return null; }
#vulnerable code public static String parseRank(User source, String var) { if (! var.contains("TOP-")) { return null; } int i = getIndex(var); if (i <= 0) { FunnyGuilds.getInstance().getPluginLogger().error("Index in TOP- must be greater or equal to 1!"); return null; } PluginConfiguration config = FunnyGuilds.getInstance().getPluginConfiguration(); if (var.contains("GTOP")) { List<Guild> rankedGuilds = new ArrayList<>(); for (int in = 1; in <= RankManager.getInstance().guilds(); in++) { Guild guild = RankManager.getInstance().getGuild(in); if (guild != null && guild.getMembers().size() >= config.minMembersToInclude) { rankedGuilds.add(guild); } } if (rankedGuilds.isEmpty() || i - 1 >= rankedGuilds.size()) { return StringUtils.replace(var, "{GTOP-" + i + '}', FunnyGuilds.getInstance().getMessageConfiguration().gtopNoValue); } else { Guild guild = rankedGuilds.get(i - 1); int points = guild.getRank().getPoints(); String pointsFormat = config.gtopPoints; if (!pointsFormat.isEmpty()) { pointsFormat = pointsFormat.replace("{POINTS-FORMAT}", IntegerRange.inRange(points, config.pointsFormat, "POINTS")); pointsFormat = pointsFormat.replace("{POINTS}", String.valueOf(points)); } String guildTag = guild.getTag(); if (config.playerListUseRelationshipColors) { guildTag = StringUtils.replace(config.prefixOther, "{TAG}", guild.getTag()); if (source != null && source.hasGuild()) { Guild sourceGuild = source.getGuild(); if (sourceGuild.getAllies().contains(guild)) { guildTag = StringUtils.replace(config.prefixAllies, "{TAG}", guild.getTag()); } else if (sourceGuild.getUUID().equals(guild.getUUID())) { guildTag = StringUtils.replace(config.prefixOur, "{TAG}", guild.getTag()); } } } return StringUtils.replace(var, "{GTOP-" + i + '}', guildTag + pointsFormat); } } else if (var.contains("PTOP")) { User user = RankManager.getInstance().getUser(i); if (user != null) { int points = user.getRank().getPoints(); String pointsFormat = config.ptopPoints; if (!pointsFormat.isEmpty()) { pointsFormat = pointsFormat.replace("{POINTS-FORMAT}", IntegerRange.inRange(points, config.pointsFormat, "POINTS")); pointsFormat = pointsFormat.replace("{POINTS}", String.valueOf(points)); } return StringUtils.replace(var, "{PTOP-" + i + '}', (user.isOnline() ? config.ptopOnline : config.ptopOffline) + user.getName() + pointsFormat); } else { return StringUtils.replace(var, "{PTOP-" + i + '}', FunnyGuilds.getInstance().getMessageConfiguration().ptopNoValue); } } return null; } #location 27 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Override public void execute(CommandSender sender, String[] args) { MessagesConfig messages = Messages.getInstance(); if (args.length < 1) { sender.sendMessage(messages.generalNoTagGiven); return; } Guild guild = GuildUtils.byTag(args[0]); if (guild == null) { sender.sendMessage(messages.generalNoGuildFound); return; } if (args.length < 2) { sender.sendMessage(messages.generalNoNickGiven); return; } if (!UserUtils.playedBefore(args[1])) { sender.sendMessage(messages.generalNotPlayedBefore); return; } User user = User.get(args[1]); if (!guild.getMembers().contains(user)) { sender.sendMessage(messages.adminUserNotMemberOf); return; } if (guild.getOwner().equals(user)) { sender.sendMessage(messages.adminAlreadyLeader); return; } Player leaderPlayer = user.getPlayer(); guild.setOwner(user); sender.sendMessage(messages.leaderSet); if (leaderPlayer != null) { leaderPlayer.sendMessage(messages.leaderOwner); } String message = messages.leaderMembers.replace("{PLAYER}", user.getName()); for (User member : guild.getOnlineMembers()) { member.getPlayer().sendMessage(message); } }
#vulnerable code @Override public void execute(CommandSender sender, String[] args) { MessagesConfig messages = Messages.getInstance(); if (args.length < 1) { sender.sendMessage(messages.generalNoTagGiven); return; } if (!GuildUtils.tagExists(args[0])) { sender.sendMessage(messages.generalNoGuildFound); return; } if (args.length < 2) { sender.sendMessage(messages.generalNoNickGiven); return; } if (!UserUtils.playedBefore(args[1])) { sender.sendMessage(messages.generalNotPlayedBefore); return; } Guild guild = GuildUtils.byTag(args[0]); User user = User.get(args[1]); if (!guild.getMembers().contains(user)) { sender.sendMessage(messages.adminUserNotMemberOf); return; } if (guild.getOwner().equals(user)) { sender.sendMessage(messages.adminAlreadyLeader); return; } Player leaderPlayer = user.getPlayer(); guild.setOwner(user); sender.sendMessage(messages.leaderSet); if (leaderPlayer != null) { leaderPlayer.sendMessage(messages.leaderOwner); } for (User member : guild.getOnlineMembers()) { member.getPlayer().sendMessage(messages.leaderMembers.replace("{PLAYER}", user.getName())); } } #location 28 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Override public void execute(CommandSender sender, String[] args) { MessagesConfig messages = Messages.getInstance(); User user = User.get((Player) sender); if (user.isSpy()) { user.setSpy(false); sender.sendMessage(messages.adminStopSpy); } else { user.setSpy(true); sender.sendMessage(messages.adminStartSpy); } }
#vulnerable code @Override public void execute(CommandSender sender, String[] args) { MessagesConfig m = Messages.getInstance(); User user = User.get((Player) sender); if (user.isSpy()) { user.setSpy(false); sender.sendMessage(m.adminStopSpy); } else { user.setSpy(true); sender.sendMessage(m.adminStartSpy); } } #location 8 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public boolean checkPlayer(Player player, SecurityType type, Object... values) { if (!Settings.getConfig().regionsEnabled) { return false; } if (isBanned(User.get(player))) { return true; } switch (type) { case FREECAM: Guild guild = null; for (Object value : values) { if (value instanceof Guild) { guild = (Guild) value; } } if (guild == null) { return false; } Region region = RegionUtils.get(guild.getRegion()); if (region == null) { return false; } int dis = (int) region.getCenter().distance(player.getLocation()); if (dis < 6) { return false; } for (Player w : Bukkit.getOnlinePlayers()) { if (w.isOp()) { w.sendMessage(SecurityUtils.getBustedMessage(player.getName(), "FreeCam")); w.sendMessage(SecurityUtils.getNoteMessage("Zaatakowal krysztal z odleglosci &c" + dis + " kratek")); } } blocked.add(User.get(player)); return true; case EVERYTHING: break; default: break; } return false; }
#vulnerable code public boolean checkPlayer(Player player, SecurityType type, Object... values) { if (!Settings.getConfig().regionsEnabled) { return false; } if (isBanned(User.get(player))) { return true; } switch (type) { case FREECAM: Guild guild = null; for (int i = 0; i < values.length; i++) { if (values[i] instanceof Guild) { guild = (Guild) values[i]; } } int dis = (int) RegionUtils.get(guild.getRegion()).getCenter().distance(player.getLocation()); if (dis < 6) { return false; } for (Player w : Bukkit.getOnlinePlayers()) { if (w.isOp()) { w.sendMessage(SecurityUtils.getBustedMessage(player.getName(), "FreeCam")); w.sendMessage(SecurityUtils.getNoteMessage("Zaatakowal krysztal z odleglosci &c" + dis + " kratek")); } } blocked.add(User.get(player)); return true; case EVERYTHING: break; default: break; } return false; } #location 19 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code protected final boolean sendStopToPostgresqlInstance() { final boolean result = shutdownPostgres(getConfig()); if (runtimeConfig.getArtifactStore() instanceof PostgresArtifactStore) { final IDirectory tempDir = ((PostgresArtifactStore) runtimeConfig.getArtifactStore()).getTempDir(); if (tempDir != null && tempDir.asFile() != null) { logger.log(Level.INFO, format("Cleaning up after the embedded process (removing %s)...", tempDir.asFile().getAbsolutePath())); forceDelete(tempDir.asFile()); } } return result; }
#vulnerable code protected final boolean sendStopToPostgresqlInstance() { final boolean result = shutdownPostgres(getConfig()); if (runtimeConfig.getArtifactStore() instanceof PostgresArtifactStore) { final IDirectory tempDir = ((PostgresArtifactStore) runtimeConfig.getArtifactStore()).getTempDir(); if (tempDir != null && tempDir.asFile() != null) { logger.log(Level.INFO, format("Cleaning up after the embedded process (removing %s)...", tempDir.asFile().getAbsolutePath())); } forceDelete(tempDir.asFile()); } return result; } #location 9 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Test public void simpleBmiTestSplit() throws Exception { final List<Instance> instances = TreeBuilderTestUtils.getIntegerInstances(1000); final TreeBuilder tb = new TreeBuilder(new SplitDiffScorer()); final RandomForestBuilder rfb = new RandomForestBuilder(tb); final PAVCalibratedPredictiveModelBuilder cpmb = new PAVCalibratedPredictiveModelBuilder(rfb); final UpdatablePAVCalibratedPredictiveModelBuilder ucpmb = new UpdatablePAVCalibratedPredictiveModelBuilder(cpmb); final long startTime = System.currentTimeMillis(); final CalibratedPredictiveModel calibratedPredictiveModel = ucpmb.buildPredictiveModel(instances); final RandomForest randomForest = (RandomForest) calibratedPredictiveModel.predictiveModel; TreeBuilderTestUtils.serializeDeserialize(randomForest); final List<Tree> trees = randomForest.trees; final int treeSize = trees.size(); final int firstTreeNodeSize = trees.get(0).node.size(); Assert.assertTrue(treeSize < 400, "Forest size should be less than 400"); Assert.assertTrue((System.currentTimeMillis() - startTime) < 20000,"Building this node should take far less than 20 seconds"); final List<Instance> newInstances = TreeBuilderTestUtils.getIntegerInstances(1000); final CalibratedPredictiveModel newCalibratedPredictiveModel = ucpmb.buildPredictiveModel(newInstances); final RandomForest newRandomForest = (RandomForest) newCalibratedPredictiveModel.predictiveModel; Assert.assertTrue(calibratedPredictiveModel == newCalibratedPredictiveModel, "Expect same tree to be updated"); Assert.assertEquals(treeSize, newRandomForest.trees.size(), "Expected same number of trees"); Assert.assertNotEquals(firstTreeNodeSize, newRandomForest.trees.get(0).node.size(), "Expected new nodes"); }
#vulnerable code @Test public void simpleBmiTestSplit() throws Exception { final List<Instance> instances = TreeBuilderTestUtils.getIntegerInstances(1000); final TreeBuilder tb = new TreeBuilder(new SplitDiffScorer()); final RandomForestBuilder rfb = new RandomForestBuilder(tb); final PAVCalibratedPredictiveModelBuilder cpmb = new PAVCalibratedPredictiveModelBuilder(rfb); final UpdatablePAVCalibratedPredictiveModelBuilder ucpmb = new UpdatablePAVCalibratedPredictiveModelBuilder(cpmb, null, 1); final long startTime = System.currentTimeMillis(); final CalibratedPredictiveModel calibratedPredictiveModel = ucpmb.buildPredictiveModel(instances); final RandomForest randomForest = (RandomForest) calibratedPredictiveModel.predictiveModel; TreeBuilderTestUtils.serializeDeserialize(randomForest); final List<Tree> trees = randomForest.trees; final int treeSize = trees.size(); final int firstTreeNodeSize = trees.get(0).node.size(); Assert.assertTrue(treeSize < 400, "Forest size should be less than 400"); Assert.assertTrue((System.currentTimeMillis() - startTime) < 20000,"Building this node should take far less than 20 seconds"); final List<Instance> newInstances = TreeBuilderTestUtils.getIntegerInstances(1000); final CalibratedPredictiveModel newCalibratedPredictiveModel = ucpmb.buildPredictiveModel(newInstances); final RandomForest newRandomForest = (RandomForest) newCalibratedPredictiveModel.predictiveModel; Assert.assertTrue(calibratedPredictiveModel == newCalibratedPredictiveModel, "Expect same tree to be updated"); Assert.assertEquals(treeSize, newRandomForest.trees.size(), "Expected same number of trees"); Assert.assertNotEquals(firstTreeNodeSize, newRandomForest.trees.get(0).node.size(), "Expected new nodes"); } #location 9 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public static String exportToHtml(Option option, String folderPath, String fileName) { if (fileName == null || fileName.length() == 0) { return exportToHtml(option, folderPath); } FileWriter writer = null; List<String> lines = readLines(option); //写入文件 File html = new File(getFolderPath(folderPath) + "/" + fileName); try { writer = new FileWriter(html); for (String l : lines) { writer.write(l + "\n"); } } catch (Exception e) { } finally { if (writer != null) { try { writer.close(); } catch (IOException e) { //ignore } } } //处理 try { return html.getAbsolutePath(); } catch (Exception e) { return null; } }
#vulnerable code public static String exportToHtml(Option option, String folderPath, String fileName) { if (fileName == null || fileName.length() == 0) { return exportToHtml(option, folderPath); } String optionStr = GsonUtil.format(option); File folder = new File(folderPath); if (folder.exists() && folder.isFile()) { String tempPath = folder.getParent(); folder = new File(tempPath); } if (!folder.exists()) { folder.mkdirs(); } InputStream is = null; InputStreamReader iReader = null; BufferedReader bufferedReader = null; FileWriter writer = null; List<String> lines = new ArrayList<String>(); String line; //写入文件 File html = new File(folder.getPath() + "/" + fileName); try { is = OptionUtil.class.getResourceAsStream("/template"); iReader = new InputStreamReader(is); bufferedReader = new BufferedReader(iReader); while ((line = bufferedReader.readLine()) != null) { if (line.contains("##option##")) { line = line.replace("##option##", optionStr); } lines.add(line); } writer = new FileWriter(html); for (String l : lines) { writer.write(l + "\n"); } } catch (Exception e) { e.printStackTrace(); } finally { if (is != null) { try { is.close(); } catch (IOException e) { //ignore } } if (writer != null) { try { writer.close(); } catch (IOException e) { //ignore } } } //处理 try { return html.getAbsolutePath(); } catch (Exception e) { return null; } } #location 38 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code private static List<String> readLines(Option option) { String optionStr = GsonUtil.format(option); InputStream is = null; InputStreamReader iReader = null; BufferedReader bufferedReader = null; List<String> lines = new ArrayList<String>(); String line; try { is = OptionUtil.class.getResourceAsStream("/template"); iReader = new InputStreamReader(is, "UTF-8"); bufferedReader = new BufferedReader(iReader); while ((line = bufferedReader.readLine()) != null) { if (line.contains("##option##")) { line = line.replace("##option##", optionStr); } lines.add(line); } } catch (Exception e) { } finally { if (is != null) { try { is.close(); } catch (IOException e) { //ignore } } } return lines; }
#vulnerable code private static List<String> readLines(Option option) { String optionStr = GsonUtil.format(option); InputStream is = null; InputStreamReader iReader = null; BufferedReader bufferedReader = null; List<String> lines = new ArrayList<String>(); String line; try { is = OptionUtil.class.getResourceAsStream("/template"); iReader = new InputStreamReader(is); bufferedReader = new BufferedReader(iReader); while ((line = bufferedReader.readLine()) != null) { if (line.contains("##option##")) { line = line.replace("##option##", optionStr); } lines.add(line); } } catch (Exception e) { } finally { if (is != null) { try { is.close(); } catch (IOException e) { //ignore } } } return lines; } #location 18 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public static Geometry loadGeometryFromWKTFileDbg(String file_name) { if (file_name == null) { throw new IllegalArgumentException(); } String s = null; Reader reader = null; try { FileInputStream stream = new FileInputStream(file_name); reader = new BufferedReader(new InputStreamReader(stream)); StringBuilder builder = new StringBuilder(); char[] buffer = new char[8192]; int read; while ((read = reader.read(buffer, 0, buffer.length)) > 0) { builder.append(buffer, 0, read); } s = builder.toString(); } catch (Exception ex) { } finally { if (reader != null) { try { reader.close(); } catch (IOException e) { } } } return OperatorImportFromWkt.local().execute(0, Geometry.Type.Unknown, s, null); }
#vulnerable code public static Geometry loadGeometryFromWKTFileDbg(String file_name) { if (file_name == null) { throw new IllegalArgumentException(); } String s = null; try { FileInputStream stream = new FileInputStream(file_name); Reader reader = new BufferedReader(new InputStreamReader(stream)); StringBuilder builder = new StringBuilder(); char[] buffer = new char[8192]; int read; while ((read = reader.read(buffer, 0, buffer.length)) > 0) { builder.append(buffer, 0, read); } stream.close(); s = builder.toString(); } catch (Exception ex) { } return OperatorImportFromWkt.local().execute(0, Geometry.Type.Unknown, s, null); } #location 16 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Test public void testGetSingleFileGzip() throws Exception { final HttpClientBuilder client = HttpClientBuilder.create(); client.addInterceptorFirst(new HttpResponseInterceptor() { public void process(final HttpResponse r, final HttpContext context) throws HttpException, IOException { assertEquals(200, r.getStatusLine().getStatusCode()); assertNotNull(r.getHeaders(HttpHeaders.CONTENT_ENCODING)); assertEquals(1, r.getHeaders(HttpHeaders.CONTENT_ENCODING).length); assertEquals("gzip", r.getHeaders(HttpHeaders.CONTENT_ENCODING)[0].getValue()); } }); Sardine sardine = new SardineImpl(client); sardine.enableCompression(); // final String url = "http://sardine.googlecode.com/svn/trunk/README.html"; final String url = "http://sudo.ch/dav/anon/sardine/single/file"; final InputStream in = sardine.get(url); assertNotNull(in); assertNotNull(in.read()); try { in.close(); } catch (EOFException e) { fail("Issue https://issues.apache.org/jira/browse/HTTPCLIENT-1075 pending"); } }
#vulnerable code @Test public void testGetSingleFileGzip() throws Exception { final DefaultHttpClient client = new DefaultHttpClient(); client.addResponseInterceptor(new HttpResponseInterceptor() { public void process(final HttpResponse r, final HttpContext context) throws HttpException, IOException { assertEquals(200, r.getStatusLine().getStatusCode()); assertNotNull(r.getHeaders(HttpHeaders.CONTENT_ENCODING)); assertEquals(1, r.getHeaders(HttpHeaders.CONTENT_ENCODING).length); assertEquals("gzip", r.getHeaders(HttpHeaders.CONTENT_ENCODING)[0].getValue()); client.removeResponseInterceptorByClass(this.getClass()); } }); Sardine sardine = new SardineImpl(client); sardine.enableCompression(); // final String url = "http://sardine.googlecode.com/svn/trunk/README.html"; final String url = "http://sudo.ch/dav/anon/sardine/single/file"; final InputStream in = sardine.get(url); assertNotNull(in); assertNotNull(in.read()); try { in.close(); } catch (EOFException e) { fail("Issue https://issues.apache.org/jira/browse/HTTPCLIENT-1075 pending"); } } #location 20 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Test public void testBasicPreemptiveAuth() throws Exception { final HttpClientBuilder client = HttpClientBuilder.create(); final CountDownLatch count = new CountDownLatch(1); client.setDefaultCredentialsProvider(new BasicCredentialsProvider() { @Override public Credentials getCredentials(AuthScope authscope) { // Set flag that credentials have been used indicating preemptive authentication count.countDown(); return new Credentials() { public Principal getUserPrincipal() { return new BasicUserPrincipal("anonymous"); } public String getPassword() { return "invalid"; } }; } }); SardineImpl sardine = new SardineImpl(client); URI url = URI.create("http://sudo.ch/dav/basic/"); //Send basic authentication header in initial request sardine.enablePreemptiveAuthentication(url.getHost()); try { sardine.list(url.toString()); fail("Expected authorization failure"); } catch (SardineException e) { // Expect Authorization Failed assertEquals(401, e.getStatusCode()); // Make sure credentials have been queried assertEquals("No preemptive authentication attempt", 0, count.getCount()); } }
#vulnerable code @Test public void testBasicPreemptiveAuth() throws Exception { final DefaultHttpClient client = new DefaultHttpClient(); final CountDownLatch count = new CountDownLatch(1); client.setCredentialsProvider(new BasicCredentialsProvider() { @Override public Credentials getCredentials(AuthScope authscope) { // Set flag that credentials have been used indicating preemptive authentication count.countDown(); return new Credentials() { public Principal getUserPrincipal() { return new BasicUserPrincipal("anonymous"); } public String getPassword() { return "invalid"; } }; } }); SardineImpl sardine = new SardineImpl(client); URI url = URI.create("http://sudo.ch/dav/basic/"); //Send basic authentication header in initial request sardine.enablePreemptiveAuthentication(url.getHost()); try { sardine.list(url.toString()); fail("Expected authorization failure"); } catch (SardineException e) { // Expect Authorization Failed assertEquals(401, e.getStatusCode()); // Make sure credentials have been queried assertEquals("No preemptive authentication attempt", 0, count.getCount()); } } #location 33 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Test public void testPutRange() throws Exception { final HttpClientBuilder client = HttpClientBuilder.create(); client.addInterceptorFirst(new HttpResponseInterceptor() { public void process(final HttpResponse r, final HttpContext context) throws HttpException, IOException { assertEquals(201, r.getStatusLine().getStatusCode()); } }); Sardine sardine = new SardineImpl(client); // mod_dav supports Range headers for PUT final String url = "http://sudo.ch/dav/anon/sardine/" + UUID.randomUUID().toString(); sardine.put(url, new ByteArrayInputStream("Te".getBytes("UTF-8"))); try { // Append to existing file final Map<String, String> header = Collections.singletonMap(HttpHeaders.CONTENT_RANGE, "bytes " + 2 + "-" + 3 + "/" + 4); client.addInterceptorFirst(new HttpRequestInterceptor() { public void process(final HttpRequest r, final HttpContext context) throws HttpException, IOException { assertNotNull(r.getHeaders(HttpHeaders.CONTENT_RANGE)); assertEquals(1, r.getHeaders(HttpHeaders.CONTENT_RANGE).length); } }); client.addInterceptorFirst(new HttpResponseInterceptor() { public void process(final HttpResponse r, final HttpContext context) throws HttpException, IOException { assertEquals(204, r.getStatusLine().getStatusCode()); } }); sardine.put(url, new ByteArrayInputStream("st".getBytes("UTF-8")), header); assertEquals("Test", new BufferedReader(new InputStreamReader(sardine.get(url), "UTF-8")).readLine()); } finally { sardine.delete(url); } }
#vulnerable code @Test public void testPutRange() throws Exception { final DefaultHttpClient client = new DefaultHttpClient(); Sardine sardine = new SardineImpl(client); // mod_dav supports Range headers for PUT final String url = "http://sudo.ch/dav/anon/sardine/" + UUID.randomUUID().toString(); client.addResponseInterceptor(new HttpResponseInterceptor() { public void process(final HttpResponse r, final HttpContext context) throws HttpException, IOException { assertEquals(201, r.getStatusLine().getStatusCode()); client.removeResponseInterceptorByClass(this.getClass()); } }); sardine.put(url, new ByteArrayInputStream("Te".getBytes("UTF-8"))); try { // Append to existing file final Map<String, String> header = Collections.singletonMap(HttpHeaders.CONTENT_RANGE, "bytes " + 2 + "-" + 3 + "/" + 4); client.addRequestInterceptor(new HttpRequestInterceptor() { public void process(final HttpRequest r, final HttpContext context) throws HttpException, IOException { assertNotNull(r.getHeaders(HttpHeaders.CONTENT_RANGE)); assertEquals(1, r.getHeaders(HttpHeaders.CONTENT_RANGE).length); client.removeRequestInterceptorByClass(this.getClass()); } }); client.addResponseInterceptor(new HttpResponseInterceptor() { public void process(final HttpResponse r, final HttpContext context) throws HttpException, IOException { assertEquals(204, r.getStatusLine().getStatusCode()); client.removeResponseInterceptorByClass(this.getClass()); } }); sardine.put(url, new ByteArrayInputStream("st".getBytes("UTF-8")), header); assertEquals("Test", new BufferedReader(new InputStreamReader(sardine.get(url), "UTF-8")).readLine()); } finally { sardine.delete(url); } } #location 47 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Test public void TestEmptyDefaultsConfig(){ String expectedConfigDirectory = "."; ServerPaths serverPaths = mock(ServerPaths.class); when(serverPaths.getConfigDir()).thenReturn(expectedConfigDirectory); SlackNotificationMainSettings whms = new SlackNotificationMainSettings(server, serverPaths); whms.register(); whms.readFrom(getEmptyDefaultsConfigElement()); String proxy = whms.getProxy(); SlackNotificationProxyConfig whpc = whms.getProxyConfig(); assertTrue(proxy.equals(this.proxyHost)); assertTrue(whpc.getProxyHost().equals(this.proxyHost )); assertTrue(whpc.getProxyPort().equals(this.proxyPort)); assertTrue(whms.getDefaultChannel().equals(this.defaultChannel)); assertTrue(whms.getTeamName().equals(this.teamName)); assertTrue(whms.getToken().equals(this.token)); assertTrue(whms.getIconUrl().equals(this.iconUrl)); assertTrue(whms.getBotName().equals(this.botName)); assertNull(whms.getShowBuildAgent()); assertNull(whms.getShowElapsedBuildTime()); assertTrue(whms.getShowCommits()); assertEquals(5, whms.getMaxCommitsToDisplay()); }
#vulnerable code @Test public void TestEmptyDefaultsConfig(){ String expectedConfigDirectory = "."; ServerPaths serverPaths = mock(ServerPaths.class); when(serverPaths.getConfigDir()).thenReturn(expectedConfigDirectory); SlackNotificationMainSettings whms = new SlackNotificationMainSettings(server, serverPaths); whms.register(); whms.readFrom(getEmptyDefaultsConfigElement()); String proxy = whms.getProxyForUrl("http://something.somecompany.com"); SlackNotificationProxyConfig whpc = whms.getProxyConfigForUrl("http://something.somecompany.com"); assertTrue(proxy.equals(this.proxyHost)); assertTrue(whpc.getProxyHost().equals(this.proxyHost )); assertTrue(whpc.getProxyPort().equals(this.proxyPort)); assertTrue(whms.getDefaultChannel().equals(this.defaultChannel)); assertTrue(whms.getTeamName().equals(this.teamName)); assertTrue(whms.getToken().equals(this.token)); assertTrue(whms.getIconUrl().equals(this.iconUrl)); assertTrue(whms.getBotName().equals(this.botName)); assertNull(whms.getShowBuildAgent()); assertNull(whms.getShowElapsedBuildTime()); assertTrue(whms.getShowCommits()); assertEquals(5, whms.getMaxCommitsToDisplay()); } #location 13 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public SlackNotification createMockNotification(String teamName, String defaultChannel, String botName, String token, String iconUrl, Integer maxCommitsToDisplay, Boolean showElapsedBuildTime, Boolean showBuildAgent, Boolean showCommits, Boolean showCommitters) { SlackNotification notification = new SlackNotificationImpl(defaultChannel); notification.setTeamName(teamName); notification.setBotName(botName); notification.setToken(token); notification.setIconUrl(iconUrl); notification.setMaxCommitsToDisplay(maxCommitsToDisplay); notification.setShowElapsedBuildTime(showElapsedBuildTime); notification.setShowBuildAgent(showBuildAgent); notification.setShowCommits(showCommits); notification.setShowCommitters(showCommitters); SlackNotificationPayloadContent payload = new SlackNotificationPayloadContent(); payload.setAgentName("Build Agent 1"); payload.setBranchDisplayName("master"); payload.setBranchIsDefault(true); payload.setBuildDescriptionWithLinkSyntax(String.format("<http://buildserver/builds/|Failed - My Awesome Build #5>")); payload.setBuildFullName("The Awesome Build"); payload.setBuildId("b123"); payload.setBuildName("My Awesome Build"); payload.setBuildResult("Failed"); payload.setBuildStatusUrl("http://buildserver/builds"); payload.setBuildTypeId("b123"); payload.setColor("danger"); List<Commit> commits = new ArrayList<Commit>(); commits.add(new Commit("a5bdc78", "Bug fix for that awful thing", "jbloggs", "jbloggs")); commits.add(new Commit("cc4500d", "New feature that rocks", "bbrave", "bbrave")); commits.add(new Commit("abb23b4", "Merge of branch xyz", "ddruff", "ddruff")); payload.setCommits(commits); payload.setElapsedTime(13452); payload.setFirstFailedBuild(true); payload.setIsComplete(true); payload.setText("My Awesome build"); notification.setPayload(payload); return notification; }
#vulnerable code public SlackNotification createMockNotification(String teamName, String defaultChannel, String botName, String token, String iconUrl, Integer maxCommitsToDisplay, Boolean showElapsedBuildTime, Boolean showBuildAgent, Boolean showCommits, Boolean showCommitters) { SlackNotification notification = new SlackNotificationImpl(defaultChannel); notification.setTeamName(teamName); notification.setBotName(botName); notification.setToken(token); notification.setIconUrl(iconUrl); notification.setMaxCommitsToDisplay(maxCommitsToDisplay); notification.setShowElapsedBuildTime(showElapsedBuildTime); notification.setShowBuildAgent(showBuildAgent); notification.setShowCommits(showCommits); notification.setShowCommitters(showCommitters); notification.setPayload(payloadManager.buildFinished(null, null)); return notification; } #location 16 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Test public void TestFullConfig(){ String expectedConfigDirectory = "."; ServerPaths serverPaths = mock(ServerPaths.class); when(serverPaths.getConfigDir()).thenReturn(expectedConfigDirectory); SlackNotificationMainSettings whms = new SlackNotificationMainSettings(server, serverPaths); whms.register(); whms.readFrom(getFullConfigElement()); String proxy = whms.getProxy(); SlackNotificationProxyConfig whpc = whms.getProxyConfig(); assertTrue(proxy.equals(this.proxyHost)); assertTrue(whpc.getProxyHost().equals(this.proxyHost )); assertTrue(whpc.getProxyPort().equals(this.proxyPort)); assertTrue(whms.getDefaultChannel().equals(this.defaultChannel)); assertTrue(whms.getTeamName().equals(this.teamName)); assertTrue(whms.getToken().equals(this.token)); assertTrue(whms.getIconUrl().equals(this.iconUrl)); assertTrue(whms.getBotName().equals(this.botName)); assertTrue(whms.getShowBuildAgent()); assertTrue(whms.getShowElapsedBuildTime()); assertFalse(whms.getShowCommits()); assertEquals(15, whms.getMaxCommitsToDisplay()); Credentials credentials = whpc.getCreds(); assertEquals("some-username", credentials.getUserPrincipal().getName()); assertEquals("some-password", credentials.getPassword()); }
#vulnerable code @Test public void TestFullConfig(){ String expectedConfigDirectory = "."; ServerPaths serverPaths = mock(ServerPaths.class); when(serverPaths.getConfigDir()).thenReturn(expectedConfigDirectory); SlackNotificationMainSettings whms = new SlackNotificationMainSettings(server, serverPaths); whms.register(); whms.readFrom(getFullConfigElement()); String proxy = whms.getProxyForUrl("http://something.somecompany.com"); SlackNotificationProxyConfig whpc = whms.getProxyConfigForUrl("http://something.somecompany.com"); assertTrue(proxy.equals(this.proxyHost)); assertTrue(whpc.getProxyHost().equals(this.proxyHost )); assertTrue(whpc.getProxyPort().equals(this.proxyPort)); assertTrue(whms.getDefaultChannel().equals(this.defaultChannel)); assertTrue(whms.getTeamName().equals(this.teamName)); assertTrue(whms.getToken().equals(this.token)); assertTrue(whms.getIconUrl().equals(this.iconUrl)); assertTrue(whms.getBotName().equals(this.botName)); assertTrue(whms.getShowBuildAgent()); assertTrue(whms.getShowElapsedBuildTime()); assertFalse(whms.getShowCommits()); assertEquals(15, whms.getMaxCommitsToDisplay()); Credentials credentials = whpc.getCreds(); assertEquals("some-username", credentials.getUserPrincipal().getName()); assertEquals("some-password", credentials.getPassword()); } #location 13 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code Long getDegreeCutoff(ProcedureConfiguration configuration) { return configuration.get("degreeCutoff", 0L); }
#vulnerable code RleWeightedInput[] prepareRleWeights(List<Map<String, Object>> data, long degreeCutoff, Double skipValue) { RleWeightedInput[] inputs = new RleWeightedInput[data.size()]; int idx = 0; for (Map<String, Object> row : data) { List<Number> weightList = extractValues(row.get("weights")); int size = weightList.size(); if (size > degreeCutoff) { double[] weights = Weights.buildRleWeights(weightList, REPEAT_CUTOFF); inputs[idx++] = skipValue == null ? new RleWeightedInput((Long) row.get("item"), weights, size) : new RleWeightedInput((Long) row.get("item"), weights, size, skipValue); } } if (idx != inputs.length) inputs = Arrays.copyOf(inputs, idx); Arrays.sort(inputs); return inputs; } #location 11 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code private String findPathToJarFileFromClasspath() { final String[] classPath = getClassPath().split(File.pathSeparator); for (final String root : classPath) { if (JAR_REGEX.matcher(root).matches()) { return root; } } return null; }
#vulnerable code private String findPathToJarFileFromClasspath() { final String[] classPath = System.getProperty("java.class.path").split( File.pathSeparator); for (final String root : classPath) { if (JAR_REGEX.matcher(root).matches()) { return root; } } return null; } #location 2 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code private void processMetaData(final MutationMetaData value) { try { this.mutatorScores.registerResults(value.getMutations()); final String css = FileUtil.readToString(IsolationUtils .getContextClassLoader().getResourceAsStream( "templates/mutation/style.css")); final int lineCoverage = calculateLineCoverage(value); final MutationTestSummaryData summaryData = new MutationTestSummaryData( value.getMutatedClass(), value.getTestClasses(), value.getPercentageMutationCoverage(), lineCoverage); collectSummaryData(summaryData); final String fileName = summaryData.getFileName(); final Writer writer = this.outputStrategy.createWriterForFile(fileName); final StringTemplateGroup group = new StringTemplateGroup("mutation_test"); final StringTemplate st = group .getInstanceOf("templates/mutation/mutation_report"); st.setAttribute("css", css); st.setAttribute("summary", summaryData); st.setAttribute("tests", value.getTargettedTests()); st.setAttribute("mutators", value.getConfig().getMutatorNames()); final Collection<SourceFile> sourceFiles = createAnnotatedSoureFiles(value); st.setAttribute("sourceFiles", sourceFiles); st.setAttribute("mutatedClasses", value.getMutatedClass()); // st.setAttribute("groups", groups); writer.write(st.toString()); writer.close(); } catch (final IOException ex) { ex.printStackTrace(); } }
#vulnerable code private void processMetaData(final MutationMetaData value) { try { this.mutatorScores.registerResults(value.getMutations()); final String css = FileUtil.readToString(IsolationUtils .getContextClassLoader().getResourceAsStream( "templates/mutation/style.css")); final int lineCoverage = calculateLineCoverage(value); final MutationTestSummaryData summaryData = new MutationTestSummaryData( value.getMutatedClass(), value.getTestClasses(), value.getPercentageMutationCoverage(), lineCoverage); collectSummaryData(summaryData); final String fileName = summaryData.getFileName(); final BufferedWriter bf = new BufferedWriter(new FileWriter( this.reportDir.getAbsolutePath() + File.separatorChar + fileName)); final StringTemplateGroup group = new StringTemplateGroup("mutation_test"); final StringTemplate st = group .getInstanceOf("templates/mutation/mutation_report"); st.setAttribute("css", css); st.setAttribute("summary", summaryData); st.setAttribute("tests", value.getTargettedTests()); st.setAttribute("mutators", value.getConfig().getMutatorNames()); final Collection<SourceFile> sourceFiles = createAnnotatedSoureFiles(value); st.setAttribute("sourceFiles", sourceFiles); st.setAttribute("mutatedClasses", value.getMutatedClass()); // st.setAttribute("groups", groups); bf.write(st.toString()); bf.close(); } catch (final IOException ex) { ex.printStackTrace(); } } #location 41 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Override public void run() { ServerSocket socket = null; Socket clientSocket = null; try { socket = new ServerSocket(this.port); clientSocket = socket.accept(); final BufferedInputStream bif = new BufferedInputStream( clientSocket.getInputStream()); sendTests(clientSocket); final DataInputStream is = new DataInputStream(bif); receiveCoverage(is); } catch (final IOException e) { throw Unchecked.translateCheckedException(e); } finally { try { if (clientSocket != null) { clientSocket.close(); } if (socket != null) { socket.close(); } } catch (final IOException e) { throw Unchecked.translateCheckedException(e); } } }
#vulnerable code @Override public void run() { ServerSocket socket = null; try { socket = new ServerSocket(this.port); final Socket clientSocket = socket.accept(); final BufferedInputStream bif = new BufferedInputStream( clientSocket.getInputStream()); final DataInputStream is = new DataInputStream(bif); Description d = null; final CoverageStatistics cs = new CoverageStatistics(); byte control = is.readByte(); while (control != CoveragePipe.DONE) { switch (control) { case CoveragePipe.CLAZZ: final int id = is.readInt(); final String name = is.readUTF(); final int newId = cs.registerClass(name); if (id != newId) { throw new PitError("Coverage id out of sync"); } break; case CoveragePipe.LINE: final int classId = is.readInt(); final int lineId = is.readInt(); cs.visitLine(classId, lineId); break; case CoveragePipe.OUTCOME: final boolean isGreen = is.readBoolean(); final long executionTime = is.readLong(); final CoverageResult cr = new CoverageResult(d, executionTime, isGreen, cs.getClassStatistics()); this.handler.apply(cr); cs.clearCoverageStats(); break; case CoveragePipe.TEST_CHANGE: final int index = is.readInt(); d = this.tus.get(index).getDescription(); break; case CoveragePipe.DONE: } control = is.readByte(); } } catch (final IOException e) { throw Unchecked.translateCheckedException(e); } finally { if (socket != null) { try { socket.close(); } catch (final IOException e) { throw Unchecked.translateCheckedException(e); } } } } #location 60 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code private void run(final Class<?> clazz, final Class<?> test, final MethodMutatorFactory... mutators) { final ReportOptions data = new ReportOptions(); final Set<Predicate<String>> tests = Collections.singleton(Prelude .isEqualTo(test.getName())); data.setTargetTests(tests); data.setDependencyAnalysisMaxDistance(-1); final Set<Predicate<String>> mutees = Collections.singleton(Prelude .isEqualTo(clazz.getName())); data.setTargetClasses(mutees); data.setTimeoutConstant(PercentAndConstantTimeoutStrategy.DEFAULT_CONSTANT); data.setTimeoutFactor(PercentAndConstantTimeoutStrategy.DEFAULT_FACTOR); final ArrayList<Predicate<String>> inScope = new ArrayList<Predicate<String>>(); inScope.addAll(mutees); inScope.addAll(tests); data.setClassesInScope(inScope); final JavaAgent agent = new JarCreatingJarFinder(); try { createEngineAndRun(data, agent, mutators); } finally { agent.close(); } }
#vulnerable code private void run(final Class<?> clazz, final Class<?> test, final MethodMutatorFactory... mutators) { final ReportOptions data = new ReportOptions(); final Set<Predicate<String>> tests = Collections.singleton(Prelude .isEqualTo(test.getName())); data.setTargetTests(tests); data.setDependencyAnalysisMaxDistance(-1); final Set<Predicate<String>> mutees = Collections.singleton(Prelude .isEqualTo(clazz.getName())); data.setTargetClasses(mutees); data.setTimeoutConstant(PercentAndConstantTimeoutStrategy.DEFAULT_CONSTANT); data.setTimeoutFactor(PercentAndConstantTimeoutStrategy.DEFAULT_FACTOR); final ArrayList<Predicate<String>> inScope = new ArrayList<Predicate<String>>(); inScope.addAll(mutees); inScope.addAll(tests); data.setClassesInScope(inScope); final CoverageDatabase coverageDatabase = new DefaultCoverageDatabase( this.config, new ClassPath(), new JavaAgentJarFinder(), data); coverageDatabase.initialise(); final Collection<ClassGrouping> codeClasses = coverageDatabase .getGroupedClasses(); final MutationEngine engine = DefaultMutationConfigFactory.createEngine( false, False.<String> instance(), Collections.<String> emptyList(), mutators); final MutationConfig mutationConfig = new MutationConfig(engine, Collections.<String> emptyList()); final MutationTestBuilder builder = new MutationTestBuilder(mutationConfig, UnfilteredMutationFilter.factory(), this.config, data, new JavaAgentJarFinder()); final List<TestUnit> tus = builder.createMutationTestUnits(codeClasses, this.config, coverageDatabase); this.pit.run(this.container, tus); } #location 42 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public static void main(final String[] args) { ExitCode exitCode = ExitCode.OK; Socket s = null; CoveragePipe invokeQueue = null; try { final int port = Integer.valueOf(args[0]); s = new Socket("localhost", port); final SafeDataInputStream dis = new SafeDataInputStream( s.getInputStream()); final SlaveArguments paramsFromParent = dis.read(SlaveArguments.class); Log.setVerbose(paramsFromParent.isVerbose()); final DataOutputStream dos = new DataOutputStream( new BufferedOutputStream(s.getOutputStream())); invokeQueue = new CoveragePipe(dos); CodeCoverageStore.init(invokeQueue); HotSwapAgent.addTransformer(new CoverageTransformer(paramsFromParent .getFilter())); final List<TestUnit> tus = getTestsFromParent(dis, paramsFromParent); LOG.info(tus.size() + " tests received"); final CoverageWorker worker = new CoverageWorker(invokeQueue, tus); worker.run(); } catch (final Throwable ex) { LOG.log(Level.SEVERE, "Error calculating coverage. Process will exit.", ex); ex.printStackTrace(); exitCode = ExitCode.UNKNOWN_ERROR; } finally { if (invokeQueue != null) { invokeQueue.end(); } try { if (s != null) { s.close(); } } catch (final IOException e) { throw translateCheckedException(e); } } System.exit(exitCode.getCode()); }
#vulnerable code public static void main(final String[] args) { ExitCode exitCode = ExitCode.OK; Socket s = null; CoveragePipe invokeQueue = null; try { final int port = Integer.valueOf(args[0]); s = new Socket("localhost", port); final SafeDataInputStream dis = new SafeDataInputStream( s.getInputStream()); final SlaveArguments paramsFromParent = dis.read(SlaveArguments.class); Log.setVerbose(paramsFromParent.isVerbose()); final DataOutputStream dos = new DataOutputStream( new BufferedOutputStream(s.getOutputStream())); invokeQueue = new CoveragePipe(dos); CodeCoverageStore.init(invokeQueue); HotSwapAgent.addTransformer(new CoverageTransformer(paramsFromParent .getFilter())); final List<TestUnit> tus = getTestsFromParent(dis); LOG.info(tus.size() + " tests received"); final CoverageWorker worker = new CoverageWorker(invokeQueue, tus); worker.run(); } catch (final Throwable ex) { LOG.log(Level.SEVERE, "Error calculating coverage. Process will exit.", ex); ex.printStackTrace(); exitCode = ExitCode.UNKNOWN_ERROR; } finally { if (invokeQueue != null) { invokeQueue.end(); } try { if (s != null) { s.close(); } } catch (final IOException e) { throw translateCheckedException(e); } } System.exit(exitCode.getCode()); } #location 44 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public static void main(final String[] args) { ExitCode exitCode = ExitCode.OK; Socket s = null; CoveragePipe invokeQueue = null; try { final int port = Integer.valueOf(args[0]); s = new Socket("localhost", port); final SafeDataInputStream dis = new SafeDataInputStream( s.getInputStream()); final CoverageOptions paramsFromParent = dis.read(CoverageOptions.class); Log.setVerbose(paramsFromParent.isVerbose()); if (paramsFromParent.getPitConfig().verifyEnvironment().hasSome()) { throw paramsFromParent.getPitConfig().verifyEnvironment().value(); } final DataOutputStream dos = new DataOutputStream( new BufferedOutputStream(s.getOutputStream())); invokeQueue = new CoveragePipe(dos); CodeCoverageStore.init(invokeQueue); HotSwapAgent.addTransformer(new CoverageTransformer( convertToJVMClassFilter(paramsFromParent.getFilter()))); final List<TestUnit> tus = getTestsFromParent(dis, paramsFromParent); LOG.info(tus.size() + " tests received"); final CoverageWorker worker = new CoverageWorker(invokeQueue, tus); worker.run(); } catch (final Throwable ex) { LOG.log(Level.SEVERE, "Error calculating coverage. Process will exit.", ex); ex.printStackTrace(); exitCode = ExitCode.UNKNOWN_ERROR; } finally { if (invokeQueue != null) { invokeQueue.end(); } try { if (s != null) { s.close(); } } catch (final IOException e) { throw translateCheckedException(e); } } System.exit(exitCode.getCode()); }
#vulnerable code public static void main(final String[] args) { ExitCode exitCode = ExitCode.OK; Socket s = null; CoveragePipe invokeQueue = null; try { final int port = Integer.valueOf(args[0]); s = new Socket("localhost", port); final SafeDataInputStream dis = new SafeDataInputStream( s.getInputStream()); final CoverageOptions paramsFromParent = dis.read(CoverageOptions.class); Log.setVerbose(paramsFromParent.isVerbose()); final DataOutputStream dos = new DataOutputStream( new BufferedOutputStream(s.getOutputStream())); invokeQueue = new CoveragePipe(dos); CodeCoverageStore.init(invokeQueue); HotSwapAgent.addTransformer(new CoverageTransformer( convertToJVMClassFilter(paramsFromParent.getFilter()))); final List<TestUnit> tus = getTestsFromParent(dis, paramsFromParent); LOG.info(tus.size() + " tests received"); final CoverageWorker worker = new CoverageWorker(invokeQueue, tus); worker.run(); } catch (final Throwable ex) { LOG.log(Level.SEVERE, "Error calculating coverage. Process will exit.", ex); ex.printStackTrace(); exitCode = ExitCode.UNKNOWN_ERROR; } finally { if (invokeQueue != null) { invokeQueue.end(); } try { if (s != null) { s.close(); } } catch (final IOException e) { throw translateCheckedException(e); } } System.exit(exitCode.getCode()); } #location 44 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public static byte[] classAsBytes(final String className) throws ClassNotFoundException { try { final URL resource = ClassUtils.class.getClassLoader().getResource( convertClassNameToFileName(className)); final BufferedInputStream stream = new BufferedInputStream( resource.openStream()); final byte[] result = new byte[resource.openConnection() .getContentLength()]; int i; int counter = 0; while ((i = stream.read()) != -1) { result[counter] = (byte) i; counter++; } stream.close(); return result; } catch (final IOException e) { throw new ClassNotFoundException("", e); } }
#vulnerable code public static byte[] classAsBytes(final String className) throws ClassNotFoundException { try { final URL resource = ClassUtils.class.getClassLoader().getResource( convertClassNameToFileName(className)); final BufferedInputStream stream = new BufferedInputStream( resource.openStream()); final byte[] result = new byte[resource.openConnection() .getContentLength()]; int i; int counter = 0; while ((i = stream.read()) != -1) { result[counter] = (byte) i; counter++; } return result; } catch (final IOException e) { throw new ClassNotFoundException("", e); } } #location 18 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Override public void run() { ServerSocket socket = null; Socket clientSocket = null; try { socket = new ServerSocket(this.port); clientSocket = socket.accept(); final BufferedInputStream bif = new BufferedInputStream( clientSocket.getInputStream()); sendTests(clientSocket); final DataInputStream is = new DataInputStream(bif); receiveCoverage(is); } catch (final IOException e) { throw Unchecked.translateCheckedException(e); } finally { try { if (clientSocket != null) { clientSocket.close(); } if (socket != null) { socket.close(); } } catch (final IOException e) { throw Unchecked.translateCheckedException(e); } } }
#vulnerable code @Override public void run() { ServerSocket socket = null; try { socket = new ServerSocket(this.port); final Socket clientSocket = socket.accept(); final BufferedInputStream bif = new BufferedInputStream( clientSocket.getInputStream()); final DataInputStream is = new DataInputStream(bif); Description d = null; final CoverageStatistics cs = new CoverageStatistics(); byte control = is.readByte(); while (control != CoveragePipe.DONE) { switch (control) { case CoveragePipe.CLAZZ: final int id = is.readInt(); final String name = is.readUTF(); final int newId = cs.registerClass(name); if (id != newId) { throw new PitError("Coverage id out of sync"); } break; case CoveragePipe.LINE: final int classId = is.readInt(); final int lineId = is.readInt(); cs.visitLine(classId, lineId); break; case CoveragePipe.OUTCOME: final boolean isGreen = is.readBoolean(); final long executionTime = is.readLong(); final CoverageResult cr = new CoverageResult(d, executionTime, isGreen, cs.getClassStatistics()); this.handler.apply(cr); cs.clearCoverageStats(); break; case CoveragePipe.TEST_CHANGE: final int index = is.readInt(); d = this.tus.get(index).getDescription(); break; case CoveragePipe.DONE: } control = is.readByte(); } } catch (final IOException e) { throw Unchecked.translateCheckedException(e); } finally { if (socket != null) { try { socket.close(); } catch (final IOException e) { throw Unchecked.translateCheckedException(e); } } } } #location 65 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code private String getGeneratedManifestAttribute(final String key) throws IOException, FileNotFoundException { final Option<String> actual = this.testee.getJarLocation(); final File f = new File(actual.value()); final JarInputStream jis = new JarInputStream(new FileInputStream(f)); final Manifest m = jis.getManifest(); final Attributes a = m.getMainAttributes(); final String am = a.getValue(key); jis.close(); return am; }
#vulnerable code private String getGeneratedManifestAttribute(final String key) throws IOException, FileNotFoundException { final Option<String> actual = this.testee.getJarLocation(); final File f = new File(actual.value()); final JarInputStream jis = new JarInputStream(new FileInputStream(f)); final Manifest m = jis.getManifest(); final Attributes a = m.getMainAttributes(); final String am = a.getValue(key); return am; } #location 6 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public static void main(final String[] args) { enablePowerMockSupport(); final int port = Integer.valueOf(args[0]); Socket s = null; try { s = new Socket("localhost", port); final SafeDataInputStream dis = new SafeDataInputStream( s.getInputStream()); Reporter reporter = new DefaultReporter(s.getOutputStream()); addMemoryWatchDog(reporter); final MutationTestSlave instance = new MutationTestSlave(dis, reporter); instance.run(); } catch (final UnknownHostException ex) { LOG.log(Level.WARNING, "Error during mutation test", ex); } catch (final IOException ex) { LOG.log(Level.WARNING, "Error during mutation test", ex); } finally { if ( s != null ) { safelyCloseSocket(s); } } }
#vulnerable code public static void main(final String[] args) { enablePowerMockSupport(); Socket s = null; Reporter r = null; try { final int port = Integer.valueOf(args[0]); s = new Socket("localhost", port); final SafeDataInputStream dis = new SafeDataInputStream( s.getInputStream()); final SlaveArguments paramsFromParent = dis.read(SlaveArguments.class); Log.setVerbose(paramsFromParent.isVerbose()); final F3<String, ClassLoader,byte[], Boolean> hotswap = new F3<String, ClassLoader, byte[], Boolean>() { public Boolean apply(final String clazzName, ClassLoader loader, final byte[] b) { Class<?> clazz; try { clazz = Class.forName(clazzName, false, loader); return HotSwapAgent.hotSwap(clazz, b); } catch (ClassNotFoundException e) { throw Unchecked.translateCheckedException(e); } } }; r = new DefaultReporter(s.getOutputStream()); addMemoryWatchDog(r); final ClassLoader loader = IsolationUtils.getContextClassLoader(); final MutationTestWorker worker = new MutationTestWorker(hotswap, paramsFromParent.config.createMutator(new ClassloaderByteArraySource( loader)), loader); final List<TestUnit> tests = findTestsForTestClasses(loader, paramsFromParent.testClasses, paramsFromParent.pitConfig); worker.run(paramsFromParent.mutations, r, new TimeOutDecoratedTestSource( paramsFromParent.timeoutStrategy, tests, r)); } catch (final Exception ex) { LOG.log(Level.WARNING, "Error during mutation test", ex); if (r != null) { r.done(ExitCode.UNKNOWN_ERROR); } safelyCloseSocket(s); } finally { if (r != null) { r.done(ExitCode.OK); } safelyCloseSocket(s); } } #location 29 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Override public void run() { ServerSocket socket = null; Socket clientSocket = null; try { socket = new ServerSocket(this.port); clientSocket = socket.accept(); final BufferedInputStream bif = new BufferedInputStream( clientSocket.getInputStream()); sendTests(clientSocket); final DataInputStream is = new DataInputStream(bif); receiveCoverage(is); } catch (final IOException e) { throw Unchecked.translateCheckedException(e); } finally { try { if (clientSocket != null) { clientSocket.close(); } if (socket != null) { socket.close(); } } catch (final IOException e) { throw Unchecked.translateCheckedException(e); } } }
#vulnerable code @Override public void run() { ServerSocket socket = null; try { socket = new ServerSocket(this.port); final Socket clientSocket = socket.accept(); final BufferedInputStream bif = new BufferedInputStream( clientSocket.getInputStream()); final DataInputStream is = new DataInputStream(bif); Description d = null; final CoverageStatistics cs = new CoverageStatistics(); byte control = is.readByte(); while (control != CoveragePipe.DONE) { switch (control) { case CoveragePipe.CLAZZ: final int id = is.readInt(); final String name = is.readUTF(); final int newId = cs.registerClass(name); if (id != newId) { throw new PitError("Coverage id out of sync"); } break; case CoveragePipe.LINE: final int classId = is.readInt(); final int lineId = is.readInt(); cs.visitLine(classId, lineId); break; case CoveragePipe.OUTCOME: final boolean isGreen = is.readBoolean(); final long executionTime = is.readLong(); final CoverageResult cr = new CoverageResult(d, executionTime, isGreen, cs.getClassStatistics()); this.handler.apply(cr); cs.clearCoverageStats(); break; case CoveragePipe.TEST_CHANGE: final int index = is.readInt(); d = this.tus.get(index).getDescription(); break; case CoveragePipe.DONE: } control = is.readByte(); } } catch (final IOException e) { throw Unchecked.translateCheckedException(e); } finally { if (socket != null) { try { socket.close(); } catch (final IOException e) { throw Unchecked.translateCheckedException(e); } } } } #location 9 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Test public void capitalizeTest() { assertEquals(capitalize("hola mundo abc"), "Hola mundo abc"); assertEquals(capitalize("HOLA mundO AbC"), "Hola mundo abc"); assertEquals(capitalize("Hola Mundo abC"), "Hola mundo abc"); assertEquals(capitalize(" Hola Mundo abC "), "Hola mundo abc"); assertEquals(capitalize(" (hola Mundo abC) "), "(Hola mundo abc)"); assertEquals(capitalize("[HOLA Mundo abC]"), "[Hola mundo abc]"); assertEquals(capitalize("-HOLA Mundo abC-"), "-Hola mundo abc-"); assertEquals(capitalize(" ~.-(HOLA Mundo abC)-.~"), "~.-(Hola mundo abc)-.~"); assertEquals(capitalize(""), ""); assertEquals(capitalize("* Hola Mundo aBC"), "* Hola mundo abc"); assertEquals(capitalize("2020"), "2020"); assertEquals(capitalize("iyi akşamlar", new Locale("tr")), "İyi akşamlar"); try { capitalize(null); fail("handles null?"); } catch (NullPointerException ex) { } }
#vulnerable code @Test public void capitalizeTest() { assertEquals(capitalize("hola mundo abc"), "Hola mundo abc"); assertEquals(capitalize("HOLA mundO AbC"), "Hola mundo abc"); assertEquals(capitalize("Hola Mundo abC"), "Hola mundo abc"); assertEquals(capitalize(""), ""); assertEquals(capitalize("* Hola Mundo aBC"), "* hola mundo abc"); assertEquals(capitalize("iyi akşamlar", new Locale("tr")), "İyi akşamlar"); try { capitalize(null); fail("handles null?"); } catch (NullPointerException ex) { } } #location 15 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public void addProductImage(ProductImage productImage, ImageContentFile contentImage) throws ServiceException { try { /** copy to input stream **/ ByteArrayOutputStream baos = new ByteArrayOutputStream(); // Fake code simulating the copy // You can generally do better with nio if you need... // And please, unlike me, do something about the Exceptions :D byte[] buffer = new byte[1024]; int len; while ((len = contentImage.getFile().read(buffer)) > -1) { baos.write(buffer, 0, len); } baos.flush(); // Open new InputStreams using the recorded bytes // Can be repeated as many times as you wish InputStream is1 = new ByteArrayInputStream(baos.toByteArray()); InputStream is2 = new ByteArrayInputStream(baos.toByteArray()); BufferedImage bufferedImage = ImageIO.read(is2); if (bufferedImage == null) { LOGGER.error("Cannot read image format for " + productImage.getProductImage()); throw new Exception("Cannot read image format " + productImage.getProductImage()); } // contentImage.setBufferedImage(bufferedImage); contentImage.setFile(is1); // upload original -- L contentImage.setFileContentType(FileContentType.PRODUCTLG); uploadImage.addProductImage(productImage, contentImage); /* * //default large InputContentImage largeContentImage = new * InputContentImage(ImageContentType.PRODUCT); * largeContentImage.setFile(contentImage.getFile()); * largeContentImage.setDefaultImage(productImage.isDefaultImage()); * largeContentImage.setImageName(new * StringBuilder().append("L-").append(productImage.getProductImage()).toString()); * * * uploadImage.uploadProductImage(configuration, productImage, largeContentImage); */ /* * //default small InputContentImage smallContentImage = new * InputContentImage(ImageContentType.PRODUCT); * smallContentImage.setFile(contentImage.getFile()); * smallContentImage.setDefaultImage(productImage.isDefaultImage()); * smallContentImage.setImageName(new * StringBuilder().append("S-").append(productImage.getProductImage()).toString()); * * uploadImage.uploadProductImage(configuration, productImage, smallContentImage); */ // get template properties file String slargeImageHeight = configuration.getProperty(PRODUCT_IMAGE_HEIGHT_SIZE); String slargeImageWidth = configuration.getProperty(PRODUCT_IMAGE_WIDTH_SIZE); // String ssmallImageHeight = configuration.getProperty("SMALL_IMAGE_HEIGHT_SIZE"); // String ssmallImageWidth = configuration.getProperty("SMALL_IMAGE_WIDTH_SIZE"); //Resizes if (!StringUtils.isBlank(slargeImageHeight) && !StringUtils.isBlank(slargeImageWidth)) { // && // !StringUtils.isBlank(ssmallImageHeight) // && // !StringUtils.isBlank(ssmallImageWidth)) // { FileNameMap fileNameMap = URLConnection.getFileNameMap(); String contentType = fileNameMap.getContentTypeFor(contentImage.getFileName()); String extension = null; if (contentType != null) { extension = contentType.substring(contentType.indexOf('/') + 1, contentType.length()); } if (extension == null) { extension = "jpeg"; } int largeImageHeight = Integer.parseInt(slargeImageHeight); int largeImageWidth = Integer.parseInt(slargeImageWidth); if (largeImageHeight <= 0 || largeImageWidth <= 0) { String sizeMsg = "Image configuration set to an invalid value [PRODUCT_IMAGE_HEIGHT_SIZE] " + largeImageHeight + " , [PRODUCT_IMAGE_WIDTH_SIZE] " + largeImageWidth; LOGGER.error(sizeMsg); throw new ServiceException(sizeMsg); } if (!StringUtils.isBlank(configuration.getProperty(CROP_UPLOADED_IMAGES)) && configuration.getProperty(CROP_UPLOADED_IMAGES).equals(Constants.TRUE)) { // crop image ProductImageCropUtils utils = new ProductImageCropUtils(bufferedImage, largeImageWidth, largeImageHeight); if (utils.isCropeable()) { bufferedImage = utils.getCroppedImage(); } } // do not keep a large image for now, just take care of the regular image and a small image // resize large // ByteArrayOutputStream output = new ByteArrayOutputStream(); BufferedImage largeResizedImage = ProductImageSizeUtils.resizeWithRatio(bufferedImage, largeImageWidth, largeImageHeight); File tempLarge = File.createTempFile(new StringBuilder().append(productImage.getProduct().getId()) .append("tmpLarge").toString(), "." + extension); ImageIO.write(largeResizedImage, extension, tempLarge); try(FileInputStream isLarge = new FileInputStream(tempLarge)) { // IOUtils.copy(isLarge, output); ImageContentFile largeContentImage = new ImageContentFile(); largeContentImage.setFileContentType(FileContentType.PRODUCT); largeContentImage.setFileName(productImage.getProductImage()); largeContentImage.setFile(isLarge); // largeContentImage.setBufferedImage(bufferedImage); // largeContentImage.setFile(output); // largeContentImage.setDefaultImage(false); // largeContentImage.setImageName(new // StringBuilder().append("L-").append(productImage.getProductImage()).toString()); uploadImage.addProductImage(productImage, largeContentImage); // output.flush(); // output.close(); tempLarge.delete(); // now upload original /* * //resize small BufferedImage smallResizedImage = ProductImageSizeUtils.resize(cropped, * smallImageWidth, smallImageHeight); File tempSmall = File.createTempFile(new * StringBuilder().append(productImage.getProduct().getId()).append("tmpSmall").toString(), * "." + extension ); ImageIO.write(smallResizedImage, extension, tempSmall); * * //byte[] is = IOUtils.toByteArray(new FileInputStream(tempSmall)); * * FileInputStream isSmall = new FileInputStream(tempSmall); * * output = new ByteArrayOutputStream(); IOUtils.copy(isSmall, output); * * * smallContentImage = new InputContentImage(ImageContentType.PRODUCT); * smallContentImage.setFile(output); smallContentImage.setDefaultImage(false); * smallContentImage.setImageName(new * StringBuilder().append("S-").append(productImage.getProductImage()).toString()); * * uploadImage.uploadProductImage(configuration, productImage, smallContentImage); * * output.flush(); output.close(); * * tempSmall.delete(); */ } } else { // small will be the same as the original contentImage.setFileContentType(FileContentType.PRODUCT); uploadImage.addProductImage(productImage, contentImage); } } catch (Exception e) { throw new ServiceException(e); } finally { try { productImage.getImage().close(); } catch (Exception ignore) { } } }
#vulnerable code public void addProductImage(ProductImage productImage, ImageContentFile contentImage) throws ServiceException { try { /** copy to input stream **/ ByteArrayOutputStream baos = new ByteArrayOutputStream(); // Fake code simulating the copy // You can generally do better with nio if you need... // And please, unlike me, do something about the Exceptions :D byte[] buffer = new byte[1024]; int len; while ((len = contentImage.getFile().read(buffer)) > -1) { baos.write(buffer, 0, len); } baos.flush(); // Open new InputStreams using the recorded bytes // Can be repeated as many times as you wish InputStream is1 = new ByteArrayInputStream(baos.toByteArray()); InputStream is2 = new ByteArrayInputStream(baos.toByteArray()); BufferedImage bufferedImage = ImageIO.read(is2); if (bufferedImage == null) { LOGGER.error("Cannot read image format for " + productImage.getProductImage()); throw new Exception("Cannot read image format " + productImage.getProductImage()); } // contentImage.setBufferedImage(bufferedImage); contentImage.setFile(is1); // upload original -- L contentImage.setFileContentType(FileContentType.PRODUCTLG); uploadImage.addProductImage(productImage, contentImage); /* * //default large InputContentImage largeContentImage = new * InputContentImage(ImageContentType.PRODUCT); * largeContentImage.setFile(contentImage.getFile()); * largeContentImage.setDefaultImage(productImage.isDefaultImage()); * largeContentImage.setImageName(new * StringBuilder().append("L-").append(productImage.getProductImage()).toString()); * * * uploadImage.uploadProductImage(configuration, productImage, largeContentImage); */ /* * //default small InputContentImage smallContentImage = new * InputContentImage(ImageContentType.PRODUCT); * smallContentImage.setFile(contentImage.getFile()); * smallContentImage.setDefaultImage(productImage.isDefaultImage()); * smallContentImage.setImageName(new * StringBuilder().append("S-").append(productImage.getProductImage()).toString()); * * uploadImage.uploadProductImage(configuration, productImage, smallContentImage); */ // get template properties file String slargeImageHeight = configuration.getProperty(PRODUCT_IMAGE_HEIGHT_SIZE); String slargeImageWidth = configuration.getProperty(PRODUCT_IMAGE_WIDTH_SIZE); // String ssmallImageHeight = configuration.getProperty("SMALL_IMAGE_HEIGHT_SIZE"); // String ssmallImageWidth = configuration.getProperty("SMALL_IMAGE_WIDTH_SIZE"); //Resizes if (!StringUtils.isBlank(slargeImageHeight) && !StringUtils.isBlank(slargeImageWidth)) { // && // !StringUtils.isBlank(ssmallImageHeight) // && // !StringUtils.isBlank(ssmallImageWidth)) // { FileNameMap fileNameMap = URLConnection.getFileNameMap(); String contentType = fileNameMap.getContentTypeFor(contentImage.getFileName()); String extension = null; if (contentType != null) { extension = contentType.substring(contentType.indexOf("/") + 1, contentType.length()); } if (extension == null) { extension = "jpeg"; } int largeImageHeight = Integer.parseInt(slargeImageHeight); int largeImageWidth = Integer.parseInt(slargeImageWidth); if (largeImageHeight <= 0 || largeImageWidth <= 0) { String sizeMsg = "Image configuration set to an invalid value [PRODUCT_IMAGE_HEIGHT_SIZE] " + largeImageHeight + " , [PRODUCT_IMAGE_WIDTH_SIZE] " + largeImageWidth; LOGGER.error(sizeMsg); throw new ServiceException(sizeMsg); } if (!StringUtils.isBlank(configuration.getProperty(CROP_UPLOADED_IMAGES)) && configuration.getProperty(CROP_UPLOADED_IMAGES).equals(Constants.TRUE)) { // crop image ProductImageCropUtils utils = new ProductImageCropUtils(bufferedImage, largeImageWidth, largeImageHeight); if (utils.isCropeable()) { bufferedImage = utils.getCroppedImage(); } } // do not keep a large image for now, just take care of the regular image and a small image // resize large // ByteArrayOutputStream output = new ByteArrayOutputStream(); BufferedImage largeResizedImage = ProductImageSizeUtils.resizeWithRatio(bufferedImage, largeImageWidth, largeImageHeight); File tempLarge = File.createTempFile(new StringBuilder().append(productImage.getProduct().getId()) .append("tmpLarge").toString(), "." + extension); ImageIO.write(largeResizedImage, extension, tempLarge); FileInputStream isLarge = new FileInputStream(tempLarge); // IOUtils.copy(isLarge, output); ImageContentFile largeContentImage = new ImageContentFile(); largeContentImage.setFileContentType(FileContentType.PRODUCT); largeContentImage.setFileName(productImage.getProductImage()); largeContentImage.setFile(isLarge); // largeContentImage.setBufferedImage(bufferedImage); // largeContentImage.setFile(output); // largeContentImage.setDefaultImage(false); // largeContentImage.setImageName(new // StringBuilder().append("L-").append(productImage.getProductImage()).toString()); uploadImage.addProductImage(productImage, largeContentImage); // output.flush(); // output.close(); tempLarge.delete(); // now upload original /* * //resize small BufferedImage smallResizedImage = ProductImageSizeUtils.resize(cropped, * smallImageWidth, smallImageHeight); File tempSmall = File.createTempFile(new * StringBuilder().append(productImage.getProduct().getId()).append("tmpSmall").toString(), * "." + extension ); ImageIO.write(smallResizedImage, extension, tempSmall); * * //byte[] is = IOUtils.toByteArray(new FileInputStream(tempSmall)); * * FileInputStream isSmall = new FileInputStream(tempSmall); * * output = new ByteArrayOutputStream(); IOUtils.copy(isSmall, output); * * * smallContentImage = new InputContentImage(ImageContentType.PRODUCT); * smallContentImage.setFile(output); smallContentImage.setDefaultImage(false); * smallContentImage.setImageName(new * StringBuilder().append("S-").append(productImage.getProductImage()).toString()); * * uploadImage.uploadProductImage(configuration, productImage, smallContentImage); * * output.flush(); output.close(); * * tempSmall.delete(); */ } else { // small will be the same as the original contentImage.setFileContentType(FileContentType.PRODUCT); uploadImage.addProductImage(productImage, contentImage); } } catch (Exception e) { throw new ServiceException(e); } finally { try { productImage.getImage().close(); } catch (Exception ignore) { } } } #location 147 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public JSONObject actionReadFile(HttpServletRequest request, HttpServletResponse response) throws Exception { String path = getPath(request, "path"); File file = new File(docRoot.getPath() + path); if (!file.exists()) { return getErrorResponse(dictionnary.getProperty("INVALID_DIRECTORY_OR_FILE")); } if (file.isDirectory()) { return getErrorResponse(dictionnary.getProperty("FORBIDDEN_ACTION_DIR")); } if (!isAllowedName(file.getName(), false)) { return getErrorResponse(dictionnary.getProperty("INVALID_DIRECTORY_OR_FILE")); } // check if file is readable if (!file.canRead()) { return getErrorResponse(dictionnary.getProperty("NOT_ALLOWED_SYSTEM")); } String filename = file.getName(); String fileExt = filename.substring(filename.lastIndexOf(".") + 1); String mimeType = FileManagerUtils.getMimeTypeByExt(fileExt); long fileSize = file.length(); //TO DO : IMPLEMENT HTTP RANGE FOR STREAM FILE (AUDIO/VIDEO) response.setContentType(mimeType); response.setHeader("Content-Length", Long.toString(fileSize)); response.setHeader("Content-Transfer-Encoding", "binary"); response.setHeader("Content-Disposition", "inline; filename=\"" + filename + "\""); try(BufferedInputStream bufferedInputStream = new BufferedInputStream(new FileInputStream(file))) { FileUtils.copy(bufferedInputStream, response.getOutputStream()); } catch (IOException e) { throw new Exception("Read file error: " + path, e); } return null; }
#vulnerable code public JSONObject actionReadFile(HttpServletRequest request, HttpServletResponse response) throws Exception { String path = getPath(request, "path"); File file = new File(docRoot.getPath() + path); if (!file.exists()) { return getErrorResponse(dictionnary.getProperty("INVALID_DIRECTORY_OR_FILE")); } if (file.isDirectory()) { return getErrorResponse(dictionnary.getProperty("FORBIDDEN_ACTION_DIR")); } if (!isAllowedName(file.getName(), false)) { return getErrorResponse(dictionnary.getProperty("INVALID_DIRECTORY_OR_FILE")); } // check if file is readable if (!file.canRead()) { return getErrorResponse(dictionnary.getProperty("NOT_ALLOWED_SYSTEM")); } String filename = file.getName(); String fileExt = filename.substring(filename.lastIndexOf(".") + 1); String mimeType = FileManagerUtils.getMimeTypeByExt(fileExt); long fileSize = file.length(); //TO DO : IMPLEMENT HTTP RANGE FOR STREAM FILE (AUDIO/VIDEO) response.setContentType(mimeType); response.setHeader("Content-Length", Long.toString(fileSize)); response.setHeader("Content-Transfer-Encoding", "binary"); response.setHeader("Content-Disposition", "inline; filename=\"" + filename + "\""); try { FileUtils.copy(new BufferedInputStream(new FileInputStream(file)), response.getOutputStream()); } catch (IOException e) { throw new Exception("Read file error: " + path, e); } return null; } #location 37 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Test public void standard_syntax() throws Exception { IfStatementTree tree = parse("if ($a) {}", PHPLexicalGrammar.IF_STATEMENT); assertThat(tree.ifToken().text()).isEqualTo("if"); assertThat(expressionToString(tree.condition())).isEqualTo("($a)"); assertThat(tree.statements()).hasSize(1); assertThat(tree.elseClause()).isNull(); assertThat(tree.elseifClauses()).hasSize(0); assertThat(tree.endifToken()).isNull(); assertThat(tree.eosToken()).isNull(); }
#vulnerable code @Test public void standard_syntax() throws Exception { IfStatementTree tree = parse("if ($a) {} else {}", PHPLexicalGrammar.IF_STATEMENT); assertThat(tree.is(Kind.IF_STATEMENT)).isTrue(); assertThat(tree.ifToken().text()).isEqualTo("if"); assertThat(tree.condition()).isNotNull(); assertThat(tree.statements()).hasSize(1); ElseClauseTree elseClause = tree.elseClause(); assertThat(elseClause).isNotNull(); assertThat(elseClause.is(Kind.ELSE_CLAUSE)).isTrue(); assertThat(elseClause.statements()).hasSize(1); assertThat(tree.elseifClauses()).hasSize(0); assertThat(tree.colonToken()).isNull(); assertThat(tree.endifToken()).isNull(); assertThat(tree.eosToken()).isNull(); } #location 11 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code private void test_global_scope(Scope scope) { assertThat(globalSymbolA.usages()).hasSize(4); assertThat(globalSymbolB.usages()).hasSize(1); Symbol arraySymbol = scope.getSymbol("$array"); assertThat(arraySymbol.usages()).hasSize(1); assertThat(scope.getSymbol("$f").usages()).hasSize(1); assertThat(scope.getSymbol("h").usages()).hasSize(1); assertThat(scope.getSymbol("j").usages()).hasSize(1); assertThat(scope.getSymbol("$compoundVar").usages()).hasSize(2); assertThat(scope.getSymbol("$heredocVar").usages()).hasSize(2); assertThat(scope.getSymbol("$var").usages()).hasSize(2); Symbol classSymbol = scope.getSymbol("A"); assertThat(classSymbol).isNotNull(); assertThat(classSymbol.is(Kind.CLASS)).isTrue(); assertThat(classSymbol.usages()).hasSize(3); }
#vulnerable code private void test_global_scope(Scope scope) { assertThat(globalSymbolA.usages()).hasSize(4); assertThat(globalSymbolB.usages()).hasSize(1); Symbol arraySymbol = scope.getSymbol("$array"); assertThat(arraySymbol.usages()).hasSize(1); assertThat(scope.getSymbol("$f").usages()).hasSize(1); assertThat(scope.getSymbol("h").usages()).hasSize(1); assertThat(scope.getSymbol("j").usages()).hasSize(1); assertThat(scope.getSymbol("$compoundVar").usages()).hasSize(2); assertThat(scope.getSymbol("$heredocVar").usages()).hasSize(2); assertThat(scope.getSymbol("$var").usages()).hasSize(2); Symbol classSymbol = scope.getSymbol("A"); assertThat(classSymbol).isNotNull(); assertThat(classSymbol.is(Kind.CLASS)).isTrue(); assertThat(classSymbol.usages()).hasSize(2); } #location 6 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public void execute() { List<String> commandLine = getCommandLine(); LOG.info("Executing " + getExecutedTool() + " with command '{}'", prettyPrint(commandLine)); Iterator<String> commandLineIterator = commandLine.iterator(); Command command = Command.create(commandLineIterator.next()); while (commandLineIterator.hasNext()) { command.addArgument(commandLineIterator.next()); } int exitCode = CommandExecutor.create().execute(command, configuration.getTimeout() * MINUTES_TO_MILLISECONDS); if ( !acceptedExitCodes.contains(exitCode)) { throw new SonarException(getExecutedTool() + " execution failed with returned code '" + exitCode + "'. Please check the documentation of " + getExecutedTool() + " to know more about this failure."); } else { LOG.info(getExecutedTool() + " succeeded with returned code '{}'.", exitCode); } }
#vulnerable code public void execute() { try { // Gets the tool command line List<String> commandLine = getCommandLine(); ProcessBuilder builder = new ProcessBuilder(commandLine); LOG.info("Executing " + getExecutedTool() + " with command '{}'", prettyPrint(commandLine)); // Starts the process Process p = builder.start(); // And handles it's normal and error stream in separated threads. ByteArrayOutputStream output = new ByteArrayOutputStream(DEFAUT_BUFFER_INITIAL_SIZE); AsyncPipe outputStreamThread = new AsyncPipe(p.getInputStream(), output); outputStreamThread.start(); ByteArrayOutputStream error = new ByteArrayOutputStream(DEFAUT_BUFFER_INITIAL_SIZE); AsyncPipe errorStreamThread = new AsyncPipe(p.getErrorStream(), error); errorStreamThread.start(); LOG.info(getExecutedTool() + " ended with returned code '{}'.", p.waitFor()); } catch (IOException e) { LOG.error("Can't execute the external tool", e); throw new PhpPluginExecutionException(e); } catch (InterruptedException e) { LOG.error("Async pipe interrupted: ", e); throw new PhpPluginExecutionException(e); } } #location 13 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Override public void visitClassDeclaration(ClassDeclarationTree tree) { stringLiterals.clear(); super.visitClassDeclaration(tree); if (tree.is(Tree.Kind.CLASS_DECLARATION)) { checkClass(tree); } }
#vulnerable code @Override public void visitClassDeclaration(ClassDeclarationTree tree) { stringLiterals.clear(); super.visitClassDeclaration(tree); if (tree.is(Tree.Kind.CLASS_DECLARATION)) { Scope classScope = context().symbolTable().getScopeFor(tree); for (Symbol methodSymbol : classScope.getSymbols(Kind.FUNCTION)) { boolean ruleConditions = methodSymbol.hasModifier("private") && methodSymbol.usages().isEmpty(); if (ruleConditions && !isConstructor(methodSymbol.declaration(), tree) && !isMagicMethod(methodSymbol.name()) && !isUsedInStringLiteral(methodSymbol)) { context().newIssue(this, methodSymbol.declaration(), String.format(MESSAGE, methodSymbol.name())); } } } } #location 8 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code private void checkCfg(ControlFlowGraph cfg) { for (CfgBlock cfgBlock : cfg.blocks()) { if (cfgBlock.successors().size() == 1 && cfgBlock.successors().contains(cfgBlock.syntacticSuccessor())) { Tree lastElement = Iterables.getLast(cfgBlock.elements()); if (isIgnoredReturn(lastElement)) { continue; } if (lastElement.is(Kind.RETURN_STATEMENT, Kind.CONTINUE_STATEMENT, Kind.GOTO_STATEMENT)) { context().newIssue(this, lastElement, MESSAGE); } } } }
#vulnerable code private void checkCfg(ControlFlowGraph cfg) { for (CfgBlock cfgBlock : cfg.blocks()) { if (cfgBlock.successors().size() == 1 && cfgBlock.successors().contains(cfgBlock.syntacticSuccessor())) { Tree lastElement = cfgBlock.elements().get(cfgBlock.elements().size() - 1); if (lastElement.is(Kind.RETURN_STATEMENT) && (((ReturnStatementTree) lastElement).expression() != null || lastElement.getParent().is(Kind.CASE_CLAUSE, Kind.DEFAULT_CLAUSE))) { continue; } if (lastElement.is(Kind.RETURN_STATEMENT, Kind.CONTINUE_STATEMENT, Kind.GOTO_STATEMENT)) { context().newIssue(this, lastElement, MESSAGE); } } } } #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 test() throws Exception { IssueLocation issueLocation = new IssueLocation(TOKEN1, "Test message"); assertThat(issueLocation.message()).isEqualTo("Test message"); assertThat(issueLocation.startLine()).isEqualTo(5); assertThat(issueLocation.startLineOffset()).isEqualTo(10); assertThat(issueLocation.endLine()).isEqualTo(5); assertThat(issueLocation.endLineOffset()).isEqualTo(16); assertThat(issueLocation.filePath()).isNull(); }
#vulnerable code @Test public void test() throws Exception { IssueLocation issueLocation = new IssueLocation(TOKEN1, "Test message"); assertThat(issueLocation.message()).isEqualTo("Test message"); assertThat(issueLocation.startLine()).isEqualTo(5); assertThat(issueLocation.startLineOffset()).isEqualTo(10); assertThat(issueLocation.endLine()).isEqualTo(5); assertThat(issueLocation.endLineOffset()).isEqualTo(16); } #location 8 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Override public void visitAssignmentExpression(AssignmentExpressionTree assignment) { checkVariable(((PHPTree) assignment.variable()).getLastToken(), assignment.value()); super.visitAssignmentExpression(assignment); }
#vulnerable code @Override public void visitAssignmentExpression(AssignmentExpressionTree assignment) { SyntaxToken lastToken = ((PHPTree) assignment.variable()).getLastToken(); String variableName = lastToken.text(); checkVariable(lastToken, variableName, assignment.value()); super.visitAssignmentExpression(assignment); } #location 4 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public static Map<ClassSymbolData, ClassSymbol> createSymbols(Set<ClassSymbolData> fileDeclarations, ProjectSymbolData projectSymbolData) { Map<ClassSymbolData, ClassSymbolImpl> symbolsByData = new HashMap<>(); Map<ClassSymbolData, ClassSymbol> result = new HashMap<>(); Deque<ClassSymbolData> toComplete = new ArrayDeque<>(); Map<QualifiedName, ClassSymbolImpl> symbolsByQualifiedName = new HashMap<>(); fileDeclarations.forEach(data -> { ClassSymbolImpl symbol = new ClassSymbolImpl(data.location(), data.qualifiedName()); result.put(data, symbol); toComplete.push(data); symbolsByQualifiedName.put(symbol.qualifiedName, symbol); symbolsByData.put(data, symbol); }); while (!toComplete.isEmpty()) { ClassSymbolData data = toComplete.pop(); Optional<QualifiedName> superClassName = data.superClass(); if (superClassName.isPresent()) { ClassSymbolImpl superClass = symbolsByQualifiedName.get(superClassName.get()); if (superClass == null) { Optional<ClassSymbolData> superClassData = projectSymbolData.classSymbolData(superClassName.get()); if (superClassData.isPresent()) { superClass = new ClassSymbolImpl(superClassData.get().location(), superClassName.get()); toComplete.push(superClassData.get()); symbolsByQualifiedName.put(superClassName.get(), superClass); symbolsByData.put(superClassData.get(), superClass); } } symbolsByData.get(data).superClass = superClass == null ? UnknownClassSymbol.UNKNOWN : superClass; } } return result; }
#vulnerable code public static Map<ClassSymbolData, ClassSymbol> createSymbols(Set<ClassSymbolData> fileDeclarations, ProjectSymbolData projectSymbolData) { Map<ClassSymbolData, ClassSymbolImpl> symbolsByData = new HashMap<>(); Map<ClassSymbolData, ClassSymbol> result = new HashMap<>(); Deque<ClassSymbolData> toComplete = new ArrayDeque<>(); Map<QualifiedName, ClassSymbolImpl> symbolsByQualifiedName = new HashMap<>(); fileDeclarations.forEach(data -> { ClassSymbolImpl symbol = new ClassSymbolImpl(data.qualifiedName()); result.put(data, symbol); toComplete.push(data); symbolsByQualifiedName.put(symbol.qualifiedName, symbol); symbolsByData.put(data, symbol); }); while (!toComplete.isEmpty()) { ClassSymbolData data = toComplete.pop(); Optional<QualifiedName> superClassName = data.superClass(); if (superClassName.isPresent()) { ClassSymbolImpl superClass = symbolsByQualifiedName.get(superClassName.get()); if (superClass == null) { Optional<ClassSymbolData> superClassData = projectSymbolData.classSymbolData(superClassName.get()); if (superClassData.isPresent()) { superClass = new ClassSymbolImpl(superClassName.get()); toComplete.push(superClassData.get()); symbolsByQualifiedName.put(superClassName.get(), superClass); symbolsByData.put(superClassData.get(), superClass); } } symbolsByData.get(data).superClass = superClass == null ? UnknownClassSymbol.UNKNOWN : superClass; } } return result; } #location 28 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code private void createTemplateParameters(File outputDir, Template template, File templatesDir) throws MojoExecutionException { JsonNodeFactory nodeFactory = JsonNodeFactory.instance; ObjectNode values = nodeFactory.objectNode(); List<io.fabric8.openshift.api.model.Parameter> parameters = template.getParameters(); if (parameters == null || parameters.isEmpty()) { return; } List<HelmParameter> helmParameters = new ArrayList<>(); for (io.fabric8.openshift.api.model.Parameter parameter : parameters) { HelmParameter helmParameter = new HelmParameter(parameter); helmParameter.addToValue(values); helmParameters.add(helmParameter); } File outputChartFile = new File(outputDir, "values.yaml"); try { saveYaml(values, outputChartFile); } catch (IOException e) { throw new MojoExecutionException("Failed to save chart values " + outputChartFile + ": " + e, e); } // now lets replace all the parameter expressions in each template File[] files = templatesDir.listFiles(); if (files != null) { for (File file : files) { if (file.isFile()) { String extension = Files.getExtension(file.getName()).toLowerCase(); if (extension.equals("yaml") || extension.equals("yml")) { convertTemplateParameterExpressionsWithHelmExpressions(file, helmParameters); } } } } }
#vulnerable code private void createTemplateParameters(File outputDir, Template template, File templatesDir) throws MojoExecutionException { JsonNodeFactory nodeFactory = JsonNodeFactory.instance; ObjectNode values = nodeFactory.objectNode(); List<io.fabric8.openshift.api.model.Parameter> parameters = template.getParameters(); if (parameters == null && parameters.isEmpty()) { return; } List<HelmParameter> helmParameters = new ArrayList<>(); for (io.fabric8.openshift.api.model.Parameter parameter : parameters) { HelmParameter helmParameter = new HelmParameter(parameter); helmParameter.addToValue(values); helmParameters.add(helmParameter); } File outputChartFile = new File(outputDir, "values.yaml"); try { saveYaml(values, outputChartFile); } catch (IOException e) { throw new MojoExecutionException("Failed to save chart values " + outputChartFile + ": " + e, e); } // now lets replace all the parameter expressions in each template File[] files = templatesDir.listFiles(); if (files != null) { for (File file : files) { if (file.isFile()) { String extension = Files.getExtension(file.getName()).toLowerCase(); if (extension.equals("yaml") || extension.equals("yml")) { convertTemplateParameterExpressionsWithHelmExpressions(file, helmParameters); } } } } } #location 5 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code private void addProfiledResourcesFromSubirectories(KubernetesListBuilder builder, File resourceDir, EnricherManager enricherManager) throws IOException, MojoExecutionException { File[] profileDirs = resourceDir.listFiles(new FileFilter() { @Override public boolean accept(File pathname) { return pathname.isDirectory(); } }); for (File profileDir : profileDirs) { Profile profile = ProfileUtil.findProfile(profileDir.getName(), resourceDir); if (profile == null) { throw new MojoExecutionException(String.format("Invalid profile '%s' given as directory in %s. " + "Please either define a profile of this name or move this directory away", profileDir.getName(), resourceDir)); } ProcessorConfig enricherConfig = profile.getEnricherConfig(); File[] resourceFiles = KubernetesResourceUtil.listResourceFragments(profileDir); if (resourceFiles.length > 0) { KubernetesListBuilder profileBuilder = readResourceFragments(resourceFiles); enricherManager.createDefaultResources(enricherConfig, profileBuilder); enricherManager.enrich(enricherConfig, profileBuilder); KubernetesList profileItems = profileBuilder.build(); for (HasMetadata item : profileItems.getItems()) { builder.addToItems(item); } } } }
#vulnerable code private void addProfiledResourcesFromSubirectories(KubernetesListBuilder builder, File resourceDir, EnricherManager enricherManager) throws IOException, MojoExecutionException { File[] profileDirs = resourceDir.listFiles(new FileFilter() { @Override public boolean accept(File pathname) { return pathname.isDirectory(); } }); for (File profileDir : profileDirs) { Profile profile = ProfileUtil.findProfile(profileDir.getName(), resourceDir); ProcessorConfig enricherConfig = profile.getEnricherConfig(); if (profile == null) { throw new MojoExecutionException(String.format("Invalid profile '%s' given as directory in %s. " + "Please either define a profile of this name or move this directory away", profileDir.getName(), resourceDir)); } File[] resourceFiles = KubernetesResourceUtil.listResourceFragments(profileDir); if (resourceFiles.length > 0) { KubernetesListBuilder profileBuilder = readResourceFragments(resourceFiles); enricherManager.createDefaultResources(enricherConfig, profileBuilder); enricherManager.enrich(enricherConfig, profileBuilder); KubernetesList profileItems = profileBuilder.build(); for (HasMetadata item : profileItems.getItems()) { builder.addToItems(item); } } } } #location 10 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code private KubernetesList convertToOpenShiftResources(KubernetesList resources) throws MojoExecutionException { KubernetesListBuilder builder = new KubernetesListBuilder(); builder.withMetadata(resources.getMetadata()); List<HasMetadata> items = resources.getItems(); List<HasMetadata> objects = new ArrayList<>(); if (items != null) { for (HasMetadata item : items) { if (item instanceof Deployment) { // if we have a Deployment and a DeploymentConfig of the same name // since we have a different manifest for OpenShift then lets filter out // the Kubernetes specific Deployment String name = KubernetesHelper.getName(item); if (hasDeploymentConfigNamed(items, name)) { continue; } } HasMetadata converted = convertKubernetesItemToOpenShift(item); if (converted != null) { objects.add(converted); } } } openshiftDependencyResources.addMissingResources(objects); moveTemplatesToTopLevel(builder, objects); // TODO: Remove this ASAP when https://github.com/fabric8io/fabric8-maven-plugin/issues/678 is fixed removeInitContainers(builder, VolumePermissionEnricher.ENRICHER_NAME); return builder.build(); }
#vulnerable code private KubernetesList convertToOpenShiftResources(KubernetesList resources) throws MojoExecutionException { KubernetesListBuilder builder = new KubernetesListBuilder(); builder.withMetadata(resources.getMetadata()); List<HasMetadata> items = resources.getItems(); List<HasMetadata> objects = new ArrayList<>(); if (items != null) { for (HasMetadata item : items) { if (item instanceof Deployment) { // if we have a Deployment and a DeploymentConfig of the same name // since we have a different manifest for OpenShift then lets filter out // the Kubernetes specific Deployment String name = KubernetesHelper.getName(item); if (hasDeploymentConfigNamed(items, name)) { continue; } } HasMetadata converted = convertKubernetesItemToOpenShift(item); if (converted != null) { objects.add(converted); } } } openshiftDependencyResources.addMissingResources(objects); if (openshiftManifest != null && openshiftManifest.isFile() && openshiftManifest.exists()) { // lets add any ImageStream / ImageStreamTag objects which are already on disk // from a previous `BuildMojo` execution KubernetesClient client = clusterAccess.createDefaultClient(log); Set<HasMetadata> oldEntities; try { oldEntities = KubernetesResourceUtil.loadResources(openshiftManifest); } catch (Exception e) { throw new MojoExecutionException("Failed to load openshift manifest " + openshiftManifest + ". " + e, e); } for (HasMetadata entity : oldEntities) { if (entity instanceof ImageStream || entity instanceof ImageStreamTag) { if (KubernetesResourceUtil.findResourceByName(objects, entity.getClass(), KubernetesHelper.getName(entity)) == null) { objects.add(entity); } } } } moveTemplatesToTopLevel(builder, objects); return builder.build(); } #location 29 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code private BuildStrategy createBuildStrategy(ImageConfiguration imageConfig, OpenShiftBuildStrategy osBuildStrategy) { if (osBuildStrategy == OpenShiftBuildStrategy.docker) { return new BuildStrategyBuilder().withType("Docker").build(); } else if (osBuildStrategy == OpenShiftBuildStrategy.s2i) { BuildImageConfiguration buildConfig = imageConfig.getBuildConfiguration(); Map<String, String> fromExt = buildConfig.getFromExt(); String fromName = getMapValueWithDefault(fromExt, OpenShiftBuildStrategy.SourceStrategy.name, buildConfig.getFrom()); String fromKind = getMapValueWithDefault(fromExt, OpenShiftBuildStrategy.SourceStrategy.kind, "DockerImage"); String fromNamespace = getMapValueWithDefault(fromExt, OpenShiftBuildStrategy.SourceStrategy.namespace, "ImageStreamTag".equals(fromKind) ? "openshift" : null); return new BuildStrategyBuilder() .withType("Source") .withNewSourceStrategy() .withNewFrom() .withKind(fromKind) .withName(fromName) .withNamespace(StringUtils.isEmpty(fromNamespace) ? null : fromNamespace) .endFrom() .endSourceStrategy() .build(); } else { throw new IllegalArgumentException("Unsupported BuildStrategy " + osBuildStrategy); } }
#vulnerable code private BuildStrategy createBuildStrategy(ImageConfiguration imageConfig, OpenShiftBuildStrategy osBuildStrategy) { if (osBuildStrategy == OpenShiftBuildStrategy.docker) { return new BuildStrategyBuilder().withType("Docker").build(); } else if (osBuildStrategy == OpenShiftBuildStrategy.s2i) { BuildImageConfiguration buildConfig = imageConfig.getBuildConfiguration(); Map<String, String> fromExt = buildConfig.getFromExt(); String fromName = getMapValueWithDefault(fromExt, OpenShiftBuildStrategy.SourceStrategy.name, buildConfig.getFrom()); String fromKind = getMapValueWithDefault(fromExt, OpenShiftBuildStrategy.SourceStrategy.kind, "DockerImage"); String fromNamespace = getMapValueWithDefault(fromExt, OpenShiftBuildStrategy.SourceStrategy.namespace, "ImageStreamTag".equals(fromKind) ? "openshift" : null); if (fromNamespace.isEmpty()) { fromNamespace = null; } return new BuildStrategyBuilder() .withType("Source") .withNewSourceStrategy() .withNewFrom() .withKind(fromKind) .withName(fromName) .withNamespace(fromNamespace) .endFrom() .endSourceStrategy() .build(); } else { throw new IllegalArgumentException("Unsupported BuildStrategy " + osBuildStrategy); } } #location 11 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public WatcherContext getWatcherContext() throws MojoExecutionException { try { BuildService.BuildContext buildContext = getBuildContext(); WatchService.WatchContext watchContext = hub != null ? getWatchContext(hub) : null; return new WatcherContext.Builder() .serviceHub(hub) .buildContext(buildContext) .watchContext(watchContext) .config(extractWatcherConfig()) .logger(log) .newPodLogger(createLogger("[[C]][NEW][[C]] ")) .oldPodLogger(createLogger("[[R]][OLD][[R]] ")) .mode(mode) .project(project) .useProjectClasspath(useProjectClasspath) .clusterConfiguration(getClusterConfiguration()) .kubernetesClient(kubernetes) .fabric8ServiceHub(getFabric8ServiceHub()) .build(); } catch(IOException exception) { throw new MojoExecutionException(exception.getMessage()); } }
#vulnerable code public WatcherContext getWatcherContext() throws MojoExecutionException { try { BuildService.BuildContext buildContext = getBuildContext(); WatchService.WatchContext watchContext = getWatchContext(hub); return new WatcherContext.Builder() .serviceHub(hub) .buildContext(buildContext) .watchContext(watchContext) .config(extractWatcherConfig()) .logger(log) .newPodLogger(createLogger("[[C]][NEW][[C]] ")) .oldPodLogger(createLogger("[[R]][OLD][[R]] ")) .mode(mode) .project(project) .useProjectClasspath(useProjectClasspath) .clusterConfiguration(getClusterConfiguration()) .kubernetesClient(kubernetes) .fabric8ServiceHub(getFabric8ServiceHub()) .build(); } catch(IOException exception) { throw new MojoExecutionException(exception.getMessage()); } } #location 21 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code private void assertApplicationEndpoint(String key, String value) throws Exception { int nTries = 0; Response readResponse = null; String responseContent = null; Route applicationRoute = getApplicationRouteWithName(testsuiteRepositoryArtifactId); String hostUrl = applicationRoute.getSpec().getHost() + TEST_ENDPOINT; do { readResponse = makeHttpRequest(HttpRequestType.GET, "http://" + hostUrl, null); responseContent = new JSONObject(readResponse.body().string()).getString(key); nTries++; TimeUnit.SECONDS.sleep(10); } while(nTries < 3 && readResponse.code() != HttpStatus.SC_OK); if (!responseContent.equals(value)) throw new AssertionError(String.format("Actual : %s, Expected : %s", responseContent, value)); }
#vulnerable code private void assertApplicationEndpoint(String key, String value) throws Exception { int nTries = 0; Response readResponse = null; String responseContent = null; Route applicationRoute = getApplicationRouteWithName(testsuiteRepositoryArtifactId); String hostUrl = applicationRoute.getSpec().getHost() + TEST_ENDPOINT; do { Response response = makeHttpRequest(HttpRequestType.GET, "http://" + hostUrl, null); responseContent = new JSONObject(response.body().string()).getString(key); nTries++; TimeUnit.SECONDS.sleep(10); } while(nTries < 3 && readResponse != null && readResponse.code() != HttpStatus.SC_OK); if (!responseContent.equals(value)) throw new AssertionError(String.format("Actual : %s, Expected : %s", responseContent, value)); } #location 9 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code protected void applyEntities(Controller controller, KubernetesClient kubernetes, String namespace, String fileName, Set<HasMetadata> entities) throws Exception { // Apply all items for (HasMetadata entity : entities) { if (entity instanceof Pod) { Pod pod = (Pod) entity; controller.applyPod(pod, fileName); } else if (entity instanceof Service) { Service service = (Service) entity; controller.applyService(service, fileName); } else if (entity instanceof ReplicationController) { ReplicationController replicationController = (ReplicationController) entity; controller.applyReplicationController(replicationController, fileName); } else if (entity != null) { controller.apply(entity, fileName); } } File file = null; try { Fabric8ServiceHub hub = getFabric8ServiceHub(controller); file = hub.getClientToolsService().getKubeCtlExecutable(); } catch (Exception e) { log.warn("%s", e.getMessage()); } if (file != null) { log.info("[[B]]HINT:[[B]] Use the command `%s get pods -w` to watch your pods start up",file.getName()); } Logger serviceLogger = createExternalProcessLogger("[[G]][SVC][[G]] "); long serviceUrlWaitTimeSeconds = this.serviceUrlWaitTimeSeconds; for (HasMetadata entity : entities) { if (entity instanceof Service) { Service service = (Service) entity; String name = getName(service); Resource<Service, DoneableService> serviceResource = kubernetes.services().inNamespace(namespace).withName(name); String url = null; // lets wait a little while until there is a service URL in case the exposecontroller is running slow for (int i = 0; i < serviceUrlWaitTimeSeconds; i++) { if (i > 0) { Thread.sleep(1000); } Service s = serviceResource.get(); if (s != null) { url = getExternalServiceURL(s); if (Strings.isNotBlank(url)) { break; } } if (!isExposeService(service)) { break; } } // lets not wait for other services serviceUrlWaitTimeSeconds = 1; if (Strings.isNotBlank(url) && url.startsWith("http")) { serviceLogger.info("" + name + ": " + url); } } } }
#vulnerable code protected void applyEntities(Controller controller, KubernetesClient kubernetes, String namespace, String fileName, Set<HasMetadata> entities) throws Exception { // Apply all items for (HasMetadata entity : entities) { if (entity instanceof Pod) { Pod pod = (Pod) entity; controller.applyPod(pod, fileName); } else if (entity instanceof Service) { Service service = (Service) entity; controller.applyService(service, fileName); } else if (entity instanceof ReplicationController) { ReplicationController replicationController = (ReplicationController) entity; controller.applyReplicationController(replicationController, fileName); } else if (entity != null) { controller.apply(entity, fileName); } } File file = null; try { Fabric8ServiceHub hub = getFabric8ServiceHub(); file = hub.getClientToolsService().getKubeCtlExecutable(controller); } catch (Exception e) { log.warn("%s", e.getMessage()); } if (file != null) { log.info("[[B]]HINT:[[B]] Use the command `%s get pods -w` to watch your pods start up",file.getName()); } Logger serviceLogger = createExternalProcessLogger("[[G]][SVC][[G]] "); long serviceUrlWaitTimeSeconds = this.serviceUrlWaitTimeSeconds; for (HasMetadata entity : entities) { if (entity instanceof Service) { Service service = (Service) entity; String name = getName(service); Resource<Service, DoneableService> serviceResource = kubernetes.services().inNamespace(namespace).withName(name); String url = null; // lets wait a little while until there is a service URL in case the exposecontroller is running slow for (int i = 0; i < serviceUrlWaitTimeSeconds; i++) { if (i > 0) { Thread.sleep(1000); } Service s = serviceResource.get(); if (s != null) { url = getExternalServiceURL(s); if (Strings.isNotBlank(url)) { break; } } if (!isExposeService(service)) { break; } } // lets not wait for other services serviceUrlWaitTimeSeconds = 1; if (Strings.isNotBlank(url) && url.startsWith("http")) { serviceLogger.info("" + name + ": " + url); } } } } #location 21 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code protected Fabric8ServiceHub getFabric8ServiceHub() { return new Fabric8ServiceHub.Builder() .log(log) .clusterAccess(clusterAccess) .dockerServiceHub(hub) .platformMode(mode) .repositorySystem(repositorySystem) .build(); }
#vulnerable code protected Fabric8ServiceHub getFabric8ServiceHub() { return new Fabric8ServiceHub.Builder() .log(log) .clusterAccess(clusterAccess) .dockerServiceHub(hub) .platformMode(mode) .build(); } #location 4 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code FatJarDetector(String dir) { this.directory = new File(dir); }
#vulnerable code Result scan() throws MojoExecutionException { // Scanning is lazy ... if (result == null) { if (!directory.exists()) { // No directory to check found so we return null here ... return null; } String[] jarOrWars = directory.list((dir, name) -> name.endsWith(".war") || name.endsWith(".jar")); if (jarOrWars == null || jarOrWars.length == 0) { return null; } long maxSize = 0; for (String jarOrWar : jarOrWars) { File archiveFile = new File(directory, jarOrWar); try { JarFile archive = new JarFile(archiveFile); Manifest mf = archive.getManifest(); Attributes mainAttributes = mf.getMainAttributes(); if (mainAttributes != null) { String mainClass = mainAttributes.getValue("Main-Class"); if (mainClass != null) { long size = archiveFile.length(); // Take the largest jar / war file found if (size > maxSize) { maxSize = size; result = new Result(archiveFile, mainClass, mainAttributes); } } } } catch (IOException e) { throw new MojoExecutionException("Cannot examine file " + archiveFile + " for the manifest"); } } } return result; } #location 17 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Override public void enrich(KubernetesListBuilder builder) { final ServiceConfiguration defaultServiceConfig = extractDefaultServiceConfig(); final Service defaultService = serviceHandler.getService(defaultServiceConfig,null); if (hasServices(builder)) { builder.accept(new Visitor<ServiceBuilder>() { @Override public void visit(ServiceBuilder service) { mergeServices(service, defaultService); } }); } else { if (defaultService != null) { ServiceSpec spec = defaultService.getSpec(); if (spec != null) { List<ServicePort> ports = spec.getPorts(); if (ports != null) { log.info("Adding a default Service with ports [%s]", formatPortsAsList(ports)); builder.addToServiceItems(defaultService); } } } } }
#vulnerable code @Override public void enrich(KubernetesListBuilder builder) { final ServiceConfiguration defaultServiceConfig = extractDefaultServiceConfig(); final Service defaultService = serviceHandler.getService(defaultServiceConfig,null); if (hasServices(builder)) { builder.accept(new Visitor<ServiceBuilder>() { @Override public void visit(ServiceBuilder service) { mergeServices(service, defaultService); } }); } else { log.info("Adding a default Service with ports [%s]", formatPortsAsList(defaultService.getSpec().getPorts())); builder.addToServiceItems(defaultService); } } #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 testValidate() { TestUtils.log(this.getClass(), "validate"); RandomValue.randomGenerator = new Random(42); /* Example from http://www.inf.u-szeged.hu/~ormandi/ai2/06-naiveBayes-example.pdf FeatureList: - 0: red - 1: yellow - 2: sports - 3: suv - 4: domestic - 5: imported - c1: yes - c2: no */ /* Dataset trainingData = new Dataset(); trainingData.add(Record.newDataVector(new Double[] {1.0, 0.0, 1.0, 0.0, 1.0, 0.0}, 1)); trainingData.add(Record.newDataVector(new Double[] {1.0, 0.0, 1.0, 0.0, 1.0, 0.0}, 0)); trainingData.add(Record.newDataVector(new Double[] {1.0, 0.0, 1.0, 0.0, 1.0, 0.0}, 1)); trainingData.add(Record.newDataVector(new Double[] {0.0, 1.0, 1.0, 0.0, 1.0, 0.0}, 0)); trainingData.add(Record.newDataVector(new Double[] {0.0, 1.0, 1.0, 0.0, 0.0, 1.0}, 1)); trainingData.add(Record.newDataVector(new Double[] {0.0, 1.0, 0.0, 1.0, 0.0, 1.0}, 0)); trainingData.add(Record.newDataVector(new Double[] {0.0, 1.0, 0.0, 1.0, 0.0, 1.0}, 1)); trainingData.add(Record.newDataVector(new Double[] {0.0, 1.0, 0.0, 1.0, 1.0, 0.0}, 0)); trainingData.add(Record.newDataVector(new Double[] {1.0, 0.0, 0.0, 1.0, 0.0, 1.0}, 0)); trainingData.add(Record.newDataVector(new Double[] {1.0, 0.0, 1.0, 0.0, 0.0, 1.0}, 1)); Dataset validationData = new Dataset(); validationData.add(Record.newDataVector(new Double[] {1.0, 0.0, 0.0, 1.0, 1.0, 0.0}, 0)); */ Dataset trainingData = new Dataset(); trainingData.add(Record.newDataVector(new String[] {"red", "sports", "domestic"}, "yes")); trainingData.add(Record.newDataVector(new String[] {"red", "sports", "domestic"}, "no")); trainingData.add(Record.newDataVector(new String[] {"red", "sports", "domestic"}, "yes")); trainingData.add(Record.newDataVector(new String[] {"yellow", "sports", "domestic"}, "no")); trainingData.add(Record.newDataVector(new String[] {"yellow", "sports", "imported"}, "yes")); trainingData.add(Record.newDataVector(new String[] {"yellow", "suv", "imported"}, "no")); trainingData.add(Record.newDataVector(new String[] {"yellow", "suv", "imported"}, "yes")); trainingData.add(Record.newDataVector(new String[] {"yellow", "suv", "domestic"}, "no")); trainingData.add(Record.newDataVector(new String[] {"red", "suv", "imported"}, "no")); trainingData.add(Record.newDataVector(new String[] {"red", "sports", "imported"}, "yes")); Dataset validationData = new Dataset(); validationData.add(Record.newDataVector(new String[] {"red", "suv", "domestic"}, "no")); String dbName = "JUnitClassifier"; DummyXYMinMaxNormalizer df = new DummyXYMinMaxNormalizer(dbName, TestUtils.getDBConfig()); df.fit_transform(trainingData, new DummyXYMinMaxNormalizer.TrainingParameters()); df.transform(validationData); BootstrapAggregating instance = new BootstrapAggregating(dbName, TestUtils.getDBConfig()); BootstrapAggregating.TrainingParameters param = new BootstrapAggregating.TrainingParameters(); param.setMaxWeakClassifiers(5); param.setWeakClassifierClass(MultinomialNaiveBayes.class); MultinomialNaiveBayes.TrainingParameters trainingParameters = new MultinomialNaiveBayes.TrainingParameters(); trainingParameters.setMultiProbabilityWeighted(true); param.setWeakClassifierTrainingParameters(trainingParameters); instance.fit(trainingData, param); instance = null; instance = new BootstrapAggregating(dbName, TestUtils.getDBConfig()); instance.validate(validationData); df.denormalize(trainingData); df.denormalize(validationData); df.erase(); Map<Integer, Object> expResult = new HashMap<>(); Map<Integer, Object> result = new HashMap<>(); for(Record r : validationData) { expResult.put(r.getId(), r.getY()); result.put(r.getId(), r.getYPredicted()); } assertEquals(expResult, result); instance.erase(); }
#vulnerable code @Test public void testValidate() { TestUtils.log(this.getClass(), "validate"); RandomValue.randomGenerator = new Random(42); /* Example from http://www.inf.u-szeged.hu/~ormandi/ai2/06-naiveBayes-example.pdf FeatureList: - 0: red - 1: yellow - 2: sports - 3: suv - 4: domestic - 5: imported - c1: yes - c2: no */ /* Dataset trainingData = new Dataset(); trainingData.add(Record.newDataVector(new Double[] {1.0, 0.0, 1.0, 0.0, 1.0, 0.0}, 1)); trainingData.add(Record.newDataVector(new Double[] {1.0, 0.0, 1.0, 0.0, 1.0, 0.0}, 0)); trainingData.add(Record.newDataVector(new Double[] {1.0, 0.0, 1.0, 0.0, 1.0, 0.0}, 1)); trainingData.add(Record.newDataVector(new Double[] {0.0, 1.0, 1.0, 0.0, 1.0, 0.0}, 0)); trainingData.add(Record.newDataVector(new Double[] {0.0, 1.0, 1.0, 0.0, 0.0, 1.0}, 1)); trainingData.add(Record.newDataVector(new Double[] {0.0, 1.0, 0.0, 1.0, 0.0, 1.0}, 0)); trainingData.add(Record.newDataVector(new Double[] {0.0, 1.0, 0.0, 1.0, 0.0, 1.0}, 1)); trainingData.add(Record.newDataVector(new Double[] {0.0, 1.0, 0.0, 1.0, 1.0, 0.0}, 0)); trainingData.add(Record.newDataVector(new Double[] {1.0, 0.0, 0.0, 1.0, 0.0, 1.0}, 0)); trainingData.add(Record.newDataVector(new Double[] {1.0, 0.0, 1.0, 0.0, 0.0, 1.0}, 1)); Dataset validationData = new Dataset(); validationData.add(Record.newDataVector(new Double[] {1.0, 0.0, 0.0, 1.0, 1.0, 0.0}, 0)); */ Dataset trainingData = new Dataset(); trainingData.add(Record.newDataVector(new String[] {"red", "sports", "domestic"}, "yes")); trainingData.add(Record.newDataVector(new String[] {"red", "sports", "domestic"}, "no")); trainingData.add(Record.newDataVector(new String[] {"red", "sports", "domestic"}, "yes")); trainingData.add(Record.newDataVector(new String[] {"yellow", "sports", "domestic"}, "no")); trainingData.add(Record.newDataVector(new String[] {"yellow", "sports", "imported"}, "yes")); trainingData.add(Record.newDataVector(new String[] {"yellow", "suv", "imported"}, "no")); trainingData.add(Record.newDataVector(new String[] {"yellow", "suv", "imported"}, "yes")); trainingData.add(Record.newDataVector(new String[] {"yellow", "suv", "domestic"}, "no")); trainingData.add(Record.newDataVector(new String[] {"red", "suv", "imported"}, "no")); trainingData.add(Record.newDataVector(new String[] {"red", "sports", "imported"}, "yes")); Dataset validationData = new Dataset(); validationData.add(Record.newDataVector(new String[] {"red", "suv", "domestic"}, "no")); String dbName = "JUnitClassifier"; SimpleDummyVariableExtractor df = new SimpleDummyVariableExtractor(dbName, TestUtils.getDBConfig()); df.fit_transform(trainingData, new SimpleDummyVariableExtractor.TrainingParameters()); df.transform(validationData); BootstrapAggregating instance = new BootstrapAggregating(dbName, TestUtils.getDBConfig()); BootstrapAggregating.TrainingParameters param = new BootstrapAggregating.TrainingParameters(); param.setMaxWeakClassifiers(5); param.setWeakClassifierClass(MultinomialNaiveBayes.class); MultinomialNaiveBayes.TrainingParameters trainingParameters = new MultinomialNaiveBayes.TrainingParameters(); trainingParameters.setMultiProbabilityWeighted(true); param.setWeakClassifierTrainingParameters(trainingParameters); instance.fit(trainingData, param); instance = null; instance = new BootstrapAggregating(dbName, TestUtils.getDBConfig()); instance.validate(validationData); df.denormalize(trainingData); df.denormalize(validationData); df.erase(); Map<Integer, Object> expResult = new HashMap<>(); Map<Integer, Object> result = new HashMap<>(); for(Record r : validationData) { expResult.put(r.getId(), r.getY()); result.put(r.getId(), r.getYPredicted()); } assertEquals(expResult, result); instance.erase(); } #location 55 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Test public void testValidate() { TestUtils.log(this.getClass(), "validate"); /* Example from http://www.inf.u-szeged.hu/~ormandi/ai2/06-naiveBayes-example.pdf FeatureList: - 0: red - 1: yellow - 2: sports - 3: suv - 4: domestic - 5: imported - c1: yes - c2: no */ /* Dataset trainingData = new Dataset(); trainingData.add(Record.newDataVector(new Double[] {1.0, 0.0, 1.0, 0.0, 1.0, 0.0}, 1)); trainingData.add(Record.newDataVector(new Double[] {1.0, 0.0, 1.0, 0.0, 1.0, 0.0}, 0)); trainingData.add(Record.newDataVector(new Double[] {1.0, 0.0, 1.0, 0.0, 1.0, 0.0}, 1)); trainingData.add(Record.newDataVector(new Double[] {0.0, 1.0, 1.0, 0.0, 1.0, 0.0}, 0)); trainingData.add(Record.newDataVector(new Double[] {0.0, 1.0, 1.0, 0.0, 0.0, 1.0}, 1)); trainingData.add(Record.newDataVector(new Double[] {0.0, 1.0, 0.0, 1.0, 0.0, 1.0}, 0)); trainingData.add(Record.newDataVector(new Double[] {0.0, 1.0, 0.0, 1.0, 0.0, 1.0}, 1)); trainingData.add(Record.newDataVector(new Double[] {0.0, 1.0, 0.0, 1.0, 1.0, 0.0}, 0)); trainingData.add(Record.newDataVector(new Double[] {1.0, 0.0, 0.0, 1.0, 0.0, 1.0}, 0)); trainingData.add(Record.newDataVector(new Double[] {1.0, 0.0, 1.0, 0.0, 0.0, 1.0}, 1)); Dataset validationData = new Dataset(); validationData.add(Record.newDataVector(new Double[] {1.0, 0.0, 0.0, 1.0, 1.0, 0.0}, 0)); */ Dataset trainingData = new Dataset(); trainingData.add(Record.newDataVector(new String[] {"red", "sports", "domestic"}, "yes")); trainingData.add(Record.newDataVector(new String[] {"red", "sports", "domestic"}, "no")); trainingData.add(Record.newDataVector(new String[] {"red", "sports", "domestic"}, "yes")); trainingData.add(Record.newDataVector(new String[] {"yellow", "sports", "domestic"}, "no")); trainingData.add(Record.newDataVector(new String[] {"yellow", "sports", "imported"}, "yes")); trainingData.add(Record.newDataVector(new String[] {"yellow", "suv", "imported"}, "no")); trainingData.add(Record.newDataVector(new String[] {"yellow", "suv", "imported"}, "yes")); trainingData.add(Record.newDataVector(new String[] {"yellow", "suv", "domestic"}, "no")); trainingData.add(Record.newDataVector(new String[] {"red", "suv", "imported"}, "no")); trainingData.add(Record.newDataVector(new String[] {"red", "sports", "imported"}, "yes")); Dataset validationData = new Dataset(); validationData.add(Record.newDataVector(new String[] {"red", "suv", "domestic"}, "no")); String dbName = "JUnitClassifier"; DummyXYMinMaxNormalizer df = new DummyXYMinMaxNormalizer(dbName, TestUtils.getDBConfig()); df.fit_transform(trainingData, new DummyXYMinMaxNormalizer.TrainingParameters()); df.transform(validationData); MultinomialNaiveBayes instance = new MultinomialNaiveBayes(dbName, TestUtils.getDBConfig()); MultinomialNaiveBayes.TrainingParameters param = new MultinomialNaiveBayes.TrainingParameters(); param.setMultiProbabilityWeighted(true); instance.fit(trainingData, param); instance = null; instance = new MultinomialNaiveBayes(dbName, TestUtils.getDBConfig()); instance.validate(validationData); df.denormalize(trainingData); df.denormalize(validationData); df.erase(); Map<Integer, Object> expResult = new HashMap<>(); Map<Integer, Object> result = new HashMap<>(); for(Record r : validationData) { expResult.put(r.getId(), r.getY()); result.put(r.getId(), r.getYPredicted()); } assertEquals(expResult, result); instance.erase(); }
#vulnerable code @Test public void testValidate() { TestUtils.log(this.getClass(), "validate"); /* Example from http://www.inf.u-szeged.hu/~ormandi/ai2/06-naiveBayes-example.pdf FeatureList: - 0: red - 1: yellow - 2: sports - 3: suv - 4: domestic - 5: imported - c1: yes - c2: no */ /* Dataset trainingData = new Dataset(); trainingData.add(Record.newDataVector(new Double[] {1.0, 0.0, 1.0, 0.0, 1.0, 0.0}, 1)); trainingData.add(Record.newDataVector(new Double[] {1.0, 0.0, 1.0, 0.0, 1.0, 0.0}, 0)); trainingData.add(Record.newDataVector(new Double[] {1.0, 0.0, 1.0, 0.0, 1.0, 0.0}, 1)); trainingData.add(Record.newDataVector(new Double[] {0.0, 1.0, 1.0, 0.0, 1.0, 0.0}, 0)); trainingData.add(Record.newDataVector(new Double[] {0.0, 1.0, 1.0, 0.0, 0.0, 1.0}, 1)); trainingData.add(Record.newDataVector(new Double[] {0.0, 1.0, 0.0, 1.0, 0.0, 1.0}, 0)); trainingData.add(Record.newDataVector(new Double[] {0.0, 1.0, 0.0, 1.0, 0.0, 1.0}, 1)); trainingData.add(Record.newDataVector(new Double[] {0.0, 1.0, 0.0, 1.0, 1.0, 0.0}, 0)); trainingData.add(Record.newDataVector(new Double[] {1.0, 0.0, 0.0, 1.0, 0.0, 1.0}, 0)); trainingData.add(Record.newDataVector(new Double[] {1.0, 0.0, 1.0, 0.0, 0.0, 1.0}, 1)); Dataset validationData = new Dataset(); validationData.add(Record.newDataVector(new Double[] {1.0, 0.0, 0.0, 1.0, 1.0, 0.0}, 0)); */ Dataset trainingData = new Dataset(); trainingData.add(Record.newDataVector(new String[] {"red", "sports", "domestic"}, "yes")); trainingData.add(Record.newDataVector(new String[] {"red", "sports", "domestic"}, "no")); trainingData.add(Record.newDataVector(new String[] {"red", "sports", "domestic"}, "yes")); trainingData.add(Record.newDataVector(new String[] {"yellow", "sports", "domestic"}, "no")); trainingData.add(Record.newDataVector(new String[] {"yellow", "sports", "imported"}, "yes")); trainingData.add(Record.newDataVector(new String[] {"yellow", "suv", "imported"}, "no")); trainingData.add(Record.newDataVector(new String[] {"yellow", "suv", "imported"}, "yes")); trainingData.add(Record.newDataVector(new String[] {"yellow", "suv", "domestic"}, "no")); trainingData.add(Record.newDataVector(new String[] {"red", "suv", "imported"}, "no")); trainingData.add(Record.newDataVector(new String[] {"red", "sports", "imported"}, "yes")); Dataset validationData = new Dataset(); validationData.add(Record.newDataVector(new String[] {"red", "suv", "domestic"}, "no")); String dbName = "JUnitClassifier"; SimpleDummyVariableExtractor df = new SimpleDummyVariableExtractor(dbName, TestUtils.getDBConfig()); df.fit_transform(trainingData, new SimpleDummyVariableExtractor.TrainingParameters()); df.transform(validationData); MultinomialNaiveBayes instance = new MultinomialNaiveBayes(dbName, TestUtils.getDBConfig()); MultinomialNaiveBayes.TrainingParameters param = new MultinomialNaiveBayes.TrainingParameters(); param.setMultiProbabilityWeighted(true); instance.fit(trainingData, param); instance = null; instance = new MultinomialNaiveBayes(dbName, TestUtils.getDBConfig()); instance.validate(validationData); df.denormalize(trainingData); df.denormalize(validationData); df.erase(); Map<Integer, Object> expResult = new HashMap<>(); Map<Integer, Object> result = new HashMap<>(); for(Record r : validationData) { expResult.put(r.getId(), r.getY()); result.put(r.getId(), r.getYPredicted()); } assertEquals(expResult, result); instance.erase(); } #location 52 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Test public void testSelectFeatures() { TestUtils.log(this.getClass(), "selectFeatures"); RandomValue.setRandomGenerator(new Random(42)); String dbName = "JUnitChisquareFeatureSelection"; TFIDF.TrainingParameters param = new TFIDF.TrainingParameters(); param.setBinarized(false); param.setMaxFeatures(3); Dataset trainingData = new Dataset(TestUtils.getDBConfig()); AssociativeArray xData1 = new AssociativeArray(); xData1.put("important1", 2.0); xData1.put("important2", 3.0); xData1.put("stopword1", 10.0); xData1.put("stopword2", 4.0); xData1.put("stopword3", 8.0); trainingData.add(new Record(xData1, null)); AssociativeArray xData2 = new AssociativeArray(); xData2.put("important1", 2.0); xData2.put("important3", 5.0); xData2.put("stopword1", 10.0); xData2.put("stopword2", 2.0); xData2.put("stopword3", 4.0); trainingData.add(new Record(xData2, null)); AssociativeArray xData3 = new AssociativeArray(); xData3.put("important2", 2.0); xData3.put("important3", 5.0); xData3.put("stopword1", 10.0); xData3.put("stopword2", 2.0); xData3.put("stopword3", 4.0); trainingData.add(new Record(xData3, null)); TFIDF instance = new TFIDF(dbName, TestUtils.getDBConfig()); instance.fit(trainingData, param); instance = null; instance = new TFIDF(dbName, TestUtils.getDBConfig()); instance.transform(trainingData); Set<Object> expResult = new HashSet<>(Arrays.asList("important1", "important2", "important3")); Set<Object> result = trainingData.getColumns().keySet(); assertEquals(expResult, result); instance.erase(); }
#vulnerable code @Test public void testSelectFeatures() { TestUtils.log(this.getClass(), "selectFeatures"); RandomValue.setRandomGenerator(new Random(42)); String dbName = "JUnitChisquareFeatureSelection"; TFIDF.TrainingParameters param = new TFIDF.TrainingParameters(); param.setBinarized(false); param.setMaxFeatures(3); Dataset trainingData = new Dataset(); AssociativeArray xData1 = new AssociativeArray(); xData1.put("important1", 2.0); xData1.put("important2", 3.0); xData1.put("stopword1", 10.0); xData1.put("stopword2", 4.0); xData1.put("stopword3", 8.0); trainingData.add(new Record(xData1, null)); AssociativeArray xData2 = new AssociativeArray(); xData2.put("important1", 2.0); xData2.put("important3", 5.0); xData2.put("stopword1", 10.0); xData2.put("stopword2", 2.0); xData2.put("stopword3", 4.0); trainingData.add(new Record(xData2, null)); AssociativeArray xData3 = new AssociativeArray(); xData3.put("important2", 2.0); xData3.put("important3", 5.0); xData3.put("stopword1", 10.0); xData3.put("stopword2", 2.0); xData3.put("stopword3", 4.0); trainingData.add(new Record(xData3, null)); TFIDF instance = new TFIDF(dbName, TestUtils.getDBConfig()); instance.fit(trainingData, param); instance = null; instance = new TFIDF(dbName, TestUtils.getDBConfig()); instance.transform(trainingData); Set<Object> expResult = new HashSet<>(Arrays.asList("important1", "important2", "important3")); Set<Object> result = trainingData.getColumns().keySet(); assertEquals(expResult, result); instance.erase(); } #location 40 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code private double calculateError(Dataframe trainingData, Map<List<Object>, Double> thitas) { //The cost function as described on http://ufldl.stanford.edu/wiki/index.php/Softmax_Regression //It is optimized for speed to reduce the amount of loops double error = StreamMethods.stream(trainingData.stream(), isParallelized()).mapToDouble(r -> { AssociativeArray classProbabilities = hypothesisFunction(r.getX(), thitas); Double score = classProbabilities.getDouble(r.getY()); return Math.log(score); //no need to loop through the categories. Just grab the one that we are interested in }).sum(); return -error/kb().getModelParameters().getN(); }
#vulnerable code private double calculateError(Dataframe trainingData, Map<List<Object>, Double> thitas) { //The cost function as described on http://ufldl.stanford.edu/wiki/index.php/Softmax_Regression //It is optimized for speed to reduce the amount of loops double error=0.0; for(Record r : trainingData) { AssociativeArray classProbabilities = hypothesisFunction(r.getX(), thitas); Double score = classProbabilities.getDouble(r.getY()); error+=Math.log(score); //no need to loop through the categories. Just grab the one that we are interested in } return -error/kb().getModelParameters().getN(); } #location 9 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Override protected void predictDataset(Dataframe newData) { _predictDataset(newData, false); }
#vulnerable code @Override protected void predictDataset(Dataframe newData) { Map<List<Object>, Double> similarities = knowledgeBase.getModelParameters().getSimilarities(); //generate recommendation for each record in the list for(Map.Entry<Integer, Record> e : newData.entries()) { Integer rId = e.getKey(); Record r = e.getValue(); Map<Object, Object> recommendations = new HashMap<>(); Map<Object, Double> simSums = new HashMap<>(); for(Map.Entry<Object, Object> entry : r.getX().entrySet()) { Object row = entry.getKey(); Double score = TypeInference.toDouble(entry.getValue()); //Since we can't use 2D Maps due to mongo, we are forced to loop //the whole similarities map which is very inefficient. for(Map.Entry<List<Object>, Double> entry2 : similarities.entrySet()) { List<Object> tpk = entry2.getKey(); if(!tpk.get(0).equals(row)) { continue; //filter the irrelevant two pair key combinations that do not include the row } Object column = tpk.get(1); if(r.getX().containsKey(column)) { continue; // they already rated this } Double previousRecValue = TypeInference.toDouble(recommendations.get(column)); Double previousSimsumValue = simSums.get(column); if(previousRecValue==null) { previousRecValue=0.0; previousSimsumValue=0.0; } Double similarity = entry2.getValue(); recommendations.put(column, previousRecValue+similarity*score); simSums.put(column, previousSimsumValue+similarity); } } for(Map.Entry<Object, Object> entry : recommendations.entrySet()) { Object column = entry.getKey(); Double score = TypeInference.toDouble(entry.getValue()); recommendations.put(column, score/simSums.get(column)); } simSums = null; if(!recommendations.isEmpty()) { //sort recommendation by popularity recommendations = MapFunctions.sortNumberMapByValueDescending(recommendations); newData._unsafe_set(rId, new Record(r.getX(), r.getY(), recommendations.keySet().iterator().next(), new AssociativeArray(recommendations))); } } } #location 12 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public static double median(AssociativeArray2D survivalFunction) { Double ApointTi = null; Double BpointTi = null; int n = survivalFunction.size(); if(n==0) { throw new IllegalArgumentException("The provided collection can't be empty."); } for(Map.Entry<Object, AssociativeArray> entry : survivalFunction.entrySet()) { Object ti = entry.getKey(); AssociativeArray row = entry.getValue(); Double Sti = row.getDouble("Sti"); if(Sti==null) { continue; //skip censored } Double point = Double.valueOf(ti.toString()); if(Math.abs(Sti-0.5) < 0.0000001) { return point; //we found extactly the point } else if(Sti>0.5) { ApointTi=point; //keep the point just before the 0.5 probability } else { BpointTi=point; //keep the first point after the 0.5 probability and exit loop break; } } if(n==1) { return (ApointTi!=null)?ApointTi:BpointTi; } else if(ApointTi == null || BpointTi == null) { throw new IllegalArgumentException("Invalid A and B points."); //we should never get here } double ApointTiValue = TypeInference.toDouble(survivalFunction.get2d(ApointTi.toString(), "Sti")); double BpointTiValue = TypeInference.toDouble(survivalFunction.get2d(BpointTi.toString(), "Sti")); double median=BpointTi-(BpointTiValue-0.5)*(BpointTi-ApointTi)/(BpointTiValue-ApointTiValue); return median; }
#vulnerable code public static double median(AssociativeArray2D survivalFunction) { Double ApointTi = null; Double BpointTi = null; int n = survivalFunction.size(); if(n==0) { throw new IllegalArgumentException("The provided collection can't be empty."); } for(Map.Entry<Object, AssociativeArray> entry : survivalFunction.entrySet()) { Object ti = entry.getKey(); AssociativeArray row = entry.getValue(); Double Sti = row.getDouble("Sti"); if(Sti==null) { continue; //skip censored } Double point = Double.valueOf(ti.toString()); if(Sti==0.5) { return point; //we found extactly the point } else if(Sti>0.5) { ApointTi=point; //keep the point just before the 0.5 probability } else { BpointTi=point; //keep the first point after the 0.5 probability and exit loop break; } } if(n==1) { return (ApointTi!=null)?ApointTi:BpointTi; } else if(ApointTi == null || BpointTi == null) { throw new IllegalArgumentException("Invalid A and B points."); //we should never get here } double ApointTiValue = TypeInference.toDouble(survivalFunction.get2d(ApointTi.toString(), "Sti")); double BpointTiValue = TypeInference.toDouble(survivalFunction.get2d(BpointTi.toString(), "Sti")); double median=BpointTi-(BpointTiValue-0.5)*(BpointTi-ApointTi)/(BpointTiValue-ApointTiValue); return median; } #location 34 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code protected static void denormalizeX(Dataset data, Map<Object, Double> minColumnValues, Map<Object, Double> maxColumnValues) { for(Integer rId : data) { Record r = data.get(rId); AssociativeArray xData = new AssociativeArray(r.getX()); for(Object column : minColumnValues.keySet()) { Double value = xData.getDouble(column); if(value==null) { //if we have a missing value don't perform any denormalization continue; } Double min = minColumnValues.get(column); Double max = maxColumnValues.get(column); if(min.equals(max)) { xData.put(column, min); } else { xData.put(column, value*(max-min) + min); } } r = new Record(xData, r.getY(), r.getYPredicted(), r.getYPredictedProbabilities()); data.set(rId, r); } }
#vulnerable code protected static void denormalizeX(Dataset data, Map<Object, Double> minColumnValues, Map<Object, Double> maxColumnValues) { for(Integer rId : data) { Record r = data.get(rId); for(Object column : minColumnValues.keySet()) { Double value = r.getX().getDouble(column); if(value==null) { //if we have a missing value don't perform any denormalization continue; } Double min = minColumnValues.get(column); Double max = maxColumnValues.get(column); if(min.equals(max)) { r.getX().put(column, min); } else { r.getX().put(column, value*(max-min) + min); } } //do nothing for the response variable Y } } #location 5 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code protected static void extractDummies(Dataset data, Map<Object, Object> referenceLevels) { Map<Object, Dataset.ColumnType> columnTypes = data.getColumns(); if(referenceLevels.isEmpty()) { //Training Mode //find the referenceLevels for each categorical variable for(Integer rId: data) { Record r = data.get(rId); for(Map.Entry<Object, Object> entry: r.getX().entrySet()) { Object column = entry.getKey(); if(referenceLevels.containsKey(column)==false) { //already set? if(covert2dummy(columnTypes.get(column))==false) { continue; //only ordinal and categorical are converted into dummyvars } Object value = entry.getValue(); referenceLevels.put(column, value); } } } } //Replace variables with dummy versions for(Integer rId: data) { Record r = data.get(rId); AssociativeArray xData = new AssociativeArray(); xData.putAll(r.getX()); boolean modified = false; for(Object column : r.getX().keySet()) { if(covert2dummy(columnTypes.get(column))==false) { continue; } Object value = xData.get(column); xData.remove(column); //remove the original column modified = true; Object referenceLevel= referenceLevels.get(column); if(referenceLevel != null && //not unknown variable !referenceLevel.equals(value)) { //not equal to reference level //create a new column List<Object> newColumn = Arrays.<Object>asList(column,value); //add a new dummy variable for this column-value combination xData.put(newColumn, true); } } if(modified) { r = new Record(xData, r.getY(), r.getYPredicted(), r.getYPredictedProbabilities()); data.set(rId, r); } } //Reset Meta info data.resetMeta(); }
#vulnerable code protected static void extractDummies(Dataset data, Map<Object, Object> referenceLevels) { Map<Object, Dataset.ColumnType> columnTypes = data.getColumns(); if(referenceLevels.isEmpty()) { //Training Mode //find the referenceLevels for each categorical variable for(Integer rId: data) { Record r = data.get(rId); for(Map.Entry<Object, Object> entry: r.getX().entrySet()) { Object column = entry.getKey(); if(referenceLevels.containsKey(column)==false) { //already set? if(covert2dummy(columnTypes.get(column))==false) { continue; //only ordinal and categorical are converted into dummyvars } Object value = entry.getValue(); referenceLevels.put(column, value); } } } } //Replace variables with dummy versions for(Integer rId: data) { Record r = data.get(rId); Set<Object> columns = new HashSet<>(r.getX().keySet()); //TODO: remove this once we make Record immutable for(Object column : columns) { if(covert2dummy(columnTypes.get(column))==false) { continue; } Object value = r.getX().get(column); r.getX().remove(column); //remove the original column Object referenceLevel= referenceLevels.get(column); if(referenceLevel != null && //not unknown variable !referenceLevel.equals(value)) { //not equal to reference level //create a new column List<Object> newColumn = Arrays.<Object>asList(column,value); //add a new dummy variable for this column-value combination r.getX().put(newColumn, true); } } } //Reset Meta info data.resetMeta(); } #location 26 #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) { final JFrame frame = new JFrame(); final Provider provider = Provider.getCurrentProvider(true); final JTextField textField = new JTextField(); textField.setEditable(false); textField.addKeyListener(new KeyAdapter() { @Override public void keyPressed(KeyEvent e) { if (MODIFIERS.contains(e.getKeyCode())) textField.setText(""); else textField.setText(KeyStroke.getKeyStrokeForEvent(e).toString().replaceAll("pressed ", "")); } }); frame.add(textField, BorderLayout.CENTER); JPanel box = new JPanel(new GridLayout(2, 1)); JButton grab = new JButton("Grab"); box.add(grab); final HotKeyListener listener = new HotKeyListener() { public void onHotKey(final HotKey hotKey) { JOptionPane.showMessageDialog(frame, "Hooray: " + hotKey); } }; grab.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { String text = textField.getText(); if (text != null && text.length() > 0) { provider.reset(); provider.register(KeyStroke.getKeyStroke(text), listener); } } }); JButton grabMedia = new JButton("Grab media keys"); grabMedia.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { provider.register(MediaKey.MEDIA_NEXT_TRACK, listener); provider.register(MediaKey.MEDIA_PLAY_PAUSE, listener); provider.register(MediaKey.MEDIA_PREV_TRACK, listener); provider.register(MediaKey.MEDIA_STOP, listener); } }); box.add(grabMedia); frame.add(box, BorderLayout.PAGE_END); frame.addWindowListener(new WindowAdapter() { @Override public void windowClosing(WindowEvent e) { provider.reset(); provider.stop(); System.exit(0); } }); frame.setSize(300, 150); frame.setLocationRelativeTo(null); frame.setVisible(true); }
#vulnerable code public static void main(String[] args) { final JFrame frame = new JFrame(); final Provider provider = Provider.getCurrentProvider(); provider.init(); final JTextField textField = new JTextField(); textField.setEditable(false); textField.addKeyListener(new KeyAdapter() { @Override public void keyPressed(KeyEvent e) { if (MODIFIERS.contains(e.getKeyCode())) textField.setText(""); else textField.setText(KeyStroke.getKeyStrokeForEvent(e).toString().replaceAll("pressed ", "")); } }); frame.add(textField, BorderLayout.CENTER); JPanel box = new JPanel(new GridLayout(2, 1)); JButton grab = new JButton("Grab"); box.add(grab); final HotKeyListener listener = new HotKeyListener() { public void onHotKey(final HotKey hotKey) { SwingUtilities.invokeLater(new Runnable() { public void run() { JOptionPane.showMessageDialog(frame, "Hooray: " + hotKey); } }); } }; grab.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { String text = textField.getText(); if (text != null && text.length() > 0) { provider.reset(); provider.register(KeyStroke.getKeyStroke(text), listener); } } }); JButton grabMedia = new JButton("Grab media keys"); grabMedia.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { provider.register(MediaKey.MEDIA_NEXT_TRACK, listener); provider.register(MediaKey.MEDIA_PLAY_PAUSE, listener); provider.register(MediaKey.MEDIA_PREV_TRACK, listener); provider.register(MediaKey.MEDIA_STOP, listener); } }); box.add(grabMedia); frame.add(box, BorderLayout.PAGE_END); frame.addWindowListener(new WindowAdapter() { @Override public void windowClosing(WindowEvent e) { provider.reset(); provider.stop(); System.exit(0); } }); frame.setSize(300, 150); frame.setLocationRelativeTo(null); frame.setVisible(true); } #location 5 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public CHConnection connect(String url, CHProperties properties) throws SQLException { logger.info("Creating connection"); CHConnectionImpl connection = new CHConnectionImpl(url, properties); connections.put(connection, true); return LogProxy.wrap(CHConnection.class, connection); }
#vulnerable code public CHConnection connect(String url, CHProperties properties) throws SQLException { logger.info("Creating connection"); return LogProxy.wrap(CHConnection.class, new CHConnectionImpl(url, properties)); } #location 3 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Override protected void saveMetadata() { commandFactory.createContainerMetadataCommand(getAccount(), getClient(), getAccess(), this, info.getMetadata()).call(); }
#vulnerable code @Override protected void saveMetadata() { new ContainerMetadataCommand(getAccount(), getClient(), getAccess(), this, info.getMetadata()).call(); } #location 3 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public void delete() { commandFactory.createDeleteContainerCommand(getAccount(), getClient(), getAccess(), this).call(); }
#vulnerable code public void delete() { new DeleteContainerCommand(getAccount(), getClient(), getAccess(), this).call(); } #location 2 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Test (expected = CommandException.class ) public void getSegmentationPlanThrowsIOException() throws Exception { new Expectations() { @Mocked UploadPayloadFile uploadPayload; { new UploadPayloadFile(null); result = uploadPayload; uploadPayload.getSegmentationPlan(anyLong); result = new IOException(); }}; UploadInstructions instructions = new UploadInstructions((File)null); instructions.getSegmentationPlan(); }
#vulnerable code @Test (expected = CommandException.class ) public void getSegmentationPlanThrowsIOException() throws Exception { UploadPayloadFile uploadPayload = mock(UploadPayloadFile.class); whenNew(UploadPayloadFile.class).withArguments(null).thenReturn(uploadPayload); when(uploadPayload.getSegmentationPlan(anyLong())).thenThrow(new IOException()); UploadInstructions instructions = new UploadInstructions((File)null); instructions.getSegmentationPlan(); } #location 5 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Test public void pushAndUpdate() throws IOException, URISyntaxException { Swift swift = new Swift() .setOnFileObjectStore("websites", false); website = new WebsiteMock(new AccountMock(swift), "website"); website.pushDirectory(FileAction.getFile("websites/website")); assertEquals(7, website.list().size()); website.pushDirectory(FileAction.getFile("websites/website2")); assertEquals(6, website.list().size()); }
#vulnerable code @Test public void pushAndUpdate() throws IOException, URISyntaxException { Swift swift = new Swift() .setOnFileObjectStore("websites"); website = new WebsiteMock(new AccountMock(swift), "website"); website.pushDirectory(FileAction.getFile("websites/website")); assertEquals(7, website.list().size()); website.pushDirectory(FileAction.getFile("websites/website2")); assertEquals(6, website.list().size()); } #location 8 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code protected void getInfo() { this.info = new AccountInformationCommand(this, httpClient, access).call(); this.setInfoRetrieved(); }
#vulnerable code protected void getInfo() { AccountInformation info = new AccountInformationCommand(this, httpClient, access).call(); this.bytesUsed = info.getBytesUsed(); this.containerCount = info.getContainerCount(); this.objectCount = info.getObjectCount(); this.setMetadata(info.getMetadata()); this.setInfoRetrieved(); } #location 3 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public Container create() { commandFactory.createCreateContainerCommand(getAccount(), getClient(), getAccess(), this).call(); return this; }
#vulnerable code public Container create() { new CreateContainerCommand(getAccount(), getClient(), getAccess(), this).call(); return this; } #location 2 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code protected void getInfo() { this.info = commandFactory.createContainerInformationCommand(getAccount(), getClient(), getAccess(), this).call(); this.setInfoRetrieved(); }
#vulnerable code protected void getInfo() { this.info = new ContainerInformationCommand(getAccount(), getClient(), getAccess(), this).call(); this.setInfoRetrieved(); } #location 2 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @SuppressWarnings("ConstantConditions") @Test public void pullWebsite() throws IOException, URISyntaxException { Swift swift = new Swift() .setOnFileObjectStore("websites", false); website = new WebsiteMock(new AccountMock(swift), "website"); website.pullDirectory(this.writeDir); assertEquals(5, writeDir.listFiles().length); }
#vulnerable code @SuppressWarnings("ConstantConditions") @Test public void pullWebsite() throws IOException, URISyntaxException { Swift swift = new Swift() .setOnFileObjectStore("websites"); website = new WebsiteMock(new AccountMock(swift), "website"); website.pullDirectory(this.writeDir); assertEquals(5, writeDir.listFiles().length); } #location 8 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public void delete() { commandFactory.createDeleteObjectCommand(getAccount(), getClient(), getAccess(), this).call(); }
#vulnerable code public void delete() { new DeleteObjectCommand(getAccount(), getClient(), getAccess(), this).call(); } #location 2 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Test (expected = CommandException.class) public void unknownError() throws IOException { checkForError(500, new ContainerInformationCommandImpl(this.account, httpClient, defaultAccess, account.getContainer("containerName"))); }
#vulnerable code @Test (expected = CommandException.class) public void unknownError() throws IOException { checkForError(500, new ContainerInformationCommand(this.account, httpClient, defaultAccess, account.getContainer("containerName"))); } #location 3 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @SuppressWarnings("ConstantConditions") @Test public void pullDifferentWebsites() throws IOException, URISyntaxException { Swift swift = new Swift() .setOnFileObjectStore("object-store", false); website = new WebsiteMock(new AccountMock(swift), "container1"); website.pullDirectory(this.writeDir); assertEquals(2, writeDir.listFiles().length); // 2 files website = new WebsiteMock(new AccountMock(swift), "container2"); website.pullDirectory(this.writeDir); assertEquals(5, writeDir.listFiles().length); // 5 files }
#vulnerable code @SuppressWarnings("ConstantConditions") @Test public void pullDifferentWebsites() throws IOException, URISyntaxException { Swift swift = new Swift() .setOnFileObjectStore("object-store"); website = new WebsiteMock(new AccountMock(swift), "container1"); website.pullDirectory(this.writeDir); assertEquals(2, writeDir.listFiles().length); // 2 files website = new WebsiteMock(new AccountMock(swift), "container2"); website.pullDirectory(this.writeDir); assertEquals(5, writeDir.listFiles().length); // 5 files } #location 8 #vulnerability type NULL_DEREFERENCE