output
stringlengths
79
30.1k
instruction
stringclasses
1 value
input
stringlengths
216
28.9k
#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(); }
Below is the vulnerable code, please generate the patch based on the following information.
#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
#fixed code private static int spawnPacket(Location loc) throws Exception { Object world = Reflections.getHandle(loc.getWorld()); Object crystal = enderCrystalConstructor.newInstance(world); setLocation.invoke(crystal, loc.getX(), loc.getY(), loc.getZ(), 0, 0); Object packet = spawnEntityConstructor.newInstance(crystal, 51); int id = (int) getId.invoke(crystal); ids.put(id, packet); return id; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code private static int spawnPacket(Location loc) throws Exception { Object world = Reflections.getHandle(loc.getWorld()); Object crystal = enderCrystalClass.getConstructor(Reflections.getCraftClass("World")).newInstance(world); Reflections.getMethod(enderCrystalClass, "setLocation", double.class, double.class, double.class, float.class, float.class).invoke(crystal, loc.getX(), loc.getY(), loc.getZ(), 0, 0); Object packet = spawnEntityClass.getConstructor(new Class<?>[]{entityClass, int.class}).newInstance(crystal, 51); int id = (int) Reflections.getMethod(enderCrystalClass, "getId").invoke(crystal); ids.put(id, packet); return id; } #location 6 #vulnerability type NULL_DEREFERENCE
#fixed code @EventHandler public void onJoin(PlayerJoinEvent e) { Player player = e.getPlayer(); User user = User.get(player); if (user == null) { user = User.create(player); } else { if (! user.getName().equals(player.getName())) { user.setName(player.getName()); } } user.updateReference(player); PluginConfiguration config = FunnyGuilds.getInstance().getPluginConfiguration(); if (config.playerListEnable && ! AbstractTablist.hasTablist(player)) { AbstractTablist.createTablist(config.playerList, config.playerListHeader, config.playerListFooter, config.playerListPing, player); } UserCache cache = user.getCache(); if (cache.getScoreboard() == null) { cache.setScoreboard(Bukkit.getScoreboardManager().getNewScoreboard()); } if (cache.getIndividualPrefix() == null && config.guildTagEnabled) { IndividualPrefix prefix = new IndividualPrefix(user); prefix.initialize(); cache.setIndividualPrefix(prefix); } ConcurrencyManager concurrencyManager = FunnyGuilds.getInstance().getConcurrencyManager(); concurrencyManager.postRequests( new PrefixGlobalUpdatePlayer(player), new DummyGlobalUpdateUserRequest(user), new RankUpdateUserRequest(user) ); this.plugin.getServer().getScheduler().runTaskLaterAsynchronously(this.plugin, () -> { PacketExtension.registerPlayer(player); FunnyGuildsVersion.isNewAvailable(player, false); Region region = RegionUtils.getAt(player.getLocation()); if (region == null || region.getGuild() == null) { return; } if (config.createEntityType != null) { GuildEntityHelper.spawnGuildHeart(region.getGuild(), player); } }, 30L); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @EventHandler public void onJoin(PlayerJoinEvent e) { Player player = e.getPlayer(); User user = User.get(player); if (user == null) { user = User.create(player); } user.updateReference(player); PluginConfiguration config = FunnyGuilds.getInstance().getPluginConfiguration(); if (config.playerListEnable && ! AbstractTablist.hasTablist(player)) { AbstractTablist.createTablist(config.playerList, config.playerListHeader, config.playerListFooter, config.playerListPing, player); } UserCache cache = user.getCache(); if (cache.getScoreboard() == null) { cache.setScoreboard(Bukkit.getScoreboardManager().getNewScoreboard()); } if (cache.getIndividualPrefix() == null && config.guildTagEnabled) { IndividualPrefix prefix = new IndividualPrefix(user); prefix.initialize(); cache.setIndividualPrefix(prefix); } ConcurrencyManager concurrencyManager = FunnyGuilds.getInstance().getConcurrencyManager(); concurrencyManager.postRequests( new PrefixGlobalUpdatePlayer(player), new DummyGlobalUpdateUserRequest(user), new RankUpdateUserRequest(user) ); this.plugin.getServer().getScheduler().runTaskLaterAsynchronously(this.plugin, () -> { PacketExtension.registerPlayer(player); FunnyGuildsVersion.isNewAvailable(player, false); Region region = RegionUtils.getAt(player.getLocation()); if (region == null || region.getGuild() == null) { return; } if (config.createEntityType != null) { GuildEntityHelper.spawnGuildHeart(region.getGuild(), player); } }, 30L); } #location 19 #vulnerability type NULL_DEREFERENCE
#fixed code private void sendMessageToGuild(Guild guild, Player player, String message) { for (User user : guild.getOnlineMembers()) { Player p = user.getPlayer(); if(!p.equals(player) || !user.isSpy()) { p.sendMessage(message); } } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code private void sendMessageToGuild(Guild guild, Player player, String message) { for (User user : guild.getMembers()) { Player loopedPlayer = this.plugin.getServer().getPlayer(user.getName()); if (loopedPlayer != null) { if (user.getPlayer().equals(player)) { if (!user.isSpy()) { loopedPlayer.sendMessage(message); } } else { loopedPlayer.sendMessage(message); } } } } #location 5 #vulnerability type NULL_DEREFERENCE
#fixed code private static List<String> getWorldGuardRegionNames(User user) { if (user == null || user.getPlayer() == null) { return Collections.emptyList(); } Location location = user.getPlayer().getLocation(); if (location != null) { List<String> regionNames = WorldGuardHook.getRegionNames(location); if (regionNames != null && !regionNames.isEmpty()) { return regionNames; } } return null; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code private static List<String> getWorldGuardRegionNames(User user) { Location location = user.getPlayer().getLocation(); if (location != null) { List<String> regionNames = WorldGuardHook.getRegionNames(location); if (regionNames != null && !regionNames.isEmpty()) { return regionNames; } } return null; } #location 2 #vulnerability type NULL_DEREFERENCE
#fixed code @Override public boolean isInNonPointsRegion(Location location) { ApplicableRegionSet regionSet = getRegionSet(location); if (regionSet == null) { return false; } for (ProtectedRegion region : regionSet) { if (region.getFlag(noPointsFlag) == StateFlag.State.ALLOW) { return true; } } return false; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Override public boolean isInNonPointsRegion(Location location) { if (! isInRegion(location)) { return false; } for (ProtectedRegion region : getRegionSet(location)) { if (region.getFlag(noPointsFlag) == StateFlag.State.ALLOW) { return true; } } return false; } #location 7 #vulnerability type NULL_DEREFERENCE
#fixed code @Test public void testBasicPreemptiveAuthHeader() throws Exception { final HttpClientBuilder client = HttpClientBuilder.create(); client.addInterceptorFirst(new HttpRequestInterceptor() { public void process(final HttpRequest r, final HttpContext context) throws HttpException, IOException { assertNotNull(r.getHeaders(HttpHeaders.AUTHORIZATION)); assertEquals(1, r.getHeaders(HttpHeaders.AUTHORIZATION).length); } }); Sardine sardine = new SardineImpl(client); sardine.setCredentials("anonymous", null); // mod_dav supports Range headers for PUT final URI url = URI.create("http://sardine.googlecode.com/svn/trunk/README.html"); sardine.enablePreemptiveAuthentication(url.getHost()); assertTrue(sardine.exists(url.toString())); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void testBasicPreemptiveAuthHeader() throws Exception { final DefaultHttpClient client = new DefaultHttpClient(); client.addRequestInterceptor(new HttpRequestInterceptor() { public void process(final HttpRequest r, final HttpContext context) throws HttpException, IOException { assertNotNull(r.getHeaders(HttpHeaders.AUTHORIZATION)); assertEquals(1, r.getHeaders(HttpHeaders.AUTHORIZATION).length); client.removeRequestInterceptorByClass(this.getClass()); } }); Sardine sardine = new SardineImpl(client); sardine.setCredentials("anonymous", null); // mod_dav supports Range headers for PUT final URI url = URI.create("http://sardine.googlecode.com/svn/trunk/README.html"); sardine.enablePreemptiveAuthentication(url.getHost()); assertTrue(sardine.exists(url.toString())); } #location 19 #vulnerability type RESOURCE_LEAK
#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); } } }
Below is the vulnerable code, please generate the patch based on the following information.
#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 25 #vulnerability type RESOURCE_LEAK
#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(); } }
Below is the vulnerable code, please generate the patch based on the following information.
#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
#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; }
Below is the vulnerable code, please generate the patch based on the following information.
#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
#fixed code @Test public void shouldPrintScoresFourToALine() { final String[] ss = generateReportLines(); assertEquals("> KILLED 0 SURVIVED 0 TIMED_OUT 0 NON_VIABLE 0 ", ss[2]); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void shouldPrintScoresFourToALine() { final ByteArrayOutputStream s = new ByteArrayOutputStream(); final PrintStream out = new PrintStream(s); this.testee.report(out); final String actual = new String(s.toByteArray()); final String[] ss = actual.split(StringUtil.newLine()); assertEquals("> foo", ss[0]); assertEquals("> KILLED 0 SURVIVED 0 TIMED_OUT 0 NON_VIABLE 0 ", ss[1]); } #location 5 #vulnerability type RESOURCE_LEAK
#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); } }
Below is the vulnerable code, please generate the patch based on the following information.
#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 17 #vulnerability type RESOURCE_LEAK
#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); } } } }
Below is the vulnerable code, please generate the patch based on the following information.
#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
#fixed code private String getPortForwardUrl(final Set<HasMetadata> resources) throws Exception { LabelSelector selector = KubernetesResourceUtil.getPodLabelSelector(resources); if (selector == null) { log.warn("Unable to determine a selector for application pods"); return null; } PortForwardService portForwardService = getContext().getFabric8ServiceHub().getPortForwardService(); int port = IoUtil.getFreeRandomPort(); portForwardService.forwardPortAsync(getContext().getLogger(), selector, 8080, port); return "http://localhost:" + port; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code private String getPortForwardUrl(final Set<HasMetadata> resources) throws Exception { LabelSelector selector = KubernetesResourceUtil.getPodLabelSelector(resources); if (selector == null) { log.warn("Unable to determine a selector for application pods"); return null; } PortForwardService portForwardService = getContext().getFabric8ServiceHub().getPortForwardService(); // TODO choose the right ports portForwardService.forwardPortAsync(getContext().getLogger(), selector, 8080, 20000); return "http://localhost:20000"; } #location 10 #vulnerability type RESOURCE_LEAK
#fixed code @Override public void execute(final JobDetail jobDetail, JobTriggerType triggerType, JobExecutionContext context) { final String appName = jobDetail.getApp().getAppName(); final String jobClass = jobDetail.getJob().getClazz(); JobInstance instance = null; try { Logs.info("The job({}/{}) is fired.", appName, jobClass); if (triggerType == JobTriggerType.DEFAULT){ // refresh the job fire time if triggered by scheduler asyncExecutor.submit(new RefreshJobFireTimeTask(appName, jobClass, context)); } if (!canRunJobInstance(appName, jobClass)){ return; } // job is running jobSupport.updateJobStateDirectly(appName, jobClass, JobState.RUNNING); // create the job instance and shards instance = createInstanceAndShards(jobDetail, triggerType); // trigger the clients to pull shards jobSupport.triggerJobInstance(appName, jobClass, instance); // blocking until all shards to be finished or timeout Long timeout = jobDetail.getConfig().getTimeout(); timeout = timeout == null ? 0L : timeout; JobInstanceWaitResp finishResp = jobSupport.waitingJobInstanceFinish(appName, jobClass, instance.getId(), timeout); if (finishResp.isSuccess()){ // job instance is finished successfully // publish job finish event eventDispatcher.publish(new JobFinishedEvent(instance.getJobId(), instance.getId())); } else if (finishResp.isTimeout()){ // job instance is timeout eventDispatcher.publish(new JobTimeoutEvent(instance.getJobId(), instance.getId(), buildJobTimeoutDetail(instance))); } // maybe now the job is paused, stopped, ..., so need to expect the job state jobSupport.updateJobStateSafely(appName, jobClass, JobState.WAITING); // job has finished } catch (JobStateTransferInvalidException e){ // job state transfer error Logs.warn("failed to update job state(instances={}), cause: {}.", instance, e.toString()); } catch (JobInstanceCreateException e){ // handle when job instance create failed String cause = Throwables.getStackTraceAsString(e); Logs.error("failed to create job instance when execute job(jobDetail={}, instance={}), cause: {}", jobDetail, instance, cause); handleJobExecuteFailed(jobDetail, instance, appName, jobClass, cause); } catch (Exception e){ // handle other exceptions String cause = Throwables.getStackTraceAsString(e); Logs.error("failed to execute job(jobDetail={}, instance={}), cause: {}", jobDetail, instance, cause); handleJobExecuteFailed(jobDetail, instance, appName, jobClass, cause); } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Override public void execute(final JobDetail jobDetail, JobTriggerType triggerType, JobExecutionContext context) { final String appName = jobDetail.getApp().getAppName(); final String jobClass = jobDetail.getJob().getClazz(); JobInstance instance = null; try { Logs.info("The job({}/{}) is fired.", appName, jobClass); if (triggerType == JobTriggerType.DEFAULT){ // refresh the job fire time if triggered by scheduler asyncExecutor.submit(new RefreshJobFireTimeTask(appName, jobClass, context)); } if (!canRunJobInstance(appName, jobClass)){ return; } // job is running jobSupport.updateJobStateDirectly(appName, jobClass, JobState.RUNNING); // create the job instance and shards instance = createInstanceAndShards(jobDetail, triggerType); // trigger the clients to pull shards jobSupport.triggerJobInstance(appName, jobClass, instance); // blocking until all shards to be finished or timeout Long timeout = jobDetail.getConfig().getTimeout(); timeout = timeout == null ? 0L : timeout; JobInstanceWaitResp finishResp = jobSupport.waitingJobInstanceFinish(appName, jobClass, timeout, instance.getId()); if (finishResp.isSuccess()){ // job instance is finished successfully // publish job finish event eventDispatcher.publish(new JobFinishedEvent(instance.getJobId(), instance.getId())); } else if (finishResp.isTimeout()){ // job instance is timeout eventDispatcher.publish(new JobTimeoutEvent(instance.getJobId(), instance.getId(), buildJobTimeoutDetail(instance))); } // maybe now the job is paused, stopped, ..., so need to expect the job state jobSupport.updateJobStateSafely(appName, jobClass, JobState.WAITING); // job has finished } catch (JobStateTransferInvalidException e){ // job state transfer error Logs.warn("failed to update job state(instances={}), cause: {}.", instance, e.toString()); } catch (JobInstanceCreateException e){ // handle when job instance create failed String cause = Throwables.getStackTraceAsString(e); Logs.error("failed to create job instance when execute job(jobDetail={}, instance={}), cause: {}", jobDetail, instance, cause); handleJobExecuteFailed(jobDetail, instance, appName, jobClass, cause); } catch (Exception e){ // handle other exceptions String cause = Throwables.getStackTraceAsString(e); Logs.error("failed to execute job(jobDetail={}, instance={}), cause: {}", jobDetail, instance, cause); handleJobExecuteFailed(jobDetail, instance, appName, jobClass, cause); } } #location 33 #vulnerability type NULL_DEREFERENCE
#fixed code @Test public void testTrainAndValidate() { TestUtils.log(this.getClass(), "testTrainAndValidate"); RandomValue.setRandomGenerator(new Random(TestConfiguration.RANDOM_SEED)); DatabaseConfiguration dbConf = TestUtils.getDBConfig(); Dataset[] data = Datasets.carsNumeric(dbConf); Dataset trainingData = data[0]; Dataset newData = data[1]; String dbName = "JUnit"; Modeler instance = new Modeler(dbName, dbConf); Modeler.TrainingParameters trainingParameters = new Modeler.TrainingParameters(); trainingParameters.setkFolds(5); //Model Configuration trainingParameters.setMLmodelClass(MultinomialNaiveBayes.class); MultinomialNaiveBayes.TrainingParameters modelTrainingParameters = new MultinomialNaiveBayes.TrainingParameters(); modelTrainingParameters.setMultiProbabilityWeighted(true); trainingParameters.setMLmodelTrainingParameters(modelTrainingParameters); //data transfomation configuration trainingParameters.setDataTransformerClass(DummyXMinMaxNormalizer.class); DummyXMinMaxNormalizer.TrainingParameters dtParams = new DummyXMinMaxNormalizer.TrainingParameters(); trainingParameters.setDataTransformerTrainingParameters(dtParams); //feature selection configuration trainingParameters.setFeatureSelectionClass(null); trainingParameters.setFeatureSelectionTrainingParameters(null); instance.fit(trainingData, trainingParameters); MultinomialNaiveBayes.ValidationMetrics vm = (MultinomialNaiveBayes.ValidationMetrics) instance.validate(trainingData); double expResult2 = 0.8; assertEquals(expResult2, vm.getMacroF1(), TestConfiguration.DOUBLE_ACCURACY_HIGH); instance = null; TestUtils.log(this.getClass(), "validate"); instance = new Modeler(dbName, dbConf); instance.validate(newData); Map<Integer, Object> expResult = new HashMap<>(); Map<Integer, Object> result = new HashMap<>(); for(Integer rId : newData) { Record r = newData.get(rId); expResult.put(rId, r.getY()); result.put(rId, r.getYPredicted()); } assertEquals(expResult, result); instance.erase(); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void testTrainAndValidate() { TestUtils.log(this.getClass(), "testTrainAndValidate"); RandomValue.setRandomGenerator(new Random(TestConfiguration.RANDOM_SEED)); DatabaseConfiguration dbConf = TestUtils.getDBConfig(); Dataset trainingData = new Dataset(dbConf); 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)); 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)); 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)); 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)); 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 newData = new Dataset(dbConf); newData.add(Record.newDataVector(new Double[] {0.0, 1.0, 0.0, 1.0, 1.0, 0.0}, 0)); String dbName = "JUnit"; Modeler instance = new Modeler(dbName, dbConf); Modeler.TrainingParameters trainingParameters = new Modeler.TrainingParameters(); trainingParameters.setkFolds(5); //Model Configuration trainingParameters.setMLmodelClass(MultinomialNaiveBayes.class); MultinomialNaiveBayes.TrainingParameters modelTrainingParameters = new MultinomialNaiveBayes.TrainingParameters(); modelTrainingParameters.setMultiProbabilityWeighted(true); trainingParameters.setMLmodelTrainingParameters(modelTrainingParameters); /* trainingParameters.setMLmodelClass(Kmeans.class); Kmeans.TrainingParameters modelTrainingParameters = new Kmeans.TrainingParameters(); modelTrainingParameters.setK(2); modelTrainingParameters.setMaxIterations(200); modelTrainingParameters.setInitMethod(Kmeans.TrainingParameters.Initialization.FORGY); modelTrainingParameters.setDistanceMethod(Kmeans.TrainingParameters.Distance.EUCLIDIAN); modelTrainingParameters.setWeighted(false); modelTrainingParameters.setCategoricalGamaMultiplier(1.0); modelTrainingParameters.setSubsetFurthestFirstcValue(2.0); trainingParameters.setMLmodelTrainingParameters(modelTrainingParameters); */ //data transfomation configuration trainingParameters.setDataTransformerClass(DummyXMinMaxNormalizer.class); DummyXMinMaxNormalizer.TrainingParameters dtParams = new DummyXMinMaxNormalizer.TrainingParameters(); trainingParameters.setDataTransformerTrainingParameters(dtParams); //feature selection configuration trainingParameters.setFeatureSelectionClass(null); trainingParameters.setFeatureSelectionTrainingParameters(null); instance.fit(trainingData, trainingParameters); MultinomialNaiveBayes.ValidationMetrics vm = (MultinomialNaiveBayes.ValidationMetrics) instance.validate(trainingData); double expResult2 = 0.8; assertEquals(expResult2, vm.getMacroF1(), TestConfiguration.DOUBLE_ACCURACY_HIGH); instance = null; TestUtils.log(this.getClass(), "validate"); instance = new Modeler(dbName, dbConf); instance.validate(newData); Map<Integer, Object> expResult = new HashMap<>(); Map<Integer, Object> result = new HashMap<>(); for(Integer rId : newData) { Record r = newData.get(rId); expResult.put(rId, r.getY()); result.put(rId, r.getYPredicted()); } assertEquals(expResult, result); instance.erase(); } #location 8 #vulnerability type NULL_DEREFERENCE
#fixed code @Override public ResultSet executeQuery(String sql) throws SQLException { String csql = clickhousifySql(sql); CountingInputStream is = getInputStream(csql); try { return new CHResultSet(properties.isCompress() ? new ClickhouseLZ4Stream(is) : is, properties.getBufferSize()); } catch (Exception e) { throw new RuntimeException(e); } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Override public ResultSet executeQuery(String sql) throws SQLException { String csql = clickhousifySql(sql, "TabSeparatedWithNamesAndTypes"); CountingInputStream is = getInputStream(csql); try { return new HttpResult(properties.isCompress() ? new ClickhouseLZ4Stream(is) : is, is, properties.getBufferSize()); } catch (Exception e) { throw new RuntimeException(e); } } #location 7 #vulnerability type RESOURCE_LEAK
#fixed code public void delete() { commandFactory.createDeleteContainerCommand(getAccount(), getClient(), getAccess(), this).call(); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public void delete() { new DeleteContainerCommand(getAccount(), getClient(), getAccess(), this).call(); } #location 2 #vulnerability type RESOURCE_LEAK
#fixed code public StoredObject setContentType(String contentType) { checkForInfo(); info.setContentType(new ObjectContentType(contentType)); commandFactory.createObjectMetadataCommand( getAccount(), getClient(), getAccess(), this, info.getHeadersIncludingHeader(info.getContentTypeHeader())).call(); return this; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public StoredObject setContentType(String contentType) { checkForInfo(); info.setContentType(new ObjectContentType(contentType)); new ObjectMetadataCommand( getAccount(), getClient(), getAccess(), this, info.getHeadersIncludingHeader(info.getContentTypeHeader())).call(); return this; } #location 6 #vulnerability type RESOURCE_LEAK
#fixed code protected void getInfo() { this.info = new ObjectInformationCommand(getAccount(), getClient(), getAccess(), getContainer(), this).call(); this.setInfoRetrieved(); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code protected void getInfo() { ObjectInformation info = new ObjectInformationCommand(getAccount(), getClient(), getAccess(), getContainer(), this).call(); this.lastModified = info.getLastModified(); this.etag = info.getEtag(); this.contentLength = info.getContentLength(); this.contentType = info.getContentType(); this.setMetadata(info.getMetadata()); this.setInfoRetrieved(); } #location 3 #vulnerability type NULL_DEREFERENCE
#fixed code public void testCreation() throws Exception { final Processor processor = new Processor(new Console() { public void println(String s) { } }, null); final File control = new File(getClass().getResource("deb/control/control").toURI()); final File archive1 = new File(getClass().getResource("deb/data.tgz").toURI()); final File archive2 = new File(getClass().getResource("deb/data.tar.bz2").toURI()); final File directory = new File(getClass().getResource("deb/data").toURI()); final DataProducer[] data = new DataProducer[] { new DataProducerArchive(archive1, null, null, null), new DataProducerArchive(archive2, null, null, null), new DataProducerDirectory(directory, null, new String[] { "**/.svn/**" }, null) }; final File deb = File.createTempFile("jdeb", ".deb"); final PackageDescriptor packageDescriptor = processor.createDeb(new File[] { control }, data, deb, "gzip"); assertTrue(packageDescriptor.isValid()); final Set filesInDeb = new HashSet(); FileInputStream in = new FileInputStream(deb); final ArInputStream ar = new ArInputStream(in); while(true) { final ArEntry arEntry = ar.getNextEntry(); if (arEntry == null) { break; } if ("data.tar.gz".equals(arEntry.getName())) { final TarInputStream tar = new TarInputStream(new GZIPInputStream(ar)); while(true) { final TarEntry tarEntry = tar.getNextEntry(); if (tarEntry == null) { break; } filesInDeb.add(tarEntry.getName()); } tar.close(); break; } for (int i = 0; i < arEntry.getLength(); i++) { ar.read(); } } in.close(); assertTrue("" + filesInDeb, filesInDeb.contains("/test/testfile")); assertTrue("" + filesInDeb, filesInDeb.contains("/test/testfile2")); assertTrue("" + filesInDeb, filesInDeb.contains("/test/testfile3")); assertTrue("Cannot delete the file " + deb, deb.delete()); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public void testCreation() throws Exception { final Processor processor = new Processor(new Console() { public void println(String s) { } }, null); final File control = new File(getClass().getResource("deb/control/control").toURI()); final File archive1 = new File(getClass().getResource("deb/data.tgz").toURI()); final File archive2 = new File(getClass().getResource("deb/data.tar.bz2").toURI()); final File directory = new File(getClass().getResource("deb/data").toURI()); final DataProducer[] data = new DataProducer[] { new DataProducerArchive(archive1, null, null, null), new DataProducerArchive(archive2, null, null, null), new DataProducerDirectory(directory, null, new String[] { "**/.svn/**" }, null) }; final File deb = File.createTempFile("jdeb", ".deb"); final PackageDescriptor packageDescriptor = processor.createDeb(new File[] { control }, data, deb, "gzip"); assertTrue(packageDescriptor.isValid()); final Set filesInDeb = new HashSet(); final ArInputStream ar = new ArInputStream(new FileInputStream(deb)); while(true) { final ArEntry arEntry = ar.getNextEntry(); if (arEntry == null) { break; } if ("data.tar.gz".equals(arEntry.getName())) { final TarInputStream tar = new TarInputStream(new GZIPInputStream(ar)); while(true) { final TarEntry tarEntry = tar.getNextEntry(); if (tarEntry == null) { break; } filesInDeb.add(tarEntry.getName()); } tar.close(); break; } for (int i = 0; i < arEntry.getLength(); i++) { ar.read(); } } assertTrue("" + filesInDeb, filesInDeb.contains("/test/testfile")); assertTrue("" + filesInDeb, filesInDeb.contains("/test/testfile2")); assertTrue("" + filesInDeb, filesInDeb.contains("/test/testfile3")); assertTrue(deb.delete()); } #location 36 #vulnerability type RESOURCE_LEAK
#fixed code public void testNoCompression() throws Exception { project.executeTarget("no-compression"); File deb = new File("target/test-classes/test.deb"); assertTrue("package not build", deb.exists()); boolean found = false; ArInputStream in = new ArInputStream(new FileInputStream(deb)); ArEntry entry; while ((entry = in.getNextEntry()) != null) { if (entry.getName().equals("data.tar")) { found = true; TarInputStream tar = new TarInputStream(new NonClosingInputStream(in)); while ((tar.getNextEntry()) != null); tar.close(); } else { // skip to the next entry long skip = entry.getLength(); while(skip > 0) { long skipped = in.skip(skip); if (skipped == -1) { throw new IOException("Failed to skip"); } skip -= skipped; } } } in.close(); assertTrue("tar file not found", found); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public void testNoCompression() throws Exception { project.executeTarget("no-compression"); File deb = new File("target/test-classes/test.deb"); assertTrue("package not build", deb.exists()); boolean found = false; ArInputStream in = new ArInputStream(new FileInputStream(deb)); ArEntry entry; while ((entry = in.getNextEntry()) != null) { if (entry.getName().equals("data.tar")) { found = true; TarInputStream tar = new TarInputStream(in); while ((tar.getNextEntry()) != null); tar.close(); } else { // skip to the next entry long skip = entry.getLength(); while(skip > 0) { long skipped = in.skip(skip); if (skipped == -1) { throw new IOException("Failed to skip"); } skip -= skipped; } } } assertTrue("tar file not found", found); } #location 31 #vulnerability type RESOURCE_LEAK
#fixed code public void testBZip2Compression() throws Exception { project.executeTarget("bzip2-compression"); File deb = new File("target/test-classes/test.deb"); assertTrue("package not build", deb.exists()); boolean found = false; ArInputStream in = new ArInputStream(new FileInputStream(deb)); ArEntry entry; while ((entry = in.getNextEntry()) != null) { if (entry.getName().equals("data.tar.bz2")) { found = true; assertEquals("header 0", (byte) 'B', in.read()); assertEquals("header 1", (byte) 'Z', in.read()); TarInputStream tar = new TarInputStream(new CBZip2InputStream(in)); while ((tar.getNextEntry()) != null); tar.close(); break; } else { // skip to the next entry long skip = entry.getLength(); while(skip > 0) { long skipped = in.skip(skip); if (skipped == -1) { throw new IOException("Failed to skip"); } skip -= skipped; } } } assertTrue("bz2 file not found", found); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public void testBZip2Compression() throws Exception { project.executeTarget("bzip2-compression"); File deb = new File("target/test-classes/test.deb"); assertTrue("package not build", deb.exists()); boolean found = false; ArInputStream in = new ArInputStream(new FileInputStream(deb)); ArEntry entry; while ((entry = in.getNextEntry()) != null) { if (entry.getName().equals("data.tar.bz2")) { found = true; assertEquals("header 0", (byte) 'B', in.read()); assertEquals("header 1", (byte) 'Z', in.read()); TarInputStream tar = new TarInputStream(new CBZip2InputStream(in)); while ((tar.getNextEntry()) != null); break; } else { // skip to the next entry in.skip(entry.getLength()); } } assertTrue("bz2 file not found", found); } #location 19 #vulnerability type RESOURCE_LEAK
#fixed code public static byte[] toUnixLineEndings(InputStream input) throws IOException { String encoding = "ISO-8859-1"; FixCrLfFilter filter = new FixCrLfFilter(new InputStreamReader(input, encoding)); filter.setEol(FixCrLfFilter.CrLf.newInstance("unix")); ByteArrayOutputStream filteredFile = new ByteArrayOutputStream(); Utils.copy(new ReaderInputStream(filter, encoding), filteredFile); return filteredFile.toByteArray(); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public static byte[] toUnixLineEndings(InputStream input) throws IOException { final Charset UTF8 = Charset.forName("UTF-8"); final BufferedReader reader = new BufferedReader(new InputStreamReader(input)); final ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); String line; while((line = reader.readLine()) != null) { dataStream.write(line.getBytes(UTF8)); dataStream.write('\n'); } reader.close(); return dataStream.toByteArray(); } #location 14 #vulnerability type RESOURCE_LEAK
#fixed code protected void parse( final InputStream pInput ) throws IOException, ParseException { final BufferedReader br = new BufferedReader(new InputStreamReader(pInput, "UTF-8")); StringBuilder buffer = new StringBuilder(); String key = null; int linenr = 0; while (true) { final String line = br.readLine(); if (line == null) { if (buffer.length() > 0) { // flush value of previous key set(key, buffer.toString()); buffer = null; } break; } linenr++; if (line.length() == 0) { throw new ParseException("Empty line", linenr); } final char first = line.charAt(0); if (Character.isLetter(first)) { // new key if (buffer.length() > 0) { // flush value of previous key set(key, buffer.toString()); buffer = new StringBuilder(); } final int i = line.indexOf(':'); if (i < 0) { throw new ParseException("Line misses ':' delimiter", linenr); } key = line.substring(0, i); buffer.append(line.substring(i + 1).trim()); continue; } // continuing old value buffer.append('\n').append(line.substring(1)); } br.close(); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code protected void parse( final InputStream pInput ) throws IOException, ParseException { final BufferedReader br = new BufferedReader(new InputStreamReader(pInput)); StringBuilder buffer = new StringBuilder(); String key = null; int linenr = 0; while (true) { final String line = br.readLine(); if (line == null) { if (buffer.length() > 0) { // flush value of previous key set(key, buffer.toString()); buffer = null; } break; } linenr++; if (line.length() == 0) { throw new ParseException("Empty line", linenr); } final char first = line.charAt(0); if (Character.isLetter(first)) { // new key if (buffer.length() > 0) { // flush value of previous key set(key, buffer.toString()); buffer = new StringBuilder(); } final int i = line.indexOf(':'); if (i < 0) { throw new ParseException("Line misses ':' delimiter", linenr); } key = line.substring(0, i); buffer.append(line.substring(i + 1).trim()); continue; } // continuing old value buffer.append('\n').append(line.substring(1)); } br.close(); } #location 21 #vulnerability type RESOURCE_LEAK
#fixed code private void unpackDependencies() throws MojoExecutionException { ExecutionEnvironment executionEnvironment = executionEnvironment(mavenProject, mavenSession, buildPluginManager); // try { executeMojo( plugin( groupId("org.apache.maven.plugins"), artifactId("maven-dependency-plugin"), version("3.0.1") ), goal("unpack"), configuration( element("artifact", LOADER_JAR_GAV), element("excludes", "META-INF/**"), element("outputDirectory", "${project.build.directory}/classes") ), executionEnvironment ); // } catch (MojoExecutionException e) { // unpackDependenciesFallback(); // } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code private void unpackDependencies() throws MojoExecutionException { try { // get plugin JAR String pluginJarPath = getPluginJarPath(); JarFile pluginJar = new JarFile(new File(pluginJarPath)); // extract loader JAR from plugin JAR JarEntry pluginJarloaderJarEntry = pluginJar.getJarEntry(LOADER_JAR); InputStream loaderJarInputStream = pluginJar.getInputStream(pluginJarloaderJarEntry); File tmpDirectory = new File(System.getProperty("java.io.tmpdir"), "EeBootLoader"); if (!tmpDirectory.exists()) { tmpDirectory.mkdir(); } chmod777(tmpDirectory); File tmpLoaderJarFile = File.createTempFile(TEMP_DIR_NAME_PREFIX, null, tmpDirectory); tmpLoaderJarFile.deleteOnExit(); chmod777(tmpLoaderJarFile); FileUtils.copyInputStreamToFile(loaderJarInputStream, tmpLoaderJarFile); // extract loader JAR contents JarFile loaderJar = new JarFile(tmpLoaderJarFile); loaderJar .stream() .parallel() .filter(loaderJarEntry -> loaderJarEntry.getName().toLowerCase().endsWith(CLASS_SUFFIX)) .forEach(loaderJarEntry -> { try { File file = new File(mavenProject.getBuild().getDirectory(), "classes/" + loaderJarEntry.getName()); if (file.getParentFile() != null) { file.getParentFile().mkdirs(); } InputStream inputStream = loaderJar.getInputStream(loaderJarEntry); FileUtils.copyInputStreamToFile(inputStream, file); } catch (IOException e) { // ignore } }); loaderJar.close(); } catch (IOException e) { throw new MojoExecutionException("Failed to unpack kumuluzee-loader dependency: " + e.getMessage() + "."); } } #location 9 #vulnerability type RESOURCE_LEAK
#fixed code @Override public HttpSession getSession(final boolean create) { return servletContext.getSession(exchange.getExchange(), create); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Override public HttpSession getSession(final boolean create) { if (httpSession == null) { Session session = exchange.getExchange().getAttachment(Session.ATTACHMENT_KEY); if (session != null) { httpSession = new HttpSessionImpl(session, servletContext, servletContext.getDeployment().getApplicationListeners(), exchange.getExchange(), false); } else if (create) { final SessionManager sessionManager = exchange.getExchange().getAttachment(SessionManager.ATTACHMENT_KEY); try { Session newSession = sessionManager.getOrCreateSession(exchange.getExchange()).get(); httpSession = new HttpSessionImpl(newSession, servletContext, servletContext.getDeployment().getApplicationListeners(), exchange.getExchange(), true); servletContext.getDeployment().getApplicationListeners().sessionCreated(httpSession); } catch (IOException e) { throw new RuntimeException(e); } } } return httpSession; } #location 10 #vulnerability type NULL_DEREFERENCE
#fixed code public static void main(String[] args) throws Exception { TokenManager tokenManager = new TokenManager(new ConcurrentHashMap<>(), null, null, ""); String email = "dmitriy@blynk.cc"; String pass = "b"; String appName = AppName.BLYNK; User user = new User(email, SHA256Util.makeHash(pass, email), appName, "local", false, false); user.purchaseEnergy(98000); int count = 300; user.profile.dashBoards = new DashBoard[count]; for (int i = 1; i <= count; i++) { DashBoard dash = new DashBoard(); dash.id = i; dash.theme = Theme.Blynk; dash.isActive = true; user.profile.dashBoards[i - 1] = dash; } List<String> tokens = new ArrayList<>(); for (int i = 1; i <= count; i++) { //tokens.add(tokenManager.refreshToken(user, i, 0)); } write("/path/300_tokens.txt", tokens); write(Paths.get("/path/" + email + "." + appName + ".user"), JsonParser.toJson(user)); //scp /path/dmitriy@blynk.cc.Blynk.user root@IP:/root/data/ }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public static void main(String[] args) throws Exception { TokenManager tokenManager = new TokenManager(new ConcurrentHashMap<>(), null, null, ""); String email = "dmitriy@blynk.cc"; String pass = "b"; String appName = AppName.BLYNK; User user = new User(email, SHA256Util.makeHash(pass, email), appName, "local", false, false); user.purchaseEnergy(98000); int count = 300; user.profile.dashBoards = new DashBoard[count]; for (int i = 1; i <= count; i++) { DashBoard dash = new DashBoard(); dash.id = i; dash.theme = Theme.Blynk; dash.isActive = true; user.profile.dashBoards[i - 1] = dash; } List<String> tokens = new ArrayList<>(); for (int i = 1; i <= count; i++) { tokens.add(tokenManager.refreshToken(user, i, 0)); } write("/path/300_tokens.txt", tokens); write(Paths.get("/path/" + email + "." + appName + ".user"), JsonParser.toJson(user)); //scp /path/dmitriy@blynk.cc.Blynk.user root@IP:/root/data/ } #location 22 #vulnerability type NULL_DEREFERENCE
#fixed code private void sendPushNotification(DashBoard dashBoard, Notification notification, int dashId, int deviceId) { Device device = dashBoard.getDeviceById(deviceId); final String dashName = dashBoard.name == null ? "" : dashBoard.name; final String deviceName = ((device == null || device.name == null) ? "device" : device.name); String message = "Your " + deviceName + " went offline. \"" + dashName + "\" project is disconnected."; notification.push(gcmWrapper, message, dashId ); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code private void sendPushNotification(DashBoard dashBoard, Notification notification, int dashId, int deviceId) { Device device = dashBoard.getDeviceById(deviceId); final String dashName = dashBoard.name == null ? "" : dashBoard.name; final String deviceName = device.name == null ? "device" : device.name; String message = "Your " + deviceName + " went offline. \"" + dashName + "\" project is disconnected."; notification.push(gcmWrapper, message, dashId ); } #location 4 #vulnerability type NULL_DEREFERENCE
#fixed code @Test @Ignore public void testGetTestString() { RedisClient redisClient = new RedisClient("localhost", "123", 6378, false); String result = redisClient.getServerByToken("test"); assertEquals("It's working!", result); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test @Ignore public void testGetTestString() { RealRedisClient redisClient = new RealRedisClient("localhost", "123", 6378); String result = redisClient.getServerByToken("test"); assertEquals("It's working!", result); } #location 5 #vulnerability type RESOURCE_LEAK
#fixed code private Response singleDeviceOTA(ChannelHandlerContext ctx, String token, String path) { TokenValue tokenValue = tokenManager.getTokenValueByToken(token); if (tokenValue == null) { log.debug("Requested token {} not found.", token); return badRequest("Invalid token."); } User user = tokenValue.user; int dashId = tokenValue.dash.id; int deviceId = tokenValue.deviceId; Session session = sessionDao.userSession.get(new UserKey(user)); if (session == null) { log.debug("No session for user {}.", user.email); return badRequest("Device wasn't connected yet."); } String body = otaManager.buildOTAInitCommandBody(path); if (session.sendMessageToHardware(dashId, BLYNK_INTERNAL, 7777, body, deviceId)) { log.debug("No device in session."); return badRequest("No device in session."); } Device device = tokenValue.dash.getDeviceById(deviceId); User initiator = ctx.channel().attr(AuthHeadersBaseHttpHandler.USER).get(); if (initiator != null) { device.updateOTAInfo(initiator.email); } return ok(path); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code private Response singleDeviceOTA(ChannelHandlerContext ctx, String token, String path) { TokenValue tokenValue = tokenManager.getTokenValueByToken(token); if (tokenValue == null) { log.debug("Requested token {} not found.", token); return badRequest("Invalid token."); } User user = tokenValue.user; int dashId = tokenValue.dashId; int deviceId = tokenValue.deviceId; Session session = sessionDao.userSession.get(new UserKey(user)); if (session == null) { log.debug("No session for user {}.", user.email); return badRequest("Device wasn't connected yet."); } String body = otaManager.buildOTAInitCommandBody(path); if (session.sendMessageToHardware(dashId, BLYNK_INTERNAL, 7777, body, deviceId)) { log.debug("No device in session."); return badRequest("No device in session."); } DashBoard dash = user.profile.getDashById(dashId); Device device = dash.getDeviceById(deviceId); User initiator = ctx.channel().attr(AuthHeadersBaseHttpHandler.USER).get(); if (initiator != null) { device.updateOTAInfo(initiator.email); } return ok(path); } #location 26 #vulnerability type NULL_DEREFERENCE
#fixed code public void run() throws Exception { TChannel tchannel = new TChannel.Builder("ping-server") .register("ping", new PingRequestHandler()) .setServerPort(this.port) .build(); tchannel.listen().channel().closeFuture().sync(); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public void run() throws Exception { TChannel tchannel = new TChannel.Builder("ping-server") .register("ping", new PingRequestHandler()) .setPort(this.port) .build(); tchannel.listen().channel().closeFuture().sync(); } #location 7 #vulnerability type RESOURCE_LEAK
#fixed code OffHeapMap(OHCacheBuilder builder, AtomicLong freeCapacity) { this.freeCapacity = freeCapacity; int hts = builder.getHashTableSize(); if (hts <= 0) hts = 8192; if (hts < 256) hts = 256; int bl = builder.getBucketLength(); if (bl <= 0) bl = 8; int buckets = (int) Util.roundUpToPowerOf2(hts, MAX_TABLE_SIZE); entriesPerBucket = (int) Util.roundUpToPowerOf2(bl, MAX_TABLE_SIZE); table = Table.create(buckets, entriesPerBucket); if (table == null) throw new RuntimeException("unable to allocate off-heap memory for segment"); float lf = builder.getLoadFactor(); if (lf <= .0d) lf = .75f; if (lf >= 1d) throw new IllegalArgumentException("load factor must not be greater that 1"); this.loadFactor = lf; threshold = (long) ((double) table.size() * loadFactor); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code long missCount() { return missCount; } #location 3 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code OffHeapMap(OHCacheBuilder builder, AtomicLong freeCapacity) { this.freeCapacity = freeCapacity; int hts = builder.getHashTableSize(); if (hts <= 0) hts = 8192; if (hts < 256) hts = 256; table = Table.create((int) Util.roundUpToPowerOf2(hts, MAX_TABLE_SIZE)); if (table == null) throw new RuntimeException("unable to allocate off-heap memory for segment"); float lf = builder.getLoadFactor(); if (lf <= .0d) lf = .75f; this.loadFactor = lf; threshold = (long) ((double) table.size() * loadFactor); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code long putReplaceCount() { return putReplaceCount; } #location 3 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code OffHeapMap(OHCacheBuilder builder, AtomicLong freeCapacity) { this.freeCapacity = freeCapacity; int hts = builder.getHashTableSize(); if (hts <= 0) hts = 8192; if (hts < 256) hts = 256; int bl = builder.getBucketLength(); if (bl <= 0) bl = 8; int buckets = (int) Util.roundUpToPowerOf2(hts, MAX_TABLE_SIZE); entriesPerBucket = (int) Util.roundUpToPowerOf2(bl, MAX_TABLE_SIZE); table = Table.create(buckets, entriesPerBucket); if (table == null) throw new RuntimeException("unable to allocate off-heap memory for segment"); float lf = builder.getLoadFactor(); if (lf <= .0d) lf = .75f; if (lf >= 1d) throw new IllegalArgumentException("load factor must not be greater that 1"); this.loadFactor = lf; threshold = (long) ((double) table.size() * loadFactor); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code int hashTableSize() { return table.size(); } #location 3 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code OffHeapMap(OHCacheBuilder builder, AtomicLong freeCapacity) { this.freeCapacity = freeCapacity; int hts = builder.getHashTableSize(); if (hts <= 0) hts = 8192; if (hts < 256) hts = 256; table = Table.create((int) Util.roundUpToPowerOf2(hts, MAX_TABLE_SIZE)); if (table == null) throw new RuntimeException("unable to allocate off-heap memory for segment"); float lf = builder.getLoadFactor(); if (lf <= .0d) lf = .75f; this.loadFactor = lf; threshold = (long) ((double) table.size() * loadFactor); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code void resetStatistics() { rehashes = 0L; evictedEntries = 0L; hitCount = 0L; missCount = 0L; putAddCount = 0L; putReplaceCount = 0L; removeCount = 0L; } #location 3 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code OffHeapMap(OHCacheBuilder builder, long freeCapacity) { this.freeCapacity = freeCapacity; this.throwOOME = builder.isThrowOOME(); this.lock = builder.isUnlocked() ? null : new ReentrantLock(); int hts = builder.getHashTableSize(); if (hts <= 0) hts = 8192; if (hts < 256) hts = 256; int bl = builder.getBucketLength(); if (bl <= 0) bl = 8; int buckets = (int) Util.roundUpToPowerOf2(hts, MAX_TABLE_SIZE); entriesPerBucket = (int) Util.roundUpToPowerOf2(bl, MAX_TABLE_SIZE); table = Table.create(buckets, entriesPerBucket, throwOOME); if (table == null) throw new RuntimeException("unable to allocate off-heap memory for segment"); float lf = builder.getLoadFactor(); if (lf <= .0d) lf = .75f; if (lf >= 1d) throw new IllegalArgumentException("load factor must not be greater that 1"); this.loadFactor = lf; threshold = (long) ((double) table.size() * loadFactor); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code long putReplaceCount() { return putReplaceCount; } #location 3 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code OffHeapMap(OHCacheBuilder builder, long freeCapacity) { this.freeCapacity = freeCapacity; this.throwOOME = builder.isThrowOOME(); this.lock = builder.isUnlocked() ? null : new ReentrantLock(); int hts = builder.getHashTableSize(); if (hts <= 0) hts = 8192; if (hts < 256) hts = 256; int bl = builder.getBucketLength(); if (bl <= 0) bl = 8; int buckets = (int) Util.roundUpToPowerOf2(hts, MAX_TABLE_SIZE); entriesPerBucket = (int) Util.roundUpToPowerOf2(bl, MAX_TABLE_SIZE); table = Table.create(buckets, entriesPerBucket, throwOOME); if (table == null) throw new RuntimeException("unable to allocate off-heap memory for segment"); float lf = builder.getLoadFactor(); if (lf <= .0d) lf = .75f; if (lf >= 1d) throw new IllegalArgumentException("load factor must not be greater that 1"); this.loadFactor = lf; threshold = (long) ((double) table.size() * loadFactor); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code long rehashes() { return rehashes; } #location 3 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code OffHeapMap(OHCacheBuilder builder, AtomicLong freeCapacity) { this.freeCapacity = freeCapacity; int hts = builder.getHashTableSize(); if (hts <= 0) hts = 8192; if (hts < 256) hts = 256; int bl = builder.getBucketLength(); if (bl <= 0) bl = 8; int buckets = (int) Util.roundUpToPowerOf2(hts, MAX_TABLE_SIZE); entriesPerBucket = (int) Util.roundUpToPowerOf2(bl, MAX_TABLE_SIZE); table = Table.create(buckets, entriesPerBucket); if (table == null) throw new RuntimeException("unable to allocate off-heap memory for segment"); float lf = builder.getLoadFactor(); if (lf <= .0d) lf = .75f; if (lf >= 1d) throw new IllegalArgumentException("load factor must not be greater that 1"); this.loadFactor = lf; threshold = (long) ((double) table.size() * loadFactor); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code void resetStatistics() { rehashes = 0L; evictedEntries = 0L; hitCount = 0L; missCount = 0L; putAddCount = 0L; putReplaceCount = 0L; removeCount = 0L; lruCompactions = 0L; } #location 7 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code OffHeapMap(OHCacheBuilder builder, long freeCapacity) { this.freeCapacity = freeCapacity; this.throwOOME = builder.isThrowOOME(); this.lock = builder.isUnlocked() ? null : new ReentrantLock(); int hts = builder.getHashTableSize(); if (hts <= 0) hts = 8192; if (hts < 256) hts = 256; table = Table.create((int) Util.roundUpToPowerOf2(hts, MAX_TABLE_SIZE), throwOOME); if (table == null) throw new RuntimeException("unable to allocate off-heap memory for segment"); float lf = builder.getLoadFactor(); if (lf <= .0d) lf = .75f; this.loadFactor = lf; threshold = (long) ((double) table.size() * loadFactor); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code boolean putEntry(long newHashEntryAdr, long hash, long keyLen, long bytes, boolean ifAbsent, long oldValueAddr, long oldValueOffset, long oldValueLen) { long removeHashEntryAdr = 0L; LongArrayList derefList = null; lock.lock(); try { long oldHashEntryAdr = 0L; long hashEntryAdr; long prevEntryAdr = 0L; for (hashEntryAdr = table.getFirst(hash); hashEntryAdr != 0L; prevEntryAdr = hashEntryAdr, hashEntryAdr = HashEntries.getNext(hashEntryAdr)) { if (notSameKey(newHashEntryAdr, hash, keyLen, hashEntryAdr)) continue; // replace existing entry if (ifAbsent) return false; if (oldValueAddr != 0L) { // code for replace() operation long valueLen = HashEntries.getValueLen(hashEntryAdr); if (valueLen != oldValueLen || !HashEntries.compare(hashEntryAdr, Util.ENTRY_OFF_DATA + Util.roundUpTo8(keyLen), oldValueAddr, oldValueOffset, oldValueLen)) return false; } removeInternal(hashEntryAdr, prevEntryAdr); removeHashEntryAdr = hashEntryAdr; oldHashEntryAdr = hashEntryAdr; break; } while (freeCapacity < bytes) { long eldestHashAdr = removeEldest(); if (eldestHashAdr == 0L) { if (oldHashEntryAdr != 0L) size--; return false; } if (derefList == null) derefList = new LongArrayList(); derefList.add(eldestHashAdr); } if (hashEntryAdr == 0L) { if (size >= threshold) rehash(); size++; } freeCapacity -= bytes; add(newHashEntryAdr, hash); if (hashEntryAdr == 0L) putAddCount++; else putReplaceCount++; return true; } finally { lock.unlock(); if (removeHashEntryAdr != 0L) HashEntries.dereference(removeHashEntryAdr); if (derefList != null) for (int i = 0; i < derefList.size(); i++) HashEntries.dereference(derefList.getLong(i)); } } #location 79 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code OffHeapMap(OHCacheBuilder builder, long freeCapacity) { this.freeCapacity = freeCapacity; this.throwOOME = builder.isThrowOOME(); this.lock = builder.isUnlocked() ? null : new ReentrantLock(); int hts = builder.getHashTableSize(); if (hts <= 0) hts = 8192; if (hts < 256) hts = 256; int bl = builder.getBucketLength(); if (bl <= 0) bl = 8; int buckets = (int) Util.roundUpToPowerOf2(hts, MAX_TABLE_SIZE); entriesPerBucket = (int) Util.roundUpToPowerOf2(bl, MAX_TABLE_SIZE); table = Table.create(buckets, entriesPerBucket, throwOOME); if (table == null) throw new RuntimeException("unable to allocate off-heap memory for segment"); float lf = builder.getLoadFactor(); if (lf <= .0d) lf = .75f; if (lf >= 1d) throw new IllegalArgumentException("load factor must not be greater that 1"); this.loadFactor = lf; threshold = (long) ((double) table.size() * loadFactor); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code void resetStatistics() { rehashes = 0L; evictedEntries = 0L; hitCount = 0L; missCount = 0L; putAddCount = 0L; putReplaceCount = 0L; removeCount = 0L; lruCompactions = 0L; } #location 10 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code OffHeapMap(OHCacheBuilder builder, AtomicLong freeCapacity) { this.freeCapacity = freeCapacity; int hts = builder.getHashTableSize(); if (hts <= 0) hts = 8192; if (hts < 256) hts = 256; int bl = builder.getBucketLength(); if (bl <= 0) bl = 8; int buckets = (int) Util.roundUpToPowerOf2(hts, MAX_TABLE_SIZE); entriesPerBucket = (int) Util.roundUpToPowerOf2(bl, MAX_TABLE_SIZE); table = Table.create(buckets, entriesPerBucket); if (table == null) throw new RuntimeException("unable to allocate off-heap memory for segment"); float lf = builder.getLoadFactor(); if (lf <= .0d) lf = .75f; if (lf >= 1d) throw new IllegalArgumentException("load factor must not be greater that 1"); this.loadFactor = lf; threshold = (long) ((double) table.size() * loadFactor); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code long rehashes() { return rehashes; } #location 3 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code @Test public void vanilla() { AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext( TestConfiguration.class); Service service = context.getBean(Service.class); Foo foo = context.getBean(Foo.class); assertFalse(AopUtils.isAopProxy(foo)); service.service(); assertEquals(3, service.getCount()); context.close(); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void vanilla() { AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext( TestConfiguration.class); Service service = context.getBean(Service.class); service.service(); assertEquals(3, service.getCount()); context.close(); } #location 9 #vulnerability type RESOURCE_LEAK
#fixed code private void downloadLoeschen(boolean dauerhaft) { int rows[] = tabelle.getSelectedRows(); if (rows.length > 0) { String[] urls = new String[rows.length]; for (int i = 0; i < rows.length; ++i) { urls[i] = tabelle.getModel().getValueAt(tabelle.convertRowIndexToModel(rows[i]), DatenDownload.DOWNLOAD_URL_NR).toString(); } for (int i = 0; i < urls.length; ++i) { DatenDownload download = ddaten.listeDownloads.getDownloadByUrl(urls[i]); if (download == null) { // wie kann das sein?? Log.debugMeldung("Gits ja gar nicht"); } else { if (dauerhaft) { if (download.istAbo()) { // ein Abo wird zusätzlich ins Logfile geschrieben ddaten.erledigteAbos.zeileSchreiben(download.arr[DatenDownload.DOWNLOAD_THEMA_NR], download.arr[DatenDownload.DOWNLOAD_TITEL_NR], urls[i]); } ddaten.listeDownloads.delDownloadByUrl(urls[i]); }// if (dauerhaft) { ddaten.starterClass.filmLoeschen(urls[i]); } } } else { new HinweisKeineAuswahl().zeigen(); } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code private void downloadLoeschen(boolean dauerhaft) { int rows[] = tabelle.getSelectedRows(); if (rows.length > 0) { for (int i = rows.length - 1; i >= 0; --i) { int delRow = tabelle.convertRowIndexToModel(rows[i]); String url = tabelle.getModel().getValueAt(delRow, DatenDownload.DOWNLOAD_URL_NR).toString(); DatenDownload download = ddaten.listeDownloads.getDownloadByUrl(url); if (dauerhaft) { if (download.istAbo()) { // ein Abo wird zusätzlich ins Logfile geschrieben ddaten.erledigteAbos.zeileSchreiben(download.arr[DatenDownload.DOWNLOAD_THEMA_NR], download.arr[DatenDownload.DOWNLOAD_TITEL_NR], url); } ddaten.listeDownloads.delDownloadByUrl(url); } ddaten.starterClass.filmLoeschen(tabelle.getModel().getValueAt(delRow, DatenDownload.DOWNLOAD_URL_NR).toString()); ((TModelDownload) tabelle.getModel()).removeRow(delRow); } setInfo(); } else { new HinweisKeineAuswahl().zeigen(); } } #location 9 #vulnerability type NULL_DEREFERENCE
#fixed code public static String getMusterPfadVlc() { final String PFAD_LINUX_VLC = "/usr/bin/vlc"; final String PFAD_MAC_VLC = "/Applications/VLC.app/Contents/MacOS/VLC"; final String PFAD_WIN_DEFAULT = "C:\\Programme\\VideoLAN\\VLC\\vlc.exe"; final String PFAD_WIN = "\\VideoLAN\\VLC\\vlc.exe"; String pfad; switch (getOs()) { case OS_LINUX: pfad = PFAD_LINUX_VLC; break; case OS_MAC: pfad = PFAD_MAC_VLC; break; case OS_WIN_32BIT: case OS_WIN_64BIT: case OS_UNKNOWN: default: if (System.getenv("ProgramFiles") != null) { pfad = System.getenv("ProgramFiles") + PFAD_WIN; } else if (System.getenv("ProgramFiles(x86)") != null) { pfad = System.getenv("ProgramFiles(x86)") + PFAD_WIN; } else { pfad = PFAD_WIN_DEFAULT; } } if (!new File(pfad).exists()) { pfad = ""; } return pfad; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public static String getMusterPfadVlc() { final String PFAD_LINUX_VLC = "/usr/bin/vlc"; final String PFAD_MAC_VLC = "/Applications/VLC.app/Contents/MacOS/VLC"; String pfad = ""; if (System.getProperty("os.name").toLowerCase().contains("windows")) { pfad = getWindowsVlcPath(); } else if (System.getProperty("os.name").toLowerCase().contains("linux")) { pfad = PFAD_LINUX_VLC; } else if (System.getProperty("os.name").toLowerCase().contains("mac")) { pfad = PFAD_MAC_VLC; } if (new File(pfad).exists()) { return pfad; } else { return ""; } } #location 5 #vulnerability type NULL_DEREFERENCE
#fixed code private synchronized StringBuffer getUri(String sender, String addr, StringBuffer seite, String kodierung, int timeout, String meldung, int versuch, boolean lVersuch) { int timeo = timeout; boolean proxyB = false; char[] zeichen = new char[1]; seite.setLength(0); HttpURLConnection conn = null; int code = 0; InputStream in = null; InputStreamReader inReader = null; Proxy proxy = null; SocketAddress saddr = null; int ladeArt = LADE_ART_UNBEKANNT; // immer etwas bremsen try { long w = wartenBasis * faktorWarten; this.wait(w); } catch (Exception ex) { Log.fehlerMeldung(976120379, Log.FEHLER_ART_GETURL, GetUrl.class.getName() + ".getUri", ex, sender); } try { // conn = url.openConnection(Proxy.NO_PROXY); conn = (HttpURLConnection) new URL(addr).openConnection(); conn.setRequestProperty("User-Agent", Daten.getUserAgent()); conn.setRequestProperty("User-Agent", Daten.getUserAgent()); System.setProperty("http.maxConnections", "600"); System.setProperty("http.keepAlive", "false"); conn.setRequestProperty("Accept-Encoding", "gzip, deflate"); if (timeout > 0) { conn.setReadTimeout(timeout); conn.setConnectTimeout(timeout); } // the encoding returned by the server String encoding = conn.getContentEncoding(); // if (conn instanceof HttpURLConnection) { // HttpURLConnection httpConnection = (HttpURLConnection) conn; // code = httpConnection.getResponseCode(); // if (code >= 400) { // if (true) { // // wenn möglich, einen Proxy einrichten // Log.fehlerMeldung(236597125, Log.FEHLER_ART_GETURL, GetUrl.class.getName() + ".getUri", "---Proxy---"); // proxyB = true; // saddr = new InetSocketAddress("localhost", 9050); // proxy = new Proxy(Proxy.Type.SOCKS, saddr); // conn = url.openConnection(proxy); // conn.setRequestProperty("User-Agent", Daten.getUserAgent()); // if (timeout > 0) { // conn.setReadTimeout(timeout); // conn.setConnectTimeout(timeout); // } // } else { // Log.fehlerMeldung(864123698, Log.FEHLER_ART_GETURL, GetUrl.class.getName() + ".getUri", "returncode >= 400"); // } // } // } else { // Log.fehlerMeldung(949697315, Log.FEHLER_ART_GETURL, GetUrl.class.getName() + ".getUri", "keine HTTPcon"); // } //in = conn.getInputStream(); if (encoding != null && encoding.equalsIgnoreCase("gzip")) { ladeArt = LADE_ART_GZIP; in = new GZIPInputStream(conn.getInputStream()); } else if (encoding != null && encoding.equalsIgnoreCase("deflate")) { ladeArt = LADE_ART_DEFLATE; in = new InflaterInputStream(conn.getInputStream(), new Inflater(true)); } else { ladeArt = LADE_ART_NIX; in = conn.getInputStream(); } inReader = new InputStreamReader(in, kodierung); //// while (!Daten.filmeLaden.getStop() && inReader.read(zeichen) != -1) { //// seite.append(zeichen); //// incSeitenZaehler(LISTE_SUMME_BYTE, sender, 1); //// } char[] buff = new char[256]; int cnt; while (!Daten.filmeLaden.getStop() && (cnt = inReader.read(buff)) > 0) { seite.append(buff, 0, cnt); incSeitenZaehler(LISTE_SUMME_BYTE, sender, cnt, ladeArt); } } catch (IOException ex) { // consume error stream, otherwise, connection won't be reused if (conn != null) { try { InputStream i = conn.getErrorStream(); if (i != null) { i.close(); } if (inReader != null) { inReader.close(); } } catch (Exception e) { Log.fehlerMeldung(645105987, Log.FEHLER_ART_GETURL, GetUrl.class.getName() + ".getUri", e, ""); } } if (lVersuch) { String[] text; if (meldung.equals("")) { text = new String[]{sender + " - timout: " + timeo + " Versuche: " + versuch, addr /*, (proxyB ? "Porxy - " : "")*/}; } else { text = new String[]{sender + " - timout: " + timeo + " Versuche: " + versuch, addr, meldung/*, (proxyB ? "Porxy - " : "")*/}; } if (ex.getMessage().equals("Read timed out")) { Log.fehlerMeldung(502739817, Log.FEHLER_ART_GETURL, GetUrl.class.getName() + ".getUri: TimeOut", text); } else { Log.fehlerMeldung(502739817, Log.FEHLER_ART_GETURL, GetUrl.class.getName() + ".getUri", ex, text); } } } catch (Exception ex) { Log.fehlerMeldung(973969801, Log.FEHLER_ART_GETURL, GetUrl.class.getName() + ".getUri", ex, ""); } finally { try { if (in != null) { in.close(); } } catch (Exception ex) { Log.fehlerMeldung(696321478, Log.FEHLER_ART_GETURL, GetUrl.class.getName() + ".getUri", ex, ""); } } return seite; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code private synchronized StringBuffer getUri(String sender, String addr, StringBuffer seite, String kodierung, int timeout, String meldung, int versuch, boolean lVersuch) { int timeo = timeout; boolean proxyB = false; char[] zeichen = new char[1]; seite.setLength(0); URLConnection conn; int code = 0; InputStream in = null; InputStreamReader inReader = null; Proxy proxy = null; SocketAddress saddr = null; // immer etwas bremsen try { long w = wartenBasis * faktorWarten; this.wait(w); } catch (Exception ex) { Log.fehlerMeldung(976120379, Log.FEHLER_ART_GETURL, GetUrl.class.getName() + ".getUri", ex, sender); } try { URL url = new URL(addr); // conn = url.openConnection(Proxy.NO_PROXY); conn = url.openConnection(); conn.setRequestProperty("User-Agent", Daten.getUserAgent()); if (timeout > 0) { conn.setReadTimeout(timeout); conn.setConnectTimeout(timeout); } if (conn instanceof HttpURLConnection) { HttpURLConnection httpConnection = (HttpURLConnection) conn; code = httpConnection.getResponseCode(); // if (code >= 400) { // if (true) { // // wenn möglich, einen Proxy einrichten // Log.fehlerMeldung(236597125, Log.FEHLER_ART_GETURL, GetUrl.class.getName() + ".getUri", "---Proxy---"); // proxyB = true; // saddr = new InetSocketAddress("localhost", 9050); // proxy = new Proxy(Proxy.Type.SOCKS, saddr); // conn = url.openConnection(proxy); // conn.setRequestProperty("User-Agent", Daten.getUserAgent()); // if (timeout > 0) { // conn.setReadTimeout(timeout); // conn.setConnectTimeout(timeout); // } // } else { // Log.fehlerMeldung(864123698, Log.FEHLER_ART_GETURL, GetUrl.class.getName() + ".getUri", "returncode >= 400"); // } // } } else { Log.fehlerMeldung(949697315, Log.FEHLER_ART_GETURL, GetUrl.class.getName() + ".getUri", "keine HTTPcon"); } in = conn.getInputStream(); inReader = new InputStreamReader(in, kodierung); while (!Daten.filmeLaden.getStop() && inReader.read(zeichen) != -1) { seite.append(zeichen); incSeitenZaehler(LISTE_SUMME_BYTE, sender, 1); } } catch (IOException ex) { if (lVersuch) { String[] text; if (meldung.equals("")) { text = new String[]{sender + " - timout: " + timeo + " Versuche: " + versuch, addr /*, (proxyB ? "Porxy - " : "")*/}; } else { text = new String[]{sender + " - timout: " + timeo + " Versuche: " + versuch, addr, meldung/*, (proxyB ? "Porxy - " : "")*/}; } Log.fehlerMeldung(502739817, Log.FEHLER_ART_GETURL, GetUrl.class.getName() + ".getUri", ex, text); } } catch (Exception ex) { Log.fehlerMeldung(973969801, Log.FEHLER_ART_GETURL, GetUrl.class.getName() + ".getUri", ex, ""); } finally { try { if (in != null) { inReader.close(); } } catch (IOException ex) { } } return seite; } #location 72 #vulnerability type NULL_DEREFERENCE
#fixed code public static boolean isLeopard() { return SystemInfo.isMacOSX() && SystemInfo.getOSVersion().startsWith("10.5"); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public static boolean isLeopard() { return isMac() && getOsVersion().startsWith("10.5"); } #location 2 #vulnerability type NULL_DEREFERENCE
#fixed code void addToListNormal() { //<strong style="margin-left:10px;">Sesamstraße präsentiert: Eine Möhre für Zwei</strong><br /> //<a style="margin-left:20px;" href="?programm=168&amp;id=14487&amp;ag=5" title="Sendung vom 10.10.2012" class="overlay_link">42. Ordnung ist das halbe Chaos</a><br /> //<a style="margin-left:20px;" href="?programm=168&amp;id=14485&amp;ag=5" title="Sendung vom 10.10.2012" class="overlay_link">41. Über den Wolken</a><br /> final String ADRESSE = "http://kikaplus.net/clients/kika/kikaplus/"; final String MUSTER_URL = "<a style=\"margin-left:20px;\" href=\""; final String MUSTER_THEMA = "<strong style=\"margin-left:10px;\">"; final String MUSTER_DATUM = "title=\"Sendung vom "; listeThemen.clear(); seite = new MVStringBuilder(Konstanten.STRING_BUFFER_START_BUFFER); seite = getUrlIo.getUri(nameSenderMReader, ADRESSE, Konstanten.KODIERUNG_UTF, 3, seite, "KiKA: Startseite"); int pos = 0; int pos1, pos2, stop, pDatum1, pDatum2, pTitel1, pTitel2; String url, thema, datum, titel; while ((pos = seite.indexOf(MUSTER_THEMA, pos)) != -1) { try { thema = ""; pos += MUSTER_THEMA.length(); stop = seite.indexOf(MUSTER_THEMA, pos); pos1 = pos; if ((pos2 = seite.indexOf("<", pos1)) != -1) { thema = seite.substring(pos1, pos2); } while ((pos1 = seite.indexOf(MUSTER_URL, pos1)) != -1) { titel = ""; datum = ""; if (stop != -1 && pos1 > stop) { // dann schon das nächste Thema break; } pos1 += MUSTER_URL.length(); if ((pos2 = seite.indexOf("\"", pos1)) != -1) { url = seite.substring(pos1, pos2); //if (!url.equals("")) { url = StringEscapeUtils.unescapeXml(url); if (!url.equals("") && !url.startsWith("http://") && !url.startsWith("/")) { // Datum if ((pDatum1 = seite.indexOf(MUSTER_DATUM, pos2)) != -1) { pDatum1 += MUSTER_DATUM.length(); if ((pDatum2 = seite.indexOf("\"", pDatum1)) != -1) { if (stop != -1 && pDatum1 < stop && pDatum2 < stop) { // dann schon das nächste Thema datum = seite.substring(pDatum1, pDatum2); } } } // Titel if ((pTitel1 = seite.indexOf(">", pos2)) != -1) { pTitel1 += 1; if ((pTitel2 = seite.indexOf("<", pTitel1)) != -1) { //if (stop != -1 && pTitel1 > stop && pTitel2 > stop) { if (stop != -1 && pTitel1 < stop && pTitel2 < stop) { titel = seite.substring(pTitel1, pTitel2); } } } // in die Liste eintragen String[] add = new String[]{ADRESSE + url, thema, titel, datum}; listeThemen.addUrl(add); } } } } catch (Exception ex) { Log.fehlerMeldung(-302025469, Log.FEHLER_ART_MREADER, "MediathekKiKA.addToList", ex, ""); } } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code void addToListHttp() { //http://www.kikaplus.net/clients/kika/kikaplus/hbbtv/index.php?cmd=az&age=3&page=all //http://www.kikaplus.net/clients/kika/kikaplus/hbbtv/index.php?cmd=az&age=6&page=all //http://www.kikaplus.net/clients/kika/kikaplus/hbbtv/index.php?cmd=az&age=10&page=all final String ADRESSE_1 = "http://www.kikaplus.net/clients/kika/kikaplus/hbbtv/index.php?cmd=az&age="; final String ADRESSE_2 = "&page=all"; final String MUSTER_START = "var programletterlist = {\""; final String[] ALTER = {"3", "6", "10"}; // listeThemen.clear(); MVStringBuilder seite = new MVStringBuilder(Konstanten.STRING_BUFFER_START_BUFFER); meldungStart(); int pos1 = 0, pos2, start = 0, stop = 0; String id = "", thema = "", url = ""; for (String alter : ALTER) { seite = getUrlIo.getUri(nameSenderMReader, ADRESSE_1 + alter + ADRESSE_2, Konstanten.KODIERUNG_UTF, 3, seite, "KiKA: Startseite"); if ((start = seite.indexOf(MUSTER_START)) != -1) { start += MUSTER_START.length(); pos1 = start; if ((stop = seite.indexOf("}};", start)) != -1) { while ((pos1 = seite.indexOf("\"", pos1)) != -1) { thema = ""; id = ""; pos1 += 1; if ((pos2 = seite.indexOf("\"", pos1)) != -1) { id = seite.substring(pos1, pos2); try { // Testen auf Zehl int z = Integer.parseInt(id); } catch (Exception ex) { continue; } ++pos2; if ((pos1 = seite.indexOf("\"", pos2)) != -1) { ++pos1; if ((pos2 = seite.indexOf("\"", pos1)) != -1) { thema = seite.substring(pos1, pos2); } } // http://www.kikaplus.net/clients/kika/kikaplus/hbbtv/index.php?cmd=program&id=165&age=10 url = "http://www.kikaplus.net/clients/kika/kikaplus/hbbtv/index.php?cmd=program&id=" + id + "&age=" + alter; ladenHttp(url, thema, alter); } } } } } } #location 42 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code void addToListNormal() { //<strong style="margin-left:10px;">Sesamstraße präsentiert: Eine Möhre für Zwei</strong><br /> //<a style="margin-left:20px;" href="?programm=168&amp;id=14487&amp;ag=5" title="Sendung vom 10.10.2012" class="overlay_link">42. Ordnung ist das halbe Chaos</a><br /> //<a style="margin-left:20px;" href="?programm=168&amp;id=14485&amp;ag=5" title="Sendung vom 10.10.2012" class="overlay_link">41. Über den Wolken</a><br /> final String ADRESSE = "http://kikaplus.net/clients/kika/kikaplus/"; final String MUSTER_URL = "<a style=\"margin-left:20px;\" href=\""; final String MUSTER_THEMA = "<strong style=\"margin-left:10px;\">"; final String MUSTER_DATUM = "title=\"Sendung vom "; listeThemen.clear(); seite = new MVStringBuilder(Konstanten.STRING_BUFFER_START_BUFFER); seite = getUrlIo.getUri(nameSenderMReader, ADRESSE, Konstanten.KODIERUNG_UTF, 3, seite, "KiKA: Startseite"); int pos = 0; int pos1, pos2, stop, pDatum1, pDatum2, pTitel1, pTitel2; String url, thema, datum, titel; while ((pos = seite.indexOf(MUSTER_THEMA, pos)) != -1) { try { thema = ""; pos += MUSTER_THEMA.length(); stop = seite.indexOf(MUSTER_THEMA, pos); pos1 = pos; if ((pos2 = seite.indexOf("<", pos1)) != -1) { thema = seite.substring(pos1, pos2); } while ((pos1 = seite.indexOf(MUSTER_URL, pos1)) != -1) { titel = ""; datum = ""; if (stop != -1 && pos1 > stop) { // dann schon das nächste Thema break; } pos1 += MUSTER_URL.length(); if ((pos2 = seite.indexOf("\"", pos1)) != -1) { url = seite.substring(pos1, pos2); //if (!url.equals("")) { url = StringEscapeUtils.unescapeXml(url); if (!url.equals("") && !url.startsWith("http://") && !url.startsWith("/")) { // Datum if ((pDatum1 = seite.indexOf(MUSTER_DATUM, pos2)) != -1) { pDatum1 += MUSTER_DATUM.length(); if ((pDatum2 = seite.indexOf("\"", pDatum1)) != -1) { if (stop != -1 && pDatum1 < stop && pDatum2 < stop) { // dann schon das nächste Thema datum = seite.substring(pDatum1, pDatum2); } } } // Titel if ((pTitel1 = seite.indexOf(">", pos2)) != -1) { pTitel1 += 1; if ((pTitel2 = seite.indexOf("<", pTitel1)) != -1) { //if (stop != -1 && pTitel1 > stop && pTitel2 > stop) { if (stop != -1 && pTitel1 < stop && pTitel2 < stop) { titel = seite.substring(pTitel1, pTitel2); } } } // in die Liste eintragen String[] add = new String[]{ADRESSE + url, thema, titel, datum}; listeThemen.addUrl(add); } } } } catch (Exception ex) { Log.fehlerMeldung(-302025469, Log.FEHLER_ART_MREADER, "MediathekKiKA.addToList", ex, ""); } } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code void ladenHttp(String filmWebsite, String thema, String alter) { // erst die Nummer suchen // >25420<4<165<23. Die b // <http://www.kikaplus.net/clients/kika/mediathek/previewpic/1355302530-f80b463888fd4602d925b2ef2c861928 9.jpg< final String MUSTER_BILD = "<http://www."; seiteHttp = getUrlIo.getUri(nameSenderMReader, filmWebsite, Konstanten.KODIERUNG_UTF, 1, seiteHttp, thema); String nummer, url, bild, urlFilm, titel; nummer = seiteHttp.extract(">", "<"); bild = seiteHttp.extract(MUSTER_BILD, "<"); if (!bild.isEmpty()) { bild = "http://www." + bild; } // die URL bauen: // http://www.kikaplus.net/clients/kika/kikaplus/hbbtv/index.php?cmd=video&age=10&id=25420&page=az if (!nummer.isEmpty()) { url = "http://www.kikaplus.net/clients/kika/kikaplus/hbbtv/index.php?cmd=video&age=" + alter + "&id=" + nummer + "&page=az"; seiteHttp = getUrlIo.getUri(nameSenderMReader, url, Konstanten.KODIERUNG_UTF, 1, seiteHttp, thema); final String MUSTER_URL = "var videofile = \""; final String MUSTER_TITEL = "var videotitle = \""; urlFilm = seiteHttp.extract(MUSTER_URL, "\""); titel = seiteHttp.extract(MUSTER_TITEL, "\""); if (!urlFilm.equals("")) { meldung(urlFilm); // DatenFilm(String ssender, String tthema, String filmWebsite, String ttitel, String uurl, String uurlRtmp, // String datum, String zeit, // long dauerSekunden, String description, String thumbnailUrl, String imageUrl, String[] keywords) { DatenFilm film = null; if ((film = istInFilmListe(nameSenderMReader, thema, titel)) != null) { film.addUrlKlein(urlFilm, ""); } else { // dann gibs ihn noch nicht addFilm(new DatenFilm(nameSenderMReader, thema, "http://www.kika.de/fernsehen/mediathek/index.shtml", titel, urlFilm, ""/* urlRtmp */, ""/*datum*/, ""/*zeit*/, 0, "", bild, "", new String[]{""})); } } else { Log.fehlerMeldung(-915263078, Log.FEHLER_ART_MREADER, "MediathekKika", "keine URL: " + filmWebsite); } } } #location 21 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code public void executeCommand(String containerId, String[] command, boolean waitForExecution) { String swarmNodeIp = null; try { List<Task> tasks = dockerClient.listTasks(); for (Task task : tasks) { ContainerStatus containerStatus = task.status().containerStatus(); if (containerStatus != null && containerStatus.containerId().equals(containerId)) { List<Node> nodes = dockerClient.listNodes(); for (Node node :nodes) { if (node.id().equals(task.nodeId())) { swarmNodeIp = node.status().addr(); execCommandOnRemote(swarmNodeIp, containerId, command); } } } } } catch (DockerException | InterruptedException | NullPointerException e) { logger.debug(nodeId + " Error while executing the command", e); ga.trackException(e); } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public void executeCommand(String containerId, String[] command, boolean waitForExecution) { String swarmNodeIp = null; try { List<Task> tasks = dockerClient.listTasks(); for (Task task : tasks) { if (task.status().containerStatus().containerId().equals(containerId)) { List<Node> nodes = dockerClient.listNodes(); for (Node node :nodes) { if (node.id().equals(task.nodeId())) { swarmNodeIp = node.status().addr(); } } } } } catch (DockerException | InterruptedException | NullPointerException e) { logger.debug(nodeId + " Error while executing the command", e); ga.trackException(e); } if (swarmNodeIp != null) { execCommandOnRemote(swarmNodeIp, containerId, command); } } #location 6 #vulnerability type NULL_DEREFERENCE
#fixed code @Test public void pollerThreadTearsDownNodeAfterTestIsCompleted() throws IOException { // Supported desired capability for the test session Map<String, Object> requestedCapability = getCapabilitySupportedByDockerSelenium(); // Start poller thread proxy.startPolling(); // Mock the poller HttpClient to avoid exceptions due to failed connections proxy.getDockerSeleniumNodePollerThread().setClient(getMockedClient()); // Get a test session TestSession newSession = proxy.getNewSession(requestedCapability); Assert.assertNotNull(newSession); // The node should be busy since there is a session in it Assert.assertTrue(proxy.isBusy()); // We release the session, the node should be free WebDriverRequest request = mock(WebDriverRequest.class); HttpServletResponse response = mock(HttpServletResponse.class); when(request.getMethod()).thenReturn("DELETE"); when(request.getRequestType()).thenReturn(RequestType.STOP_SESSION); newSession.getSlot().doFinishRelease(); proxy.afterCommand(newSession, request, response); // After running one test, the node shouldn't be busy and also down Assert.assertFalse(proxy.isBusy()); long sleepTime = proxy.getDockerSeleniumNodePollerThread().getSleepTimeBetweenChecks(); await().atMost(sleepTime + 2000, MILLISECONDS).untilCall(to(proxy).isDown(), equalTo(true)); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void pollerThreadTearsDownNodeAfterTestIsCompleted() throws IOException { // Supported desired capability for the test session Map<String, Object> requestedCapability = getCapabilitySupportedByDockerSelenium(); // Start poller thread proxy.startPolling(); // Mock the poller HttpClient to avoid exceptions due to failed connections proxy.getDockerSeleniumNodePollerThread().setClient(getMockedClient()); // Get a test session TestSession newSession = proxy.getNewSession(requestedCapability); Assert.assertNotNull(newSession); // The node should be busy since there is a session in it Assert.assertTrue(proxy.isBusy()); // We release the session, the node should be free newSession.getSlot().doFinishRelease(); // After running one test, the node shouldn't be busy and also down Assert.assertFalse(proxy.isBusy()); long sleepTime = proxy.getDockerSeleniumNodePollerThread().getSleepTimeBetweenChecks(); await().atMost(sleepTime + 2000, MILLISECONDS).untilCall(to(proxy).isDown(), equalTo(true)); } #location 21 #vulnerability type NULL_DEREFERENCE
#fixed code private ContainerCreationStatus getContainerCreationStatus (String serviceId, String nodePort) throws DockerException, InterruptedException { List<Task> tasks = dockerClient.listTasks(); for (Task task : tasks) { if (task.serviceId().equals(serviceId)) { ContainerStatus containerStatus = task.status().containerStatus(); if (containerStatus != null) { String containerId = containerStatus.containerId(); String containerName = containerStatus.containerId(); return new ContainerCreationStatus(true, containerName, containerId, nodePort); } } } return null; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code private ContainerCreationStatus getContainerCreationStatus (String serviceId, String nodePort) throws DockerException, InterruptedException { List<Task> tasks = dockerClient.listTasks(); for (Task task : tasks) { if (task.serviceId().equals(serviceId)) { ContainerStatus containerStatus = task.status().containerStatus(); String containerId = containerStatus.containerId(); String containerName = containerStatus.containerId(); return new ContainerCreationStatus(true, containerName, containerId, nodePort); } } return null; } #location 6 #vulnerability type NULL_DEREFERENCE
#fixed code public <T> Future<List<T>> fetchAsync(final JsonObject criteria, final String pojo) { return JqFlow.create(this.analyzer, pojo).inputQrJAsync(criteria).compose(this.reader::fetchAsync); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public <T> Future<List<T>> fetchAsync(final JsonObject criteria, final String pojo) { return this.reader.fetchAsync(criteria, JqFlow.create(this.analyzer, pojo)); } #location 2 #vulnerability type NULL_DEREFERENCE
#fixed code @Test(expected = Exception.class) public void testParse_Integer_Exception_NotTerminated() { BEParser parser = new BEParser("i1".getBytes()); assertEquals(BEType.INTEGER, parser.readType()); parser.readInteger(); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test(expected = Exception.class) public void testParse_Integer_Exception_NotTerminated() { BEParser parser = new BEParser("i1"); assertEquals(BEType.INTEGER, parser.readType()); parser.readInteger(); } #location 3 #vulnerability type RESOURCE_LEAK
#fixed code @Test(expected = Exception.class) public void testParse_Integer_Exception_UnexpectedTokens() { BEParser parser = new BEParser("i-1-e".getBytes()); assertEquals(BEType.INTEGER, parser.readType()); parser.readInteger(); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test(expected = Exception.class) public void testParse_Integer_Exception_UnexpectedTokens() { BEParser parser = new BEParser("i-1-e"); assertEquals(BEType.INTEGER, parser.readType()); parser.readInteger(); } #location 5 #vulnerability type RESOURCE_LEAK
#fixed code public static void delete(String key) throws IOException { delete(propertyFile, key); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public static void delete(String key) throws IOException { Properties props = getProperty(); OutputStream fos = new FileOutputStream(propertyFile); props.remove(key); props.store(fos, "Delete '" + key + "' value"); } #location 6 #vulnerability type RESOURCE_LEAK
#fixed code public static List<String> callCommand(String command, String[] environ) { List<String> lines = new LinkedList<String>(); PythonPlugin.LOG.debug("Calling command: '{}'", command); BufferedReader stdInput = null; Process process = null; try { if(environ == null){ process = Runtime.getRuntime().exec(command); } else { process = Runtime.getRuntime().exec(command, environ); } stdInput = new BufferedReader(new InputStreamReader(process.getInputStream())); String s = null; while ((s = stdInput.readLine()) != null) { lines.add(s); } } catch (IOException e) { throw new SonarException("Error calling command '" + command + "', details: '" + e + "'"); } finally { IOUtils.closeQuietly(stdInput); if (process != null) { IOUtils.closeQuietly(process.getInputStream()); IOUtils.closeQuietly(process.getOutputStream()); IOUtils.closeQuietly(process.getErrorStream()); } } return lines; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public static List<String> callCommand(String command, String[] environ) { List<String> lines = new LinkedList<String>(); PythonPlugin.LOG.debug("Calling command: '{}'", command); BufferedReader stdInput = null; try { Process p = null; if(environ == null){ p = Runtime.getRuntime().exec(command); } else { p = Runtime.getRuntime().exec(command, environ); } stdInput = new BufferedReader(new InputStreamReader(p.getInputStream())); String s = null; while ((s = stdInput.readLine()) != null) { lines.add(s); } } catch (IOException e) { throw new SonarException("Error calling command '" + command + "', details: '" + e + "'"); } finally { IOUtils.closeQuietly(stdInput); } return lines; } #location 15 #vulnerability type RESOURCE_LEAK
#fixed code @Test public void definition_callee_symbol() { FileInput tree = parse( "def fn(): pass", "fn('foo')" ); assertNameAndQualifiedName(tree, "fn", null); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void definition_callee_symbol() { FileInput tree = parse( "def fn(): pass", "fn('foo')" ); // TODO: create a symbol for function declaration CallExpression callExpression = getCallExpression(tree); assertThat(callExpression.calleeSymbol()).isNull(); } #location 9 #vulnerability type NULL_DEREFERENCE
#fixed code @RequestMapping("/file/downloadFile") @ResponseBody public void downloadFile(String path, String name, HttpServletRequest request, HttpServletResponse response) { response.setHeader("Content-Disposition", "attachment;filename=" + name); response.setContentType("application/octet-stream"); String peersUrl = getPeers().getServerAddress(); if(StrUtil.isNotBlank(getPeersGroupName())){ peersUrl += "/"+getPeersGroupName(); }else { peersUrl += "/group1"; } BufferedInputStream in = null; try { URL url = new URL(peersUrl+path+"/"+name); in = new BufferedInputStream(url.openStream()); response.reset(); response.setContentType("application/octet-stream"); response.setHeader("Content-Disposition","attachment;filename=" + URLEncoder.encode(name, "UTF-8")); // 将网络输入流转换为输出流 int i; while ((i = in.read()) != -1) { response.getOutputStream().write(i); } response.getOutputStream().close(); } catch (IOException e) { e.printStackTrace(); }finally { try { if (in != null){ in.close(); } } catch (IOException e) { e.printStackTrace(); } } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @RequestMapping("/file/downloadFile") @ResponseBody public void downloadFile(String path, String name, HttpServletRequest request, HttpServletResponse response) { response.setHeader("Content-Disposition", "attachment;filename=" + name); response.setContentType("application/octet-stream"); String peersUrl = getPeers().getServerAddress(); if(StrUtil.isNotBlank(getPeersGroupName())){ peersUrl += "/"+getPeersGroupName(); }else { peersUrl += "/group1"; } BufferedInputStream in = null; try { URL url = new URL(peersUrl+path+"/"+name); in = new BufferedInputStream(url.openStream()); response.reset(); response.setContentType("application/octet-stream"); String os = System.getProperty("os.name"); if(os.toLowerCase().indexOf("windows") != -1){ name = new String(name.getBytes("GBK"), "ISO-8859-1"); }else{ //判断浏览器 String userAgent = request.getHeader("User-Agent").toLowerCase(); if(userAgent.indexOf("msie") > 0){ name = URLEncoder.encode(name, "ISO-8859-1"); } } response.setHeader("Content-Disposition","attachment;filename=" + name); // 将网络输入流转换为输出流 int i; while ((i = in.read()) != -1) { response.getOutputStream().write(i); } response.getOutputStream().close(); } catch (IOException e) { e.printStackTrace(); }finally { try { if (in != null){ in.close(); } } catch (IOException e) { e.printStackTrace(); } } } #location 19 #vulnerability type NULL_DEREFERENCE
#fixed code private static void writeSymJson(@NotNull Binding binding, JsonGenerator json) throws IOException { if (binding.start < 0) { return; } String name = binding.node.name; boolean isExported = !( Binding.Kind.VARIABLE == binding.kind || Binding.Kind.PARAMETER == binding.kind || Binding.Kind.SCOPE == binding.kind || Binding.Kind.ATTRIBUTE == binding.kind || (name != null && (name.length() == 0 || name.startsWith("lambda%")))); String path = binding.qname.replace("%20", "."); if (!seenDef.contains(path)) { seenDef.add(path); json.writeStartObject(); json.writeStringField("name", name); json.writeStringField("path", path); json.writeStringField("file", binding.file); json.writeNumberField("identStart", binding.start); json.writeNumberField("identEnd", binding.end); json.writeNumberField("defStart", binding.bodyStart); json.writeNumberField("defEnd", binding.bodyEnd); json.writeBooleanField("exported", isExported); json.writeStringField("kind", kindName(binding.kind)); if (binding.kind == Binding.Kind.METHOD || binding.kind == Binding.Kind.CLASS_METHOD) { // get args expression Type t = binding.type; if (t.isUnionType()) { t = t.asUnionType().firstUseful(); } if (t != null && t.isFuncType()) { Function func = t.asFuncType().func; if (func != null) { String signature = func.getArgList(); if (!signature.equals("")) { signature = "(" + signature + ")"; } json.writeStringField("signature", signature); } } } Str docstring = binding.findDocString(); if (docstring != null) { json.writeStringField("docstring", docstring.value); } json.writeEndObject(); } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code private static void writeSymJson(@NotNull Binding binding, JsonGenerator json) throws IOException { if (binding.start < 0) { return; } String name = binding.node.name; boolean isExported = !( Binding.Kind.VARIABLE == binding.kind || Binding.Kind.PARAMETER == binding.kind || Binding.Kind.SCOPE == binding.kind || Binding.Kind.ATTRIBUTE == binding.kind || (name != null && (name.length() == 0 || name.startsWith("lambda%")))); String path = binding.qname.replace("%20", "."); if (!seenDef.contains(path)) { seenDef.add(path); if (binding.kind == Binding.Kind.METHOD) { neMethods++; } if (binding.kind == Binding.Kind.CLASS) { neClass++; } json.writeStartObject(); json.writeStringField("name", name); json.writeStringField("path", path); json.writeStringField("file", binding.file); json.writeNumberField("identStart", binding.start); json.writeNumberField("identEnd", binding.end); json.writeNumberField("defStart", binding.bodyStart); json.writeNumberField("defEnd", binding.bodyEnd); json.writeBooleanField("exported", isExported); json.writeStringField("kind", kindName(binding.kind)); if (binding.kind == Binding.Kind.METHOD || binding.kind == Binding.Kind.CLASS_METHOD) { // get args expression String argExpr = null; Type t = binding.type; if (t.isUnionType()) { t = t.asUnionType().firstUseful(); } if (t != null && t.isFuncType()) { Function func = t.asFuncType().func; if (func != null) { argExpr = func.getArgList(); } } String signature; if (argExpr == null) { signature = ""; } else if (argExpr.equals("()")) { signature = ""; } else { signature = argExpr; } json.writeStringField("signature", signature); } String doc = binding.findDocString().value; if (doc != null) { json.writeStringField("docstring", doc); } json.writeEndObject(); } } #location 65 #vulnerability type NULL_DEREFERENCE
#fixed code private void createStreams(final String host) throws Exception { appServerPort = randomFreeLocalPort(); streams = KafkaMusicExample.createChartsStreams(CLUSTER.bootstrapServers(), CLUSTER.schemaRegistryUrl(), appServerPort, TestUtils.tempDirectory().getPath(), host); int count = 0; final int maxTries = 3; while (count <= maxTries) { try { // Starts the Rest Service on the provided host:port restProxy = KafkaMusicExample.startRestProxy(streams, new HostInfo(host, appServerPort)); break; } catch (final Exception ex) { log.error("Could not start Rest Service due to: " + ex.toString()); } count++; } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code private void createStreams(final String host) throws Exception { appServerPort = randomFreeLocalPort(); streams = KafkaMusicExample.createChartsStreams(CLUSTER.bootstrapServers(), CLUSTER.schemaRegistryUrl(), appServerPort, TestUtils.tempDirectory().getPath(), host); int count = 0; final int maxTries = 3; while (count <= maxTries) { try { // Starts the Rest Service on the provided host:port restProxy = KafkaMusicExample.startRestProxy(streams, new HostInfo(host, appServerPort)); } catch (final Exception ex) { log.error("Could not start Rest Service due to: " + ex.toString()); } count++; } } #location 13 #vulnerability type RESOURCE_LEAK
#fixed code @Test public void testShutdown2() throws SQLException { Assert.assertSame("StubConnection count not as expected", 0, StubConnection.count.get()); StubConnection.slowCreate = true; HikariConfig config = new HikariConfig(); config.setMinimumIdle(10); config.setMaximumPoolSize(10); config.setInitializationFailFast(false); config.setConnectionTestQuery("VALUES 1"); config.setDataSourceClassName("com.zaxxer.hikari.mocks.StubDataSource"); HikariDataSource ds = new HikariDataSource(config); HikariPool pool = TestElf.getPool(ds); PoolUtilities.quietlySleep(300); Assert.assertTrue("Totals connection count not as expected, ", pool.getTotalConnections() > 0); ds.close(); Assert.assertSame("Active connection count not as expected, ", 0, pool.getActiveConnections()); Assert.assertSame("Idle connection count not as expected, ", 0, pool.getIdleConnections()); Assert.assertSame("Total connection count not as expected", 0, pool.getTotalConnections()); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void testShutdown2() throws SQLException { Assert.assertSame("StubConnection count not as expected", 0, StubConnection.count.get()); StubConnection.slowCreate = true; HikariConfig config = new HikariConfig(); config.setMinimumIdle(10); config.setMaximumPoolSize(10); config.setInitializationFailFast(false); config.setConnectionTestQuery("VALUES 1"); config.setDataSourceClassName("com.zaxxer.hikari.mocks.StubDataSource"); HikariDataSource ds = new HikariDataSource(config); HikariPool pool = TestElf.getPool(ds); PoolUtilities.quietlySleep(300); Assert.assertTrue("Totals connection count not as expected, ", pool.getTotalConnections() > 0); ds.shutdown(); Assert.assertSame("Active connection count not as expected, ", 0, pool.getActiveConnections()); Assert.assertSame("Idle connection count not as expected, ", 0, pool.getIdleConnections()); Assert.assertSame("Total connection count not as expected", 0, pool.getTotalConnections()); } #location 22 #vulnerability type RESOURCE_LEAK
#fixed code private long runAndMeasure(Measurable[] runners, CountDownLatch latch, String timeUnit) { for (int i = 0; i < runners.length; i++) { Thread t = new Thread(runners[i]); t.start(); } try { latch.await(); } catch (InterruptedException e) { e.printStackTrace(); } int i = 0; long[] track = new long[runners.length]; long max = 0, avg = 0, med = 0; long counter = 0; long absoluteStart = Long.MAX_VALUE, absoluteFinish = Long.MIN_VALUE; for (Measurable runner : runners) { long elapsed = runner.getElapsed(); absoluteStart = Math.min(absoluteStart, runner.getStart()); absoluteFinish = Math.max(absoluteFinish, runner.getFinish()); track[i++] = elapsed; max = Math.max(max, elapsed); avg = (avg + elapsed) / 2; counter += runner.getCounter(); } Arrays.sort(track); med = track[runners.length / 2]; System.out.printf(" %s max=%d%5$s, avg=%d%5$s, med=%d%5$s\n", (Boolean.getBoolean("showCounter") ? "Counter=" + counter : ""), max, avg, med, timeUnit); return absoluteFinish - absoluteStart; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code private long runAndMeasure(Measurable[] runners, CountDownLatch latch, String timeUnit) { for (int i = 0; i < runners.length; i++) { Thread t = new Thread(runners[i]); t.start(); } try { latch.await(); } catch (InterruptedException e) { e.printStackTrace(); } int i = 0; long[] track = new long[runners.length]; long max = 0, avg = 0, med = 0; long absoluteStart = Long.MAX_VALUE, absoluteFinish = Long.MIN_VALUE; for (Measurable runner : runners) { long elapsed = runner.getElapsed(); absoluteStart = Math.min(absoluteStart, runner.getStart()); absoluteFinish = Math.max(absoluteFinish, runner.getFinish()); track[i++] = elapsed; max = Math.max(max, elapsed); avg = (avg + elapsed) / 2; } Arrays.sort(track); med = track[runners.length / 2]; System.out.printf(" max=%d%4$s, avg=%d%4$s, med=%d%4$s\n", max, avg, med, timeUnit); return absoluteFinish - absoluteStart; } #location 34 #vulnerability type CHECKERS_PRINTF_ARGS
#fixed code @Test public void testShutdown3() throws SQLException { Assert.assertSame("StubConnection count not as expected", 0, StubConnection.count.get()); StubConnection.slowCreate = true; HikariConfig config = new HikariConfig(); config.setMinimumIdle(5); config.setMaximumPoolSize(5); config.setInitializationFailFast(true); config.setConnectionTestQuery("VALUES 1"); config.setDataSourceClassName("com.zaxxer.hikari.mocks.StubDataSource"); HikariDataSource ds = new HikariDataSource(config); HikariPool pool = TestElf.getPool(ds); PoolUtilities.quietlySleep(300); Assert.assertTrue("Totals connection count not as expected, ", pool.getTotalConnections() == 5); ds.close(); Assert.assertSame("Active connection count not as expected, ", 0, pool.getActiveConnections()); Assert.assertSame("Idle connection count not as expected, ", 0, pool.getIdleConnections()); Assert.assertSame("Total connection count not as expected", 0, pool.getTotalConnections()); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void testShutdown3() throws SQLException { Assert.assertSame("StubConnection count not as expected", 0, StubConnection.count.get()); StubConnection.slowCreate = true; HikariConfig config = new HikariConfig(); config.setMinimumIdle(5); config.setMaximumPoolSize(5); config.setInitializationFailFast(true); config.setConnectionTestQuery("VALUES 1"); config.setDataSourceClassName("com.zaxxer.hikari.mocks.StubDataSource"); HikariDataSource ds = new HikariDataSource(config); HikariPool pool = TestElf.getPool(ds); PoolUtilities.quietlySleep(300); Assert.assertTrue("Totals connection count not as expected, ", pool.getTotalConnections() == 5); ds.shutdown(); Assert.assertSame("Active connection count not as expected, ", 0, pool.getActiveConnections()); Assert.assertSame("Idle connection count not as expected, ", 0, pool.getIdleConnections()); Assert.assertSame("Total connection count not as expected", 0, pool.getTotalConnections()); } #location 22 #vulnerability type RESOURCE_LEAK
#fixed code @Test public void testConnectionIdleFill() throws Exception { HikariConfig config = new HikariConfig(); config.setMinimumIdle(5); config.setMaximumPoolSize(10); config.setConnectionTimeout(1000); config.setConnectionTestQuery("VALUES 1"); config.setDataSourceClassName("com.zaxxer.hikari.mocks.StubDataSource"); HikariDataSource ds = new HikariDataSource(config); try { Connection connection1 = ds.getConnection(); Connection connection2 = ds.getConnection(); Connection connection3 = ds.getConnection(); Connection connection4 = ds.getConnection(); Connection connection5 = ds.getConnection(); Connection connection6 = ds.getConnection(); Connection connection7 = ds.getConnection(); Thread.sleep(1200); Assert.assertSame("Totals connections not as expected", 10, TestElf.getPool(ds).getTotalConnections()); Assert.assertSame("Idle connections not as expected", 3, TestElf.getPool(ds).getIdleConnections()); connection1.close(); connection2.close(); connection3.close(); connection4.close(); connection5.close(); connection6.close(); connection7.close(); Assert.assertSame("Totals connections not as expected", 10, TestElf.getPool(ds).getTotalConnections()); Assert.assertSame("Idle connections not as expected", 10, TestElf.getPool(ds).getIdleConnections()); } finally { ds.close(); } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void testConnectionIdleFill() throws Exception { HikariConfig config = new HikariConfig(); config.setMinimumIdle(5); config.setMaximumPoolSize(10); config.setConnectionTimeout(1000); config.setConnectionTestQuery("VALUES 1"); config.setDataSourceClassName("com.zaxxer.hikari.mocks.StubDataSource"); HikariDataSource ds = new HikariDataSource(config); try { Connection connection1 = ds.getConnection(); Connection connection2 = ds.getConnection(); Connection connection3 = ds.getConnection(); Connection connection4 = ds.getConnection(); Connection connection5 = ds.getConnection(); Connection connection6 = ds.getConnection(); Connection connection7 = ds.getConnection(); Thread.sleep(1200); Assert.assertSame("Totals connections not as expected", 10, TestElf.getPool(ds).getTotalConnections()); Assert.assertSame("Idle connections not as expected", 3, TestElf.getPool(ds).getIdleConnections()); connection1.close(); connection2.close(); connection3.close(); connection4.close(); connection5.close(); connection6.close(); connection7.close(); Assert.assertSame("Totals connections not as expected", 10, TestElf.getPool(ds).getTotalConnections()); Assert.assertSame("Idle connections not as expected", 10, TestElf.getPool(ds).getIdleConnections()); } finally { ds.shutdown(); } } #location 41 #vulnerability type RESOURCE_LEAK
#fixed code @Override public void startCrackedSession(ProtocolLibLoginSource source, StoredProfile profile, String username) { BukkitLoginSession loginSession = new BukkitLoginSession(username, profile); plugin.putSession(player.getAddress(), loginSession); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Override public void startCrackedSession(ProtocolLibLoginSource source, StoredProfile profile, String username) { BukkitLoginSession loginSession = new BukkitLoginSession(username, profile); plugin.getLoginSessions().put(player.getAddress().toString(), loginSession); } #location 4 #vulnerability type NULL_DEREFERENCE
#fixed code protected static String rootPath() { String path = OS.getTarget(); String sep = System.getProperty("file.separator"); if (!path.endsWith(sep)) { path += sep; } return path + "chronicle-jul" + Time.uniqueId(); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code protected static String rootPath() { String path = System.getProperty("java.io.tmpdir"); String sep = System.getProperty("file.separator"); if (!path.endsWith(sep)) { path += sep; } return path + "chronicle-jul"; } #location 5 #vulnerability type NULL_DEREFERENCE
#fixed code static String rootPath() { String path = OS.getTarget(); String sep = System.getProperty("file.separator"); if (!path.endsWith(sep)) { path += sep; } return path + "chronicle-log4j1" + Time.uniqueId(); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code static String rootPath() { String path = System.getProperty("java.io.tmpdir"); String sep = System.getProperty("file.separator"); if (!path.endsWith(sep)) { path += sep; } return path + "chronicle-log4j1"; } #location 5 #vulnerability type NULL_DEREFERENCE
#fixed code protected void checkProviderInfo(ProviderGroup providerGroup) { List<ProviderInfo> providerInfos = providerGroup == null ? null : providerGroup.getProviderInfos(); if (CommonUtils.isEmpty(providerInfos)) { return; } Iterator<ProviderInfo> iterator = providerInfos.iterator(); while (iterator.hasNext()) { ProviderInfo providerInfo = iterator.next(); if (!StringUtils.equals(providerInfo.getProtocolType(), consumerConfig.getProtocol())) { if (LOGGER.isWarnEnabled(consumerConfig.getAppName())) { LOGGER.warnWithApp(consumerConfig.getAppName(), "Unmatched protocol between consumer [{}] and provider [{}].", consumerConfig.getProtocol(), providerInfo.getProtocolType()); } } } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code protected void checkProviderInfo(ProviderGroup providerGroup) { List<ProviderInfo> providerInfos = providerGroup == null ? null : providerGroup.getProviderInfos(); if (CommonUtils.isEmpty(providerInfos)) { return; } Iterator<ProviderInfo> iterator = providerInfos.iterator(); while (iterator.hasNext()) { ProviderInfo providerInfo = iterator.next(); if (!StringUtils.equals(providerInfo.getProtocolType(), consumerConfig.getProtocol())) { if (LOGGER.isWarnEnabled(consumerConfig.getAppName())) { LOGGER.warnWithApp(consumerConfig.getAppName(), "Unmatched protocol between consumer [{}] and provider [{}].", consumerConfig.getProtocol(), providerInfo.getProtocolType()); } } if (StringUtils.isEmpty(providerInfo.getSerializationType())) { providerInfo.setSerializationType(consumerConfig.getSerialization()); } } } #location 17 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code @Override public void updateProviders(ProviderGroup providerGroup) { checkProviderInfo(providerGroup); ProviderGroup oldProviderGroup = addressHolder.getProviderGroup(providerGroup.getName()); if (ProviderHelper.isEmpty(providerGroup)) { addressHolder.updateProviders(providerGroup); if (!ProviderHelper.isEmpty(oldProviderGroup)) { if (LOGGER.isWarnEnabled(consumerConfig.getAppName())) { LOGGER.warnWithApp(consumerConfig.getAppName(), "Provider list is emptied, may be all " + "providers has been closed, or this consumer has been add to blacklist"); closeTransports(); } } } else { addressHolder.updateProviders(providerGroup); connectionHolder.updateProviders(providerGroup); } if (EventBus.isEnable(ProviderInfoUpdateEvent.class)) { ProviderInfoUpdateEvent event = new ProviderInfoUpdateEvent(consumerConfig, oldProviderGroup, providerGroup); EventBus.post(event); } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Override public void updateProviders(ProviderGroup providerGroup) { checkProviderInfo(providerGroup); ProviderGroup oldProviderGroup = addressHolder.getProviderGroup(providerGroup.getName()); if (ProviderHelper.isEmpty(providerGroup)) { addressHolder.updateProviders(providerGroup); if (CommonUtils.isNotEmpty(oldProviderGroup.getProviderInfos())) { if (LOGGER.isWarnEnabled(consumerConfig.getAppName())) { LOGGER.warnWithApp(consumerConfig.getAppName(), "Provider list is emptied, may be all " + "providers has been closed, or this consumer has been add to blacklist"); closeTransports(); } } } else { addressHolder.updateProviders(providerGroup); connectionHolder.updateProviders(providerGroup); } if (EventBus.isEnable(ProviderInfoUpdateEvent.class)) { ProviderInfoUpdateEvent event = new ProviderInfoUpdateEvent(consumerConfig, oldProviderGroup, providerGroup); EventBus.post(event); } } #location 3 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code private void populateMarkovMatrix(String markovMatrixStorageLocation) { File file = new File(markovMatrixStorageLocation); FileInputStream fileInputStream = null; BufferedInputStream bufferedInputStream = null; BufferedReader bufferedReader = null; String[] statesNames = null; String key; String startState; String endState; Map<String, Double> transitionCount = new HashMap<String, Double>(); Map<String, Double> startStateCount = new HashMap<String, Double>(); try { fileInputStream = new FileInputStream(file); bufferedInputStream = new BufferedInputStream(fileInputStream); bufferedReader = new BufferedReader(new InputStreamReader(bufferedInputStream)); int rowNumber = 0; String row = bufferedReader.readLine(); if (row != null) { statesNames = row.split(","); } while ((row = bufferedReader.readLine()) != null) { if (rowNumber >= statesNames.length) { throw new OperationNotSupportedException( "Number of rows in the matrix should be equal to number of states. please provide a " + statesNames.length + " x " + statesNames.length + " matrix."); } startState = statesNames[rowNumber]; String[] values = row.split(","); double totalCount = 0.0; if (values.length != statesNames.length) { throw new OperationNotSupportedException( "Number of columns in the matrix should be equal to number of states. please provide a " + statesNames.length + " x " + statesNames.length + " matrix."); } for (String value : values) { try { totalCount = totalCount + Double.parseDouble(value); } catch (NumberFormatException e) { log.error("Exception occurred while reading the data file: " + markovMatrixStorageLocation + ". All values in the matrix should be in double.", e); } } startStateCount.put(startState, totalCount); for (int j = 0; j < statesNames.length; j++) { endState = statesNames[j]; key = markovMatrix.getKey(startState, endState); transitionCount.put(key, Double.parseDouble(values[j])); } rowNumber++; } } catch (IOException e) { log.error("Exception occurred while reading the data file: " + markovMatrixStorageLocation, e); } finally { closedQuietly(markovMatrixStorageLocation, bufferedReader, bufferedInputStream, fileInputStream); } markovMatrix.setStartStateCount(startStateCount); markovMatrix.setTransitionCount(transitionCount); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code private void populateMarkovMatrix(String markovMatrixStorageLocation) { File file = new File(markovMatrixStorageLocation); FileInputStream fileInputStream = null; BufferedInputStream bufferedInputStream = null; BufferedReader bufferedReader = null; String[] statesNames = null; String key; String startState; String endState; Map<String, Double> transitionCount = new HashMap<String, Double>(); Map<String, Double> startStateCount = new HashMap<String, Double>(); try { fileInputStream = new FileInputStream(file); bufferedInputStream = new BufferedInputStream(fileInputStream); bufferedReader = new BufferedReader(new InputStreamReader(bufferedInputStream)); int rowNumber = 0; String row = bufferedReader.readLine(); if (row != null) { statesNames = row.split(","); } while ((row = bufferedReader.readLine()) != null) { if (rowNumber >= statesNames.length) { throw new OperationNotSupportedException( "Number of rows in the matrix should be equal to number of states. please provide a " + statesNames.length + " x " + statesNames.length + " matrix"); } startState = statesNames[rowNumber]; String[] values = row.split(","); double totalCount = 0.0; if (values.length != statesNames.length) { throw new OperationNotSupportedException( "Number of columns in the matrix should be equal to number of states. please provide a " + statesNames.length + " x " + statesNames.length + " matrix"); } for (String value : values) { try { totalCount = totalCount + Double.parseDouble(value); } catch (NumberFormatException e) { log.error("Exception occurred while reading the data file " + markovMatrixStorageLocation + ". All values in the matrix should be in double", e); } } startStateCount.put(startState, totalCount); for (int j = 0; j < statesNames.length; j++) { endState = statesNames[j]; key = markovMatrix.getKey(startState, endState); transitionCount.put(key, Double.parseDouble(values[j])); } rowNumber++; } } catch (IOException e) { log.error("Exception occurred while reading the data file " + markovMatrixStorageLocation, e); } finally { closeQuietly(bufferedReader, bufferedInputStream, fileInputStream); } markovMatrix.setStartStateCount(startStateCount); markovMatrix.setTransitionCount(transitionCount); } #location 65 #vulnerability type NULL_DEREFERENCE
#fixed code @Override public void process(ComplexEventChunk complexEventChunk) { if (trigger) { ComplexEventChunk<StateEvent> returnEventChunk = new ComplexEventChunk<StateEvent>(true); StateEvent joinStateEvent = new StateEvent(2, 0); StreamEvent nextEvent = (StreamEvent) complexEventChunk.getFirst(); complexEventChunk.clear(); while (nextEvent != null) { StreamEvent streamEvent = nextEvent; nextEvent = streamEvent.getNext(); streamEvent.setNext(null); joinLockWrapper.lock(); try { ComplexEvent.Type eventType = streamEvent.getType(); if (eventType == ComplexEvent.Type.TIMER) { continue; } else if (eventType == ComplexEvent.Type.RESET) { if (outerJoinProcessor && !leftJoinProcessor) { returnEventChunk.add(joinEventBuilder(null, streamEvent, eventType)); } else if (outerJoinProcessor && leftJoinProcessor) { returnEventChunk.add(joinEventBuilder(streamEvent, null, eventType)); } } else { joinStateEvent.setEvent(matchingStreamIndex, streamEvent); StreamEvent foundStreamEvent = findableProcessor.find(joinStateEvent, finder); joinStateEvent.setEvent(matchingStreamIndex, null); if (foundStreamEvent == null) { if (outerJoinProcessor && !leftJoinProcessor) { returnEventChunk.add(joinEventBuilder(foundStreamEvent, streamEvent, eventType)); } else if (outerJoinProcessor && leftJoinProcessor) { returnEventChunk.add(joinEventBuilder(streamEvent, foundStreamEvent, eventType)); } } else { while (foundStreamEvent != null) { if (!leftJoinProcessor) { returnEventChunk.add(joinEventBuilder(foundStreamEvent, streamEvent, eventType)); } else { returnEventChunk.add(joinEventBuilder(streamEvent, foundStreamEvent, eventType)); } foundStreamEvent = foundStreamEvent.getNext(); } } } } finally { joinLockWrapper.unlock(); } if (returnEventChunk.getFirst() != null) { selector.process(returnEventChunk); returnEventChunk.clear(); } } } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Override public void process(ComplexEventChunk complexEventChunk) { if (trigger) { ComplexEventChunk<StateEvent> returnEventChunk = new ComplexEventChunk<StateEvent>(true); StateEvent joinStateEvent = new StateEvent(2, 0); StreamEvent nextEvent = (StreamEvent) complexEventChunk.getFirst(); complexEventChunk.clear(); while (nextEvent != null) { StreamEvent streamEvent = nextEvent; nextEvent = streamEvent.getNext(); streamEvent.setNext(null); joinLock.lock(); try { ComplexEvent.Type eventType = streamEvent.getType(); if (eventType == ComplexEvent.Type.TIMER) { continue; } else if (eventType == ComplexEvent.Type.RESET) { if (outerJoinProcessor && !leftJoinProcessor) { returnEventChunk.add(joinEventBuilder(null, streamEvent, eventType)); } else if (outerJoinProcessor && leftJoinProcessor) { returnEventChunk.add(joinEventBuilder(streamEvent, null, eventType)); } } else { joinStateEvent.setEvent(matchingStreamIndex, streamEvent); StreamEvent foundStreamEvent = findableProcessor.find(joinStateEvent, finder); joinStateEvent.setEvent(matchingStreamIndex, null); if (foundStreamEvent == null) { if (outerJoinProcessor && !leftJoinProcessor) { returnEventChunk.add(joinEventBuilder(foundStreamEvent, streamEvent, eventType)); } else if (outerJoinProcessor && leftJoinProcessor) { returnEventChunk.add(joinEventBuilder(streamEvent, foundStreamEvent, eventType)); } } else { while (foundStreamEvent != null) { if (!leftJoinProcessor) { returnEventChunk.add(joinEventBuilder(foundStreamEvent, streamEvent, eventType)); } else { returnEventChunk.add(joinEventBuilder(streamEvent, foundStreamEvent, eventType)); } foundStreamEvent = foundStreamEvent.getNext(); } } } } finally { joinLock.unlock(); } if (returnEventChunk.getFirst() != null) { selector.process(returnEventChunk); returnEventChunk.clear(); } } } else { if (preJoinProcessor) { joinLock.lock(); try { nextProcessor.process(complexEventChunk); } finally { joinLock.unlock(); } } } } #location 6 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code @Override protected void process(ComplexEventChunk<StreamEvent> streamEventChunk, Processor nextProcessor, StreamEventCloner streamEventCloner) { while (streamEventChunk.hasNext()) { StreamEvent streamEvent = streamEventChunk.next(); StreamEvent clonedEvent = streamEventCloner.copyStreamEvent(streamEvent); clonedEvent.setType(StreamEvent.Type.EXPIRED); if (count < length) { count++; this.expiredEventChunk.add(clonedEvent); } else { StreamEvent firstEvent = this.expiredEventChunk.poll(); if(firstEvent!=null) { streamEventChunk.insertBeforeCurrent(firstEvent); this.expiredEventChunk.add(clonedEvent); } else { streamEventChunk.insertBeforeCurrent(clonedEvent); } } } nextProcessor.process(streamEventChunk); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Override protected void process(ComplexEventChunk<StreamEvent> streamEventChunk, Processor nextProcessor, StreamEventCloner streamEventCloner) { while (streamEventChunk.hasNext()) { StreamEvent streamEvent = streamEventChunk.next(); StreamEvent clonedEvent = streamEventCloner.copyStreamEvent(streamEvent); clonedEvent.setType(StreamEvent.Type.EXPIRED); if (count < length) { count++; this.expiredEventChunk.add(clonedEvent); } else { StreamEvent firstEvent = this.expiredEventChunk.poll(); streamEventChunk.insertBeforeCurrent(firstEvent); this.expiredEventChunk.add(clonedEvent); } } nextProcessor.process(streamEventChunk); } #location 12 #vulnerability type NULL_DEREFERENCE
#fixed code @Override protected void process(ComplexEventChunk<StreamEvent> streamEventChunk, Processor nextProcessor, StreamEventCloner streamEventCloner, ComplexEventPopulater complexEventPopulater) { ComplexEventChunk<StreamEvent> complexEventChunk = new ComplexEventChunk<StreamEvent>(false); lock.lock(); try { while (streamEventChunk.hasNext()) { StreamEvent event = streamEventChunk.next(); if(event.getType() != ComplexEvent.Type.TIMER) { streamEventChunk.remove(); //We might have the rest of the events linked to this event forming a chain. long timestamp = (Long) timestampExecutor.execute(event); if (expireFlag) { if (timestamp < lastSentTimeStamp) { continue; } } ArrayList<StreamEvent> eventList = eventTreeMap.get(timestamp); if (eventList == null) { eventList = new ArrayList<StreamEvent>(); } eventList.add(event); eventTreeMap.put(timestamp, eventList); if (timestamp > greatestTimestamp) { greatestTimestamp = timestamp; long minTimestamp = eventTreeMap.firstKey(); long timeDifference = greatestTimestamp - minTimestamp; if (timeDifference > k) { if (timeDifference < MAX_K) { k = timeDifference; } else { k = MAX_K; } } Iterator<Map.Entry<Long, ArrayList<StreamEvent>>> entryIterator = eventTreeMap.entrySet().iterator(); while (entryIterator.hasNext()) { Map.Entry<Long, ArrayList<StreamEvent>> entry = entryIterator.next(); ArrayList<StreamEvent> list = expiredEventTreeMap.get(entry.getKey()); if (list != null) { list.addAll(entry.getValue()); } else { expiredEventTreeMap.put(entry.getKey(), entry.getValue()); } } eventTreeMap = new TreeMap<Long, ArrayList<StreamEvent>>(); entryIterator = expiredEventTreeMap.entrySet().iterator(); while (entryIterator.hasNext()) { Map.Entry<Long, ArrayList<StreamEvent>> entry = entryIterator.next(); if (entry.getKey() + k <= greatestTimestamp) { entryIterator.remove(); ArrayList<StreamEvent> timeEventList = entry.getValue(); lastSentTimeStamp = entry.getKey(); for (StreamEvent aTimeEventList : timeEventList) { complexEventChunk.add(aTimeEventList); } } } } } else { if(expiredEventTreeMap.size() > 0) { TreeMap<Long, ArrayList<StreamEvent>> expiredEventTreeMapSnapShot = expiredEventTreeMap; expiredEventTreeMap = new TreeMap<Long, ArrayList<StreamEvent>>(); onTimerEvent(expiredEventTreeMapSnapShot, nextProcessor); lastScheduledTimestamp = lastScheduledTimestamp + TIMER_DURATION; scheduler.notifyAt(lastScheduledTimestamp); } } } } catch (ArrayIndexOutOfBoundsException ec) { //This happens due to user specifying an invalid field index. throw new ExecutionPlanCreationException("The very first parameter must be an Integer with a valid " + " field index (0 to (fieldsLength-1))."); } lock.unlock(); nextProcessor.process(complexEventChunk); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Override protected void process(ComplexEventChunk<StreamEvent> streamEventChunk, Processor nextProcessor, StreamEventCloner streamEventCloner, ComplexEventPopulater complexEventPopulater) { ComplexEventChunk<StreamEvent> complexEventChunk = new ComplexEventChunk<StreamEvent>(false); try { while (streamEventChunk.hasNext()) { StreamEvent event = streamEventChunk.next(); if(event.getType() != ComplexEvent.Type.TIMER) { streamEventChunk.remove(); //We might have the rest of the events linked to this event forming a chain. long timestamp = (Long) timestampExecutor.execute(event); if (expireFlag) { if (timestamp < lastSentTimeStamp) { continue; } } ArrayList<StreamEvent> eventList = eventTreeMap.get(timestamp); if (eventList == null) { eventList = new ArrayList<StreamEvent>(); } eventList.add(event); eventTreeMap.put(timestamp, eventList); if (timestamp > greatestTimestamp) { greatestTimestamp = timestamp; long minTimestamp = eventTreeMap.firstKey(); if ((greatestTimestamp - minTimestamp) > k) { if ((greatestTimestamp - minTimestamp) < MAX_K) { k = greatestTimestamp - minTimestamp; } else { k = MAX_K; } } lock.lock(); Iterator<Map.Entry<Long, ArrayList<StreamEvent>>> entryIterator = eventTreeMap.entrySet().iterator(); while (entryIterator.hasNext()) { Map.Entry<Long, ArrayList<StreamEvent>> entry = entryIterator.next(); ArrayList<StreamEvent> list = expiredEventTreeMap.get(entry.getKey()); if (list != null) { list.addAll(entry.getValue()); } else { expiredEventTreeMap.put(entry.getKey(), entry.getValue()); } } eventTreeMap = new TreeMap<Long, ArrayList<StreamEvent>>(); entryIterator = expiredEventTreeMap.entrySet().iterator(); while (entryIterator.hasNext()) { Map.Entry<Long, ArrayList<StreamEvent>> entry = entryIterator.next(); if (entry.getKey() + k <= greatestTimestamp) { entryIterator.remove(); ArrayList<StreamEvent> timeEventList = entry.getValue(); lastSentTimeStamp = entry.getKey(); for (StreamEvent aTimeEventList : timeEventList) { complexEventChunk.add(aTimeEventList); } } } lock.unlock(); } } else { onTimerEvent(expiredEventTreeMap, nextProcessor); lastScheduledTimestamp = lastScheduledTimestamp + TIMER_DURATION; scheduler.notifyAt(lastScheduledTimestamp); } } } catch (ArrayIndexOutOfBoundsException ec) { // This happens due to user specifying an invalid field index. throw new ExecutionPlanCreationException("The very first parameter must be an Integer with a valid " + " field index (0 to (fieldsLength-1))."); } nextProcessor.process(complexEventChunk); } #location 32 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code @Override public AuthenticationMechanismOutcome authenticate(HttpServerExchange exchange, SecurityContext securityContext) { BearerTokenAuthenticator bearer = createBearerTokenAuthenticator(); AuthenticationMechanismOutcome outcome = bearer.authenticate(exchange); if (outcome == AuthenticationMechanismOutcome.NOT_AUTHENTICATED) { exchange.putAttachment(KEYCLOAK_CHALLENGE_ATTACHMENT_KEY, bearer.getChallenge()); return AuthenticationMechanismOutcome.NOT_AUTHENTICATED; } else if (outcome == AuthenticationMechanismOutcome.AUTHENTICATED) { completeAuthentication(securityContext, bearer); return AuthenticationMechanismOutcome.AUTHENTICATED; } else if (adapterConfig.isBearerOnly()) { exchange.putAttachment(KEYCLOAK_CHALLENGE_ATTACHMENT_KEY, bearer.getChallenge()); return AuthenticationMechanismOutcome.NOT_ATTEMPTED; } OAuthAuthenticator oauth = createOAuthAuthenticator(exchange); outcome = oauth.authenticate(); if (outcome == AuthenticationMechanismOutcome.NOT_AUTHENTICATED) { exchange.putAttachment(KEYCLOAK_CHALLENGE_ATTACHMENT_KEY, oauth.getChallenge()); return AuthenticationMechanismOutcome.NOT_AUTHENTICATED; } else if (outcome == AuthenticationMechanismOutcome.NOT_ATTEMPTED) { exchange.putAttachment(KEYCLOAK_CHALLENGE_ATTACHMENT_KEY, oauth.getChallenge()); return AuthenticationMechanismOutcome.NOT_ATTEMPTED; } completeAuthentication(securityContext, oauth); log.info("AUTHENTICATED"); return AuthenticationMechanismOutcome.AUTHENTICATED; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Override public AuthenticationMechanismOutcome authenticate(HttpServerExchange exchange, SecurityContext securityContext) { BearerTokenAuthenticator bearer = createBearerTokenAuthenticator(); AuthenticationMechanismOutcome outcome = bearer.authenticate(exchange); if (outcome == AuthenticationMechanismOutcome.NOT_AUTHENTICATED) { exchange.putAttachment(KEYCLOAK_CHALLENGE_ATTACHMENT_KEY, bearer.getChallenge()); return AuthenticationMechanismOutcome.NOT_AUTHENTICATED; } else if (outcome == AuthenticationMechanismOutcome.AUTHENTICATED) { final AccessToken token = bearer.getToken(); String surrogate = bearer.getSurrogate(); KeycloakAuthenticatedSession session = new KeycloakAuthenticatedSession(bearer.getTokenString(), token, resourceMetadata); KeycloakPrincipal principal = completeAuthentication(securityContext, token, surrogate); propagateBearer(exchange, session, principal); return AuthenticationMechanismOutcome.AUTHENTICATED; } else if (adapterConfig.isBearerOnly()) { exchange.putAttachment(KEYCLOAK_CHALLENGE_ATTACHMENT_KEY, bearer.getChallenge()); return AuthenticationMechanismOutcome.NOT_ATTEMPTED; } OAuthAuthenticator oauth = createOAuthAuthenticator(exchange); outcome = oauth.authenticate(); if (outcome == AuthenticationMechanismOutcome.NOT_AUTHENTICATED) { exchange.putAttachment(KEYCLOAK_CHALLENGE_ATTACHMENT_KEY, oauth.getChallenge()); return AuthenticationMechanismOutcome.NOT_AUTHENTICATED; } else if (outcome == AuthenticationMechanismOutcome.NOT_ATTEMPTED) { exchange.putAttachment(KEYCLOAK_CHALLENGE_ATTACHMENT_KEY, oauth.getChallenge()); return AuthenticationMechanismOutcome.NOT_ATTEMPTED; } KeycloakAuthenticatedSession session = new KeycloakAuthenticatedSession(oauth.getTokenString(), oauth.getToken(), resourceMetadata); KeycloakPrincipal principal = completeAuthentication(securityContext, oauth.getToken(), null); propagateOauth(exchange, session, principal); log.info("AUTHENTICATED"); return AuthenticationMechanismOutcome.AUTHENTICATED; } #location 34 #vulnerability type NULL_DEREFERENCE
#fixed code protected void start() { if (started) { throw new IllegalStateException("Filter already started. Make sure to specify just keycloakConfigResolver or keycloakConfigFile but not both"); } if (keycloakConfigResolverClass != null) { Class<? extends KeycloakConfigResolver> resolverClass = loadResolverClass(); try { KeycloakConfigResolver resolver = resolverClass.newInstance(); log.info("Using " + resolver + " to resolve Keycloak configuration on a per-request basis."); this.deploymentContext = new AdapterDeploymentContext(resolver); } catch (Exception e) { throw new RuntimeException("Unable to instantiate resolver " + resolverClass); } } else { if (keycloakConfigFile == null) { throw new IllegalArgumentException("You need to specify either keycloakConfigResolverClass or keycloakConfigFile in configuration"); } InputStream is = loadKeycloakConfigFile(); KeycloakDeployment kd = KeycloakDeploymentBuilder.build(is); deploymentContext = new AdapterDeploymentContext(kd); log.info("Keycloak is using a per-deployment configuration loaded from: " + keycloakConfigFile); } nodesRegistrationManagement = new NodesRegistrationManagement(); started = true; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code protected void start() { if (started) { throw new IllegalStateException("Filter already started. Make sure to specify just keycloakConfigResolver or keycloakConfigFile but not both"); } if (keycloakConfigResolverClass != null) { Class<?> clazz; try { clazz = getClass().getClassLoader().loadClass(keycloakConfigResolverClass); } catch (ClassNotFoundException cnfe) { // Fallback to tccl try { clazz = Thread.currentThread().getContextClassLoader().loadClass(keycloakConfigResolverClass); } catch (ClassNotFoundException cnfe2) { throw new RuntimeException("Unable to find resolver class: " + keycloakConfigResolverClass); } } try { KeycloakConfigResolver resolver = (KeycloakConfigResolver) clazz.newInstance(); log.info("Using " + resolver + " to resolve Keycloak configuration on a per-request basis."); this.deploymentContext = new AdapterDeploymentContext(resolver); } catch (Exception e) { throw new RuntimeException("Unable to instantiate resolver " + clazz); } } else { if (keycloakConfigFile == null) { throw new IllegalArgumentException("You need to specify either keycloakConfigResolverClass or keycloakConfigFile in configuration"); } InputStream is = readConfigFile(); KeycloakDeployment kd = KeycloakDeploymentBuilder.build(is); deploymentContext = new AdapterDeploymentContext(kd); log.info("Keycloak is using a per-deployment configuration loaded from: " + keycloakConfigFile); } nodesRegistrationManagement = new NodesRegistrationManagement(); started = true; } #location 31 #vulnerability type RESOURCE_LEAK
#fixed code protected void checkKeycloakSession(Request request, HttpFacade facade) { if (request.getSessionInternal(false) == null || request.getSessionInternal().getPrincipal() == null) return; RefreshableKeycloakSecurityContext session = (RefreshableKeycloakSecurityContext) request.getSessionInternal().getNote(KeycloakSecurityContext.class.getName()); if (session == null) return; // just in case session got serialized if (session.getDeployment() == null) session.setDeployment(deploymentContext.resolveDeployment(facade)); if (session.isActive() && !session.getDeployment().isAlwaysRefreshToken()) return; // FYI: A refresh requires same scope, so same roles will be set. Otherwise, refresh will fail and token will // not be updated boolean success = session.refreshExpiredToken(false); if (success && session.isActive()) return; // Refresh failed, so user is already logged out from keycloak. Cleanup and expire our session Session catalinaSession = request.getSessionInternal(); log.debugf("Cleanup and expire session %s after failed refresh", catalinaSession.getId()); catalinaSession.removeNote(KeycloakSecurityContext.class.getName()); request.setUserPrincipal(null); request.setAuthType(null); catalinaSession.setPrincipal(null); catalinaSession.setAuthType(null); catalinaSession.expire(); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code protected void checkKeycloakSession(Request request, HttpFacade facade) { if (request.getSessionInternal(false) == null || request.getSessionInternal().getPrincipal() == null) return; RefreshableKeycloakSecurityContext session = (RefreshableKeycloakSecurityContext) request.getSessionInternal().getNote(KeycloakSecurityContext.class.getName()); if (session == null) return; // just in case session got serialized if (session.getDeployment() == null) session.setDeployment(deploymentContext.resolveDeployment(facade)); if (session.isActive() && !session.getDeployment().isAlwaysRefreshToken()) return; // FYI: A refresh requires same scope, so same roles will be set. Otherwise, refresh will fail and token will // not be updated boolean success = session.refreshExpiredToken(false); if (success && session.isActive()) return; request.getSessionInternal().removeNote(KeycloakSecurityContext.class.getName()); request.setUserPrincipal(null); request.setAuthType(null); request.getSessionInternal().setPrincipal(null); request.getSessionInternal().setAuthType(null); } #location 7 #vulnerability type NULL_DEREFERENCE
#fixed code private byte[] unHashBlockStream(SafeInputStream decryptedStream) throws IOException { HashedBlockInputStream hashedBlockInputStream = new HashedBlockInputStream(decryptedStream); return StreamUtils.toByteArray(hashedBlockInputStream); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code private byte[] unHashBlockStream(SafeInputStream decryptedStream) throws IOException { HashedBlockInputStream hashedBlockInputStream = new HashedBlockInputStream(decryptedStream); byte[] hashedBlockBytes = StreamUtils.toByteArray(hashedBlockInputStream); return hashedBlockBytes; } #location 3 #vulnerability type RESOURCE_LEAK
#fixed code public void checkVersionSupport(byte[] keepassFile) throws IOException { BufferedInputStream inputStream = new BufferedInputStream(new ByteArrayInputStream(keepassFile)); byte[] signature = new byte[VERSION_SIGNATURE_LENGTH]; int readBytes = inputStream.read(signature); if(readBytes == -1) { throw new UnsupportedOperationException("Could not read KeePass header. The provided file seems to be no KeePass database file!"); } ByteBuffer signatureBuffer = ByteBuffer.wrap(signature); signatureBuffer.order(ByteOrder.LITTLE_ENDIAN); int signaturePart1 = ByteUtils.toUnsignedInt(signatureBuffer.getInt()); int signaturePart2 = ByteUtils.toUnsignedInt(signatureBuffer.getInt()); if (signaturePart1 == DATABASE_V2_FILE_SIGNATURE_1_INT && signaturePart2 == DATABASE_V2_FILE_SIGNATURE_2_INT) { return; } else if (signaturePart1 == OLD_DATABASE_V1_FILE_SIGNATURE_1_INT && signaturePart2 == OLD_DATABASE_V1_FILE_SIGNATURE_2_INT) { throw new UnsupportedOperationException( "The provided KeePass database file seems to be from KeePass 1.x which is not supported!"); } else { throw new UnsupportedOperationException("The provided file seems to be no KeePass database file!"); } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public void checkVersionSupport(byte[] keepassFile) throws IOException { BufferedInputStream bufferedInputStream = new BufferedInputStream(new ByteArrayInputStream(keepassFile)); byte[] signature = new byte[VERSION_SIGNATURE_LENGTH]; bufferedInputStream.read(signature); ByteBuffer signatureBuffer = ByteBuffer.wrap(signature); signatureBuffer.order(ByteOrder.LITTLE_ENDIAN); int signaturePart1 = ByteUtils.toUnsignedInt(signatureBuffer.getInt()); int signaturePart2 = ByteUtils.toUnsignedInt(signatureBuffer.getInt()); if (signaturePart1 == DATABASE_V2_FILE_SIGNATURE_1_INT && signaturePart2 == DATABASE_V2_FILE_SIGNATURE_2_INT) { return; } else if (signaturePart1 == OLD_DATABASE_V1_FILE_SIGNATURE_1_INT && signaturePart2 == OLD_DATABASE_V1_FILE_SIGNATURE_2_INT) { throw new UnsupportedOperationException( "The provided KeePass database file seems to be from KeePass 1.x which is not supported!"); } else { throw new UnsupportedOperationException("The provided file seems to be no KeePass database file!"); } } #location 5 #vulnerability type RESOURCE_LEAK
#fixed code @Test public void testCountAllWithPredicate() { List<Tuple> expected = computeExpected("SELECT COUNT(*) FROM orders WHERE orderstatus = 'F'", FIXED_INT_64); TupleStream orderStatus = createTupleStream(ordersData, Column.ORDER_ORDERSTATUS, VARIABLE_BINARY); ApplyPredicateOperator filtered = new ApplyPredicateOperator(orderStatus, new Predicate<Cursor>() { @Override public boolean apply(Cursor input) { return input.getSlice(0).equals(Slices.copiedBuffer("F", Charsets.UTF_8)); } }); AggregationOperator aggregation = new AggregationOperator(filtered, CountAggregation.PROVIDER); assertEqualsIgnoreOrder(tuples(aggregation), expected); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void testCountAllWithPredicate() { List<Tuple> expected = computeExpected("SELECT COUNT(*) FROM orders WHERE orderstatus = 'F'", FIXED_INT_64); TupleStream orderStatus = createBlockStream(ordersData, Column.ORDER_ORDERSTATUS, VARIABLE_BINARY); ApplyPredicateOperator filtered = new ApplyPredicateOperator(orderStatus, new Predicate<Cursor>() { @Override public boolean apply(Cursor input) { return input.getSlice(0).equals(Slices.copiedBuffer("F", Charsets.UTF_8)); } }); AggregationOperator aggregation = new AggregationOperator(filtered, CountAggregation.PROVIDER); assertEqualsIgnoreOrder(tuples(aggregation), expected); } #location 19 #vulnerability type RESOURCE_LEAK
#fixed code public ZooKeeper getClient(){ if (zooKeeper==null) { try { if (INSTANCE_INIT_LOCK.tryLock(2, TimeUnit.SECONDS)) { if (zooKeeper==null) { // 二次校验,防止并发创建client // init new-client ZooKeeper newZk = null; try { newZk = new ZooKeeper(zkaddress, 10000, watcher); if (zkdigest!=null && zkdigest.trim().length()>0) { newZk.addAuthInfo("digest",zkdigest.getBytes()); // like "account:password" } newZk.exists(zkpath, false); // sync wait until succcess conn // set success new-client zooKeeper = newZk; logger.info(">>>>>>>>>> xxl-rpc, XxlZkClient init success."); } catch (Exception e) { // close fail new-client if (newZk != null) { newZk.close(); } logger.error(e.getMessage(), e); } finally { INSTANCE_INIT_LOCK.unlock(); } } } } catch (InterruptedException e) { logger.error(e.getMessage(), e); } } if (zooKeeper == null) { throw new XxlRpcException("XxlZkClient.zooKeeper is null."); } return zooKeeper; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public ZooKeeper getClient(){ if (zooKeeper==null) { try { if (INSTANCE_INIT_LOCK.tryLock(2, TimeUnit.SECONDS)) { if (zooKeeper==null) { // 二次校验,防止并发创建client try { zooKeeper = new ZooKeeper(zkaddress, 10000, watcher); // TODO,本地变量方式,成功才会赋值 if (zkdigest!=null && zkdigest.trim().length()>0) { zooKeeper.addAuthInfo("digest",zkdigest.getBytes()); // like "account:password" } zooKeeper.exists(zkpath, false); // sync } catch (Exception e) { logger.error(e.getMessage(), e); } finally { INSTANCE_INIT_LOCK.unlock(); } logger.info(">>>>>>>>>> xxl-rpc, XxlZkClient init success."); } } } catch (InterruptedException e) { logger.error(e.getMessage(), e); } } if (zooKeeper == null) { throw new XxlRpcException("XxlZkClient.zooKeeper is null."); } return zooKeeper; } #location 2 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code private static String getAddress() { if (LOCAL_ADDRESS != null) { return LOCAL_ADDRESS; } InetAddress localAddress = getFirstValidAddress(); LOCAL_ADDRESS = localAddress != null ? localAddress.getHostAddress() : null; return LOCAL_ADDRESS; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code private static String getAddress() { if (LOCAL_ADDRESS != null) { return LOCAL_ADDRESS; } InetAddress localAddress = getFirstValidAddress(); LOCAL_ADDRESS = localAddress.getHostAddress(); return LOCAL_ADDRESS; } #location 6 #vulnerability type NULL_DEREFERENCE
#fixed code @Override public void start() { createKafkaConsumer(); //按主题数创建ConsumerWorker线程 for (int i = 0; i < topicHandlers.size(); i++) { ConsumerWorker consumer = new ConsumerWorker(); consumerWorks.add(consumer); fetcheExecutor.submit(consumer); } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Override public void start() { for (int i = 0; i < topicHandlers.size(); i++) { ConsumerWorker<String, DefaultMessage> consumer = new ConsumerWorker<>(configs, topicHandlers,processExecutor); consumers.add(consumer); fetcheExecutor.submit(consumer); } } #location 7 #vulnerability type RESOURCE_LEAK
#fixed code @Override public Result query(String cypher, Map<String, ?> parameters, boolean readOnly) { validateQuery(cypher, parameters, readOnly); //If readOnly=true, just execute the query. If false, execute the query and return stats as well if(readOnly) { return new QueryResult(executeAndMap(null, cypher, parameters, new MapRowModelMapper()),null); } else { Transaction tx = session.ensureTransaction(); RowModelQueryWithStatistics parameterisedStatement = new RowModelQueryWithStatistics(cypher, parameters); try (Neo4jResponse<RowQueryStatisticsResult> response = session.requestHandler().execute(parameterisedStatement, tx)) { RowQueryStatisticsResult result = response.next(); RowModelMapper rowModelMapper = new MapRowModelMapper(); Collection rowResult = new LinkedHashSet(); for (Iterator<Object> iterator = result.getRows().iterator(); iterator.hasNext(); ) { List next = (List) iterator.next(); rowModelMapper.mapIntoResult(rowResult, next.toArray(), response.columns()); } return new QueryResult(rowResult, result.getStats()); } } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Override public Result query(String cypher, Map<String, ?> parameters, boolean readOnly) { validateQuery(cypher, parameters, readOnly); //If readOnly=true, just execute the query. If false, execute the query and return stats as well if(readOnly) { return new QueryResult(executeAndMap(null, cypher, parameters, new MapRowModelMapper()),null); } else { String url = session.ensureTransaction().url(); RowModelQueryWithStatistics parameterisedStatement = new RowModelQueryWithStatistics(cypher, parameters); try (Neo4jResponse<RowQueryStatisticsResult> response = session.requestHandler().execute(parameterisedStatement, url)) { RowQueryStatisticsResult result = response.next(); RowModelMapper rowModelMapper = new MapRowModelMapper(); Collection rowResult = new LinkedHashSet(); for (Iterator<Object> iterator = result.getRows().iterator(); iterator.hasNext(); ) { List next = (List) iterator.next(); rowModelMapper.mapIntoResult(rowResult, next.toArray(), response.columns()); } return new QueryResult(rowResult, result.getStats()); } } } #location 10 #vulnerability type RESOURCE_LEAK
#fixed code @Test public void shouldParseDataInRowResponseCorrectly() { try (Response<DefaultRestModel> rsp = new TestRestHttpResponse((rowResultsAndNoErrors()))) { DefaultRestModel restModel = rsp.next(); assertNotNull(restModel); Map<String,Object> rows = restModel.getRow(); assertEquals(3,rows.entrySet().size()); assertEquals(1, rows.get("count")); NodeModel data = (NodeModel) rows.get("director"); assertEquals(1931,data.property("born")); data = (NodeModel) rows.get("movie"); assertEquals("The Birdcage", data.property("title")); assertEquals(395L, data.getId().longValue()); restModel = rsp.next(); rows = restModel.getRow(); assertEquals(3,rows.entrySet().size()); assertEquals(1, rows.get("count")); data = (NodeModel) rows.get("director"); assertEquals(1931,data.property("born")); data = (NodeModel) rows.get("movie"); assertEquals(2007,data.property("released")); } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void shouldParseDataInRowResponseCorrectly() { try (Response<DefaultRestModel> rsp = new TestRestHttpResponse((rowResultsAndNoErrors()))) { DefaultRestModel restModel = rsp.next(); assertNotNull(restModel); Object[] rows = restModel.getValues(); assertEquals(3,rows.length); assertEquals(1, rows[0]); Map data = (Map) rows[1]; assertEquals(1931,((Map)data.get("data")).get("born")); data = (Map) rows[2]; assertEquals("The Birdcage", ((Map)data.get("data")).get("title")); assertEquals(395, ((Map)data.get("metadata")).get("id")); restModel = rsp.next(); rows = restModel.getValues(); assertEquals(3,rows.length); assertEquals(1, rows[0]); data = (Map) rows[1]; assertEquals(1931,((Map)data.get("data")).get("born")); data = (Map) rows[2]; assertEquals(2007, ((Map)data.get("data")).get("released")); } } #location 23 #vulnerability type RESOURCE_LEAK
#fixed code @Override public RelationalReader getIterableReader(ClassInfo classInfo, Class<?> parameterType, String relationshipType, String relationshipDirection) { if(!iterableReaderCache.containsKey(classInfo)) { iterableReaderCache.put(classInfo, new HashMap<DirectedRelationshipForType, RelationalReader>()); } DirectedRelationshipForType directedRelationshipForType = new DirectedRelationshipForType(relationshipType,relationshipDirection, parameterType); if(iterableReaderCache.get(classInfo).containsKey(directedRelationshipForType)) { return iterableReaderCache.get(classInfo).get(directedRelationshipForType); } //1st find a method annotated with type and direction MethodInfo methodInfo = getIterableGetterMethodInfo(classInfo, parameterType, relationshipType, relationshipDirection, STRICT_MODE); if (methodInfo != null) { MethodReader methodReader = new MethodReader(classInfo, methodInfo); iterableReaderCache.get(classInfo).put(directedRelationshipForType, methodReader); return methodReader; } //2nd find a field annotated with type and direction FieldInfo fieldInfo = getIterableFieldInfo(classInfo, parameterType, relationshipType, relationshipDirection, STRICT_MODE); if (fieldInfo != null) { FieldReader fieldReader = new FieldReader(classInfo, fieldInfo); iterableReaderCache.get(classInfo).put(directedRelationshipForType, fieldReader); return fieldReader; } //If relationshipDirection=INCOMING, we should have found an annotated field already if(!relationshipDirection.equals(Relationship.INCOMING)) { //3rd find a method with implied type and direction methodInfo = getIterableGetterMethodInfo(classInfo, parameterType, relationshipType, relationshipDirection, INFERRED_MODE); if (methodInfo != null) { MethodReader methodReader = new MethodReader(classInfo, methodInfo); iterableReaderCache.get(classInfo).put(directedRelationshipForType, methodReader); return methodReader; } //4th find a field with implied type and direction fieldInfo = getIterableFieldInfo(classInfo, parameterType, relationshipType, relationshipDirection, INFERRED_MODE); if (fieldInfo != null) { FieldReader fieldReader = new FieldReader(classInfo, fieldInfo); iterableReaderCache.get(classInfo).put(directedRelationshipForType, fieldReader); return fieldReader; } } iterableReaderCache.get(classInfo).put(directedRelationshipForType, null); return null; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Override public RelationalReader getIterableReader(ClassInfo classInfo, Class<?> parameterType, String relationshipType, String relationshipDirection) { if(iterableReaderCache.get(classInfo) == null) { iterableReaderCache.put(classInfo, new HashMap<DirectedRelationshipForType, RelationalReader>()); } DirectedRelationshipForType directedRelationshipForType = new DirectedRelationshipForType(relationshipType,relationshipDirection, parameterType); if(iterableReaderCache.get(classInfo).containsKey(directedRelationshipForType)) { return iterableReaderCache.get(classInfo).get(directedRelationshipForType); } //1st find a method annotated with type and direction MethodInfo methodInfo = getIterableGetterMethodInfo(classInfo, parameterType, relationshipType, relationshipDirection, STRICT_MODE); if (methodInfo != null) { MethodReader methodReader = new MethodReader(classInfo, methodInfo); iterableReaderCache.get(classInfo).put(directedRelationshipForType, methodReader); return methodReader; } //2nd find a field annotated with type and direction FieldInfo fieldInfo = getIterableFieldInfo(classInfo, parameterType, relationshipType, relationshipDirection, STRICT_MODE); if (fieldInfo != null) { FieldReader fieldReader = new FieldReader(classInfo, fieldInfo); iterableReaderCache.get(classInfo).put(directedRelationshipForType, fieldReader); return fieldReader; } //If relationshipDirection=INCOMING, we should have found an annotated field already if(!relationshipDirection.equals(Relationship.INCOMING)) { //3rd find a method with implied type and direction methodInfo = getIterableGetterMethodInfo(classInfo, parameterType, relationshipType, relationshipDirection, INFERRED_MODE); if (methodInfo != null) { MethodReader methodReader = new MethodReader(classInfo, methodInfo); iterableReaderCache.get(classInfo).put(directedRelationshipForType, methodReader); return methodReader; } //4th find a field with implied type and direction fieldInfo = getIterableFieldInfo(classInfo, parameterType, relationshipType, relationshipDirection, INFERRED_MODE); if (fieldInfo != null) { FieldReader fieldReader = new FieldReader(classInfo, fieldInfo); iterableReaderCache.get(classInfo).put(directedRelationshipForType, fieldReader); return fieldReader; } } iterableReaderCache.get(classInfo).put(directedRelationshipForType, null); return null; } #location 7 #vulnerability type NULL_DEREFERENCE
#fixed code @Override public <T> Collection<T> loadAll(Class<T> type, Collection<Long> ids, SortOrder sortOrder, Pagination pagination, int depth) { Transaction tx = session.ensureTransaction(); String entityType = session.entityType(type.getName()); QueryStatements queryStatements = session.queryStatementsFor(type); Query qry = queryStatements.findAllByType(entityType, ids, depth) .setSortOrder(sortOrder) .setPagination(pagination); try (Neo4jResponse<GraphModel> response = session.requestHandler().execute(qry, tx)) { return session.responseHandler().loadAll(type, response); } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Override public <T> Collection<T> loadAll(Class<T> type, Collection<Long> ids, SortOrder sortOrder, Pagination pagination, int depth) { String url = session.ensureTransaction().url(); String entityType = session.entityType(type.getName()); QueryStatements queryStatements = session.queryStatementsFor(type); Query qry = queryStatements.findAllByType(entityType, ids, depth) .setSortOrder(sortOrder) .setPagination(pagination); try (Neo4jResponse<GraphModel> response = session.requestHandler().execute(qry, url)) { return session.responseHandler().loadAll(type, response); } } #location 4 #vulnerability type RESOURCE_LEAK
#fixed code public FieldInfo propertyField(String propertyName) { if (propertyFields == null) { initPropertyFields(); } return propertyFields.get(propertyName.toLowerCase()); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public FieldInfo propertyField(String propertyName) { if (propertyFields == null) { if (propertyFields == null) { Collection<FieldInfo> fieldInfos = propertyFields(); propertyFields = new HashMap<>(fieldInfos.size()); for (FieldInfo fieldInfo : fieldInfos) { propertyFields.put(fieldInfo.property().toLowerCase(), fieldInfo); } } } return propertyFields.get(propertyName.toLowerCase()); } #location 9 #vulnerability type NULL_DEREFERENCE
#fixed code private Object createRelationshipEntity(Edge edge, Object startEntity, Object endEntity) { // create and hydrate the new RE Object relationshipEntity = entityFactory.newObject(getRelationshipEntity(edge)); setIdentity(relationshipEntity, edge.getId()); // REs also have properties setProperties(edge, relationshipEntity); // register it in the mapping context mappingContext.registerRelationshipEntity(relationshipEntity, edge.getId()); // set the start and end entities ClassInfo relEntityInfo = metadata.classInfo(relationshipEntity); RelationalWriter startNodeWriter = EntityAccessManager.getRelationalEntityWriter(relEntityInfo, StartNode.class); if (startNodeWriter != null) { startNodeWriter.write(relationshipEntity, startEntity); } else { throw new RuntimeException("Cannot find a writer for the StartNode of relational entity " + relEntityInfo.name()); } RelationalWriter endNodeWriter = EntityAccessManager.getRelationalEntityWriter(relEntityInfo, EndNode.class); if (endNodeWriter != null) { endNodeWriter.write(relationshipEntity, endEntity); } else { throw new RuntimeException("Cannot find a writer for the EndNode of relational entity " + relEntityInfo.name()); } return relationshipEntity; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code private Object createRelationshipEntity(Edge edge, Object startEntity, Object endEntity) { // create and hydrate the new RE Object relationshipEntity = entityFactory.newObject(getRelationshipEntity(edge)); setIdentity(relationshipEntity, edge.getId()); // REs also have properties setProperties(edge, relationshipEntity); // register it in the mapping context mappingContext.registerRelationshipEntity(relationshipEntity, edge.getId()); // set the start and end entities ClassInfo relEntityInfo = metadata.classInfo(relationshipEntity); RelationalWriter startNodeWriter = entityAccessStrategy.getRelationalEntityWriter(relEntityInfo, StartNode.class); if (startNodeWriter != null) { startNodeWriter.write(relationshipEntity, startEntity); } else { throw new RuntimeException("Cannot find a writer for the StartNode of relational entity " + relEntityInfo.name()); } RelationalWriter endNodeWriter = entityAccessStrategy.getRelationalEntityWriter(relEntityInfo, EndNode.class); if (endNodeWriter != null) { endNodeWriter.write(relationshipEntity, endEntity); } else { throw new RuntimeException("Cannot find a writer for the EndNode of relational entity " + relEntityInfo.name()); } return relationshipEntity; } #location 20 #vulnerability type NULL_DEREFERENCE
#fixed code public void setPlatform(String platform) throws FileNotFoundException, IOException { if(!platformPattern.matcher(platform).matches()) throw new IllegalArgumentException("Platform must match " + platformPattern.pattern()); this.platform = platform; rewriteHeader(); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public void setPlatform(String platform) throws FileNotFoundException, IOException { if(!platformPattern.matcher(platform).matches()) throw new IllegalArgumentException("Platform must match " + platformPattern.pattern()); File tempFile = new File(file.getAbsolutePath() + ".tmp"); BufferedReader br; PrintWriter pw; if(compressed) { GZIPInputStream zipStream = new GZIPInputStream(new FileInputStream(file)); br = new BufferedReader(new InputStreamReader(zipStream)); GZIPOutputStream outStream = new GZIPOutputStream(new FileOutputStream(tempFile)); pw = new PrintWriter(outStream); } else { br = new BufferedReader(new InputStreamReader(new FileInputStream(file))); pw = new PrintWriter(new FileWriter(tempFile)); } String line = null; boolean written = false; while ((line = br.readLine()) != null) { /* If line is found overwrite it */ if (!written && line.startsWith(("PLATFORM"))) { pw.println("PLATFORM " + platform); written = true; /* If header has no such field add it */ } else if(!written && line.startsWith("(")) { pw.println("PLATFORM " + platform); pw.println(line); written = true; /* Write all other header lines */ } else { pw.println(line); pw.flush(); } } pw.close(); br.close(); if (!file.delete()) { logger.log(Level.WARNING, "Could not delete old file"); return; } if (!tempFile.renameTo(file)) { logger.log(Level.WARNING, "Could not rename new file to old filename"); } this.platform = platform; } #location 10 #vulnerability type RESOURCE_LEAK
#fixed code @Override @JsonIgnore public Set<Aggregation> getAggregations() { return getInnerQueryUnchecked().getAggregations(); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Override @JsonIgnore public Set<Aggregation> getAggregations() { return getInnerQuery().getAggregations(); } #location 4 #vulnerability type NULL_DEREFERENCE
#fixed code @Override public void refreshIndex(Map<String, Pair<DimensionRow, DimensionRow>> changedRows) { // Make a single Document instance to hold field data being updated to Lucene // Creating documents is costly and so Document will be reused for each record being processed due to // performance best practices. Document doc = new Document(); Map<DimensionField, Field> dimFieldToLuceneField = new HashMap<>(dimension.getDimensionFields().size()); // Create the document fields for this dimension and add them to the document for (DimensionField dimensionField : dimension.getDimensionFields()) { Field luceneField = new StringField( DimensionStoreKeyUtils.getColumnKey(dimensionField.getName()), "", dimensionField.equals(dimension.getKey()) ? Field.Store.YES : Field.Store.NO ); // Store the lucene field in the doc and in our lookup map dimFieldToLuceneField.put(dimensionField, luceneField); doc.add(luceneField); } // Write the rows to the document IndexWriterConfig indexWriterConfig = new IndexWriterConfig(LUCENE_ANALYZER).setRAMBufferSizeMB(BUFFER_SIZE); lock.writeLock().lock(); try { try (IndexWriter luceneIndexWriter = new IndexWriter(luceneDirectory, indexWriterConfig)) { // Update the document fields for each row and update the document for (String rowId : changedRows.keySet()) { // Get the new row from the pair DimensionRow newDimensionRow = changedRows.get(rowId).getKey(); // Update the index updateDimensionRow(doc, dimFieldToLuceneField, luceneIndexWriter, newDimensionRow); } } catch (IOException e) { luceneIndexIsHealthy = false; LOG.error("Failed to refresh index for dimension rows", e); throw new RuntimeException(e); // Commit all the changes to the index (on .close, called by try-resources) and refresh the cardinality } //This must be outside the try-resources block because it may _also_ need to open an IndexWriter, and //opening an IndexWriter involves taking a write lock on lucene, of which there can only be one at a time. reopenIndexSearcher(true); refreshCardinality(); } finally { lock.writeLock().unlock(); } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Override public void refreshIndex(Map<String, Pair<DimensionRow, DimensionRow>> changedRows) { // Make a single Document instance to hold field data being updated to Lucene // Creating documents is costly and so Document will be reused for each record being processed due to // performance best practices. Document doc = new Document(); Map<DimensionField, Field> dimFieldToLuceneField = new HashMap<>(dimension.getDimensionFields().size()); // Create the document fields for this dimension and add them to the document for (DimensionField dimensionField : dimension.getDimensionFields()) { Field luceneField = new StringField( DimensionStoreKeyUtils.getColumnKey(dimensionField.getName()), "", dimensionField.equals(dimension.getKey()) ? Field.Store.YES : Field.Store.NO ); // Store the lucene field in the doc and in our lookup map dimFieldToLuceneField.put(dimensionField, luceneField); doc.add(luceneField); } // Write the rows to the document IndexWriterConfig indexWriterConfig = new IndexWriterConfig(LUCENE_ANALYZER).setRAMBufferSizeMB(BUFFER_SIZE); lock.writeLock().lock(); try (IndexWriter luceneIndexWriter = new IndexWriter(luceneDirectory, indexWriterConfig)) { // Update the document fields for each row and update the document for (String rowId : changedRows.keySet()) { // Get the new row from the pair DimensionRow newDimensionRow = changedRows.get(rowId).getKey(); // Update the index updateDimensionRow(doc, dimFieldToLuceneField, luceneIndexWriter, newDimensionRow); } // Commit all the changes to the index (on .close, called by try-resources) and refresh the cardinality } catch (IOException e) { luceneIndexIsHealthy = false; LOG.error("Failed to refresh index for dimension rows", e); throw new RuntimeException(e); } finally { lock.writeLock().unlock(); } reopenIndexSearcher(true); refreshCardinality(); } #location 44 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code @Override @JsonIgnore public Granularity getGranularity() { return getInnerQueryUnchecked().getGranularity(); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Override @JsonIgnore public Granularity getGranularity() { return getInnerQuery().getGranularity(); } #location 4 #vulnerability type NULL_DEREFERENCE
#fixed code public void run() { if (shutdown) { return; } try { initialize(); LOG.info("Initialization complete. Starting worker loop."); } catch (RuntimeException e1) { LOG.error("Unable to initialize after " + MAX_INITIALIZATION_ATTEMPTS + " attempts. Shutting down.", e1); shutdown(); } while (!shouldShutdown()) { runProcessLoop(); } finalShutdown(); LOG.info("Worker loop is complete. Exiting from worker."); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public void run() { if (shutdown) { return; } try { initialize(); LOG.info("Initialization complete. Starting worker loop."); } catch (RuntimeException e1) { LOG.error("Unable to initialize after " + MAX_INITIALIZATION_ATTEMPTS + " attempts. Shutting down.", e1); shutdown(); } while (!shouldShutdown()) { try { boolean foundCompletedShard = false; Set<ShardInfo> assignedShards = new HashSet<ShardInfo>(); for (ShardInfo shardInfo : getShardInfoForAssignments()) { ShardConsumer shardConsumer = createOrGetShardConsumer(shardInfo, recordProcessorFactory); if (shardConsumer.isShutdown() && shardConsumer.getShutdownReason().equals(ShutdownReason.TERMINATE)) { foundCompletedShard = true; } else { shardConsumer.consumeShard(); } assignedShards.add(shardInfo); } if (foundCompletedShard) { controlServer.syncShardAndLeaseInfo(null); } // clean up shard consumers for unassigned shards cleanupShardConsumers(assignedShards); wlog.info("Sleeping ..."); Thread.sleep(idleTimeInMilliseconds); } catch (Exception e) { LOG.error(String.format("Worker.run caught exception, sleeping for %s milli seconds!", String.valueOf(idleTimeInMilliseconds)), e); try { Thread.sleep(idleTimeInMilliseconds); } catch (InterruptedException ex) { LOG.info("Worker: sleep interrupted after catching exception ", ex); } } wlog.resetInfoLogging(); } finalShutdown(); LOG.info("Worker loop is complete. Exiting from worker."); } #location 18 #vulnerability type NULL_DEREFERENCE
#fixed code @Override public void start(ExtendedSequenceNumber extendedSequenceNumber, InitialPositionInStreamExtended initialPositionInStreamExtended) { if (executorService.isShutdown()) { throw new IllegalStateException("ExecutorService has been shutdown."); } publisherSession.init(extendedSequenceNumber, initialPositionInStreamExtended); if (!started) { log.info("{} : Starting prefetching thread.", shardId); executorService.execute(defaultGetRecordsCacheDaemon); } started = true; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Override public void start(ExtendedSequenceNumber extendedSequenceNumber, InitialPositionInStreamExtended initialPositionInStreamExtended) { if (executorService.isShutdown()) { throw new IllegalStateException("ExecutorService has been shutdown."); } this.initialPositionInStreamExtended = initialPositionInStreamExtended; highestSequenceNumber = extendedSequenceNumber.sequenceNumber(); dataFetcher.initialize(extendedSequenceNumber, initialPositionInStreamExtended); if (!started) { log.info("{} : Starting prefetching thread.", shardId); executorService.execute(defaultGetRecordsCacheDaemon); } started = true; } #location 8 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code @Test public void test() throws Exception { for (int i = 0; i < 5; i++) { SpecCaptcha specCaptcha = new SpecCaptcha(); //specCaptcha.setCharType(Captcha.TYPE_ONLY_NUMBER); System.out.println(specCaptcha.text()); //specCaptcha.out(new FileOutputStream(new File("D:/Java/aa" + i + ".png"))); } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void test() throws Exception { for (int i = 0; i < 5; i++) { SpecCaptcha specCaptcha = new SpecCaptcha(); //specCaptcha.setCharType(Captcha.TYPE_ONLY_NUMBER); System.out.println(specCaptcha.text()); specCaptcha.out(new FileOutputStream(new File("D:/Java/aa" + i + ".png"))); } } #location 7 #vulnerability type RESOURCE_LEAK
#fixed code Module(final ConcreteModuleSpec spec, final ModuleLoader moduleLoader, final Object myKey) { this.moduleLoader = moduleLoader; this.myKey = myKey; // Initialize state from the spec. identifier = spec.getModuleIdentifier(); mainClassName = spec.getMainClass(); fallbackLoader = spec.getFallbackLoader(); //noinspection ThisEscapedInObjectConstruction final ModuleClassLoader.Configuration configuration = new ModuleClassLoader.Configuration(this, spec.getAssertionSetting(), spec.getResourceLoaders(), spec.getClassFileTransformer()); final ModuleClassLoaderFactory factory = spec.getModuleClassLoaderFactory(); ModuleClassLoader moduleClassLoader = null; if (factory != null) moduleClassLoader = factory.create(configuration); if (moduleClassLoader == null) moduleClassLoader = new ModuleClassLoader(configuration); this.moduleClassLoader = moduleClassLoader; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code Map<String, List<LocalLoader>> getPathsUnchecked(final boolean export) { try { return getPaths(export); } catch (ModuleLoadException e) { throw e.toError(); } } #location 3 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code public static IterableResourceLoader createIterableFileResourceLoader(final String name, final File root) { return createFileResourceLoader(name, root); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public static IterableResourceLoader createIterableFileResourceLoader(final String name, final File root) { return new FileResourceLoader(name, root, AccessController.getContext()); } #location 2 #vulnerability type RESOURCE_LEAK
#fixed code Module(final ConcreteModuleSpec spec, final ModuleLoader moduleLoader) { this.moduleLoader = moduleLoader; // Initialize state from the spec. identifier = spec.getModuleIdentifier(); mainClassName = spec.getMainClass(); fallbackLoader = spec.getFallbackLoader(); //noinspection ThisEscapedInObjectConstruction final ModuleClassLoader.Configuration configuration = new ModuleClassLoader.Configuration(this, spec.getAssertionSetting(), spec.getResourceLoaders(), spec.getClassFileTransformer()); final ModuleClassLoaderFactory factory = spec.getModuleClassLoaderFactory(); ModuleClassLoader moduleClassLoader = null; if (factory != null) moduleClassLoader = factory.create(configuration); if (moduleClassLoader == null) moduleClassLoader = new ModuleClassLoader(configuration); this.moduleClassLoader = moduleClassLoader; final Map<String, String> properties = spec.getProperties(); this.properties = properties.isEmpty() ? Collections.<String, String>emptyMap() : new LinkedHashMap<String, String>(properties); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code long addExportedPaths(Dependency[] dependencies, Map<String, List<LocalLoader>> map, FastCopyHashSet<PathFilter> filterStack, FastCopyHashSet<ClassFilter> classFilterStack, final FastCopyHashSet<PathFilter> resourceFilterStack, Set<Visited> visited) throws ModuleLoadException { if (!visited.add(new Visited(this, filterStack, classFilterStack, resourceFilterStack))) { return 0L; } long subtract = 0L; moduleLoader.incScanCount(); for (Dependency dependency : dependencies) { final PathFilter exportFilter = dependency.getExportFilter(); // skip non-exported dependencies altogether if (exportFilter != PathFilters.rejectAll()) { if (dependency instanceof ModuleDependency) { final ModuleDependency moduleDependency = (ModuleDependency) dependency; final ModuleLoader moduleLoader = moduleDependency.getModuleLoader(); final ModuleIdentifier id = moduleDependency.getIdentifier(); final Module module; try { long pauseStart = Metrics.getCurrentCPUTime(); try { module = moduleLoader.preloadModule(id); } finally { subtract += Metrics.getCurrentCPUTime() - pauseStart; } } catch (ModuleLoadException ex) { if (moduleDependency.isOptional()) { continue; } else { throw ex; } } if (module == null) { if (!moduleDependency.isOptional()) { throw new ModuleNotFoundException(id.toString()); } continue; } final PathFilter importFilter = dependency.getImportFilter(); final FastCopyHashSet<PathFilter> nestedFilters; final FastCopyHashSet<ClassFilter> nestedClassFilters; final FastCopyHashSet<PathFilter> nestedResourceFilters; if (filterStack.contains(importFilter) && filterStack.contains(exportFilter)) { nestedFilters = filterStack; } else { nestedFilters = filterStack.clone(); nestedFilters.add(importFilter); nestedFilters.add(exportFilter); } final ClassFilter classImportFilter = dependency.getClassImportFilter(); final ClassFilter classExportFilter = dependency.getClassExportFilter(); if ((classImportFilter == ClassFilters.acceptAll() || classFilterStack.contains(classImportFilter)) && (classExportFilter == ClassFilters.acceptAll() || classFilterStack.contains(classExportFilter))) { nestedClassFilters = classFilterStack; } else { nestedClassFilters = classFilterStack.clone(); if (classImportFilter != ClassFilters.acceptAll()) nestedClassFilters.add(classImportFilter); if (classExportFilter != ClassFilters.acceptAll()) nestedClassFilters.add(classExportFilter); } final PathFilter resourceImportFilter = dependency.getResourceImportFilter(); final PathFilter resourceExportFilter = dependency.getResourceExportFilter(); if ((resourceImportFilter == PathFilters.acceptAll() || resourceFilterStack.contains(resourceImportFilter)) && (resourceExportFilter == PathFilters.acceptAll() || resourceFilterStack.contains(resourceExportFilter))) { nestedResourceFilters = resourceFilterStack; } else { nestedResourceFilters = resourceFilterStack.clone(); if (resourceImportFilter != PathFilters.acceptAll()) nestedResourceFilters.add(resourceImportFilter); if (resourceExportFilter != PathFilters.acceptAll()) nestedResourceFilters.add(resourceExportFilter); } subtract += module.addExportedPaths(module.getDependencies(), map, nestedFilters, nestedClassFilters, nestedResourceFilters, visited); } else if (dependency instanceof ModuleClassLoaderDependency) { final ModuleClassLoaderDependency classLoaderDependency = (ModuleClassLoaderDependency) dependency; LocalLoader localLoader = classLoaderDependency.getLocalLoader(); for (Object filter : classFilterStack.getRawArray()) { if (filter != null && filter != ClassFilters.acceptAll()) { localLoader = LocalLoaders.createClassFilteredLocalLoader((ClassFilter) filter, localLoader); } } for (Object filter : resourceFilterStack.getRawArray()) { if (filter != null && filter != PathFilters.acceptAll()) { localLoader = LocalLoaders.createPathFilteredLocalLoader((PathFilter) filter, localLoader); } } ClassFilter classImportFilter = classLoaderDependency.getClassImportFilter(); if (classImportFilter != ClassFilters.acceptAll()) { localLoader = LocalLoaders.createClassFilteredLocalLoader(classImportFilter, localLoader); } ClassFilter classExportFilter = classLoaderDependency.getClassExportFilter(); if (classExportFilter != ClassFilters.acceptAll()) { localLoader = LocalLoaders.createClassFilteredLocalLoader(classExportFilter, localLoader); } PathFilter resourceImportFilter = classLoaderDependency.getResourceImportFilter(); if (resourceImportFilter != PathFilters.acceptAll()) { localLoader = LocalLoaders.createPathFilteredLocalLoader(resourceImportFilter, localLoader); } PathFilter resourceExportFilter = classLoaderDependency.getResourceExportFilter(); if (resourceExportFilter != PathFilters.acceptAll()) { localLoader = LocalLoaders.createPathFilteredLocalLoader(resourceExportFilter, localLoader); } final PathFilter importFilter = classLoaderDependency.getImportFilter(); final Set<String> paths = classLoaderDependency.getPaths(); for (String path : paths) { boolean accept = true; for (Object filter : filterStack.getRawArray()) { if (filter != null && ! ((PathFilter)filter).accept(path)) { accept = false; break; } } if (accept && importFilter.accept(path) && exportFilter.accept(path)) { List<LocalLoader> list = map.get(path); if (list == null) { map.put(path, list = new ArrayList<LocalLoader>(1)); list.add(localLoader); } else if (! list.contains(localLoader)) { list.add(localLoader); } } } } else if (dependency instanceof LocalDependency) { final LocalDependency localDependency = (LocalDependency) dependency; LocalLoader localLoader = localDependency.getLocalLoader(); for (Object filter : classFilterStack.getRawArray()) { if (filter != null && filter != ClassFilters.acceptAll()) { localLoader = LocalLoaders.createClassFilteredLocalLoader((ClassFilter) filter, localLoader); } } for (Object filter : resourceFilterStack.getRawArray()) { if (filter != null && filter != PathFilters.acceptAll()) { localLoader = LocalLoaders.createPathFilteredLocalLoader((PathFilter) filter, localLoader); } } ClassFilter classFilter = localDependency.getClassExportFilter(); if (classFilter != ClassFilters.acceptAll()) { localLoader = LocalLoaders.createClassFilteredLocalLoader(classFilter, localLoader); } classFilter = localDependency.getClassImportFilter(); if (classFilter != ClassFilters.acceptAll()) { localLoader = LocalLoaders.createClassFilteredLocalLoader(classFilter, localLoader); } PathFilter resourceFilter = localDependency.getResourceExportFilter(); if (resourceFilter != PathFilters.acceptAll()) { localLoader = LocalLoaders.createPathFilteredLocalLoader(resourceFilter, localLoader); } resourceFilter = localDependency.getResourceImportFilter(); if (resourceFilter != PathFilters.acceptAll()) { localLoader = LocalLoaders.createPathFilteredLocalLoader(resourceFilter, localLoader); } final Set<String> paths = localDependency.getPaths(); for (String path : paths) { boolean accept = true; for (Object filter : filterStack.getRawArray()) { if (filter != null && ! ((PathFilter)filter).accept(path)) { accept = false; break; } } if (accept && localDependency.getImportFilter().accept(path) && localDependency.getExportFilter().accept(path)) { List<LocalLoader> list = map.get(path); if (list == null) { map.put(path, list = new ArrayList<LocalLoader>(1)); list.add(localLoader); } else if (! list.contains(localLoader)) { list.add(localLoader); } } } } // else unknown dep type so just skip } } return subtract; } #location 64 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code public static ResourceLoader createMavenArtifactLoader(final MavenResolver mavenResolver, final String name) throws IOException { File fp = mavenResolver.resolveJarArtifact(ArtifactCoordinates.fromString(name)); if (fp == null) return null; JarFile jarFile = JDKSpecific.getJarFile(fp, true); return ResourceLoaders.createJarResourceLoader(name, jarFile); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public static ResourceLoader createMavenArtifactLoader(final MavenResolver mavenResolver, final String name) throws IOException { File fp = mavenResolver.resolveJarArtifact(ArtifactCoordinates.fromString(name)); if (fp == null) return null; JarFile jarFile = new JarFile(fp, true); return ResourceLoaders.createJarResourceLoader(name, jarFile); } #location 5 #vulnerability type RESOURCE_LEAK