input
stringlengths
205
73.3k
output
stringlengths
64
73.2k
instruction
stringclasses
1 value
#vulnerable code public void prepareIoc() throws Exception { if (ctx.getComboIocLoader() == null) { int asyncPoolSize = ctx.getConfigureLoader().get().getInt("nutz.ioc.async.poolSize", 64); List<String> args = new ArrayList<>(); args.add("*js"); ...
#fixed code public void prepareIoc() throws Exception { if (ctx.getComboIocLoader() == null) { int asyncPoolSize = ctx.getConfigureLoader().get().getInt("nutz.ioc.async.poolSize", 64); List<String> args = new ArrayList<>(); args.add("*js"); arg...
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public void prepareBasic() throws Exception { if (this.ctx == null) { ctx = AppContext.getDefault(); } if (ctx.getMainClass() == null && mainClass != null) ctx.setMainClass(mainClass); // 检查ClassLoader的情况 if (...
#fixed code public void prepareBasic() throws Exception { // 检查ClassLoader的情况 if (ctx.getClassLoader() == null) ctx.setClassLoader(NbApp.class.getClassLoader()); if (ctx.getEnvHolder() == null) { ctx.setEnvHolder(new SystemProperti...
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public void _run() throws Exception { Stopwatch sw = Stopwatch.begin(); // 各种预备操作 this.prepare(); if (printProcDoc) { PropDocReader docReader = new PropDocReader(ctx); docReader.load(); Logs.get().inf...
#fixed code public void _run() throws Exception { Stopwatch sw = Stopwatch.begin(); // 各种预备操作 this.prepare(); // 依次启动 try { ctx.init(); ctx.startServers(); if (ctx.getMainClass().getAnnotation(IocBean.class) ...
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public void shutdown() { log.info("ok, shutting down ..."); synchronized (lock) { lock.notify(); } } #location 2 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code public void shutdown() { log.info("ok, shutting down ..."); if (lock == null) { _shutdown(); } else { synchronized (lock) { lock.notify(); } } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public void _run() throws Exception { Stopwatch sw = Stopwatch.begin(); // 各种预备操作 this.prepare(); if (printProcDoc) { PropDocReader docReader = new PropDocReader(ctx); docReader.load(); Logs.get().info("Configure Man...
#fixed code public void _run() throws Exception { Stopwatch sw = Stopwatch.begin(); // 各种预备操作 this.prepare(); if (printProcDoc) { PropDocReader docReader = new PropDocReader(ctx); docReader.load(); Logs.get().info("Configure Manual:\r...
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public void prepare() throws Exception { if (prepared) return; // 初始化上下文 listeners.forEach((listener)->listener.whenPrepareBasic(this, EventType.before)); this.prepareBasic(); listeners.forEach((listener)->listener.whe...
#fixed code public void prepare() throws Exception { if (prepared) return; // 初始化上下文 listeners.forEach((listener)->listener.whenPrepareBasic(this, EventType.before)); this.prepareBasic(); listeners.forEach((listener)->listener.whenPrepa...
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @RequestMapping("/logout") public String logout(HttpServletRequest request) { HttpSession session = request.getSession(); // 注销本地会话 if (session != null) { session.invalidate(); } // 如果是客户端发起的注销请求 String token = (String) session.getAttribute(AuthConst....
#fixed code @RequestMapping("/logout") public String logout(HttpServletRequest request) { HttpSession session = request.getSession(); if (session != null) { session.invalidate(); } return "redirect:/"; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void testBugSentences() throws IOException { String[] bugSentences = new String[] { "干脆就把那部蒙人的闲法给废了拉倒!RT @laoshipukong : 27日,全国人大常委会第三次审议侵权责任法草案,删除了有关医疗损害责任“举证倒置”的规定。在医患纠纷中本已处于弱势地位的消费者由此将陷入万劫不复的境地。 " }; JiebaAnalyzer analyzer = new Jieba...
#fixed code @Test public void testBugSentences() throws IOException { String[] bugSentences = new String[] { "干脆就把那部蒙人的闲法给废了拉倒!RT @laoshipukong : 27日,全国人大常委会第三次审议侵权责任法草案,删除了有关医疗损害责任“举证倒置”的规定。在医患纠纷中本已处于弱势地位的消费者由此将陷入万劫不复的境地。 " }; JiebaAnalyzer analyzer = new JiebaAnalyz...
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void test() throws IOException { JiebaAnalyzer analyzer = new JiebaAnalyzer("index", new File("data"), true); for (String sentence : sentences) { TokenStream tokenStream = analyzer.tokenStream(null, ...
#fixed code @Test public void test() throws IOException { JiebaAnalyzer analyzer = new JiebaAnalyzer("index", new File("data"), true); for (String sentence : sentences) { TokenStream tokenStream = analyzer.tokenStream(null, new StringR...
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void testSegModeOther() throws IOException { JiebaAnalyzer analyzer = new JiebaAnalyzer("other", new File("data"), true); for (String sentence : sentences) { TokenStream tokenStream = analyzer.tokenStream(nul...
#fixed code @Test public void testSegModeOther() throws IOException { JiebaAnalyzer analyzer = new JiebaAnalyzer("other", new File("data"), true); for (String sentence : sentences) { TokenStream tokenStream = analyzer.tokenStream(null, ...
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @RequestMapping(value = "/cluster/info/ajax", method = RequestMethod.GET) public void clusterAjax(HttpServletResponse response, HttpServletRequest request) { response.setContentType("text/html;charset=utf-8"); response.setCharacterEncoding("utf-8"); response.setHead...
#fixed code @RequestMapping(value = "/cluster/info/ajax", method = RequestMethod.GET) public void clusterAjax(HttpServletResponse response, HttpServletRequest request) { response.setContentType("text/html;charset=utf-8"); response.setCharacterEncoding("utf-8"); response.setHeader("Ch...
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @RequestMapping(value = "/consumer/offset/{group}/{topic}/ajax", method = RequestMethod.GET) public void offsetDetailAjax(@PathVariable("group") String group, @PathVariable("topic") String topic, HttpServletResponse response, HttpServletRequest request) { response.setCo...
#fixed code @RequestMapping(value = "/consumer/offset/{group}/{topic}/ajax", method = RequestMethod.GET) public void offsetDetailAjax(@PathVariable("group") String group, @PathVariable("topic") String topic, HttpServletResponse response, HttpServletRequest request) { response.setContentT...
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public static long getLogSize(List<String> hosts, String topic, int partition) { LOG.info("Find leader hosts [" + hosts + "]"); PartitionMetadata metadata = findLeader(hosts, topic, partition); if (metadata == null) { LOG.error("[KafkaClusterUtils.getLogSize()] - ...
#fixed code public static long getLogSize(List<String> hosts, String topic, int partition) { LOG.info("Find leader hosts [" + hosts + "]"); PartitionMetadata metadata = findLeader(hosts, topic, partition); if (metadata == null) { LOG.error("[KafkaClusterUtils.getLogSize()] - Can't ...
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @RequestMapping(value = "/dash/kafka/ajax", method = RequestMethod.GET) public void dashboardAjax(HttpServletResponse response, HttpServletRequest request) { response.setContentType("text/html;charset=utf-8"); response.setCharacterEncoding("utf-8"); response.setHead...
#fixed code @RequestMapping(value = "/dash/kafka/ajax", method = RequestMethod.GET) public void dashboardAjax(HttpServletResponse response, HttpServletRequest request) { response.setContentType("text/html;charset=utf-8"); response.setCharacterEncoding("utf-8"); response.setHeader("Ch...
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @RequestMapping(value = "/topic/meta/{tname}/ajax", method = RequestMethod.GET) public void topicMetaAjax(@PathVariable("tname") String tname, HttpServletResponse response, HttpServletRequest request) { response.setContentType("text/html;charset=utf-8"); response.setC...
#fixed code @RequestMapping(value = "/topic/meta/{tname}/ajax", method = RequestMethod.GET) public void topicMetaAjax(@PathVariable("tname") String tname, HttpServletResponse response, HttpServletRequest request) { response.setContentType("text/html;charset=utf-8"); response.setCharact...
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @RequestMapping(value = "/consumer/offset/{group}/{topic}/realtime/ajax", method = RequestMethod.GET) public void offsetGraphAjax(@PathVariable("group") String group, @PathVariable("topic") String topic, HttpServletResponse response, HttpServletRequest request) { respon...
#fixed code @RequestMapping(value = "/consumer/offset/{group}/{topic}/realtime/ajax", method = RequestMethod.GET) public void offsetGraphAjax(@PathVariable("group") String group, @PathVariable("topic") String topic, HttpServletResponse response, HttpServletRequest request) { response.set...
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public static List<KafkaMetaDomain> findLeader(String topic) { List<KafkaMetaDomain> list = new ArrayList<>(); SimpleConsumer consumer = null; for (KafkaBrokerDomain broker : getBrokers()) { try { consumer = new SimpleConsumer(broker.getHost(), broker.getPort...
#fixed code public static List<KafkaMetaDomain> findLeader(String topic) { List<KafkaMetaDomain> list = new ArrayList<>(); SimpleConsumer consumer = null; for (KafkaBrokerDomain broker : getBrokers()) { try { consumer = new SimpleConsumer(broker.getHost(), broker.getPort(), 10...
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @RequestMapping(value = "/alarm/topic/ajax", method = RequestMethod.GET) public void alarmTopicAjax(HttpServletResponse response, HttpServletRequest request) { response.setContentType("text/html;charset=utf-8"); response.setCharacterEncoding("utf-8"); response.setHe...
#fixed code @RequestMapping(value = "/alarm/topic/ajax", method = RequestMethod.GET) public void alarmTopicAjax(HttpServletResponse response, HttpServletRequest request) { response.setContentType("text/html;charset=utf-8"); response.setCharacterEncoding("utf-8"); response.setHeader("...
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public static boolean emptyDirectory(File directory) { boolean result = true; File[] entries = directory.listFiles(); for (int i = 0; i < entries.length; i++) { if (!entries[i].delete()) { result = false; }...
#fixed code public static boolean emptyDirectory(File directory) { boolean result = true; File[] entries = directory.listFiles(); for (File entry : entries) { if (!entry.delete()) { result = false; } } return...
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public List<ColumnInfo> getMetaData(String tableName) throws SQLException { // 获取主键 ResultSet keyResultSet = connection.getMetaData().getPrimaryKeys(null, null, tableName); String primaryKey = null; if (keyResultSet.next()) { ...
#fixed code public List<ColumnInfo> getMetaData(String tableName) throws Exception { // 获取主键 ResultSet keyResultSet = connection.getMetaData().getPrimaryKeys(null, getSchema(connection), tableName.toUpperCase()); String primaryKey = null; if (keyResultSet....
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code private Set<RaftPeerId> getHigherPriorityPeers(RaftConfiguration conf) { Set<RaftPeerId> higherPriorityPeers = new HashSet<>(); int currPriority = conf.getPeer(server.getId()).getPriority(); Collection<RaftPeer> peers = conf.getPeers(); for (RaftPeer pee...
#fixed code private Set<RaftPeerId> getHigherPriorityPeers(RaftConfiguration conf) { Set<RaftPeerId> higherPriorityPeers = new HashSet<>(); int currPriority = conf.getPeer(server.getId()).getPriority(); final Collection<RaftPeer> peers = conf.getAllPeers(); for (RaftPeer ...
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public void runTestDataStream(){ final int bufferSize = 1024*1024; final int bufferNum = 10; final DataStreamOutput out = client.stream(); //send request final List<CompletableFuture<DataStreamReply>> futures = new ArrayList<>(); futures.add(sendR...
#fixed code public void runTestDataStream(){ final int bufferSize = 1024*1024; final int bufferNum = 10; final DataStreamOutput out = client.stream(); DataStreamClientImpl.DataStreamOutputImpl impl = (DataStreamClientImpl.DataStreamOutputImpl) out; final List<Completab...
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public static void main(String[] args) { VerificationTool tool = new VerificationTool(); JCommander.newBuilder() .addObject(tool) .build() .parse(args); System.out.println(tool.metaQuorum); ...
#fixed code public static void main(String[] args) throws IOException { VerificationTool tool = new VerificationTool(); JCommander jc = JCommander.newBuilder() .addObject(tool) .build(); jc.parse(args); if (tool.hel...
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code private static void checkFollowerCommitLagsLeader(MiniRaftCluster cluster) { List<RaftServerImpl> followers = cluster.getFollowers(); RaftServerImpl leader = cluster.getLeader(); RatisMetricRegistry leaderMetricsRegistry = RatisMetrics.getMetricRegist...
#fixed code private static void checkFollowerCommitLagsLeader(MiniRaftCluster cluster) { List<RaftServerImpl> followers = cluster.getFollowers(); RaftServerImpl leader = cluster.getLeader(); Gauge leaderCommitGauge = RaftServerMetrics .getPeerCommitIndexGauge(leader, l...
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code private static Map<RaftPeer, NettyRpcService> initRpcServices( Collection<RaftServer> servers, RaftConfiguration conf) { final Map<RaftPeer, NettyRpcService> peerRpcs = new HashMap<>(); for (RaftServer s : servers) { final String address = getAddress(...
#fixed code private static Map<RaftPeer, NettyRpcService> initRpcServices( Collection<RaftServer> servers, RaftConfiguration conf) { final Map<RaftPeer, NettyRpcService> peerRpcs = new HashMap<>(); for (RaftServer s : servers) { final NettyRpcService rpc = newNettyRpcS...
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code private static void saveMD5File(File dataFile, String digestString) throws IOException { File md5File = getDigestFileForFile(dataFile); String md5Line = digestString + " *" + dataFile.getName() + "\n"; AtomicFileOutputStream afos = new AtomicFileOutputS...
#fixed code private static void saveMD5File(File dataFile, String digestString) throws IOException { File md5File = getDigestFileForFile(dataFile); String md5Line = digestString + " *" + dataFile.getName() + "\n"; try (AtomicFileOutputStream afos = new AtomicFil...
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @BeforeClass public static void beforeClass() { cluster = new LogServiceCluster(3); cluster.createWorkers(3); List<LogServer> workers = cluster.getWorkers(); assert(workers.size() == 3); } #location 6 ...
#fixed code @BeforeClass public static void beforeClass() { cluster = new LogServiceCluster(3); cluster.createWorkers(3); workers = cluster.getWorkers(); assert(workers.size() == 3); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @BeforeClass public static void beforeClass() { cluster = new LogServiceCluster(3); cluster.createWorkers(3); workers = cluster.getWorkers(); assert(workers.size() == 3); } #location 6 ...
#fixed code @BeforeClass public static void beforeClass() { cluster = new LogServiceCluster(3); cluster.createWorkers(3); workers = cluster.getWorkers(); assert(workers.size() == 3); RaftProperties properties = new RaftProperties(); Ra...
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public void assertServer(MiniRaftCluster cluster, ClientId clientId, long callId, long oldLastApplied) throws Exception { final long leaderApplied = RaftServerTestUtil.getLastAppliedIndex(cluster.getLeader()); // make sure retry cache has the entry for (RaftSe...
#fixed code public void assertServer(MiniRaftCluster cluster, ClientId clientId, long callId, long oldLastApplied) throws Exception { final long leaderApplied = cluster.getLeader().getInfo().getLastAppliedIndex(); // make sure retry cache has the entry for (RaftServer.Division ...
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code private void setupServer(){ servers = new ArrayList<>(peers.size()); singleDataStreamStateMachines = new ArrayList<>(peers.size()); // start stream servers on raft peers. for (int i = 0; i < peers.size(); i++) { SingleDataStreamStateMachine singleDat...
#fixed code private void setupServer(){ servers = new ArrayList<>(peers.size()); singleDataStreamStateMachines = new ArrayList<>(peers.size()); // start stream servers on raft peers. for (int i = 0; i < peers.size(); i++) { SingleDataStreamStateMachine singleDataStrea...
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void testZeroSizeInProgressFile() throws Exception { final RaftStorage storage = new RaftStorage(storageDir, StartupOption.REGULAR); final File file = storage.getStorageDir().getOpenLogFile(0); storage.close(); // create zero size in-progre...
#fixed code @Test public void testZeroSizeInProgressFile() throws Exception { final RaftStorage storage = RaftStorageTestUtils.newRaftStorage(storageDir); final File file = storage.getStorageDir().getOpenLogFile(0); storage.close(); // create zero size in-progress file ...
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void testDataStreamDisabled() throws Exception { try { setup(1); final DataStreamClientImpl client = newDataStreamClientImpl(); exception.expect(UnsupportedOperationException.class); exception.expectMessage(DisabledDataStreamClie...
#fixed code @Test public void testDataStreamDisabled() throws Exception { try { setup(1); final RaftClient client = newRaftClientForDataStream(); exception.expect(UnsupportedOperationException.class); exception.expectMessage(DisabledDataStreamClientFactory.cla...
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test(timeout = 1000) public void testMultipleTasks() throws Exception { final TimeoutScheduler scheduler = TimeoutScheduler.newInstance(1); final TimeDuration grace = TimeDuration.valueOf(100, TimeUnit.MILLISECONDS); scheduler.setGracePeriod(grace); Ass...
#fixed code @Test(timeout = 1000) public void testMultipleTasks() throws Exception { final TimeoutScheduler scheduler = TimeoutScheduler.newInstance(); final TimeDuration grace = TimeDuration.valueOf(100, TimeUnit.MILLISECONDS); scheduler.setGracePeriod(grace); Assert.ass...
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code private Map<String, List<CompletableFuture<DataStreamReply>>> streamWrite( List<String> paths, FileStoreClient fileStoreClient) throws IOException { Map<String, List<CompletableFuture<DataStreamReply>>> fileMap = new HashMap<>(); for(String path : paths) { ...
#fixed code private Map<String, List<CompletableFuture<DataStreamReply>>> streamWrite( List<String> paths, FileStoreClient fileStoreClient) throws IOException { Map<String, List<CompletableFuture<DataStreamReply>>> fileMap = new HashMap<>(); for(String path : paths) { F...
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code protected void setup(int numServers){ peers = Arrays.stream(MiniRaftCluster.generateIds(numServers, 0)) .map(RaftPeerId::valueOf) .map(id -> new RaftPeer(id, NetUtils.createLocalServerAddress())) .collect(Collectors.toList()); servers = new...
#fixed code protected void setup(int numServers){ final List<RaftPeer> peers = Arrays.stream(MiniRaftCluster.generateIds(numServers, 0)) .map(RaftPeerId::valueOf) .map(id -> new RaftPeer(id, NetUtils.createLocalServerAddress())) .collect(Collectors.toList()); ...
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public void assertServer(MiniRaftCluster cluster, ClientId clientId, long callId, long oldLastApplied) throws Exception { long leaderApplied = cluster.getLeader().getState().getLastAppliedIndex(); // make sure retry cache has the entry for (RaftServerImpl serv...
#fixed code public void assertServer(MiniRaftCluster cluster, ClientId clientId, long callId, long oldLastApplied) throws Exception { final long leaderApplied = RaftServerTestUtil.getLastAppliedIndex(cluster.getLeader()); // make sure retry cache has the entry for (RaftServer.D...
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test(timeout = 1000) public void testRestartingScheduler() throws Exception { final TimeoutScheduler scheduler = TimeoutScheduler.newInstance(1); final TimeDuration grace = TimeDuration.valueOf(100, TimeUnit.MILLISECONDS); scheduler.setGracePeriod(grace); ...
#fixed code @Test(timeout = 1000) public void testRestartingScheduler() throws Exception { final TimeoutScheduler scheduler = TimeoutScheduler.newInstance(); final TimeDuration grace = TimeDuration.valueOf(100, TimeUnit.MILLISECONDS); scheduler.setGracePeriod(grace); Asse...
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test(timeout = 1000) public void testSingleTask() throws Exception { final TimeoutScheduler scheduler = TimeoutScheduler.newInstance(1); final TimeDuration grace = TimeDuration.valueOf(100, TimeUnit.MILLISECONDS); scheduler.setGracePeriod(grace); Assert...
#fixed code @Test(timeout = 1000) public void testSingleTask() throws Exception { final TimeoutScheduler scheduler = TimeoutScheduler.newInstance(); final TimeDuration grace = TimeDuration.valueOf(100, TimeUnit.MILLISECONDS); scheduler.setGracePeriod(grace); Assert.assert...
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code private Map<String, List<CompletableFuture<DataStreamReply>>> streamWrite( List<String> paths, FileStoreClient fileStoreClient) throws IOException { Map<String, List<CompletableFuture<DataStreamReply>>> fileMap = new HashMap<>(); for(String path : paths) { ...
#fixed code private Map<String, List<CompletableFuture<DataStreamReply>>> streamWrite( List<String> paths, FileStoreClient fileStoreClient) throws IOException { Map<String, List<CompletableFuture<DataStreamReply>>> fileMap = new HashMap<>(); for(String path : paths) { F...
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void testDataStreamDisabled() throws Exception { try { setup(1); final DataStreamClientImpl client = newDataStreamClientImpl(); exception.expect(UnsupportedOperationException.class); exception.expectMessage(DisabledDataStreamClie...
#fixed code @Test public void testDataStreamDisabled() throws Exception { try { setup(1); final RaftClient client = newRaftClientForDataStream(); exception.expect(UnsupportedOperationException.class); exception.expectMessage(DisabledDataStreamClientFactory.cla...
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test(timeout = 1000) public void testExtendingGracePeriod() throws Exception { final TimeoutScheduler scheduler = TimeoutScheduler.newInstance(1); final TimeDuration grace = TimeDuration.valueOf(100, TimeUnit.MILLISECONDS); scheduler.setGracePeriod(grace); ...
#fixed code @Test(timeout = 1000) public void testExtendingGracePeriod() throws Exception { final TimeoutScheduler scheduler = TimeoutScheduler.newInstance(); final TimeDuration grace = TimeDuration.valueOf(100, TimeUnit.MILLISECONDS); scheduler.setGracePeriod(grace); Ass...
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Override protected void operation(RaftClient client) throws IOException { int length = Integer.parseInt(size); int num = Integer.parseInt(numFiles); AtomicLong totalBytes = new AtomicLong(0); String entropy = RandomStringUtils.randomAlphanumeric(10); ...
#fixed code @Override protected void operation(RaftClient client) throws IOException { List<String> paths = generateFiles(); FileStoreClient fileStoreClient = new FileStoreClient(client); System.out.println("Starting Async write now "); long startTime = System.currentTim...
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Override public String toString() { return peer.getId() + "(next=" + nextIndex + ", match=" + matchIndex + "," + " attendVote=" + attendVote + ", lastRpcSendTime=" + lastRpcSendTime.get().elapsedTimeMs() + ", lastRpcResponseTime=" + lastRpcR...
#fixed code @Override public String toString() { return name + "(c" + getCommitIndex() + ",m" + getMatchIndex() + ",n" + getNextIndex() + ", attendVote=" + attendVote + ", lastRpcSendTime=" + lastRpcSendTime.get().elapsedTimeMs() + ", lastRpcResponseTime=" + l...
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public static Inventory deserializeInventory(JsonElement data, String title) { Preconditions.checkArgument(data.isJsonPrimitive()); try (ByteArrayInputStream inputStream = new ByteArrayInputStream(Base64Coder.decodeLines(data.getAsString()))) { ...
#fixed code public static Inventory deserializeInventory(JsonElement data, String title) { Preconditions.checkArgument(data.isJsonPrimitive()); return InventorySerialization.decodeInventory(data.getAsString(), title); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Override protected void enable() { // provide an info command Commands.create() .handler(c -> { LoaderUtils.getHelperImplementationPlugins().stream() .sorted(Comparator.comparing(Plugin...
#fixed code @Override protected void enable() { // provide an info command if (getConfig().getBoolean("info-command", true)) { Commands.create() .handler(c -> LoaderUtils.getHelperImplementationPlugins().stream() ...
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public static ItemStack deserializeItemstack(JsonElement data) { Preconditions.checkArgument(data.isJsonPrimitive()); try (ByteArrayInputStream inputStream = new ByteArrayInputStream(Base64Coder.decodeLines(data.getAsString()))) { try (Bukkit...
#fixed code public static ItemStack deserializeItemstack(JsonElement data) { Preconditions.checkArgument(data.isJsonPrimitive()); return InventorySerialization.decodeItemStack(data.getAsString()); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Override public final void onEnable() { // schedule cleanup of the registry Scheduler.runTaskRepeatingAsync(terminableRegistry::cleanup, 600L, 600L).bindWith(terminableRegistry); // call subclass enable(); } ...
#fixed code @Override public final void onEnable() { // schedule cleanup of the registry Scheduler.builder() .async() .after(10, TimeUnit.SECONDS) .every(30, TimeUnit.SECONDS) .run(terminableRegistry::cle...
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public static ItemStack[] deserializeItemstacks(JsonElement data) { Preconditions.checkArgument(data.isJsonPrimitive()); try (ByteArrayInputStream inputStream = new ByteArrayInputStream(Base64Coder.decodeLines(data.getAsString()))) { try (Buk...
#fixed code public static ItemStack[] deserializeItemstacks(JsonElement data) { Preconditions.checkArgument(data.isJsonPrimitive()); return InventorySerialization.decodeItemStacks(data.getAsString()); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public synchronized boolean saveApi(ApiResult apiResult) { boolean successful = false; Connection connection = null; PreparedStatement preparedStatement = null; ResultSet resultSet = null; try { connection = this.dbC...
#fixed code public synchronized boolean saveApi(ApiResult apiResult) { boolean successful = false; Connection connection; PreparedStatement preparedStatement = null; try { connection = this.dbConfig.getConnection(); preparedStatem...
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public synchronized boolean saveApi(ApiResult apiResult) { boolean successful = false; Connection conn = null; PreparedStatement stmt = null; ResultSet rs = null; try { conn = this.dbConfig.getConnection(); ...
#fixed code public synchronized boolean saveApi(ApiResult apiResult) { boolean successful = false; Connection connection = null; PreparedStatement preparedStatement = null; ResultSet resultSet = null; try { connection = this.dbConfig....
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public void getGitChangeSets() throws IOException, GitAPIException { Repository localRepository = new FileRepository(new File("./repo/server/.git")); Git git = new Git(localRepository); Iterable<RevCommit> logs = git.log().call(); List<...
#fixed code public void getGitChangeSets() throws IOException, GitAPIException { Repository localRepository = new FileRepository(new File("./repo/server/.git")); Git git = new Git(localRepository); Iterable<RevCommit> logs = git.log().call(); List<String...
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public static List<String> readFileLinesGuessEncoding(String filePath, int maxFileLineDepth) throws IOException { BufferedReader reader = new BufferedReader( new InputStreamReader( new FileInputStream(filePath), guessCharset(new File(filePath)))); List<...
#fixed code public static List<String> readFileLinesGuessEncoding(String filePath, int maxFileLineDepth) throws IOException { List<String> fileLines = new ArrayList<>(); BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(filePath), guessC...
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public void execute(JobExecutionContext context) throws JobExecutionException { Thread.currentThread().setPriority(Thread.MIN_PRIORITY); while(CodeIndexer.shouldPauseAdding()) { Singleton.getLogger().info("Pausing parser."); retu...
#fixed code public void execute(JobExecutionContext context) throws JobExecutionException { if (isEnabled() == false) { return; } Thread.currentThread().setPriority(Thread.MIN_PRIORITY); while(CodeIndexer.shouldPauseAdding()) { S...
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public synchronized void deleteRepoByName(String repositoryName) { Connection conn = null; PreparedStatement stmt = null; ResultSet rs = null; try { conn = this.dbConfig.getConnection(); stmt = conn.prepareStateme...
#fixed code public synchronized void deleteRepoByName(String repositoryName) { Connection connection = null; PreparedStatement preparedStatement = null; ResultSet resultSet = null; try { connection = this.dbConfig.getConnection(); ...
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public SlocCount countStats(String contents, String languageName) { if (contents == null || contents.isEmpty()) { return new SlocCount(); } FileClassifierResult fileClassifierResult = this.database.get(languageName); State c...
#fixed code public SlocCount countStats(String contents, String languageName) { if (contents == null || contents.isEmpty()) { return new SlocCount(); } FileClassifierResult fileClassifierResult = this.database.get(languageName); State current...
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public String languageGuesser(String fileName) { fileName = fileName.toLowerCase(); String extension = this.getExtension(fileName); for (String key: database.keySet()) { FileClassifierResult fileClassifierResult = database.get(key);...
#fixed code public String languageGuesser(String fileName) { fileName = fileName.toLowerCase(); String extension; Optional<String> lang = this.checkIfExtentionExists(fileName); if (!lang.isPresent()) { extension = this.getExtension(fileName);...
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public static List<String> readFileLines(String filePath, int maxFileLineDepth) throws FileNotFoundException { List<String> lines = new ArrayList<>(); Scanner input = new Scanner(new File(filePath)); int counter = 0; while(input.hasNext...
#fixed code public static List<String> readFileLines(String filePath, int maxFileLineDepth) throws FileNotFoundException { List<String> lines = new ArrayList<>(); Scanner input = new Scanner(new File(filePath)); try { int counter = 0; whil...
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Override public synchronized boolean saveRepo(RepoResult repoResult) { RepoResult existing = this.getRepoByName(repoResult.getName()); this.cache.remove(repoResult.getName()); boolean isNew = false; Connection conn = null; ...
#fixed code @Override public synchronized boolean saveRepo(RepoResult repoResult) { RepoResult existing = this.getRepoByName(repoResult.getName()); this.cache.remove(repoResult.getName()); boolean isNew = false; Connection connection = null; ...
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public RepositoryChanged updateSvnRepository(String repoName, String repoRemoteLocation, String repoUserName, String repoPassword, String repoLocations, boolean useCredentials) { boolean changed = false; List<String> changedFiles = new ArrayList<>(); ...
#fixed code public RepositoryChanged updateSvnRepository(String repoName, String repoRemoteLocation, String repoUserName, String repoPassword, String repoLocations, boolean useCredentials) { boolean changed = false; List<String> changedFiles = new ArrayList<>(); L...
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public synchronized void createTableIfMissing() { Connection connection; PreparedStatement preparedStatement = null; ResultSet resultSet = null; try { connection = this.dbConfig.getConnection(); preparedStatement...
#fixed code public synchronized void createTableIfMissing() { Connection connection; PreparedStatement preparedStatement = null; ResultSet resultSet = null; try { connection = this.dbConfig.getConnection(); preparedStatement = conn...
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public synchronized void deleteApiByPublicKey(String publicKey) { Connection conn = null; PreparedStatement stmt = null; ResultSet rs = null; try { conn = this.dbConfig.getConnection(); stmt = conn.prepareStatemen...
#fixed code public synchronized void deleteApiByPublicKey(String publicKey) { Connection connection = null; PreparedStatement preparedStatement = null; ResultSet resultSet = null; try { connection = this.dbConfig.getConnection(); p...
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public void testSaveRetrieve() { String randomApiString = this.getRandomString(); this.api.saveApi(new ApiResult(0, randomApiString, "privateKey", "", "")); ApiResult apiResult = this.api.getApiByPublicKey(randomApiString); assertThat(a...
#fixed code public void testSaveRetrieve() { String randomApiString = this.getRandomString(); this.api.saveApi(new ApiResult(0, randomApiString, "privateKey", "", "")); Optional<ApiResult> apiByPublicKey = this.api.getApiByPublicKey(randomApiString); ass...
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public synchronized void deleteApiByPublicKey(String publicKey) { Connection connection = null; PreparedStatement preparedStatement = null; ResultSet resultSet = null; try { connection = this.dbConfig.getConnection(); ...
#fixed code public synchronized void deleteApiByPublicKey(String publicKey) { Connection connection; PreparedStatement preparedStatement = null; try { connection = this.dbConfig.getConnection(); preparedStatement = connection.prepareStatem...
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public List<CodeOwner> getBlameInfoExternal(int codeLinesSize, String repoName, String repoLocations, String fileName) { List<CodeOwner> codeOwners = new ArrayList<>(codeLinesSize); // -w is to ignore whitespace bug ProcessBuilder processBuilder...
#fixed code public List<CodeOwner> getBlameInfoExternal(int codeLinesSize, String repoName, String repoLocations, String fileName) { List<CodeOwner> codeOwners = new ArrayList<>(codeLinesSize); // -w is to ignore whitespace bug ProcessBuilder processBuilder = new...
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public static java.util.Properties getProperties() { if (properties == null) { properties = new java.util.Properties(); try { properties.load(new FileInputStream("searchcode.properties")); } catch (IOException ...
#fixed code public static java.util.Properties getProperties() { if (properties == null) { properties = new java.util.Properties(); FileInputStream fileInputStream = null; try { fileInputStream = new FileInputStream("searchcode....
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public void testRepoSaveDelete() { this.repo.saveRepo(new RepoResult(-1, "myname", "git", "myurl", "username", "password", "mysource", "mybranch", "{}")); RepoResult result = this.repo.getRepoByName("myname"); assertThat(result.getName()).isEqua...
#fixed code public void testRepoSaveDelete() { this.repo.saveRepo(new RepoResult(-1, "myname", "git", "myurl", "username", "password", "mysource", "mybranch", "{}")); Optional<RepoResult> repoResult = this.repo.getRepoByName("myname"); RepoResult result = repoResu...
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public RepositoryChanged checkoutSvnRepository(String repoName, String repoRemoteLocation, String repoUserName, String repoPassword, String repoLocations, boolean useCredentials) { boolean successful = false; Singleton.getLogger().info("Attempting to che...
#fixed code public RepositoryChanged checkoutSvnRepository(String repoName, String repoRemoteLocation, String repoUserName, String repoPassword, String repoLocations, boolean useCredentials) { boolean successful = false; Singleton.getLogger().info("Attempting to checkout ...
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public void testIsBinaryWhiteListedExtension() { SearchcodeLib sl = new SearchcodeLib(); ArrayList<String> codeLines = new ArrayList<>(); codeLines.add("你你你你你你你你你你你你你你你你你你你你你你你你你你你"); FileClassifier fileClassifier = new FileClassifier();...
#fixed code public void testIsBinaryWhiteListedExtension() { SearchcodeLib sl = new SearchcodeLib(); ArrayList<String> codeLines = new ArrayList<>(); codeLines.add("你你你你你你你你你你你你你你你你你你你你你你你你你你你"); FileClassifier fileClassifier = new FileClassifier(); ...
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Override public void indexDocument(Queue<CodeIndexDocument> documentQueue) throws IOException { // Need to connect to each sphinx config eventually SphinxSearchConfig sphinxSearchConfig = new SphinxSearchConfig(); Connection connection = nul...
#fixed code @Override public void indexDocument(Queue<CodeIndexDocument> documentQueue) throws IOException { // Need to connect to each sphinx config eventually SphinxSearchConfig sphinxSearchConfig = new SphinxSearchConfig(); Connection connection = null; ...
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code private CodeOwner getInfoExternal(int codeLinesSize, String repoName, String repoLocations, String fileName) { CodeOwner owner = new CodeOwner("Unknown", codeLinesSize, (int)(System.currentTimeMillis() / 1000)); ProcessBuilder processBuilder = new Proce...
#fixed code private CodeOwner getInfoExternal(int codeLinesSize, String repoName, String repoLocations, String fileName) { CodeOwner owner = new CodeOwner("Unknown", codeLinesSize, (int)(System.currentTimeMillis() / 1000)); ProcessBuilder processBuilder = new ProcessBuil...
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Override public synchronized boolean saveRepo(RepoResult repoResult) { RepoResult existing = this.getRepoByName(repoResult.getName()); this.cache.remove(repoResult.getName()); boolean isNew = false; Connection conn = null; ...
#fixed code @Override public synchronized boolean saveRepo(RepoResult repoResult) { RepoResult existing = this.getRepoByName(repoResult.getName()); this.cache.remove(repoResult.getName()); boolean isNew = false; Connection connection = null; ...
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public SourceCodeDTO saveCode(CodeIndexDocument codeIndexDocument) { Optional<SourceCodeDTO> existing = this.getByCodeIndexDocument(codeIndexDocument); Connection conn = null; PreparedStatement stmt = null; try { conn = thi...
#fixed code public SourceCodeDTO saveCode(CodeIndexDocument codeIndexDocument) { Optional<SourceCodeDTO> existing = this.getByCodeIndexDocument(codeIndexDocument); Connection conn = null; PreparedStatement stmt = null; try { conn = this.dbCo...
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public void testMultipleRetrieveCache() { String randomApiString = this.getRandomString(); this.api.saveApi(new ApiResult(0, randomApiString, "privateKey", "", "")); for(int i=0; i < 500; i++) { ApiResult apiResult = this.api.getApi...
#fixed code public void testMultipleRetrieveCache() { String randomApiString = this.getRandomString(); this.api.saveApi(new ApiResult(0, randomApiString, "privateKey", "", "")); for(int i=0; i < 500; i++) { Optional<ApiResult> apiByPublicKey = this.a...
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public static List<String> readFileLinesGuessEncoding(String filePath, int maxFileLineDepth) throws IOException { BufferedReader reader = new BufferedReader( new InputStreamReader( new FileInputStream(filePath), guessCharset(new File(filePath)))); List<...
#fixed code public static List<String> readFileLinesGuessEncoding(String filePath, int maxFileLineDepth) throws IOException { List<String> fileLines = new ArrayList<>(); BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(filePath), guessC...
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public String getCurrentRevision(String repoLocations, String repoName) { String currentRevision = ""; ProcessBuilder processBuilder = new ProcessBuilder(this.SVNBINARYPATH, "info", "--xml"); processBuilder.directory(new File(repoLocations + rep...
#fixed code public String getCurrentRevision(String repoLocations, String repoName) { String currentRevision = ""; ProcessBuilder processBuilder = new ProcessBuilder(this.SVNBINARYPATH, "info", "--xml"); processBuilder.directory(new File(repoLocations + repoName)...
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public void testExecuteNothingInQueue() throws JobExecutionException { IndexGitRepoJob indexGitRepoJob = new IndexGitRepoJob(); IndexGitRepoJob spy = spy(indexGitRepoJob); when(spy.getNextQueuedRepo()).thenReturn(new UniqueRepoQueue()); ...
#fixed code public void testExecuteNothingInQueue() throws JobExecutionException { IndexGitRepoJob indexGitRepoJob = new IndexGitRepoJob(); IndexGitRepoJob spy = spy(indexGitRepoJob); when(spy.getNextQueuedRepo()).thenReturn(new UniqueRepoQueue()); JobEx...
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public synchronized boolean saveData(String key, String value) { String existing = this.getDataByName(key); boolean isNew = false; Connection conn = null; PreparedStatement stmt = null; ResultSet rs = null; if (existing...
#fixed code public synchronized boolean saveData(String key, String value) { String existing = this.getDataByName(key); boolean isNew = false; Connection connection = null; PreparedStatement preparedStatement = null; try { connection ...
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public synchronized void deleteRepoByName(String repositoryName) { Connection connection; PreparedStatement preparedStatement = null; ResultSet resultSet = null; try { connection = this.dbConfig.getConnection(); p...
#fixed code public synchronized void deleteRepoByName(String repositoryName) { ConnStmtRs connStmtRs = new ConnStmtRs(); try { connStmtRs.conn = this.dbConfig.getConnection(); connStmtRs.stmt = connStmtRs.conn.prepareStatement("delete from repo wh...
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public RepositoryChanged getDiffBetweenRevisions(String repoLocations, String repoName, String startRevision) { // svn diff -r 4000:HEAD --summarize --xml List<String> changedFiles = new ArrayList<>(); List<String> deletedFiles = new ArrayList<>...
#fixed code public RepositoryChanged getDiffBetweenRevisions(String repoLocations, String repoName, String startRevision) { // svn diff -r 4000:HEAD --summarize --xml List<String> changedFiles = new ArrayList<>(); List<String> deletedFiles = new ArrayList<>(); ...
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code private String runCommand(String directory, String... command) throws IOException { ProcessBuilder processBuilder = new ProcessBuilder(command); processBuilder.directory(new File(directory)); Process process = processBuilder.start(); In...
#fixed code private String runCommand(String directory, String... command) throws IOException { ProcessBuilder processBuilder = new ProcessBuilder(command); processBuilder.directory(new File(directory)); Process process = processBuilder.start(); InputStr...
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public void getGitChangeSets() throws IOException, GitAPIException { Repository localRepository = new FileRepository(new File("./repo/.timelord/test/.git")); Git git = new Git(localRepository); Iterable<RevCommit> logs = git.log().call(); ...
#fixed code public void getGitChangeSets() throws IOException, GitAPIException { Repository localRepository = new FileRepository(new File("./repo/server/.git")); Git git = new Git(localRepository); Iterable<RevCommit> logs = git.log().call(); List<String...
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Override public void reindexByRepo(RepoResult repo) { // Stop adding to job processing queue this.repoAdderPause = true; this.repoJobExit = true; // Clear job processing queue queue // CLear index queue this.codeIndex...
#fixed code @Override public void reindexByRepo(RepoResult repo) { // Stop adding to job processing queue //this.repoAdderPause = true; //this.repoJobExit = true; // Clear job processing queue queue // CLear index queue //this.codeIndex...
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public SourceCodeDTO saveCode(CodeIndexDocument codeIndexDocument) { Optional<SourceCodeDTO> existing = this.getByCodeIndexDocument(codeIndexDocument); Connection conn = null; PreparedStatement stmt = null; try { conn = thi...
#fixed code public SourceCodeDTO saveCode(CodeIndexDocument codeIndexDocument) { Optional<SourceCodeDTO> existing = this.getByCodeIndexDocument(codeIndexDocument); ConnStmtRs connStmtRs = new ConnStmtRs(); try { connStmtRs.conn = this.dbConfig.getConn...
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Override public Home createHome(BridgeSettingsDescriptor bridgeSettings) { lifxMap = null; aGsonHandler = null; validLifx = bridgeSettings.isValidLifx(); log.info("LifxDevice Home created." + (validLifx ? "" : " No LifxDevices configured.")); if(validLifx) { ...
#fixed code @Override public Home createHome(BridgeSettingsDescriptor bridgeSettings) { lifxMap = null; aGsonHandler = null; validLifx = bridgeSettings.isValidLifx(); log.info("LifxDevice Home created." + (validLifx ? "" : " No LifxDevices configured.")); if(validLifx) { tr...
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code private void configWriter(String content, Path filePath) { if(Files.exists(filePath) && !Files.isWritable(filePath)){ log.error("Error file is not writable: " + filePath); return; } if(Files.notExists(filePath.getParent())) { try { Files.createDirecto...
#fixed code private void configWriter(String content, Path filePath) { if(Files.exists(filePath) && !Files.isWritable(filePath)){ log.error("Error file is not writable: " + filePath); return; } if(Files.notExists(filePath.getParent())) { try { Files.createDirectories(f...
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code private void denormalizeSdata(Sdata theSdata) { Map<String,Room> roomMap = new HashMap<String,Room>(); for (Room i : theSdata.getRooms()) roomMap.put(i.getId(),i); Map<String,Categorie> categoryMap = new HashMap<String,Categorie>(); for (Categorie i : theSdata.getC...
#fixed code private void denormalizeSdata(Sdata theSdata) { Map<String,Room> roomMap = new HashMap<String,Room>(); for (Room i : theSdata.getRooms()) roomMap.put(i.getId(),i); Map<String,Categorie> categoryMap = new HashMap<String,Categorie>(); for (Categorie i : theSdata.getCategor...
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Override public String deviceHandler(CallItem anItem, MultiCommandUtil aMultiUtil, String lightId, int intensity, Integer targetBri,Integer targetBriInc, DeviceDescriptor device, String body) { log.debug("executing HUE api request to TCP: " + anItem.getItem().getAsS...
#fixed code @Override public String deviceHandler(CallItem anItem, MultiCommandUtil aMultiUtil, String lightId, int intensity, Integer targetBri,Integer targetBriInc, DeviceDescriptor device, String body) { Socket dataSendSocket = null; log.debug("executing HUE api request to TCP: "...
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Override public Home createHome(BridgeSettings bridgeSettings) { fhemMap = null; validFhem = bridgeSettings.getBridgeSettingsDescriptor().isValidOpenhab(); log.info("FHEM Home created." + (validFhem ? "" : " No FHEMs configured.")); if(validFhem) { fhemMap = n...
#fixed code @Override public Home createHome(BridgeSettings bridgeSettings) { fhemMap = null; validFhem = bridgeSettings.getBridgeSettingsDescriptor().isValidFhem(); log.info("FHEM Home created." + (validFhem ? "" : " No FHEMs configured.")); if(validFhem) { fhemMap = new HashMa...
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public HueError[] validateWhitelistUser(String aUser, String userDescription, boolean strict) { String validUser = null; boolean found = false; if (aUser != null && !aUser.equalsIgnoreCase("undefined") && !aUser.equalsIgnoreCase("null") && !aUser.equalsIgnoreCase...
#fixed code public HueError[] validateWhitelistUser(String aUser, String userDescription, boolean strict) { String validUser = null; boolean found = false; if (aUser != null && !aUser.equalsIgnoreCase("undefined") && !aUser.equalsIgnoreCase("null") && !aUser.equalsIgnoreCase("")) ...
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Override public String deviceHandler(CallItem anItem, MultiCommandUtil aMultiUtil, String lightId, int intensity, Integer targetBri, Integer targetBriInc, ColorData colorData, DeviceDescriptor device, String body) { log.debug("Exec Request called with url: " + anItem....
#fixed code @Override public String deviceHandler(CallItem anItem, MultiCommandUtil aMultiUtil, String lightId, int intensity, Integer targetBri, Integer targetBriInc, ColorData colorData, DeviceDescriptor device, String body) { log.debug("Exec Request called with url: " + anItem.getIte...
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Override public String deviceHandler(CallItem anItem, MultiCommandUtil aMultiUtil, String lightId, int itensity, Integer targetBri, Integer targetBriInc, DeviceDescriptor device, String body) { log.debug("Exec Request called with url: " + anItem.getItem().getAsString(...
#fixed code @Override public String deviceHandler(CallItem anItem, MultiCommandUtil aMultiUtil, String lightId, int itensity, Integer targetBri, Integer targetBriInc, DeviceDescriptor device, String body) { log.debug("Exec Request called with url: " + anItem.getItem().getAsString() + " ...
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public static void main(String[] args) { Logger log = LoggerFactory.getLogger(HABridge.class); DeviceResource theResources; HomeManager homeManager; HueMulator theHueMulator; UDPDatagramSender udpSender; UpnpSettingsResour...
#fixed code public static void main(String[] args) { Logger log = LoggerFactory.getLogger(HABridge.class); DeviceResource theResources; HomeManager homeManager; HueMulator theHueMulator; UDPDatagramSender udpSender; UpnpSettingsResource the...
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code private void denormalizeSdata(Sdata theSdata) { Map<String,Room> roomMap = new HashMap<String,Room>(); for (Room i : theSdata.getRooms()) roomMap.put(i.getId(),i); Map<String,Categorie> categoryMap = new HashMap<String,Categorie>(); for (Categorie i : theSdata.getC...
#fixed code private void denormalizeSdata(Sdata theSdata) { Map<String,Room> roomMap = new HashMap<String,Room>(); for (Room i : theSdata.getRooms()) roomMap.put(i.getId(),i); Map<String,Categorie> categoryMap = new HashMap<String,Categorie>(); for (Categorie i : theSdata.getCategor...
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public void saveResource(String resourcePath, boolean replace) { if (resourcePath == null || resourcePath.equals("")) { throw new IllegalArgumentException("ResourcePath cannot be null or empty"); } resourcePath = resourcePath.replace...
#fixed code public void saveResource(String resourcePath, boolean replace) { if (resourcePath == null || resourcePath.equals("")) { throw new IllegalArgumentException("ResourcePath cannot be null or empty"); } resourcePath = resourcePath.replace('\\',...
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public void load(File file) throws FileNotFoundException, IOException, InvalidConfigurationException { Validate.notNull(file, "File cannot be null"); load(new FileInputStream(file)); } #location 4 ...
#fixed code public void load(File file) throws FileNotFoundException, IOException, InvalidConfigurationException { Validate.notNull(file, "File cannot be null"); final FileInputStream stream = new FileInputStream(file); load(new InputStreamReader(stream, UTF8_OV...
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public Plugin loadPlugin(File file) throws InvalidPluginException, InvalidDescriptionException, UnknownDependencyException { JavaPlugin result = null; PluginDescriptionFile description = null; if (!file.exists()) { throw new InvalidP...
#fixed code public Plugin loadPlugin(File file) throws InvalidPluginException, InvalidDescriptionException, UnknownDependencyException { return loadPlugin(file, false); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Override public boolean execute(CommandSender sender, String currentAlias, String[] args) { if (!testPermission(sender)) return true; if (args.length < 1 || args.length > 4) { sender.sendMessage(ChatColor.RED + "Usage: " + usageMessage);...
#fixed code @Override public boolean execute(CommandSender sender, String currentAlias, String[] args) { if (!testPermission(sender)) return true; if (args.length < 1 || args.length > 4) { sender.sendMessage(ChatColor.RED + "Usage: " + usageMessage); ...
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public void recalculatePermissions() { dirtyPermissions = true; } #location 2 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code public void recalculatePermissions() { clearPermissions(); Set<Permission> defaults = Bukkit.getServer().getPluginManager().getDefaultPermissions(isOp()); Bukkit.getServer().getPluginManager().subscribeToDefaultPerms(isOp(), parent); for (Perm...
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public List<byte[]> getLoadBlocks(boolean includeDebug, boolean separateComponents, int blockSize) { List<byte[]> blocks = null; if (!separateComponents) { ByteArrayOutputStream bo = new ByteArrayOutputStream(); try {...
#fixed code public List<byte[]> getLoadBlocks(boolean includeDebug, boolean separateComponents, int blockSize) { List<byte[]> blocks = null; if (!separateComponents) { ByteArrayOutputStream bo = new ByteArrayOutputStream(); try { ...
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void testConsumerNormalOps() throws InterruptedException, ExecutionException { // Tests create instance, read, and delete final List<ConsumerRecord> referenceRecords = Arrays.asList( new ConsumerRecord("k1".getBytes(), "v...
#fixed code @Test public void testConsumerNormalOps() throws InterruptedException, ExecutionException { // Tests create instance, read, and delete final List<ConsumerRecord> referenceRecords = Arrays.asList( new ConsumerRecord("k1".getBytes(), "v1".get...
Below is the vulnerable code, please generate the patch based on the following information.