input
stringlengths
205
73.3k
output
stringlengths
64
73.2k
instruction
stringclasses
1 value
#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(this, arg)) * 31 + (n.getParameters().accept(this, arg)) * 31 + (n.getReceiverParameter().isPresent() ? n.getReceiverParameter().get().accept(this, arg) : 0) * 31 + (n.getThrownExceptions().accept(this, arg)) * 31 + (n.getTypeParameters().accept(this, arg)) * 31 + (n.getAnnotations().accept(this, arg)) * 31 + (n.getComment().isPresent() ? n.getComment().get().accept(this, arg) : 0); } #location 3 #vulnerability type NULL_DEREFERENCE
#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, arg)) * 31 + (n.getParameters().accept(this, arg)) * 31 + (n.getThrownExceptions().accept(this, arg)) * 31 + (n.getTypeParameters().accept(this, arg)) * 31 + (n.getAnnotations().accept(this, arg)) * 31 + (n.getComment().isPresent() ? n.getComment().get().accept(this, arg) : 0); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test void resolveFieldOfEnumAsInternalClassOfInterfaceQualifiedSamePackage() throws IOException { File src = new File("src/test/resources/internalClassInInterface"); File aClass = new File(src.getPath() + File.separator + "foo" + File.separator + "bar" + File.separator + "AClass.java"); CombinedTypeSolver localCts = new CombinedTypeSolver(); localCts.add(new ReflectionTypeSolver()); localCts.add(new JavaParserTypeSolver(src)); ParserConfiguration parserConfiguration = new ParserConfiguration().setSymbolResolver(new JavaSymbolSolver(localCts)); JavaParser parser = new JavaParser(parserConfiguration); StreamProvider classProvider = new StreamProvider(new FileInputStream(aClass), StandardCharsets.UTF_8); CompilationUnit cu = parser.parse(ParseStart.COMPILATION_UNIT, classProvider).getResult().get(); Optional<FieldAccessExpr> fae = cu.findFirst(FieldAccessExpr.class, n -> n.toString().equals("foo.bar.AnInterface.ListChangeType.ADDITION") && n.getRange().get().begin.line == 5); assertTrue(fae.isPresent()); assertEquals("foo.bar.AnInterface.ListChangeType", fae.get().resolve().getType().describe()); assertEquals("ADDITION", fae.get().resolve().getName()); } #location 13 #vulnerability type RESOURCE_LEAK
#fixed code @Test void resolveFieldOfEnumAsInternalClassOfInterfaceQualifiedSamePackage() throws IOException { File src = new File("src/test/resources/internalClassInInterface"); File aClass = new File(src.getPath() + File.separator + "foo" + File.separator + "bar" + File.separator + "AClass.java"); CombinedTypeSolver localCts = new CombinedTypeSolver(); localCts.add(new ReflectionTypeSolver()); localCts.add(new JavaParserTypeSolver(src)); ParserConfiguration parserConfiguration = new ParserConfiguration().setSymbolResolver(new JavaSymbolSolver(localCts)); JavaParser parser = new JavaParser(parserConfiguration); StreamProvider classProvider = new StreamProvider(new FileInputStream(aClass), StandardCharsets.UTF_8.name()); CompilationUnit cu = parser.parse(ParseStart.COMPILATION_UNIT, classProvider).getResult().get(); Optional<FieldAccessExpr> fae = cu.findFirst(FieldAccessExpr.class, n -> n.toString().equals("foo.bar.AnInterface.ListChangeType.ADDITION") && n.getRange().get().begin.line == 5); assertTrue(fae.isPresent()); assertEquals("foo.bar.AnInterface.ListChangeType", fae.get().resolve().getType().describe()); assertEquals("ADDITION", fae.get().resolve().getName()); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test void resolveFieldOfEnumAsInternalClassOfInterfaceUnqualifiedDifferentPackage() throws IOException { File src = new File("src/test/resources/internalClassInInterface"); File aClass = new File(src.getPath() + File.separator + "foo" + File.separator + "bar" + File.separator + "differentpackage" + File.separator + "AClass2.java"); CombinedTypeSolver localCts = new CombinedTypeSolver(); localCts.add(new ReflectionTypeSolver()); localCts.add(new JavaParserTypeSolver(src)); ParserConfiguration parserConfiguration = new ParserConfiguration().setSymbolResolver(new JavaSymbolSolver(localCts)); JavaParser parser = new JavaParser(parserConfiguration); StreamProvider classProvider = new StreamProvider(new FileInputStream(aClass)); CompilationUnit cu = parser.parse(ParseStart.COMPILATION_UNIT, classProvider).getResult().get(); Optional<FieldAccessExpr> fae = cu.findFirst(FieldAccessExpr.class, n -> n.toString().equals("AnInterface.ListChangeType.ADDITION") && n.getRange().get().begin.line == 6); assertTrue(fae.isPresent()); assertEquals("foo.bar.AnInterface.ListChangeType", fae.get().resolve().getType().describe()); assertEquals("ADDITION", fae.get().resolve().getName()); } #location 15 #vulnerability type RESOURCE_LEAK
#fixed code @Test void resolveFieldOfEnumAsInternalClassOfInterfaceUnqualifiedDifferentPackage() throws IOException { File src = new File("src/test/resources/internalClassInInterface"); File aClass = new File(src.getPath() + File.separator + "foo" + File.separator + "bar" + File.separator + "differentpackage" + File.separator + "AClass2.java"); CombinedTypeSolver localCts = new CombinedTypeSolver(); localCts.add(new ReflectionTypeSolver()); localCts.add(new JavaParserTypeSolver(src)); ParserConfiguration parserConfiguration = new ParserConfiguration().setSymbolResolver(new JavaSymbolSolver(localCts)); JavaParser parser = new JavaParser(parserConfiguration); StreamProvider classProvider = new StreamProvider(new FileInputStream(aClass), StandardCharsets.UTF_8); CompilationUnit cu = parser.parse(ParseStart.COMPILATION_UNIT, classProvider).getResult().get(); Optional<FieldAccessExpr> fae = cu.findFirst(FieldAccessExpr.class, n -> n.toString().equals("AnInterface.ListChangeType.ADDITION") && n.getRange().get().begin.line == 6); assertTrue(fae.isPresent()); assertEquals("foo.bar.AnInterface.ListChangeType", fae.get().resolve().getType().describe()); assertEquals("ADDITION", fae.get().resolve().getName()); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Override public SymbolReference<TypeDeclaration> solveType(String name, TypeSolver typeSolver) { return JavaParserFactory.getContext(wrappedNode.getParentNode(), typeSolver).solveType(name, typeSolver); } #location 3 #vulnerability type NULL_DEREFERENCE
#fixed code @Override public SymbolReference<TypeDeclaration> solveType(String name, TypeSolver typeSolver) { return JavaParserFactory.getContext(getParentNode(wrappedNode), typeSolver).solveType(name, typeSolver); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Override public Optional<MethodUsage> solveMethodAsUsage(String name, List<TypeUsage> parameterTypes, TypeSolver typeSolver) { // TODO consider call of static methods if (wrappedNode.getScope() != null) { try { TypeUsage typeOfScope = JavaParserFacade.get(typeSolver).getType(wrappedNode.getScope()); return typeOfScope.solveMethodAsUsage(name, parameterTypes, typeSolver, this); } catch (UnsolvedSymbolException e){ // ok, maybe it was instead a static access, so let's look for a type if (wrappedNode.getScope() instanceof NameExpr){ String className = ((NameExpr)wrappedNode.getScope()).getName(); SymbolReference<TypeDeclaration> ref = solveType(className, typeSolver); if (ref.isSolved()) { SymbolReference<MethodDeclaration> m = ref.getCorrespondingDeclaration().solveMethod(name, parameterTypes, typeSolver); if (m.isSolved()) { return Optional.of(new MethodUsage(m.getCorrespondingDeclaration(), typeSolver)); } else { throw new UnsolvedSymbolException(ref.getCorrespondingDeclaration().toString(), "Method "+name+" with parameterTypes "+parameterTypes); } } else { throw e; } } else { throw e; } } } else { if (wrappedNode.getParentNode() instanceof MethodCallExpr) { MethodCallExpr parent = (MethodCallExpr)wrappedNode.getParentNode(); if (parent.getScope() == wrappedNode) { return getParent().getParent().solveMethodAsUsage(name, parameterTypes, typeSolver); } } //TypeUsage typeOfScope = JavaParserFacade.get(typeSolver).getTypeOfThisIn(wrappedNode); //return typeOfScope.solveMethodAsUsage(name, parameterTypes, typeSolver, this); Context parentContext = getParent(); //System.out.println("NAME "+name); return parentContext.solveMethodAsUsage(name, parameterTypes, typeSolver); } } #location 38 #vulnerability type NULL_DEREFERENCE
#fixed code @Override public Optional<MethodUsage> solveMethodAsUsage(String name, List<TypeUsage> parameterTypes, TypeSolver typeSolver) { // TODO consider call of static methods if (wrappedNode.getScope() != null) { try { TypeUsage typeOfScope = JavaParserFacade.get(typeSolver).getType(wrappedNode.getScope()); return typeOfScope.solveMethodAsUsage(name, parameterTypes, typeSolver, this); } catch (UnsolvedSymbolException e){ // ok, maybe it was instead a static access, so let's look for a type if (wrappedNode.getScope() instanceof NameExpr){ String className = ((NameExpr)wrappedNode.getScope()).getName(); SymbolReference<TypeDeclaration> ref = solveType(className, typeSolver); if (ref.isSolved()) { if (name.equals("getModifiers") && !ref.getCorrespondingDeclaration().solveMethod(name, parameterTypes, typeSolver).isSolved()){ System.out.println("FOO"); } SymbolReference<MethodDeclaration> m = ref.getCorrespondingDeclaration().solveMethod(name, parameterTypes, typeSolver); if (m.isSolved()) { return Optional.of(new MethodUsage(m.getCorrespondingDeclaration(), typeSolver)); } else { throw new UnsolvedSymbolException(ref.getCorrespondingDeclaration().toString(), "Method "+name+" with parameterTypes "+parameterTypes); } } else { throw e; } } else { throw e; } } } else { if (wrappedNode.getParentNode() instanceof MethodCallExpr) { MethodCallExpr parent = (MethodCallExpr)wrappedNode.getParentNode(); if (parent.getScope() == wrappedNode) { return getParent().getParent().solveMethodAsUsage(name, parameterTypes, typeSolver); } } //TypeUsage typeOfScope = JavaParserFacade.get(typeSolver).getTypeOfThisIn(wrappedNode); //return typeOfScope.solveMethodAsUsage(name, parameterTypes, typeSolver, this); Context parentContext = getParent(); //System.out.println("NAME "+name); return parentContext.solveMethodAsUsage(name, parameterTypes, typeSolver); } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Override public SymbolReference<ResolvedTypeDeclaration> solveType(String name, TypeSolver typeSolver) { if (wrappedNode.getTypes() != null) { for (TypeDeclaration<?> type : wrappedNode.getTypes()) { if (type.getName().getId().equals(name)) { if (type instanceof ClassOrInterfaceDeclaration) { return SymbolReference.solved(JavaParserFacade.get(typeSolver).getTypeDeclaration((ClassOrInterfaceDeclaration) type)); } else if (type instanceof AnnotationDeclaration) { return SymbolReference.solved(new JavaParserAnnotationDeclaration((AnnotationDeclaration) type, typeSolver)); } else if (type instanceof EnumDeclaration) { return SymbolReference.solved(new JavaParserEnumDeclaration((EnumDeclaration) type, typeSolver)); } else { throw new UnsupportedOperationException(type.getClass().getCanonicalName()); } } } } // Look in current package if (this.wrappedNode.getPackageDeclaration().isPresent()) { String qName = this.wrappedNode.getPackageDeclaration().get().getName().toString() + "." + name; SymbolReference<ResolvedReferenceTypeDeclaration> ref = typeSolver.tryToSolveType(qName); if (ref != null && ref.isSolved()) { return SymbolReference.adapt(ref, ResolvedTypeDeclaration.class); } } else { // look for classes in the default package String qName = name; SymbolReference<ResolvedReferenceTypeDeclaration> ref = typeSolver.tryToSolveType(qName); if (ref != null && ref.isSolved()) { return SymbolReference.adapt(ref, ResolvedTypeDeclaration.class); } } if (wrappedNode.getImports() != null) { int dotPos = name.indexOf('.'); String prefix = null; if (dotPos > -1) { prefix = name.substring(0, dotPos); } // look into type imports for (ImportDeclaration importDecl : wrappedNode.getImports()) { if (!importDecl.isAsterisk()) { String qName = importDecl.getNameAsString(); boolean defaultPackage = !importDecl.getName().getQualifier().isPresent(); boolean found = !defaultPackage && importDecl.getName().getIdentifier().equals(name); if (!found) { if (prefix != null) { found = qName.endsWith("." + prefix); if (found) { qName = qName + name.substring(dotPos); } } } if (found) { SymbolReference<ResolvedReferenceTypeDeclaration> ref = typeSolver.tryToSolveType(qName); if (ref.isSolved()) { return SymbolReference.adapt(ref, ResolvedTypeDeclaration.class); } } } } // look into type imports on demand for (ImportDeclaration importDecl : wrappedNode.getImports()) { if (importDecl.isAsterisk()) { String qName = importDecl.getNameAsString() + "." + name; SymbolReference<ResolvedReferenceTypeDeclaration> ref = typeSolver.tryToSolveType(qName); if (ref.isSolved()) { return SymbolReference.adapt(ref, ResolvedTypeDeclaration.class); } } } } // Look in the java.lang package SymbolReference<ResolvedReferenceTypeDeclaration> ref = typeSolver.tryToSolveType("java.lang." + name); if (ref.isSolved()) { return SymbolReference.adapt(ref, ResolvedTypeDeclaration.class); } // DO NOT look for absolute name if this name is not qualified: you cannot import classes from the default package if (isQualifiedName(name)) { return SymbolReference.adapt(typeSolver.tryToSolveType(name), ResolvedTypeDeclaration.class); } else { return SymbolReference.unsolved(ResolvedReferenceTypeDeclaration.class); } } #location 57 #vulnerability type NULL_DEREFERENCE
#fixed code @Override public SymbolReference<ResolvedTypeDeclaration> solveType(String name, TypeSolver typeSolver) { if (wrappedNode.getTypes() != null) { for (TypeDeclaration<?> type : wrappedNode.getTypes()) { if (type.getName().getId().equals(name)) { if (type instanceof ClassOrInterfaceDeclaration) { return SymbolReference.solved(JavaParserFacade.get(typeSolver).getTypeDeclaration((ClassOrInterfaceDeclaration) type)); } else if (type instanceof AnnotationDeclaration) { return SymbolReference.solved(new JavaParserAnnotationDeclaration((AnnotationDeclaration) type, typeSolver)); } else if (type instanceof EnumDeclaration) { return SymbolReference.solved(new JavaParserEnumDeclaration((EnumDeclaration) type, typeSolver)); } else { throw new UnsupportedOperationException(type.getClass().getCanonicalName()); } } } // look for member classes/interfaces of types in this compilation unit if (name.indexOf('.') > -1) { SymbolReference<ResolvedTypeDeclaration> ref = null; SymbolReference<ResolvedTypeDeclaration> outerMostRef = solveType(name.substring(0, name.indexOf(".")), typeSolver); if (outerMostRef.isSolved() && outerMostRef.getCorrespondingDeclaration() instanceof JavaParserClassDeclaration) { ref = ((JavaParserClassDeclaration) outerMostRef.getCorrespondingDeclaration()) .solveType(name.substring(name.indexOf(".") + 1), typeSolver); } if (ref != null && ref.isSolved()) { return ref; } } } // Look in current package if (this.wrappedNode.getPackageDeclaration().isPresent()) { String qName = this.wrappedNode.getPackageDeclaration().get().getName().toString() + "." + name; SymbolReference<ResolvedReferenceTypeDeclaration> ref = typeSolver.tryToSolveType(qName); if (ref != null && ref.isSolved()) { return SymbolReference.adapt(ref, ResolvedTypeDeclaration.class); } } else { // look for classes in the default package String qName = name; SymbolReference<ResolvedReferenceTypeDeclaration> ref = typeSolver.tryToSolveType(qName); if (ref != null && ref.isSolved()) { return SymbolReference.adapt(ref, ResolvedTypeDeclaration.class); } } if (wrappedNode.getImports() != null) { int dotPos = name.indexOf('.'); String prefix = null; if (dotPos > -1) { prefix = name.substring(0, dotPos); } // look into type imports for (ImportDeclaration importDecl : wrappedNode.getImports()) { if (!importDecl.isAsterisk()) { String qName = importDecl.getNameAsString(); boolean defaultPackage = !importDecl.getName().getQualifier().isPresent(); boolean found = !defaultPackage && importDecl.getName().getIdentifier().equals(name); if (!found) { if (prefix != null) { found = qName.endsWith("." + prefix); if (found) { qName = qName + name.substring(dotPos); } } } if (found) { SymbolReference<ResolvedReferenceTypeDeclaration> ref = typeSolver.tryToSolveType(qName); if (ref != null && ref.isSolved()) { return SymbolReference.adapt(ref, ResolvedTypeDeclaration.class); } } } } // look into type imports on demand for (ImportDeclaration importDecl : wrappedNode.getImports()) { if (importDecl.isAsterisk()) { String qName = importDecl.getNameAsString() + "." + name; SymbolReference<ResolvedReferenceTypeDeclaration> ref = typeSolver.tryToSolveType(qName); if (ref != null && ref.isSolved()) { return SymbolReference.adapt(ref, ResolvedTypeDeclaration.class); } } } } // Look in the java.lang package SymbolReference<ResolvedReferenceTypeDeclaration> ref = typeSolver.tryToSolveType("java.lang." + name); if (ref != null && ref.isSolved()) { return SymbolReference.adapt(ref, ResolvedTypeDeclaration.class); } // DO NOT look for absolute name if this name is not qualified: you cannot import classes from the default package if (isQualifiedName(name)) { return SymbolReference.adapt(typeSolver.tryToSolveType(name), ResolvedTypeDeclaration.class); } else { return SymbolReference.unsolved(ResolvedReferenceTypeDeclaration.class); } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test void resolveFieldOfEnumAsInternalClassOfInterfaceQualifiedDifferentPackage() throws IOException { File src = new File("src/test/resources/internalClassInInterface"); File aClass = new File(src.getPath() + File.separator + "foo" + File.separator + "bar" + File.separator + "differentpackage" + File.separator + "AClass2.java"); CombinedTypeSolver localCts = new CombinedTypeSolver(); localCts.add(new ReflectionTypeSolver()); localCts.add(new JavaParserTypeSolver(src)); ParserConfiguration parserConfiguration = new ParserConfiguration().setSymbolResolver(new JavaSymbolSolver(localCts)); JavaParser parser = new JavaParser(parserConfiguration); StreamProvider classProvider = new StreamProvider(new FileInputStream(aClass)); CompilationUnit cu = parser.parse(ParseStart.COMPILATION_UNIT, classProvider).getResult().get(); Optional<FieldAccessExpr> fae = cu.findFirst(FieldAccessExpr.class, n -> n.toString().equals("foo.bar.AnInterface.ListChangeType.ADDITION") && n.getRange().get().begin.line == 7); assertTrue(fae.isPresent()); assertEquals("foo.bar.AnInterface.ListChangeType", fae.get().resolve().getType().describe()); assertEquals("ADDITION", fae.get().resolve().getName()); } #location 15 #vulnerability type RESOURCE_LEAK
#fixed code @Test void resolveFieldOfEnumAsInternalClassOfInterfaceQualifiedDifferentPackage() throws IOException { File src = new File("src/test/resources/internalClassInInterface"); File aClass = new File(src.getPath() + File.separator + "foo" + File.separator + "bar" + File.separator + "differentpackage" + File.separator + "AClass2.java"); CombinedTypeSolver localCts = new CombinedTypeSolver(); localCts.add(new ReflectionTypeSolver()); localCts.add(new JavaParserTypeSolver(src)); ParserConfiguration parserConfiguration = new ParserConfiguration().setSymbolResolver(new JavaSymbolSolver(localCts)); JavaParser parser = new JavaParser(parserConfiguration); StreamProvider classProvider = new StreamProvider(new FileInputStream(aClass), StandardCharsets.UTF_8); CompilationUnit cu = parser.parse(ParseStart.COMPILATION_UNIT, classProvider).getResult().get(); Optional<FieldAccessExpr> fae = cu.findFirst(FieldAccessExpr.class, n -> n.toString().equals("foo.bar.AnInterface.ListChangeType.ADDITION") && n.getRange().get().begin.line == 7); assertTrue(fae.isPresent()); assertEquals("foo.bar.AnInterface.ListChangeType", fae.get().resolve().getType().describe()); assertEquals("ADDITION", fae.get().resolve().getName()); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public void saveAll() throws FileNotFoundException, UnsupportedEncodingException { for (CompilationUnit cu : compilationUnits) { Path filename = cu.getData(ORIGINAL_LOCATION); System.out.println("Saving " + filename); filename.getParent().toFile().mkdirs(); String code = new PrettyPrinter().print(cu); try (PrintWriter out = new PrintWriter(filename.toFile(), UTF8.toString())) { out.println(code); } } } #location 5 #vulnerability type NULL_DEREFERENCE
#fixed code public void saveAll() throws FileNotFoundException, UnsupportedEncodingException { saveAll(root); }
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 + "bar" + File.separator + "AClass.java"); CombinedTypeSolver localCts = new CombinedTypeSolver(); localCts.add(new ReflectionTypeSolver()); localCts.add(new JavaParserTypeSolver(src)); ParserConfiguration parserConfiguration = new ParserConfiguration().setSymbolResolver(new JavaSymbolSolver(localCts)); JavaParser parser = new JavaParser(parserConfiguration); StreamProvider classProvider = new StreamProvider(new FileInputStream(aClass), StandardCharsets.UTF_8); CompilationUnit cu = parser.parse(ParseStart.COMPILATION_UNIT, classProvider).getResult().get(); Optional<FieldAccessExpr> fae = cu.findFirst(FieldAccessExpr.class, n -> n.toString().equals("BinaryExpr.Operator.OR") && n.getRange().get().begin.line == 4); assertTrue(fae.isPresent()); assertEquals("foo.bar.BinaryExpr.Operator", fae.get().resolve().getType().describe()); assertEquals("OR", fae.get().resolve().getName()); } #location 13 #vulnerability type RESOURCE_LEAK
#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" + File.separator + "AClass.java"); CombinedTypeSolver localCts = new CombinedTypeSolver(); localCts.add(new ReflectionTypeSolver()); localCts.add(new JavaParserTypeSolver(src)); ParserConfiguration parserConfiguration = new ParserConfiguration().setSymbolResolver(new JavaSymbolSolver(localCts)); JavaParser parser = new JavaParser(parserConfiguration); StreamProvider classProvider = new StreamProvider(new FileInputStream(aClass), StandardCharsets.UTF_8.name()); CompilationUnit cu = parser.parse(ParseStart.COMPILATION_UNIT, classProvider).getResult().get(); Optional<FieldAccessExpr> fae = cu.findFirst(FieldAccessExpr.class, n -> n.toString().equals("BinaryExpr.Operator.OR") && n.getRange().get().begin.line == 4); assertTrue(fae.isPresent()); assertEquals("foo.bar.BinaryExpr.Operator", fae.get().resolve().getType().describe()); assertEquals("OR", fae.get().resolve().getName()); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Override public SymbolReference<MethodDeclaration> solveMethod(String name, List<Type> parameterTypes) { return getContext().solveMethod(name, parameterTypes, typeSolver()); } #location 3 #vulnerability type NULL_DEREFERENCE
#fixed code @Override public SymbolReference<MethodDeclaration> solveMethod(String name, List<Type> parameterTypes) { Context ctx = getContext(); return ctx.solveMethod(name, parameterTypes, typeSolver); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public void solveMethodCalls(Path path) throws IOException { File file = path.toFile(); if (file.isDirectory()) { for (File f : file.listFiles()) { solveMethodCalls(f.toPath()); } } else { if (file.getName().endsWith(".java")) { if (printFileName) { out.println("- parsing " + file.getAbsolutePath()); } CompilationUnit cu = JavaParser.parse(file); solveMethodCalls(cu); } } } #location 4 #vulnerability type NULL_DEREFERENCE
#fixed code public void solveMethodCalls(Path path) throws IOException { Files.walkFileTree(path, new SimpleFileVisitor<Path>() { @Override public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException { if (file.toString().endsWith(".java")) { if (printFileName) { out.println("- parsing " + file.toAbsolutePath()); } CompilationUnit cu = JavaParser.parse(file); solveMethodCalls(cu); } return FileVisitResult.CONTINUE; } }); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test void resolveFieldOfEnumAsInternalClassOfInterfaceQualifiedSamePackage() throws IOException { File src = new File("src/test/resources/internalClassInInterface"); File aClass = new File(src.getPath() + File.separator + "foo" + File.separator + "bar" + File.separator + "AClass.java"); CombinedTypeSolver localCts = new CombinedTypeSolver(); localCts.add(new ReflectionTypeSolver()); localCts.add(new JavaParserTypeSolver(src)); ParserConfiguration parserConfiguration = new ParserConfiguration().setSymbolResolver(new JavaSymbolSolver(localCts)); JavaParser parser = new JavaParser(parserConfiguration); StreamProvider classProvider = new StreamProvider(new FileInputStream(aClass)); CompilationUnit cu = parser.parse(ParseStart.COMPILATION_UNIT, classProvider).getResult().get(); Optional<FieldAccessExpr> fae = cu.findFirst(FieldAccessExpr.class, n -> n.toString().equals("foo.bar.AnInterface.ListChangeType.ADDITION") && n.getRange().get().begin.line == 5); assertTrue(fae.isPresent()); assertEquals("foo.bar.AnInterface.ListChangeType", fae.get().resolve().getType().describe()); assertEquals("ADDITION", fae.get().resolve().getName()); } #location 15 #vulnerability type RESOURCE_LEAK
#fixed code @Test void resolveFieldOfEnumAsInternalClassOfInterfaceQualifiedSamePackage() throws IOException { File src = new File("src/test/resources/internalClassInInterface"); File aClass = new File(src.getPath() + File.separator + "foo" + File.separator + "bar" + File.separator + "AClass.java"); CombinedTypeSolver localCts = new CombinedTypeSolver(); localCts.add(new ReflectionTypeSolver()); localCts.add(new JavaParserTypeSolver(src)); ParserConfiguration parserConfiguration = new ParserConfiguration().setSymbolResolver(new JavaSymbolSolver(localCts)); JavaParser parser = new JavaParser(parserConfiguration); StreamProvider classProvider = new StreamProvider(new FileInputStream(aClass), StandardCharsets.UTF_8); CompilationUnit cu = parser.parse(ParseStart.COMPILATION_UNIT, classProvider).getResult().get(); Optional<FieldAccessExpr> fae = cu.findFirst(FieldAccessExpr.class, n -> n.toString().equals("foo.bar.AnInterface.ListChangeType.ADDITION") && n.getRange().get().begin.line == 5); assertTrue(fae.isPresent()); assertEquals("foo.bar.AnInterface.ListChangeType", fae.get().resolve().getType().describe()); assertEquals("ADDITION", fae.get().resolve().getName()); }
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 + "bar" + File.separator + "AClass.java"); CombinedTypeSolver localCts = new CombinedTypeSolver(); localCts.add(new ReflectionTypeSolver()); localCts.add(new JavaParserTypeSolver(src)); ParserConfiguration parserConfiguration = new ParserConfiguration().setSymbolResolver(new JavaSymbolSolver(localCts)); JavaParser parser = new JavaParser(parserConfiguration); StreamProvider classProvider = new StreamProvider(new FileInputStream(aClass), StandardCharsets.UTF_8); CompilationUnit cu = parser.parse(ParseStart.COMPILATION_UNIT, classProvider).getResult().get(); Optional<FieldAccessExpr> fae = cu.findFirst(FieldAccessExpr.class, n -> n.toString().equals("foo.bar.BinaryExpr.Operator.AND") && n.getRange().get().begin.line == 5); assertTrue(fae.isPresent()); assertEquals("foo.bar.BinaryExpr.Operator", fae.get().resolve().getType().describe()); assertEquals("AND", fae.get().resolve().getName()); } #location 13 #vulnerability type RESOURCE_LEAK
#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" + File.separator + "AClass.java"); CombinedTypeSolver localCts = new CombinedTypeSolver(); localCts.add(new ReflectionTypeSolver()); localCts.add(new JavaParserTypeSolver(src)); ParserConfiguration parserConfiguration = new ParserConfiguration().setSymbolResolver(new JavaSymbolSolver(localCts)); JavaParser parser = new JavaParser(parserConfiguration); StreamProvider classProvider = new StreamProvider(new FileInputStream(aClass), StandardCharsets.UTF_8.name()); CompilationUnit cu = parser.parse(ParseStart.COMPILATION_UNIT, classProvider).getResult().get(); Optional<FieldAccessExpr> fae = cu.findFirst(FieldAccessExpr.class, n -> n.toString().equals("foo.bar.BinaryExpr.Operator.AND") && n.getRange().get().begin.line == 5); assertTrue(fae.isPresent()); assertEquals("foo.bar.BinaryExpr.Operator", fae.get().resolve().getType().describe()); assertEquals("AND", fae.get().resolve().getName()); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test void resolveFieldOfEnumAsInternalClassOfInterfaceQualifiedDifferentPackage() throws IOException { File src = new File("src/test/resources/internalClassInInterface"); File aClass = new File(src.getPath() + File.separator + "foo" + File.separator + "bar" + File.separator + "differentpackage" + File.separator + "AClass2.java"); CombinedTypeSolver localCts = new CombinedTypeSolver(); localCts.add(new ReflectionTypeSolver()); localCts.add(new JavaParserTypeSolver(src)); ParserConfiguration parserConfiguration = new ParserConfiguration().setSymbolResolver(new JavaSymbolSolver(localCts)); JavaParser parser = new JavaParser(parserConfiguration); StreamProvider classProvider = new StreamProvider(new FileInputStream(aClass), StandardCharsets.UTF_8); CompilationUnit cu = parser.parse(ParseStart.COMPILATION_UNIT, classProvider).getResult().get(); Optional<FieldAccessExpr> fae = cu.findFirst(FieldAccessExpr.class, n -> n.toString().equals("foo.bar.AnInterface.ListChangeType.ADDITION") && n.getRange().get().begin.line == 7); assertTrue(fae.isPresent()); assertEquals("foo.bar.AnInterface.ListChangeType", fae.get().resolve().getType().describe()); assertEquals("ADDITION", fae.get().resolve().getName()); } #location 13 #vulnerability type RESOURCE_LEAK
#fixed code @Test void resolveFieldOfEnumAsInternalClassOfInterfaceQualifiedDifferentPackage() throws IOException { File src = new File("src/test/resources/internalClassInInterface"); File aClass = new File(src.getPath() + File.separator + "foo" + File.separator + "bar" + File.separator + "differentpackage" + File.separator + "AClass2.java"); CombinedTypeSolver localCts = new CombinedTypeSolver(); localCts.add(new ReflectionTypeSolver()); localCts.add(new JavaParserTypeSolver(src)); ParserConfiguration parserConfiguration = new ParserConfiguration().setSymbolResolver(new JavaSymbolSolver(localCts)); JavaParser parser = new JavaParser(parserConfiguration); StreamProvider classProvider = new StreamProvider(new FileInputStream(aClass), StandardCharsets.UTF_8.name()); CompilationUnit cu = parser.parse(ParseStart.COMPILATION_UNIT, classProvider).getResult().get(); Optional<FieldAccessExpr> fae = cu.findFirst(FieldAccessExpr.class, n -> n.toString().equals("foo.bar.AnInterface.ListChangeType.ADDITION") && n.getRange().get().begin.line == 7); assertTrue(fae.isPresent()); assertEquals("foo.bar.AnInterface.ListChangeType", fae.get().resolve().getType().describe()); assertEquals("ADDITION", fae.get().resolve().getName()); }
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); Type lambdaType = JavaParserFacade.get(typeSolver).getType(wrappedNode.getParentNode()); // TODO understand from the context to which method this corresponds //MethodDeclaration methodDeclaration = JavaParserFacade.get(typeSolver).getMethodCalled //MethodDeclaration methodCalled = JavaParserFacade.get(typeSolver).solve() throw new UnsupportedOperationException(wrappedNode.getClass().getCanonicalName()); } else { Type rawType = null; if (parameter.getType() instanceof com.github.javaparser.ast.type.PrimitiveType) { rawType = PrimitiveType.byName(((com.github.javaparser.ast.type.PrimitiveType) parameter.getType()).getType().name()); } else { rawType = JavaParserFacade.get(typeSolver).convertToUsage(parameter.getType(), wrappedNode); } if (parameter.isVarArgs()) { return new ArrayType(rawType); } else { return rawType; } } } else if (wrappedNode instanceof VariableDeclarator) { VariableDeclarator variableDeclarator = (VariableDeclarator) wrappedNode; if (wrappedNode.getParentNode() instanceof VariableDeclarationExpr) { VariableDeclarationExpr variableDeclarationExpr = (VariableDeclarationExpr) variableDeclarator.getParentNode(); return JavaParserFacade.get(typeSolver).convert(variableDeclarationExpr.getElementType(), JavaParserFactory.getContext(wrappedNode, typeSolver)); } else if (wrappedNode.getParentNode() instanceof FieldDeclaration) { FieldDeclaration fieldDeclaration = (FieldDeclaration) variableDeclarator.getParentNode(); return JavaParserFacade.get(typeSolver).convert(fieldDeclaration.getElementType(), JavaParserFactory.getContext(wrappedNode, typeSolver)); } else { throw new UnsupportedOperationException(wrappedNode.getParentNode().getClass().getCanonicalName()); } } else { throw new UnsupportedOperationException(wrappedNode.getClass().getCanonicalName()); } } #location 30 #vulnerability type NULL_DEREFERENCE
#fixed code @Override public Type getType() { if (wrappedNode instanceof Parameter) { Parameter parameter = (Parameter) wrappedNode; if (getParentNode(wrappedNode) instanceof LambdaExpr) { int pos = getParamPos(parameter); Type lambdaType = JavaParserFacade.get(typeSolver).getType(getParentNode(wrappedNode)); // TODO understand from the context to which method this corresponds //MethodDeclaration methodDeclaration = JavaParserFacade.get(typeSolver).getMethodCalled //MethodDeclaration methodCalled = JavaParserFacade.get(typeSolver).solve() throw new UnsupportedOperationException(wrappedNode.getClass().getCanonicalName()); } else { Type rawType = null; if (parameter.getType() instanceof com.github.javaparser.ast.type.PrimitiveType) { rawType = PrimitiveType.byName(((com.github.javaparser.ast.type.PrimitiveType) parameter.getType()).getType().name()); } else { rawType = JavaParserFacade.get(typeSolver).convertToUsage(parameter.getType(), wrappedNode); } if (parameter.isVarArgs()) { return new ArrayType(rawType); } else { return rawType; } } } else if (wrappedNode instanceof VariableDeclarator) { VariableDeclarator variableDeclarator = (VariableDeclarator) wrappedNode; if (getParentNode(wrappedNode) instanceof VariableDeclarationExpr) { VariableDeclarationExpr variableDeclarationExpr = (VariableDeclarationExpr) getParentNode(variableDeclarator); return JavaParserFacade.get(typeSolver).convert(variableDeclarationExpr.getElementType(), JavaParserFactory.getContext(wrappedNode, typeSolver)); } else if (getParentNode(wrappedNode) instanceof FieldDeclaration) { FieldDeclaration fieldDeclaration = (FieldDeclaration) getParentNode(variableDeclarator); return JavaParserFacade.get(typeSolver).convert(fieldDeclaration.getElementType(), JavaParserFactory.getContext(wrappedNode, typeSolver)); } else { throw new UnsupportedOperationException(getParentNode(wrappedNode).getClass().getCanonicalName()); } } else { throw new UnsupportedOperationException(wrappedNode.getClass().getCanonicalName()); } }
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)); ancestors.addAll(getSuperClass(typeSolver).getAllAncestors()); } ancestors.addAll(getAllInterfaces(typeSolver).stream().map((i)->new ReferenceTypeUsage(i, typeSolver)).collect(Collectors.<ReferenceTypeUsage>toList())); return ancestors; } #location 5 #vulnerability type NULL_DEREFERENCE
#fixed code @Override public List<ReferenceTypeUsage> getAllAncestors() { List<ReferenceTypeUsage> ancestors = new LinkedList<>(); if (getSuperClass(typeSolver) != null) { ReferenceTypeUsage superClass = getSuperClass(typeSolver); ancestors.add(superClass); ancestors.addAll(getSuperClass(typeSolver).getAllAncestors()); } ancestors.addAll(getAllInterfaces(typeSolver).stream().map((i)->new ReferenceTypeUsage(i, typeSolver)).collect(Collectors.<ReferenceTypeUsage>toList())); return ancestors; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code private void parse(String fileName) throws IOException { Path sourceFile = properSrc.resolve( fileName + ".java"); SourceFileInfoExtractor sourceFileInfoExtractor = getSourceFileInfoExtractor(); OutputStream outErrStream = new ByteArrayOutputStream(); PrintStream outErr = new PrintStream(outErrStream); sourceFileInfoExtractor.setOut(outErr); sourceFileInfoExtractor.setErr(outErr); sourceFileInfoExtractor.solve(sourceFile); String output = outErrStream.toString(); String path = "expected_output/" + fileName.replaceAll("/", "_") + ".txt"; Path dstFile = adaptPath(root.resolve(path)); if (DEBUG && (sourceFileInfoExtractor.getKo() != 0 || sourceFileInfoExtractor.getUnsupported() != 0)) { System.err.println(output); } assertEquals(0, sourceFileInfoExtractor.getKo(), "No failures expected when analyzing " + path); assertEquals(0, sourceFileInfoExtractor.getUnsupported(), "No UnsupportedOperationException expected when analyzing " + path); String expected = readFile(dstFile); String[] outputLines = output.split("\n"); String[] expectedLines = expected.split("\n"); for (int i = 0; i < Math.min(outputLines.length, expectedLines.length); i++) { assertEquals(expectedLines[i].trim(), outputLines[i].trim(), "Line " + (i + 1) + " of " + path + " is different from what is expected"); } assertEquals(expectedLines.length, outputLines.length); JavaParserFacade.clearInstances(); // If we need to update the file uncomment these lines //PrintWriter writer = new PrintWriter(dstFile.getAbsoluteFile(), "UTF-8"); //writer.print(output); //writer.close(); } #location 20 #vulnerability type RESOURCE_LEAK
#fixed code private void parse(String fileName) throws IOException { Path sourceFile = properSrc.resolve( fileName + ".java"); SourceFileInfoExtractor sourceFileInfoExtractor = getSourceFileInfoExtractor(); OutputStream outErrStream = new ByteArrayOutputStream(); PrintStream outErr = new PrintStream(outErrStream); sourceFileInfoExtractor.setOut(outErr); sourceFileInfoExtractor.setErr(outErr); sourceFileInfoExtractor.solve(sourceFile); String output = outErrStream.toString(); String path = "expected_output/" + fileName.replaceAll("/", "_") + ".txt"; Path dstFile = adaptPath(root.resolve(path)); if (DEBUG && (sourceFileInfoExtractor.getFailures() != 0 || sourceFileInfoExtractor.getUnsupported() != 0)) { System.err.println(output); } assertEquals(0, sourceFileInfoExtractor.getFailures(), "No failures expected when analyzing " + path); assertEquals(0, sourceFileInfoExtractor.getUnsupported(), "No UnsupportedOperationException expected when analyzing " + path); String expected = readFile(dstFile); String[] outputLines = output.split("\n"); String[] expectedLines = expected.split("\n"); for (int i = 0; i < Math.min(outputLines.length, expectedLines.length); i++) { assertEquals(expectedLines[i].trim(), outputLines[i].trim(), "Line " + (i + 1) + " of " + path + " is different from what is expected"); } assertEquals(expectedLines.length, outputLines.length); JavaParserFacade.clearInstances(); // If we need to update the file uncomment these lines //PrintWriter writer = new PrintWriter(dstFile.getAbsoluteFile(), "UTF-8"); //writer.print(output); //writer.close(); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test void resolveFieldOfEnumAsInternalClassOfInterfaceQualifiedDifferentPackage() throws IOException { File src = new File("src/test/resources/internalClassInInterface"); File aClass = new File(src.getPath() + File.separator + "foo" + File.separator + "bar" + File.separator + "differentpackage" + File.separator + "AClass2.java"); CombinedTypeSolver localCts = new CombinedTypeSolver(); localCts.add(new ReflectionTypeSolver()); localCts.add(new JavaParserTypeSolver(src)); ParserConfiguration parserConfiguration = new ParserConfiguration().setSymbolResolver(new JavaSymbolSolver(localCts)); JavaParser parser = new JavaParser(parserConfiguration); StreamProvider classProvider = new StreamProvider(new FileInputStream(aClass)); CompilationUnit cu = parser.parse(ParseStart.COMPILATION_UNIT, classProvider).getResult().get(); Optional<FieldAccessExpr> fae = cu.findFirst(FieldAccessExpr.class, n -> n.toString().equals("foo.bar.AnInterface.ListChangeType.ADDITION") && n.getRange().get().begin.line == 7); assertTrue(fae.isPresent()); assertEquals("foo.bar.AnInterface.ListChangeType", fae.get().resolve().getType().describe()); assertEquals("ADDITION", fae.get().resolve().getName()); } #location 15 #vulnerability type RESOURCE_LEAK
#fixed code @Test void resolveFieldOfEnumAsInternalClassOfInterfaceQualifiedDifferentPackage() throws IOException { File src = new File("src/test/resources/internalClassInInterface"); File aClass = new File(src.getPath() + File.separator + "foo" + File.separator + "bar" + File.separator + "differentpackage" + File.separator + "AClass2.java"); CombinedTypeSolver localCts = new CombinedTypeSolver(); localCts.add(new ReflectionTypeSolver()); localCts.add(new JavaParserTypeSolver(src)); ParserConfiguration parserConfiguration = new ParserConfiguration().setSymbolResolver(new JavaSymbolSolver(localCts)); JavaParser parser = new JavaParser(parserConfiguration); StreamProvider classProvider = new StreamProvider(new FileInputStream(aClass), StandardCharsets.UTF_8); CompilationUnit cu = parser.parse(ParseStart.COMPILATION_UNIT, classProvider).getResult().get(); Optional<FieldAccessExpr> fae = cu.findFirst(FieldAccessExpr.class, n -> n.toString().equals("foo.bar.AnInterface.ListChangeType.ADDITION") && n.getRange().get().begin.line == 7); assertTrue(fae.isPresent()); assertEquals("foo.bar.AnInterface.ListChangeType", fae.get().resolve().getType().describe()); assertEquals("ADDITION", fae.get().resolve().getName()); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Override public SymbolReference<ResolvedTypeDeclaration> solveType(String name, TypeSolver typeSolver) { if (wrappedNode.getTypes() != null) { for (TypeDeclaration<?> type : wrappedNode.getTypes()) { if (type.getName().getId().equals(name)) { if (type instanceof ClassOrInterfaceDeclaration) { return SymbolReference.solved(JavaParserFacade.get(typeSolver).getTypeDeclaration((ClassOrInterfaceDeclaration) type)); } else if (type instanceof AnnotationDeclaration) { return SymbolReference.solved(new JavaParserAnnotationDeclaration((AnnotationDeclaration) type, typeSolver)); } else if (type instanceof EnumDeclaration) { return SymbolReference.solved(new JavaParserEnumDeclaration((EnumDeclaration) type, typeSolver)); } else { throw new UnsupportedOperationException(type.getClass().getCanonicalName()); } } } } // Look in current package if (this.wrappedNode.getPackageDeclaration().isPresent()) { String qName = this.wrappedNode.getPackageDeclaration().get().getName().toString() + "." + name; SymbolReference<ResolvedReferenceTypeDeclaration> ref = typeSolver.tryToSolveType(qName); if (ref != null && ref.isSolved()) { return SymbolReference.adapt(ref, ResolvedTypeDeclaration.class); } } else { // look for classes in the default package String qName = name; SymbolReference<ResolvedReferenceTypeDeclaration> ref = typeSolver.tryToSolveType(qName); if (ref != null && ref.isSolved()) { return SymbolReference.adapt(ref, ResolvedTypeDeclaration.class); } } if (wrappedNode.getImports() != null) { int dotPos = name.indexOf('.'); String prefix = null; if (dotPos > -1) { prefix = name.substring(0, dotPos); } // look into type imports for (ImportDeclaration importDecl : wrappedNode.getImports()) { if (!importDecl.isAsterisk()) { String qName = importDecl.getNameAsString(); boolean defaultPackage = !importDecl.getName().getQualifier().isPresent(); boolean found = !defaultPackage && importDecl.getName().getIdentifier().equals(name); if (!found) { if (prefix != null) { found = qName.endsWith("." + prefix); if (found) { qName = qName + name.substring(dotPos); } } } if (found) { SymbolReference<ResolvedReferenceTypeDeclaration> ref = typeSolver.tryToSolveType(qName); if (ref.isSolved()) { return SymbolReference.adapt(ref, ResolvedTypeDeclaration.class); } } } } // look into type imports on demand for (ImportDeclaration importDecl : wrappedNode.getImports()) { if (importDecl.isAsterisk()) { String qName = importDecl.getNameAsString() + "." + name; SymbolReference<ResolvedReferenceTypeDeclaration> ref = typeSolver.tryToSolveType(qName); if (ref.isSolved()) { return SymbolReference.adapt(ref, ResolvedTypeDeclaration.class); } } } } // Look in the java.lang package SymbolReference<ResolvedReferenceTypeDeclaration> ref = typeSolver.tryToSolveType("java.lang." + name); if (ref.isSolved()) { return SymbolReference.adapt(ref, ResolvedTypeDeclaration.class); } // DO NOT look for absolute name if this name is not qualified: you cannot import classes from the default package if (isQualifiedName(name)) { return SymbolReference.adapt(typeSolver.tryToSolveType(name), ResolvedTypeDeclaration.class); } else { return SymbolReference.unsolved(ResolvedReferenceTypeDeclaration.class); } } #location 57 #vulnerability type NULL_DEREFERENCE
#fixed code @Override public SymbolReference<ResolvedTypeDeclaration> solveType(String name, TypeSolver typeSolver) { if (wrappedNode.getTypes() != null) { for (TypeDeclaration<?> type : wrappedNode.getTypes()) { if (type.getName().getId().equals(name)) { if (type instanceof ClassOrInterfaceDeclaration) { return SymbolReference.solved(JavaParserFacade.get(typeSolver).getTypeDeclaration((ClassOrInterfaceDeclaration) type)); } else if (type instanceof AnnotationDeclaration) { return SymbolReference.solved(new JavaParserAnnotationDeclaration((AnnotationDeclaration) type, typeSolver)); } else if (type instanceof EnumDeclaration) { return SymbolReference.solved(new JavaParserEnumDeclaration((EnumDeclaration) type, typeSolver)); } else { throw new UnsupportedOperationException(type.getClass().getCanonicalName()); } } } // look for member classes/interfaces of types in this compilation unit if (name.indexOf('.') > -1) { SymbolReference<ResolvedTypeDeclaration> ref = null; SymbolReference<ResolvedTypeDeclaration> outerMostRef = solveType(name.substring(0, name.indexOf(".")), typeSolver); if (outerMostRef.isSolved() && outerMostRef.getCorrespondingDeclaration() instanceof JavaParserClassDeclaration) { ref = ((JavaParserClassDeclaration) outerMostRef.getCorrespondingDeclaration()) .solveType(name.substring(name.indexOf(".") + 1), typeSolver); } if (ref != null && ref.isSolved()) { return ref; } } } // Look in current package if (this.wrappedNode.getPackageDeclaration().isPresent()) { String qName = this.wrappedNode.getPackageDeclaration().get().getName().toString() + "." + name; SymbolReference<ResolvedReferenceTypeDeclaration> ref = typeSolver.tryToSolveType(qName); if (ref != null && ref.isSolved()) { return SymbolReference.adapt(ref, ResolvedTypeDeclaration.class); } } else { // look for classes in the default package String qName = name; SymbolReference<ResolvedReferenceTypeDeclaration> ref = typeSolver.tryToSolveType(qName); if (ref != null && ref.isSolved()) { return SymbolReference.adapt(ref, ResolvedTypeDeclaration.class); } } if (wrappedNode.getImports() != null) { int dotPos = name.indexOf('.'); String prefix = null; if (dotPos > -1) { prefix = name.substring(0, dotPos); } // look into type imports for (ImportDeclaration importDecl : wrappedNode.getImports()) { if (!importDecl.isAsterisk()) { String qName = importDecl.getNameAsString(); boolean defaultPackage = !importDecl.getName().getQualifier().isPresent(); boolean found = !defaultPackage && importDecl.getName().getIdentifier().equals(name); if (!found) { if (prefix != null) { found = qName.endsWith("." + prefix); if (found) { qName = qName + name.substring(dotPos); } } } if (found) { SymbolReference<ResolvedReferenceTypeDeclaration> ref = typeSolver.tryToSolveType(qName); if (ref != null && ref.isSolved()) { return SymbolReference.adapt(ref, ResolvedTypeDeclaration.class); } } } } // look into type imports on demand for (ImportDeclaration importDecl : wrappedNode.getImports()) { if (importDecl.isAsterisk()) { String qName = importDecl.getNameAsString() + "." + name; SymbolReference<ResolvedReferenceTypeDeclaration> ref = typeSolver.tryToSolveType(qName); if (ref != null && ref.isSolved()) { return SymbolReference.adapt(ref, ResolvedTypeDeclaration.class); } } } } // Look in the java.lang package SymbolReference<ResolvedReferenceTypeDeclaration> ref = typeSolver.tryToSolveType("java.lang." + name); if (ref != null && ref.isSolved()) { return SymbolReference.adapt(ref, ResolvedTypeDeclaration.class); } // DO NOT look for absolute name if this name is not qualified: you cannot import classes from the default package if (isQualifiedName(name)) { return SymbolReference.adapt(typeSolver.tryToSolveType(name), ResolvedTypeDeclaration.class); } else { return SymbolReference.unsolved(ResolvedReferenceTypeDeclaration.class); } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test void resolveFieldOfEnumAsInternalClassOfClassUnqualifiedDifferentPackage() throws IOException { File src = new File("src/test/resources/enumLiteralsInAnnotatedClass"); File aClass = new File(src.getPath() + File.separator + "foo" + File.separator + "bar" + File.separator + "differentpackage" + File.separator + "AClass2.java"); CombinedTypeSolver localCts = new CombinedTypeSolver(); localCts.add(new ReflectionTypeSolver()); localCts.add(new JavaParserTypeSolver(src)); ParserConfiguration parserConfiguration = new ParserConfiguration().setSymbolResolver(new JavaSymbolSolver(localCts)); JavaParser parser = new JavaParser(parserConfiguration); StreamProvider classProvider = new StreamProvider(new FileInputStream(aClass)); CompilationUnit cu = parser.parse(ParseStart.COMPILATION_UNIT, classProvider).getResult().get(); Optional<FieldAccessExpr> fae = cu.findFirst(FieldAccessExpr.class, n -> n.toString().equals("BinaryExpr.Operator.OR") && n.getRange().get().begin.line == 6); assertTrue(fae.isPresent()); assertEquals("foo.bar.BinaryExpr.Operator", fae.get().resolve().getType().describe()); assertEquals("OR", fae.get().resolve().getName()); } #location 15 #vulnerability type RESOURCE_LEAK
#fixed code @Test void resolveFieldOfEnumAsInternalClassOfClassUnqualifiedDifferentPackage() throws IOException { File src = new File("src/test/resources/enumLiteralsInAnnotatedClass"); File aClass = new File(src.getPath() + File.separator + "foo" + File.separator + "bar" + File.separator + "differentpackage" + File.separator + "AClass2.java"); CombinedTypeSolver localCts = new CombinedTypeSolver(); localCts.add(new ReflectionTypeSolver()); localCts.add(new JavaParserTypeSolver(src)); ParserConfiguration parserConfiguration = new ParserConfiguration().setSymbolResolver(new JavaSymbolSolver(localCts)); JavaParser parser = new JavaParser(parserConfiguration); StreamProvider classProvider = new StreamProvider(new FileInputStream(aClass), StandardCharsets.UTF_8); CompilationUnit cu = parser.parse(ParseStart.COMPILATION_UNIT, classProvider).getResult().get(); Optional<FieldAccessExpr> fae = cu.findFirst(FieldAccessExpr.class, n -> n.toString().equals("BinaryExpr.Operator.OR") && n.getRange().get().begin.line == 6); assertTrue(fae.isPresent()); assertEquals("foo.bar.BinaryExpr.Operator", fae.get().resolve().getType().describe()); assertEquals("OR", fae.get().resolve().getName()); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Override public Optional<Value> solveSymbolAsValue(String name, TypeSolver typeSolver) { return JavaParserFactory.getContext(wrappedNode.getParentNode()).solveSymbolAsValue(name, typeSolver); } #location 3 #vulnerability type NULL_DEREFERENCE
#fixed code @Override public Optional<Value> solveSymbolAsValue(String name, TypeSolver typeSolver) { return getParent().solveSymbolAsValue(name, typeSolver); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code private ParseResult parseSample(String sampleName) { InputStream is = this.getClass().getResourceAsStream( "/com/github/javaparser/issue_samples/" + sampleName + ".java.txt"); Provider p = Providers.provider(is, Charsets.UTF_8); return new JavaParser().parse(ParseStart.COMPILATION_UNIT, p); } #location 5 #vulnerability type RESOURCE_LEAK
#fixed code private ParseResult parseSample(String sampleName) { Provider p = Providers.resourceProvider( "com/github/javaparser/issue_samples/" + sampleName + ".java.txt"); return new JavaParser().parse(ParseStart.COMPILATION_UNIT, p); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Override public SymbolReference<? extends ValueDeclaration> solveSymbol(String name, TypeSolver typeSolver) { if (wrappedNode.getFieldExpr().toString().equals(name)) { if (wrappedNode.getScope() instanceof ThisExpr) { Type typeOfThis = JavaParserFacade.get(typeSolver).getTypeOfThisIn(wrappedNode); return new SymbolSolver(typeSolver).solveSymbolInType(typeOfThis.asReferenceType().getTypeDeclaration(), name); } } return JavaParserFactory.getContext(wrappedNode.getParentNode(), typeSolver).solveSymbol(name, typeSolver); } #location 9 #vulnerability type NULL_DEREFERENCE
#fixed code @Override public SymbolReference<? extends ValueDeclaration> solveSymbol(String name, TypeSolver typeSolver) { if (wrappedNode.getFieldExpr().toString().equals(name)) { if (wrappedNode.getScope() instanceof ThisExpr) { Type typeOfThis = JavaParserFacade.get(typeSolver).getTypeOfThisIn(wrappedNode); return new SymbolSolver(typeSolver).solveSymbolInType(typeOfThis.asReferenceType().getTypeDeclaration(), name); } } return JavaParserFactory.getContext(getParentNode(wrappedNode), typeSolver).solveSymbol(name, typeSolver); }
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 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 @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" + File.separator + "AClass.java"); CombinedTypeSolver localCts = new CombinedTypeSolver(); localCts.add(new ReflectionTypeSolver()); localCts.add(new JavaParserTypeSolver(src)); ParserConfiguration parserConfiguration = new ParserConfiguration().setSymbolResolver(new JavaSymbolSolver(localCts)); JavaParser parser = new JavaParser(parserConfiguration); StreamProvider classProvider = new StreamProvider(new FileInputStream(aClass)); CompilationUnit cu = parser.parse(ParseStart.COMPILATION_UNIT, classProvider).getResult().get(); Optional<FieldAccessExpr> fae = cu.findFirst(FieldAccessExpr.class, n -> n.toString().equals("BinaryExpr.Operator.OR") && n.getRange().get().begin.line == 4); assertTrue(fae.isPresent()); assertEquals("foo.bar.BinaryExpr.Operator", fae.get().resolve().getType().describe()); assertEquals("OR", fae.get().resolve().getName()); } #location 15 #vulnerability type RESOURCE_LEAK
#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" + File.separator + "AClass.java"); CombinedTypeSolver localCts = new CombinedTypeSolver(); localCts.add(new ReflectionTypeSolver()); localCts.add(new JavaParserTypeSolver(src)); ParserConfiguration parserConfiguration = new ParserConfiguration().setSymbolResolver(new JavaSymbolSolver(localCts)); JavaParser parser = new JavaParser(parserConfiguration); StreamProvider classProvider = new StreamProvider(new FileInputStream(aClass), StandardCharsets.UTF_8); CompilationUnit cu = parser.parse(ParseStart.COMPILATION_UNIT, classProvider).getResult().get(); Optional<FieldAccessExpr> fae = cu.findFirst(FieldAccessExpr.class, n -> n.toString().equals("BinaryExpr.Operator.OR") && n.getRange().get().begin.line == 4); assertTrue(fae.isPresent()); assertEquals("foo.bar.BinaryExpr.Operator", fae.get().resolve().getType().describe()); assertEquals("OR", fae.get().resolve().getName()); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test void resolveFieldOfEnumAsInternalClassOfInterfaceUnqualifiedSamePackage() throws IOException { File src = new File("src/test/resources/internalClassInInterface"); File aClass = new File(src.getPath() + File.separator + "foo" + File.separator + "bar" + File.separator + "AClass.java"); CombinedTypeSolver localCts = new CombinedTypeSolver(); localCts.add(new ReflectionTypeSolver()); localCts.add(new JavaParserTypeSolver(src)); ParserConfiguration parserConfiguration = new ParserConfiguration().setSymbolResolver(new JavaSymbolSolver(localCts)); JavaParser parser = new JavaParser(parserConfiguration); StreamProvider classProvider = new StreamProvider(new FileInputStream(aClass), StandardCharsets.UTF_8); CompilationUnit cu = parser.parse(ParseStart.COMPILATION_UNIT, classProvider).getResult().get(); Optional<FieldAccessExpr> fae = cu.findFirst(FieldAccessExpr.class, n -> n.toString().equals("AnInterface.ListChangeType.ADDITION") && n.getRange().get().begin.line == 4); assertTrue(fae.isPresent()); assertEquals("foo.bar.AnInterface.ListChangeType", fae.get().resolve().getType().describe()); assertEquals("ADDITION", fae.get().resolve().getName()); } #location 13 #vulnerability type RESOURCE_LEAK
#fixed code @Test void resolveFieldOfEnumAsInternalClassOfInterfaceUnqualifiedSamePackage() throws IOException { File src = new File("src/test/resources/internalClassInInterface"); File aClass = new File(src.getPath() + File.separator + "foo" + File.separator + "bar" + File.separator + "AClass.java"); CombinedTypeSolver localCts = new CombinedTypeSolver(); localCts.add(new ReflectionTypeSolver()); localCts.add(new JavaParserTypeSolver(src)); ParserConfiguration parserConfiguration = new ParserConfiguration().setSymbolResolver(new JavaSymbolSolver(localCts)); JavaParser parser = new JavaParser(parserConfiguration); StreamProvider classProvider = new StreamProvider(new FileInputStream(aClass), StandardCharsets.UTF_8.name()); CompilationUnit cu = parser.parse(ParseStart.COMPILATION_UNIT, classProvider).getResult().get(); Optional<FieldAccessExpr> fae = cu.findFirst(FieldAccessExpr.class, n -> n.toString().equals("AnInterface.ListChangeType.ADDITION") && n.getRange().get().begin.line == 4); assertTrue(fae.isPresent()); assertEquals("foo.bar.AnInterface.ListChangeType", fae.get().resolve().getType().describe()); assertEquals("ADDITION", fae.get().resolve().getName()); }
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 + "bar" + File.separator + "AClass.java"); CombinedTypeSolver localCts = new CombinedTypeSolver(); localCts.add(new ReflectionTypeSolver()); localCts.add(new JavaParserTypeSolver(src)); ParserConfiguration parserConfiguration = new ParserConfiguration().setSymbolResolver(new JavaSymbolSolver(localCts)); JavaParser parser = new JavaParser(parserConfiguration); StreamProvider classProvider = new StreamProvider(new FileInputStream(aClass)); CompilationUnit cu = parser.parse(ParseStart.COMPILATION_UNIT, classProvider).getResult().get(); Optional<FieldAccessExpr> fae = cu.findFirst(FieldAccessExpr.class, n -> n.toString().equals("foo.bar.BinaryExpr.Operator.AND") && n.getRange().get().begin.line == 5); assertTrue(fae.isPresent()); assertEquals("foo.bar.BinaryExpr.Operator", fae.get().resolve().getType().describe()); assertEquals("AND", fae.get().resolve().getName()); } #location 15 #vulnerability type RESOURCE_LEAK
#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" + File.separator + "AClass.java"); CombinedTypeSolver localCts = new CombinedTypeSolver(); localCts.add(new ReflectionTypeSolver()); localCts.add(new JavaParserTypeSolver(src)); ParserConfiguration parserConfiguration = new ParserConfiguration().setSymbolResolver(new JavaSymbolSolver(localCts)); JavaParser parser = new JavaParser(parserConfiguration); StreamProvider classProvider = new StreamProvider(new FileInputStream(aClass), StandardCharsets.UTF_8); CompilationUnit cu = parser.parse(ParseStart.COMPILATION_UNIT, classProvider).getResult().get(); Optional<FieldAccessExpr> fae = cu.findFirst(FieldAccessExpr.class, n -> n.toString().equals("foo.bar.BinaryExpr.Operator.AND") && n.getRange().get().begin.line == 5); assertTrue(fae.isPresent()); assertEquals("foo.bar.BinaryExpr.Operator", fae.get().resolve().getType().describe()); assertEquals("AND", fae.get().resolve().getName()); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test void resolveFieldOfEnumAsInternalClassOfClassUnqualifiedDifferentPackage() throws IOException { File src = new File("src/test/resources/enumLiteralsInAnnotatedClass"); File aClass = new File(src.getPath() + File.separator + "foo" + File.separator + "bar" + File.separator + "differentpackage" + File.separator + "AClass2.java"); CombinedTypeSolver localCts = new CombinedTypeSolver(); localCts.add(new ReflectionTypeSolver()); localCts.add(new JavaParserTypeSolver(src)); ParserConfiguration parserConfiguration = new ParserConfiguration().setSymbolResolver(new JavaSymbolSolver(localCts)); JavaParser parser = new JavaParser(parserConfiguration); StreamProvider classProvider = new StreamProvider(new FileInputStream(aClass), StandardCharsets.UTF_8); CompilationUnit cu = parser.parse(ParseStart.COMPILATION_UNIT, classProvider).getResult().get(); Optional<FieldAccessExpr> fae = cu.findFirst(FieldAccessExpr.class, n -> n.toString().equals("BinaryExpr.Operator.OR") && n.getRange().get().begin.line == 6); assertTrue(fae.isPresent()); assertEquals("foo.bar.BinaryExpr.Operator", fae.get().resolve().getType().describe()); assertEquals("OR", fae.get().resolve().getName()); } #location 13 #vulnerability type RESOURCE_LEAK
#fixed code @Test void resolveFieldOfEnumAsInternalClassOfClassUnqualifiedDifferentPackage() throws IOException { File src = new File("src/test/resources/enumLiteralsInAnnotatedClass"); File aClass = new File(src.getPath() + File.separator + "foo" + File.separator + "bar" + File.separator + "differentpackage" + File.separator + "AClass2.java"); CombinedTypeSolver localCts = new CombinedTypeSolver(); localCts.add(new ReflectionTypeSolver()); localCts.add(new JavaParserTypeSolver(src)); ParserConfiguration parserConfiguration = new ParserConfiguration().setSymbolResolver(new JavaSymbolSolver(localCts)); JavaParser parser = new JavaParser(parserConfiguration); StreamProvider classProvider = new StreamProvider(new FileInputStream(aClass), StandardCharsets.UTF_8.name()); CompilationUnit cu = parser.parse(ParseStart.COMPILATION_UNIT, classProvider).getResult().get(); Optional<FieldAccessExpr> fae = cu.findFirst(FieldAccessExpr.class, n -> n.toString().equals("BinaryExpr.Operator.OR") && n.getRange().get().begin.line == 6); assertTrue(fae.isPresent()); assertEquals("foo.bar.BinaryExpr.Operator", fae.get().resolve().getType().describe()); assertEquals("OR", fae.get().resolve().getName()); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test void resolveFieldOfEnumAsInternalClassOfClassUnqualifiedDifferentPackage() throws IOException { File src = new File("src/test/resources/enumLiteralsInAnnotatedClass"); File aClass = new File(src.getPath() + File.separator + "foo" + File.separator + "bar" + File.separator + "differentpackage" + File.separator + "AClass2.java"); CombinedTypeSolver localCts = new CombinedTypeSolver(); localCts.add(new ReflectionTypeSolver()); localCts.add(new JavaParserTypeSolver(src)); ParserConfiguration parserConfiguration = new ParserConfiguration().setSymbolResolver(new JavaSymbolSolver(localCts)); JavaParser parser = new JavaParser(parserConfiguration); StreamProvider classProvider = new StreamProvider(new FileInputStream(aClass)); CompilationUnit cu = parser.parse(ParseStart.COMPILATION_UNIT, classProvider).getResult().get(); Optional<FieldAccessExpr> fae = cu.findFirst(FieldAccessExpr.class, n -> n.toString().equals("BinaryExpr.Operator.OR") && n.getRange().get().begin.line == 6); assertTrue(fae.isPresent()); assertEquals("foo.bar.BinaryExpr.Operator", fae.get().resolve().getType().describe()); assertEquals("OR", fae.get().resolve().getName()); } #location 15 #vulnerability type RESOURCE_LEAK
#fixed code @Test void resolveFieldOfEnumAsInternalClassOfClassUnqualifiedDifferentPackage() throws IOException { File src = new File("src/test/resources/enumLiteralsInAnnotatedClass"); File aClass = new File(src.getPath() + File.separator + "foo" + File.separator + "bar" + File.separator + "differentpackage" + File.separator + "AClass2.java"); CombinedTypeSolver localCts = new CombinedTypeSolver(); localCts.add(new ReflectionTypeSolver()); localCts.add(new JavaParserTypeSolver(src)); ParserConfiguration parserConfiguration = new ParserConfiguration().setSymbolResolver(new JavaSymbolSolver(localCts)); JavaParser parser = new JavaParser(parserConfiguration); StreamProvider classProvider = new StreamProvider(new FileInputStream(aClass), StandardCharsets.UTF_8); CompilationUnit cu = parser.parse(ParseStart.COMPILATION_UNIT, classProvider).getResult().get(); Optional<FieldAccessExpr> fae = cu.findFirst(FieldAccessExpr.class, n -> n.toString().equals("BinaryExpr.Operator.OR") && n.getRange().get().begin.line == 6); assertTrue(fae.isPresent()); assertEquals("foo.bar.BinaryExpr.Operator", fae.get().resolve().getType().describe()); assertEquals("OR", fae.get().resolve().getName()); }
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 + "bar" + File.separator + "AClass.java"); CombinedTypeSolver localCts = new CombinedTypeSolver(); localCts.add(new ReflectionTypeSolver()); localCts.add(new JavaParserTypeSolver(src)); ParserConfiguration parserConfiguration = new ParserConfiguration().setSymbolResolver(new JavaSymbolSolver(localCts)); JavaParser parser = new JavaParser(parserConfiguration); StreamProvider classProvider = new StreamProvider(new FileInputStream(aClass)); CompilationUnit cu = parser.parse(ParseStart.COMPILATION_UNIT, classProvider).getResult().get(); Optional<FieldAccessExpr> fae = cu.findFirst(FieldAccessExpr.class, n -> n.toString().equals("BinaryExpr.Operator.OR") && n.getRange().get().begin.line == 4); assertTrue(fae.isPresent()); assertEquals("foo.bar.BinaryExpr.Operator", fae.get().resolve().getType().describe()); assertEquals("OR", fae.get().resolve().getName()); } #location 15 #vulnerability type RESOURCE_LEAK
#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" + File.separator + "AClass.java"); CombinedTypeSolver localCts = new CombinedTypeSolver(); localCts.add(new ReflectionTypeSolver()); localCts.add(new JavaParserTypeSolver(src)); ParserConfiguration parserConfiguration = new ParserConfiguration().setSymbolResolver(new JavaSymbolSolver(localCts)); JavaParser parser = new JavaParser(parserConfiguration); StreamProvider classProvider = new StreamProvider(new FileInputStream(aClass), StandardCharsets.UTF_8); CompilationUnit cu = parser.parse(ParseStart.COMPILATION_UNIT, classProvider).getResult().get(); Optional<FieldAccessExpr> fae = cu.findFirst(FieldAccessExpr.class, n -> n.toString().equals("BinaryExpr.Operator.OR") && n.getRange().get().begin.line == 4); assertTrue(fae.isPresent()); assertEquals("foo.bar.BinaryExpr.Operator", fae.get().resolve().getType().describe()); assertEquals("OR", fae.get().resolve().getName()); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test void resolveFieldOfEnumAsInternalClassOfInterfaceUnqualifiedDifferentPackage() throws IOException { File src = new File("src/test/resources/internalClassInInterface"); File aClass = new File(src.getPath() + File.separator + "foo" + File.separator + "bar" + File.separator + "differentpackage" + File.separator + "AClass2.java"); CombinedTypeSolver localCts = new CombinedTypeSolver(); localCts.add(new ReflectionTypeSolver()); localCts.add(new JavaParserTypeSolver(src)); ParserConfiguration parserConfiguration = new ParserConfiguration().setSymbolResolver(new JavaSymbolSolver(localCts)); JavaParser parser = new JavaParser(parserConfiguration); StreamProvider classProvider = new StreamProvider(new FileInputStream(aClass)); CompilationUnit cu = parser.parse(ParseStart.COMPILATION_UNIT, classProvider).getResult().get(); Optional<FieldAccessExpr> fae = cu.findFirst(FieldAccessExpr.class, n -> n.toString().equals("AnInterface.ListChangeType.ADDITION") && n.getRange().get().begin.line == 6); assertTrue(fae.isPresent()); assertEquals("foo.bar.AnInterface.ListChangeType", fae.get().resolve().getType().describe()); assertEquals("ADDITION", fae.get().resolve().getName()); } #location 15 #vulnerability type RESOURCE_LEAK
#fixed code @Test void resolveFieldOfEnumAsInternalClassOfInterfaceUnqualifiedDifferentPackage() throws IOException { File src = new File("src/test/resources/internalClassInInterface"); File aClass = new File(src.getPath() + File.separator + "foo" + File.separator + "bar" + File.separator + "differentpackage" + File.separator + "AClass2.java"); CombinedTypeSolver localCts = new CombinedTypeSolver(); localCts.add(new ReflectionTypeSolver()); localCts.add(new JavaParserTypeSolver(src)); ParserConfiguration parserConfiguration = new ParserConfiguration().setSymbolResolver(new JavaSymbolSolver(localCts)); JavaParser parser = new JavaParser(parserConfiguration); StreamProvider classProvider = new StreamProvider(new FileInputStream(aClass), StandardCharsets.UTF_8); CompilationUnit cu = parser.parse(ParseStart.COMPILATION_UNIT, classProvider).getResult().get(); Optional<FieldAccessExpr> fae = cu.findFirst(FieldAccessExpr.class, n -> n.toString().equals("AnInterface.ListChangeType.ADDITION") && n.getRange().get().begin.line == 6); assertTrue(fae.isPresent()); assertEquals("foo.bar.AnInterface.ListChangeType", fae.get().resolve().getType().describe()); assertEquals("ADDITION", fae.get().resolve().getName()); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void issue506() throws IOException { InputStream is = this.getClass().getResourceAsStream("/com/github/javaparser/SourcesHelperOldVersion.java.txt"); ParseResult<CompilationUnit> res = new JavaParser().parse(ParseStart.COMPILATION_UNIT, new StreamProvider(is)); assertTrue(res.getProblems().isEmpty()); CompilationUnit cu = res.getResult().get(); getAllNodes(cu).forEach(n -> { if (n.getRange() == null) { throw new IllegalArgumentException("There should be no node without a range: " + n + " (class: " + n.getClass().getCanonicalName() + ")"); } if (n.getBegin().get().line == 0 && !n.toString().isEmpty() && !(n instanceof ArrayBracketPair)) { throw new IllegalArgumentException("There should be no node at line 0: " + n + " (class: " + n.getClass().getCanonicalName() + ")"); } }); } #location 4 #vulnerability type RESOURCE_LEAK
#fixed code @Test public void issue506() throws IOException { ensureAllNodesHaveValidBeginPosition( "SourcesHelperOldVersion.java.txt" ); }
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().accept(this, arg)) * 31 + (n.getParameters().accept(this, arg)) * 31 + (n.getReceiverParameter().isPresent() ? n.getReceiverParameter().get().accept(this, arg) : 0) * 31 + (n.getThrownExceptions().accept(this, arg)) * 31 + (n.getTypeParameters().accept(this, arg)) * 31 + (n.getAnnotations().accept(this, arg)); } #location 3 #vulnerability type NULL_DEREFERENCE
#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().accept(this, arg)) * 31 + (n.getParameters().accept(this, arg)) * 31 + (n.getThrownExceptions().accept(this, arg)) * 31 + (n.getTypeParameters().accept(this, arg)) * 31 + (n.getAnnotations().accept(this, arg)); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public CommentsCollection parse(final InputStream in, final String encoding) throws IOException, UnsupportedEncodingException { boolean lastWasASlashR = false; BufferedReader br = new BufferedReader(new InputStreamReader(in)); CommentsCollection comments = new CommentsCollection(); int r; Deque prevTwoChars = new LinkedList<Character>(Arrays.asList('z','z')); State state = State.CODE; LineComment currentLineComment = null; BlockComment currentBlockComment = null; StringBuffer currentContent = null; int currLine = 1; int currCol = 1; while ((r=br.read()) != -1){ char c = (char)r; if (c=='\r'){ lastWasASlashR = true; } else if (c=='\n'&&lastWasASlashR){ lastWasASlashR=false; continue; } else { lastWasASlashR=false; } switch (state){ case CODE: if (prevTwoChars.peekLast().equals('/') && c=='/'){ currentLineComment = new LineComment(); currentLineComment.setBeginLine(currLine); currentLineComment.setBeginColumn(currCol-1); state = State.IN_LINE_COMMENT; currentContent = new StringBuffer(); } else if (prevTwoChars.peekLast().equals('/') && c=='*'){ currentBlockComment= new BlockComment(); currentBlockComment.setBeginLine(currLine); currentBlockComment.setBeginColumn(currCol-1); state = State.IN_BLOCK_COMMENT; currentContent = new StringBuffer(); } else { // nothing to do } break; case IN_LINE_COMMENT: if (c=='\n' || c=='\r'){ currentLineComment.setContent(currentContent.toString()); currentLineComment.setEndLine(currLine); currentLineComment.setEndColumn(currCol); comments.addComment(currentLineComment); state = State.CODE; } else { currentContent.append(c); } break; case IN_BLOCK_COMMENT: if (prevTwoChars.peekLast().equals('*') && c=='/' && !prevTwoChars.peekFirst().equals('/')){ // delete last character String content = currentContent.deleteCharAt(currentContent.toString().length()-1).toString(); if (content.startsWith("*")){ JavadocComment javadocComment = new JavadocComment(); javadocComment.setContent(content.substring(1)); javadocComment.setBeginLine(currentBlockComment.getBeginLine()); javadocComment.setBeginColumn(currentBlockComment.getBeginColumn()); javadocComment.setEndLine(currLine); javadocComment.setEndColumn(currCol+1); comments.addComment(javadocComment); } else { currentBlockComment.setContent(content); currentBlockComment.setEndLine(currLine); currentBlockComment.setEndColumn(currCol+1); comments.addComment(currentBlockComment); } state = State.CODE; } else { currentContent.append(c=='\r'?'\n':c); } break; default: throw new RuntimeException("Unexpected"); } switch (c){ case '\n': case '\r': currLine+=1; currCol = 1; break; case '\t': currCol+=COLUMNS_PER_TAB; break; default: currCol+=1; } prevTwoChars.remove(); prevTwoChars.add(c); } if (state==State.IN_LINE_COMMENT){ currentLineComment.setContent(currentContent.toString()); currentLineComment.setEndLine(currLine); currentLineComment.setEndColumn(currCol); comments.addComment(currentLineComment); } return comments; } #location 78 #vulnerability type NULL_DEREFERENCE
#fixed code public CommentsCollection parse(final InputStream in, final String encoding) throws IOException, UnsupportedEncodingException { boolean lastWasASlashR = false; BufferedReader br = new BufferedReader(new InputStreamReader(in)); CommentsCollection comments = new CommentsCollection(); int r; Deque prevTwoChars = new LinkedList<Character>(Arrays.asList('z','z')); State state = State.CODE; LineComment currentLineComment = null; BlockComment currentBlockComment = null; StringBuffer currentContent = null; int currLine = 1; int currCol = 1; while ((r=br.read()) != -1){ char c = (char)r; if (c=='\r'){ lastWasASlashR = true; } else if (c=='\n'&&lastWasASlashR){ lastWasASlashR=false; continue; } else { lastWasASlashR=false; } switch (state) { case CODE: if (prevTwoChars.peekLast().equals('/') && c == '/') { currentLineComment = new LineComment(); currentLineComment.setBeginLine(currLine); currentLineComment.setBeginColumn(currCol - 1); state = State.IN_LINE_COMMENT; currentContent = new StringBuffer(); } else if (prevTwoChars.peekLast().equals('/') && c == '*') { currentBlockComment = new BlockComment(); currentBlockComment.setBeginLine(currLine); currentBlockComment.setBeginColumn(currCol - 1); state = State.IN_BLOCK_COMMENT; currentContent = new StringBuffer(); } else if (c == '"') { state = State.IN_STRING; } else { // nothing to do } break; case IN_LINE_COMMENT: if (c=='\n' || c=='\r'){ currentLineComment.setContent(currentContent.toString()); currentLineComment.setEndLine(currLine); currentLineComment.setEndColumn(currCol); comments.addComment(currentLineComment); state = State.CODE; } else { currentContent.append(c); } break; case IN_BLOCK_COMMENT: if (prevTwoChars.peekLast().equals('*') && c=='/' && !prevTwoChars.peekFirst().equals('/')){ // delete last character String content = currentContent.deleteCharAt(currentContent.toString().length()-1).toString(); if (content.startsWith("*")){ JavadocComment javadocComment = new JavadocComment(); javadocComment.setContent(content.substring(1)); javadocComment.setBeginLine(currentBlockComment.getBeginLine()); javadocComment.setBeginColumn(currentBlockComment.getBeginColumn()); javadocComment.setEndLine(currLine); javadocComment.setEndColumn(currCol+1); comments.addComment(javadocComment); } else { currentBlockComment.setContent(content); currentBlockComment.setEndLine(currLine); currentBlockComment.setEndColumn(currCol+1); comments.addComment(currentBlockComment); } state = State.CODE; } else { currentContent.append(c=='\r'?'\n':c); } break; case IN_STRING: if (!prevTwoChars.peekLast().equals('\\') && c == '"') { state = State.CODE; } break; default: throw new RuntimeException("Unexpected"); } switch (c){ case '\n': case '\r': currLine+=1; currCol = 1; break; case '\t': currCol+=COLUMNS_PER_TAB; break; default: currCol+=1; } prevTwoChars.remove(); prevTwoChars.add(c); } if (state==State.IN_LINE_COMMENT){ currentLineComment.setContent(currentContent.toString()); currentLineComment.setEndLine(currLine); currentLineComment.setEndColumn(currCol); comments.addComment(currentLineComment); } return comments; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public void solve(Path path) throws IOException { File file = path.toFile(); if (file.isDirectory()) { for (File f : file.listFiles()) { solve(f.toPath()); } } else { if (file.getName().endsWith(".java")) { if (printFileName) { out.println("- parsing " + file.getAbsolutePath()); } CompilationUnit cu = JavaParser.parse(file); List<Node> nodes = collectAllNodes(cu); nodes.forEach(n -> solve(n)); } } } #location 4 #vulnerability type NULL_DEREFERENCE
#fixed code public void solve(Path path) throws IOException { Files.walkFileTree(path, new SimpleFileVisitor<Path>() { @Override public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException { if (file.toString().endsWith(".java")) { if (printFileName) { out.println("- parsing " + file.toAbsolutePath()); } CompilationUnit cu = JavaParser.parse(file); List<Node> nodes = collectAllNodes(cu); nodes.forEach(n -> solve(n)); } return FileVisitResult.CONTINUE; } }); }
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 + "bar" + File.separator + "AClass.java"); CombinedTypeSolver localCts = new CombinedTypeSolver(); localCts.add(new ReflectionTypeSolver()); localCts.add(new JavaParserTypeSolver(src)); ParserConfiguration parserConfiguration = new ParserConfiguration().setSymbolResolver(new JavaSymbolSolver(localCts)); JavaParser parser = new JavaParser(parserConfiguration); StreamProvider classProvider = new StreamProvider(new FileInputStream(aClass)); CompilationUnit cu = parser.parse(ParseStart.COMPILATION_UNIT, classProvider).getResult().get(); Optional<FieldAccessExpr> fae = cu.findFirst(FieldAccessExpr.class, n -> n.toString().equals("foo.bar.BinaryExpr.Operator.AND") && n.getRange().get().begin.line == 5); assertTrue(fae.isPresent()); assertEquals("foo.bar.BinaryExpr.Operator", fae.get().resolve().getType().describe()); assertEquals("AND", fae.get().resolve().getName()); } #location 15 #vulnerability type RESOURCE_LEAK
#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" + File.separator + "AClass.java"); CombinedTypeSolver localCts = new CombinedTypeSolver(); localCts.add(new ReflectionTypeSolver()); localCts.add(new JavaParserTypeSolver(src)); ParserConfiguration parserConfiguration = new ParserConfiguration().setSymbolResolver(new JavaSymbolSolver(localCts)); JavaParser parser = new JavaParser(parserConfiguration); StreamProvider classProvider = new StreamProvider(new FileInputStream(aClass), StandardCharsets.UTF_8); CompilationUnit cu = parser.parse(ParseStart.COMPILATION_UNIT, classProvider).getResult().get(); Optional<FieldAccessExpr> fae = cu.findFirst(FieldAccessExpr.class, n -> n.toString().equals("foo.bar.BinaryExpr.Operator.AND") && n.getRange().get().begin.line == 5); assertTrue(fae.isPresent()); assertEquals("foo.bar.BinaryExpr.Operator", fae.get().resolve().getType().describe()); assertEquals("AND", fae.get().resolve().getName()); }
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, false, 1)); DbTable table = new DbTable("tableA", columns); Map<String, FieldAlias> aliasMap = new HashMap<>(); aliasMap.put("f1", new FieldAlias("col3")); FieldsMappings mappings = new FieldsMappings("tableA", "topic1", true, aliasMap); FieldsMappings newMappings = PreparedStatementBuilderHelper.validateAndMerge(mappings, table); assertEquals(newMappings.getTableName(), mappings.getTableName()); assertEquals(newMappings.getIncomingTopic(), mappings.getIncomingTopic()); assertEquals(newMappings.areAllFieldsIncluded(), false); Map<String, FieldAlias> newAliasMap = newMappings.getMappings(); assertEquals(4, newAliasMap.size()); //+ the specific mapping assertTrue(newAliasMap.containsKey("col1")); assertEquals(newAliasMap.get("col1").getName(), "col1"); assertEquals(newAliasMap.get("col1").isPrimaryKey(), true); assertTrue(newAliasMap.containsKey("col2")); assertEquals(newAliasMap.get("col2").getName(), "col2"); assertEquals(newAliasMap.get("col2").isPrimaryKey(), false); assertTrue(newAliasMap.containsKey("col3")); assertEquals(newAliasMap.get("col3").getName(), "col3"); assertEquals(newAliasMap.get("col3").isPrimaryKey(), false); assertTrue(newAliasMap.containsKey("f1")); assertEquals(newAliasMap.get("f1").getName(), "col3"); assertEquals(newAliasMap.get("f1").isPrimaryKey(), false); } #location 25 #vulnerability type NULL_DEREFERENCE
#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, false, 1)); DbTable table = new DbTable("tableA", columns); Map<String, FieldAlias> aliasMap = new HashMap<>(); aliasMap.put("f1", new FieldAlias("col3")); FieldsMappings mappings = new FieldsMappings("tableA", "topic1", true, aliasMap); FieldsMappings newMappings = PreparedStatementBuilderHelper.validateAndMerge(mappings, table, InsertModeEnum.INSERT); assertEquals(newMappings.getTableName(), mappings.getTableName()); assertEquals(newMappings.getIncomingTopic(), mappings.getIncomingTopic()); assertEquals(newMappings.areAllFieldsIncluded(), false); Map<String, FieldAlias> newAliasMap = newMappings.getMappings(); assertEquals(4, newAliasMap.size()); //+ the specific mapping assertTrue(newAliasMap.containsKey("col1")); assertEquals(newAliasMap.get("col1").getName(), "col1"); assertEquals(newAliasMap.get("col1").isPrimaryKey(), true); assertTrue(newAliasMap.containsKey("col2")); assertEquals(newAliasMap.get("col2").getName(), "col2"); assertEquals(newAliasMap.get("col2").isPrimaryKey(), false); assertTrue(newAliasMap.containsKey("col3")); assertEquals(newAliasMap.get("col3").getName(), "col3"); assertEquals(newAliasMap.get("col3").isPrimaryKey(), false); assertTrue(newAliasMap.containsKey("f1")); assertEquals(newAliasMap.get("f1").getName(), "col3"); assertEquals(newAliasMap.get("f1").isPrimaryKey(), false); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void returnAllFieldsAndApplyMappings() { Schema schema = SchemaBuilder.struct().name("com.example.Person") .field("firstName", Schema.STRING_SCHEMA) .field("lastName", Schema.STRING_SCHEMA) .field("age", Schema.INT32_SCHEMA) .field("threshold", Schema.OPTIONAL_FLOAT64_SCHEMA).build(); double threshold = 215.66612; Struct struct = new Struct(schema) .put("firstName", "Alex") .put("lastName", "Smith") .put("age", 30) .put("threshold", threshold); Map<String, FieldAlias> mappings = Maps.newHashMap(); mappings.put("lastName", new FieldAlias("Name")); mappings.put("age", new FieldAlias("a")); FieldsMappings tm = new FieldsMappings("table", "topic", true, mappings); StructFieldsDataExtractor dataExtractor = new StructFieldsDataExtractor(tm); StructFieldsDataExtractor.PreparedStatementBinders binders = dataExtractor.get(struct, new SinkRecord("", 1, null, null, schema, struct, 0)); HashMap<String, PreparedStatementBinder> map = new HashMap<>(); for (PreparedStatementBinder p : Iterables.concat(binders.getKeyColumns(), binders.getNonKeyColumns())) map.put(p.getFieldName(), p); assertTrue(!binders.isEmpty()); assertEquals(binders.getKeyColumns().size() + binders.getNonKeyColumns().size(), 4); assertTrue(map.containsKey("firstName")); assertTrue(map.get("firstName").getClass() == StringPreparedStatementBinder.class); assertEquals(((StringPreparedStatementBinder) map.get("firstName")).getValue(), "Alex"); assertTrue(map.containsKey("Name")); assertTrue(map.get("Name").getClass() == StringPreparedStatementBinder.class); assertEquals(((StringPreparedStatementBinder) map.get("Name")).getValue(), "Smith"); assertTrue(map.containsKey("a")); assertTrue(map.get("a").getClass() == IntPreparedStatementBinder.class); assertEquals(((IntPreparedStatementBinder) map.get("a")).getValue(), 30); assertTrue(map.containsKey("threshold")); assertTrue(map.get("threshold").getClass() == DoublePreparedStatementBinder.class); assertTrue(Double.compare(((DoublePreparedStatementBinder) map.get("threshold")).getValue(), threshold) == 0); } #location 33 #vulnerability type NULL_DEREFERENCE
#fixed code @Test public void returnAllFieldsAndApplyMappings() { Schema schema = SchemaBuilder.struct().name("com.example.Person") .field("firstName", Schema.STRING_SCHEMA) .field("lastName", Schema.STRING_SCHEMA) .field("age", Schema.INT32_SCHEMA) .field("threshold", Schema.OPTIONAL_FLOAT64_SCHEMA).build(); double threshold = 215.66612; Struct struct = new Struct(schema) .put("firstName", "Alex") .put("lastName", "Smith") .put("age", 30) .put("threshold", threshold); Map<String, FieldAlias> mappings = Maps.newHashMap(); mappings.put("lastName", new FieldAlias("Name")); mappings.put("age", new FieldAlias("a")); FieldsMappings tm = new FieldsMappings("table", "topic", true, mappings); StructFieldsDataExtractor dataExtractor = new StructFieldsDataExtractor(tm); List<PreparedStatementBinder> binders = dataExtractor.get(struct, new SinkRecord("", 1, null, null, schema, struct, 0)); HashMap<String, PreparedStatementBinder> map = new HashMap<>(); for (PreparedStatementBinder p : binders) map.put(p.getFieldName(), p); assertTrue(!binders.isEmpty()); assertEquals(binders.size(), 4); assertTrue(map.containsKey("firstName")); assertTrue(map.get("firstName").getClass() == StringPreparedStatementBinder.class); assertEquals(((StringPreparedStatementBinder) map.get("firstName")).getValue(), "Alex"); assertTrue(map.containsKey("Name")); assertTrue(map.get("Name").getClass() == StringPreparedStatementBinder.class); assertEquals(((StringPreparedStatementBinder) map.get("Name")).getValue(), "Smith"); assertTrue(map.containsKey("a")); assertTrue(map.get("a").getClass() == IntPreparedStatementBinder.class); assertEquals(((IntPreparedStatementBinder) map.get("a")).getValue(), 30); assertTrue(map.containsKey("threshold")); assertTrue(map.get("threshold").getClass() == DoublePreparedStatementBinder.class); assertTrue(Double.compare(((DoublePreparedStatementBinder) map.get("threshold")).getValue(), threshold) == 0); }
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) .field("age", Schema.INT32_SCHEMA) .field("bool", Schema.BOOLEAN_SCHEMA) .field("short", Schema.INT16_SCHEMA) .field("byte", Schema.INT8_SCHEMA) .field("long", Schema.INT64_SCHEMA) .field("float", Schema.FLOAT32_SCHEMA) .field("double", Schema.FLOAT64_SCHEMA) .field("bytes", Schema.BYTES_SCHEMA) .field("threshold", Schema.OPTIONAL_FLOAT64_SCHEMA).build(); short s = 1234; byte b = -32; long l = 12425436; float f = (float) 2356.3; double d = -2436546.56457; byte[] bs = new byte[]{-32, 124}; Struct struct = new Struct(schema) .put("firstName", "Alex") .put("lastName", "Smith") .put("bool", true) .put("short", s) .put("byte", b) .put("long", l) .put("float", f) .put("double", d) .put("bytes", bs) .put("age", 30); Map<String, FieldAlias> mappings = new HashMap<>(); mappings.put("firstName", new FieldAlias("fName", true)); mappings.put("lastName", new FieldAlias("lName", true)); FieldsMappings tm = new FieldsMappings("table", "topic", true, mappings); StructFieldsDataExtractor dataExtractor = new StructFieldsDataExtractor(tm); StructFieldsDataExtractor.PreparedStatementBinders binders = dataExtractor.get(struct, new SinkRecord("", 1, null, null, schema, struct, 0)); HashMap<String, PreparedStatementBinder> map = new HashMap<>(); for (PreparedStatementBinder p : Iterables.concat(binders.getNonKeyColumns(), binders.getKeyColumns())) map.put(p.getFieldName(), p); assertTrue(!binders.isEmpty()); assertEquals(binders.getNonKeyColumns().size() + binders.getKeyColumns().size(), 10); List<PreparedStatementBinder> pkBinders = binders.getKeyColumns(); assertEquals(pkBinders.size(), 2); assertTrue(Objects.equals(pkBinders.get(0).getFieldName(), "fName") || Objects.equals(pkBinders.get(1).getFieldName(), "fName") ); assertTrue(Objects.equals(pkBinders.get(0).getFieldName(), "lName") || Objects.equals(pkBinders.get(1).getFieldName(), "lName") ); assertTrue(map.containsKey("fName")); assertTrue(map.get("fName").getClass() == StringPreparedStatementBinder.class); assertTrue(map.containsKey("lName")); assertTrue(map.get("lName").getClass() == StringPreparedStatementBinder.class); assertTrue(map.containsKey("age")); assertTrue(map.get("age").getClass() == IntPreparedStatementBinder.class); assertTrue(map.get("long").getClass() == LongPreparedStatementBinder.class); assertEquals(((LongPreparedStatementBinder) map.get("long")).getValue(), l); assertTrue(map.get("short").getClass() == ShortPreparedStatementBinder.class); assertEquals(((ShortPreparedStatementBinder) map.get("short")).getValue(), s); assertTrue(map.get("byte").getClass() == BytePreparedStatementBinder.class); assertEquals(((BytePreparedStatementBinder) map.get("byte")).getValue(), b); assertTrue(map.get("float").getClass() == FloatPreparedStatementBinder.class); assertEquals(Float.compare(((FloatPreparedStatementBinder) map.get("float")).getValue(), f), 0); assertTrue(map.get("double").getClass() == DoublePreparedStatementBinder.class); assertEquals(Double.compare(((DoublePreparedStatementBinder) map.get("double")).getValue(), d), 0); assertTrue(map.get("bytes").getClass() == BytesPreparedStatementBinder.class); assertTrue(Arrays.equals(bs, ((BytesPreparedStatementBinder) map.get("bytes")).getValue())); } #location 49 #vulnerability type NULL_DEREFERENCE
#fixed code @Test public void shouldReturnThePrimaryKeysAtTheEndWhenMultipleFieldsFormThePrimaryKey() { Schema schema = SchemaBuilder.struct().name("com.example.Person") .field("firstName", Schema.STRING_SCHEMA) .field("lastName", Schema.STRING_SCHEMA) .field("age", Schema.INT32_SCHEMA) .field("bool", Schema.BOOLEAN_SCHEMA) .field("short", Schema.INT16_SCHEMA) .field("byte", Schema.INT8_SCHEMA) .field("long", Schema.INT64_SCHEMA) .field("float", Schema.FLOAT32_SCHEMA) .field("double", Schema.FLOAT64_SCHEMA) .field("bytes", Schema.BYTES_SCHEMA) .field("threshold", Schema.OPTIONAL_FLOAT64_SCHEMA).build(); short s = 1234; byte b = -32; long l = 12425436; float f = (float) 2356.3; double d = -2436546.56457; byte[] bs = new byte[]{-32, 124}; Struct struct = new Struct(schema) .put("firstName", "Alex") .put("lastName", "Smith") .put("bool", true) .put("short", s) .put("byte", b) .put("long", l) .put("float", f) .put("double", d) .put("bytes", bs) .put("age", 30); Map<String, FieldAlias> mappings = new HashMap<>(); mappings.put("firstName", new FieldAlias("fName", true)); mappings.put("lastName", new FieldAlias("lName", true)); FieldsMappings tm = new FieldsMappings("table", "topic", true, mappings); StructFieldsDataExtractor dataExtractor = new StructFieldsDataExtractor(tm); List<PreparedStatementBinder> binders = dataExtractor.get(struct, new SinkRecord("", 1, null, null, schema, struct, 0)); HashMap<String, PreparedStatementBinder> map = new HashMap<>(); List<PreparedStatementBinder> pkBinders = new LinkedList<>(); for (PreparedStatementBinder p : binders) { if (p.isPrimaryKey()) { pkBinders.add(p); } map.put(p.getFieldName(), p); } assertTrue(!binders.isEmpty()); assertEquals(binders.size(), 10); assertEquals(pkBinders.size(), 2); assertTrue(Objects.equals(pkBinders.get(0).getFieldName(), "fName") || Objects.equals(pkBinders.get(1).getFieldName(), "fName") ); assertTrue(Objects.equals(pkBinders.get(0).getFieldName(), "lName") || Objects.equals(pkBinders.get(1).getFieldName(), "lName") ); assertTrue(map.containsKey("fName")); assertTrue(map.get("fName").getClass() == StringPreparedStatementBinder.class); assertTrue(map.containsKey("lName")); assertTrue(map.get("lName").getClass() == StringPreparedStatementBinder.class); assertTrue(map.containsKey("age")); assertTrue(map.get("age").getClass() == IntPreparedStatementBinder.class); assertTrue(map.get("long").getClass() == LongPreparedStatementBinder.class); assertEquals(((LongPreparedStatementBinder) map.get("long")).getValue(), l); assertTrue(map.get("short").getClass() == ShortPreparedStatementBinder.class); assertEquals(((ShortPreparedStatementBinder) map.get("short")).getValue(), s); assertTrue(map.get("byte").getClass() == BytePreparedStatementBinder.class); assertEquals(((BytePreparedStatementBinder) map.get("byte")).getValue(), b); assertTrue(map.get("float").getClass() == FloatPreparedStatementBinder.class); assertEquals(Float.compare(((FloatPreparedStatementBinder) map.get("float")).getValue(), f), 0); assertTrue(map.get("double").getClass() == DoublePreparedStatementBinder.class); assertEquals(Double.compare(((DoublePreparedStatementBinder) map.get("double")).getValue(), d), 0); assertTrue(map.get("bytes").getClass() == BytesPreparedStatementBinder.class); assertTrue(Arrays.equals(bs, ((BytesPreparedStatementBinder) map.get("bytes")).getValue())); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void returnAllFieldsAndTheirBytesValue() { Schema schema = SchemaBuilder.struct().name("com.example.Person") .field("firstName", Schema.STRING_SCHEMA) .field("lastName", Schema.STRING_SCHEMA) .field("age", Schema.INT32_SCHEMA) .field("bool", Schema.BOOLEAN_SCHEMA) .field("short", Schema.INT16_SCHEMA) .field("byte", Schema.INT8_SCHEMA) .field("long", Schema.INT64_SCHEMA) .field("float", Schema.FLOAT32_SCHEMA) .field("double", Schema.FLOAT64_SCHEMA) .field("bytes", Schema.BYTES_SCHEMA) .field("threshold", Schema.OPTIONAL_FLOAT64_SCHEMA).build(); short s = 1234; byte b = -32; long l = 12425436; float f = (float) 2356.3; double d = -2436546.56457; byte[] bs = new byte[]{-32, 124}; Struct struct = new Struct(schema) .put("firstName", "Alex") .put("lastName", "Smith") .put("bool", true) .put("short", s) .put("byte", b) .put("long", l) .put("float", f) .put("double", d) .put("bytes", bs) .put("age", 30); FieldsMappings tm = new FieldsMappings("table", "topic", true, new HashMap<String, FieldAlias>()); StructFieldsDataExtractor dataExtractor = new StructFieldsDataExtractor(tm); StructFieldsDataExtractor.PreparedStatementBinders binders = dataExtractor.get(struct, new SinkRecord("", 1, null, null, schema, struct, 0)); HashMap<String, PreparedStatementBinder> map = new HashMap<>(); for (PreparedStatementBinder p : Iterables.concat(binders.getNonKeyColumns(), binders.getKeyColumns())) map.put(p.getFieldName(), p); assertTrue(!binders.isEmpty()); assertEquals(binders.getKeyColumns().size() + binders.getNonKeyColumns().size(), 10); assertTrue(map.containsKey("firstName")); assertTrue(map.get("firstName").getClass() == StringPreparedStatementBinder.class); assertTrue(map.containsKey("lastName")); assertTrue(map.get("lastName").getClass() == StringPreparedStatementBinder.class); assertTrue(map.containsKey("age")); assertTrue(map.get("age").getClass() == IntPreparedStatementBinder.class); assertTrue(map.get("long").getClass() == LongPreparedStatementBinder.class); assertEquals(((LongPreparedStatementBinder) map.get("long")).getValue(), l); assertTrue(map.get("short").getClass() == ShortPreparedStatementBinder.class); assertEquals(((ShortPreparedStatementBinder) map.get("short")).getValue(), s); assertTrue(map.get("byte").getClass() == BytePreparedStatementBinder.class); assertEquals(((BytePreparedStatementBinder) map.get("byte")).getValue(), b); assertTrue(map.get("float").getClass() == FloatPreparedStatementBinder.class); assertEquals(Float.compare(((FloatPreparedStatementBinder) map.get("float")).getValue(), f), 0); assertTrue(map.get("double").getClass() == DoublePreparedStatementBinder.class); assertEquals(Double.compare(((DoublePreparedStatementBinder) map.get("double")).getValue(), d), 0); assertTrue(map.get("bytes").getClass() == BytesPreparedStatementBinder.class); assertTrue(Arrays.equals(bs, ((BytesPreparedStatementBinder) map.get("bytes")).getValue())); } #location 45 #vulnerability type NULL_DEREFERENCE
#fixed code @Test public void returnAllFieldsAndTheirBytesValue() { Schema schema = SchemaBuilder.struct().name("com.example.Person") .field("firstName", Schema.STRING_SCHEMA) .field("lastName", Schema.STRING_SCHEMA) .field("age", Schema.INT32_SCHEMA) .field("bool", Schema.BOOLEAN_SCHEMA) .field("short", Schema.INT16_SCHEMA) .field("byte", Schema.INT8_SCHEMA) .field("long", Schema.INT64_SCHEMA) .field("float", Schema.FLOAT32_SCHEMA) .field("double", Schema.FLOAT64_SCHEMA) .field("bytes", Schema.BYTES_SCHEMA) .field("threshold", Schema.OPTIONAL_FLOAT64_SCHEMA).build(); short s = 1234; byte b = -32; long l = 12425436; float f = (float) 2356.3; double d = -2436546.56457; byte[] bs = new byte[]{-32, 124}; Struct struct = new Struct(schema) .put("firstName", "Alex") .put("lastName", "Smith") .put("bool", true) .put("short", s) .put("byte", b) .put("long", l) .put("float", f) .put("double", d) .put("bytes", bs) .put("age", 30); FieldsMappings tm = new FieldsMappings("table", "topic", true, new HashMap<String, FieldAlias>()); StructFieldsDataExtractor dataExtractor = new StructFieldsDataExtractor(tm); List<PreparedStatementBinder> binders = dataExtractor.get(struct, new SinkRecord("", 1, null, null, schema, struct, 0)); HashMap<String, PreparedStatementBinder> map = new HashMap<>(); for (PreparedStatementBinder p : binders) map.put(p.getFieldName(), p); assertTrue(!binders.isEmpty()); assertEquals(binders.size(), 10); assertTrue(map.containsKey("firstName")); assertTrue(map.get("firstName").getClass() == StringPreparedStatementBinder.class); assertTrue(map.containsKey("lastName")); assertTrue(map.get("lastName").getClass() == StringPreparedStatementBinder.class); assertTrue(map.containsKey("age")); assertTrue(map.get("age").getClass() == IntPreparedStatementBinder.class); assertTrue(map.get("long").getClass() == LongPreparedStatementBinder.class); assertEquals(((LongPreparedStatementBinder) map.get("long")).getValue(), l); assertTrue(map.get("short").getClass() == ShortPreparedStatementBinder.class); assertEquals(((ShortPreparedStatementBinder) map.get("short")).getValue(), s); assertTrue(map.get("byte").getClass() == BytePreparedStatementBinder.class); assertEquals(((BytePreparedStatementBinder) map.get("byte")).getValue(), b); assertTrue(map.get("float").getClass() == FloatPreparedStatementBinder.class); assertEquals(Float.compare(((FloatPreparedStatementBinder) map.get("float")).getValue(), f), 0); assertTrue(map.get("double").getClass() == DoublePreparedStatementBinder.class); assertEquals(Double.compare(((DoublePreparedStatementBinder) map.get("double")).getValue(), d), 0); assertTrue(map.get("bytes").getClass() == BytesPreparedStatementBinder.class); assertTrue(Arrays.equals(bs, ((BytesPreparedStatementBinder) map.get("bytes")).getValue())); }
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, false, 1)); DbTable table = new DbTable("tableA", columns); Map<String, FieldAlias> aliasMap = new HashMap<>(); aliasMap.put("f1", new FieldAlias("col3")); FieldsMappings mappings = new FieldsMappings("tableA", "topic1", true, aliasMap); FieldsMappings newMappings = PreparedStatementBuilderHelper.validateAndMerge(mappings, table); assertEquals(newMappings.getTableName(), mappings.getTableName()); assertEquals(newMappings.getIncomingTopic(), mappings.getIncomingTopic()); assertEquals(newMappings.areAllFieldsIncluded(), false); Map<String, FieldAlias> newAliasMap = newMappings.getMappings(); assertEquals(4, newAliasMap.size()); //+ the specific mapping assertTrue(newAliasMap.containsKey("col1")); assertEquals(newAliasMap.get("col1").getName(), "col1"); assertEquals(newAliasMap.get("col1").isPrimaryKey(), true); assertTrue(newAliasMap.containsKey("col2")); assertEquals(newAliasMap.get("col2").getName(), "col2"); assertEquals(newAliasMap.get("col2").isPrimaryKey(), false); assertTrue(newAliasMap.containsKey("col3")); assertEquals(newAliasMap.get("col3").getName(), "col3"); assertEquals(newAliasMap.get("col3").isPrimaryKey(), false); assertTrue(newAliasMap.containsKey("f1")); assertEquals(newAliasMap.get("f1").getName(), "col3"); assertEquals(newAliasMap.get("f1").isPrimaryKey(), false); } #location 21 #vulnerability type NULL_DEREFERENCE
#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, false, 1)); DbTable table = new DbTable("tableA", columns); Map<String, FieldAlias> aliasMap = new HashMap<>(); aliasMap.put("f1", new FieldAlias("col3")); FieldsMappings mappings = new FieldsMappings("tableA", "topic1", true, aliasMap); FieldsMappings newMappings = PreparedStatementBuilderHelper.validateAndMerge(mappings, table, InsertModeEnum.INSERT); assertEquals(newMappings.getTableName(), mappings.getTableName()); assertEquals(newMappings.getIncomingTopic(), mappings.getIncomingTopic()); assertEquals(newMappings.areAllFieldsIncluded(), false); Map<String, FieldAlias> newAliasMap = newMappings.getMappings(); assertEquals(4, newAliasMap.size()); //+ the specific mapping assertTrue(newAliasMap.containsKey("col1")); assertEquals(newAliasMap.get("col1").getName(), "col1"); assertEquals(newAliasMap.get("col1").isPrimaryKey(), true); assertTrue(newAliasMap.containsKey("col2")); assertEquals(newAliasMap.get("col2").getName(), "col2"); assertEquals(newAliasMap.get("col2").isPrimaryKey(), false); assertTrue(newAliasMap.containsKey("col3")); assertEquals(newAliasMap.get("col3").getName(), "col3"); assertEquals(newAliasMap.get("col3").isPrimaryKey(), false); assertTrue(newAliasMap.containsKey("f1")); assertEquals(newAliasMap.get("f1").getName(), "col3"); assertEquals(newAliasMap.get("f1").isPrimaryKey(), false); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void returnAllFieldsAndApplyMappings() { Schema schema = SchemaBuilder.struct().name("com.example.Person") .field("firstName", Schema.STRING_SCHEMA) .field("lastName", Schema.STRING_SCHEMA) .field("age", Schema.INT32_SCHEMA) .field("threshold", Schema.OPTIONAL_FLOAT64_SCHEMA).build(); double threshold = 215.66612; Struct struct = new Struct(schema) .put("firstName", "Alex") .put("lastName", "Smith") .put("age", 30) .put("threshold", threshold); Map<String, FieldAlias> mappings = Maps.newHashMap(); mappings.put("lastName", new FieldAlias("Name")); mappings.put("age", new FieldAlias("a")); FieldsMappings tm = new FieldsMappings("table", "topic", true, mappings); StructFieldsDataExtractor dataExtractor = new StructFieldsDataExtractor(tm); StructFieldsDataExtractor.PreparedStatementBinders binders = dataExtractor.get(struct, new SinkRecord("", 1, null, null, schema, struct, 0)); HashMap<String, PreparedStatementBinder> map = new HashMap<>(); for (PreparedStatementBinder p : Iterables.concat(binders.getKeyColumns(), binders.getNonKeyColumns())) map.put(p.getFieldName(), p); assertTrue(!binders.isEmpty()); assertEquals(binders.getKeyColumns().size() + binders.getNonKeyColumns().size(), 4); assertTrue(map.containsKey("firstName")); assertTrue(map.get("firstName").getClass() == StringPreparedStatementBinder.class); assertEquals(((StringPreparedStatementBinder) map.get("firstName")).getValue(), "Alex"); assertTrue(map.containsKey("Name")); assertTrue(map.get("Name").getClass() == StringPreparedStatementBinder.class); assertEquals(((StringPreparedStatementBinder) map.get("Name")).getValue(), "Smith"); assertTrue(map.containsKey("a")); assertTrue(map.get("a").getClass() == IntPreparedStatementBinder.class); assertEquals(((IntPreparedStatementBinder) map.get("a")).getValue(), 30); assertTrue(map.containsKey("threshold")); assertTrue(map.get("threshold").getClass() == DoublePreparedStatementBinder.class); assertTrue(Double.compare(((DoublePreparedStatementBinder) map.get("threshold")).getValue(), threshold) == 0); } #location 33 #vulnerability type NULL_DEREFERENCE
#fixed code @Test public void returnAllFieldsAndApplyMappings() { Schema schema = SchemaBuilder.struct().name("com.example.Person") .field("firstName", Schema.STRING_SCHEMA) .field("lastName", Schema.STRING_SCHEMA) .field("age", Schema.INT32_SCHEMA) .field("threshold", Schema.OPTIONAL_FLOAT64_SCHEMA).build(); double threshold = 215.66612; Struct struct = new Struct(schema) .put("firstName", "Alex") .put("lastName", "Smith") .put("age", 30) .put("threshold", threshold); Map<String, FieldAlias> mappings = Maps.newHashMap(); mappings.put("lastName", new FieldAlias("Name")); mappings.put("age", new FieldAlias("a")); FieldsMappings tm = new FieldsMappings("table", "topic", true, mappings); StructFieldsDataExtractor dataExtractor = new StructFieldsDataExtractor(tm); List<PreparedStatementBinder> binders = dataExtractor.get(struct, new SinkRecord("", 1, null, null, schema, struct, 0)); HashMap<String, PreparedStatementBinder> map = new HashMap<>(); for (PreparedStatementBinder p : binders) map.put(p.getFieldName(), p); assertTrue(!binders.isEmpty()); assertEquals(binders.size(), 4); assertTrue(map.containsKey("firstName")); assertTrue(map.get("firstName").getClass() == StringPreparedStatementBinder.class); assertEquals(((StringPreparedStatementBinder) map.get("firstName")).getValue(), "Alex"); assertTrue(map.containsKey("Name")); assertTrue(map.get("Name").getClass() == StringPreparedStatementBinder.class); assertEquals(((StringPreparedStatementBinder) map.get("Name")).getValue(), "Smith"); assertTrue(map.containsKey("a")); assertTrue(map.get("a").getClass() == IntPreparedStatementBinder.class); assertEquals(((IntPreparedStatementBinder) map.get("a")).getValue(), 30); assertTrue(map.containsKey("threshold")); assertTrue(map.get("threshold").getClass() == DoublePreparedStatementBinder.class); assertTrue(Double.compare(((DoublePreparedStatementBinder) map.get("threshold")).getValue(), threshold) == 0); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void handleAllFieldsMappingSetting() { List<DbTableColumn> columns = Lists.newArrayList( new DbTableColumn("col1", true, false, 1), new DbTableColumn("col2", false, false, 1), new DbTableColumn("col3", false, false, 1)); DbTable table = new DbTable("tableA", columns); Map<String, FieldAlias> aliasMap = new HashMap<>(); FieldsMappings mappings = new FieldsMappings("tableA", "topic1", true, aliasMap); FieldsMappings newMappings = PreparedStatementBuilderHelper.validateAndMerge(mappings, table); assertEquals(newMappings.getTableName(), mappings.getTableName()); assertEquals(newMappings.getIncomingTopic(), mappings.getIncomingTopic()); assertEquals(newMappings.areAllFieldsIncluded(), false); Map<String, FieldAlias> newAliasMap = newMappings.getMappings(); assertEquals(3, newAliasMap.size()); assertTrue(newAliasMap.containsKey("col1")); assertEquals(newAliasMap.get("col1").getName(), "col1"); assertEquals(newAliasMap.get("col1").isPrimaryKey(), true); assertTrue(newAliasMap.containsKey("col2")); assertEquals(newAliasMap.get("col2").getName(), "col2"); assertEquals(newAliasMap.get("col2").isPrimaryKey(), false); assertTrue(newAliasMap.containsKey("col3")); assertEquals(newAliasMap.get("col3").getName(), "col3"); assertEquals(newAliasMap.get("col3").isPrimaryKey(), false); } #location 29 #vulnerability type NULL_DEREFERENCE
#fixed code @Test public void handleAllFieldsMappingSetting() { List<DbTableColumn> columns = Lists.newArrayList( new DbTableColumn("col1", true, false, 1), new DbTableColumn("col2", false, false, 1), new DbTableColumn("col3", false, false, 1)); DbTable table = new DbTable("tableA", columns); Map<String, FieldAlias> aliasMap = new HashMap<>(); FieldsMappings mappings = new FieldsMappings("tableA", "topic1", true, aliasMap); FieldsMappings newMappings = PreparedStatementBuilderHelper.validateAndMerge(mappings, table, InsertModeEnum.INSERT); assertEquals(newMappings.getTableName(), mappings.getTableName()); assertEquals(newMappings.getIncomingTopic(), mappings.getIncomingTopic()); assertEquals(newMappings.areAllFieldsIncluded(), false); Map<String, FieldAlias> newAliasMap = newMappings.getMappings(); assertEquals(3, newAliasMap.size()); assertTrue(newAliasMap.containsKey("col1")); assertEquals(newAliasMap.get("col1").getName(), "col1"); assertEquals(newAliasMap.get("col1").isPrimaryKey(), true); assertTrue(newAliasMap.containsKey("col2")); assertEquals(newAliasMap.get("col2").getName(), "col2"); assertEquals(newAliasMap.get("col2").isPrimaryKey(), false); assertTrue(newAliasMap.containsKey("col3")); assertEquals(newAliasMap.get("col3").getName(), "col3"); assertEquals(newAliasMap.get("col3").isPrimaryKey(), false); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test(expected = ConfigException.class) public void throwAnExceptionWhenForANewTableToCreateWhichDoesNotAllowAutoCreation() throws SQLException { Database changesExecutor = new Database(new HashSet<String>(), new HashSet<String>(), new DatabaseMetadata(null, new ArrayList<DbTable>()), DbDialect.fromConnectionString(SQL_LITE_URI), 2); String tableName = "tableA"; Map<String, Collection<SinkRecordField>> map = new HashMap<>(); map.put(tableName, Lists.newArrayList( new SinkRecordField(Schema.Type.INT32, "col1", true), new SinkRecordField(Schema.Type.STRING, "col2", false), new SinkRecordField(Schema.Type.INT8, "col3", false), new SinkRecordField(Schema.Type.INT64, "col3", false), new SinkRecordField(Schema.Type.FLOAT64, "col4", false) )); Connection connection = null; try { connection = connectionProvider.getConnection(); changesExecutor.update(map, connection); } finally { AutoCloseableHelper.close(connection); } } #location 24 #vulnerability type NULL_DEREFERENCE
#fixed code @Test(expected = ConfigException.class) public void throwAnExceptionWhenForANewTableToCreateWhichDoesNotAllowAutoCreation() throws SQLException { Database changesExecutor = new Database(new HashSet<String>(), new HashSet<String>(), new DatabaseMetadata(null, new ArrayList<DbTable>()), DbDialect.fromConnectionString(SQL_LITE_URI), 2); String tableName = "tableA"; Map<String, Collection<SinkRecordField>> map = new HashMap<>(); map.put(tableName, Lists.newArrayList( new SinkRecordField(Schema.Type.INT32, "col1", true), new SinkRecordField(Schema.Type.STRING, "col2", false), new SinkRecordField(Schema.Type.INT8, "col3", false), new SinkRecordField(Schema.Type.INT64, "col3", false), new SinkRecordField(Schema.Type.FLOAT64, "col4", false) )); try (Connection connection = connectionProvider.getConnection()) { changesExecutor.update(map, connection); } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void handleAllFieldsIncludedAndAnExistingMapping() { List<DbTableColumn> columns = Lists.newArrayList( new DbTableColumn("col1", true, false, 1), new DbTableColumn("col2", false, false, 1), new DbTableColumn("col3", false, false, 1)); DbTable table = new DbTable("tableA", columns); Map<String, FieldAlias> aliasMap = new HashMap<>(); aliasMap.put("col3", new FieldAlias("col3", true)); FieldsMappings mappings = new FieldsMappings("tableA", "topic1", true, aliasMap); FieldsMappings newMappings = PreparedStatementBuilderHelper.validateAndMerge(mappings, table); assertEquals(newMappings.getTableName(), mappings.getTableName()); assertEquals(newMappings.getIncomingTopic(), mappings.getIncomingTopic()); assertEquals(newMappings.areAllFieldsIncluded(), false); Map<String, FieldAlias> newAliasMap = newMappings.getMappings(); assertEquals(3, newAliasMap.size()); //+ the specific mapping assertTrue(newAliasMap.containsKey("col1")); assertEquals(newAliasMap.get("col1").getName(), "col1"); assertEquals(newAliasMap.get("col1").isPrimaryKey(), true); assertTrue(newAliasMap.containsKey("col2")); assertEquals(newAliasMap.get("col2").getName(), "col2"); assertEquals(newAliasMap.get("col2").isPrimaryKey(), false); assertTrue(newAliasMap.containsKey("col3")); assertEquals(newAliasMap.get("col3").getName(), "col3"); assertEquals(newAliasMap.get("col3").isPrimaryKey(), false); } #location 21 #vulnerability type NULL_DEREFERENCE
#fixed code @Test public void handleAllFieldsIncludedAndAnExistingMapping() { List<DbTableColumn> columns = Lists.newArrayList( new DbTableColumn("col1", true, false, 1), new DbTableColumn("col2", false, false, 1), new DbTableColumn("col3", false, false, 1)); DbTable table = new DbTable("tableA", columns); Map<String, FieldAlias> aliasMap = new HashMap<>(); aliasMap.put("col3", new FieldAlias("col3", true)); FieldsMappings mappings = new FieldsMappings("tableA", "topic1", true, aliasMap); FieldsMappings newMappings = PreparedStatementBuilderHelper.validateAndMerge(mappings, table, InsertModeEnum.INSERT); assertEquals(newMappings.getTableName(), mappings.getTableName()); assertEquals(newMappings.getIncomingTopic(), mappings.getIncomingTopic()); assertEquals(newMappings.areAllFieldsIncluded(), false); Map<String, FieldAlias> newAliasMap = newMappings.getMappings(); assertEquals(3, newAliasMap.size()); //+ the specific mapping assertTrue(newAliasMap.containsKey("col1")); assertEquals(newAliasMap.get("col1").getName(), "col1"); assertEquals(newAliasMap.get("col1").isPrimaryKey(), true); assertTrue(newAliasMap.containsKey("col2")); assertEquals(newAliasMap.get("col2").getName(), "col2"); assertEquals(newAliasMap.get("col2").isPrimaryKey(), false); assertTrue(newAliasMap.containsKey("col3")); assertEquals(newAliasMap.get("col3").getName(), "col3"); assertEquals(newAliasMap.get("col3").isPrimaryKey(), false); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void handleBatchedStatementPerRecordInsertingSameRecord100Times() throws SQLException { String tableName = "batched_statement_test_100"; String createTable = "CREATE TABLE " + tableName + " (" + " firstName TEXT," + " lastName TEXT," + " age INTEGER," + " bool NUMERIC," + " byte INTEGER," + " short INTEGER," + " long INTEGER," + " float NUMERIC," + " double NUMERIC," + " bytes BLOB " + ");"; SqlLiteHelper.deleteTable(SQL_LITE_URI, tableName); SqlLiteHelper.createTable(SQL_LITE_URI, createTable); Schema schema = SchemaBuilder.struct().name("com.example.Person") .field("firstName", Schema.OPTIONAL_STRING_SCHEMA) .field("lastName", Schema.OPTIONAL_STRING_SCHEMA) .field("age", Schema.OPTIONAL_INT32_SCHEMA) .field("bool", Schema.OPTIONAL_BOOLEAN_SCHEMA) .field("short", Schema.OPTIONAL_INT16_SCHEMA) .field("byte", Schema.OPTIONAL_INT8_SCHEMA) .field("long", Schema.OPTIONAL_INT64_SCHEMA) .field("float", Schema.OPTIONAL_FLOAT32_SCHEMA) .field("double", Schema.OPTIONAL_FLOAT64_SCHEMA) .field("bytes", Schema.OPTIONAL_BYTES_SCHEMA); final String fName1 = "Alex"; final String lName1 = "Smith"; final int age1 = 21; final boolean bool1 = true; final short s1 = 1234; final byte b1 = -32; final long l1 = 12425436; final float f1 = (float) 2356.3; final double d1 = -2436546.56457; final byte[] bs1 = new byte[]{-32, 124}; Struct struct1 = new Struct(schema) .put("firstName", fName1) .put("lastName", lName1) .put("bool", bool1) .put("short", s1) .put("byte", b1) .put("long", l1) .put("float", f1) .put("double", d1) .put("bytes", bs1) .put("age", age1); String topic = "topic"; int partition = 2; Collection<SinkRecord> records = Collections.nCopies( 100, new SinkRecord(topic, partition, null, null, schema, struct1, 1)); Map<String, StructFieldsDataExtractor> map = new HashMap<>(); map.put(topic.toLowerCase(), new StructFieldsDataExtractor(new FieldsMappings(tableName, topic, true, new HashMap<String, FieldAlias>()))); List<DbTable> dbTables = Lists.newArrayList( new DbTable(tableName, Lists.<DbTableColumn>newArrayList( new DbTableColumn("firstName", true, false, 1), new DbTableColumn("lastName", true, false, 1), new DbTableColumn("age", false, false, 1), new DbTableColumn("bool", true, false, 1), new DbTableColumn("byte", true, false, 1), new DbTableColumn("short", true, false, 1), new DbTableColumn("long", true, false, 1), new DbTableColumn("float", true, false, 1), new DbTableColumn("double", true, false, 1), new DbTableColumn("BLOB", true, false, 1) ))); DatabaseMetadata dbMetadata = new DatabaseMetadata(null, dbTables); HikariDataSource ds = HikariHelper.from(SQL_LITE_URI, null, null); DatabaseChangesExecutor executor = new DatabaseChangesExecutor( ds, Sets.<String>newHashSet(), Sets.<String>newHashSet(), dbMetadata, new SQLiteDialect(), 1); JdbcDbWriter writer = new JdbcDbWriter(ds, new BatchedPreparedStatementBuilder(map, new InsertQueryBuilder()), new ThrowErrorHandlingPolicy(), executor, 10); writer.write(records); String query = "SELECT * FROM " + tableName + " ORDER BY firstName"; SqlLiteHelper.ResultSetReadCallback callback = new SqlLiteHelper.ResultSetReadCallback() { int index = 0; @Override public void read(ResultSet rs) throws SQLException { if (index < 100) { assertEquals(rs.getString("firstName"), fName1); assertEquals(rs.getString("lastName"), lName1); assertEquals(rs.getBoolean("bool"), bool1); assertEquals(rs.getShort("short"), s1); assertEquals(rs.getByte("byte"), b1); assertEquals(rs.getLong("long"), l1); assertEquals(Float.compare(rs.getFloat("float"), f1), 0); assertEquals(Double.compare(rs.getDouble("double"), d1), 0); assertTrue(Arrays.equals(rs.getBytes("bytes"), bs1)); assertEquals(rs.getInt("age"), age1); } else throw new RuntimeException(String.format("%d is too high", index)); index++; } }; SqlLiteHelper.select(SQL_LITE_URI, query, callback); } #location 94 #vulnerability type RESOURCE_LEAK
#fixed code @Test public void handleBatchedStatementPerRecordInsertingSameRecord100Times() throws SQLException { String tableName = "batched_statement_test_100"; String createTable = "CREATE TABLE " + tableName + " (" + " firstName TEXT," + " lastName TEXT," + " age INTEGER," + " bool NUMERIC," + " byte INTEGER," + " short INTEGER," + " long INTEGER," + " float NUMERIC," + " double NUMERIC," + " bytes BLOB " + ");"; SqlLiteHelper.deleteTable(SQL_LITE_URI, tableName); SqlLiteHelper.createTable(SQL_LITE_URI, createTable); Schema schema = SchemaBuilder.struct().name("com.example.Person") .field("firstName", Schema.OPTIONAL_STRING_SCHEMA) .field("lastName", Schema.OPTIONAL_STRING_SCHEMA) .field("age", Schema.OPTIONAL_INT32_SCHEMA) .field("bool", Schema.OPTIONAL_BOOLEAN_SCHEMA) .field("short", Schema.OPTIONAL_INT16_SCHEMA) .field("byte", Schema.OPTIONAL_INT8_SCHEMA) .field("long", Schema.OPTIONAL_INT64_SCHEMA) .field("float", Schema.OPTIONAL_FLOAT32_SCHEMA) .field("double", Schema.OPTIONAL_FLOAT64_SCHEMA) .field("bytes", Schema.OPTIONAL_BYTES_SCHEMA); final String fName1 = "Alex"; final String lName1 = "Smith"; final int age1 = 21; final boolean bool1 = true; final short s1 = 1234; final byte b1 = -32; final long l1 = 12425436; final float f1 = (float) 2356.3; final double d1 = -2436546.56457; final byte[] bs1 = new byte[]{-32, 124}; Struct struct1 = new Struct(schema) .put("firstName", fName1) .put("lastName", lName1) .put("bool", bool1) .put("short", s1) .put("byte", b1) .put("long", l1) .put("float", f1) .put("double", d1) .put("bytes", bs1) .put("age", age1); String topic = "topic"; int partition = 2; Collection<SinkRecord> records = Collections.nCopies( 100, new SinkRecord(topic, partition, null, null, schema, struct1, 1)); Map<String, StructFieldsDataExtractor> map = new HashMap<>(); map.put(topic.toLowerCase(), new StructFieldsDataExtractor(new FieldsMappings(tableName, topic, true, new HashMap<String, FieldAlias>()))); List<DbTable> dbTables = Lists.newArrayList( new DbTable(tableName, Lists.<DbTableColumn>newArrayList( new DbTableColumn("firstName", true, false, 1), new DbTableColumn("lastName", true, false, 1), new DbTableColumn("age", false, false, 1), new DbTableColumn("bool", true, false, 1), new DbTableColumn("byte", true, false, 1), new DbTableColumn("short", true, false, 1), new DbTableColumn("long", true, false, 1), new DbTableColumn("float", true, false, 1), new DbTableColumn("double", true, false, 1), new DbTableColumn("BLOB", true, false, 1) ))); DatabaseMetadata dbMetadata = new DatabaseMetadata(null, dbTables); HikariDataSource ds = HikariHelper.from(SQL_LITE_URI, null, null); DatabaseChangesExecutor executor = new DatabaseChangesExecutor( ds, Sets.<String>newHashSet(), Sets.<String>newHashSet(), dbMetadata, new SQLiteDialect(), 1); JdbcDbWriter writer = new JdbcDbWriter(ds, new BatchedPreparedStatementBuilder(map, new InsertQueryBuilder(new SQLiteDialect())), new ThrowErrorHandlingPolicy(), executor, 10); writer.write(records); String query = "SELECT * FROM " + tableName + " ORDER BY firstName"; SqlLiteHelper.ResultSetReadCallback callback = new SqlLiteHelper.ResultSetReadCallback() { int index = 0; @Override public void read(ResultSet rs) throws SQLException { if (index < 100) { assertEquals(rs.getString("firstName"), fName1); assertEquals(rs.getString("lastName"), lName1); assertEquals(rs.getBoolean("bool"), bool1); assertEquals(rs.getShort("short"), s1); assertEquals(rs.getByte("byte"), b1); assertEquals(rs.getLong("long"), l1); assertEquals(Float.compare(rs.getFloat("float"), f1), 0); assertEquals(Double.compare(rs.getDouble("double"), d1), 0); assertTrue(Arrays.equals(rs.getBytes("bytes"), bs1)); assertEquals(rs.getInt("age"), age1); } else throw new RuntimeException(String.format("%d is too high", index)); index++; } }; SqlLiteHelper.select(SQL_LITE_URI, query, callback); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void shouldReturnThePrimaryKeysAtTheEndWhenOneFieldIsPK() { Schema schema = SchemaBuilder.struct().name("com.example.Person") .field("firstName", Schema.STRING_SCHEMA) .field("lastName", Schema.STRING_SCHEMA) .field("age", Schema.INT32_SCHEMA) .field("bool", Schema.BOOLEAN_SCHEMA) .field("short", Schema.INT16_SCHEMA) .field("byte", Schema.INT8_SCHEMA) .field("long", Schema.INT64_SCHEMA) .field("float", Schema.FLOAT32_SCHEMA) .field("double", Schema.FLOAT64_SCHEMA) .field("bytes", Schema.BYTES_SCHEMA) .field("threshold", Schema.OPTIONAL_FLOAT64_SCHEMA).build(); short s = 1234; byte b = -32; long l = 12425436; float f = (float) 2356.3; double d = -2436546.56457; byte[] bs = new byte[]{-32, 124}; Struct struct = new Struct(schema) .put("firstName", "Alex") .put("lastName", "Smith") .put("bool", true) .put("short", s) .put("byte", b) .put("long", l) .put("float", f) .put("double", d) .put("bytes", bs) .put("age", 30); Map<String, FieldAlias> mappings = new HashMap<>(); mappings.put("long", new FieldAlias("long", true)); FieldsMappings tm = new FieldsMappings("table", "topic", true, mappings); StructFieldsDataExtractor dataExtractor = new StructFieldsDataExtractor(tm); StructFieldsDataExtractor.PreparedStatementBinders binders = dataExtractor.get(struct, new SinkRecord("", 2, null, null, schema, struct, 2)); HashMap<String, PreparedStatementBinder> map = new HashMap<>(); for (PreparedStatementBinder p : Iterables.concat(binders.getNonKeyColumns(), binders.getKeyColumns())) map.put(p.getFieldName(), p); assertTrue(!binders.isEmpty()); assertEquals(map.size(), 10); assertTrue(Objects.equals(binders.getKeyColumns().get(0).getFieldName(), "long")); assertTrue(map.containsKey("firstName")); assertTrue(map.get("firstName").getClass() == StringPreparedStatementBinder.class); assertTrue(map.containsKey("lastName")); assertTrue(map.get("lastName").getClass() == StringPreparedStatementBinder.class); assertTrue(map.containsKey("age")); assertTrue(map.get("age").getClass() == IntPreparedStatementBinder.class); assertTrue(map.get("long").getClass() == LongPreparedStatementBinder.class); assertEquals(((LongPreparedStatementBinder) map.get("long")).getValue(), l); assertTrue(map.get("short").getClass() == ShortPreparedStatementBinder.class); assertEquals(((ShortPreparedStatementBinder) map.get("short")).getValue(), s); assertTrue(map.get("byte").getClass() == BytePreparedStatementBinder.class); assertEquals(((BytePreparedStatementBinder) map.get("byte")).getValue(), b); assertTrue(map.get("float").getClass() == FloatPreparedStatementBinder.class); assertEquals(Float.compare(((FloatPreparedStatementBinder) map.get("float")).getValue(), f), 0); assertTrue(map.get("double").getClass() == DoublePreparedStatementBinder.class); assertEquals(Double.compare(((DoublePreparedStatementBinder) map.get("double")).getValue(), d), 0); assertTrue(map.get("bytes").getClass() == BytesPreparedStatementBinder.class); assertTrue(Arrays.equals(bs, ((BytesPreparedStatementBinder) map.get("bytes")).getValue())); } #location 51 #vulnerability type NULL_DEREFERENCE
#fixed code @Test public void shouldReturnThePrimaryKeysAtTheEndWhenOneFieldIsPK() { Schema schema = SchemaBuilder.struct().name("com.example.Person") .field("firstName", Schema.STRING_SCHEMA) .field("lastName", Schema.STRING_SCHEMA) .field("age", Schema.INT32_SCHEMA) .field("bool", Schema.BOOLEAN_SCHEMA) .field("short", Schema.INT16_SCHEMA) .field("byte", Schema.INT8_SCHEMA) .field("long", Schema.INT64_SCHEMA) .field("float", Schema.FLOAT32_SCHEMA) .field("double", Schema.FLOAT64_SCHEMA) .field("bytes", Schema.BYTES_SCHEMA) .field("threshold", Schema.OPTIONAL_FLOAT64_SCHEMA).build(); short s = 1234; byte b = -32; long l = 12425436; float f = (float) 2356.3; double d = -2436546.56457; byte[] bs = new byte[]{-32, 124}; Struct struct = new Struct(schema) .put("firstName", "Alex") .put("lastName", "Smith") .put("bool", true) .put("short", s) .put("byte", b) .put("long", l) .put("float", f) .put("double", d) .put("bytes", bs) .put("age", 30); Map<String, FieldAlias> mappings = new HashMap<>(); mappings.put("long", new FieldAlias("long", true)); FieldsMappings tm = new FieldsMappings("table", "topic", true, mappings); StructFieldsDataExtractor dataExtractor = new StructFieldsDataExtractor(tm); List<PreparedStatementBinder> binders = dataExtractor.get(struct, new SinkRecord("", 2, null, null, schema, struct, 2)); HashMap<String, PreparedStatementBinder> map = new HashMap<>(); LinkedList<PreparedStatementBinder> pkBinders = new LinkedList<>(); for (PreparedStatementBinder p : binders) { if (p.isPrimaryKey()) { pkBinders.add(p); } map.put(p.getFieldName(), p); } assertTrue(!binders.isEmpty()); assertEquals(map.size(), 10); assertTrue(Objects.equals(pkBinders.get(0).getFieldName(), "long")); assertTrue(map.containsKey("firstName")); assertTrue(map.get("firstName").getClass() == StringPreparedStatementBinder.class); assertTrue(map.containsKey("lastName")); assertTrue(map.get("lastName").getClass() == StringPreparedStatementBinder.class); assertTrue(map.containsKey("age")); assertTrue(map.get("age").getClass() == IntPreparedStatementBinder.class); assertTrue(map.get("long").getClass() == LongPreparedStatementBinder.class); assertEquals(((LongPreparedStatementBinder) map.get("long")).getValue(), l); assertTrue(map.get("short").getClass() == ShortPreparedStatementBinder.class); assertEquals(((ShortPreparedStatementBinder) map.get("short")).getValue(), s); assertTrue(map.get("byte").getClass() == BytePreparedStatementBinder.class); assertEquals(((BytePreparedStatementBinder) map.get("byte")).getValue(), b); assertTrue(map.get("float").getClass() == FloatPreparedStatementBinder.class); assertEquals(Float.compare(((FloatPreparedStatementBinder) map.get("float")).getValue(), f), 0); assertTrue(map.get("double").getClass() == DoublePreparedStatementBinder.class); assertEquals(Double.compare(((DoublePreparedStatementBinder) map.get("double")).getValue(), d), 0); assertTrue(map.get("bytes").getClass() == BytesPreparedStatementBinder.class); assertTrue(Arrays.equals(bs, ((BytesPreparedStatementBinder) map.get("bytes")).getValue())); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void handleAllFieldsIncludedAndAnExistingMapping() { List<DbTableColumn> columns = Lists.newArrayList( new DbTableColumn("col1", true, false, 1), new DbTableColumn("col2", false, false, 1), new DbTableColumn("col3", false, false, 1)); DbTable table = new DbTable("tableA", columns); Map<String, FieldAlias> aliasMap = new HashMap<>(); aliasMap.put("col3", new FieldAlias("col3", true)); FieldsMappings mappings = new FieldsMappings("tableA", "topic1", true, aliasMap); FieldsMappings newMappings = PreparedStatementBuilderHelper.validateAndMerge(mappings, table); assertEquals(newMappings.getTableName(), mappings.getTableName()); assertEquals(newMappings.getIncomingTopic(), mappings.getIncomingTopic()); assertEquals(newMappings.areAllFieldsIncluded(), false); Map<String, FieldAlias> newAliasMap = newMappings.getMappings(); assertEquals(3, newAliasMap.size()); //+ the specific mapping assertTrue(newAliasMap.containsKey("col1")); assertEquals(newAliasMap.get("col1").getName(), "col1"); assertEquals(newAliasMap.get("col1").isPrimaryKey(), true); assertTrue(newAliasMap.containsKey("col2")); assertEquals(newAliasMap.get("col2").getName(), "col2"); assertEquals(newAliasMap.get("col2").isPrimaryKey(), false); assertTrue(newAliasMap.containsKey("col3")); assertEquals(newAliasMap.get("col3").getName(), "col3"); assertEquals(newAliasMap.get("col3").isPrimaryKey(), false); } #location 25 #vulnerability type NULL_DEREFERENCE
#fixed code @Test public void handleAllFieldsIncludedAndAnExistingMapping() { List<DbTableColumn> columns = Lists.newArrayList( new DbTableColumn("col1", true, false, 1), new DbTableColumn("col2", false, false, 1), new DbTableColumn("col3", false, false, 1)); DbTable table = new DbTable("tableA", columns); Map<String, FieldAlias> aliasMap = new HashMap<>(); aliasMap.put("col3", new FieldAlias("col3", true)); FieldsMappings mappings = new FieldsMappings("tableA", "topic1", true, aliasMap); FieldsMappings newMappings = PreparedStatementBuilderHelper.validateAndMerge(mappings, table, InsertModeEnum.INSERT); assertEquals(newMappings.getTableName(), mappings.getTableName()); assertEquals(newMappings.getIncomingTopic(), mappings.getIncomingTopic()); assertEquals(newMappings.areAllFieldsIncluded(), false); Map<String, FieldAlias> newAliasMap = newMappings.getMappings(); assertEquals(3, newAliasMap.size()); //+ the specific mapping assertTrue(newAliasMap.containsKey("col1")); assertEquals(newAliasMap.get("col1").getName(), "col1"); assertEquals(newAliasMap.get("col1").isPrimaryKey(), true); assertTrue(newAliasMap.containsKey("col2")); assertEquals(newAliasMap.get("col2").getName(), "col2"); assertEquals(newAliasMap.get("col2").isPrimaryKey(), false); assertTrue(newAliasMap.containsKey("col3")); assertEquals(newAliasMap.get("col3").getName(), "col3"); assertEquals(newAliasMap.get("col3").isPrimaryKey(), false); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void handleBatchedStatementPerRecordInsertingSameRecord100Times() throws SQLException { String tableName = "batched_statement_test_100"; String createTable = "CREATE TABLE " + tableName + " (" + " firstName TEXT," + " lastName TEXT," + " age INTEGER," + " bool NUMERIC," + " byte INTEGER," + " short INTEGER," + " long INTEGER," + " float NUMERIC," + " double NUMERIC," + " bytes BLOB " + ");"; SqlLiteHelper.deleteTable(SQL_LITE_URI, tableName); SqlLiteHelper.createTable(SQL_LITE_URI, createTable); Schema schema = SchemaBuilder.struct().name("com.example.Person") .field("firstName", Schema.OPTIONAL_STRING_SCHEMA) .field("lastName", Schema.OPTIONAL_STRING_SCHEMA) .field("age", Schema.OPTIONAL_INT32_SCHEMA) .field("bool", Schema.OPTIONAL_BOOLEAN_SCHEMA) .field("short", Schema.OPTIONAL_INT16_SCHEMA) .field("byte", Schema.OPTIONAL_INT8_SCHEMA) .field("long", Schema.OPTIONAL_INT64_SCHEMA) .field("float", Schema.OPTIONAL_FLOAT32_SCHEMA) .field("double", Schema.OPTIONAL_FLOAT64_SCHEMA) .field("bytes", Schema.OPTIONAL_BYTES_SCHEMA); final String fName1 = "Alex"; final String lName1 = "Smith"; final int age1 = 21; final boolean bool1 = true; final short s1 = 1234; final byte b1 = -32; final long l1 = 12425436; final float f1 = (float) 2356.3; final double d1 = -2436546.56457; final byte[] bs1 = new byte[]{-32, 124}; Struct struct1 = new Struct(schema) .put("firstName", fName1) .put("lastName", lName1) .put("bool", bool1) .put("short", s1) .put("byte", b1) .put("long", l1) .put("float", f1) .put("double", d1) .put("bytes", bs1) .put("age", age1); String topic = "topic"; int partition = 2; Collection<SinkRecord> records = Collections.nCopies( 100, new SinkRecord(topic, partition, null, null, schema, struct1, 1)); Map<String, StructFieldsDataExtractor> map = new HashMap<>(); map.put(topic.toLowerCase(), new StructFieldsDataExtractor(new FieldsMappings(tableName, topic, true, new HashMap<String, FieldAlias>()))); List<DbTable> dbTables = Lists.newArrayList( new DbTable(tableName, Lists.<DbTableColumn>newArrayList( new DbTableColumn("firstName", true, false, 1), new DbTableColumn("lastName", true, false, 1), new DbTableColumn("age", false, false, 1), new DbTableColumn("bool", true, false, 1), new DbTableColumn("byte", true, false, 1), new DbTableColumn("short", true, false, 1), new DbTableColumn("long", true, false, 1), new DbTableColumn("float", true, false, 1), new DbTableColumn("double", true, false, 1), new DbTableColumn("BLOB", true, false, 1) ))); DatabaseMetadata dbMetadata = new DatabaseMetadata(null, dbTables); HikariDataSource ds = HikariHelper.from(SQL_LITE_URI, null, null); DatabaseChangesExecutor executor = new DatabaseChangesExecutor( ds, Sets.<String>newHashSet(), Sets.<String>newHashSet(), dbMetadata, new SQLiteDialect(), 1); JdbcDbWriter writer = new JdbcDbWriter(ds, new BatchedPreparedStatementBuilder(map, new InsertQueryBuilder()), new ThrowErrorHandlingPolicy(), executor, 10); writer.write(records); String query = "SELECT * FROM " + tableName + " ORDER BY firstName"; SqlLiteHelper.ResultSetReadCallback callback = new SqlLiteHelper.ResultSetReadCallback() { int index = 0; @Override public void read(ResultSet rs) throws SQLException { if (index < 100) { assertEquals(rs.getString("firstName"), fName1); assertEquals(rs.getString("lastName"), lName1); assertEquals(rs.getBoolean("bool"), bool1); assertEquals(rs.getShort("short"), s1); assertEquals(rs.getByte("byte"), b1); assertEquals(rs.getLong("long"), l1); assertEquals(Float.compare(rs.getFloat("float"), f1), 0); assertEquals(Double.compare(rs.getDouble("double"), d1), 0); assertTrue(Arrays.equals(rs.getBytes("bytes"), bs1)); assertEquals(rs.getInt("age"), age1); } else throw new RuntimeException(String.format("%d is too high", index)); index++; } }; SqlLiteHelper.select(SQL_LITE_URI, query, callback); } #location 115 #vulnerability type RESOURCE_LEAK
#fixed code @Test public void handleBatchedStatementPerRecordInsertingSameRecord100Times() throws SQLException { String tableName = "batched_statement_test_100"; String createTable = "CREATE TABLE " + tableName + " (" + " firstName TEXT," + " lastName TEXT," + " age INTEGER," + " bool NUMERIC," + " byte INTEGER," + " short INTEGER," + " long INTEGER," + " float NUMERIC," + " double NUMERIC," + " bytes BLOB " + ");"; SqlLiteHelper.deleteTable(SQL_LITE_URI, tableName); SqlLiteHelper.createTable(SQL_LITE_URI, createTable); Schema schema = SchemaBuilder.struct().name("com.example.Person") .field("firstName", Schema.OPTIONAL_STRING_SCHEMA) .field("lastName", Schema.OPTIONAL_STRING_SCHEMA) .field("age", Schema.OPTIONAL_INT32_SCHEMA) .field("bool", Schema.OPTIONAL_BOOLEAN_SCHEMA) .field("short", Schema.OPTIONAL_INT16_SCHEMA) .field("byte", Schema.OPTIONAL_INT8_SCHEMA) .field("long", Schema.OPTIONAL_INT64_SCHEMA) .field("float", Schema.OPTIONAL_FLOAT32_SCHEMA) .field("double", Schema.OPTIONAL_FLOAT64_SCHEMA) .field("bytes", Schema.OPTIONAL_BYTES_SCHEMA); final String fName1 = "Alex"; final String lName1 = "Smith"; final int age1 = 21; final boolean bool1 = true; final short s1 = 1234; final byte b1 = -32; final long l1 = 12425436; final float f1 = (float) 2356.3; final double d1 = -2436546.56457; final byte[] bs1 = new byte[]{-32, 124}; Struct struct1 = new Struct(schema) .put("firstName", fName1) .put("lastName", lName1) .put("bool", bool1) .put("short", s1) .put("byte", b1) .put("long", l1) .put("float", f1) .put("double", d1) .put("bytes", bs1) .put("age", age1); String topic = "topic"; int partition = 2; Collection<SinkRecord> records = Collections.nCopies( 100, new SinkRecord(topic, partition, null, null, schema, struct1, 1)); Map<String, StructFieldsDataExtractor> map = new HashMap<>(); map.put(topic.toLowerCase(), new StructFieldsDataExtractor(new FieldsMappings(tableName, topic, true, new HashMap<String, FieldAlias>()))); List<DbTable> dbTables = Lists.newArrayList( new DbTable(tableName, Lists.<DbTableColumn>newArrayList( new DbTableColumn("firstName", true, false, 1), new DbTableColumn("lastName", true, false, 1), new DbTableColumn("age", false, false, 1), new DbTableColumn("bool", true, false, 1), new DbTableColumn("byte", true, false, 1), new DbTableColumn("short", true, false, 1), new DbTableColumn("long", true, false, 1), new DbTableColumn("float", true, false, 1), new DbTableColumn("double", true, false, 1), new DbTableColumn("BLOB", true, false, 1) ))); DatabaseMetadata dbMetadata = new DatabaseMetadata(null, dbTables); HikariDataSource ds = HikariHelper.from(SQL_LITE_URI, null, null); DatabaseChangesExecutor executor = new DatabaseChangesExecutor( ds, Sets.<String>newHashSet(), Sets.<String>newHashSet(), dbMetadata, new SQLiteDialect(), 1); JdbcDbWriter writer = new JdbcDbWriter(ds, new BatchedPreparedStatementBuilder(map, new InsertQueryBuilder(new SQLiteDialect())), new ThrowErrorHandlingPolicy(), executor, 10); writer.write(records); String query = "SELECT * FROM " + tableName + " ORDER BY firstName"; SqlLiteHelper.ResultSetReadCallback callback = new SqlLiteHelper.ResultSetReadCallback() { int index = 0; @Override public void read(ResultSet rs) throws SQLException { if (index < 100) { assertEquals(rs.getString("firstName"), fName1); assertEquals(rs.getString("lastName"), lName1); assertEquals(rs.getBoolean("bool"), bool1); assertEquals(rs.getShort("short"), s1); assertEquals(rs.getByte("byte"), b1); assertEquals(rs.getLong("long"), l1); assertEquals(Float.compare(rs.getFloat("float"), f1), 0); assertEquals(Double.compare(rs.getDouble("double"), d1), 0); assertTrue(Arrays.equals(rs.getBytes("bytes"), bs1)); assertEquals(rs.getInt("age"), age1); } else throw new RuntimeException(String.format("%d is too high", index)); index++; } }; SqlLiteHelper.select(SQL_LITE_URI, query, callback); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void handleAllFieldsMappingSetting() { List<DbTableColumn> columns = Lists.newArrayList( new DbTableColumn("col1", true, false, 1), new DbTableColumn("col2", false, false, 1), new DbTableColumn("col3", false, false, 1)); DbTable table = new DbTable("tableA", columns); Map<String, FieldAlias> aliasMap = new HashMap<>(); FieldsMappings mappings = new FieldsMappings("tableA", "topic1", true, aliasMap); FieldsMappings newMappings = PreparedStatementBuilderHelper.validateAndMerge(mappings, table); assertEquals(newMappings.getTableName(), mappings.getTableName()); assertEquals(newMappings.getIncomingTopic(), mappings.getIncomingTopic()); assertEquals(newMappings.areAllFieldsIncluded(), false); Map<String, FieldAlias> newAliasMap = newMappings.getMappings(); assertEquals(3, newAliasMap.size()); assertTrue(newAliasMap.containsKey("col1")); assertEquals(newAliasMap.get("col1").getName(), "col1"); assertEquals(newAliasMap.get("col1").isPrimaryKey(), true); assertTrue(newAliasMap.containsKey("col2")); assertEquals(newAliasMap.get("col2").getName(), "col2"); assertEquals(newAliasMap.get("col2").isPrimaryKey(), false); assertTrue(newAliasMap.containsKey("col3")); assertEquals(newAliasMap.get("col3").getName(), "col3"); assertEquals(newAliasMap.get("col3").isPrimaryKey(), false); } #location 25 #vulnerability type NULL_DEREFERENCE
#fixed code @Test public void handleAllFieldsMappingSetting() { List<DbTableColumn> columns = Lists.newArrayList( new DbTableColumn("col1", true, false, 1), new DbTableColumn("col2", false, false, 1), new DbTableColumn("col3", false, false, 1)); DbTable table = new DbTable("tableA", columns); Map<String, FieldAlias> aliasMap = new HashMap<>(); FieldsMappings mappings = new FieldsMappings("tableA", "topic1", true, aliasMap); FieldsMappings newMappings = PreparedStatementBuilderHelper.validateAndMerge(mappings, table, InsertModeEnum.INSERT); assertEquals(newMappings.getTableName(), mappings.getTableName()); assertEquals(newMappings.getIncomingTopic(), mappings.getIncomingTopic()); assertEquals(newMappings.areAllFieldsIncluded(), false); Map<String, FieldAlias> newAliasMap = newMappings.getMappings(); assertEquals(3, newAliasMap.size()); assertTrue(newAliasMap.containsKey("col1")); assertEquals(newAliasMap.get("col1").getName(), "col1"); assertEquals(newAliasMap.get("col1").isPrimaryKey(), true); assertTrue(newAliasMap.containsKey("col2")); assertEquals(newAliasMap.get("col2").getName(), "col2"); assertEquals(newAliasMap.get("col2").isPrimaryKey(), false); assertTrue(newAliasMap.containsKey("col3")); assertEquals(newAliasMap.get("col3").getName(), "col3"); assertEquals(newAliasMap.get("col3").isPrimaryKey(), false); }
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) .field("age", Schema.INT32_SCHEMA) .field("bool", Schema.BOOLEAN_SCHEMA) .field("short", Schema.INT16_SCHEMA) .field("byte", Schema.INT8_SCHEMA) .field("long", Schema.INT64_SCHEMA) .field("float", Schema.FLOAT32_SCHEMA) .field("double", Schema.FLOAT64_SCHEMA) .field("bytes", Schema.BYTES_SCHEMA) .field("threshold", Schema.OPTIONAL_FLOAT64_SCHEMA).build(); short s = 1234; byte b = -32; long l = 12425436; float f = (float) 2356.3; double d = -2436546.56457; byte[] bs = new byte[]{-32, 124}; Struct struct = new Struct(schema) .put("firstName", "Alex") .put("lastName", "Smith") .put("bool", true) .put("short", s) .put("byte", b) .put("long", l) .put("float", f) .put("double", d) .put("bytes", bs) .put("age", 30); Map<String, FieldAlias> mappings = new HashMap<>(); mappings.put("firstName", new FieldAlias("fName", true)); mappings.put("lastName", new FieldAlias("lName", true)); FieldsMappings tm = new FieldsMappings("table", "topic", true, mappings); StructFieldsDataExtractor dataExtractor = new StructFieldsDataExtractor(tm); StructFieldsDataExtractor.PreparedStatementBinders binders = dataExtractor.get(struct, new SinkRecord("", 1, null, null, schema, struct, 0)); HashMap<String, PreparedStatementBinder> map = new HashMap<>(); for (PreparedStatementBinder p : Iterables.concat(binders.getNonKeyColumns(), binders.getKeyColumns())) map.put(p.getFieldName(), p); assertTrue(!binders.isEmpty()); assertEquals(binders.getNonKeyColumns().size() + binders.getKeyColumns().size(), 10); List<PreparedStatementBinder> pkBinders = binders.getKeyColumns(); assertEquals(pkBinders.size(), 2); assertTrue(Objects.equals(pkBinders.get(0).getFieldName(), "fName") || Objects.equals(pkBinders.get(1).getFieldName(), "fName") ); assertTrue(Objects.equals(pkBinders.get(0).getFieldName(), "lName") || Objects.equals(pkBinders.get(1).getFieldName(), "lName") ); assertTrue(map.containsKey("fName")); assertTrue(map.get("fName").getClass() == StringPreparedStatementBinder.class); assertTrue(map.containsKey("lName")); assertTrue(map.get("lName").getClass() == StringPreparedStatementBinder.class); assertTrue(map.containsKey("age")); assertTrue(map.get("age").getClass() == IntPreparedStatementBinder.class); assertTrue(map.get("long").getClass() == LongPreparedStatementBinder.class); assertEquals(((LongPreparedStatementBinder) map.get("long")).getValue(), l); assertTrue(map.get("short").getClass() == ShortPreparedStatementBinder.class); assertEquals(((ShortPreparedStatementBinder) map.get("short")).getValue(), s); assertTrue(map.get("byte").getClass() == BytePreparedStatementBinder.class); assertEquals(((BytePreparedStatementBinder) map.get("byte")).getValue(), b); assertTrue(map.get("float").getClass() == FloatPreparedStatementBinder.class); assertEquals(Float.compare(((FloatPreparedStatementBinder) map.get("float")).getValue(), f), 0); assertTrue(map.get("double").getClass() == DoublePreparedStatementBinder.class); assertEquals(Double.compare(((DoublePreparedStatementBinder) map.get("double")).getValue(), d), 0); assertTrue(map.get("bytes").getClass() == BytesPreparedStatementBinder.class); assertTrue(Arrays.equals(bs, ((BytesPreparedStatementBinder) map.get("bytes")).getValue())); } #location 49 #vulnerability type NULL_DEREFERENCE
#fixed code @Test public void shouldReturnThePrimaryKeysAtTheEndWhenMultipleFieldsFormThePrimaryKey() { Schema schema = SchemaBuilder.struct().name("com.example.Person") .field("firstName", Schema.STRING_SCHEMA) .field("lastName", Schema.STRING_SCHEMA) .field("age", Schema.INT32_SCHEMA) .field("bool", Schema.BOOLEAN_SCHEMA) .field("short", Schema.INT16_SCHEMA) .field("byte", Schema.INT8_SCHEMA) .field("long", Schema.INT64_SCHEMA) .field("float", Schema.FLOAT32_SCHEMA) .field("double", Schema.FLOAT64_SCHEMA) .field("bytes", Schema.BYTES_SCHEMA) .field("threshold", Schema.OPTIONAL_FLOAT64_SCHEMA).build(); short s = 1234; byte b = -32; long l = 12425436; float f = (float) 2356.3; double d = -2436546.56457; byte[] bs = new byte[]{-32, 124}; Struct struct = new Struct(schema) .put("firstName", "Alex") .put("lastName", "Smith") .put("bool", true) .put("short", s) .put("byte", b) .put("long", l) .put("float", f) .put("double", d) .put("bytes", bs) .put("age", 30); Map<String, FieldAlias> mappings = new HashMap<>(); mappings.put("firstName", new FieldAlias("fName", true)); mappings.put("lastName", new FieldAlias("lName", true)); FieldsMappings tm = new FieldsMappings("table", "topic", true, mappings); StructFieldsDataExtractor dataExtractor = new StructFieldsDataExtractor(tm); List<PreparedStatementBinder> binders = dataExtractor.get(struct, new SinkRecord("", 1, null, null, schema, struct, 0)); HashMap<String, PreparedStatementBinder> map = new HashMap<>(); List<PreparedStatementBinder> pkBinders = new LinkedList<>(); for (PreparedStatementBinder p : binders) { if (p.isPrimaryKey()) { pkBinders.add(p); } map.put(p.getFieldName(), p); } assertTrue(!binders.isEmpty()); assertEquals(binders.size(), 10); assertEquals(pkBinders.size(), 2); assertTrue(Objects.equals(pkBinders.get(0).getFieldName(), "fName") || Objects.equals(pkBinders.get(1).getFieldName(), "fName") ); assertTrue(Objects.equals(pkBinders.get(0).getFieldName(), "lName") || Objects.equals(pkBinders.get(1).getFieldName(), "lName") ); assertTrue(map.containsKey("fName")); assertTrue(map.get("fName").getClass() == StringPreparedStatementBinder.class); assertTrue(map.containsKey("lName")); assertTrue(map.get("lName").getClass() == StringPreparedStatementBinder.class); assertTrue(map.containsKey("age")); assertTrue(map.get("age").getClass() == IntPreparedStatementBinder.class); assertTrue(map.get("long").getClass() == LongPreparedStatementBinder.class); assertEquals(((LongPreparedStatementBinder) map.get("long")).getValue(), l); assertTrue(map.get("short").getClass() == ShortPreparedStatementBinder.class); assertEquals(((ShortPreparedStatementBinder) map.get("short")).getValue(), s); assertTrue(map.get("byte").getClass() == BytePreparedStatementBinder.class); assertEquals(((BytePreparedStatementBinder) map.get("byte")).getValue(), b); assertTrue(map.get("float").getClass() == FloatPreparedStatementBinder.class); assertEquals(Float.compare(((FloatPreparedStatementBinder) map.get("float")).getValue(), f), 0); assertTrue(map.get("double").getClass() == DoublePreparedStatementBinder.class); assertEquals(Double.compare(((DoublePreparedStatementBinder) map.get("double")).getValue(), d), 0); assertTrue(map.get("bytes").getClass() == BytesPreparedStatementBinder.class); assertTrue(Arrays.equals(bs, ((BytesPreparedStatementBinder) map.get("bytes")).getValue())); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void handleBatchStatementPerRecordInsertingWithAutoCreatedColumnForPK() throws SQLException { String tableName = "batch_100_auto_create_column"; Schema schema = SchemaBuilder.struct().name("com.example.Person") .field("firstName", Schema.OPTIONAL_STRING_SCHEMA) .field("lastName", Schema.OPTIONAL_STRING_SCHEMA) .field("age", Schema.OPTIONAL_INT32_SCHEMA) .field("bool", Schema.OPTIONAL_BOOLEAN_SCHEMA) .field("short", Schema.OPTIONAL_INT16_SCHEMA) .field("byte", Schema.OPTIONAL_INT8_SCHEMA) .field("long", Schema.OPTIONAL_INT64_SCHEMA) .field("float", Schema.OPTIONAL_FLOAT32_SCHEMA) .field("double", Schema.OPTIONAL_FLOAT64_SCHEMA) .field("bytes", Schema.OPTIONAL_BYTES_SCHEMA); final String fName1 = "Alex"; final String lName1 = "Smith"; final int age1 = 21; final boolean bool1 = true; final short s1 = 1234; final byte b1 = -32; final long l1 = 12425436; final float f1 = (float) 2356.3; final double d1 = -2436546.56457; final byte[] bs1 = new byte[]{-32, 124}; Struct struct1 = new Struct(schema) .put("firstName", fName1) .put("lastName", lName1) .put("bool", bool1) .put("short", s1) .put("byte", b1) .put("long", l1) .put("float", f1) .put("double", d1) .put("bytes", bs1) .put("age", age1); final String topic = "topic"; final int partition = 2; List<SinkRecord> records = new ArrayList<>(100); for (int i = 0; i < 100; ++i) { records.add(new SinkRecord(topic, partition, null, null, schema, struct1, i)); } Map<String, StructFieldsDataExtractor> map = new HashMap<>(); Map<String, FieldAlias> fields = new HashMap<>(); fields.put(FieldsMappings.CONNECT_AUTO_ID_COLUMN, new FieldAlias(FieldsMappings.CONNECT_AUTO_ID_COLUMN, true)); map.put(topic.toLowerCase(), new StructFieldsDataExtractor(new FieldsMappings(tableName, topic, true, fields, true, true))); List<DbTable> dbTables = Lists.newArrayList(); DatabaseMetadata dbMetadata = new DatabaseMetadata(null, dbTables); HikariDataSource ds = HikariHelper.from(SQL_LITE_URI, null, null); DatabaseChangesExecutor executor = new DatabaseChangesExecutor( ds, Sets.<String>newHashSet(tableName), Sets.<String>newHashSet(), dbMetadata, new SQLiteDialect(), 1); JdbcDbWriter writer = new JdbcDbWriter( ds, new BatchedPreparedStatementBuilder(map, new InsertQueryBuilder()), new ThrowErrorHandlingPolicy(), executor, 10); writer.write(records); String query = "SELECT * FROM " + tableName + " ORDER BY firstName"; SqlLiteHelper.ResultSetReadCallback callback = new SqlLiteHelper.ResultSetReadCallback() { int index = 0; @Override public void read(ResultSet rs) throws SQLException { if (index < 100) { assertEquals(rs.getString(FieldsMappings.CONNECT_AUTO_ID_COLUMN), String.format("%s.%s.%d", topic, partition, index)); assertEquals(rs.getString("firstName"), fName1); assertEquals(rs.getString("lastName"), lName1); assertEquals(rs.getBoolean("bool"), bool1); assertEquals(rs.getShort("short"), s1); assertEquals(rs.getByte("byte"), b1); assertEquals(rs.getLong("long"), l1); assertEquals(Float.compare(rs.getFloat("float"), f1), 0); assertEquals(Double.compare(rs.getDouble("double"), d1), 0); assertTrue(Arrays.equals(rs.getBytes("bytes"), bs1)); assertEquals(rs.getInt("age"), age1); } else throw new RuntimeException(String.format("%d is too high", index)); index++; } }; SqlLiteHelper.select(SQL_LITE_URI, query, callback); } #location 46 #vulnerability type RESOURCE_LEAK
#fixed code @Test public void handleBatchStatementPerRecordInsertingWithAutoCreatedColumnForPK() throws SQLException { String tableName = "batch_100_auto_create_column"; Schema schema = SchemaBuilder.struct().name("com.example.Person") .field("firstName", Schema.OPTIONAL_STRING_SCHEMA) .field("lastName", Schema.OPTIONAL_STRING_SCHEMA) .field("age", Schema.OPTIONAL_INT32_SCHEMA) .field("bool", Schema.OPTIONAL_BOOLEAN_SCHEMA) .field("short", Schema.OPTIONAL_INT16_SCHEMA) .field("byte", Schema.OPTIONAL_INT8_SCHEMA) .field("long", Schema.OPTIONAL_INT64_SCHEMA) .field("float", Schema.OPTIONAL_FLOAT32_SCHEMA) .field("double", Schema.OPTIONAL_FLOAT64_SCHEMA) .field("bytes", Schema.OPTIONAL_BYTES_SCHEMA); final String fName1 = "Alex"; final String lName1 = "Smith"; final int age1 = 21; final boolean bool1 = true; final short s1 = 1234; final byte b1 = -32; final long l1 = 12425436; final float f1 = (float) 2356.3; final double d1 = -2436546.56457; final byte[] bs1 = new byte[]{-32, 124}; Struct struct1 = new Struct(schema) .put("firstName", fName1) .put("lastName", lName1) .put("bool", bool1) .put("short", s1) .put("byte", b1) .put("long", l1) .put("float", f1) .put("double", d1) .put("bytes", bs1) .put("age", age1); final String topic = "topic"; final int partition = 2; List<SinkRecord> records = new ArrayList<>(100); for (int i = 0; i < 100; ++i) { records.add(new SinkRecord(topic, partition, null, null, schema, struct1, i)); } Map<String, StructFieldsDataExtractor> map = new HashMap<>(); Map<String, FieldAlias> fields = new HashMap<>(); fields.put(FieldsMappings.CONNECT_AUTO_ID_COLUMN, new FieldAlias(FieldsMappings.CONNECT_AUTO_ID_COLUMN, true)); map.put(topic.toLowerCase(), new StructFieldsDataExtractor(new FieldsMappings(tableName, topic, true, fields, true, true))); List<DbTable> dbTables = Lists.newArrayList(); DatabaseMetadata dbMetadata = new DatabaseMetadata(null, dbTables); HikariDataSource ds = HikariHelper.from(SQL_LITE_URI, null, null); DatabaseChangesExecutor executor = new DatabaseChangesExecutor( ds, Sets.<String>newHashSet(tableName), Sets.<String>newHashSet(), dbMetadata, new SQLiteDialect(), 1); JdbcDbWriter writer = new JdbcDbWriter( ds, new BatchedPreparedStatementBuilder(map, new InsertQueryBuilder(new SQLiteDialect())), new ThrowErrorHandlingPolicy(), executor, 10); writer.write(records); String query = "SELECT * FROM " + tableName + " ORDER BY firstName"; SqlLiteHelper.ResultSetReadCallback callback = new SqlLiteHelper.ResultSetReadCallback() { int index = 0; @Override public void read(ResultSet rs) throws SQLException { if (index < 100) { assertEquals(rs.getString(FieldsMappings.CONNECT_AUTO_ID_COLUMN), String.format("%s.%s.%d", topic, partition, index)); assertEquals(rs.getString("firstName"), fName1); assertEquals(rs.getString("lastName"), lName1); assertEquals(rs.getBoolean("bool"), bool1); assertEquals(rs.getShort("short"), s1); assertEquals(rs.getByte("byte"), b1); assertEquals(rs.getLong("long"), l1); assertEquals(Float.compare(rs.getFloat("float"), f1), 0); assertEquals(Double.compare(rs.getDouble("double"), d1), 0); assertTrue(Arrays.equals(rs.getBytes("bytes"), bs1)); assertEquals(rs.getInt("age"), age1); } else throw new RuntimeException(String.format("%d is too high", index)); index++; } }; SqlLiteHelper.select(SQL_LITE_URI, query, callback); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void handleAllFieldsMappingSetting() { List<DbTableColumn> columns = Lists.newArrayList( new DbTableColumn("col1", true, false, 1), new DbTableColumn("col2", false, false, 1), new DbTableColumn("col3", false, false, 1)); DbTable table = new DbTable("tableA", columns); Map<String, FieldAlias> aliasMap = new HashMap<>(); FieldsMappings mappings = new FieldsMappings("tableA", "topic1", true, aliasMap); FieldsMappings newMappings = PreparedStatementBuilderHelper.validateAndMerge(mappings, table); assertEquals(newMappings.getTableName(), mappings.getTableName()); assertEquals(newMappings.getIncomingTopic(), mappings.getIncomingTopic()); assertEquals(newMappings.areAllFieldsIncluded(), false); Map<String, FieldAlias> newAliasMap = newMappings.getMappings(); assertEquals(3, newAliasMap.size()); assertTrue(newAliasMap.containsKey("col1")); assertEquals(newAliasMap.get("col1").getName(), "col1"); assertEquals(newAliasMap.get("col1").isPrimaryKey(), true); assertTrue(newAliasMap.containsKey("col2")); assertEquals(newAliasMap.get("col2").getName(), "col2"); assertEquals(newAliasMap.get("col2").isPrimaryKey(), false); assertTrue(newAliasMap.containsKey("col3")); assertEquals(newAliasMap.get("col3").getName(), "col3"); assertEquals(newAliasMap.get("col3").isPrimaryKey(), false); } #location 21 #vulnerability type NULL_DEREFERENCE
#fixed code @Test public void handleAllFieldsMappingSetting() { List<DbTableColumn> columns = Lists.newArrayList( new DbTableColumn("col1", true, false, 1), new DbTableColumn("col2", false, false, 1), new DbTableColumn("col3", false, false, 1)); DbTable table = new DbTable("tableA", columns); Map<String, FieldAlias> aliasMap = new HashMap<>(); FieldsMappings mappings = new FieldsMappings("tableA", "topic1", true, aliasMap); FieldsMappings newMappings = PreparedStatementBuilderHelper.validateAndMerge(mappings, table, InsertModeEnum.INSERT); assertEquals(newMappings.getTableName(), mappings.getTableName()); assertEquals(newMappings.getIncomingTopic(), mappings.getIncomingTopic()); assertEquals(newMappings.areAllFieldsIncluded(), false); Map<String, FieldAlias> newAliasMap = newMappings.getMappings(); assertEquals(3, newAliasMap.size()); assertTrue(newAliasMap.containsKey("col1")); assertEquals(newAliasMap.get("col1").getName(), "col1"); assertEquals(newAliasMap.get("col1").isPrimaryKey(), true); assertTrue(newAliasMap.containsKey("col2")); assertEquals(newAliasMap.get("col2").getName(), "col2"); assertEquals(newAliasMap.get("col2").isPrimaryKey(), false); assertTrue(newAliasMap.containsKey("col3")); assertEquals(newAliasMap.get("col3").getName(), "col3"); assertEquals(newAliasMap.get("col3").isPrimaryKey(), false); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void returnAllFieldsAndTheirBytesValue() { Schema schema = SchemaBuilder.struct().name("com.example.Person") .field("firstName", Schema.STRING_SCHEMA) .field("lastName", Schema.STRING_SCHEMA) .field("age", Schema.INT32_SCHEMA) .field("bool", Schema.BOOLEAN_SCHEMA) .field("short", Schema.INT16_SCHEMA) .field("byte", Schema.INT8_SCHEMA) .field("long", Schema.INT64_SCHEMA) .field("float", Schema.FLOAT32_SCHEMA) .field("double", Schema.FLOAT64_SCHEMA) .field("bytes", Schema.BYTES_SCHEMA) .field("threshold", Schema.OPTIONAL_FLOAT64_SCHEMA).build(); short s = 1234; byte b = -32; long l = 12425436; float f = (float) 2356.3; double d = -2436546.56457; byte[] bs = new byte[]{-32, 124}; Struct struct = new Struct(schema) .put("firstName", "Alex") .put("lastName", "Smith") .put("bool", true) .put("short", s) .put("byte", b) .put("long", l) .put("float", f) .put("double", d) .put("bytes", bs) .put("age", 30); FieldsMappings tm = new FieldsMappings("table", "topic", true, new HashMap<String, FieldAlias>()); StructFieldsDataExtractor dataExtractor = new StructFieldsDataExtractor(tm); StructFieldsDataExtractor.PreparedStatementBinders binders = dataExtractor.get(struct, new SinkRecord("", 1, null, null, schema, struct, 0)); HashMap<String, PreparedStatementBinder> map = new HashMap<>(); for (PreparedStatementBinder p : Iterables.concat(binders.getNonKeyColumns(), binders.getKeyColumns())) map.put(p.getFieldName(), p); assertTrue(!binders.isEmpty()); assertEquals(binders.getKeyColumns().size() + binders.getNonKeyColumns().size(), 10); assertTrue(map.containsKey("firstName")); assertTrue(map.get("firstName").getClass() == StringPreparedStatementBinder.class); assertTrue(map.containsKey("lastName")); assertTrue(map.get("lastName").getClass() == StringPreparedStatementBinder.class); assertTrue(map.containsKey("age")); assertTrue(map.get("age").getClass() == IntPreparedStatementBinder.class); assertTrue(map.get("long").getClass() == LongPreparedStatementBinder.class); assertEquals(((LongPreparedStatementBinder) map.get("long")).getValue(), l); assertTrue(map.get("short").getClass() == ShortPreparedStatementBinder.class); assertEquals(((ShortPreparedStatementBinder) map.get("short")).getValue(), s); assertTrue(map.get("byte").getClass() == BytePreparedStatementBinder.class); assertEquals(((BytePreparedStatementBinder) map.get("byte")).getValue(), b); assertTrue(map.get("float").getClass() == FloatPreparedStatementBinder.class); assertEquals(Float.compare(((FloatPreparedStatementBinder) map.get("float")).getValue(), f), 0); assertTrue(map.get("double").getClass() == DoublePreparedStatementBinder.class); assertEquals(Double.compare(((DoublePreparedStatementBinder) map.get("double")).getValue(), d), 0); assertTrue(map.get("bytes").getClass() == BytesPreparedStatementBinder.class); assertTrue(Arrays.equals(bs, ((BytesPreparedStatementBinder) map.get("bytes")).getValue())); } #location 45 #vulnerability type NULL_DEREFERENCE
#fixed code @Test public void returnAllFieldsAndTheirBytesValue() { Schema schema = SchemaBuilder.struct().name("com.example.Person") .field("firstName", Schema.STRING_SCHEMA) .field("lastName", Schema.STRING_SCHEMA) .field("age", Schema.INT32_SCHEMA) .field("bool", Schema.BOOLEAN_SCHEMA) .field("short", Schema.INT16_SCHEMA) .field("byte", Schema.INT8_SCHEMA) .field("long", Schema.INT64_SCHEMA) .field("float", Schema.FLOAT32_SCHEMA) .field("double", Schema.FLOAT64_SCHEMA) .field("bytes", Schema.BYTES_SCHEMA) .field("threshold", Schema.OPTIONAL_FLOAT64_SCHEMA).build(); short s = 1234; byte b = -32; long l = 12425436; float f = (float) 2356.3; double d = -2436546.56457; byte[] bs = new byte[]{-32, 124}; Struct struct = new Struct(schema) .put("firstName", "Alex") .put("lastName", "Smith") .put("bool", true) .put("short", s) .put("byte", b) .put("long", l) .put("float", f) .put("double", d) .put("bytes", bs) .put("age", 30); FieldsMappings tm = new FieldsMappings("table", "topic", true, new HashMap<String, FieldAlias>()); StructFieldsDataExtractor dataExtractor = new StructFieldsDataExtractor(tm); List<PreparedStatementBinder> binders = dataExtractor.get(struct, new SinkRecord("", 1, null, null, schema, struct, 0)); HashMap<String, PreparedStatementBinder> map = new HashMap<>(); for (PreparedStatementBinder p : binders) map.put(p.getFieldName(), p); assertTrue(!binders.isEmpty()); assertEquals(binders.size(), 10); assertTrue(map.containsKey("firstName")); assertTrue(map.get("firstName").getClass() == StringPreparedStatementBinder.class); assertTrue(map.containsKey("lastName")); assertTrue(map.get("lastName").getClass() == StringPreparedStatementBinder.class); assertTrue(map.containsKey("age")); assertTrue(map.get("age").getClass() == IntPreparedStatementBinder.class); assertTrue(map.get("long").getClass() == LongPreparedStatementBinder.class); assertEquals(((LongPreparedStatementBinder) map.get("long")).getValue(), l); assertTrue(map.get("short").getClass() == ShortPreparedStatementBinder.class); assertEquals(((ShortPreparedStatementBinder) map.get("short")).getValue(), s); assertTrue(map.get("byte").getClass() == BytePreparedStatementBinder.class); assertEquals(((BytePreparedStatementBinder) map.get("byte")).getValue(), b); assertTrue(map.get("float").getClass() == FloatPreparedStatementBinder.class); assertEquals(Float.compare(((FloatPreparedStatementBinder) map.get("float")).getValue(), f), 0); assertTrue(map.get("double").getClass() == DoublePreparedStatementBinder.class); assertEquals(Double.compare(((DoublePreparedStatementBinder) map.get("double")).getValue(), d), 0); assertTrue(map.get("bytes").getClass() == BytesPreparedStatementBinder.class); assertTrue(Arrays.equals(bs, ((BytesPreparedStatementBinder) map.get("bytes")).getValue())); }
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 = socketFactory != null ? socketFactory.createSocket() : new Socket(); socket.connect(new InetSocketAddress(hostname, port)); channel = new PacketChannel(socket); if (channel.getInputStream().peek() == -1) { throw new EOFException(); } } catch (IOException e) { throw new IOException("Failed to connect to MySQL on " + hostname + ":" + port + ". Please make sure it's running.", e); } greetingPacket = receiveGreeting(); authenticate(greetingPacket); if (binlogFilename == null) { fetchBinlogFilenameAndPosition(); } if (binlogPosition < 4) { if (logger.isLoggable(Level.WARNING)) { logger.warning("Binary log position adjusted from " + binlogPosition + " to " + 4); } binlogPosition = 4; } ChecksumType checksumType = fetchBinlogChecksum(); if (checksumType != ChecksumType.NONE) { confirmSupportOfChecksum(checksumType); } requestBinaryLogStream(); } catch (IOException e) { if (channel != null && channel.isOpen()) { channel.close(); } throw e; } connected = true; connectionId = greetingPacket.getThreadId(); if (logger.isLoggable(Level.INFO)) { String position; synchronized (gtidSetAccessLock) { position = gtidSet != null ? gtidSet.toString() : binlogFilename + "/" + binlogPosition; } logger.info("Connected to " + hostname + ":" + port + " at " + position + " (" + (blocking ? "sid:" + serverId + ", " : "") + "cid:" + connectionId + ")"); } synchronized (lifecycleListeners) { for (LifecycleListener lifecycleListener : lifecycleListeners) { lifecycleListener.onConnect(this); } } if (keepAlive && !isKeepAliveThreadRunning()) { spawnKeepAliveThread(); } ensureEventDataDeserializer(EventType.ROTATE, RotateEventDataDeserializer.class); synchronized (gtidSetAccessLock) { if (gtidSet != null) { ensureEventDataDeserializer(EventType.GTID, GtidEventDataDeserializer.class); } } listenForEventPackets(); } #location 31 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code public void connect() throws IOException { if (!connectLock.tryLock()) { throw new IllegalStateException("BinaryLogClient is already connected"); } boolean notifyWhenDisconnected = false; try { try { channel = openChannel(); GreetingPacket greetingPacket = receiveGreeting(); authenticate(greetingPacket); connectionId = greetingPacket.getThreadId(); if (binlogFilename == null) { fetchBinlogFilenameAndPosition(); } if (binlogPosition < 4) { if (logger.isLoggable(Level.WARNING)) { logger.warning("Binary log position adjusted from " + binlogPosition + " to " + 4); } binlogPosition = 4; } ChecksumType checksumType = fetchBinlogChecksum(); if (checksumType != ChecksumType.NONE) { confirmSupportOfChecksum(checksumType); } requestBinaryLogStream(); } catch (IOException e) { disconnectChannel(); throw e; } connected = true; notifyWhenDisconnected = true; if (logger.isLoggable(Level.INFO)) { String position; synchronized (gtidSetAccessLock) { position = gtidSet != null ? gtidSet.toString() : binlogFilename + "/" + binlogPosition; } logger.info("Connected to " + hostname + ":" + port + " at " + position + " (" + (blocking ? "sid:" + serverId + ", " : "") + "cid:" + connectionId + ")"); } synchronized (lifecycleListeners) { for (LifecycleListener lifecycleListener : lifecycleListeners) { lifecycleListener.onConnect(this); } } if (keepAlive && !isKeepAliveThreadRunning()) { spawnKeepAliveThread(); } ensureEventDataDeserializer(EventType.ROTATE, RotateEventDataDeserializer.class); synchronized (gtidSetAccessLock) { if (gtidSet != null) { ensureEventDataDeserializer(EventType.GTID, GtidEventDataDeserializer.class); } } listenForEventPackets(); } finally { connectLock.unlock(); if (notifyWhenDisconnected) { synchronized (lifecycleListeners) { for (LifecycleListener lifecycleListener : lifecycleListeners) { lifecycleListener.onDisconnect(this); } } } } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code private void listenForEventPackets() throws IOException { ByteArrayInputStream inputStream = channel.getInputStream(); try { while (inputStream.peek() != -1) { int packetLength = inputStream.readInteger(3); inputStream.skip(1); // 1 byte for sequence int marker = inputStream.read(); byte[] bytes = inputStream.read(packetLength - 1); if (marker == 0xFF) { ErrorPacket errorPacket = new ErrorPacket(bytes); throw new IOException(errorPacket.getErrorCode() + " - " + errorPacket.getErrorMessage()); } Event event; try { event = eventDeserializer.nextEvent(new ByteArrayInputStream(bytes)); } catch (Exception e) { if (isConnected()) { synchronized (lifecycleListeners) { for (LifecycleListener lifecycleListener : lifecycleListeners) { lifecycleListener.onEventDeserializationFailure(this, e); } } } continue; } if (isConnected()) { notifyEventListeners(event); updateClientBinlogFilenameAndPosition(event); } } } catch (Exception e) { if (isConnected()) { synchronized (lifecycleListeners) { for (LifecycleListener lifecycleListener : lifecycleListeners) { lifecycleListener.onCommunicationFailure(this, e); } } } } finally { if (isConnected()) { disconnectChannel(); } } } #location 15 #vulnerability type RESOURCE_LEAK
#fixed code private void listenForEventPackets() throws IOException { ByteArrayInputStream inputStream = channel.getInputStream(); try { while (inputStream.peek() != -1) { int packetLength = inputStream.readInteger(3); inputStream.skip(1); // 1 byte for sequence int marker = inputStream.read(); if (marker == 0xFF) { ErrorPacket errorPacket = new ErrorPacket(inputStream.read(packetLength - 1)); throw new IOException(errorPacket.getErrorCode() + " - " + errorPacket.getErrorMessage()); } Event event; try { event = eventDeserializer.nextEvent(inputStream); } catch (Exception e) { if (isConnected()) { synchronized (lifecycleListeners) { for (LifecycleListener lifecycleListener : lifecycleListeners) { lifecycleListener.onEventDeserializationFailure(this, e); } } } continue; } if (isConnected()) { notifyEventListeners(event); updateClientBinlogFilenameAndPosition(event); } } } catch (Exception e) { if (isConnected()) { synchronized (lifecycleListeners) { for (LifecycleListener lifecycleListener : lifecycleListeners) { lifecycleListener.onCommunicationFailure(this, e); } } } } finally { if (isConnected()) { disconnectChannel(); } } }
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 = socketFactory != null ? socketFactory.createSocket() : new Socket(); socket.connect(new InetSocketAddress(hostname, port)); channel = new PacketChannel(socket); if (channel.getInputStream().peek() == -1) { throw new EOFException(); } } catch (IOException e) { throw new IOException("Failed to connect to MySQL on " + hostname + ":" + port + ". Please make sure it's running.", e); } greetingPacket = receiveGreeting(); authenticate(greetingPacket); if (binlogFilename == null) { fetchBinlogFilenameAndPosition(); } if (binlogPosition < 4) { if (logger.isLoggable(Level.WARNING)) { logger.warning("Binary log position adjusted from " + binlogPosition + " to " + 4); } binlogPosition = 4; } ChecksumType checksumType = fetchBinlogChecksum(); if (checksumType != ChecksumType.NONE) { confirmSupportOfChecksum(checksumType); } requestBinaryLogStream(); } catch (IOException e) { if (channel != null && channel.isOpen()) { channel.close(); } throw e; } connected = true; connectionId = greetingPacket.getThreadId(); if (logger.isLoggable(Level.INFO)) { String position; synchronized (gtidSetAccessLock) { position = gtidSet != null ? gtidSet.toString() : binlogFilename + "/" + binlogPosition; } logger.info("Connected to " + hostname + ":" + port + " at " + position + " (" + (blocking ? "sid:" + serverId + ", " : "") + "cid:" + connectionId + ")"); } synchronized (lifecycleListeners) { for (LifecycleListener lifecycleListener : lifecycleListeners) { lifecycleListener.onConnect(this); } } if (keepAlive && !isKeepAliveThreadRunning()) { spawnKeepAliveThread(); } ensureEventDataDeserializer(EventType.ROTATE, RotateEventDataDeserializer.class); synchronized (gtidSetAccessLock) { if (gtidSet != null) { ensureEventDataDeserializer(EventType.GTID, GtidEventDataDeserializer.class); } } listenForEventPackets(); } #location 8 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code public void connect() throws IOException { if (!connectLock.tryLock()) { throw new IllegalStateException("BinaryLogClient is already connected"); } boolean notifyWhenDisconnected = false; try { try { channel = openChannel(); GreetingPacket greetingPacket = receiveGreeting(); authenticate(greetingPacket); connectionId = greetingPacket.getThreadId(); if (binlogFilename == null) { fetchBinlogFilenameAndPosition(); } if (binlogPosition < 4) { if (logger.isLoggable(Level.WARNING)) { logger.warning("Binary log position adjusted from " + binlogPosition + " to " + 4); } binlogPosition = 4; } ChecksumType checksumType = fetchBinlogChecksum(); if (checksumType != ChecksumType.NONE) { confirmSupportOfChecksum(checksumType); } requestBinaryLogStream(); } catch (IOException e) { disconnectChannel(); throw e; } connected = true; notifyWhenDisconnected = true; if (logger.isLoggable(Level.INFO)) { String position; synchronized (gtidSetAccessLock) { position = gtidSet != null ? gtidSet.toString() : binlogFilename + "/" + binlogPosition; } logger.info("Connected to " + hostname + ":" + port + " at " + position + " (" + (blocking ? "sid:" + serverId + ", " : "") + "cid:" + connectionId + ")"); } synchronized (lifecycleListeners) { for (LifecycleListener lifecycleListener : lifecycleListeners) { lifecycleListener.onConnect(this); } } if (keepAlive && !isKeepAliveThreadRunning()) { spawnKeepAliveThread(); } ensureEventDataDeserializer(EventType.ROTATE, RotateEventDataDeserializer.class); synchronized (gtidSetAccessLock) { if (gtidSet != null) { ensureEventDataDeserializer(EventType.GTID, GtidEventDataDeserializer.class); } } listenForEventPackets(); } finally { connectLock.unlock(); if (notifyWhenDisconnected) { synchronized (lifecycleListeners) { for (LifecycleListener lifecycleListener : lifecycleListeners) { lifecycleListener.onDisconnect(this); } } } } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code private void listenForEventPackets() throws IOException { latch.countDown(); ByteArrayInputStream inputStream = channel.getInputStream(); while (channel.isOpen()) { int packetLength = inputStream.readInteger(3); inputStream.skip(2); // 1 byte for sequence and 1 for marker ByteArrayInputStream eventByteArray = new ByteArrayInputStream(inputStream.read(packetLength - 1)); Event event = eventDeserializer.nextEvent(eventByteArray); notifyEventListeners(event); } } #location 8 #vulnerability type RESOURCE_LEAK
#fixed code private void listenForEventPackets() throws IOException { latch.countDown(); ByteArrayInputStream inputStream = channel.getInputStream(); try { while (true) { try { inputStream.peek(); } catch (SocketException e) { if (!connected) { break; } throw e; } int packetLength = inputStream.readInteger(3); inputStream.skip(1); // 1 byte for sequence int marker = inputStream.read(); byte[] bytes = inputStream.read(packetLength - 1); if (marker == 0xFF) { ErrorPacket errorPacket = new ErrorPacket(bytes); throw new IOException(errorPacket.getErrorCode() + " - " + errorPacket.getErrorMessage()); } Event event = eventDeserializer.nextEvent(new ByteArrayInputStream(bytes)); notifyEventListeners(event); } } finally { disconnect(); } }
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 = socketFactory != null ? socketFactory.createSocket() : new Socket(); socket.connect(new InetSocketAddress(hostname, port)); channel = new PacketChannel(socket); if (channel.getInputStream().peek() == -1) { throw new EOFException(); } } catch (IOException e) { throw new IOException("Failed to connect to MySQL on " + hostname + ":" + port + ". Please make sure it's running.", e); } greetingPacket = receiveGreeting(); authenticate(greetingPacket); if (binlogFilename == null) { fetchBinlogFilenameAndPosition(); } if (binlogPosition < 4) { if (logger.isLoggable(Level.WARNING)) { logger.warning("Binary log position adjusted from " + binlogPosition + " to " + 4); } binlogPosition = 4; } ChecksumType checksumType = fetchBinlogChecksum(); if (checksumType != ChecksumType.NONE) { confirmSupportOfChecksum(checksumType); } requestBinaryLogStream(); } catch (IOException e) { if (channel != null && channel.isOpen()) { channel.close(); } throw e; } connected = true; connectionId = greetingPacket.getThreadId(); if (logger.isLoggable(Level.INFO)) { String position; synchronized (gtidSetAccessLock) { position = gtidSet != null ? gtidSet.toString() : binlogFilename + "/" + binlogPosition; } logger.info("Connected to " + hostname + ":" + port + " at " + position + " (" + (blocking ? "sid:" + serverId + ", " : "") + "cid:" + connectionId + ")"); } synchronized (lifecycleListeners) { for (LifecycleListener lifecycleListener : lifecycleListeners) { lifecycleListener.onConnect(this); } } if (keepAlive && !isKeepAliveThreadRunning()) { spawnKeepAliveThread(); } ensureEventDataDeserializer(EventType.ROTATE, RotateEventDataDeserializer.class); synchronized (gtidSetAccessLock) { if (gtidSet != null) { ensureEventDataDeserializer(EventType.GTID, GtidEventDataDeserializer.class); } } listenForEventPackets(); } #location 29 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code public void connect() throws IOException { if (!connectLock.tryLock()) { throw new IllegalStateException("BinaryLogClient is already connected"); } boolean notifyWhenDisconnected = false; try { try { channel = openChannel(); GreetingPacket greetingPacket = receiveGreeting(); authenticate(greetingPacket); connectionId = greetingPacket.getThreadId(); if (binlogFilename == null) { fetchBinlogFilenameAndPosition(); } if (binlogPosition < 4) { if (logger.isLoggable(Level.WARNING)) { logger.warning("Binary log position adjusted from " + binlogPosition + " to " + 4); } binlogPosition = 4; } ChecksumType checksumType = fetchBinlogChecksum(); if (checksumType != ChecksumType.NONE) { confirmSupportOfChecksum(checksumType); } requestBinaryLogStream(); } catch (IOException e) { disconnectChannel(); throw e; } connected = true; notifyWhenDisconnected = true; if (logger.isLoggable(Level.INFO)) { String position; synchronized (gtidSetAccessLock) { position = gtidSet != null ? gtidSet.toString() : binlogFilename + "/" + binlogPosition; } logger.info("Connected to " + hostname + ":" + port + " at " + position + " (" + (blocking ? "sid:" + serverId + ", " : "") + "cid:" + connectionId + ")"); } synchronized (lifecycleListeners) { for (LifecycleListener lifecycleListener : lifecycleListeners) { lifecycleListener.onConnect(this); } } if (keepAlive && !isKeepAliveThreadRunning()) { spawnKeepAliveThread(); } ensureEventDataDeserializer(EventType.ROTATE, RotateEventDataDeserializer.class); synchronized (gtidSetAccessLock) { if (gtidSet != null) { ensureEventDataDeserializer(EventType.GTID, GtidEventDataDeserializer.class); } } listenForEventPackets(); } finally { connectLock.unlock(); if (notifyWhenDisconnected) { synchronized (lifecycleListeners) { for (LifecycleListener lifecycleListener : lifecycleListeners) { lifecycleListener.onDisconnect(this); } } } } }
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"); } try { try { Socket socket = socketFactory != null ? socketFactory.createSocket() : new Socket(); socket.connect(new InetSocketAddress(hostname, port)); channel = new PacketChannel(socket); if (channel.getInputStream().peek() == -1) { throw new EOFException(); } } catch (IOException e) { throw new IOException("Failed to connect to MySQL on " + hostname + ":" + port + ". Please make sure it's running.", e); } GreetingPacket greetingPacket = new GreetingPacket(channel.read()); authenticate(greetingPacket.getScramble(), greetingPacket.getServerCollation()); if (binlogFilename == null) { fetchBinlogFilenameAndPosition(); } if (binlogPosition < 4) { if (logger.isLoggable(Level.WARNING)) { logger.warning("Binary log position adjusted from " + binlogPosition + " to " + 4); } binlogPosition = 4; } ChecksumType checksumType = fetchBinlogChecksum(); if (checksumType != ChecksumType.NONE) { confirmSupportOfChecksum(checksumType); } channel.write(new DumpBinaryLogCommand(serverId, binlogFilename, binlogPosition)); } catch (IOException e) { if (channel != null && channel.isOpen()) { channel.close(); } throw e; } connected = true; if (logger.isLoggable(Level.INFO)) { logger.info("Connected to " + hostname + ":" + port + " at " + binlogFilename + "/" + binlogPosition); } synchronized (lifecycleListeners) { for (LifecycleListener lifecycleListener : lifecycleListeners) { lifecycleListener.onConnect(this); } } if (keepAlive && !isKeepAliveThreadRunning()) { spawnKeepAliveThread(); } listenForEventPackets(); } #location 51 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code public void connect() throws IOException { if (connected) { throw new IllegalStateException("BinaryLogClient is already connected"); } try { try { Socket socket = socketFactory != null ? socketFactory.createSocket() : new Socket(); socket.connect(new InetSocketAddress(hostname, port)); channel = new PacketChannel(socket); if (channel.getInputStream().peek() == -1) { throw new EOFException(); } } catch (IOException e) { throw new IOException("Failed to connect to MySQL on " + hostname + ":" + port + ". Please make sure it's running.", e); } GreetingPacket greetingPacket = new GreetingPacket(channel.read()); authenticate(greetingPacket.getScramble(), greetingPacket.getServerCollation()); if (binlogFilename == null) { fetchBinlogFilenameAndPosition(); } if (binlogPosition < 4) { if (logger.isLoggable(Level.WARNING)) { logger.warning("Binary log position adjusted from " + binlogPosition + " to " + 4); } binlogPosition = 4; } ChecksumType checksumType = fetchBinlogChecksum(); if (checksumType != ChecksumType.NONE) { confirmSupportOfChecksum(checksumType); } channel.write(new DumpBinaryLogCommand(serverId, binlogFilename, binlogPosition)); } catch (IOException e) { if (channel != null && channel.isOpen()) { channel.close(); } throw e; } connected = true; if (logger.isLoggable(Level.INFO)) { logger.info("Connected to " + hostname + ":" + port + " at " + binlogFilename + "/" + binlogPosition); } synchronized (lifecycleListeners) { for (LifecycleListener lifecycleListener : lifecycleListeners) { lifecycleListener.onConnect(this); } } if (keepAlive && !isKeepAliveThreadRunning()) { spawnKeepAliveThread(); } EventDataDeserializer eventDataDeserializer = eventDeserializer.getEventDataDeserializer(EventType.ROTATE); if (eventDataDeserializer.getClass() != RotateEventDataDeserializer.class && eventDataDeserializer.getClass() != EventDeserializer.EventDataWrapper.Deserializer.class) { eventDeserializer.setEventDataDeserializer(EventType.ROTATE, new EventDeserializer.EventDataWrapper.Deserializer(new RotateEventDataDeserializer(), eventDataDeserializer)); } listenForEventPackets(); }
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 = socketFactory != null ? socketFactory.createSocket() : new Socket(); socket.connect(new InetSocketAddress(hostname, port)); channel = new PacketChannel(socket); if (channel.getInputStream().peek() == -1) { throw new EOFException(); } } catch (IOException e) { throw new IOException("Failed to connect to MySQL on " + hostname + ":" + port + ". Please make sure it's running.", e); } greetingPacket = receiveGreeting(); authenticate(greetingPacket); if (binlogFilename == null) { fetchBinlogFilenameAndPosition(); } if (binlogPosition < 4) { if (logger.isLoggable(Level.WARNING)) { logger.warning("Binary log position adjusted from " + binlogPosition + " to " + 4); } binlogPosition = 4; } ChecksumType checksumType = fetchBinlogChecksum(); if (checksumType != ChecksumType.NONE) { confirmSupportOfChecksum(checksumType); } requestBinaryLogStream(); } catch (IOException e) { if (channel != null && channel.isOpen()) { channel.close(); } throw e; } connected = true; connectionId = greetingPacket.getThreadId(); if (logger.isLoggable(Level.INFO)) { String position; synchronized (gtidSetAccessLock) { position = gtidSet != null ? gtidSet.toString() : binlogFilename + "/" + binlogPosition; } logger.info("Connected to " + hostname + ":" + port + " at " + position + " (" + (blocking ? "sid:" + serverId + ", " : "") + "cid:" + connectionId + ")"); } synchronized (lifecycleListeners) { for (LifecycleListener lifecycleListener : lifecycleListeners) { lifecycleListener.onConnect(this); } } if (keepAlive && !isKeepAliveThreadRunning()) { spawnKeepAliveThread(); } ensureEventDataDeserializer(EventType.ROTATE, RotateEventDataDeserializer.class); synchronized (gtidSetAccessLock) { if (gtidSet != null) { ensureEventDataDeserializer(EventType.GTID, GtidEventDataDeserializer.class); } } listenForEventPackets(); } #location 21 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code public void connect() throws IOException { if (!connectLock.tryLock()) { throw new IllegalStateException("BinaryLogClient is already connected"); } boolean notifyWhenDisconnected = false; try { try { channel = openChannel(); GreetingPacket greetingPacket = receiveGreeting(); authenticate(greetingPacket); connectionId = greetingPacket.getThreadId(); if (binlogFilename == null) { fetchBinlogFilenameAndPosition(); } if (binlogPosition < 4) { if (logger.isLoggable(Level.WARNING)) { logger.warning("Binary log position adjusted from " + binlogPosition + " to " + 4); } binlogPosition = 4; } ChecksumType checksumType = fetchBinlogChecksum(); if (checksumType != ChecksumType.NONE) { confirmSupportOfChecksum(checksumType); } requestBinaryLogStream(); } catch (IOException e) { disconnectChannel(); throw e; } connected = true; notifyWhenDisconnected = true; if (logger.isLoggable(Level.INFO)) { String position; synchronized (gtidSetAccessLock) { position = gtidSet != null ? gtidSet.toString() : binlogFilename + "/" + binlogPosition; } logger.info("Connected to " + hostname + ":" + port + " at " + position + " (" + (blocking ? "sid:" + serverId + ", " : "") + "cid:" + connectionId + ")"); } synchronized (lifecycleListeners) { for (LifecycleListener lifecycleListener : lifecycleListeners) { lifecycleListener.onConnect(this); } } if (keepAlive && !isKeepAliveThreadRunning()) { spawnKeepAliveThread(); } ensureEventDataDeserializer(EventType.ROTATE, RotateEventDataDeserializer.class); synchronized (gtidSetAccessLock) { if (gtidSet != null) { ensureEventDataDeserializer(EventType.GTID, GtidEventDataDeserializer.class); } } listenForEventPackets(); } finally { connectLock.unlock(); if (notifyWhenDisconnected) { synchronized (lifecycleListeners) { for (LifecycleListener lifecycleListener : lifecycleListeners) { lifecycleListener.onDisconnect(this); } } } } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public void disconnect() throws IOException { shutdownLock.lock(); try { if (isKeepAliveThreadRunning()) { keepAliveThreadExecutor.shutdownNow(); } disconnectChannel(); } finally { shutdownLock.unlock(); } if (isKeepAliveThreadRunning()) { waitForKeepAliveThreadToBeTerminated(); } } #location 7 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code public void disconnect() throws IOException { terminateKeepAliveThread(); terminateConnect(); }
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 = socketFactory != null ? socketFactory.createSocket() : new Socket(); socket.connect(new InetSocketAddress(hostname, port)); channel = new PacketChannel(socket); if (channel.getInputStream().peek() == -1) { throw new EOFException(); } } catch (IOException e) { throw new IOException("Failed to connect to MySQL on " + hostname + ":" + port + ". Please make sure it's running.", e); } greetingPacket = receiveGreeting(); authenticate(greetingPacket); if (binlogFilename == null) { fetchBinlogFilenameAndPosition(); } if (binlogPosition < 4) { if (logger.isLoggable(Level.WARNING)) { logger.warning("Binary log position adjusted from " + binlogPosition + " to " + 4); } binlogPosition = 4; } ChecksumType checksumType = fetchBinlogChecksum(); if (checksumType != ChecksumType.NONE) { confirmSupportOfChecksum(checksumType); } requestBinaryLogStream(); } catch (IOException e) { if (channel != null && channel.isOpen()) { channel.close(); } throw e; } connected = true; connectionId = greetingPacket.getThreadId(); if (logger.isLoggable(Level.INFO)) { String position; synchronized (gtidSetAccessLock) { position = gtidSet != null ? gtidSet.toString() : binlogFilename + "/" + binlogPosition; } logger.info("Connected to " + hostname + ":" + port + " at " + position + " (" + (blocking ? "sid:" + serverId + ", " : "") + "cid:" + connectionId + ")"); } synchronized (lifecycleListeners) { for (LifecycleListener lifecycleListener : lifecycleListeners) { lifecycleListener.onConnect(this); } } if (keepAlive && !isKeepAliveThreadRunning()) { spawnKeepAliveThread(); } ensureEventDataDeserializer(EventType.ROTATE, RotateEventDataDeserializer.class); synchronized (gtidSetAccessLock) { if (gtidSet != null) { ensureEventDataDeserializer(EventType.GTID, GtidEventDataDeserializer.class); } } listenForEventPackets(); } #location 33 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code public void connect() throws IOException { if (!connectLock.tryLock()) { throw new IllegalStateException("BinaryLogClient is already connected"); } boolean notifyWhenDisconnected = false; try { try { channel = openChannel(); GreetingPacket greetingPacket = receiveGreeting(); authenticate(greetingPacket); connectionId = greetingPacket.getThreadId(); if (binlogFilename == null) { fetchBinlogFilenameAndPosition(); } if (binlogPosition < 4) { if (logger.isLoggable(Level.WARNING)) { logger.warning("Binary log position adjusted from " + binlogPosition + " to " + 4); } binlogPosition = 4; } ChecksumType checksumType = fetchBinlogChecksum(); if (checksumType != ChecksumType.NONE) { confirmSupportOfChecksum(checksumType); } requestBinaryLogStream(); } catch (IOException e) { disconnectChannel(); throw e; } connected = true; notifyWhenDisconnected = true; if (logger.isLoggable(Level.INFO)) { String position; synchronized (gtidSetAccessLock) { position = gtidSet != null ? gtidSet.toString() : binlogFilename + "/" + binlogPosition; } logger.info("Connected to " + hostname + ":" + port + " at " + position + " (" + (blocking ? "sid:" + serverId + ", " : "") + "cid:" + connectionId + ")"); } synchronized (lifecycleListeners) { for (LifecycleListener lifecycleListener : lifecycleListeners) { lifecycleListener.onConnect(this); } } if (keepAlive && !isKeepAliveThreadRunning()) { spawnKeepAliveThread(); } ensureEventDataDeserializer(EventType.ROTATE, RotateEventDataDeserializer.class); synchronized (gtidSetAccessLock) { if (gtidSet != null) { ensureEventDataDeserializer(EventType.GTID, GtidEventDataDeserializer.class); } } listenForEventPackets(); } finally { connectLock.unlock(); if (notifyWhenDisconnected) { synchronized (lifecycleListeners) { for (LifecycleListener lifecycleListener : lifecycleListeners) { lifecycleListener.onDisconnect(this); } } } } }
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 = socketFactory != null ? socketFactory.createSocket() : new Socket(); socket.connect(new InetSocketAddress(hostname, port)); channel = new PacketChannel(socket); if (channel.getInputStream().peek() == -1) { throw new EOFException(); } } catch (IOException e) { throw new IOException("Failed to connect to MySQL on " + hostname + ":" + port + ". Please make sure it's running.", e); } greetingPacket = receiveGreeting(); authenticate(greetingPacket); if (binlogFilename == null) { fetchBinlogFilenameAndPosition(); } if (binlogPosition < 4) { if (logger.isLoggable(Level.WARNING)) { logger.warning("Binary log position adjusted from " + binlogPosition + " to " + 4); } binlogPosition = 4; } ChecksumType checksumType = fetchBinlogChecksum(); if (checksumType != ChecksumType.NONE) { confirmSupportOfChecksum(checksumType); } requestBinaryLogStream(); } catch (IOException e) { if (channel != null && channel.isOpen()) { channel.close(); } throw e; } connected = true; connectionId = greetingPacket.getThreadId(); if (logger.isLoggable(Level.INFO)) { String position; synchronized (gtidSetAccessLock) { position = gtidSet != null ? gtidSet.toString() : binlogFilename + "/" + binlogPosition; } logger.info("Connected to " + hostname + ":" + port + " at " + position + " (" + (blocking ? "sid:" + serverId + ", " : "") + "cid:" + connectionId + ")"); } synchronized (lifecycleListeners) { for (LifecycleListener lifecycleListener : lifecycleListeners) { lifecycleListener.onConnect(this); } } if (keepAlive && !isKeepAliveThreadRunning()) { spawnKeepAliveThread(); } ensureEventDataDeserializer(EventType.ROTATE, RotateEventDataDeserializer.class); synchronized (gtidSetAccessLock) { if (gtidSet != null) { ensureEventDataDeserializer(EventType.GTID, GtidEventDataDeserializer.class); } } listenForEventPackets(); } #location 58 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code public void connect() throws IOException { if (!connectLock.tryLock()) { throw new IllegalStateException("BinaryLogClient is already connected"); } boolean notifyWhenDisconnected = false; try { try { channel = openChannel(); GreetingPacket greetingPacket = receiveGreeting(); authenticate(greetingPacket); connectionId = greetingPacket.getThreadId(); if (binlogFilename == null) { fetchBinlogFilenameAndPosition(); } if (binlogPosition < 4) { if (logger.isLoggable(Level.WARNING)) { logger.warning("Binary log position adjusted from " + binlogPosition + " to " + 4); } binlogPosition = 4; } ChecksumType checksumType = fetchBinlogChecksum(); if (checksumType != ChecksumType.NONE) { confirmSupportOfChecksum(checksumType); } requestBinaryLogStream(); } catch (IOException e) { disconnectChannel(); throw e; } connected = true; notifyWhenDisconnected = true; if (logger.isLoggable(Level.INFO)) { String position; synchronized (gtidSetAccessLock) { position = gtidSet != null ? gtidSet.toString() : binlogFilename + "/" + binlogPosition; } logger.info("Connected to " + hostname + ":" + port + " at " + position + " (" + (blocking ? "sid:" + serverId + ", " : "") + "cid:" + connectionId + ")"); } synchronized (lifecycleListeners) { for (LifecycleListener lifecycleListener : lifecycleListeners) { lifecycleListener.onConnect(this); } } if (keepAlive && !isKeepAliveThreadRunning()) { spawnKeepAliveThread(); } ensureEventDataDeserializer(EventType.ROTATE, RotateEventDataDeserializer.class); synchronized (gtidSetAccessLock) { if (gtidSet != null) { ensureEventDataDeserializer(EventType.GTID, GtidEventDataDeserializer.class); } } listenForEventPackets(); } finally { connectLock.unlock(); if (notifyWhenDisconnected) { synchronized (lifecycleListeners) { for (LifecycleListener lifecycleListener : lifecycleListeners) { lifecycleListener.onDisconnect(this); } } } } }
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 = socketFactory != null ? socketFactory.createSocket() : new Socket(); socket.connect(new InetSocketAddress(hostname, port)); channel = new PacketChannel(socket); if (channel.getInputStream().peek() == -1) { throw new EOFException(); } } catch (IOException e) { throw new IOException("Failed to connect to MySQL on " + hostname + ":" + port + ". Please make sure it's running.", e); } greetingPacket = receiveGreeting(); authenticate(greetingPacket); if (binlogFilename == null) { fetchBinlogFilenameAndPosition(); } if (binlogPosition < 4) { if (logger.isLoggable(Level.WARNING)) { logger.warning("Binary log position adjusted from " + binlogPosition + " to " + 4); } binlogPosition = 4; } ChecksumType checksumType = fetchBinlogChecksum(); if (checksumType != ChecksumType.NONE) { confirmSupportOfChecksum(checksumType); } requestBinaryLogStream(); } catch (IOException e) { if (channel != null && channel.isOpen()) { channel.close(); } throw e; } connected = true; connectionId = greetingPacket.getThreadId(); if (logger.isLoggable(Level.INFO)) { String position; synchronized (gtidSetAccessLock) { position = gtidSet != null ? gtidSet.toString() : binlogFilename + "/" + binlogPosition; } logger.info("Connected to " + hostname + ":" + port + " at " + position + " (" + (blocking ? "sid:" + serverId + ", " : "") + "cid:" + connectionId + ")"); } synchronized (lifecycleListeners) { for (LifecycleListener lifecycleListener : lifecycleListeners) { lifecycleListener.onConnect(this); } } if (keepAlive && !isKeepAliveThreadRunning()) { spawnKeepAliveThread(); } ensureEventDataDeserializer(EventType.ROTATE, RotateEventDataDeserializer.class); synchronized (gtidSetAccessLock) { if (gtidSet != null) { ensureEventDataDeserializer(EventType.GTID, GtidEventDataDeserializer.class); } } listenForEventPackets(); } #location 11 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code public void connect() throws IOException { if (!connectLock.tryLock()) { throw new IllegalStateException("BinaryLogClient is already connected"); } boolean notifyWhenDisconnected = false; try { try { channel = openChannel(); GreetingPacket greetingPacket = receiveGreeting(); authenticate(greetingPacket); connectionId = greetingPacket.getThreadId(); if (binlogFilename == null) { fetchBinlogFilenameAndPosition(); } if (binlogPosition < 4) { if (logger.isLoggable(Level.WARNING)) { logger.warning("Binary log position adjusted from " + binlogPosition + " to " + 4); } binlogPosition = 4; } ChecksumType checksumType = fetchBinlogChecksum(); if (checksumType != ChecksumType.NONE) { confirmSupportOfChecksum(checksumType); } requestBinaryLogStream(); } catch (IOException e) { disconnectChannel(); throw e; } connected = true; notifyWhenDisconnected = true; if (logger.isLoggable(Level.INFO)) { String position; synchronized (gtidSetAccessLock) { position = gtidSet != null ? gtidSet.toString() : binlogFilename + "/" + binlogPosition; } logger.info("Connected to " + hostname + ":" + port + " at " + position + " (" + (blocking ? "sid:" + serverId + ", " : "") + "cid:" + connectionId + ")"); } synchronized (lifecycleListeners) { for (LifecycleListener lifecycleListener : lifecycleListeners) { lifecycleListener.onConnect(this); } } if (keepAlive && !isKeepAliveThreadRunning()) { spawnKeepAliveThread(); } ensureEventDataDeserializer(EventType.ROTATE, RotateEventDataDeserializer.class); synchronized (gtidSetAccessLock) { if (gtidSet != null) { ensureEventDataDeserializer(EventType.GTID, GtidEventDataDeserializer.class); } } listenForEventPackets(); } finally { connectLock.unlock(); if (notifyWhenDisconnected) { synchronized (lifecycleListeners) { for (LifecycleListener lifecycleListener : lifecycleListeners) { lifecycleListener.onDisconnect(this); } } } } }
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 = socketFactory != null ? socketFactory.createSocket() : new Socket(); socket.connect(new InetSocketAddress(hostname, port)); channel = new PacketChannel(socket); if (channel.getInputStream().peek() == -1) { throw new EOFException(); } } catch (IOException e) { throw new IOException("Failed to connect to MySQL on " + hostname + ":" + port + ". Please make sure it's running.", e); } greetingPacket = receiveGreeting(); authenticate(greetingPacket); if (binlogFilename == null) { fetchBinlogFilenameAndPosition(); } if (binlogPosition < 4) { if (logger.isLoggable(Level.WARNING)) { logger.warning("Binary log position adjusted from " + binlogPosition + " to " + 4); } binlogPosition = 4; } ChecksumType checksumType = fetchBinlogChecksum(); if (checksumType != ChecksumType.NONE) { confirmSupportOfChecksum(checksumType); } requestBinaryLogStream(); } catch (IOException e) { if (channel != null && channel.isOpen()) { channel.close(); } throw e; } connected = true; connectionId = greetingPacket.getThreadId(); if (logger.isLoggable(Level.INFO)) { String position; synchronized (gtidSetAccessLock) { position = gtidSet != null ? gtidSet.toString() : binlogFilename + "/" + binlogPosition; } logger.info("Connected to " + hostname + ":" + port + " at " + position + " (" + (blocking ? "sid:" + serverId + ", " : "") + "cid:" + connectionId + ")"); } synchronized (lifecycleListeners) { for (LifecycleListener lifecycleListener : lifecycleListeners) { lifecycleListener.onConnect(this); } } if (keepAlive && !isKeepAliveThreadRunning()) { spawnKeepAliveThread(); } ensureEventDataDeserializer(EventType.ROTATE, RotateEventDataDeserializer.class); synchronized (gtidSetAccessLock) { if (gtidSet != null) { ensureEventDataDeserializer(EventType.GTID, GtidEventDataDeserializer.class); } } listenForEventPackets(); } #location 47 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code public void connect() throws IOException { if (!connectLock.tryLock()) { throw new IllegalStateException("BinaryLogClient is already connected"); } boolean notifyWhenDisconnected = false; try { try { channel = openChannel(); GreetingPacket greetingPacket = receiveGreeting(); authenticate(greetingPacket); connectionId = greetingPacket.getThreadId(); if (binlogFilename == null) { fetchBinlogFilenameAndPosition(); } if (binlogPosition < 4) { if (logger.isLoggable(Level.WARNING)) { logger.warning("Binary log position adjusted from " + binlogPosition + " to " + 4); } binlogPosition = 4; } ChecksumType checksumType = fetchBinlogChecksum(); if (checksumType != ChecksumType.NONE) { confirmSupportOfChecksum(checksumType); } requestBinaryLogStream(); } catch (IOException e) { disconnectChannel(); throw e; } connected = true; notifyWhenDisconnected = true; if (logger.isLoggable(Level.INFO)) { String position; synchronized (gtidSetAccessLock) { position = gtidSet != null ? gtidSet.toString() : binlogFilename + "/" + binlogPosition; } logger.info("Connected to " + hostname + ":" + port + " at " + position + " (" + (blocking ? "sid:" + serverId + ", " : "") + "cid:" + connectionId + ")"); } synchronized (lifecycleListeners) { for (LifecycleListener lifecycleListener : lifecycleListeners) { lifecycleListener.onConnect(this); } } if (keepAlive && !isKeepAliveThreadRunning()) { spawnKeepAliveThread(); } ensureEventDataDeserializer(EventType.ROTATE, RotateEventDataDeserializer.class); synchronized (gtidSetAccessLock) { if (gtidSet != null) { ensureEventDataDeserializer(EventType.GTID, GtidEventDataDeserializer.class); } } listenForEventPackets(); } finally { connectLock.unlock(); if (notifyWhenDisconnected) { synchronized (lifecycleListeners) { for (LifecycleListener lifecycleListener : lifecycleListeners) { lifecycleListener.onDisconnect(this); } } } } }
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 = socketFactory != null ? socketFactory.createSocket() : new Socket(); socket.connect(new InetSocketAddress(hostname, port)); channel = new PacketChannel(socket); if (channel.getInputStream().peek() == -1) { throw new EOFException(); } } catch (IOException e) { throw new IOException("Failed to connect to MySQL on " + hostname + ":" + port + ". Please make sure it's running.", e); } greetingPacket = receiveGreeting(); authenticate(greetingPacket); if (binlogFilename == null) { fetchBinlogFilenameAndPosition(); } if (binlogPosition < 4) { if (logger.isLoggable(Level.WARNING)) { logger.warning("Binary log position adjusted from " + binlogPosition + " to " + 4); } binlogPosition = 4; } ChecksumType checksumType = fetchBinlogChecksum(); if (checksumType != ChecksumType.NONE) { confirmSupportOfChecksum(checksumType); } requestBinaryLogStream(); } catch (IOException e) { if (channel != null && channel.isOpen()) { channel.close(); } throw e; } connected = true; connectionId = greetingPacket.getThreadId(); if (logger.isLoggable(Level.INFO)) { String position; synchronized (gtidSetAccessLock) { position = gtidSet != null ? gtidSet.toString() : binlogFilename + "/" + binlogPosition; } logger.info("Connected to " + hostname + ":" + port + " at " + position + " (" + (blocking ? "sid:" + serverId + ", " : "") + "cid:" + connectionId + ")"); } synchronized (lifecycleListeners) { for (LifecycleListener lifecycleListener : lifecycleListeners) { lifecycleListener.onConnect(this); } } if (keepAlive && !isKeepAliveThreadRunning()) { spawnKeepAliveThread(); } ensureEventDataDeserializer(EventType.ROTATE, RotateEventDataDeserializer.class); synchronized (gtidSetAccessLock) { if (gtidSet != null) { ensureEventDataDeserializer(EventType.GTID, GtidEventDataDeserializer.class); } } listenForEventPackets(); } #location 64 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code public void connect() throws IOException { if (!connectLock.tryLock()) { throw new IllegalStateException("BinaryLogClient is already connected"); } boolean notifyWhenDisconnected = false; try { try { channel = openChannel(); GreetingPacket greetingPacket = receiveGreeting(); authenticate(greetingPacket); connectionId = greetingPacket.getThreadId(); if (binlogFilename == null) { fetchBinlogFilenameAndPosition(); } if (binlogPosition < 4) { if (logger.isLoggable(Level.WARNING)) { logger.warning("Binary log position adjusted from " + binlogPosition + " to " + 4); } binlogPosition = 4; } ChecksumType checksumType = fetchBinlogChecksum(); if (checksumType != ChecksumType.NONE) { confirmSupportOfChecksum(checksumType); } requestBinaryLogStream(); } catch (IOException e) { disconnectChannel(); throw e; } connected = true; notifyWhenDisconnected = true; if (logger.isLoggable(Level.INFO)) { String position; synchronized (gtidSetAccessLock) { position = gtidSet != null ? gtidSet.toString() : binlogFilename + "/" + binlogPosition; } logger.info("Connected to " + hostname + ":" + port + " at " + position + " (" + (blocking ? "sid:" + serverId + ", " : "") + "cid:" + connectionId + ")"); } synchronized (lifecycleListeners) { for (LifecycleListener lifecycleListener : lifecycleListeners) { lifecycleListener.onConnect(this); } } if (keepAlive && !isKeepAliveThreadRunning()) { spawnKeepAliveThread(); } ensureEventDataDeserializer(EventType.ROTATE, RotateEventDataDeserializer.class); synchronized (gtidSetAccessLock) { if (gtidSet != null) { ensureEventDataDeserializer(EventType.GTID, GtidEventDataDeserializer.class); } } listenForEventPackets(); } finally { connectLock.unlock(); if (notifyWhenDisconnected) { synchronized (lifecycleListeners) { for (LifecycleListener lifecycleListener : lifecycleListeners) { lifecycleListener.onDisconnect(this); } } } } }
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 = socketFactory != null ? socketFactory.createSocket() : new Socket(); socket.connect(new InetSocketAddress(hostname, port)); channel = new PacketChannel(socket); if (channel.getInputStream().peek() == -1) { throw new EOFException(); } } catch (IOException e) { throw new IOException("Failed to connect to MySQL on " + hostname + ":" + port + ". Please make sure it's running.", e); } greetingPacket = receiveGreeting(); authenticate(greetingPacket); if (binlogFilename == null) { fetchBinlogFilenameAndPosition(); } if (binlogPosition < 4) { if (logger.isLoggable(Level.WARNING)) { logger.warning("Binary log position adjusted from " + binlogPosition + " to " + 4); } binlogPosition = 4; } ChecksumType checksumType = fetchBinlogChecksum(); if (checksumType != ChecksumType.NONE) { confirmSupportOfChecksum(checksumType); } requestBinaryLogStream(); } catch (IOException e) { if (channel != null && channel.isOpen()) { channel.close(); } throw e; } connected = true; connectionId = greetingPacket.getThreadId(); if (logger.isLoggable(Level.INFO)) { String position; synchronized (gtidSetAccessLock) { position = gtidSet != null ? gtidSet.toString() : binlogFilename + "/" + binlogPosition; } logger.info("Connected to " + hostname + ":" + port + " at " + position + " (" + (blocking ? "sid:" + serverId + ", " : "") + "cid:" + connectionId + ")"); } synchronized (lifecycleListeners) { for (LifecycleListener lifecycleListener : lifecycleListeners) { lifecycleListener.onConnect(this); } } if (keepAlive && !isKeepAliveThreadRunning()) { spawnKeepAliveThread(); } ensureEventDataDeserializer(EventType.ROTATE, RotateEventDataDeserializer.class); synchronized (gtidSetAccessLock) { if (gtidSet != null) { ensureEventDataDeserializer(EventType.GTID, GtidEventDataDeserializer.class); } } listenForEventPackets(); } #location 19 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code public void connect() throws IOException { if (!connectLock.tryLock()) { throw new IllegalStateException("BinaryLogClient is already connected"); } boolean notifyWhenDisconnected = false; try { try { channel = openChannel(); GreetingPacket greetingPacket = receiveGreeting(); authenticate(greetingPacket); connectionId = greetingPacket.getThreadId(); if (binlogFilename == null) { fetchBinlogFilenameAndPosition(); } if (binlogPosition < 4) { if (logger.isLoggable(Level.WARNING)) { logger.warning("Binary log position adjusted from " + binlogPosition + " to " + 4); } binlogPosition = 4; } ChecksumType checksumType = fetchBinlogChecksum(); if (checksumType != ChecksumType.NONE) { confirmSupportOfChecksum(checksumType); } requestBinaryLogStream(); } catch (IOException e) { disconnectChannel(); throw e; } connected = true; notifyWhenDisconnected = true; if (logger.isLoggable(Level.INFO)) { String position; synchronized (gtidSetAccessLock) { position = gtidSet != null ? gtidSet.toString() : binlogFilename + "/" + binlogPosition; } logger.info("Connected to " + hostname + ":" + port + " at " + position + " (" + (blocking ? "sid:" + serverId + ", " : "") + "cid:" + connectionId + ")"); } synchronized (lifecycleListeners) { for (LifecycleListener lifecycleListener : lifecycleListeners) { lifecycleListener.onConnect(this); } } if (keepAlive && !isKeepAliveThreadRunning()) { spawnKeepAliveThread(); } ensureEventDataDeserializer(EventType.ROTATE, RotateEventDataDeserializer.class); synchronized (gtidSetAccessLock) { if (gtidSet != null) { ensureEventDataDeserializer(EventType.GTID, GtidEventDataDeserializer.class); } } listenForEventPackets(); } finally { connectLock.unlock(); if (notifyWhenDisconnected) { synchronized (lifecycleListeners) { for (LifecycleListener lifecycleListener : lifecycleListeners) { lifecycleListener.onDisconnect(this); } } } } }
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 = socketFactory != null ? socketFactory.createSocket() : new Socket(); socket.connect(new InetSocketAddress(hostname, port)); channel = new PacketChannel(socket); if (channel.getInputStream().peek() == -1) { throw new EOFException(); } } catch (IOException e) { throw new IOException("Failed to connect to MySQL on " + hostname + ":" + port + ". Please make sure it's running.", e); } greetingPacket = receiveGreeting(); authenticate(greetingPacket); if (binlogFilename == null) { fetchBinlogFilenameAndPosition(); } if (binlogPosition < 4) { if (logger.isLoggable(Level.WARNING)) { logger.warning("Binary log position adjusted from " + binlogPosition + " to " + 4); } binlogPosition = 4; } ChecksumType checksumType = fetchBinlogChecksum(); if (checksumType != ChecksumType.NONE) { confirmSupportOfChecksum(checksumType); } requestBinaryLogStream(); } catch (IOException e) { if (channel != null && channel.isOpen()) { channel.close(); } throw e; } connected = true; connectionId = greetingPacket.getThreadId(); if (logger.isLoggable(Level.INFO)) { String position; synchronized (gtidSetAccessLock) { position = gtidSet != null ? gtidSet.toString() : binlogFilename + "/" + binlogPosition; } logger.info("Connected to " + hostname + ":" + port + " at " + position + " (" + (blocking ? "sid:" + serverId + ", " : "") + "cid:" + connectionId + ")"); } synchronized (lifecycleListeners) { for (LifecycleListener lifecycleListener : lifecycleListeners) { lifecycleListener.onConnect(this); } } if (keepAlive && !isKeepAliveThreadRunning()) { spawnKeepAliveThread(); } ensureEventDataDeserializer(EventType.ROTATE, RotateEventDataDeserializer.class); synchronized (gtidSetAccessLock) { if (gtidSet != null) { ensureEventDataDeserializer(EventType.GTID, GtidEventDataDeserializer.class); } } listenForEventPackets(); } #location 10 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code public void connect() throws IOException { if (!connectLock.tryLock()) { throw new IllegalStateException("BinaryLogClient is already connected"); } boolean notifyWhenDisconnected = false; try { try { channel = openChannel(); GreetingPacket greetingPacket = receiveGreeting(); authenticate(greetingPacket); connectionId = greetingPacket.getThreadId(); if (binlogFilename == null) { fetchBinlogFilenameAndPosition(); } if (binlogPosition < 4) { if (logger.isLoggable(Level.WARNING)) { logger.warning("Binary log position adjusted from " + binlogPosition + " to " + 4); } binlogPosition = 4; } ChecksumType checksumType = fetchBinlogChecksum(); if (checksumType != ChecksumType.NONE) { confirmSupportOfChecksum(checksumType); } requestBinaryLogStream(); } catch (IOException e) { disconnectChannel(); throw e; } connected = true; notifyWhenDisconnected = true; if (logger.isLoggable(Level.INFO)) { String position; synchronized (gtidSetAccessLock) { position = gtidSet != null ? gtidSet.toString() : binlogFilename + "/" + binlogPosition; } logger.info("Connected to " + hostname + ":" + port + " at " + position + " (" + (blocking ? "sid:" + serverId + ", " : "") + "cid:" + connectionId + ")"); } synchronized (lifecycleListeners) { for (LifecycleListener lifecycleListener : lifecycleListeners) { lifecycleListener.onConnect(this); } } if (keepAlive && !isKeepAliveThreadRunning()) { spawnKeepAliveThread(); } ensureEventDataDeserializer(EventType.ROTATE, RotateEventDataDeserializer.class); synchronized (gtidSetAccessLock) { if (gtidSet != null) { ensureEventDataDeserializer(EventType.GTID, GtidEventDataDeserializer.class); } } listenForEventPackets(); } finally { connectLock.unlock(); if (notifyWhenDisconnected) { synchronized (lifecycleListeners) { for (LifecycleListener lifecycleListener : lifecycleListeners) { lifecycleListener.onDisconnect(this); } } } } }
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 = socketFactory != null ? socketFactory.createSocket() : new Socket(); socket.connect(new InetSocketAddress(hostname, port)); channel = new PacketChannel(socket); if (channel.getInputStream().peek() == -1) { throw new EOFException(); } } catch (IOException e) { throw new IOException("Failed to connect to MySQL on " + hostname + ":" + port + ". Please make sure it's running.", e); } greetingPacket = receiveGreeting(); authenticate(greetingPacket); if (binlogFilename == null) { fetchBinlogFilenameAndPosition(); } if (binlogPosition < 4) { if (logger.isLoggable(Level.WARNING)) { logger.warning("Binary log position adjusted from " + binlogPosition + " to " + 4); } binlogPosition = 4; } ChecksumType checksumType = fetchBinlogChecksum(); if (checksumType != ChecksumType.NONE) { confirmSupportOfChecksum(checksumType); } requestBinaryLogStream(); } catch (IOException e) { if (channel != null && channel.isOpen()) { channel.close(); } throw e; } connected = true; connectionId = greetingPacket.getThreadId(); if (logger.isLoggable(Level.INFO)) { String position; synchronized (gtidSetAccessLock) { position = gtidSet != null ? gtidSet.toString() : binlogFilename + "/" + binlogPosition; } logger.info("Connected to " + hostname + ":" + port + " at " + position + " (" + (blocking ? "sid:" + serverId + ", " : "") + "cid:" + connectionId + ")"); } synchronized (lifecycleListeners) { for (LifecycleListener lifecycleListener : lifecycleListeners) { lifecycleListener.onConnect(this); } } if (keepAlive && !isKeepAliveThreadRunning()) { spawnKeepAliveThread(); } ensureEventDataDeserializer(EventType.ROTATE, RotateEventDataDeserializer.class); synchronized (gtidSetAccessLock) { if (gtidSet != null) { ensureEventDataDeserializer(EventType.GTID, GtidEventDataDeserializer.class); } } listenForEventPackets(); } #location 55 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code public void connect() throws IOException { if (!connectLock.tryLock()) { throw new IllegalStateException("BinaryLogClient is already connected"); } boolean notifyWhenDisconnected = false; try { try { channel = openChannel(); GreetingPacket greetingPacket = receiveGreeting(); authenticate(greetingPacket); connectionId = greetingPacket.getThreadId(); if (binlogFilename == null) { fetchBinlogFilenameAndPosition(); } if (binlogPosition < 4) { if (logger.isLoggable(Level.WARNING)) { logger.warning("Binary log position adjusted from " + binlogPosition + " to " + 4); } binlogPosition = 4; } ChecksumType checksumType = fetchBinlogChecksum(); if (checksumType != ChecksumType.NONE) { confirmSupportOfChecksum(checksumType); } requestBinaryLogStream(); } catch (IOException e) { disconnectChannel(); throw e; } connected = true; notifyWhenDisconnected = true; if (logger.isLoggable(Level.INFO)) { String position; synchronized (gtidSetAccessLock) { position = gtidSet != null ? gtidSet.toString() : binlogFilename + "/" + binlogPosition; } logger.info("Connected to " + hostname + ":" + port + " at " + position + " (" + (blocking ? "sid:" + serverId + ", " : "") + "cid:" + connectionId + ")"); } synchronized (lifecycleListeners) { for (LifecycleListener lifecycleListener : lifecycleListeners) { lifecycleListener.onConnect(this); } } if (keepAlive && !isKeepAliveThreadRunning()) { spawnKeepAliveThread(); } ensureEventDataDeserializer(EventType.ROTATE, RotateEventDataDeserializer.class); synchronized (gtidSetAccessLock) { if (gtidSet != null) { ensureEventDataDeserializer(EventType.GTID, GtidEventDataDeserializer.class); } } listenForEventPackets(); } finally { connectLock.unlock(); if (notifyWhenDisconnected) { synchronized (lifecycleListeners) { for (LifecycleListener lifecycleListener : lifecycleListeners) { lifecycleListener.onDisconnect(this); } } } } }
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 = socketFactory != null ? socketFactory.createSocket() : new Socket(); socket.connect(new InetSocketAddress(hostname, port)); channel = new PacketChannel(socket); if (channel.getInputStream().peek() == -1) { throw new EOFException(); } } catch (IOException e) { throw new IOException("Failed to connect to MySQL on " + hostname + ":" + port + ". Please make sure it's running.", e); } greetingPacket = receiveGreeting(); authenticate(greetingPacket); if (binlogFilename == null) { fetchBinlogFilenameAndPosition(); } if (binlogPosition < 4) { if (logger.isLoggable(Level.WARNING)) { logger.warning("Binary log position adjusted from " + binlogPosition + " to " + 4); } binlogPosition = 4; } ChecksumType checksumType = fetchBinlogChecksum(); if (checksumType != ChecksumType.NONE) { confirmSupportOfChecksum(checksumType); } requestBinaryLogStream(); } catch (IOException e) { if (channel != null && channel.isOpen()) { channel.close(); } throw e; } connected = true; connectionId = greetingPacket.getThreadId(); if (logger.isLoggable(Level.INFO)) { String position; synchronized (gtidSetAccessLock) { position = gtidSet != null ? gtidSet.toString() : binlogFilename + "/" + binlogPosition; } logger.info("Connected to " + hostname + ":" + port + " at " + position + " (" + (blocking ? "sid:" + serverId + ", " : "") + "cid:" + connectionId + ")"); } synchronized (lifecycleListeners) { for (LifecycleListener lifecycleListener : lifecycleListeners) { lifecycleListener.onConnect(this); } } if (keepAlive && !isKeepAliveThreadRunning()) { spawnKeepAliveThread(); } ensureEventDataDeserializer(EventType.ROTATE, RotateEventDataDeserializer.class); synchronized (gtidSetAccessLock) { if (gtidSet != null) { ensureEventDataDeserializer(EventType.GTID, GtidEventDataDeserializer.class); } } listenForEventPackets(); } #location 18 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code public void connect() throws IOException { if (!connectLock.tryLock()) { throw new IllegalStateException("BinaryLogClient is already connected"); } boolean notifyWhenDisconnected = false; try { try { channel = openChannel(); GreetingPacket greetingPacket = receiveGreeting(); authenticate(greetingPacket); connectionId = greetingPacket.getThreadId(); if (binlogFilename == null) { fetchBinlogFilenameAndPosition(); } if (binlogPosition < 4) { if (logger.isLoggable(Level.WARNING)) { logger.warning("Binary log position adjusted from " + binlogPosition + " to " + 4); } binlogPosition = 4; } ChecksumType checksumType = fetchBinlogChecksum(); if (checksumType != ChecksumType.NONE) { confirmSupportOfChecksum(checksumType); } requestBinaryLogStream(); } catch (IOException e) { disconnectChannel(); throw e; } connected = true; notifyWhenDisconnected = true; if (logger.isLoggable(Level.INFO)) { String position; synchronized (gtidSetAccessLock) { position = gtidSet != null ? gtidSet.toString() : binlogFilename + "/" + binlogPosition; } logger.info("Connected to " + hostname + ":" + port + " at " + position + " (" + (blocking ? "sid:" + serverId + ", " : "") + "cid:" + connectionId + ")"); } synchronized (lifecycleListeners) { for (LifecycleListener lifecycleListener : lifecycleListeners) { lifecycleListener.onConnect(this); } } if (keepAlive && !isKeepAliveThreadRunning()) { spawnKeepAliveThread(); } ensureEventDataDeserializer(EventType.ROTATE, RotateEventDataDeserializer.class); synchronized (gtidSetAccessLock) { if (gtidSet != null) { ensureEventDataDeserializer(EventType.GTID, GtidEventDataDeserializer.class); } } listenForEventPackets(); } finally { connectLock.unlock(); if (notifyWhenDisconnected) { synchronized (lifecycleListeners) { for (LifecycleListener lifecycleListener : lifecycleListeners) { lifecycleListener.onDisconnect(this); } } } } }
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/mysql-bin.sakila.gz")), eventDeserializer); readAll(reader, 1462); } #location 4 #vulnerability type RESOURCE_LEAK
#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"), eventDeserializer); readAll(reader, 191); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public void disconnect() throws IOException { try { connected = false; if (channel != null) { channel.close(); } } finally { synchronized (lifecycleListeners) { for (LifecycleListener lifecycleListener : lifecycleListeners) { lifecycleListener.onDisconnect(this); } } } } #location 5 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code public void disconnect() throws IOException { shutdownLock.lock(); try { if (isKeepAliveThreadRunning()) { keepAliveThreadExecutor.shutdownNow(); } disconnectChannel(); } finally { shutdownLock.unlock(); } if (isKeepAliveThreadRunning()) { waitForKeepAliveThreadToBeTerminated(); } }
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()); frequencyAnalyzer.setMinWordLength(cliParameters.getMinWordLength()); frequencyAnalyzer.setStopWords(cliParameters.getStopWords()); frequencyAnalyzer.setCharacterEncoding(cliParameters.getCharacterEncoding()); for (final NormalizerType normalizer : cliParameters.getNormalizers()) { frequencyAnalyzer.setNormalizer(buildNormalizer(normalizer)); } frequencyAnalyzer.setWordTokenizer(buildTokenizer()); return frequencyAnalyzer.load(toInputStream(input)); } catch (final IOException e) { throw new RuntimeException(e.getMessage(), e); } } #location 13 #vulnerability type RESOURCE_LEAK
#fixed code private List<WordFrequency> loadFrequencies(final String input) { try { final FrequencyAnalyzer frequencyAnalyzer = new FrequencyAnalyzer(); frequencyAnalyzer.setWordFrequenciesToReturn(cliParameters.getWordCount()); frequencyAnalyzer.setMinWordLength(cliParameters.getMinWordLength()); frequencyAnalyzer.setStopWords(cliParameters.getStopWords()); frequencyAnalyzer.setCharacterEncoding(cliParameters.getCharacterEncoding()); if (cliParameters.getNormalizers().isEmpty()) { cliParameters.getNormalizers().addAll(Arrays.asList(NormalizerType.TRIM, NormalizerType.CHARACTER_STRIPPING, NormalizerType.LOWERCASE)); } for (final NormalizerType normalizer : cliParameters.getNormalizers()) { frequencyAnalyzer.addNormalizer(buildNormalizer(normalizer)); } frequencyAnalyzer.setWordTokenizer(buildTokenizer()); return frequencyAnalyzer.load(toInputStream(input)); } catch (final IOException e) { throw new RuntimeException(e.getMessage(), e); } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code protected void preOperation(AipRequest request) { if (needAuth()) { getAccessToken(); } request.setHttpMethod(HttpMethodName.POST); request.addHeader(Headers.CONTENT_TYPE, HttpContentType.FORM_URLENCODE_DATA); request.addHeader("accept", "*/*"); request.setConfig(config); } #location 2 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code protected void preOperation(AipRequest request) { if (needAuth()) { getAccessToken(config); } request.setHttpMethod(HttpMethodName.POST); request.addHeader(Headers.CONTENT_TYPE, HttpContentType.FORM_URLENCODE_DATA); request.addHeader("accept", "*/*"); request.setConfig(config); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void testSyncHandleTimeout() throws Exception { RpcFuture rpcFuture = new RpcFuture<String>(timeout, methodInfo, null, channelInfo, rpcClient); Response resp = rpcFuture.get(100, TimeUnit.MILLISECONDS); assertThat(resp.getException(), instanceOf(RpcException.class)); assertThat(((RpcException) resp.getException()).getCode(), is(RpcException.TIMEOUT_EXCEPTION)); } #location 5 #vulnerability type NULL_DEREFERENCE
#fixed code @Test public void testSyncHandleTimeout() throws Exception { RpcFuture<String> rpcFuture = new RpcFuture<String>(timeout, methodInfo, null, channelInfo, rpcClient); try { rpcFuture.get(100, TimeUnit.MILLISECONDS); } catch (RpcException ex2) { Assert.assertTrue(ex2.getCode() == RpcException.TIMEOUT_EXCEPTION); } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Override public Response decodeResponse(Object msg, ChannelHandlerContext ctx) { FullHttpResponse httpResponse = (FullHttpResponse) msg; try { ChannelInfo channelInfo = ChannelInfo.getClientChannelInfo(ctx.channel()); Long logId = parseLogId(httpResponse.headers().get(LOG_ID), channelInfo.getLogId()); HttpResponse response = new HttpResponse(); response.setLogId(logId); RpcFuture future = channelInfo.removeRpcFuture(response.getLogId()); if (future == null) { return response; } response.setRpcFuture(future); if (!httpResponse.status().equals(HttpResponseStatus.OK)) { LOG.warn("status={}", httpResponse.status()); response.setException(new RpcException(RpcException.SERVICE_EXCEPTION, "http status=" + httpResponse.status())); return response; } int bodyLen = httpResponse.content().readableBytes(); byte[] bytes = new byte[bodyLen]; httpResponse.content().readBytes(bytes); String contentTypeAndEncoding = httpResponse.headers().get(HttpHeaderNames.CONTENT_TYPE).toLowerCase(); String[] splits = StringUtils.split(contentTypeAndEncoding, ";"); int protocolType = HttpRpcProtocol.parseProtocolType(splits[0]); String encoding = this.encoding; // 由于uc服务返回的encoding是错误的,所以这里以client端设置的encoding为准。 // for (String split : splits) { // split = split.trim(); // if (split.startsWith("charset=")) { // encoding = split.substring("charset=".length()); // } // } Object body = null; if (bodyLen != 0) { try { body = decodeBody(protocolType, encoding, bytes); } catch (Exception ex) { LOG.error("decode response body failed"); response.setException(ex); return response; } } if (body != null) { try { response.setResult(parseHttpResponse(body, future.getRpcMethodInfo())); } catch (Exception ex) { LOG.error("failed to parse result from HTTP body"); response.setException(ex); } } else { response.setResult(null); } // set response attachment if (response.getKvAttachment() == null) { response.setKvAttachment(new HashMap<String, Object>()); } for (Map.Entry<String, String> entry : httpResponse.headers()) { response.getKvAttachment().put(entry.getKey(), entry.getValue()); } return response; } finally { httpResponse.release(); } } #location 8 #vulnerability type NULL_DEREFERENCE
#fixed code @Override public Response decodeResponse(Object msg, ChannelHandlerContext ctx) { FullHttpResponse httpResponse = (FullHttpResponse) msg; try { ChannelInfo channelInfo = ChannelInfo.getClientChannelInfo(ctx.channel()); Long correlationId = parseCorrelationId(httpResponse.headers().get(CORRELATION_ID), channelInfo.getCorrelationId()); HttpResponse response = new HttpResponse(); response.setCorrelationId(correlationId); RpcFuture future = channelInfo.removeRpcFuture(response.getCorrelationId()); if (future == null) { return response; } response.setRpcFuture(future); if (!httpResponse.status().equals(HttpResponseStatus.OK)) { LOG.warn("status={}", httpResponse.status()); response.setException(new RpcException(RpcException.SERVICE_EXCEPTION, "http status=" + httpResponse.status())); return response; } int bodyLen = httpResponse.content().readableBytes(); byte[] bytes = new byte[bodyLen]; httpResponse.content().readBytes(bytes); String contentTypeAndEncoding = httpResponse.headers().get(HttpHeaderNames.CONTENT_TYPE).toLowerCase(); String[] splits = StringUtils.split(contentTypeAndEncoding, ";"); int protocolType = HttpRpcProtocol.parseProtocolType(splits[0]); String encoding = this.encoding; // 由于uc服务返回的encoding是错误的,所以这里以client端设置的encoding为准。 // for (String split : splits) { // split = split.trim(); // if (split.startsWith("charset=")) { // encoding = split.substring("charset=".length()); // } // } Object body = null; if (bodyLen != 0) { try { body = decodeBody(protocolType, encoding, bytes); } catch (Exception ex) { LOG.error("decode response body failed"); response.setException(ex); return response; } } if (body != null) { try { response.setResult(parseHttpResponse(body, future.getRpcMethodInfo())); } catch (Exception ex) { LOG.error("failed to parse result from HTTP body"); response.setException(ex); } } else { response.setResult(null); } // set response attachment if (response.getKvAttachment() == null) { response.setKvAttachment(new HashMap<String, Object>()); } for (Map.Entry<String, String> entry : httpResponse.headers()) { response.getKvAttachment().put(entry.getKey(), entry.getValue()); } return response; } finally { httpResponse.release(); } }
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"); rpcFuture.handleResponse(response); Response resp = rpcFuture.get(1, TimeUnit.SECONDS); assertThat((String) resp.getResult(), is("hello world")); } #location 8 #vulnerability type NULL_DEREFERENCE
#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 world"); rpcFuture.handleResponse(response); String resp = rpcFuture.get(1, TimeUnit.SECONDS); assertThat(resp, is("hello world")); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public Channel getChannel(String clientName) { if (log.isDebugEnabled()) { for (Map.Entry<String, List<Channel>> entry : channelMap.entrySet()) { log.debug("participantName={}, channelNum={}", entry.getKey(), entry.getValue() == null ? 0 : entry.getValue().size()); } } lock.readLock().lock(); try { List<Channel> channelList = channelMap.get(clientName); if (channelList == null || channelList.size() == 0) { log.info("no available connection for clientName={}", clientName); return null; } int id = index.getAndIncrement() % channelList.size(); Channel channel = channelList.get(id); return channel; } finally { lock.readLock().unlock(); } } #location 3 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code public Channel getChannel(String clientName) { if (log.isDebugEnabled()) { for (Map.Entry<String, List<Channel>> entry : innerStoreManager.getChannelMap().entrySet()) { log.debug("participantName={}, channelNum={}", entry.getKey(), entry.getValue() == null ? 0 : entry.getValue().size()); } } lock.readLock().lock(); try { return innerStoreManager.getChannel(clientName); } finally { lock.readLock().unlock(); } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public ThreadPool getOrCreateClientWorkThreadPool(String serviceName, boolean isSharing, int threadNum) { if (isSharing) { if (defaultWorkThreadPool == null) { synchronized (BrpcThreadPoolManager.class) { if (defaultWorkThreadPool == null) { defaultWorkThreadPool = new ThreadPool(threadNum, new CustomThreadFactory("brpc-client-work-thread-default")); } } } return defaultWorkThreadPool; } ThreadPool threadPool = workThreadPoolMap.get(serviceName); if (threadPool != null) { return threadPool; } threadPool = new ThreadPool(threadNum, new CustomThreadFactory("brpc-client-work-thread-" + serviceName)); workThreadPoolMap.put(serviceName, threadPool); return threadPool; } #location 11 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code public ThreadPool getOrCreateClientWorkThreadPool(String serviceName, boolean isSharing, int threadNum) { if (isSharing) { if (defaultWorkThreadPool == null) { synchronized (BrpcThreadPoolManager.class) { if (defaultWorkThreadPool == null) { defaultWorkThreadPool = new ThreadPool(threadNum, new CustomThreadFactory("brpc-client-work-thread-default")); } } } return defaultWorkThreadPool; } ThreadPool threadPool; if ((threadPool = workThreadPoolMap.get(serviceName)) == null) { synchronized (serviceName.intern()) { if ((threadPool = workThreadPoolMap.get(serviceName)) == null) { threadPool = new ThreadPool(threadNum, new CustomThreadFactory("brpc-client-work-thread-" + serviceName)); workThreadPoolMap.put(serviceName, threadPool); } } } return threadPool; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code private void parseRpcExporterAnnotation(RpcExporter rpcExporter, ConfigurableListableBeanFactory beanFactory, Object bean) { Class<?> serviceClass = AopUtils.getTargetClass(bean); Class<?>[] interfaces = ClassUtils.getAllInterfacesForClass(serviceClass); if (interfaces.length != 1) { throw new RuntimeException("service interface num must equal 1, " + serviceClass.getName()); } Class<?> serviceInterface = interfaces[0]; BrpcConfig brpcConfig = getServiceConfig(beanFactory, serviceInterface); // if there are multi service on one port, the first service configs effect only. Integer port = brpcConfig.getServer().getPort(); RpcServiceExporter rpcServiceExporter = portMappingExporters.get(port); if (rpcServiceExporter == null) { rpcServiceExporter = new RpcServiceExporter(); portMappingExporters.put(port, rpcServiceExporter); rpcServiceExporter.setServicePort(port); rpcServiceExporter.copyFrom(brpcConfig.getServer()); if (brpcConfig.getNaming() != null) { rpcServiceExporter.setNamingServiceUrl(brpcConfig.getNaming().getNamingServiceUrl()); } } // interceptor if (brpcConfig.getServer() != null && StringUtils.isNoneBlank(brpcConfig.getServer().getInterceptorBeanName())) { Interceptor interceptor = beanFactory.getBean( brpcConfig.getServer().getInterceptorBeanName(), Interceptor.class); if (rpcServiceExporter.getInterceptors() != null) { rpcServiceExporter.getInterceptors().add(interceptor); } else { rpcServiceExporter.setInterceptors(Arrays.asList(interceptor)); } } // naming options rpcServiceExporter.getServiceNamingOptions().put(bean, brpcConfig.getNaming()); if (brpcConfig.getServer() != null && brpcConfig.getServer().isUseSharedThreadPool()) { rpcServiceExporter.getCustomOptionsServiceMap().put(brpcConfig.getServer(), bean); } else { rpcServiceExporter.getRegisterServices().add(bean); } if (protobufRpcAnnotationResolverListener != null) { protobufRpcAnnotationResolverListener.onRpcExporterAnnotationParsered( rpcExporter, port, bean, rpcServiceExporter.getRegisterServices()); } } #location 13 #vulnerability type NULL_DEREFERENCE
#fixed code private void parseRpcExporterAnnotation(RpcExporter rpcExporter, ConfigurableListableBeanFactory beanFactory, Object bean) { Class<?> serviceClass = AopUtils.getTargetClass(bean); Class<?>[] interfaces = ClassUtils.getAllInterfacesForClass(serviceClass); if (interfaces.length != 1) { throw new RuntimeException("service interface num must equal 1, " + serviceClass.getName()); } Class<?> serviceInterface = interfaces[0]; BrpcConfig brpcConfig = getServiceConfig(beanFactory, serviceInterface); // if there are multi service on one port, the first service configs effect only. Integer port = brpcConfig.getServer().getPort(); RpcServiceExporter rpcServiceExporter = portMappingExporters.get(port); if (rpcServiceExporter == null) { rpcServiceExporter = new RpcServiceExporter(); portMappingExporters.put(port, rpcServiceExporter); rpcServiceExporter.setServicePort(port); rpcServiceExporter.copyFrom(brpcConfig.getServer()); if (brpcConfig.getNaming() != null) { rpcServiceExporter.setNamingServiceUrl(brpcConfig.getNaming().getNamingServiceUrl()); } } // interceptor if (brpcConfig.getServer() != null && StringUtils.isNoneBlank(brpcConfig.getServer().getInterceptorBeanName())) { Interceptor interceptor = beanFactory.getBean( brpcConfig.getServer().getInterceptorBeanName(), Interceptor.class); if (rpcServiceExporter.getInterceptors() != null && !rpcServiceExporter.getInterceptors().contains(interceptor)) { rpcServiceExporter.getInterceptors().add(interceptor); } else { List<Interceptor> interceptors = new ArrayList<>(); interceptors.add(interceptor); rpcServiceExporter.setInterceptors(interceptors); // must be immutable } } // naming options rpcServiceExporter.getServiceNamingOptions().put(bean, brpcConfig.getNaming()); if (brpcConfig.getServer() != null && brpcConfig.getServer().isUseSharedThreadPool()) { rpcServiceExporter.getCustomOptionsServiceMap().put(brpcConfig.getServer(), bean); } else { rpcServiceExporter.getRegisterServices().add(bean); } if (protobufRpcAnnotationResolverListener != null) { protobufRpcAnnotationResolverListener.onRpcExporterAnnotationParsered( rpcExporter, port, bean, rpcServiceExporter.getRegisterServices()); } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public EventLoopGroup getOrCreateClientIoThreadPool(String serviceName, boolean isSharing, int threadNum, int ioEventType) { if (isSharing) { if (defaultIoThreadPool == null) { synchronized (BrpcThreadPoolManager.class) { if (defaultIoThreadPool == null) { defaultIoThreadPool = createClientIoThreadPool( threadNum, "brpc-client-io-thread-default", ioEventType); } } } return defaultIoThreadPool; } EventLoopGroup threadPool = ioThreadPoolMap.get(serviceName); if (threadPool != null) { return threadPool; } threadPool = createClientIoThreadPool( threadNum, "brpc-client-io-thread-" + serviceName, ioEventType); EventLoopGroup prev = ioThreadPoolMap.putIfAbsent(serviceName, threadPool); if (prev != null) { log.warn("brpc io thread pool exist for service:{}", serviceName); threadPool.shutdownGracefully().awaitUninterruptibly(); } return threadPool; } #location 12 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code public EventLoopGroup getOrCreateClientIoThreadPool(String serviceName, boolean isSharing, int threadNum, int ioEventType) { if (isSharing) { if (defaultIoThreadPool == null) { synchronized (BrpcThreadPoolManager.class) { if (defaultIoThreadPool == null) { defaultIoThreadPool = createClientIoThreadPool( threadNum, "brpc-client-io-thread-default", ioEventType); } } } return defaultIoThreadPool; } EventLoopGroup threadPool; if ((threadPool = ioThreadPoolMap.get(serviceName)) == null) { synchronized (serviceName.intern()) { if ((threadPool = ioThreadPoolMap.get(serviceName)) == null) { threadPool = createClientIoThreadPool( threadNum, "brpc-client-io-thread-" + serviceName, ioEventType); EventLoopGroup prev = ioThreadPoolMap.putIfAbsent(serviceName, threadPool); if (prev != null) { log.warn("brpc io thread pool exist for service:{}", serviceName); threadPool.shutdownGracefully().awaitUninterruptibly(); } } } } return threadPool; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Override public ByteBuf encodeResponse(Request request, Response response) { FullHttpRequest httpRequest = (FullHttpRequest) request.getMsg(); FullHttpResponse httpResponse = null; try { if (response.getException() != null) { httpResponse = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.INTERNAL_SERVER_ERROR); } else { httpResponse = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK); addHttpResponseHeaders(httpResponse, response, httpRequest); int protocolType = Integer.parseInt(httpRequest.headers().get(PROTOCOL_TYPE)); Object body = makeResponse(protocolType, response); // encode body try { byte[] responseBytes = encodeBody(protocolType, httpRequest.headers().get(HttpHeaderNames.CONTENT_ENCODING), body, response.getRpcMethodInfo()); httpResponse.content().writeBytes(responseBytes); httpResponse.headers().set(HttpHeaderNames.CONTENT_LENGTH, responseBytes.length); } catch (Exception e) { LOG.warn("encode response failed", e); response.setException(e); httpResponse = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.INTERNAL_SERVER_ERROR); } } // encode full http response BrpcHttpResponseEncoder encoder = new BrpcHttpResponseEncoder(); return encoder.encode(httpResponse); } catch (Exception e) { LOG.warn("encode response failed", e); response.setException(e); return null; } finally { if (httpResponse != null) { httpResponse.release(); } } } #location 21 #vulnerability type NULL_DEREFERENCE
#fixed code @Override public ByteBuf encodeResponse(Request request, Response response) { FullHttpRequest httpRequest = (FullHttpRequest) request.getMsg(); FullHttpResponse httpResponse = null; try { byte[] responseBytes; if (response.getException() != null) { httpResponse = new DefaultFullHttpResponse( HttpVersion.HTTP_1_1, HttpResponseStatus.INTERNAL_SERVER_ERROR); responseBytes = response.getException().toString().getBytes(); } else { httpResponse = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK); int protocolType = Integer.parseInt(httpRequest.headers().get(PROTOCOL_TYPE)); Object body = makeResponse(protocolType, response); // encode body try { responseBytes = encodeBody(protocolType, httpRequest.headers().get(HttpHeaderNames.CONTENT_ENCODING), body, response.getRpcMethodInfo()); } catch (Exception e) { LOG.warn("encode response failed", e); response.setException(e); httpResponse = new DefaultFullHttpResponse( HttpVersion.HTTP_1_1, HttpResponseStatus.INTERNAL_SERVER_ERROR); responseBytes = response.getException().toString().getBytes(); } } httpResponse.content().writeBytes(responseBytes); addHttpResponseHeaders(httpResponse, response, httpRequest); // encode full http response BrpcHttpResponseEncoder encoder = new BrpcHttpResponseEncoder(); return encoder.encode(httpResponse); } catch (Exception e) { LOG.warn("encode response failed", e); response.setException(e); return null; } finally { if (httpResponse != null) { httpResponse.release(); } } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public Response executeWithRetry(Request request) { Response response = null; RpcException exception = null; int currentTryTimes = 0; int maxTryTimes = rpcClient.getRpcClientOptions().getMaxTryTimes(); while (currentTryTimes < maxTryTimes) { try { // if it is a retry request, add the last selected instance to request, // so that load balance strategy can exclude the selected instance. // if it is the initial request, not init HashSet, so it is more fast. // therefore, it need LoadBalanceStrategy to judge if selectInstances is null. if (currentTryTimes > 0) { if (request.getChannel() != null) { if (request.getSelectedInstances() == null) { request.setSelectedInstances(new HashSet<CommunicationClient>(maxTryTimes - 1)); } request.getSelectedInstances().add(request.getCommunicationClient()); } } response = rpcClient.execute(request, rpcClient.getCommunicationOptions()); break; } catch (RpcException ex) { exception = ex; if (exception.getCode() == RpcException.INTERCEPT_EXCEPTION) { break; } } finally { currentTryTimes++; } } if (response.getResult() == null && response.getRpcFuture() == null) { if (exception == null) { exception = new RpcException(RpcException.UNKNOWN_EXCEPTION, "unknown error"); } throw exception; } return response; } #location 32 #vulnerability type NULL_DEREFERENCE
#fixed code public Response executeWithRetry(Request request) { Response response = null; RpcException exception = null; int currentTryTimes = 0; int maxTryTimes = rpcClient.getRpcClientOptions().getMaxTryTimes(); while (currentTryTimes < maxTryTimes) { try { // if it is a retry request, add the last selected instance to request, // so that load balance strategy can exclude the selected instance. // if it is the initial request, not init HashSet, so it is more fast. // therefore, it need LoadBalanceStrategy to judge if selectInstances is null. if (currentTryTimes > 0) { if (request.getChannel() != null) { if (request.getSelectedInstances() == null) { request.setSelectedInstances(new HashSet<CommunicationClient>(maxTryTimes - 1)); } request.getSelectedInstances().add(request.getCommunicationClient()); } } response = rpcClient.execute(request, rpcClient.getCommunicationOptions()); break; } catch (RpcException ex) { exception = ex; if (exception.getCode() == RpcException.INTERCEPT_EXCEPTION) { break; } } finally { currentTryTimes++; } } if (response == null || (response.getResult() == null && response.getRpcFuture() == null)) { if (exception == null) { exception = new RpcException(RpcException.UNKNOWN_EXCEPTION, "unknown error"); } throw exception; } return response; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void testSyncHandleFailResponse() throws Exception { RpcFuture rpcFuture = new RpcFuture<String>(timeout, methodInfo, null, channelInfo, rpcClient); RpcResponse response = new RpcResponse(); RuntimeException ex = new RuntimeException("dummy"); response.setException(ex); rpcFuture.handleResponse(response); Response resp = rpcFuture.get(1, TimeUnit.SECONDS); assertThat((RuntimeException) resp.getException(), is(ex)); } #location 9 #vulnerability type NULL_DEREFERENCE
#fixed code @Test public void testSyncHandleFailResponse() throws Exception { RpcFuture<String> rpcFuture = new RpcFuture<String>(timeout, methodInfo, null, channelInfo, rpcClient); RpcResponse response = new RpcResponse(); RuntimeException ex = new RuntimeException("dummy"); response.setException(ex); rpcFuture.handleResponse(response); try { rpcFuture.get(1, TimeUnit.SECONDS); } catch (RpcException ex2) { Assert.assertTrue(ex2.getCause() == ex); } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public VerbalExpression replace(String source, String value) { this.add(""); this.source.replaceAll(pattern,value); return this; } #location 3 #vulnerability type NULL_DEREFERENCE
#fixed code public VerbalExpression replace(String source, String value) { this.updatePattern(); this.source.replaceAll(pattern,value); return this; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code private void collectLibraryInputFiles() { if ( parsedIncludeJdkLibs ) { final String slash = File.separator; // we have to add the Java framework classes to the library JARs, since they are not // distributed with the JAR on Central, and since we'll strip them out of the android.jar // that is shipped with the SDK (since that is not a complete Java distribution) String javaHome = System.getProperty( "java.home" ); String jdkLibsPath = null; if ( javaHome.startsWith( "/System/Library/Java" ) || javaHome.startsWith( "/Library/Java" ) ) { // MacOS X uses different naming conventions for JDK installations jdkLibsPath = javaHome + "/../Classes"; addLibraryJar( jdkLibsPath + "/classes.jar" ); } else { jdkLibsPath = javaHome + slash + "lib"; addLibraryJar( jdkLibsPath + slash + "rt.jar" ); } // we also need to add the JAR containing e.g. javax.servlet addLibraryJar( jdkLibsPath + slash + "jsse.jar" ); // and the javax.crypto stuff addLibraryJar( jdkLibsPath + slash + "jce.jar" ); } // we treat any dependencies with provided scope as library JARs for ( Artifact artifact : project.getArtifacts() ) { if ( artifact.getScope().equals( JavaScopes.PROVIDED ) ) { if ( artifact.getArtifactId().equals( "android" ) && parsedIncludeJdkLibs ) { addLibraryJar( artifact.getFile().getAbsolutePath(), ANDROID_LIBRARY_EXCLUDED_FILTER ); } else { addLibraryJar( artifact.getFile().getAbsolutePath() ); } } else { if ( isShiftedArtifact( artifact ) ) { // this is a blacklisted artifact that should be processed as a library instead addLibraryJar( artifact.getFile().getAbsolutePath() ); } } } } #location 11 #vulnerability type NULL_DEREFERENCE
#fixed code private void collectLibraryInputFiles() { if ( parsedIncludeJdkLibs ) { final String slash = File.separator; // we have to add the Java framework classes to the library JARs, since they are not // distributed with the JAR on Central, and since we'll strip them out of the android.jar // that is shipped with the SDK (since that is not a complete Java distribution) String javaHome = System.getProperty( "java.home" ); String jdkLibsPath = null; if ( isMacOSXJDKbyApple( javaHome ) ) { // MacOS X uses different naming conventions for JDK installations jdkLibsPath = appleJDKLibsPath( javaHome ); addLibraryJar( jdkLibsPath + "/classes.jar" ); } else { jdkLibsPath = javaHome + slash + "lib"; addLibraryJar( jdkLibsPath + slash + "rt.jar" ); } // we also need to add the JAR containing e.g. javax.servlet addLibraryJar( jdkLibsPath + slash + "jsse.jar" ); // and the javax.crypto stuff addLibraryJar( jdkLibsPath + slash + "jce.jar" ); } // we treat any dependencies with provided scope as library JARs for ( Artifact artifact : project.getArtifacts() ) { if ( artifact.getScope().equals( JavaScopes.PROVIDED ) ) { if ( artifact.getArtifactId().equals( "android" ) && parsedIncludeJdkLibs ) { addLibraryJar( artifact.getFile().getAbsolutePath(), ANDROID_LIBRARY_EXCLUDED_FILTER ); } else { addLibraryJar( artifact.getFile().getAbsolutePath() ); } } else { if ( isShiftedArtifact( artifact ) ) { // this is a blacklisted artifact that should be processed as a library instead addLibraryJar( artifact.getFile().getAbsolutePath() ); } } } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public File getPlatform() { assertPathIsDirectory( sdkPath ); final File platformsDirectory = new File( sdkPath, PLATFORMS_FOLDER_NAME ); assertPathIsDirectory( platformsDirectory ); final File platformDirectory; if ( platform == null ) { final File[] platformDirectories = platformsDirectory.listFiles(); Arrays.sort( platformDirectories ); platformDirectory = platformDirectories[ platformDirectories.length - 1 ]; } else { platformDirectory = new File( platform.path ); } assertPathIsDirectory( platformDirectory ); return platformDirectory; } #location 13 #vulnerability type NULL_DEREFERENCE
#fixed code public File getPlatform() { assertPathIsDirectory( sdkPath ); final File platformsDirectory = new File( sdkPath, PLATFORMS_FOLDER_NAME ); assertPathIsDirectory( platformsDirectory ); final File platformDirectory; if ( androidTarget == null ) { IAndroidTarget latestTarget = null; for ( IAndroidTarget target: sdkManager.getTargets() ) { if ( target.isPlatform() ) { if ( latestTarget == null || target.getVersion().getApiLevel() > latestTarget.getVersion().getApiLevel() ) { latestTarget = target; } } } platformDirectory = new File ( latestTarget.getLocation() ); } else { platformDirectory = new File( androidTarget.getLocation() ); } assertPathIsDirectory( platformDirectory ); return platformDirectory; }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public void execute() throws MojoExecutionException, MojoFailureException { CommandExecutor executor = CommandExecutor.Factory.createDefaultCommmandExecutor(); executor.setLogger(this.getLog()); if (androidManifestFile == null) { androidManifestFile = new File(resourceDirectory.getParent(), "AndroidManifest.xml"); } File tmpOutputFile; try { tmpOutputFile = File.createTempFile("android", "apk"); } catch (IOException e) { throw new MojoExecutionException("", e); } Artifact artifact = artifactFactory.createArtifact("android", "android", androidVersion, "jar", "jar"); ArtifactRepositoryLayout defaultLayout = new DefaultRepositoryLayout(); File androidJar = new File(localRepository, defaultLayout.pathOf(artifact)); artifact.setFile(androidJar); tmpOutputFile.deleteOnExit(); File outputFile = new File(project.getBuild().getDirectory(), project.getArtifactId() + "-" + project.getVersion() + ".apk"); List<String> commands = new ArrayList<String>(); commands.add("package"); commands.add("-f"); commands.add("-M"); commands.add(androidManifestFile.getAbsolutePath()); if (resourceDirectory.exists()) { commands.add("-S"); commands.add(resourceDirectory.getAbsolutePath()); } commands.add("-I"); commands.add(androidJar.getAbsolutePath()); commands.add("-F"); commands.add(tmpOutputFile.getAbsolutePath()); getLog().info("aapt " + commands.toString()); try { executor.executeCommand("aapt", commands, project.getBasedir(), false); } catch (ExecutionException e) { throw new MojoExecutionException("", e); } File dexClassesFile = new File(project.getBasedir(), "target" + File.separator + project.getArtifactId() + "-" + project.getVersion() + "-classes.dex"); ZipOutputStream os = null; InputStream is = null; try { ZipFile zipFile = new ZipFile(tmpOutputFile); os = new ZipOutputStream(new FileOutputStream(outputFile)); for (ZipEntry entry : (List<ZipEntry>) Collections.list(zipFile.entries())) { os.putNextEntry(new ZipEntry(entry.getName())); is = zipFile.getInputStream(entry); byte[] buffer = new byte[1024]; int i; while ((i = is.read(buffer)) > 0) { os.write(buffer, 0, i); } is.close(); } os.putNextEntry(new ZipEntry("classes.dex")); is = new FileInputStream(dexClassesFile); byte[] buffer = new byte[1024]; int i; while ((i = is.read(buffer)) > 0) { os.write(buffer, 0, i); } is.close(); os.close(); } catch (IOException e) { throw new MojoExecutionException("", e); } finally { if (os != null) { try { os.close(); } catch (IOException e) { } } if (is != null) { try { is.close(); } catch (IOException e) { } } } project.getArtifact().setFile(outputFile); } #location 13 #vulnerability type RESOURCE_LEAK
#fixed code public void execute() throws MojoExecutionException, MojoFailureException { CommandExecutor executor = CommandExecutor.Factory.createDefaultCommmandExecutor(); executor.setLogger(this.getLog()); if (androidManifestFile == null) { androidManifestFile = new File(resourceDirectory.getParent(), "AndroidManifest.xml"); } Artifact artifact = artifactFactory.createArtifact("android", "android", androidVersion, "jar", "jar"); ArtifactRepositoryLayout defaultLayout = new DefaultRepositoryLayout(); File androidJar = new File(localRepository, defaultLayout.pathOf(artifact)); artifact.setFile(androidJar); File outputFile = new File(project.getBuild().getDirectory(), project.getBuild().getFinalName() + ".ap_"); List<String> commands = new ArrayList<String>(); commands.add("package"); commands.add("-f"); commands.add("-M"); commands.add(androidManifestFile.getAbsolutePath()); if (resourceDirectory.exists()) { commands.add("-S"); commands.add(resourceDirectory.getAbsolutePath()); } commands.add("-I"); commands.add(androidJar.getAbsolutePath()); commands.add("-F"); commands.add(outputFile.getAbsolutePath()); getLog().info("aapt " + commands.toString()); try { executor.executeCommand("aapt", commands, project.getBasedir(), false); } catch (ExecutionException e) { throw new MojoExecutionException("", e); } /* File dexClassesFile = new File(project.getBuild().getDirectory(), project.getBuild().getFinalName() + ".classes-dex"); ZipOutputStream os = null; InputStream is = null; try { ZipFile zipFile = new ZipFile(tmpOutputFile); os = new ZipOutputStream(new FileOutputStream(outputFile)); for (ZipEntry entry : (List<ZipEntry>) Collections.list(zipFile.entries())) { os.putNextEntry(new ZipEntry(entry.getName())); is = zipFile.getInputStream(entry); byte[] buffer = new byte[1024]; int i; while ((i = is.read(buffer)) > 0) { os.write(buffer, 0, i); } is.close(); } os.putNextEntry(new ZipEntry("classes.dex")); is = new FileInputStream(dexClassesFile); byte[] buffer = new byte[1024]; int i; while ((i = is.read(buffer)) > 0) { os.write(buffer, 0, i); } is.close(); os.close(); } catch (IOException e) { throw new MojoExecutionException("", e); } finally { if (os != null) { try { os.close(); } catch (IOException e) { } } if (is != null) { try { is.close(); } catch (IOException e) { } } } */ // project.getArtifact().setFile(outputFile); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code private void collectLibraryInputFiles() { if ( parsedIncludeJdkLibs ) { final String slash = File.separator; // we have to add the Java framework classes to the library JARs, since they are not // distributed with the JAR on Central, and since we'll strip them out of the android.jar // that is shipped with the SDK (since that is not a complete Java distribution) String javaHome = System.getProperty( "java.home" ); String jdkLibsPath = null; if ( isMacOSXJDKbyApple( javaHome ) ) { // MacOS X uses different naming conventions for JDK installations jdkLibsPath = appleJDKLibsPath( javaHome ); addLibraryJar( jdkLibsPath + "/classes.jar" ); } else { jdkLibsPath = javaHome + slash + "lib"; addLibraryJar( jdkLibsPath + slash + "rt.jar" ); } // we also need to add the JAR containing e.g. javax.servlet addLibraryJar( jdkLibsPath + slash + "jsse.jar" ); // and the javax.crypto stuff addLibraryJar( jdkLibsPath + slash + "jce.jar" ); } // we treat any dependencies with provided scope as library JARs for ( Artifact artifact : project.getArtifacts() ) { if ( artifact.getScope().equals( JavaScopes.PROVIDED ) ) { if ( artifact.getArtifactId().equals( "android" ) && parsedIncludeJdkLibs ) { addLibraryJar( artifact.getFile().getAbsolutePath(), ANDROID_LIBRARY_EXCLUDED_FILTER ); } else { addLibraryJar( artifact.getFile().getAbsolutePath() ); } } else { if ( isShiftedArtifact( artifact ) ) { // this is a blacklisted artifact that should be processed as a library instead addLibraryJar( artifact.getFile().getAbsolutePath() ); } } } } #location 11 #vulnerability type NULL_DEREFERENCE
#fixed code private void collectLibraryInputFiles() { if ( parsedIncludeJdkLibs ) { // we have to add the Java framework classes to the library JARs, since they are not // distributed with the JAR on Central, and since we'll strip them out of the android.jar // that is shipped with the SDK (since that is not a complete Java distribution) File rtJar = getJVMLibrary( "rt.jar" ); if ( rtJar == null ) { rtJar = getJVMLibrary( "classes.jar" ); } if ( rtJar != null ) { addLibraryJar( rtJar.getPath() ); } // we also need to add the JAR containing e.g. javax.servlet File jsseJar = getJVMLibrary( "jsse.jar" ); if ( jsseJar != null ) { addLibraryJar( jsseJar.getPath() ); } // and the javax.crypto stuff File jceJar = getJVMLibrary( "jce.jar" ); if ( jceJar != null ) { addLibraryJar( jceJar.getPath() ); } } // we treat any dependencies with provided scope as library JARs for ( Artifact artifact : project.getArtifacts() ) { if ( artifact.getScope().equals( JavaScopes.PROVIDED ) ) { if ( artifact.getArtifactId().equals( "android" ) && parsedIncludeJdkLibs ) { addLibraryJar( artifact.getFile().getAbsolutePath(), ANDROID_LIBRARY_EXCLUDED_FILTER ); } else { addLibraryJar( artifact.getFile().getAbsolutePath() ); } } else { if ( isShiftedArtifact( artifact ) ) { // this is a blacklisted artifact that should be processed as a library instead addLibraryJar( artifact.getFile().getAbsolutePath() ); } } } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code private void runLint() { IssueRegistry registry = new BuiltinIssueRegistry(); LintCliFlags flags = new LintCliFlags(); flags.setQuiet( false ); LintCliClient client = new LintCliClient( flags ); File outHtmlFile = new File( getHtmlOutputPath() ); try { File outFile = new File( getHtmlOutputPath() + "/lint-results.txt" ); outFile.createNewFile(); FileOutputStream out = new FileOutputStream( outFile ); TextReporter reporter = new TextReporter( client, flags, new PrintWriter( out, true ), false ); flags.getReporters().add( reporter ); MultiProjectHtmlReporter htmlReporter = new MultiProjectHtmlReporter( client, outHtmlFile ); flags.getReporters().add( htmlReporter ); List< File > files = new ArrayList< File >(); files.add( resourceDirectory ); files.add( androidManifestFile ); files.add( sourceDirectory ); files.add( assetsDirectory ); client.run( registry, files ); } catch ( IOException ex ) { // TODO Error } } #location 16 #vulnerability type RESOURCE_LEAK
#fixed code private void runLint() throws MojoExecutionException { IssueRegistry registry = new BuiltinIssueRegistry(); LintCliFlags flags = new LintCliFlags(); flags.setQuiet( false ); LintCliClient client = new LintCliClient( flags ); try { if ( isNotNull( parsedIgnoreWarnings ) ) { flags.setIgnoreWarnings( parsedIgnoreWarnings ); } if ( isNotNull( parsedWarnAll ) ) { flags.setCheckAllWarnings( parsedWarnAll ); } if ( isNotNull( parsedWarningsAsErrors ) ) { flags.setWarningsAsErrors( parsedWarningsAsErrors ); } if ( isNotNullAndNotEquals( parsedConfig, "null" ) ) { flags.setDefaultConfiguration( new File( parsedConfig ) ); } if ( isNotNull( parsedFullPath ) ) { flags.setFullPath( parsedFullPath ); } if ( isNotNull( parsedShowAll ) ) { flags.setShowEverything( parsedShowAll ); } if ( isNotNull( parsedDisableSourceLines ) ) { flags.setShowSourceLines( !parsedDisableSourceLines ); } if ( isNotNullAndTrue( parsedEnableHtml ) ) { File outHtml = new File( parsedHtmlOutputPath ); flags.getReporters().add( new MultiProjectHtmlReporter( client, outHtml ) ); getLog().info( "Writing Lint HTML report in " + parsedHtmlOutputPath ); } if ( isNotNullAndNotEquals( parsedUrl, "none" ) ) { // TODO what is this? // parameters.add( "--url" ); // parameters.add( parsedUrl ); } if ( isNotNullAndTrue( parsedEnableSimpleHtml ) ) { File outSimpleHtml = new File( parsedSimpleHtmlOutputPath ); flags.getReporters().add( new MultiProjectHtmlReporter( client, outSimpleHtml ) ); getLog().info( "Writing Lint simple HTML report in " + parsedSimpleHtmlOutputPath ); } if ( isNotNullAndTrue( parsedEnableXml ) ) { flags.getReporters().add( new XmlReporter( client, new File( parsedXmlOutputPath ) ) ); getLog().info( "Writing Lint XML report in " + parsedXmlOutputPath ); } if ( isNotNullAndTrue( parsedEnableSources ) ) { // TODO what is this? // parameters.add( "--sources" ); // parameters.add( parsedSources ); } if ( isNotNullAndTrue( parsedEnableClasspath ) ) { // TODO what is this? // parameters.add( "--classpath" ); // parameters.add( parsedClasspath ); } if ( isNotNullAndTrue( parsedEnableLibraries ) ) { // TODO libraries // parameters.add( "--libraries" ); // parameters.add( parsedLibraries ); } List< File > files = new ArrayList< File >(); files.add( resourceDirectory ); files.add( androidManifestFile ); files.add( sourceDirectory ); files.add( assetsDirectory ); client.run( registry, files ); } catch ( IOException ex ) { throw new MojoExecutionException( ex.getMessage(), ex ); } }
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 ) throws IOException, MojoExecutionException { final StringBuilder makeFile = new StringBuilder( "# Generated by Android Maven Plugin\n" ); final List<File> includeDirectories = new ArrayList<File>(); // Add now output - allows us to somewhat intelligently determine the include paths to use for the header // archive makeFile.append( "$(shell echo \"LOCAL_C_INCLUDES=$(LOCAL_C_INCLUDES)\" > $(" + MAKEFILE_CAPTURE_FILE + "))" ); makeFile.append( '\n' ); makeFile.append( "$(shell echo \"LOCAL_PATH=$(LOCAL_PATH)\" >> $(" + MAKEFILE_CAPTURE_FILE + "))" ); makeFile.append( '\n' ); makeFile.append( "$(shell echo \"LOCAL_MODULE_FILENAME=$(LOCAL_MODULE_FILENAME)\" >> $(" + MAKEFILE_CAPTURE_FILE + "))" ); makeFile.append( '\n' ); makeFile.append( "$(shell echo \"LOCAL_MODULE=$(LOCAL_MODULE)\" >> $(" + MAKEFILE_CAPTURE_FILE + "))" ); makeFile.append( '\n' ); makeFile.append( "$(shell echo \"LOCAL_CFLAGS=$(LOCAL_CFLAGS)\" >> $(" + MAKEFILE_CAPTURE_FILE + "))" ); makeFile.append( '\n' ); if ( ! artifacts.isEmpty() ) { for ( Artifact artifact : artifacts ) { if ( artifact.hasClassifier() ) { makeFile.append( '\n' ); makeFile.append( "ifeq ($(TARGET_ARCH_ABI)," ).append( artifact.getClassifier() ).append( ")\n" ); } makeFile.append( "#\n" ); makeFile.append( "# Group ID: " ); makeFile.append( artifact.getGroupId() ); makeFile.append( '\n' ); makeFile.append( "# Artifact ID: " ); makeFile.append( artifact.getArtifactId() ); makeFile.append( '\n' ); makeFile.append( "# Artifact Type: " ); makeFile.append( artifact.getType() ); makeFile.append( '\n' ); makeFile.append( "# Version: " ); makeFile.append( artifact.getVersion() ); makeFile.append( '\n' ); makeFile.append( "include $(CLEAR_VARS)" ); makeFile.append( '\n' ); makeFile.append( "LOCAL_MODULE := " ); makeFile.append( artifact.getArtifactId() ); makeFile.append( '\n' ); final boolean apklibStatic = addLibraryDetails( makeFile, outputDir, artifact, ndkArchitecture ); if ( useHeaderArchives ) { try { Artifact harArtifact = new DefaultArtifact( artifact.getGroupId(), artifact.getArtifactId(), artifact.getVersion(), artifact.getScope(), "har", artifact.getClassifier(), artifact.getArtifactHandler() ); final Artifact resolvedHarArtifact = AetherHelper .resolveArtifact( harArtifact, repoSystem, repoSession, projectRepos ); File includeDir = new File( System.getProperty( "java.io.tmpdir" ), "android_maven_plugin_native_includes" + System.currentTimeMillis() + "_" + resolvedHarArtifact.getArtifactId() ); includeDir.deleteOnExit(); includeDirectories.add( includeDir ); JarHelper.unjar( new JarFile( resolvedHarArtifact.getFile() ), includeDir, new JarHelper.UnjarListener() { @Override public boolean include( JarEntry jarEntry ) { return ! jarEntry.getName().startsWith( "META-INF" ); } } ); makeFile.append( "LOCAL_EXPORT_C_INCLUDES := " ); final String str = includeDir.getAbsolutePath(); makeFile.append( str ); makeFile.append( '\n' ); if ( log.isDebugEnabled() ) { Collection<File> includes = FileUtils.listFiles( includeDir, TrueFileFilter.INSTANCE, TrueFileFilter.INSTANCE ); log.debug( "Listing LOCAL_EXPORT_C_INCLUDES for " + artifact.getId() + ": " + includes ); } } catch ( Exception e ) { throw new MojoExecutionException( "Error while resolving header archive file for: " + artifact.getArtifactId(), e ); } } if ( "a".equals( artifact.getType() ) || apklibStatic ) { makeFile.append( "include $(PREBUILT_STATIC_LIBRARY)\n" ); } else { makeFile.append( "include $(PREBUILT_SHARED_LIBRARY)\n" ); } if ( artifact.hasClassifier() ) { makeFile.append( "endif #" ).append( artifact.getClassifier() ).append( '\n' ); makeFile.append( '\n' ); } } } return new MakefileHolder( includeDirectories, makeFile.toString() ); } #location 71 #vulnerability type RESOURCE_LEAK
#fixed code public MakefileHolder createMakefileFromArtifacts( File outputDir, Set<Artifact> artifacts, String ndkArchitecture, boolean useHeaderArchives ) throws IOException, MojoExecutionException { final StringBuilder makeFile = new StringBuilder( "# Generated by Android Maven Plugin\n" ); final List<File> includeDirectories = new ArrayList<File>(); // Add now output - allows us to somewhat intelligently determine the include paths to use for the header // archive makeFile.append( "$(shell echo \"LOCAL_C_INCLUDES=$(LOCAL_C_INCLUDES)\" > $(" + MAKEFILE_CAPTURE_FILE + "))" ); makeFile.append( '\n' ); makeFile.append( "$(shell echo \"LOCAL_PATH=$(LOCAL_PATH)\" >> $(" + MAKEFILE_CAPTURE_FILE + "))" ); makeFile.append( '\n' ); makeFile.append( "$(shell echo \"LOCAL_MODULE_FILENAME=$(LOCAL_MODULE_FILENAME)\" >> $(" + MAKEFILE_CAPTURE_FILE + "))" ); makeFile.append( '\n' ); makeFile.append( "$(shell echo \"LOCAL_MODULE=$(LOCAL_MODULE)\" >> $(" + MAKEFILE_CAPTURE_FILE + "))" ); makeFile.append( '\n' ); makeFile.append( "$(shell echo \"LOCAL_CFLAGS=$(LOCAL_CFLAGS)\" >> $(" + MAKEFILE_CAPTURE_FILE + "))" ); makeFile.append( '\n' ); if ( ! artifacts.isEmpty() ) { for ( Artifact artifact : artifacts ) { final String architecture = NativeHelper.extractArchitectureFromArtifact( artifact ); makeFile.append( '\n' ); makeFile.append( "ifeq ($(TARGET_ARCH_ABI)," ).append( architecture ).append( ")\n" ); makeFile.append( "#\n" ); makeFile.append( "# Group ID: " ); makeFile.append( artifact.getGroupId() ); makeFile.append( '\n' ); makeFile.append( "# Artifact ID: " ); makeFile.append( artifact.getArtifactId() ); makeFile.append( '\n' ); makeFile.append( "# Artifact Type: " ); makeFile.append( artifact.getType() ); makeFile.append( '\n' ); makeFile.append( "# Version: " ); makeFile.append( artifact.getVersion() ); makeFile.append( '\n' ); makeFile.append( "include $(CLEAR_VARS)" ); makeFile.append( '\n' ); makeFile.append( "LOCAL_MODULE := " ); makeFile.append( artifact.getArtifactId() ); makeFile.append( '\n' ); final boolean apklibStatic = addLibraryDetails( makeFile, outputDir, artifact, ndkArchitecture ); if ( useHeaderArchives ) { try { Artifact harArtifact = new DefaultArtifact( artifact.getGroupId(), artifact.getArtifactId(), artifact.getVersion(), artifact.getScope(), "har", artifact.getClassifier(), artifact.getArtifactHandler() ); final Artifact resolvedHarArtifact = AetherHelper .resolveArtifact( harArtifact, repoSystem, repoSession, projectRepos ); File includeDir = new File( System.getProperty( "java.io.tmpdir" ), "android_maven_plugin_native_includes" + System.currentTimeMillis() + "_" + resolvedHarArtifact.getArtifactId() ); includeDir.deleteOnExit(); includeDirectories.add( includeDir ); JarHelper.unjar( new JarFile( resolvedHarArtifact.getFile() ), includeDir, new JarHelper.UnjarListener() { @Override public boolean include( JarEntry jarEntry ) { return ! jarEntry.getName().startsWith( "META-INF" ); } } ); makeFile.append( "LOCAL_EXPORT_C_INCLUDES := " ); final String str = includeDir.getAbsolutePath(); makeFile.append( str ); makeFile.append( '\n' ); if ( log.isDebugEnabled() ) { Collection<File> includes = FileUtils.listFiles( includeDir, TrueFileFilter.INSTANCE, TrueFileFilter.INSTANCE ); log.debug( "Listing LOCAL_EXPORT_C_INCLUDES for " + artifact.getId() + ": " + includes ); } } catch ( Exception e ) { throw new MojoExecutionException( "Error while resolving header archive file for: " + artifact.getArtifactId(), e ); } } if ( "a".equals( artifact.getType() ) || apklibStatic ) { makeFile.append( "include $(PREBUILT_STATIC_LIBRARY)\n" ); } else { makeFile.append( "include $(PREBUILT_SHARED_LIBRARY)\n" ); } makeFile.append( "endif #" ).append( artifact.getClassifier() ).append( '\n' ); makeFile.append( '\n' ); } } return new MakefileHolder( includeDirectories, makeFile.toString() ); }
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 ); if ( StringUtils.isNotBlank( customPackage ) ) { packageName = customPackage; } generateBuildConfigForPackage( packageName ); try { // Generate the BuildConfig for any APKLIB and AAR dependencies. // Need to generate for AAR, because some old AARs like ActionBarSherlock do not have BuildConfig (or R) for ( Artifact artifact : getTransitiveDependencyArtifacts( APKLIB, AAR ) ) { final File manifest = new File( getUnpackedLibFolder( artifact ), "AndroidManifest.xml" ); final String depPackageName = extractPackageNameFromAndroidManifest( manifest ); if ( artifact.getType().equals( AAR ) ) { final JarFile jar = new JarFile( getUnpackedAarClassesJar( artifact ) ); final JarEntry entry = jar.getJarEntry( depPackageName.replace( '.', '/' ) + "/BuildConfig.class" ); if ( entry != null ) { getLog().info( "Skip BuildConfig.java generation for " + artifact.getGroupId() + " " + artifact.getArtifactId() ); continue; } } generateBuildConfigForPackage( depPackageName ); } } catch ( IOException e ) { getLog().error( "Error generating BuildConfig ", e ); throw new MojoExecutionException( "Error generating BuildConfig", e ); } } #location 25 #vulnerability type RESOURCE_LEAK
#fixed code private void generateBuildConfig() throws MojoExecutionException { getLog().debug( "Generating BuildConfig file" ); // Create the BuildConfig for our package. String packageName = extractPackageNameFromAndroidManifest( androidManifestFile ); if ( StringUtils.isNotBlank( customPackage ) ) { packageName = customPackage; } generateBuildConfigForPackage( packageName ); // Generate the BuildConfig for any APKLIB and AAR dependencies. // Need to generate for AAR, because some old AARs like ActionBarSherlock do not have BuildConfig (or R) for ( Artifact artifact : getTransitiveDependencyArtifacts( APKLIB, AAR ) ) { if ( skipBuildConfigGeneration( artifact ) ) { continue; } final File manifest = new File( getUnpackedLibFolder( artifact ), "AndroidManifest.xml" ); final String depPackageName = extractPackageNameFromAndroidManifest( manifest ); generateBuildConfigForPackage( depPackageName ); } }
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 ) throws IOException, MojoExecutionException { final StringBuilder makeFile = new StringBuilder( "# Generated by Android Maven Plugin\n" ); final List<File> includeDirectories = new ArrayList<File>(); // Add now output - allows us to somewhat intelligently determine the include paths to use for the header // archive makeFile.append( "$(shell echo \"LOCAL_C_INCLUDES=$(LOCAL_C_INCLUDES)\" > $(" + MAKEFILE_CAPTURE_FILE + "))" ); makeFile.append( '\n' ); makeFile.append( "$(shell echo \"LOCAL_PATH=$(LOCAL_PATH)\" >> $(" + MAKEFILE_CAPTURE_FILE + "))" ); makeFile.append( '\n' ); makeFile.append( "$(shell echo \"LOCAL_MODULE_FILENAME=$(LOCAL_MODULE_FILENAME)\" >> $(" + MAKEFILE_CAPTURE_FILE + "))" ); makeFile.append( '\n' ); makeFile.append( "$(shell echo \"LOCAL_MODULE=$(LOCAL_MODULE)\" >> $(" + MAKEFILE_CAPTURE_FILE + "))" ); makeFile.append( '\n' ); makeFile.append( "$(shell echo \"LOCAL_CFLAGS=$(LOCAL_CFLAGS)\" >> $(" + MAKEFILE_CAPTURE_FILE + "))" ); makeFile.append( '\n' ); if ( ! artifacts.isEmpty() ) { for ( Artifact artifact : artifacts ) { boolean apklibStatic = false; makeFile.append( "#\n" ); makeFile.append( "# Group ID: " ); makeFile.append( artifact.getGroupId() ); makeFile.append( '\n' ); makeFile.append( "# Artifact ID: " ); makeFile.append( artifact.getArtifactId() ); makeFile.append( '\n' ); makeFile.append( "# Artifact Type: " ); makeFile.append( artifact.getType() ); makeFile.append( '\n' ); makeFile.append( "# Version: " ); makeFile.append( artifact.getVersion() ); makeFile.append( '\n' ); makeFile.append( "include $(CLEAR_VARS)" ); makeFile.append( '\n' ); makeFile.append( "LOCAL_MODULE := " ); makeFile.append( artifact.getArtifactId() ); makeFile.append( '\n' ); apklibStatic = addLibraryDetails( makeFile, outputDir, artifact, ndkArchitecture ); if ( useHeaderArchives ) { try { Artifact harArtifact = new DefaultArtifact( artifact.getGroupId(), artifact.getArtifactId(), artifact.getVersion(), artifact.getScope(), "har", artifact.getClassifier(), artifact.getArtifactHandler() ); final Artifact resolvedHarArtifact = AetherHelper .resolveArtifact( harArtifact, repoSystem, repoSession, projectRepos ); File includeDir = new File( System.getProperty( "java.io.tmpdir" ), "android_maven_plugin_native_includes" + System.currentTimeMillis() + "_" + resolvedHarArtifact.getArtifactId() ); includeDir.deleteOnExit(); includeDirectories.add( includeDir ); JarHelper.unjar( new JarFile( resolvedHarArtifact.getFile() ), includeDir, new JarHelper.UnjarListener() { @Override public boolean include( JarEntry jarEntry ) { return ! jarEntry.getName().startsWith( "META-INF" ); } } ); makeFile.append( "LOCAL_EXPORT_C_INCLUDES := " ); final String str = includeDir.getAbsolutePath(); makeFile.append( str ); makeFile.append( '\n' ); if ( log.isDebugEnabled() ) { Collection<File> includes = FileUtils.listFiles( includeDir, TrueFileFilter.INSTANCE, TrueFileFilter.INSTANCE ); log.debug( "Listing LOCAL_EXPORT_C_INCLUDES for " + artifact.getId() + ": " + includes ); } } catch ( Exception e ) { throw new MojoExecutionException( "Error while resolving header archive file for: " + artifact.getArtifactId(), e ); } } if ( "a".equals( artifact.getType() ) || apklibStatic ) { makeFile.append( "include $(PREBUILT_STATIC_LIBRARY)\n" ); } else { makeFile.append( "include $(PREBUILT_SHARED_LIBRARY)\n" ); } } } return new MakefileHolder( includeDirectories, makeFile.toString() ); } #location 65 #vulnerability type RESOURCE_LEAK
#fixed code public MakefileHolder createMakefileFromArtifacts( File outputDir, Set<Artifact> artifacts, String ndkArchitecture, boolean useHeaderArchives ) throws IOException, MojoExecutionException { final StringBuilder makeFile = new StringBuilder( "# Generated by Android Maven Plugin\n" ); final List<File> includeDirectories = new ArrayList<File>(); // Add now output - allows us to somewhat intelligently determine the include paths to use for the header // archive makeFile.append( "$(shell echo \"LOCAL_C_INCLUDES=$(LOCAL_C_INCLUDES)\" > $(" + MAKEFILE_CAPTURE_FILE + "))" ); makeFile.append( '\n' ); makeFile.append( "$(shell echo \"LOCAL_PATH=$(LOCAL_PATH)\" >> $(" + MAKEFILE_CAPTURE_FILE + "))" ); makeFile.append( '\n' ); makeFile.append( "$(shell echo \"LOCAL_MODULE_FILENAME=$(LOCAL_MODULE_FILENAME)\" >> $(" + MAKEFILE_CAPTURE_FILE + "))" ); makeFile.append( '\n' ); makeFile.append( "$(shell echo \"LOCAL_MODULE=$(LOCAL_MODULE)\" >> $(" + MAKEFILE_CAPTURE_FILE + "))" ); makeFile.append( '\n' ); makeFile.append( "$(shell echo \"LOCAL_CFLAGS=$(LOCAL_CFLAGS)\" >> $(" + MAKEFILE_CAPTURE_FILE + "))" ); makeFile.append( '\n' ); if ( ! artifacts.isEmpty() ) { for ( Artifact artifact : artifacts ) { if ( !NativeHelper.isMatchinArchitecture( ndkArchitecture, artifact ) ) { continue; } makeFile.append( "#\n" ); makeFile.append( "# Group ID: " ); makeFile.append( artifact.getGroupId() ); makeFile.append( '\n' ); makeFile.append( "# Artifact ID: " ); makeFile.append( artifact.getArtifactId() ); makeFile.append( '\n' ); makeFile.append( "# Artifact Type: " ); makeFile.append( artifact.getType() ); makeFile.append( '\n' ); makeFile.append( "# Version: " ); makeFile.append( artifact.getVersion() ); makeFile.append( '\n' ); makeFile.append( "include $(CLEAR_VARS)" ); makeFile.append( '\n' ); makeFile.append( "LOCAL_MODULE := " ); makeFile.append( artifact.getArtifactId() ); makeFile.append( '\n' ); final boolean apklibStatic = addLibraryDetails( makeFile, outputDir, artifact, ndkArchitecture ); if ( useHeaderArchives ) { try { Artifact harArtifact = new DefaultArtifact( artifact.getGroupId(), artifact.getArtifactId(), artifact.getVersion(), artifact.getScope(), "har", artifact.getClassifier(), artifact.getArtifactHandler() ); final Artifact resolvedHarArtifact = AetherHelper .resolveArtifact( harArtifact, repoSystem, repoSession, projectRepos ); File includeDir = new File( System.getProperty( "java.io.tmpdir" ), "android_maven_plugin_native_includes" + System.currentTimeMillis() + "_" + resolvedHarArtifact.getArtifactId() ); includeDir.deleteOnExit(); includeDirectories.add( includeDir ); JarHelper.unjar( new JarFile( resolvedHarArtifact.getFile() ), includeDir, new JarHelper.UnjarListener() { @Override public boolean include( JarEntry jarEntry ) { return ! jarEntry.getName().startsWith( "META-INF" ); } } ); makeFile.append( "LOCAL_EXPORT_C_INCLUDES := " ); final String str = includeDir.getAbsolutePath(); makeFile.append( str ); makeFile.append( '\n' ); if ( log.isDebugEnabled() ) { Collection<File> includes = FileUtils.listFiles( includeDir, TrueFileFilter.INSTANCE, TrueFileFilter.INSTANCE ); log.debug( "Listing LOCAL_EXPORT_C_INCLUDES for " + artifact.getId() + ": " + includes ); } } catch ( Exception e ) { throw new MojoExecutionException( "Error while resolving header archive file for: " + artifact.getArtifactId(), e ); } } if ( "a".equals( artifact.getType() ) || apklibStatic ) { makeFile.append( "include $(PREBUILT_STATIC_LIBRARY)\n" ); } else { makeFile.append( "include $(PREBUILT_SHARED_LIBRARY)\n" ); } } } return new MakefileHolder( includeDirectories, makeFile.toString() ); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code private void performVersionCodeUpdateFromVersion( Element manifestElement ) { String verString = project.getVersion(); getLog().debug( "Generating versionCode for " + verString ); ArtifactVersion artifactVersion = new DefaultArtifactVersion( verString ); String verCode; if ( artifactVersion.getMajorVersion() < 1 && artifactVersion.getMinorVersion() < 1 && artifactVersion.getIncrementalVersion() < 1 ) { getLog().warn( "Problem parsing version number occurred. Using fall back to determine version code. " ); verCode = verString.replaceAll( "\\D", "" ); Attr versionCodeAttr = manifestElement.getAttributeNode( ATTR_VERSION_CODE ); int currentVersionCode = 0; if ( versionCodeAttr != null ) { currentVersionCode = NumberUtils.toInt( versionCodeAttr.getValue(), 0 ); } if ( Integer.parseInt( verCode ) < currentVersionCode ) { getLog().info( verCode + " < " + currentVersionCode + " so padding versionCode" ); verCode = StringUtils.rightPad( verCode, versionCodeAttr.getValue().length(), "0" ); } } else { verCode = Integer.toString( artifactVersion.getMajorVersion() * MAJOR_VERSION_POSITION + artifactVersion.getMinorVersion() * MINOR_VERSION_POSITION + artifactVersion.getIncrementalVersion() * INCREMENTAL_VERSION_POSITION ); } getLog().info( "Setting " + ATTR_VERSION_CODE + " to " + verCode ); manifestElement.setAttribute( ATTR_VERSION_CODE, verCode ); project.getProperties().setProperty( "android.manifest.versionCode", String.valueOf( verCode ) ); } #location 24 #vulnerability type NULL_DEREFERENCE
#fixed code private void performVersionCodeUpdateFromVersion( Element manifestElement ) { String verString = project.getVersion(); getLog().debug( "Generating versionCode for " + verString ); String verCode = generateVersionCodeFromVersionName( verString ); getLog().info( "Setting " + ATTR_VERSION_CODE + " to " + verCode ); manifestElement.setAttribute( ATTR_VERSION_CODE, verCode ); project.getProperties().setProperty( "android.manifest.versionCode", String.valueOf( verCode ) ); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code private void updateWithMetaInf( ZipOutputStream zos, File jarFile, Set<String> entries, boolean metaInfOnly ) throws ZipException, IOException { ZipFile zin = new ZipFile( jarFile ); for( Enumeration<? extends ZipEntry> en = zin.entries(); en.hasMoreElements(); ) { ZipEntry ze = en.nextElement(); if( ze.isDirectory() ) continue; String zn = ze.getName(); if( metaInfOnly ) { if( !zn.startsWith( "META-INF/" ) ) { continue; } if( !entries.add( zn ) ) { continue; } if( !metaInfMatches( zn ) ) { continue; } } zos.putNextEntry( new ZipEntry( zn ) ); InputStream is = zin.getInputStream( ze ); copyStreamWithoutClosing( is, zos ); is.close(); zos.closeEntry(); } zin.close(); } #location 17 #vulnerability type RESOURCE_LEAK
#fixed code private void updateWithMetaInf( ZipOutputStream zos, File jarFile, Set<String> entries, boolean metaInfOnly ) throws ZipException, IOException { ZipFile zin = new ZipFile( jarFile ); for( Enumeration<? extends ZipEntry> en = zin.entries(); en.hasMoreElements(); ) { ZipEntry ze = en.nextElement(); if( ze.isDirectory() ) continue; String zn = ze.getName(); if( metaInfOnly ) { if( !zn.startsWith( "META-INF/" ) ) { continue; } if( this.extractDuplicates && !entries.add( zn ) ) { continue; } if( !metaInfMatches( zn ) ) { continue; } } zos.putNextEntry( new ZipEntry( zn ) ); InputStream is = zin.getInputStream( ze ); copyStreamWithoutClosing( is, zos ); is.close(); zos.closeEntry(); } zin.close(); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code @Test public void testTokenFilter() throws IOException{ StringReader sr = new StringReader("刘德华"); Analyzer analyzer = new StandardAnalyzer(Version.LUCENE_36); PinyinTokenFilter filter = new PinyinTokenFilter(analyzer.tokenStream("f",sr),"","none"); List<String> pinyin= new ArrayList<String>(); while (filter.incrementToken()) { CharTermAttribute ta = filter.getAttribute(CharTermAttribute.class); pinyin.add(ta.toString()); } Assert.assertEquals(3,pinyin.size()); Assert.assertEquals("liu",pinyin.get(0)); Assert.assertEquals("de",pinyin.get(1)); Assert.assertEquals("hua",pinyin.get(2)); sr = new StringReader("刘德华"); analyzer = new KeywordAnalyzer(); filter = new PinyinTokenFilter(analyzer.tokenStream("f",sr),"","only"); pinyin.clear(); while (filter.incrementToken()) { CharTermAttribute ta = filter.getAttribute(CharTermAttribute.class); pinyin.add(ta.toString()); } Assert.assertEquals(1,pinyin.size()); Assert.assertEquals("ldh",pinyin.get(0)); } #location 19 #vulnerability type RESOURCE_LEAK
#fixed code @Test public void testTokenFilter() throws IOException{ StringReader sr = new StringReader("刘德华"); Analyzer analyzer = new StandardAnalyzer(Version.LUCENE_41); PinyinTokenFilter filter = new PinyinTokenFilter(analyzer.tokenStream("f",sr),"","none"); List<String> pinyin= new ArrayList<String>(); filter.reset(); while (filter.incrementToken()) { CharTermAttribute ta = filter.getAttribute(CharTermAttribute.class); pinyin.add(ta.toString()); } // Assert.assertEquals(3,pinyin.size()); System.out.println(pinyin.get(0)); System.out.println(pinyin.get(1)); System.out.println(pinyin.get(2)); Assert.assertEquals("liu",pinyin.get(0)); Assert.assertEquals("de",pinyin.get(1)); Assert.assertEquals("hua",pinyin.get(2)); sr = new StringReader("刘德华"); analyzer = new KeywordAnalyzer(); filter = new PinyinTokenFilter(analyzer.tokenStream("f",sr),"","only"); pinyin.clear(); while (filter.incrementToken()) { CharTermAttribute ta = filter.getAttribute(CharTermAttribute.class); pinyin.add(ta.toString()); } Assert.assertEquals(1,pinyin.size()); Assert.assertEquals("ldh",pinyin.get(0)); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public V put(K key, V value) { Packet request = createRequestPacket(); request.setTxnId(0); request.setOperation(ClusterOperation.CONCURRENT_MAP_PUT); request.setKey(Serializer.toByte(key)); request.setValue(Serializer.toByte(value)); Packet response = callAndGetResult(request); if(response.getValue()!=null){ return (V)Serializer.toObject(response.getValue()); } return null; } #location 11 #vulnerability type NULL_DEREFERENCE
#fixed code public V put(K key, V value) { return (V)doOp(ClusterOperation.CONCURRENT_MAP_PUT, Serializer.toByte(key), Serializer.toByte(value)); }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public void process(Object obj) { long processStart = System.nanoTime(); if (obj instanceof Invocation) { Invocation inv = (Invocation) obj; MemberImpl memberFrom = getMember(inv.conn.getEndPoint()); if (memberFrom != null) { memberFrom.didRead(); } int operation = inv.operation; if (operation < 50) { ClusterManager.get().handle(inv); } else if (operation < 300) { ListenerManager.get().handle(inv); } else if (operation < 400) { ExecutorManager.get().handle(inv); } else if (operation < 500) { BlockingQueueManager.get().handle(inv); } else if (operation < 600) { ConcurrentMapManager.get().handle(inv); } else throw new RuntimeException("Unknown operation " + operation); } else if (obj instanceof Processable) { ((Processable) obj).process(); } else if (obj instanceof Runnable) { synchronized (obj) { ((Runnable) obj).run(); obj.notify(); } } else throw new RuntimeException("Unkown obj " + obj); long processEnd = System.nanoTime(); long elipsedTime = processEnd - processStart; totalProcessTime += elipsedTime; long duration = (processEnd - start); if (duration > TimeUnit.SECONDS.toNanos(10)) { if (DEBUG) { System.out.println("ServiceProcessUtilization: " + ((totalProcessTime * 100) / duration) + " %"); } start = processEnd; totalProcessTime = 0; } } #location 11 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code public void process(Object obj) { long processStart = System.nanoTime(); if (obj instanceof Invocation) { Invocation inv = (Invocation) obj; MemberImpl memberFrom = getMember(inv.conn.getEndPoint()); if (memberFrom != null) { memberFrom.didRead(); } int operation = inv.operation; if (operation < 50) { ClusterManager.get().handle(inv); } else if (operation < 300) { ListenerManager.get().handle(inv); } else if (operation < 400) { ExecutorManager.get().handle(inv); } else if (operation < 500) { BlockingQueueManager.get().handle(inv); } else if (operation < 600) { ConcurrentMapManager.get().handle(inv); } else throw new RuntimeException("Unknown operation " + operation); } else if (obj instanceof Processable) { ((Processable) obj).process(); } else if (obj instanceof Runnable) { synchronized (obj) { ((Runnable) obj).run(); obj.notify(); } } else throw new RuntimeException("Unkown obj " + obj); long processEnd = System.nanoTime(); long elipsedTime = processEnd - processStart; totalProcessTime += elipsedTime; long duration = (processEnd - start); if (duration > UTILIZATION_CHECK_INTERVAL) { if (DEBUG) { System.out.println("ServiceProcessUtilization: " + ((totalProcessTime * 100) / duration) + " %"); } start = processEnd; totalProcessTime = 0; } }
Below is the vulnerable code, please generate the patch based on the following information.
#vulnerable code public void run() { while (running) { Object obj = null; try { lsBuffer.clear(); queue.drainTo(lsBuffer); int size = lsBuffer.size(); if (size > 0) { for (int i = 0; i < size; i++) { obj = lsBuffer.get(i); process(obj); } lsBuffer.clear(); } else { obj = queue.take(); process(obj); } } catch (InterruptedException e) { Node.get().handleInterruptedException(Thread.currentThread(), e); } catch (Throwable e) { if (DEBUG) { System.out.println(e + ", message: " + e + ", obj=" + obj); } e.printStackTrace(System.out); } } } #location 11 #vulnerability type THREAD_SAFETY_VIOLATION
#fixed code public void run() { while (running) { Object obj = null; try { lsBuffer.clear(); queue.drainTo(lsBuffer); int size = lsBuffer.size(); if (size > 0) { for (int i = 0; i < size; i++) { obj = lsBuffer.get(i); checkHeartbeat(); process(obj); } lsBuffer.clear(); } else { obj = queue.poll(100, TimeUnit.MILLISECONDS); checkHeartbeat(); if (obj != null) { process(obj); } } } catch (InterruptedException e) { Node.get().handleInterruptedException(Thread.currentThread(), e); } catch (Throwable e) { if (DEBUG) { System.out.println(e + ", message: " + e + ", obj=" + obj); } e.printStackTrace(System.out); } } }
Below is the vulnerable code, please generate the patch based on the following information.