output
stringlengths
79
30.1k
instruction
stringclasses
1 value
input
stringlengths
216
28.9k
#fixed code public Object execute(Object ctx, Map tokens, TemplateRegistry registry) { if (nodes == null) { return new String(expression); } else if (nodes.length == 2) { /** * This is an optimization for property expressions....
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public Object execute(Object ctx, Map tokens, TemplateRegistry registry) { if (nodes == null) { return new String(expression); } else if (nodes.length == 2) { /** * This is an optimization for property expres...
#fixed code protected ASTNode verify(ParserContext pCtx, ASTNode tk) { if (tk.isDiscard() || (tk.fields & (ASTNode.OPERATOR | ASTNode.LITERAL)) != 0) return tk; if (verifying) { if (tk.isAssignment()) { char[] assign = tk.getNameAsArray(); ...
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code protected ASTNode verify(ParserContext pCtx, ASTNode tk) { if (tk.isDiscard() || (tk.fields & (ASTNode.OPERATOR | ASTNode.LITERAL)) != 0) return tk; if (verifying) { if (tk.isAssignment()) { char[] assign = tk.getNameAsArray...
#fixed code public Object execute(Object ctx, Map tokens, TemplateRegistry registry) { synchronized (Runtime.getRuntime()) { if (nodes == null) { return new String(expression); } else if (nodes.length == 2) { /*...
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public Object execute(Object ctx, Map tokens, TemplateRegistry registry) { if (nodes == null) { return new String(expression); } else if (nodes.length == 2) { /** * This is an optimization for property express...
#fixed code protected ASTNode nextToken() { /** * If the cursor is at the end of the expression, we have nothing more to do: * return null. */ if (cursor >= length) { return null; } else if (!splitAccumulator.isEmpty(...
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code protected ASTNode nextToken() { /** * If the cursor is at the end of the expression, we have nothing more to do: * return null. */ if (cursor >= length) { return null; } else if (!splitAccumulator.is...
#fixed code private TypeUsage getTypeConcrete(Node node, boolean solveLambdas) { if (node == null) throw new IllegalArgumentException(); if (node instanceof NameExpr) { NameExpr nameExpr = (NameExpr) node; logger.finest("getType on name expr " + no...
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code private TypeUsage getTypeConcrete(Node node, boolean solveLambdas) { if (node == null) throw new IllegalArgumentException(); if (node instanceof NameExpr) { NameExpr nameExpr = (NameExpr) node; logger.finest("getType on name expr ...
#fixed code @Generated("com.github.javaparser.generator.core.visitor.HashCodeVisitorGenerator") public Integer visit(final ConstructorDeclaration n, final Void arg) { return (n.getBody().accept(this, arg)) * 31 + (n.getModifiers().hashCode()) * 31 + (n.getName().accept(this, ...
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Generated("com.github.javaparser.generator.core.visitor.HashCodeVisitorGenerator") public Integer visit(final ConstructorDeclaration n, final Void arg) { return (n.getBody().accept(this, arg)) * 31 + (n.getModifiers().hashCode()) * 31 + (n.getName().accept(...
#fixed code @Test void resolveFieldOfEnumAsInternalClassOfClassUnqualifiedSamePackage() throws IOException { File src = new File("src/test/resources/enumLiteralsInAnnotatedClass"); File aClass = new File(src.getPath() + File.separator + "foo" + File.separator + "bar" ...
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test void resolveFieldOfEnumAsInternalClassOfClassUnqualifiedSamePackage() throws IOException { File src = new File("src/test/resources/enumLiteralsInAnnotatedClass"); File aClass = new File(src.getPath() + File.separator + "foo" + File.separator + ...
#fixed code @Override public Type getType() { if (wrappedNode instanceof Parameter) { Parameter parameter = (Parameter) wrappedNode; if (getParentNode(wrappedNode) instanceof LambdaExpr) { int pos = getParamPos(parameter); ...
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Override public Type getType() { if (wrappedNode instanceof Parameter) { Parameter parameter = (Parameter) wrappedNode; if (wrappedNode.getParentNode() instanceof LambdaExpr) { int pos = getParamPos(parameter); ...
#fixed code @Override public List<ReferenceTypeUsage> getAllAncestors() { List<ReferenceTypeUsage> ancestors = new LinkedList<>(); if (getSuperClass(typeSolver) != null) { ReferenceTypeUsage superClass = getSuperClass(typeSolver); ancestors.add...
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Override public List<ReferenceTypeUsage> getAllAncestors() { List<ReferenceTypeUsage> ancestors = new LinkedList<>(); if (getSuperClass(typeSolver) != null) { ancestors.add(new ReferenceTypeUsage(getSuperClass(typeSolver), typeSolver)); ...
#fixed code public Optional<Value> solveSymbolAsValue(String name, Node node) { Context context = JavaParserFactory.getContext(node); return solveSymbolAsValue(name, context); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public Optional<Value> solveSymbolAsValue(String name, Node node) { return solveSymbolAsValue(name, JavaParserFactory.getContext(node)); } #location 2 #vulnerability type NULL_DEREFERENCE
#fixed code @Test void resolveFieldOfEnumAsInternalClassOfClassUnqualifiedSamePackage() throws IOException { File src = new File("src/test/resources/enumLiteralsInAnnotatedClass"); File aClass = new File(src.getPath() + File.separator + "foo" + File.separator + "bar" ...
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test void resolveFieldOfEnumAsInternalClassOfClassUnqualifiedSamePackage() throws IOException { File src = new File("src/test/resources/enumLiteralsInAnnotatedClass"); File aClass = new File(src.getPath() + File.separator + "foo" + File.separator + ...
#fixed code @Generated("com.github.javaparser.generator.core.visitor.NoCommentHashCodeVisitorGenerator") public Integer visit(final ConstructorDeclaration n, final Void arg) { return (n.getBody().accept(this, arg)) * 31 + (n.getModifiers().hashCode()) * 31 + (n.getName().acce...
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Generated("com.github.javaparser.generator.core.visitor.NoCommentHashCodeVisitorGenerator") public Integer visit(final ConstructorDeclaration n, final Void arg) { return (n.getBody().accept(this, arg)) * 31 + (n.getModifiers().hashCode()) * 31 + (n.getName(...
#fixed code @Test void resolveFieldOfEnumAsInternalClassOfClassQualifiedSamePackage() throws IOException { File src = new File("src/test/resources/enumLiteralsInAnnotatedClass"); File aClass = new File(src.getPath() + File.separator + "foo" + File.separator + "bar" ...
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test void resolveFieldOfEnumAsInternalClassOfClassQualifiedSamePackage() throws IOException { File src = new File("src/test/resources/enumLiteralsInAnnotatedClass"); File aClass = new File(src.getPath() + File.separator + "foo" + File.separator + "b...
#fixed code @Test public void shouldReturnThePrimaryKeysAtTheEndWhenMultipleFieldsFormThePrimaryKey() { Schema schema = SchemaBuilder.struct().name("com.example.Person") .field("firstName", Schema.STRING_SCHEMA) .field("lastName", Schema.STRING_SCHEMA) ...
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void shouldReturnThePrimaryKeysAtTheEndWhenMultipleFieldsFormThePrimaryKey() { Schema schema = SchemaBuilder.struct().name("com.example.Person") .field("firstName", Schema.STRING_SCHEMA) .field("lastName", Schema.STRING_SCHEMA) ...
#fixed code @Test public void handleAllFieldsMappingSettingAndTheMappingsProvided() { List<DbTableColumn> columns = Lists.newArrayList( new DbTableColumn("col1", true, false, 1), new DbTableColumn("col2", false, false, 1), new DbTableColumn("col3", false, fals...
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void handleAllFieldsMappingSettingAndTheMappingsProvided() { List<DbTableColumn> columns = Lists.newArrayList( new DbTableColumn("col1", true, false, 1), new DbTableColumn("col2", false, false, 1), new DbTableColumn("col3", false...
#fixed code public void connect() throws IOException { if (!connectLock.tryLock()) { throw new IllegalStateException("BinaryLogClient is already connected"); } boolean notifyWhenDisconnected = false; try { try { chan...
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public void connect() throws IOException { if (connected) { throw new IllegalStateException("BinaryLogClient is already connected"); } GreetingPacket greetingPacket; try { try { Socket socket = sock...
#fixed code @Test public void testChecksumNONE() throws Exception { EventDeserializer eventDeserializer = new EventDeserializer(); BinaryLogFileReader reader = new BinaryLogFileReader( new FileInputStream("src/test/resources/mysql-bin.checksum-none"), ...
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void testChecksumNONE() throws Exception { EventDeserializer eventDeserializer = new EventDeserializer(); BinaryLogFileReader reader = new BinaryLogFileReader(new GZIPInputStream( new FileInputStream("src/test/resources/m...
#fixed code private List<WordFrequency> loadFrequencies(final String input) { try { final FrequencyAnalyzer frequencyAnalyzer = new FrequencyAnalyzer(); frequencyAnalyzer.setWordFrequenciesToReturn(cliParameters.getWordCount()); frequencyAnalyz...
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code private List<WordFrequency> loadFrequencies(final String input) { try { final FrequencyAnalyzer frequencyAnalyzer = new FrequencyAnalyzer(); frequencyAnalyzer.setWordFrequenciesToReturn(cliParameters.getWordCount()); frequency...
#fixed code @Test public void testSyncHandleSuccessfulResponse() throws Exception { RpcFuture<String> rpcFuture = new RpcFuture<String>(timeout, methodInfo, null, channelInfo, rpcClient); RpcResponse response = new RpcResponse(); response.setResult("hello worl...
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void testSyncHandleSuccessfulResponse() throws Exception { RpcFuture rpcFuture = new RpcFuture<String>(timeout, methodInfo, null, channelInfo, rpcClient); RpcResponse response = new RpcResponse(); response.setResult("hello world"...
#fixed code private void generateBuildConfig() throws MojoExecutionException { getLog().debug( "Generating BuildConfig file" ); // Create the BuildConfig for our package. String packageName = extractPackageNameFromAndroidManifest( androidManifestFile ); ...
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code private void generateBuildConfig() throws MojoExecutionException { getLog().debug( "Generating BuildConfig file" ); // Create the BuildConfig for our package. String packageName = extractPackageNameFromAndroidManifest( androidManifestFile );...
#fixed code public MakefileHolder createMakefileFromArtifacts( File outputDir, Set<Artifact> artifacts, String ndkArchitecture, boolean useHeaderArchives ) ...
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public MakefileHolder createMakefileFromArtifacts( File outputDir, Set<Artifact> artifacts, String ndkArchitecture, boolean useHeaderArchives ) ...
#fixed code @Test public void describeAsAdditionalInfo_notEmpty() { Correspondence.ExceptionStore exceptions = Correspondence.ExceptionStore.forIterable(); addCompareException(exceptions); assertExpectedFacts( exceptions.describeAsAdditionalInfo(), "additional...
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void describeAsAdditionalInfo_notEmpty() { Correspondence.ExceptionStore exceptions = Correspondence.ExceptionStore.forIterable(); addCompareException(exceptions); assertExpectedFacts( exceptions.describeAsAdditionalInfo().asIterable(), ...
#fixed code public String getConceptNetUrl() { String urlFromConfigOrDefault = (String)getConfiguration().getSettingValueFor(CONFIG_KEY_URL); return urlFromConfigOrDefault == null ? DEFAULT_CONCEPTNET_URL : urlFromConfigOrDefault; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public String getConceptNetUrl() { String urlFromConfigOrDefault = getConfiguration().getSettingValueFor(CONFIG_KEY_URL).toString(); return urlFromConfigOrDefault == null ? DEFAULT_CONCEPTNET_URL : urlFromConfigOrDefault;...
#fixed code public static List<Class<?>> getClasses(final String packageName) { List<Class<?>> classes = new LinkedList<Class<?>>(); List<File> paths = getPackageDirectories(packageName); for (File path : paths) { for (File entry : path.listFiles()) ...
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public static List<Class<?>> getClasses(final String packageName) { List<Class<?>> classes = new LinkedList<Class<?>>(); File directory = getPackageAsDirectory(packageName); for (File entry : directory.listFiles()) { if (isClass(ent...
#fixed code public Run getPreviousFinishedBuildOfSameBranch(BuildListener listener) { return SetupConfig.get().getDynamicBuildRepository() .getPreviousFinishedBuildOfSameBranch(this, getCurrentBranch().toString()); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public Run getPreviousFinishedBuildOfSameBranch(BuildListener listener) { return new DynamicBuildRepository().getPreviousFinishedBuildOfSameBranch(this, getCurrentBranch().toString()); } #location 2 #...
#fixed code public Future<byte[]> get(String uri, Callback<byte[]> callback) { return request("GET", uri, null, null, null, null, null, callback); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public Future<byte[]> get(String uri, Callback<byte[]> callback) { HttpGet req = new HttpGet(uri); Log.debug("Starting HTTP GET request", "request", req.getRequestLine()); return execute(client, req, callback); } #location 6 ...
#fixed code @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; ScanParams that = (ScanParams) o; if (!Arrays.equals(packages, that.packages)) return false; if (matching != null ? !matching.equals(th...
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; ScanParams that = (ScanParams) o; if (!Arrays.equals(packages, that.packages)) return false; if (matching != null ? !matching.equ...
#fixed code public static void setRootPath(String rootPath) { Log.info("Setting 'root' application path", "path", rootPath); Conf.rootPath = cleanPath(rootPath); setStaticPath(Conf.rootPath + "/static"); setDynamicPath(Conf.rootPath + "/dynamic"); setConfigPath(Conf.rootPath); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public static void setRootPath(String rootPath) { Log.info("Setting 'root' application path", "path", rootPath); Conf.rootPath = cleanPath(rootPath); setStaticPath(Conf.rootPath + "/static"); setDynamicPath(Conf.rootPath + "/dynamic"); setConfigPath(Conf.rootPath...
#fixed code public static void main(String[] args) { final HttpParser parser = new HttpParser(); final Buf[] reqs = {r(REQ1), r(REQ2), r(REQ3), r(REQ4)}; final RapidoidHelper helper = new RapidoidHelper(null); for (int i = 0; i < 100; i++) { Msc.benchmark("parse", 3000000, new ...
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public static void main(String[] args) { final HttpParser parser = new HttpParser(); final Buf[] reqs = {r(REQ1), r(REQ2), r(REQ3), r(REQ4)}; final RapidoidHelper helper = new RapidoidHelper(null); BufRange[] ranges = helper.ranges1.ranges; final BufRanges head...
#fixed code public void initDbConnectServer() throws Exception{ dbRpcConnnectManngeer.initManager(); dbRpcConnnectManngeer.initServers(rpcConfig.getSdDbServers()); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public void initDbConnectServer() throws Exception{ dbRpcConnnectManngeer.initManager(); dbRpcConnnectManngeer.initServers(sdDbServers); } #location 2 #vulnerability type THREAD_SAFETY_VIOLATI...
#fixed code public void loadPackage(String namespace, String ext) throws Exception { if(fileNames == null){ fileNames = messageScanner.scannerPackage(namespace, ext); } // 加载class,获取协议命令 DefaultClassLoader defaultClassLoader = Local...
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public void loadPackage(String namespace, String ext) throws Exception { if(fileNames == null){ fileNames = messageScanner.scannerPackage(namespace, ext); } // 加载class,获取协议命令 DefaultClassLoader defaultClassLoader =...
#fixed code public void execute() { if (help) { command.usage("init"); } else { try { WalkModFacade facade = new WalkModFacade(OptionsBuilder.options()); Configuration cfg = facade.getConfiguration(); Collection<PluginConfig> installedPlugins = null; if(cfg !=...
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public void execute() { if (help) { command.usage("init"); } else { try { WalkModFacade facade = new WalkModFacade(OptionsBuilder.options()); Configuration cfg = facade.getConfiguration(); Collection<PluginConfig> installedPlugins = cfg.getPlugins(); ...
#fixed code private void setTotalAndPreUsed(GCEvent event, StartElement startEl) { long total = NumberParser.parseLong(getAttributeValue(startEl, "total")); event.setTotal(toKiloBytes(total)); event.setPreUsed(toKiloBytes(total - NumberParser.parseLong(getAttribut...
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code private void setTotalAndPreUsed(GCEvent event, StartElement startEl) { long total = NumberParser.parseInt(getAttributeValue(startEl, "total")); event.setTotal(toKiloBytes(total)); event.setPreUsed(toKiloBytes(total - NumberParser.parseInt(getAttr...
#fixed code private void setPostUsed(GCEvent event, StartElement startEl) { long total = NumberParser.parseLong(getAttributeValue(startEl, "total")); event.setPostUsed(toKiloBytes(total - NumberParser.parseLong(getAttributeValue(startEl, "free")))); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code private void setPostUsed(GCEvent event, StartElement startEl) { long total = NumberParser.parseInt(getAttributeValue(startEl, "total")); event.setPostUsed(toKiloBytes(total - NumberParser.parseInt(getAttributeValue(startEl, "free")))); } ...
#fixed code @Override public void run() { // First, analyze the torrent's local data. try { this.torrent.init(); } catch (ClosedByInterruptException cbie) { logger.warn("Client was interrupted during initialization. " + "Aborting right away."); this.setState(ClientState...
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Override public void run() { // First, analyze the torrent's local data. try { this.torrent.init(); } catch (ClosedByInterruptException cbie) { logger.warn("Client was interrupted during initialization. " + "Aborting right away."); this.setState(Clien...
#fixed code @Override public void announce(AnnounceRequestMessage.RequestEvent event, boolean inhibitEvents) throws AnnounceException { logger.info("Announcing{} to tracker with {}U/{}D/{}L bytes...", new Object[] { this.formatAnnounceEvent(event), this.torrent.getUploaded()...
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Override public void announce(AnnounceRequestMessage.RequestEvent event, boolean inhibitEvents) throws AnnounceException { logger.info("Announcing{} to tracker with {}U/{}D/{}L bytes...", new Object[] { this.formatAnnounceEvent(event), this.torrent.getUplo...
#fixed code public boolean connect(SharingPeer peer) { Socket socket = new Socket(); InetSocketAddress address = new InetSocketAddress(peer.getIp(), peer.getPort()); logger.info("Connecting to {}...", peer); try { socket.connect(address, 3*1000); } catch (IOException ioe) ...
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public boolean connect(SharingPeer peer) { Socket socket = new Socket(); InetSocketAddress address = new InetSocketAddress(peer.getIp(), peer.getPort()); logger.info("Connecting to " + peer + "..."); try { socket.connect(address, 3*1000); } catch (IOExcep...
#fixed code @Override public synchronized void handleMessage(PeerMessage msg) { // logger.trace("Received msg {} from {}", msg.getType(), this); switch (msg.getType()) { case KEEP_ALIVE: // Nothing to do, we're keeping the connection open anyways. break; ...
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Override public synchronized void handleMessage(PeerMessage msg) { // logger.trace("Received msg {} from {}", msg.getType(), this); switch (msg.getType()) { case KEEP_ALIVE: // Nothing to do, we're keeping the connection open anyways. break...
#fixed code public BitSet getCompletedPieces() { if (!this.isInitialized()) { throw new IllegalStateException("Torrent not yet initialized!"); } synchronized (this.completedPieces) { return (BitSet)this.completedPieces.clone(); } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public BitSet getCompletedPieces() { synchronized (this.completedPieces) { return (BitSet)this.completedPieces.clone(); } } #location 2 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code private void validatePieceAsync(final SharedTorrent torrent, final Piece piece, String torrentHash, SharingPeer peer) { try { synchronized (piece) { if (piece.isValid()) return; piece.validate(torrent, piece); if (piece.isValid()) { ...
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code private void validatePieceAsync(final SharedTorrent torrent, final Piece piece, String torrentHash, SharingPeer peer) { try { synchronized (piece) { if (piece.isValid()) return; piece.validate(torrent, piece); if (piece.isValid()) { ...
#fixed code @Test public void canAcceptAndReadData() throws IOException, InterruptedException { final AtomicInteger acceptCount = new AtomicInteger(); final AtomicInteger readCount = new AtomicInteger(); final AtomicInteger connectCount = new AtomicInteger(); final Atomic...
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void canAcceptAndReadData() throws IOException, InterruptedException { final AtomicInteger acceptCount = new AtomicInteger(); final AtomicInteger readCount = new AtomicInteger(); final AtomicInteger connectCount = new AtomicInteger(); final ...
#fixed code public BitSet getAvailablePieces() { if (!this.isInitialized()) { throw new IllegalStateException("Torrent not yet initialized!"); } BitSet availablePieces = new BitSet(this.pieces.length); synchronized (this.pieces) { for (Piece piece : this.pieces) { if (pi...
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public BitSet getAvailablePieces() { BitSet availablePieces = new BitSet(this.pieces.length); synchronized (this.pieces) { for (Piece piece : this.pieces) { if (piece.available()) { availablePieces.set(piece.getIndex()); } } } return availableP...
#fixed code public void download_multiple_files() throws IOException, NoSuchAlgorithmException, InterruptedException, URISyntaxException { int numFiles = 50; this.tracker.setAcceptForeignTorrents(true); final File srcDir = tempFiles.createTempDir(); final File downloadDir ...
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public void download_multiple_files() throws IOException, NoSuchAlgorithmException, InterruptedException, URISyntaxException { int numFiles = 50; this.tracker.setAcceptForeignTorrents(true); final File srcDir = tempFiles.createTempDir(); final File downlo...
#fixed code public void downloadUninterruptibly(final String dotTorrentPath, final String downloadDirPath, final long idleTimeoutSec, final int minSeedersCount, ...
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public void downloadUninterruptibly(final String dotTorrentPath, final String downloadDirPath, final long idleTimeoutSec, final int minSeedersCount, ...
#fixed code public void send(PeerMessage message) throws IllegalStateException { logger.trace("Sending msg {} to {}", message.getType(), this); if (this.isConnected()) { ByteBuffer data = message.getData(); data.rewind(); connectionManager.offerWrite(new WriteTask...
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public void send(PeerMessage message) throws IllegalStateException { logger.trace("Sending msg {} to {}", message.getType(), this); if (this.isConnected()) { ByteBuffer data = message.getData(); data.rewind(); boolean writeTaskAdded = connectionM...
#fixed code public T blpopObject(int timeout, String key, Class clazz) { this.setSchema(clazz); Jedis jedis = null; try { jedis = jedisPool.getResource(); List<byte[]> bytes = jedis.blpop(timeout, key.getBytes()); if (bytes == n...
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public T blpopObject(int timeout, String key, Class clazz) { this.setSchema(clazz); Jedis jedis = null; try { List<byte[]> bytes = jedis.blpop(timeout, key.getBytes()); if (bytes == null || bytes.size() == 0) { ...
#fixed code @Test public void testCustomUserAgent() throws JSONException, UnirestException { HttpResponse<JsonNode> response = Unirest.get(MockServer.GETJSON) .header("user-agent", "hello-world") .asJson(); RequestCapture json = parse(response); ...
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void testCustomUserAgent() throws JSONException, UnirestException { HttpResponse<JsonNode> response = Unirest.get("http://httpbin.org/get?name=mark").header("user-agent", "hello-world").asJson(); assertEquals("hello-world", response.getBody().getObject()....
#fixed code @Test public void testDelete() throws JSONException, UnirestException { HttpResponse<JsonNode> response = Unirest.delete(MockServer.DELETE).asJson(); assertEquals(200, response.getStatus()); response = Unirest.delete(MockServer.DELETE) .field("name", "mark") .fie...
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void testDelete() throws JSONException, UnirestException { HttpResponse<JsonNode> response = Unirest.delete("http://httpbin.org/delete").asJson(); assertEquals(200, response.getStatus()); response = Unirest.delete("http://httpbin.org/delete").field("na...
#fixed code @Test public void testPostBinaryUTF8() throws URISyntaxException { HttpResponse<JsonNode> response = Unirest.post(MockServer.POST) .header("Accept", ContentType.MULTIPART_FORM_DATA.getMimeType()) .field("param3", "こんにちは") .field("file", new File(getClass().getReso...
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void testPostBinaryUTF8() throws URISyntaxException { HttpResponse<JsonNode> response = Unirest.post("http://httpbin.org/post").field("param3", "こんにちは").field("file", new File(getClass().getResource("/test").toURI())).asJson(); assertEquals("This is a te...
#fixed code @Test public void testMultipartInputStreamContentType() throws JSONException, InterruptedException, ExecutionException, URISyntaxException, UnirestException, FileNotFoundException { FileInputStream stream = new FileInputStream(new File(getClass().getResource("/image.jpg").toU...
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void testMultipartInputStreamContentType() throws JSONException, InterruptedException, ExecutionException, URISyntaxException, UnirestException, FileNotFoundException { HttpResponse<JsonNode> jsonResponse = Unirest.post("http://httpbin.org/post").field("nam...
#fixed code public boolean isStarted() { try { lock.lock(); return client.getState() == CuratorFrameworkState.STARTED; } finally { lock.unlock(); } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public boolean isStarted() { return client.getState() == CuratorFrameworkState.STARTED; } #location 2 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code @Test public void testReplication1() throws Exception { final int RUNS = 100; final String sourceBasePath = getVanillaTestPath("-source"); final String sinkBasePath = getVanillaTestPath("-sink"); final ChronicleSource source = new Chronic...
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void testReplication1() throws IOException { final int RUNS = 100; final String sourceBasePath = getVanillaTestPath("-source"); final String sinkBasePath = getVanillaTestPath("-sink"); final ChronicleSource source = new ...
#fixed code @Test public void testPricePublishing2() throws IOException, InterruptedException { final String basePathSource = getIndexedTestPath("-source"); final String basePathSink = getIndexedTestPath("-sink"); final Chronicle source = ChronicleQueueBuilde...
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void testPricePublishing2() throws IOException, InterruptedException { final String basePathSource = getIndexedTestPath("-source"); final String basePathSink = getIndexedTestPath("-sink"); final Chronicle source = new ChronicleS...
#fixed code @NotNull private WireStore acquireStore(final long cycle, final long epoch) { @NotNull final RollCycle rollCycle = builder.rollCycle(); @NotNull final String cycleFormat = this.dateCache.formatFor(cycle); @NotNull final File cycleFile = new File(th...
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @NotNull private WireStore acquireStore(final long cycle, final long epoch) { @NotNull final RollCycle rollCycle = builder.rollCycle(); @NotNull final String cycleFormat = this.dateCache.formatFor(cycle); @NotNull final File cycleFile = new F...
#fixed code @Test public void testPersistedLocalIndexedSink_001() throws Exception { final int port = BASE_PORT + 201; final String basePath = getIndexedTestPath(); final Chronicle chronicle = ChronicleQueueBuilder.indexed(basePath).build(); final Ch...
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void testPersistedLocalIndexedSink_001() throws Exception { final int port = BASE_PORT + 201; final String basePath = getIndexedTestPath(); final Chronicle chronicle = ChronicleQueueBuilder.indexed(basePath).build(); fin...
#fixed code @Test public void testPricePublishing3() throws IOException, InterruptedException { final String basePathSource = getIndexedTestPath("-source"); final String basePathSink = getIndexedTestPath("-sink"); final Chronicle source = ChronicleQueueBuilde...
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void testPricePublishing3() throws IOException, InterruptedException { final String basePathSource = getIndexedTestPath("-source"); final String basePathSink = getIndexedTestPath("-sink"); final Chronicle source = new ChronicleS...
#fixed code @Override public Raft.AppendEntriesResponse appendEntries(Raft.AppendEntriesRequest request) { raftNode.getLock().lock(); Raft.AppendEntriesResponse.Builder responseBuilder = Raft.AppendEntriesResponse.newBuilder(); responseBuilder.setTerm(raftNode...
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Override public Raft.AppendEntriesResponse appendEntries(Raft.AppendEntriesRequest request) { Raft.AppendEntriesResponse.Builder responseBuilder = Raft.AppendEntriesResponse.newBuilder(); responseBuilder.setTerm(raftNode.getCurrentTerm()); r...
#fixed code protected boolean isInstallingExtensionNeeded(Set<BindingEnum> bindingTypes) { final JsonObject hostJson = readHostJson(); final JsonObject extensionBundle = hostJson == null ? null : hostJson.getAsJsonObject(EXTENSION_BUNDLE); if (extensionBundle != n...
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code protected boolean isInstallingExtensionNeeded(Set<BindingEnum> bindingTypes) { final JsonObject hostJson = readHostJson(); final JsonObject extensionBundle = hostJson.getAsJsonObject(EXTENSION_BUNDLE); if (extensionBundle != null && extensionBund...
#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 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 prepareIoc() { if (ctx.getIoc() == null) { ctx.setIoc(new NutIoc(ctx.getComboIocLoader())); } // 把核心对象放进ioc容器 if (!ctx.ioc.has("appContext")){ Ioc2 ioc2 = (Ioc2)ctx.getIoc(); ioc2.getIocContext()....
Below is the vulnerable code, please generate the patch based on the following information.
#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 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 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 _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 _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 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 shutdown() { log.info("ok, shutting down ..."); synchronized (lock) { lock.notify(); } } #location 2 #vulnerability type THREAD_SAFETY_VIOLATION
#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 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 @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 @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 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 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 @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 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 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 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 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 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 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 public void testIsBinaryWhiteListedExtension() { SearchcodeLib sl = new SearchcodeLib(); ArrayList<String> codeLines = new ArrayList<>(); codeLines.add("你你你你你你你你你你你你你你你你你你你你你你你你你你你"); FileClassifier fileClassifier = new FileClassifier();...
#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 @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 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 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 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 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 @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 @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 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 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 public byte[] getPDF() throws IOException, InterruptedException { Runtime runtime = Runtime.getRuntime(); Process process = runtime.exec(getCommandAsArray()); StreamEater outputStreamEater = new StreamEater(process.getInputStream()); outputStr...
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public byte[] getPDF() throws IOException, InterruptedException { Runtime runtime = Runtime.getRuntime(); Process process = runtime.exec(getCommandAsArray()); for (Page page : pages) { if (page.getType().equals(PageType.htmlAsString)...
#fixed code @SuppressWarnings("unchecked") @Test // Add the MetadataLinkListener to the listener chain. The output will render an href to view the metadata // for the album object. public void testMetadataHref() { String prefixUrl = "/metadata/"; String f...
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @SuppressWarnings("unchecked") @Test // Add the MetadataLinkListener to the listener chain. The output will render an href to view the metadata // for the album object. public void testMetadataHref() { String prefixUrl = "/metadata/"; St...
#fixed code @Override public JimfsFileSystem newFileSystem(URI uri, Map<String, ?> env) throws IOException { checkArgument(uri.getScheme().equalsIgnoreCase(SCHEME), "uri (%s) scheme must be '%s'", uri, SCHEME); checkArgument(env.get(CONFIG_KEY) instanceof JimfsConfigurati...
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Override public JimfsFileSystem newFileSystem(URI uri, Map<String, ?> env) { checkArgument(uri.getScheme().equalsIgnoreCase(SCHEME), "uri (%s) scheme must be '%s'", uri, SCHEME); checkArgument(env.get(CONFIG_KEY) instanceof JimfsConfiguration, "...
#fixed code public void init() throws DBException { if ( (getProperties().getProperty("debug")!=null) && (getProperties().getProperty("debug").compareTo("true")==0) ) { _debug=true; } if (getProperties().containsKey("client...
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public void init() throws DBException { if ( (getProperties().getProperty("debug")!=null) && (getProperties().getProperty("debug").compareTo("true")==0) ) { _debug=true; } if (getProperties().containsKey("...
#fixed code @Override public int scan(String table, String startkey, int recordcount, Set<String> fields, Vector<HashMap<String, ByteIterator>> result) { MongoCursor<Document> cursor = null; try { MongoCollection<Document> collection = database...
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Override public int scan(String table, String startkey, int recordcount, Set<String> fields, Vector<HashMap<String, ByteIterator>> result) { MongoCursor<Document> cursor = null; try { MongoCollection<Document> collection = da...
#fixed code @Override public boolean doTransaction(DB db, Object threadstate) { String operation = operationchooser.nextString(); if (operation == null) { return false; } switch (operation) { case "UPDATE": doTransactionUpdate(db); break; case "...
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Override public boolean doTransaction(DB db, Object threadstate) { switch (operationchooser.nextString()) { case "UPDATE": doTransactionUpdate(db); break; case "INSERT": doTransactionInsert(db); break; case "DELETE": doTran...
#fixed code @Override public Status delete(String table, String key) { if (debug) { System.out.println("Doing delete for key: " + key); } setTable(table); final MutateRowRequest.Builder rowMutation = MutateRowRequest.newBuilder() .setRowKey(ByteStr...
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Override public Status delete(String table, String key) { if (debug) { System.out.println("Doing delete for key: " + key); } setTable(table); final MutateRowRequest.Builder rowMutation = MutateRowRequest.newBuilder() .setRowKey(B...
#fixed code @Override public int insert(String table, String key, HashMap<String, ByteIterator> values) { try { MongoCollection<Document> collection = database .getCollection(table); Document toInsert = new Document("_id...
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Override public int insert(String table, String key, HashMap<String, ByteIterator> values) { try { MongoCollection<Document> collection = database .getCollection(table); Document toInsert = new Documen...
#fixed code public void getHTable(String table) throws IOException { final TableName tName = TableName.valueOf(table); this.currentTable = connection.getTable(tName); if (clientSideBuffering) { final BufferedMutatorParams p = new BufferedMutatorParams(tName); p.writ...
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public void getHTable(String table) throws IOException { final TableName tName = TableName.valueOf(table); synchronized (CONNECTION_LOCK) { this.currentTable = connection.getTable(tName); if (clientSideBuffering) { final BufferedMutatorParams p...
#fixed code public void writeTo( Writer writer, WriterConfig config ) throws IOException { if( writer == null ) { throw new NullPointerException( "writer is null" ); } if( config == null ) { throw new NullPointerException( "config is null" ); } WritingBuffer...
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public void writeTo( Writer writer, WriterConfig config ) throws IOException { WritingBuffer buffer = new WritingBuffer( writer, 128 ); write( config == null ? new JsonWriter( buffer ) : config.createWriter( buffer ) ); buffer.flush(); } ...
#fixed code public String save() { Command<Dataverse> cmd = null; //TODO change to Create - for now the page is expecting INFO instead. if (dataverse.getId() == null){ dataverse.setOwner(ownerId != null ? dataverseService.find(ownerId...
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public String save() { Command<Dataverse> cmd = null; if ( editMode == EditMode.INFO ) { dataverse.setOwner(ownerId != null ? dataverseService.find(ownerId) : null); cmd = new CreateDataverseCommand(dataverse, session.getUser()); }...
#fixed code private List<RuntimeException> validateModelWithDependencies( Executable executable, Map<String, Executable> dependencies, Set<Executable> verifiedExecutables, List<RuntimeException> errors) { //validate that all require...
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code private List<RuntimeException> validateModelWithDependencies( Executable executable, Map<String, Executable> dependencies, Set<Executable> verifiedExecutables, List<RuntimeException> errors) { //validate that all r...
#fixed code public List<Value> bindAsyncLoopList( AsyncLoopStatement asyncLoopStatement, Context flowContext, Set<SystemProperty> systemProperties, String nodeName) { Validate.notNull(asyncLoopStatement, "async loop statement cannot...
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public List<Value> bindAsyncLoopList( AsyncLoopStatement asyncLoopStatement, Context flowContext, Set<SystemProperty> systemProperties, String nodeName) { Validate.notNull(asyncLoopStatement, "async loop statement ...
#fixed code public void beginTask(@Param(ScoreLangConstants.TASK_INPUTS_KEY) List<Input> taskInputs, @Param(ScoreLangConstants.LOOP_KEY) LoopStatement loop, @Param(ScoreLangConstants.RUN_ENV) RunEnvironment runEnv, ...
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public void beginTask(@Param(ScoreLangConstants.TASK_INPUTS_KEY) List<Input> taskInputs, @Param(ScoreLangConstants.LOOP_KEY) LoopStatement loop, @Param(ScoreLangConstants.RUN_ENV) RunEnvironment runEnv, ...
#fixed code @Override public void execute() throws MojoExecutionException, MojoFailureException { try { // check uncommitted changes checkUncommittedChanges(); // git for-each-ref --format='%(refname:short)' refs/heads/hotfix/* ...
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Override public void execute() throws MojoExecutionException, MojoFailureException { try { // check uncommitted changes checkUncommittedChanges(); // git for-each-ref --format='%(refname:short)' refs/heads/hotfix/* ...
#fixed code private List<Node<T, S>> createChildren() { List<Node<T, S>> children = new ArrayList<Node<T, S>>(node.childrenLength()); // reduce allocations by resusing objects int numChildren = node.childrenLength(); for (int i = 0; i < numChildren; i++) {...
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code private List<Node<T, S>> createChildren() { List<Node<T, S>> children = new ArrayList<Node<T, S>>(node.childrenLength()); // reduce allocations by resusing objects int numChildren = node.childrenLength(); for (int i = 0; i < numChildren; ...
#fixed code public boolean isInStruct() { return currentContainerIndex >= 0 && currentContainer().type == ContainerType.STRUCT; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public boolean isInStruct() { return !containers.isEmpty() && currentContainer().type == ContainerType.STRUCT; } #location 3 #vulnerability type NULL_DEREFERENCE
#fixed code @Test public void testGetMovieChangesList() throws MovieDbException { LOG.info("getMovieChangesList"); List<ChangeListItem> result = instance.getChangeList(MethodBase.MOVIE, null, null, null); assertFalse("No movie changes.", result.isEmpty()); ...
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void testGetMovieChangesList() throws MovieDbException { LOG.info("getMovieChangesList"); TmdbResultsList<ChangedMedia> result = instance.getChangeList(MethodBase.MOVIE, null, null, null); assertFalse("No movie changes.", result....
#fixed code public void read(String filename){ BufferedReader reader = getReader(filename); String line = null; boolean firstline = true; Coordinate depotCoord = null; int customerCount=0; Integer nuOfCustomer = 0; while((line=readLine(reader))!=null){ String trimedLine = l...
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public void read(String filename){ BufferedReader reader = getReader(filename); String line = null; boolean firstline = true; Coordinate depotCoord = null; int customerCount=0; Integer nuOfCustomer = 0; while((line=readLine(reader))!=null){ String trimedLi...
#fixed code @Test public void testStatesOfAct1(){ states.informInsertionStarts(Arrays.asList(vehicleRoute), null); assertEquals(10.0, states.getActivityState(act1, StateFactory.COSTS).toDouble(),0.05); assertEquals(5.0, states.getActivityState(act1, StateFactory.LOAD).toDouble(),0.05...
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void testStatesOfAct1(){ states.informInsertionStarts(Arrays.asList(vehicleRoute), null); assertEquals(10.0, states.getActivityState(tour.getActivities().get(0), StateFactory.COSTS).toDouble(),0.05); assertEquals(5.0, states.getActivityState(tour.getAct...
#fixed code public HttpResponse execute() throws Exception { StringBuilder requestBody = new StringBuilder(); if (request.getEntity() != null) { String content = ObjectMapperSingleton.getContext(request.getEntity().getClass()).writer().writeValueAsString(reque...
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public HttpResponse execute() throws Exception { StringBuilder requestBody = new StringBuilder(); if (request.getEntity() != null) { String content = ObjectMapperSingleton.getContext(request.getEntity().getClass()).writer().writeValueAsString...
#fixed code @Test public void testHelpSet() { final String expected = "1/1 !help set\n" + "!set List / set a sqlline variable\n" + "\n" + "Variables:\n" + "\n" + "Variable Value Description\n" + "====...
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void testHelpSet() { final String expected = "1/1 !help set\n" + "!set List / set a sqlline variable\n" + "\n" + "Variables:\n" + "\n" + "Variable Value Description\n" +...
#fixed code @Test public void testSave() { ByteArrayOutputStream os = new ByteArrayOutputStream(); final String testSqllinePropertiesFile = "test.sqlline.properties"; try { SqlLine.Status status = begin(sqlLine, os, false, "--propertiesFile=" + testSqllineProp...
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void testSave() { final SqlLine beeLine = new SqlLine(); ByteArrayOutputStream os = new ByteArrayOutputStream(); try { SqlLine.Status status = begin(beeLine, os, false, "-e", "!save"); assertThat(status, equalTo(SqlLine.Sta...
#fixed code @Test public void testExecutionException(@Mocked final JDBCDatabaseMetaData meta, @Mocked final JDBCResultSet resultSet) { try { new Expectations() { { // prevent calls to functions that also call resultSet.next meta.getDatabaseProd...
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void testExecutionException(@Mocked final JDBCDatabaseMetaData meta, @Mocked final JDBCResultSet resultSet) { try { new Expectations() { { // prevent calls to functions that also call resultSet.next meta.getDataba...
#fixed code @Test public void testCommandHandlerOnStartup() { ByteArrayOutputStream os = new ByteArrayOutputStream(); final String[] args = { "-e", "!set maxwidth 80", "-ch", "sqlline.extensions.HelloWorldCommandHandler"}; begin(sqlLine, os, false, args); ...
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void testCommandHandlerOnStartup() { SqlLine sqlLine = new SqlLine(); ByteArrayOutputStream os = new ByteArrayOutputStream(); final String[] args = { "-e", "!set maxwidth 80", "-ch", "sqlline.extensions.HelloWorldCommandHandler"}...