instruction
stringclasses 1
value | output
stringlengths 64
69.4k
| input
stringlengths 205
32.4k
|
---|---|---|
Below is the vulnerable code, please generate the patch based on the following information. | #fixed code
@Override
public SymbolReference<? extends ValueDeclaration> solveSymbol(String name, TypeSolver typeSolver) {
return getParent().solveSymbol(name, typeSolver);
} | #vulnerable code
@Override
public SymbolReference<? extends ValueDeclaration> solveSymbol(String name, TypeSolver typeSolver) {
return JavaParserFactory.getContext(wrappedNode.getParentNode()).solveSymbol(name, typeSolver);
}
#location 3
#vulnerability type NULL_DEREFERENCE |
Below is the vulnerable code, please generate the patch based on the following information. | #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 {
// 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;
} | #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;
char prevChar = '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 (prevChar=='/' && c=='/'){
currentLineComment = new LineComment();
currentLineComment.setBeginLine(currLine);
currentLineComment.setBeginColumn(currCol-1);
state = State.IN_LINE_COMMENT;
currentContent = new StringBuffer();
} else if (prevChar=='/' && 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 (prevChar=='*' && c=='/'){
// 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;
}
prevChar = c;
}
if (state==State.IN_LINE_COMMENT){
currentLineComment.setContent(currentContent.toString());
currentLineComment.setEndLine(currLine);
currentLineComment.setEndColumn(currCol);
comments.addComment(currentLineComment);
}
return comments;
}
#location 75
#vulnerability type NULL_DEREFERENCE |
Below is the vulnerable code, please generate the patch based on the following information. | #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();
} | #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 17
#vulnerability type RESOURCE_LEAK |
Below is the vulnerable code, please generate the patch based on the following information. | #fixed code
@Test
void resolveFieldOfEnumAsInternalClassOfClassQualifiedDifferentPackage() 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("foo.bar.BinaryExpr.Operator.AND") && n.getRange().get().begin.line == 7);
assertTrue(fae.isPresent());
assertEquals("foo.bar.BinaryExpr.Operator", fae.get().resolve().getType().describe());
assertEquals("AND", fae.get().resolve().getName());
} | #vulnerable code
@Test
void resolveFieldOfEnumAsInternalClassOfClassQualifiedDifferentPackage() 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("foo.bar.BinaryExpr.Operator.AND") && n.getRange().get().begin.line == 7);
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 |
Below is the vulnerable code, please generate the patch based on the following information. | #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());
} | #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 |
Below is the vulnerable code, please generate the patch based on the following information. | #fixed code
public CommentsCollection parse(final InputStream in, final String charsetName) throws IOException {
return parse(new InputStreamReader(in, charsetName));
} | #vulnerable code
public CommentsCollection parse(final InputStream in, final String charsetName) throws IOException, UnsupportedEncodingException {
boolean lastWasASlashR = false;
BufferedReader br = new BufferedReader(new InputStreamReader(in, charsetName));
CommentsCollection comments = new CommentsCollection();
int r;
ParserState parserState = new ParserState();
State state = State.CODE;
LineComment currentLineComment = null;
BlockComment currentBlockComment = null;
StringBuilder 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 (parserState.isLastChar('/') && c == '/') {
currentLineComment = new LineComment();
currentLineComment.setBeginLine(currLine);
currentLineComment.setBeginColumn(currCol - 1);
state = State.IN_LINE_COMMENT;
currentContent = new StringBuilder();
} else if (parserState.isLastChar('/') && c == '*') {
currentBlockComment = new BlockComment();
currentBlockComment.setBeginLine(currLine);
currentBlockComment.setBeginColumn(currCol - 1);
state = State.IN_BLOCK_COMMENT;
currentContent = new StringBuilder();
} else if (c == '"') {
state = State.IN_STRING;
} else if (c == '\'') {
state = State.IN_CHAR;
} 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:
// '/*/' is not a valid block comment: it starts the block comment but it does not close it
// However this sequence can be contained inside a comment and in that case it close the comment
// For example:
// /* blah blah /*/
// At the previous line we had a valid block comment
if (parserState.isLastChar('*') && c=='/' && (!parserState.isSecondToLastChar('/') || currentContent.length() > 0)){
// 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' ? System.getProperty("line.separator") : c);
}
break;
case IN_STRING:
if (!parserState.isLastChar('\\') && c == '"') {
state = State.CODE;
}
break;
case IN_CHAR:
if (!parserState.isLastChar('\\') && 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;
}
// ok we have two slashes in a row inside a string
// we want to replace them with... anything else, to not confuse
// the parser
if (state==State.IN_STRING && parserState.isLastChar('\\') && c == '\\') {
parserState.reset();
} else {
parserState.update(c);
}
}
if (state==State.IN_LINE_COMMENT){
currentLineComment.setContent(currentContent.toString());
currentLineComment.setEndLine(currLine);
currentLineComment.setEndColumn(currCol);
comments.addComment(currentLineComment);
}
return comments;
}
#location 125
#vulnerability type RESOURCE_LEAK |
Below is the vulnerable code, please generate the patch based on the following information. | #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);
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());
} | #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));
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 15
#vulnerability type RESOURCE_LEAK |
Below is the vulnerable code, please generate the patch based on the following information. | #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());
} | #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 |
Below is the vulnerable code, please generate the patch based on the following information. | #fixed code
@Override
public SymbolReference<TypeDeclaration> solveType(String name, TypeSolver typeSolver) {
return JavaParserFactory.getContext(getParentNode(wrappedNode), typeSolver).solveType(name, typeSolver);
} | #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 |
Below is the vulnerable code, please generate the patch based on the following information. | #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);
}
} | #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 |
Below is the vulnerable code, please generate the patch based on the following information. | #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());
} | #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 |
Below is the vulnerable code, please generate the patch based on the following information. | #fixed code
@Override
public SymbolReference<MethodDeclaration> solveMethod(String name, List<Type> parameterTypes) {
Context ctx = getContext();
return ctx.solveMethod(name, parameterTypes, typeSolver);
} | #vulnerable code
@Override
public SymbolReference<MethodDeclaration> solveMethod(String name, List<Type> parameterTypes) {
return getContext().solveMethod(name, parameterTypes, typeSolver());
}
#location 3
#vulnerability type NULL_DEREFERENCE |
Below is the vulnerable code, please generate the patch based on the following information. | #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());
}
} | #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 |
Below is the vulnerable code, please generate the patch based on the following information. | #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();
} | #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 |
Below is the vulnerable code, please generate the patch based on the following information. | #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);
}
} | #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 |
Below is the vulnerable code, please generate the patch based on the following information. | #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());
} | #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 |
Below is the vulnerable code, please generate the patch based on the following information. | #fixed code
@Override
public Optional<Value> solveSymbolAsValue(String name, TypeSolver typeSolver) {
return getParent().solveSymbolAsValue(name, typeSolver);
} | #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 |
Below is the vulnerable code, please generate the patch based on the following information. | #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);
} | #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 |
Below is the vulnerable code, please generate the patch based on the following information. | #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());
} | #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 |
Below is the vulnerable code, please generate the patch based on the following information. | #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());
} | #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 |
Below is the vulnerable code, please generate the patch based on the following information. | #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());
} | #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 |
Below is the vulnerable code, please generate the patch based on the following information. | #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());
} | #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 |
Below is the vulnerable code, please generate the patch based on the following information. | #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);
} | #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 |
Below is the vulnerable code, please generate the patch based on the following information. | #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);
} | #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 |
Below is the vulnerable code, please generate the patch based on the following information. | #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()));
} | #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 |
Below is the vulnerable code, please generate the patch based on the following information. | #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()));
} | #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 |
Below is the vulnerable code, please generate the patch based on the following information. | #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);
} | #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 |
Below is the vulnerable code, please generate the patch based on the following information. | #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);
} | #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 |
Below is the vulnerable code, please generate the patch based on the following information. | #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);
}
} | #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 |
Below is the vulnerable code, please generate the patch based on the following information. | #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);
} | #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 |
Below is the vulnerable code, please generate the patch based on the following information. | #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);
} | #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 |
Below is the vulnerable code, please generate the patch based on the following information. | #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()));
} | #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 |
Below is the vulnerable code, please generate the patch based on the following information. | #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);
} | #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 |
Below is the vulnerable code, please generate the patch based on the following information. | #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);
} | #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 |
Below is the vulnerable code, please generate the patch based on the following information. | #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()));
} | #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 |
Below is the vulnerable code, please generate the patch based on the following information. | #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);
} | #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 |
Below is the vulnerable code, please generate the patch based on the following information. | #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()));
} | #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 |
Below is the vulnerable code, please generate the patch based on the following information. | #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);
}
}
}
}
} | #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 |
Below is the vulnerable code, please generate the patch based on the following information. | #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();
}
} | #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 |
Below is the vulnerable code, please generate the patch based on the following information. | #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();
} | #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 |
Below is the vulnerable code, please generate the patch based on the following information. | #fixed code
public void disconnect() throws IOException {
terminateKeepAliveThread();
terminateConnect();
} | #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 |
Below is the vulnerable code, please generate the patch based on the following information. | #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);
}
}
}
}
} | #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 |
Below is the vulnerable code, please generate the patch based on the following information. | #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);
}
}
}
}
} | #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 |
Below is the vulnerable code, please generate the patch based on the following information. | #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);
}
}
}
}
} | #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 |
Below is the vulnerable code, please generate the patch based on the following information. | #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);
}
}
}
}
} | #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 |
Below is the vulnerable code, please generate the patch based on the following information. | #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);
}
}
}
}
} | #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 |
Below is the vulnerable code, please generate the patch based on the following information. | #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);
}
}
}
}
} | #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 |
Below is the vulnerable code, please generate the patch based on the following information. | #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);
}
}
}
}
} | #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 |
Below is the vulnerable code, please generate the patch based on the following information. | #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);
} | #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 |
Below is the vulnerable code, please generate the patch based on the following information. | #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);
}
} | #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 |
Below is the vulnerable code, please generate the patch based on the following information. | #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();
}
} | #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 |
Below is the vulnerable code, please generate the patch based on the following information. | #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"));
} | #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 |
Below is the vulnerable code, please generate the patch based on the following information. | #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());
}
} | #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 |
Below is the vulnerable code, please generate the patch based on the following information. | #fixed code
public VerbalExpression replace(String source, String value) {
this.updatePattern();
this.source.replaceAll(pattern,value);
return this;
} | #vulnerable code
public VerbalExpression replace(String source, String value) {
this.add("");
this.source.replaceAll(pattern,value);
return this;
}
#location 3
#vulnerability type NULL_DEREFERENCE |
Below is the vulnerable code, please generate the patch based on the following information. | #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;
} | #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 |
Below is the vulnerable code, please generate the patch based on the following information. | #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);
} | #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 |
Below is the vulnerable code, please generate the patch based on the following information. | #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 );
}
} | #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 |
Below is the vulnerable code, please generate the patch based on the following information. | #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 ) );
} | #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 |
Below is the vulnerable code, please generate the patch based on the following information. | #fixed code
public V put(K key, V value) {
return (V)doOp(ClusterOperation.CONCURRENT_MAP_PUT, Serializer.toByte(key), Serializer.toByte(value));
} | #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 |
Below is the vulnerable code, please generate the patch based on the following information. | #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;
}
} | #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 |
Below is the vulnerable code, please generate the patch based on the following information. | #fixed code
public V get(Object key) {
return (V)doOp(ClusterOperation.CONCURRENT_MAP_GET, Serializer.toByte(key), null);
} | #vulnerable code
public V get(Object key) {
// MapGetCall mGet = new MapGetCall();
Packet request = createRequestPacket();
request.setOperation(ClusterOperation.CONCURRENT_MAP_GET);
request.setKey(Serializer.toByte(key));
Packet response = callAndGetResult(request);
if(response.getValue()!=null){
return (V)Serializer.toObject(response.getValue());
}
return null;
}
#location 9
#vulnerability type NULL_DEREFERENCE |
Below is the vulnerable code, please generate the patch based on the following information. | #fixed code
protected Packet callAndGetResult(Packet request) {
Call c = createCall(request);
return doCall(c);
} | #vulnerable code
protected Packet callAndGetResult(Packet request) {
Call c = createCall(request);
synchronized (c) {
try {
out.enQueue(c);
c.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
Packet response = c.getResponse();
return response;
}
#location 2
#vulnerability type THREAD_SAFETY_VIOLATION |
Below is the vulnerable code, please generate the patch based on the following information. | #fixed code
public void run() {
boolean readPackets = false;
boolean readProcessables = false;
while (running) {
readPackets = (dequeuePackets() != 0);
readProcessables = (dequeueProcessables() != 0);
if (!readPackets && !readProcessables) {
try {
synchronized (notEmptyLock) {
notEmptyLock.wait(100);
}
checkPeriodics();
} catch (InterruptedException e) {
node.handleInterruptedException(Thread.currentThread(), e);
}
}
}
packetQueue.clear();
processableQueue.clear();
} | #vulnerable code
public void run() {
boolean readPackets = false;
boolean readProcessables = false;
while (running) {
readPackets = (dequeuePackets() != 0);
readProcessables = (dequeueProcessables() != 0);
if (!readPackets && !readProcessables) {
enqueueLock.lock();
try {
notEmpty.await(100, TimeUnit.MILLISECONDS);
checkPeriodics();
} catch (InterruptedException e) {
node.handleInterruptedException(Thread.currentThread(), e);
} finally {
enqueueLock.unlock();
}
}
}
packetQueue.clear();
processableQueue.clear();
}
#location 11
#vulnerability type THREAD_SAFETY_VIOLATION |
Below is the vulnerable code, please generate the patch based on the following information. | #fixed code
void reArrangeBlocks() {
if (concurrentMapManager.isMaster()) {
Map<Address, Integer> addressBlocks = getCurrentMemberBlocks();
if (addressBlocks.size() == 0) {
return;
}
List<Block> lsBlocksToRedistribute = new ArrayList<Block>();
int aveBlockOwnCount = BLOCK_COUNT / (addressBlocks.size());
for (Block blockReal : blocks) {
if (blockReal.getOwner() == null) {
logger.log(Level.SEVERE, "Master cannot have null block owner " + blockReal);
return;
}
if (blockReal.isMigrating()) {
logger.log(Level.SEVERE, "Cannot have migrating block " + blockReal);
return;
}
Integer countInt = addressBlocks.get(blockReal.getOwner());
int count = (countInt == null) ? 0 : countInt;
if (count >= aveBlockOwnCount) {
lsBlocksToRedistribute.add(new Block(blockReal));
} else {
addressBlocks.put(blockReal.getOwner(), ++count);
}
}
Collection<Address> allAddress = addressBlocks.keySet();
lsBlocksToMigrate.clear();
for (Address address : allAddress) {
Integer countInt = addressBlocks.get(address);
int count = (countInt == null) ? 0 : countInt;
while (count < aveBlockOwnCount && lsBlocksToRedistribute.size() > 0) {
Block blockToMigrate = lsBlocksToRedistribute.remove(0);
if (!blockToMigrate.getOwner().equals(address)) {
blockToMigrate.setMigrationAddress(address);
lsBlocksToMigrate.add(blockToMigrate);
}
count++;
}
}
Collections.shuffle(lsBlocksToMigrate);
}
} | #vulnerable code
void migrateBlock(final Block blockInfo) {
if (!concurrentMapManager.isBlockInfoValid(blockInfo)) {
return;
}
if (!thisAddress.equals(blockInfo.getOwner())) {
throw new RuntimeException();
}
if (!blockInfo.isMigrating()) {
throw new RuntimeException();
}
if (blockInfo.getOwner().equals(blockInfo.getMigrationAddress())) {
throw new RuntimeException();
}
Block blockReal = blocks[blockInfo.getBlockId()];
if (blockReal.isMigrating()) {
if (!blockInfo.getMigrationAddress().equals(blockReal.getMigrationAddress())) {
logger.log(Level.WARNING, blockReal + ". Already migrating blockInfo is migrating again to " + blockInfo);
} else {
logger.log(Level.WARNING, blockInfo + " migration unknown " + blockReal);
}
return;
}
blockReal.setOwner(blockInfo.getOwner());
blockReal.setMigrationAddress(blockInfo.getMigrationAddress());
logger.log(Level.FINEST, "migrate blockInfo " + blockInfo);
if (!node.isActive() || node.factory.restarted) {
return;
}
if (concurrentMapManager.isSuperClient()) {
return;
}
List<Record> lsRecordsToMigrate = new ArrayList<Record>(1000);
Collection<CMap> cmaps = concurrentMapManager.maps.values();
for (final CMap cmap : cmaps) {
if (cmap.locallyOwnedMap != null) {
cmap.locallyOwnedMap.reset();
}
final Object[] records = cmap.ownedRecords.toArray();
for (Object recObj : records) {
final Record rec = (Record) recObj;
if (rec.isActive()) {
if (rec.getKey() == null || rec.getKey().size() == 0) {
throw new RuntimeException("Record.key is null or empty " + rec.getKey());
}
if (rec.getBlockId() == blockInfo.getBlockId()) {
lsRecordsToMigrate.add(rec);
cmap.markAsRemoved(rec);
}
}
}
}
final CountDownLatch latch = new CountDownLatch(lsRecordsToMigrate.size());
for (final Record rec : lsRecordsToMigrate) {
final CMap cmap = concurrentMapManager.getMap(rec.getName());
node.executorManager.executeMigrationTask(new FallThroughRunnable() {
public void doRun() {
try {
concurrentMapManager.migrateRecord(cmap, rec);
} finally {
latch.countDown();
}
}
});
}
node.executorManager.executeMigrationTask(new FallThroughRunnable() {
public void doRun() {
try {
logger.log(Level.FINEST, "migrate blockInfo " + blockInfo + " await ");
latch.await(10, TimeUnit.SECONDS);
concurrentMapManager.enqueueAndReturn(new Processable() {
public void process() {
Block blockReal = blocks[blockInfo.getBlockId()];
logger.log(Level.FINEST, "migrate completing [" + blockInfo + "] realBlock " + blockReal);
blockReal.setOwner(blockReal.getMigrationAddress());
blockReal.setMigrationAddress(null);
logger.log(Level.FINEST, "migrate complete [" + blockInfo.getMigrationAddress() + "] now realBlock " + blockReal);
for (MemberImpl member : concurrentMapManager.lsMembers) {
if (!member.localMember()) {
concurrentMapManager.sendBlockInfo(new Block(blockReal), member.getAddress());
}
}
}
});
} catch (InterruptedException ignored) {
}
}
});
}
#location 5
#vulnerability type NULL_DEREFERENCE |
Below is the vulnerable code, please generate the patch based on the following information. | #fixed code
public void readFrom(DataInputStream dis) throws IOException {
headerSize = dis.readInt();
keySize = dis.readInt();
valueSize = dis.readInt();
headerInBytes = new byte[headerSize];
dis.read(headerInBytes);
ByteArrayInputStream bis = new ByteArrayInputStream(headerInBytes);
DataInputStream dis2 = new DataInputStream(bis);
this.operation = ClusterOperation.create(dis2.readInt());
this.blockId = dis2.readInt();
this.threadId = dis2.readInt();
this.lockCount = dis2.readInt();
this.timeout = dis2.readLong();
this.txnId = dis2.readLong();
this.longValue = dis2.readLong();
this.recordId = dis2.readLong();
this.version = dis2.readLong();
this.callId = (int) dis2.readLong();
this.client = dis2.readByte()==1;
this.responseType = dis2.readByte();
int nameLength = dis2.readInt();
byte[] b = new byte[nameLength];
dis2.read(b);
this.name = new String(b);
this.lockAddressIsNull = dis2.readBoolean();
indexCount = dis2.readByte();
for (int i=0; i<indexCount ; i++) {
indexes[i] = dis2.readLong();
indexTypes[i] = dis2.readByte();
}
key = new byte[keySize];
dis.read(key);
value = new byte[valueSize];
dis.read(value);
} | #vulnerable code
public void readFrom(DataInputStream dis) throws IOException {
System.out.println("Available:" + dis.available());
headerSize = dis.readInt();
keySize = dis.readInt();
valueSize = dis.readInt();
headerInBytes = new byte[headerSize];
dis.read(headerInBytes);
ByteArrayInputStream bis = new ByteArrayInputStream(headerInBytes);
DataInputStream dis2 = new DataInputStream(bis);
this.operation = ClusterOperation.create(dis2.readInt());
this.blockId = dis2.readInt();
this.threadId = dis2.readInt();
this.lockCount = dis2.readInt();
this.timeout = dis2.readLong();
this.txnId = dis2.readLong();
this.longValue = dis2.readLong();
this.recordId = dis2.readLong();
this.version = dis2.readLong();
this.callId = (int) dis2.readLong();
this.client = dis2.readByte()==1;
this.responseType = dis2.readByte();
int nameLength = dis2.readInt();
byte[] b = new byte[nameLength];
dis2.read(b);
this.name = new String(b);
this.lockAddressIsNull = dis2.readBoolean();
key = new byte[keySize];
dis.read(key);
value = new byte[valueSize];
dis.read(value);
}
#location 28
#vulnerability type RESOURCE_LEAK |
Below is the vulnerable code, please generate the patch based on the following information. | #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;
}
} | #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 9
#vulnerability type THREAD_SAFETY_VIOLATION |
Below is the vulnerable code, please generate the patch based on the following information. | #fixed code
public SingleResult process(TextRankRequest request) {
TextRank textrank = new TextRank(getDatabase(), getNLPManager().getConfiguration());
if (request.getStopWords() != null
&& !request.getStopWords().isEmpty()) {
textrank.setStopwords(request.getStopWords());
}
textrank.removeStopWords(request.isDoStopwords());
textrank.respectDirections(request.isRespectDirections());
textrank.respectSentences(request.isRespectSentences());
textrank.useTfIdfWeights(request.isUseTfIdfWeights());
textrank.useDependencies(request.isUseDependencies());
textrank.setCooccurrenceWindow(request.getCooccurrenceWindow());
textrank.setMaxSingleKeywords(request.getMaxSingleKeywords());
textrank.setKeywordLabel(request.getKeywordLabel());
Map<Long, Map<Long, CoOccurrenceItem>> coOccurrence = textrank.createCooccurrences(request.getNode());
boolean res = textrank.evaluate(request.getNode(),
coOccurrence,
request.getIterations(),
request.getDamp(),
request.getThreshold());
if (!res) {
return SingleResult.fail();
}
LOG.info("AnnotatedText with ID " + request.getNode().getId() + " processed.");
return SingleResult.success();
} | #vulnerable code
public SingleResult process(TextRankRequest request) {
TextRank textrank = new TextRank(getDatabase(), getNLPManager().getConfiguration());
if (request.getStopWords() != null
&& !request.getStopWords().isEmpty()) {
textrank.setStopwords(request.getStopWords());
}
textrank.removeStopWords(request.isDoStopwords());
textrank.respectDirections(request.isRespectDirections());
textrank.respectSentences(request.isRespectSentences());
textrank.useTfIdfWeights(request.isUseTfIdfWeights());
textrank.useDependencies(request.isUseDependencies());
textrank.setCooccurrenceWindow(request.getCooccurrenceWindow());
Map<Long, Map<Long, CoOccurrenceItem>> coOccurrence = textrank.createCooccurrences(request.getNode());
boolean res = textrank.evaluate(request.getNode(),
coOccurrence,
request.getIterations(),
request.getDamp(),
request.getThreshold());
if (!res) {
return SingleResult.fail();
}
LOG.info("AnnotatedText with ID " + request.getNode().getId() + " processed.");
return SingleResult.success();
}
#location 16
#vulnerability type NULL_DEREFERENCE |
Below is the vulnerable code, please generate the patch based on the following information. | #fixed code
public Map<Long, Map<Long, CoOccurrenceItem>> createCooccurrences(Node annotatedText) {
Map<String, Object> params = new HashMap<>();
params.put("id", annotatedText.getId());
String query;
if (respectSentences) {
query = COOCCURRENCE_QUERY_BY_SENTENCE;
} else {
query = COOCCURRENCE_QUERY;
}
Result res = null;
try (Transaction tx = database.beginTx();) {
res = database.execute(query, params);
tx.success();
} catch (Exception e) {
LOG.error("Error while creating co-occurrences: ", e);
}
List<CoOccurrenceItem> prelim = new ArrayList<>();
while (res != null && res.hasNext()) {
Map<String, Object> next = res.next();
Long tag1 = toLong(next.get("tag1"));
Long tag2 = toLong(next.get("tag2"));
String tagVal1 = (String) next.get("tag1_val");
String tagVal2 = (String) next.get("tag2_val");
int tag1Start = (toLong(next.get("sourceStartPosition"))).intValue();
int tag2Start = (toLong(next.get("destinationStartPosition"))).intValue();
List<String> pos1 = next.get("pos1") != null ? Arrays.asList((String[]) next.get("pos1")) : new ArrayList<>();
List<String> pos2 = next.get("pos2") != null ? Arrays.asList((String[]) next.get("pos2")) : new ArrayList<>();
// check whether POS of both tags are admitted
boolean bPOS1 = pos1.stream().filter(pos -> admittedPOSs.contains(pos)).count() != 0 || pos1.size() == 0;
boolean bPOS2 = pos2.stream().filter(pos -> admittedPOSs.contains(pos)).count() != 0 || pos2.size() == 0;
// fill tag co-occurrences (adjacency matrix)
if (bPOS1 && bPOS2) {
prelim.add(new CoOccurrenceItem(tag1, tag1Start, tag2, tag2Start));
}
// for logging purposses and for `expandNamedEntities()`
idToValue.put(tag1, tagVal1);
idToValue.put(tag2, tagVal2);
}
Map<Long, List<Pair<Long, Long>>> neExp;
if (expandNEs) {
// process named entities: split them into individual tokens by calling ga.nlp.annotate(), assign them IDs and create co-occurrences
neExp = expandNamedEntities();
neExpanded = neExp.entrySet().stream()
.collect(Collectors.toMap( Map.Entry::getKey, e -> e.getValue().stream().map(p -> p.second()).collect(Collectors.toList()) ));
} else
neExp = new HashMap<>();
Map<Long, Map<Long, CoOccurrenceItem>> results = new HashMap<>();
long neVisited = 0L;
for (CoOccurrenceItem it: prelim) {
Long tag1 = it.getSource();
Long tag2 = it.getDestination();
int tag1Start = it.getSourceStartingPositions().get(0).first().intValue();
int tag2Start = it.getSourceStartingPositions().get(0).second().intValue();
if (expandNEs) {
if (neExp.containsKey(tag1)) {
if (neVisited == 0L || neVisited != tag1.longValue()) {
connectTagsInNE(results, neExp.get(tag1), tag1Start);
neVisited = 0L;
}
tag1Start += neExp.get(tag1).get( neExp.get(tag1).size() - 1 ).first().intValue();
tag1 = neExp.get(tag1).get( neExp.get(tag1).size() - 1 ).second();
}
if (neExp.containsKey(tag2)) {
connectTagsInNE(results, neExp.get(tag2), tag2Start);
neVisited = tag2;
tag2 = neExp.get(tag2).get(0).second();
} else
neVisited = 0L;
}
addTagToCoOccurrence(results, tag1, tag1Start, tag2, tag2Start);
if (!directionsMatter) { // when direction of co-occurrence relationships is not important
addTagToCoOccurrence(results, tag2, tag2Start, tag1, tag1Start);
}
}
return results;
} | #vulnerable code
public Map<Long, Map<Long, CoOccurrenceItem>> createCooccurrences(Node annotatedText) {
Map<String, Object> params = new HashMap<>();
params.put("id", annotatedText.getId());
String query;
if (respectSentences) {
query = COOCCURRENCE_QUERY_BY_SENTENCE;
} else {
query = COOCCURRENCE_QUERY;
}
Result res = null;
try (Transaction tx = database.beginTx();) {
res = database.execute(query, params);
tx.success();
} catch (Exception e) {
LOG.error("Error while creating co-occurrences: ", e);
}
List<CoOccurrenceItem> prelim = new ArrayList<>();
while (res != null && res.hasNext()) {
Map<String, Object> next = res.next();
Long tag1 = toLong(next.get("tag1"));
Long tag2 = toLong(next.get("tag2"));
String tagVal1 = (String) next.get("tag1_val");
String tagVal2 = (String) next.get("tag2_val");
int tag1Start = (toLong(next.get("sourceStartPosition"))).intValue();
int tag2Start = (toLong(next.get("destinationStartPosition"))).intValue();
List<String> pos1 = Arrays.asList((String[]) next.get("pos1"));
List<String> pos2 = Arrays.asList((String[]) next.get("pos2"));
// check whether POS of both tags are admitted
boolean bPOS1 = pos1.stream().filter(pos -> admittedPOSs.contains(pos)).count() != 0 || pos1.size() == 0;
boolean bPOS2 = pos2.stream().filter(pos -> admittedPOSs.contains(pos)).count() != 0 || pos2.size() == 0;
// fill tag co-occurrences (adjacency matrix)
if (bPOS1 && bPOS2) {
prelim.add(new CoOccurrenceItem(tag1, tag1Start, tag2, tag2Start));
}
// for logging purposses and for `handleNamedEntities()`
idToValue.put(tag1, tagVal1);
idToValue.put(tag2, tagVal2);
}
Map<Long, List<Pair<Long, Long>>> neExp = expandNamedEntities();
neExpanded = neExp.entrySet().stream()
.collect(Collectors.toMap( Map.Entry::getKey, e -> e.getValue().stream().map(p -> p.second()).collect(Collectors.toList()) ));
Map<Long, Map<Long, CoOccurrenceItem>> results = new HashMap<>();
long neVisited = 0L;
for (CoOccurrenceItem it: prelim) {
Long tag1 = it.getSource();
Long tag2 = it.getDestination();
int tag1Start = it.getSourceStartingPositions().get(0).first().intValue();
int tag2Start = it.getSourceStartingPositions().get(0).second().intValue();
if (neExp.containsKey(tag1)) {
if (neVisited == 0L || neVisited != tag1.longValue()) {
connectTagsInNE(results, neExp.get(tag1), tag1Start);
neVisited = 0L;
}
tag1Start += neExp.get(tag1).get( neExp.get(tag1).size() - 1 ).first().intValue();
tag1 = neExp.get(tag1).get( neExp.get(tag1).size() - 1 ).second();
}
if (neExp.containsKey(tag2)) {
connectTagsInNE(results, neExp.get(tag2), tag2Start);
neVisited = tag2;
tag2 = neExp.get(tag2).get(0).second();
} else
neVisited = 0L;
addTagToCoOccurrence(results, tag1, tag1Start, tag2, tag2Start);
if (!directionsMatter) { // when direction of co-occurrence relationships is not important
addTagToCoOccurrence(results, tag2, tag2Start, tag1, tag1Start);
}
}
return results;
}
#location 62
#vulnerability type NULL_DEREFERENCE |
Below is the vulnerable code, please generate the patch based on the following information. | #fixed code
private Map<Long, Float> createFeatureMapWithCN5New(long firstNode) throws QueryExecutionException {
Map<String, Object> params = new HashMap<>();
params.put("id", firstNode);
Result res = database.execute(DEFAULT_VECTOR_QUERY_WITH_CONCEPT, params);
Map<Long, Float> result = new HashMap<>();
Map<Long, Float> result_idf = new HashMap<>();
while (res != null && res.hasNext()) {
Map<String, Object> next = res.next();
long id = (long) next.get("tagId");
int nTerms = (int) next.get("nTerms");
//float tf = getFloatValue(next.get("tf"));
float tf = getFloatValue(next.get("tf")) / nTerms;
float idf = Double.valueOf(Math.log10(Float.valueOf(getFloatValue(next.get("idf"))).doubleValue())).floatValue();
// ConceptNet5 Level_1 tags
//long cn5_tag = Long.valueOf((String) next.get("cn5_l1_tag"));
long cn5_tag = (long) next.get("cn5_l1_tag");
float cn5_tag_w = getFloatValue(next.get("cn5_l1_tag_w"));
if (cn5_tag > -1) {
if (!result.containsKey(cn5_tag)) {
result.put(cn5_tag, tf);
result_idf.put(cn5_tag, idf);
} else {
result.put(cn5_tag, result.get(cn5_tag) + tf);
if (result_idf.get(cn5_tag) < idf) // use the highest idf
{
result_idf.put(cn5_tag, idf);
}
}
} else {
result.put(id, tf);
result_idf.put(id, idf);
}
}
result.keySet().forEach((key) -> {
result.put(key, result.get(key) * result_idf.get(key));
});
return result;
} | #vulnerable code
private Map<Long, Float> createFeatureMapWithCN5New(long firstNode) throws QueryExecutionException {
Map<String, Object> params = new HashMap<>();
params.put("id", firstNode);
Result res = database.execute("MATCH (doc:AnnotatedText)\n"
+ "WITH count(doc) as documentsCount\n"
+ "MATCH (document:AnnotatedText)-[:CONTAINS_SENTENCE]->(s:Sentence)-[ht:HAS_TAG]->(tag:Tag)\n"
+ "WHERE id(document) = {id} and not any (p in tag.pos where p in [\"CC\", \"CD\", \"DT\", \"IN\", \"MD\", \"PRP\", \"PRP$\", \"UH\", \"WDT\", \"WP\", \"WRB\", \"TO\", \"PDT\", \"RP\", \"WP$\"])\n" // JJR, JJS ?
+ "WITH tag, sum(ht.tf) as tf, documentsCount, document.numTerms as nTerms\n"
+ "OPTIONAL MATCH (tag)-[rt:IS_RELATED_TO]->(t2_l1:Tag)\n"
+ "WHERE id(t2_l1) = tag.idMaxConcept and exists(t2_l1.word2vec) and com.graphaware.nlp.ml.similarity.cosine(tag.word2vec, t2_l1.word2vec)>0.2\n"
+ "WITH tag, tf, nTerms, id(t2_l1) as cn5_l1_tag, rt.weight as cn5_l1_tag_w, documentsCount\n"
+ "MATCH (a:AnnotatedText)-[:CONTAINS_SENTENCE]->(s:Sentence)-[ht:HAS_TAG]->(tag)\n"
+ "RETURN id(tag) as tagId, tf, (1.0f*documentsCount)/count(distinct a) as idf, nTerms, (case cn5_l1_tag when null then -1 else cn5_l1_tag end) as cn5_l1_tag, cn5_l1_tag_w\n"
+ "ORDER BY tagId, cn5_l1_tag", params);
Map<Long, Float> result = new HashMap<>();
Map<Long, Float> result_idf = new HashMap<>();
while (res != null && res.hasNext()) {
Map<String, Object> next = res.next();
long id = (long) next.get("tagId");
int nTerms = (int) next.get("nTerms");
//float tf = getFloatValue(next.get("tf"));
float tf = getFloatValue(next.get("tf")) / nTerms;
float idf = Double.valueOf(Math.log10(Float.valueOf(getFloatValue(next.get("idf"))).doubleValue())).floatValue();
// ConceptNet5 Level_1 tags
//long cn5_tag = Long.valueOf((String) next.get("cn5_l1_tag"));
long cn5_tag = (long) next.get("cn5_l1_tag");
float cn5_tag_w = getFloatValue(next.get("cn5_l1_tag_w"));
if (cn5_tag>-1) {
if (!result.containsKey(cn5_tag)) {
result.put(cn5_tag, tf);
result_idf.put(cn5_tag, idf);
} else {
result.put(cn5_tag, result.get(cn5_tag) + tf);
if (result_idf.get(cn5_tag) < idf) // use the highest idf
result_idf.put(cn5_tag, idf);
}
} else {
result.put(id, tf);
result_idf.put(id, idf);
}
}
for (Long key: result.keySet()) {
result.put(key, result.get(key) * result_idf.get(key));
}
return result;
}
#location 46
#vulnerability type NULL_DEREFERENCE |
Below is the vulnerable code, please generate the patch based on the following information. | #fixed code
public boolean evaluate(Node annotatedText, int iter, double damp, double threshold) {
Map<Long, Map<Long, CoOccurrenceItem>> coOccurrence = createCooccurrences(annotatedText);
PageRank pageRank = new PageRank(database);
if (useTfIdfWeights) {
pageRank.setNodeWeights(initializeNodeWeights_TfIdf(annotatedText, coOccurrence));
}
Map<Long, Double> pageRanks = pageRank.run(coOccurrence, iter, damp, threshold);
int n_oneThird = (int) (pageRanks.size() * phrasesTopxWords);
List<Long> topThird = getTopX(pageRanks, n_oneThird);
LOG.info("Top " + n_oneThird + " tags: " + topThird.stream().map(id -> idToValue.get(id)).collect(Collectors.joining(", ")));
Map<String, Object> params = new HashMap<>();
params.put("id", annotatedText.getId());
//params.put("nodeList", topThird); // new (also changed the GET_TAG_QUERY)
params.put("posList", admittedPOSs);
List<KeywordExtractedItem> keywordsOccurrences = new ArrayList<>();
Map<Long, KeywordExtractedItem> keywordMap = new HashMap<>();
try (Transaction tx = database.beginTx()) {
Result res = database.execute(GET_TAG_QUERY, params);
while (res != null && res.hasNext()) {
Map<String, Object> next = res.next();
long tagId = (long) next.get("tagId");
KeywordExtractedItem item = new KeywordExtractedItem(tagId);
item.setStartPosition(((Number) next.get("sP")).intValue());
item.setValue(((String) next.get("tag")));
item.setEndPosition(((Number) next.get("eP")).intValue());
item.setRelatedTags(iterableToList((Iterable<String>) next.get("rel_tags")));
item.setRelTagStartingPoints(iterableToList((Iterable<Number>) next.get("rel_tos")));
item.setRelTagEndingPoints(iterableToList((Iterable<Number>) next.get("rel_toe")));
item.setRelevance(pageRanks.containsKey(tagId) ? pageRanks.get(tagId) : 0);
keywordsOccurrences.add(item);
if (!keywordMap.containsKey(tagId)) {
keywordMap.put(tagId, item);
}
}
if (res != null) {
res.close();
}
tx.success();
} catch (Exception e) {
LOG.error("Error while running TextRank evaluation: ", e);
return false;
}
Map<String, Long> valToId = idToValue.entrySet().stream().collect(Collectors.toMap(Map.Entry::getValue, Map.Entry::getKey));
Map<String, Keyword> results = new HashMap<>();
while (!keywordsOccurrences.isEmpty()) {
final AtomicReference<KeywordExtractedItem> keywordOccurrence
= new AtomicReference<>(keywordsOccurrences.remove(0));
final AtomicReference<String> currValue = new AtomicReference<>(keywordOccurrence.get().getValue());
final AtomicReference<Double> currRelevance = new AtomicReference<>(keywordOccurrence.get().getRelevance());
List<Long> relTagIDs = keywordOccurrence.get().getRelatedTags().stream().map(el -> valToId.get(el)).collect(Collectors.toList()); // new
relTagIDs.retainAll(topThird); // new
if (!topThird.contains(keywordOccurrence.get().getTagId()) && relTagIDs.size()==0) // new
continue;
//System.out.println("\n> " + currValue.get() + " - " + keywordOccurrence.get().getStartPosition());
Map<String, Keyword> localResults;
do {
long tagId = keywordOccurrence.get().getTagId();
//System.out.println(" cur: " + currValue.get() + ". Examining next level");
localResults = checkNextKeyword(tagId, keywordOccurrence.get(), coOccurrence, keywordMap);
if (localResults.size() > 0) {
//System.out.println(" related tags: " + localResults.entrySet().stream().map(en -> en.getKey()).collect(Collectors.joining(", ")));
localResults.entrySet().stream().forEach((item) -> {
KeywordExtractedItem nextKeyword = keywordsOccurrences.get(0);
if (nextKeyword != null && nextKeyword.value.equalsIgnoreCase(item.getKey())) {
String newCurrValue = currValue.get().split("_")[0] + " " + item.getKey();
//System.out.println(">> " + newCurrValue);
double newCurrRelevance = currRelevance.get() + item.getValue().getRelevance();
currValue.set(newCurrValue);
currRelevance.set(newCurrRelevance);
keywordOccurrence.set(nextKeyword);
keywordsOccurrences.remove(0);
} else {
LOG.warn("Next keyword not found!");
keywordOccurrence.set(null);
}
});
}
} while (!localResults.isEmpty() && keywordOccurrence.get() != null);
addToResults(currValue.get(), currRelevance.get(), results, 1);
//System.out.println("< " + currValue.get());
}
// add named entities that contain at least some of the top 1/3 of words
for (Long key: neExpanded.keySet()) {
if (neExpanded.get(key).stream().filter(v -> topThird.contains(v)).count() == 0)
continue;
String keystr = idToValue.get(key) + "_en"; // + lang;
addToResults(keystr, pageRanks.containsKey(key) ? pageRanks.get(key) : 0, results, 1);
}
computeTotalOccurrence(results);
if (cleanSingleWordKeyword) {
results = cleanSingleWordKeyword(results);
}
peristKeyword(results, annotatedText);
return true;
} | #vulnerable code
public boolean evaluate(Node annotatedText, int iter, double damp, double threshold) {
Map<Long, Map<Long, CoOccurrenceItem>> coOccurrence = createCooccurrences(annotatedText);
PageRank pageRank = new PageRank(database);
if (useTfIdfWeights) {
pageRank.setNodeWeights(initializeNodeWeights_TfIdf(annotatedText, coOccurrence));
}
Map<Long, Double> pageRanks = pageRank.run(coOccurrence, iter, damp, threshold);
int n_oneThird = (int) (pageRanks.size() * phrasesTopxWords);
List<Long> topThird = getTopX(pageRanks, n_oneThird);
LOG.info("Top " + n_oneThird + " tags: " + topThird.stream().map(id -> idToValue.get(id)).collect(Collectors.joining(", ")));
Map<String, Object> params = new HashMap<>();
params.put("id", annotatedText.getId());
params.put("nodeList", topThird);
params.put("posList", admittedPOSs);
List<KeywordExtractedItem> keywordsOccurrences = new ArrayList<>();
Map<Long, KeywordExtractedItem> keywordMap = new HashMap<>();
try (Transaction tx = database.beginTx()) {
Result res = database.execute(GET_TAG_QUERY, params);
while (res != null && res.hasNext()) {
Map<String, Object> next = res.next();
long tagId = (long) next.get("tagId");
KeywordExtractedItem item = new KeywordExtractedItem(tagId);
item.setStartPosition(((Number) next.get("sP")).intValue());
item.setValue(((String) next.get("tag")));
item.setEndPosition(((Number) next.get("eP")).intValue());
item.setRelatedTags(iterableToList((Iterable<String>) next.get("rel_tags")));
item.setRelTagStartingPoints(iterableToList((Iterable<Number>) next.get("rel_tos")));
item.setRelTagEndingPoints(iterableToList((Iterable<Number>) next.get("rel_toe")));
item.setRelevance(pageRanks.get(tagId));
keywordsOccurrences.add(item);
if (!keywordMap.containsKey(tagId)) {
keywordMap.put(tagId, item);
}
}
if (res != null) {
res.close();
}
tx.success();
} catch (Exception e) {
LOG.error("Error while running TextRank evaluation: ", e);
return false;
}
Map<String, Keyword> results = new HashMap<>();
while (!keywordsOccurrences.isEmpty()) {
final AtomicReference<KeywordExtractedItem> keywordOccurrence
= new AtomicReference<>(keywordsOccurrences.remove(0));
final AtomicReference<String> currValue = new AtomicReference<>(keywordOccurrence.get().getValue());
final AtomicReference<Double> currRelevance = new AtomicReference<>(keywordOccurrence.get().getRelevance());
//System.out.println("> " + currValue.get() + " - " + keywordOccurrence.get().getStartPosition());
Map<String, Keyword> localResults;
do {
long tagId = keywordOccurrence.get().getTagId();
//System.out.println("cur: " + currValue.get() + " examinating next level");
localResults = checkNextKeyword(tagId, keywordOccurrence.get(), coOccurrence, keywordMap);
if (localResults.size() > 0) {
localResults.entrySet().stream().forEach((item) -> {
KeywordExtractedItem nextKeyword = keywordsOccurrences.get(0);
if (nextKeyword != null && nextKeyword.value.equalsIgnoreCase(item.getKey())) {
String newCurrValue = currValue.get().split("_")[0] + " " + item.getKey();
//System.out.println(">> " + newCurrValue);
double newCurrRelevance = currRelevance.get() + item.getValue().getRelevance();
currValue.set(newCurrValue);
currRelevance.set(newCurrRelevance);
keywordOccurrence.set(nextKeyword);
keywordsOccurrences.remove(0);
} else {
LOG.warn("Next keyword not found!");
keywordOccurrence.set(null);
}
});
}
} while (!localResults.isEmpty() && keywordOccurrence.get() != null);
addToResults(currValue.get(), currRelevance.get(), results, 1);
//System.out.println("< " + currValue.get());
}
// add named entities that contain at least some of the top 1/3 of words
/*neExpanded.entrySet().stream()
.filter(en -> {
long n = en.getValue().stream().filter(v -> topThird.contains(v)).count();
return n > 0;
//return n >= en.getValue().size() / 3.0f || (n > 0 && en.getValue().size() == 2);
})
.forEach(en -> {
final String key = idToValue.get(en.getKey()) + "_en"; // + lang;
results.put(key, new Keyword(key)); // TO DO: handle counters exactMatch and total
});*/
for (Long key: neExpanded.keySet()) {
if (neExpanded.get(key).stream().filter(v -> topThird.contains(v)).count() == 0)
continue;
String keystr = idToValue.get(key) + "_en"; // + lang;
results.put(keystr, new Keyword(keystr)); // TO DO: handle counters exactMatch and total
}
computeTotalOccurrence(results);
if (cleanSingleWordKeyword) {
results = cleanSingleWordKeyword(results);
}
peristKeyword(results, annotatedText);
return true;
}
#location 93
#vulnerability type NULL_DEREFERENCE |
Below is the vulnerable code, please generate the patch based on the following information. | #fixed code
public String getDefaultModelWorkdir() {
Object p = configuration.getSettingValueFor(SettingsConstants.DEFAULT_MODEL_WORKDIR);
if (p == null) {
return getRawConfig().get(IMPORT_DIR_CONF_KEY);
}
return p.toString();
} | #vulnerable code
public String getDefaultModelWorkdir() {
String p = configuration.getSettingValueFor(SettingsConstants.DEFAULT_MODEL_WORKDIR).toString();
if (p == null) {
throw new RuntimeException("No default model wordking directory set in configuration");
}
return p;
}
#location 2
#vulnerability type NULL_DEREFERENCE |
Below is the vulnerable code, please generate the patch based on the following information. | #fixed code
public static void main(String[] args) {
log.info("Starting DragonProxy...");
// Check the java version
if (Float.parseFloat(System.getProperty("java.class.version")) < 52.0) {
log.error("DragonProxy requires Java 8! Current version: " + System.getProperty("java.version"));
return;
}
// Define command-line options
OptionParser optionParser = new OptionParser();
optionParser.accepts("version", "Displays the proxy version");
OptionSpec<String> bedrockPortOption = optionParser.accepts("bedrockPort", "Overrides the bedrock UDP bind port").withRequiredArg();
OptionSpec<String> javaPortOption = optionParser.accepts("javaPort", "Overrides the java TCP bind port").withRequiredArg();
optionParser.accepts("help", "Display help/usage information").forHelp();
// Handle command-line options
OptionSet options = optionParser.parse(args);
if (options.has("version")) {
log.info("Version: " + Bootstrap.class.getPackage().getImplementationVersion());
return;
}
int bedrockPort = options.has(bedrockPortOption) ? Integer.parseInt(options.valueOf(bedrockPortOption)) : -1;
int javaPort = options.has(javaPortOption) ? Integer.parseInt(options.valueOf(bedrockPortOption)) : -1;
DragonProxy proxy = new DragonProxy(bedrockPort, javaPort);
Runtime.getRuntime().addShutdownHook(new Thread(proxy::shutdown, "Shutdown thread"));
} | #vulnerable code
public static void main(String[] args) {
log.info("Starting DragonProxy...");
// Check the java version
if (Float.parseFloat(System.getProperty("java.class.version")) < 52.0) {
log.error("DragonProxy requires Java 8! Current version: " + System.getProperty("java.version"));
return;
}
// Define command-line options
OptionParser optionParser = new OptionParser();
optionParser.accepts("version", "Displays the proxy version");
OptionSpec<String> bedrockPortOption = optionParser.accepts("bedrockPort", "Overrides the bedrock UDP bind port").withRequiredArg();
OptionSpec<String> javaPortOption = optionParser.accepts("javaPort", "Overrides the java TCP bind port").withRequiredArg();
optionParser.accepts("help", "Display help/usage information").forHelp();
// Handle command-line options
OptionSet options = optionParser.parse(args);
if (options.has("version")) {
log.info("Version: " + Bootstrap.class.getPackage().getImplementationVersion());
return;
}
int bedrockPort = options.has(bedrockPortOption) ? Integer.parseInt(options.valueOf(bedrockPortOption)) : -1;
int javaPort = options.has(javaPortOption) ? Integer.parseInt(options.valueOf(bedrockPortOption)) : -1;
long startTime = System.currentTimeMillis();
DragonProxy proxy = new DragonProxy(bedrockPort, javaPort);
Runtime.getRuntime().addShutdownHook(new Thread(proxy::shutdown, "Shutdown thread"));
double bootTime = (System.currentTimeMillis() - startTime) / 1000d;
log.info("Done ({}s)!", new DecimalFormat("#.##").format(bootTime));
proxy.getConsole().start();
}
#location 35
#vulnerability type NULL_DEREFERENCE |
Below is the vulnerable code, please generate the patch based on the following information. | #fixed code
@Override
public Row<Measurement> next() {
if (!hasNext()) throw new NoSuchElementException();
Row<Measurement> output = new Row<>(m_timestamps.next(), m_resource);
while (m_current != null) {
accumulate(m_current, output.getTimestamp());
if (m_current.getTimestamp().gte(output.getTimestamp())) {
break;
}
if (m_input.hasNext()) {
m_current = m_input.next();
}
else m_current = null;
}
// Go time; We've accumulated enough to produce the output row
for (String name : m_metrics) {
Accumulation accumulation = m_accumulation.get(name);
// Add sample with accumulated value to output row
output.addElement(new Measurement(
output.getTimestamp(),
output.getResource(),
name,
accumulation.average()));
// If input is greater than row, accumulate remainder for next row
if (m_current != null) {
accumulation.reset();
Sample sample = m_current.getElement(name);
if (sample == null) {
continue;
}
if (m_current.getTimestamp().gt(output.getTimestamp())) {
Duration elapsed = m_current.getTimestamp().minus(output.getTimestamp());
if (elapsed.lt(getHeartbeat(name))) {
accumulation.known = elapsed.asMillis();
accumulation.value = sample.getValue().times(elapsed.asMillis());
}
else {
accumulation.unknown = elapsed.asMillis();
}
}
}
}
return output;
} | #vulnerable code
@Override
public Row<Measurement> next() {
if (!hasNext()) throw new NoSuchElementException();
Row<Measurement> output = new Row<>(m_timestamps.next(), m_resource);
while (m_current != null) {
accumulate(m_current, output.getTimestamp());
if (m_current.getTimestamp().gte(output.getTimestamp())) {
break;
}
if (m_input.hasNext()) {
m_current = m_input.next();
}
else m_current = null;
}
// Go time; We've accumulated enough to produce the output row
for (String name : m_metrics) {
Accumulation accumulation = m_accumulation.get(name);
// Add sample with accumulated value to output row
output.addElement(new Measurement(
output.getTimestamp(),
output.getResource(),
name,
accumulation.average().doubleValue()));
// If input is greater than row, accumulate remainder for next row
if (m_current != null) {
accumulation.reset();
Sample sample = m_current.getElement(name);
if (sample == null) {
continue;
}
if (m_current.getTimestamp().gt(output.getTimestamp())) {
Duration elapsed = m_current.getTimestamp().minus(output.getTimestamp());
if (elapsed.lt(getHeartbeat(name))) {
accumulation.known = elapsed.asMillis();
accumulation.value = sample.getValue().times(elapsed.asMillis());
}
else {
accumulation.unknown = elapsed.asMillis();
}
}
}
}
return output;
}
#location 32
#vulnerability type NULL_DEREFERENCE |
Below is the vulnerable code, please generate the patch based on the following information. | #fixed code
private int go(String[] args) {
m_parser.setUsageWidth(80);
try {
m_parser.parseArgument(args);
}
catch (CmdLineException e) {
System.err.println(e.getMessage());
printUsage(System.err);
return 1;
}
if (m_needsHelp) {
printUsage(System.out);
return 0;
}
if (m_resource == null || m_metric == null) {
System.err.println("Missing required argument(s)");
printUsage(System.err);
return 1;
}
System.out.printf("timestamp,%s%n", m_metric);
for (Results.Row<Sample> row : m_repository.select(m_resource, timestamp(m_start), timestamp(m_end))) {
System.out.printf("%s,%.2f%n", row.getTimestamp().asDate(), row.getElement(m_metric).getValue().doubleValue());
}
return 0;
} | #vulnerable code
private int go(String[] args) {
m_parser.setUsageWidth(80);
try {
m_parser.parseArgument(args);
}
catch (CmdLineException e) {
System.err.println(e.getMessage());
printUsage(System.err);
return 1;
}
if (m_needsHelp) {
printUsage(System.out);
return 0;
}
if (m_resource == null || m_metric == null) {
System.err.println("Missing required argument(s)");
printUsage(System.err);
return 1;
}
System.out.printf("timestamp,%s%n", m_metric);
for (Results.Row<Sample> row : m_repository.select(m_resource, timestamp(m_start), timestamp(m_end))) {
System.out.printf("%s,%.2f%n", row.getTimestamp().asDate(), row.getElement(m_metric).getValue());
}
return 0;
}
#location 28
#vulnerability type CHECKERS_PRINTF_ARGS |
Below is the vulnerable code, please generate the patch based on the following information. | #fixed code
@Test(expected = ReflectionException.class)
public void shouldFailGetter() {
PojoField pojoField = getPrivateStringField();
assert pojoField != null;
pojoField.invokeGetter(null);
} | #vulnerable code
@Test(expected = ReflectionException.class)
public void shouldFailGetter() {
PojoField pojoField = getPrivateStringField();
pojoField.invokeGetter(null);
}
#location 4
#vulnerability type NULL_DEREFERENCE |
Below is the vulnerable code, please generate the patch based on the following information. | #fixed code
public List<PojoPackage> getPojoSubPackages() {
List<PojoPackage> pojoPackageSubPackages = new LinkedList<PojoPackage>();
List<File> paths = PackageHelper.getPackageDirectories(packageName);
for (File path : paths) {
for (File entry : path.listFiles()) {
if (entry.isDirectory()) {
String subPackageName = packageName + PACKAGE_DELIMETER + entry.getName();
pojoPackageSubPackages.add(new PojoPackageImpl(subPackageName));
}
}
}
return pojoPackageSubPackages;
} | #vulnerable code
public List<PojoPackage> getPojoSubPackages() {
List<PojoPackage> pojoPackageSubPackages = new LinkedList<PojoPackage>();
File directory = PackageHelper.getPackageAsDirectory(packageName);
for (File entry : directory.listFiles()) {
if (entry.isDirectory()) {
String subPackageName = packageName + PACKAGE_DELIMETER + entry.getName();
pojoPackageSubPackages.add(new PojoPackageImpl(subPackageName));
}
}
return pojoPackageSubPackages;
}
#location 5
#vulnerability type NULL_DEREFERENCE |
Below is the vulnerable code, please generate the patch based on the following information. | #fixed code
@Test(expected = ReflectionException.class)
public void shouldFailSetter() {
PojoField pojoField = getPrivateStringField();
assert pojoField != null;
pojoField.invokeSetter(null, RandomFactory.getRandomValue(pojoField.getType()));
} | #vulnerable code
@Test(expected = ReflectionException.class)
public void shouldFailSetter() {
PojoField pojoField = getPrivateStringField();
pojoField.invokeSetter(null, RandomFactory.getRandomValue(pojoField.getType()));
}
#location 4
#vulnerability type NULL_DEREFERENCE |
Below is the vulnerable code, please generate the patch based on the following information. | #fixed code
@Test(expected = ReflectionException.class)
public void shouldFailGet() {
PojoField pojoField = getPrivateStringField();
assert pojoField != null;
pojoField.get(null);
} | #vulnerable code
@Test(expected = ReflectionException.class)
public void shouldFailGet() {
PojoField pojoField = getPrivateStringField();
pojoField.get(null);
}
#location 4
#vulnerability type NULL_DEREFERENCE |
Below is the vulnerable code, please generate the patch based on the following information. | #fixed code
@Test(expected = ReflectionException.class)
public void shouldFailSet() {
PojoField pojoField = getPrivateStringField();
assert pojoField != null;
pojoField.set(null, RandomFactory.getRandomValue(pojoField.getType()));
} | #vulnerable code
@Test(expected = ReflectionException.class)
public void shouldFailSet() {
PojoField pojoField = getPrivateStringField();
pojoField.set(null, RandomFactory.getRandomValue(pojoField.getType()));
}
#location 4
#vulnerability type NULL_DEREFERENCE |
Below is the vulnerable code, please generate the patch based on the following information. | #fixed code
public Object doGenerate(final Class<?> type) {
if (type == boolean.class || type == Boolean.class) {
return RANDOM.nextBoolean();
}
if (type == int.class || type == Integer.class) {
return RANDOM.nextInt();
}
if (type == BigInteger.class) {
return BigInteger.valueOf(RANDOM.nextLong());
}
if (type == float.class || type == Float.class) {
return RANDOM.nextFloat();
}
if (type == double.class || type == Double.class) {
return RANDOM.nextDouble();
}
if (type == BigDecimal.class) {
return BigDecimal.valueOf(RANDOM.nextDouble());
}
if (type == long.class || type == Long.class) {
return RANDOM.nextLong();
}
if (type == short.class || type == Short.class) {
return (short) (RANDOM.nextInt(Short.MAX_VALUE + 1) * (RANDOM.nextBoolean() ? 1 : -1));
}
if (type == byte.class || type == Byte.class) {
final byte[] randomByte = new byte[1];
RANDOM.nextBytes(randomByte);
return randomByte[0];
}
if (type == char.class || type == Character.class) {
return CHARACTERS[RANDOM.nextInt(CHARACTERS.length)];
}
if (type == String.class) {
String randomString = "";
/* prevent zero length string lengths */
for (int count = 0; count < RANDOM.nextInt(MAX_RANDOM_STRING_LENGTH + 1) + 1; count++) {
randomString += RandomFactory.getRandomValue(Character.class);
}
return randomString;
}
if (type == Date.class) {
return new Date(RANDOM.nextLong());
}
if (type == Calendar.class) {
final Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(RANDOM.nextLong());
return calendar;
}
return null;
} | #vulnerable code
public Object doGenerate(final Class<?> type) {
if (type == boolean.class || type == Boolean.class) {
return RANDOM.nextBoolean();
}
if (type == int.class || type == Integer.class) {
return RANDOM.nextInt();
}
if (type == BigInteger.class) {
return BigInteger.valueOf(RANDOM.nextLong());
}
if (type == float.class || type == Float.class) {
return RANDOM.nextFloat();
}
if (type == double.class || type == Double.class) {
return RANDOM.nextDouble();
}
if (type == BigDecimal.class) {
return BigDecimal.valueOf(RANDOM.nextDouble());
}
if (type == long.class || type == Long.class) {
return RANDOM.nextLong();
}
if (type == short.class || type == Short.class) {
return (short) (RANDOM.nextInt(Short.MAX_VALUE + 1) * (RANDOM.nextBoolean() ? 1 : -1));
}
if (type == byte.class || type == Byte.class) {
final byte[] randombyte = new byte[1];
RANDOM.nextBytes(randombyte);
return randombyte[0];
}
if (type == char.class || type == Character.class) {
return CHARACTERS[RANDOM.nextInt(CHARACTERS.length)];
}
if (type == String.class) {
String randomString = "";
/* prevent zero length string lengths */
for (int count = 0; count < RANDOM.nextInt(MAX_RANDOM_STRING_LENGTH + 1) + 1; count++) {
randomString += RandomFactory.getRandomValue(Character.class);
}
return randomString;
}
if (type == Date.class) {
return new Date(RandomFactory.getRandomValue(Long.class));
}
if (type == Calendar.class) {
final Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(RandomFactory.getRandomValue(Long.class));
return calendar;
}
return null;
}
#location 55
#vulnerability type NULL_DEREFERENCE |
Below is the vulnerable code, please generate the patch based on the following information. | #fixed code
@Test
public void defaultRandomGeneratorServicePrePopulated() {
reportDifferences();
Affirm.affirmEquals("Types added / removed?", expectedTypes, randomGeneratorService.getRegisteredTypes().size());
} | #vulnerable code
@Test
public void defaultRandomGeneratorServicePrePopulated() {
// JDK 5 only supports 42 of the 44 possible types. (java.util.ArrayDeque does not exist in JDK5).
String javaVersion = System.getProperty("java.version");
if (javaVersion.startsWith("1.6") || javaVersion.startsWith("1.7") || javaVersion.startsWith("1.8")) {
System.out.println("Found that many types: " + expectedDefaultTypes.size());
for (Class<?> expectedEntry : expectedDefaultTypes) {
boolean found = false;
for (Class<?> foundEntry : randomGeneratorService.getRegisteredTypes()) {
if (expectedEntry == foundEntry) found = true;
}
if (!found) System.out.println("\"" + expectedEntry.getName() + "\"");
}
System.out.println("Registered and not in the expected list!!");
for (Class<?> foundEntry : randomGeneratorService.getRegisteredTypes()) {
boolean found = false;
for (Class<?> expectedEntry : expectedDefaultTypes) {
if (expectedEntry == foundEntry) found = true;
}
if (!found) System.out.println("\"" + foundEntry.getName() + "\"");
}
Affirm.affirmEquals("Types added / removed?", expectedTypes, randomGeneratorService.getRegisteredTypes().size());
} else {
if (javaVersion.startsWith("1.5")) {
Affirm.affirmEquals("Types added / removed?", expectedTypes - 1, // (java.util.ArrayDeque does not exist
// in JDK5),
randomGeneratorService.getRegisteredTypes().size());
} else {
Affirm.fail("Unknown java version found " + System.getProperty("java.version") + " please check the " +
"correct number of expected registered classes and register type here - (found " + randomGeneratorService
.getRegisteredTypes().size() + ")");
}
}
}
#location 5
#vulnerability type NULL_DEREFERENCE |
Below is the vulnerable code, please generate the patch based on the following information. | #fixed code
public static List<Class<?>> getClasses(final String packageName) {
List<Class<?>> classes = new LinkedList<Class<?>>();
List<File> paths = getPackageDirectories(packageName);
for (File path : paths) {
for (File entry : path.listFiles()) {
if (isClass(entry.getName())) {
Class<?> clazz = getPathEntryAsClass(packageName, entry.getName());
classes.add(clazz);
}
}
}
return classes;
} | #vulnerable code
public static List<Class<?>> getClasses(final String packageName) {
List<Class<?>> classes = new LinkedList<Class<?>>();
File directory = getPackageAsDirectory(packageName);
for (File entry : directory.listFiles()) {
if (isClass(entry.getName())) {
Class<?> clazz = getPathEntryAsClass(packageName, entry.getName());
classes.add(clazz);
}
}
return classes;
}
#location 6
#vulnerability type NULL_DEREFERENCE |
Below is the vulnerable code, please generate the patch based on the following information. | #fixed code
private ElementSerializer startDoc(
XmlSerializer serializer, Object element, boolean errorOnUnknown, String extraNamespace)
throws IOException {
serializer.startDocument(null, null);
SortedSet<String> aliases = new TreeSet<String>();
computeAliases(element, aliases);
boolean foundExtra = extraNamespace == null;
for (String alias : aliases) {
String uri = getNamespaceUriForAliasHandlingUnknown(errorOnUnknown, alias);
serializer.setPrefix(alias, uri);
if (!foundExtra && uri.equals(extraNamespace)) {
foundExtra = true;
}
}
if (!foundExtra) {
for (Map.Entry<String, String> entry : getAliasToUriMap().entrySet()) {
if (extraNamespace.equals(entry.getValue())) {
serializer.setPrefix(entry.getKey(), extraNamespace);
break;
}
}
}
return new ElementSerializer(element, errorOnUnknown);
} | #vulnerable code
private ElementSerializer startDoc(
XmlSerializer serializer, Object element, boolean errorOnUnknown, String extraNamespace)
throws IOException {
serializer.startDocument(null, null);
SortedSet<String> aliases = new TreeSet<String>();
computeAliases(element, aliases);
boolean foundExtra = extraNamespace == null;
for (String alias : aliases) {
String uri = getUriForAlias(alias);
serializer.setPrefix(alias, uri);
if (!foundExtra && uri.equals(extraNamespace)) {
foundExtra = true;
}
}
if (!foundExtra) {
for (Map.Entry<String, String> entry : getAliasToUriMap().entrySet()) {
if (extraNamespace.equals(entry.getValue())) {
serializer.setPrefix(entry.getKey(), extraNamespace);
break;
}
}
}
return new ElementSerializer(element, errorOnUnknown);
}
#location 11
#vulnerability type NULL_DEREFERENCE |
Below is the vulnerable code, please generate the patch based on the following information. | #fixed code
@SuppressWarnings("unchecked")
public static void parse(String content, Object data) {
Class<?> clazz = data.getClass();
ClassInfo classInfo = ClassInfo.of(clazz);
GenericData genericData = GenericData.class.isAssignableFrom(clazz) ? (GenericData) data : null;
@SuppressWarnings("unchecked")
Map<Object, Object> map = Map.class.isAssignableFrom(clazz) ? (Map<Object, Object>) data : null;
int cur = 0;
int length = content.length();
int nextEquals = content.indexOf('=');
while (cur < length) {
int amp = content.indexOf('&', cur);
if (amp == -1) {
amp = length;
}
String name;
String stringValue;
if (nextEquals != -1 && nextEquals < amp) {
name = content.substring(cur, nextEquals);
stringValue = CharEscapers.decodeUri(content.substring(nextEquals + 1, amp));
nextEquals = content.indexOf('=', amp + 1);
} else {
name = content.substring(cur, amp);
stringValue = "";
}
name = CharEscapers.decodeUri(name);
// get the field from the type information
FieldInfo fieldInfo = classInfo.getFieldInfo(name);
if (fieldInfo != null) {
Class<?> type = fieldInfo.type;
if (Collection.class.isAssignableFrom(type)) {
Collection<Object> collection = (Collection<Object>) fieldInfo.getValue(data);
if (collection == null) {
collection = ClassInfo.newCollectionInstance(type);
fieldInfo.setValue(data, collection);
}
Class<?> subFieldClass = ClassInfo.getCollectionParameter(fieldInfo.field);
collection.add(FieldInfo.parsePrimitiveValue(subFieldClass, stringValue));
} else {
fieldInfo.setValue(data, FieldInfo.parsePrimitiveValue(type, stringValue));
}
} else if (map != null) {
ArrayList<String> listValue = (ArrayList<String>) map.get(name);
if (listValue == null) {
listValue = new ArrayList<String>();
if (genericData != null) {
genericData.set(name, listValue);
} else {
map.put(name, listValue);
}
}
listValue.add(stringValue);
}
cur = amp + 1;
}
} | #vulnerable code
@SuppressWarnings("unchecked")
public static void parse(String content, Object data) {
Class<?> clazz = data.getClass();
ClassInfo classInfo = ClassInfo.of(clazz);
GenericData genericData = GenericData.class.isAssignableFrom(clazz) ? (GenericData) data : null;
@SuppressWarnings("unchecked")
Map<Object, Object> map = Map.class.isAssignableFrom(clazz) ? (Map<Object, Object>) data : null;
int cur = 0;
int length = content.length();
int nextEquals = content.indexOf('=');
while (cur < length) {
int amp = content.indexOf('&', cur);
if (amp == -1) {
amp = length;
}
String name;
String stringValue;
if (nextEquals != -1 && nextEquals < amp) {
name = content.substring(cur, nextEquals);
stringValue = CharEscapers.decodeUri(content.substring(nextEquals + 1, amp));
nextEquals = content.indexOf('=', amp + 1);
} else {
name = content.substring(cur, amp);
stringValue = "";
}
name = CharEscapers.decodeUri(name);
// get the field from the type information
FieldInfo fieldInfo = classInfo.getFieldInfo(name);
if (fieldInfo != null) {
Class<?> type = fieldInfo.type;
if (Collection.class.isAssignableFrom(type)) {
Collection<Object> collection = (Collection<Object>) fieldInfo.getValue(data);
if (collection == null) {
collection = ClassInfo.newCollectionInstance(type);
fieldInfo.setValue(data, collection);
}
Class<?> subFieldClass = ClassInfo.getCollectionParameter(fieldInfo.field);
collection.add(FieldInfo.parsePrimitiveValue(subFieldClass, stringValue));
} else {
fieldInfo.setValue(data, FieldInfo.parsePrimitiveValue(type, stringValue));
}
} else {
ArrayList<String> listValue = (ArrayList<String>) map.get(name);
if (listValue == null) {
listValue = new ArrayList<String>();
if (genericData != null) {
genericData.set(name, listValue);
} else {
map.put(name, listValue);
}
}
listValue.add(stringValue);
}
cur = amp + 1;
}
}
#location 43
#vulnerability type NULL_DEREFERENCE |
Below is the vulnerable code, please generate the patch based on the following information. | #fixed code
public static void parse(String content, Object data) {
if (content == null) {
return;
}
Class<?> clazz = data.getClass();
ClassInfo classInfo = ClassInfo.of(clazz);
GenericData genericData = GenericData.class.isAssignableFrom(clazz) ? (GenericData) data : null;
@SuppressWarnings("unchecked")
Map<Object, Object> map = Map.class.isAssignableFrom(clazz) ? (Map<Object, Object>) data : null;
int cur = 0;
int length = content.length();
int nextEquals = content.indexOf('=');
while (cur < length) {
int amp = content.indexOf('&', cur);
if (amp == -1) {
amp = length;
}
String name;
String stringValue;
if (nextEquals != -1 && nextEquals < amp) {
name = content.substring(cur, nextEquals);
stringValue = CharEscapers.decodeUri(content.substring(nextEquals + 1, amp));
nextEquals = content.indexOf('=', amp + 1);
} else {
name = content.substring(cur, amp);
stringValue = "";
}
name = CharEscapers.decodeUri(name);
// get the field from the type information
FieldInfo fieldInfo = classInfo.getFieldInfo(name);
if (fieldInfo != null) {
Class<?> type = fieldInfo.type;
if (Collection.class.isAssignableFrom(type)) {
@SuppressWarnings("unchecked")
Collection<Object> collection = (Collection<Object>) fieldInfo.getValue(data);
if (collection == null) {
collection = ClassInfo.newCollectionInstance(type);
fieldInfo.setValue(data, collection);
}
Class<?> subFieldClass = ClassInfo.getCollectionParameter(fieldInfo.field);
collection.add(FieldInfo.parsePrimitiveValue(subFieldClass, stringValue));
} else {
fieldInfo.setValue(data, FieldInfo.parsePrimitiveValue(type, stringValue));
}
} else if (map != null) {
@SuppressWarnings("unchecked")
ArrayList<String> listValue = (ArrayList<String>) map.get(name);
if (listValue == null) {
listValue = new ArrayList<String>();
if (genericData != null) {
genericData.set(name, listValue);
} else {
map.put(name, listValue);
}
}
listValue.add(stringValue);
}
cur = amp + 1;
}
} | #vulnerable code
public static void parse(String content, Object data) {
if (content == null) {
return;
}
Class<?> clazz = data.getClass();
ClassInfo classInfo = ClassInfo.of(clazz);
GenericData genericData = GenericData.class.isAssignableFrom(clazz) ? (GenericData) data : null;
@SuppressWarnings("unchecked")
Map<Object, Object> map = Map.class.isAssignableFrom(clazz) ? (Map<Object, Object>) data : null;
int cur = 0;
int length = content.length();
int nextEquals = content.indexOf('=');
while (cur < length) {
int amp = content.indexOf('&', cur);
if (amp == -1) {
amp = length;
}
String name;
String stringValue;
if (nextEquals != -1 && nextEquals < amp) {
name = content.substring(cur, nextEquals);
stringValue = CharEscapers.decodeUri(content.substring(nextEquals + 1, amp));
nextEquals = content.indexOf('=', amp + 1);
} else {
name = content.substring(cur, amp);
stringValue = "";
}
name = CharEscapers.decodeUri(name);
// get the field from the type information
FieldInfo fieldInfo = classInfo.getFieldInfo(name);
if (fieldInfo != null) {
Class<?> type = fieldInfo.type;
if (Collection.class.isAssignableFrom(type)) {
@SuppressWarnings("unchecked")
Collection<Object> collection = (Collection<Object>) fieldInfo.getValue(data);
if (collection == null) {
collection = ClassInfo.newCollectionInstance(type);
fieldInfo.setValue(data, collection);
}
Class<?> subFieldClass = ClassInfo.getCollectionParameter(fieldInfo.field);
collection.add(FieldInfo.parsePrimitiveValue(subFieldClass, stringValue));
} else {
fieldInfo.setValue(data, FieldInfo.parsePrimitiveValue(type, stringValue));
}
} else {
@SuppressWarnings("unchecked")
ArrayList<String> listValue = (ArrayList<String>) map.get(name);
if (listValue == null) {
listValue = new ArrayList<String>();
if (genericData != null) {
genericData.set(name, listValue);
} else {
map.put(name, listValue);
}
}
listValue.add(stringValue);
}
cur = amp + 1;
}
}
#location 47
#vulnerability type NULL_DEREFERENCE |
Below is the vulnerable code, please generate the patch based on the following information. | #fixed code
@Test
public void should_run_post_build() {
ConfigSection afterRunSection = new AfterRunSection(configListOrSingleValue("spec integration1", "spec integration2"));
Combination combination = new Combination(ImmutableMap.of("script", "post_build"));
assertTrue(afterRunSection.toScript(combination).toShellScript().contains("spec integration1"));
} | #vulnerable code
@Test
public void should_run_post_build() {
ConfigSection afterRunSection = new AfterRunSection(configListOrSingleValue("spec integration1", "spec integration2"));
Combination combination = new Combination(ImmutableMap.of("script", "post_build"));
assertTrue(afterRunSection.toScript(combination, BuildType.BareMetal).toShellScript().contains("spec integration1"));
}
#location 6
#vulnerability type NULL_DEREFERENCE |
Below is the vulnerable code, please generate the patch based on the following information. | #fixed code
@Override
public Object handle(HttpExchange x) throws Exception {
String code = x.param("code");
String state = x.param("state");
U.debug("Received OAuth code", "code", code, "state", state);
if (code != null && state != null) {
U.must(stateCheck.isValidState(state, clientSecret, x.sessionId()), "Invalid OAuth state!");
String redirectUrl = oauthDomain != null ? oauthDomain + callbackPath : x.constructUrl(callbackPath);
TokenRequestBuilder reqBuilder = OAuthClientRequest.tokenLocation(provider.getTokenEndpoint())
.setGrantType(GrantType.AUTHORIZATION_CODE).setClientId(clientId).setClientSecret(clientSecret)
.setRedirectURI(redirectUrl).setCode(code);
OAuthClientRequest request = paramsInBody() ? reqBuilder.buildBodyMessage() : reqBuilder.buildBodyMessage();
OAuthClient oAuthClient = new OAuthClient(new URLConnectionClient());
String accessToken = token(request, oAuthClient);
String profileUrl = U.fillIn(provider.getProfileEndpoint(), "token", accessToken);
OAuthClientRequest bearerClientRequest = new OAuthBearerClientRequest(profileUrl).setAccessToken(
accessToken).buildQueryMessage();
OAuthResourceResponse res = oAuthClient.resource(bearerClientRequest,
org.apache.oltu.oauth2.common.OAuth.HttpMethod.GET, OAuthResourceResponse.class);
U.must(res.getResponseCode() == 200, "OAuth response error!");
Map<String, Object> auth = JSON.parseMap(res.getBody());
String firstName = (String) U.or(auth.get("firstName"),
U.or(auth.get("first_name"), auth.get("given_name")));
String lastName = (String) U.or(auth.get("lastName"), U.or(auth.get("last_name"), auth.get("family_name")));
UserInfo user = new UserInfo();
user.name = U.or((String) auth.get("name"), firstName + " " + lastName);
user.oauthProvider = provider.getName();
user.email = (String) U.or(auth.get("email"), auth.get("emailAddress"));
user.username = user.email;
user.oauthId = String.valueOf(auth.get("id"));
x.sessionSet("_user", user);
U.must(x.user() == user);
return x.redirect("/");
} else {
String error = x.param("error");
if (error != null) {
U.warn("OAuth error", "error", error);
throw U.rte("OAuth error!");
}
}
throw U.rte("OAuth error!");
} | #vulnerable code
@Override
public Object handle(HttpExchange x) throws Exception {
String code = x.param("code");
String state = x.param("state");
U.debug("Received OAuth code", "code", code, "state", state);
if (code != null && state != null) {
U.must(stateCheck.isValidState(state, clientSecret, x.sessionId()), "Invalid OAuth state!");
String redirectUrl = oauthDomain != null ? oauthDomain + callbackPath : x.constructUrl(callbackPath);
TokenRequestBuilder reqBuilder = OAuthClientRequest.tokenLocation(provider.getTokenEndpoint())
.setGrantType(GrantType.AUTHORIZATION_CODE).setClientId(clientId).setClientSecret(clientSecret)
.setRedirectURI(redirectUrl).setCode(code);
OAuthClientRequest request = paramsInBody() ? reqBuilder.buildBodyMessage() : reqBuilder.buildBodyMessage();
OAuthClient oAuthClient = new OAuthClient(new URLConnectionClient());
String accessToken = token(request, oAuthClient);
String profileUrl = U.fillIn(provider.getProfileEndpoint(), "token", accessToken);
OAuthClientRequest bearerClientRequest = new OAuthBearerClientRequest(profileUrl).setAccessToken(
accessToken).buildQueryMessage();
OAuthResourceResponse res = oAuthClient.resource(bearerClientRequest,
org.apache.oltu.oauth2.common.OAuth.HttpMethod.GET, OAuthResourceResponse.class);
U.must(res.getResponseCode() == 200, "OAuth response error!");
Map<String, Object> auth = JSON.parseMap(res.getBody());
String firstName = (String) U.or(auth.get("firstName"),
U.or(auth.get("first_name"), auth.get("given_name")));
String lastName = (String) U.or(auth.get("lastName"), U.or(auth.get("last_name"), auth.get("family_name")));
UserInfo user = new UserInfo();
user.name = U.or((String) auth.get("name"), firstName + " " + lastName);
user.oauthProvider = provider.getName();
user.email = (String) U.or(auth.get("email"), auth.get("emailAddress"));
user.username = user.email;
user.oauthId = String.valueOf(auth.get("id"));
user.display = user.email.substring(0, user.email.indexOf('@'));
x.sessionSet("_user", user);
U.must(x.user() == user);
return x.redirect("/");
} else {
String error = x.param("error");
if (error != null) {
U.warn("OAuth error", "error", error);
throw U.rte("OAuth error!");
}
}
throw U.rte("OAuth error!");
}
#location 46
#vulnerability type NULL_DEREFERENCE |
Below is the vulnerable code, please generate the patch based on the following information. | #fixed code
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
ScanParams that = (ScanParams) o;
if (!Arrays.equals(packages, that.packages)) return false;
if (matching != null ? !matching.equals(that.matching) : that.matching != null) return false;
if (!Arrays.equals(annotated, that.annotated)) return false;
if (classLoader != null ? !classLoader.equals(that.classLoader) : that.classLoader != null) return false;
if (!Arrays.equals(classpath, that.classpath)) return false;
return bytecodeFilter != null ? bytecodeFilter.equals(that.bytecodeFilter) : that.bytecodeFilter == null;
} | #vulnerable code
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
ScanParams that = (ScanParams) o;
if (!Arrays.equals(packages, that.packages)) return false;
if (matching != null ? !matching.equals(that.matching) : that.matching != null) return false;
if (!Arrays.equals(annotated, that.annotated)) return false;
return classLoader != null ? classLoader.equals(that.classLoader) : that.classLoader == null;
}
#location 8
#vulnerability type THREAD_SAFETY_VIOLATION |
Below is the vulnerable code, please generate the patch based on the following information. | #fixed code
@Override
public void reset() {
super.reset();
isGet.value = false;
isKeepAlive.value = false;
verb.reset();
uri.reset();
path.reset();
query.reset();
protocol.reset();
body.reset();
multipartBoundary.reset();
params.reset();
headersKV.reset();
headers.reset();
cookies.reset();
data.reset();
files.reset();
parsedParams = false;
parsedHeaders = false;
parsedBody = false;
resetResponse();
} | #vulnerable code
@Override
public void reset() {
super.reset();
isGet.value = false;
isKeepAlive.value = false;
verb.reset();
uri.reset();
path.reset();
query.reset();
protocol.reset();
body.reset();
multipartBoundary.reset();
params.reset();
headersKV.reset();
headers.reset();
cookies.reset();
data.reset();
files.reset();
parsedParams = false;
parsedHeaders = false;
parsedBody = false;
total = -1;
writesBody = false;
bodyPos = -1;
hasContentType = false;
responses = null;
responseCode = -1;
}
#location 28
#vulnerability type THREAD_SAFETY_VIOLATION |
Below is the vulnerable code, please generate the patch based on the following information. | #fixed code
@Override
public void reset() {
super.reset();
isGet.value = false;
isKeepAlive.value = false;
verb.reset();
uri.reset();
path.reset();
query.reset();
protocol.reset();
body.reset();
multipartBoundary.reset();
params.reset();
headersKV.reset();
headers.reset();
cookies.reset();
data.reset();
files.reset();
parsedParams = false;
parsedHeaders = false;
parsedBody = false;
total = -1;
writesBody = false;
bodyPos = -1;
hasContentType = false;
responses = null;
responseCode = -1;
} | #vulnerable code
@Override
public void reset() {
super.reset();
isGet.value = false;
isKeepAlive.value = false;
verb.reset();
uri.reset();
path.reset();
query.reset();
protocol.reset();
body.reset();
multipartBoundary.reset();
params.reset();
headersKV.reset();
headers.reset();
cookies.reset();
data.reset();
files.reset();
parsedParams = false;
parsedHeaders = false;
parsedBody = false;
total = -1;
writesBody = false;
bodyPos = -1;
hasContentType = false;
responses = null;
startedResponse = false;
responseCode = -1;
}
#location 32
#vulnerability type THREAD_SAFETY_VIOLATION |
Below is the vulnerable code, please generate the patch based on the following information. | #fixed code
public static Db db() {
assert U.must(db != null, "Database not initialized!");
return db;
} | #vulnerable code
public static Db db() {
assert U.must(defaultDb != null, "Database not initialized!");
return defaultDb;
}
#location 3
#vulnerability type THREAD_SAFETY_VIOLATION |
Below is the vulnerable code, please generate the patch based on the following information. | #fixed code
@Test(timeout = 30000)
public void testJDBCWithTextConfig() {
Conf.JDBC.set("driver", "org.h2.Driver");
Conf.JDBC.set("url", "jdbc:h2:mem:mydb");
Conf.JDBC.set("username", "sa");
Conf.C3P0.set("maxPoolSize", "123");
JdbcClient jdbc = JDBC.defaultApi();
eq(jdbc.driver(), "org.h2.Driver");
C3P0ConnectionPool pool = (C3P0ConnectionPool) JDBC.defaultApi().init().pool();
ComboPooledDataSource c3p0 = pool.pool();
eq(c3p0.getMinPoolSize(), 5);
eq(c3p0.getMaxPoolSize(), 123);
JDBC.execute("create table abc (id int, name varchar)");
JDBC.execute("insert into abc values (?, ?)", 123, "xyz");
final Map<String, ?> expected = U.map("id", 123, "name", "xyz");
Msc.benchmarkMT(100, "select", 100000, () -> {
Map<String, Object> record = U.single(JDBC.query("select id, name from abc"));
record = Msc.lowercase(record);
eq(record, expected);
});
} | #vulnerable code
@Test(timeout = 30000)
public void testJDBCWithTextConfig() {
Conf.JDBC.set("driver", "org.h2.Driver");
Conf.JDBC.set("url", "jdbc:h2:mem:mydb");
Conf.JDBC.set("username", "sa");
Conf.C3P0.set("maxPoolSize", "123");
JDBC.defaultApi().pooled();
JdbcClient jdbc = JDBC.defaultApi();
eq(jdbc.driver(), "org.h2.Driver");
C3P0ConnectionPool pool = (C3P0ConnectionPool) JDBC.defaultApi().pool();
ComboPooledDataSource c3p0 = pool.pool();
eq(c3p0.getMinPoolSize(), 5);
eq(c3p0.getMaxPoolSize(), 123);
JDBC.execute("create table abc (id int, name varchar)");
JDBC.execute("insert into abc values (?, ?)", 123, "xyz");
final Map<String, ?> expected = U.map("id", 123, "name", "xyz");
Msc.benchmarkMT(100, "select", 100000, () -> {
Map<String, Object> record = U.single(JDBC.query("select id, name from abc"));
record = Msc.lowercase(record);
eq(record, expected);
});
}
#location 15
#vulnerability type NULL_DEREFERENCE |
Below is the vulnerable code, please generate the patch based on the following information. | #fixed code
public void complete(Channel ctx, boolean isKeepAlive, Req req, Object result) {
if (result == null) {
http.notFound(ctx, isKeepAlive, this, req);
return; // not found
}
if (result instanceof HttpStatus) {
complete(ctx, isKeepAlive, req, U.rte("HttpStatus result is not supported!"));
return;
}
if (result instanceof Throwable) {
HttpIO.errorAndDone(req, (Throwable) result);
return;
} else {
HttpUtils.resultToResponse(req, result);
}
// the Req object will do the rendering
if (!req.isAsync()) {
req.done();
}
} | #vulnerable code
public void complete(Channel ctx, boolean isKeepAlive, Req req, Object result) {
if (result == null) {
http.notFound(ctx, isKeepAlive, this, req);
return; // not found
}
if (result instanceof HttpStatus) {
complete(ctx, isKeepAlive, req, U.rte("HttpStatus result is not supported!"));
return;
}
if (result instanceof Throwable) {
HttpIO.errorAndDone(req, (Throwable) result, Customization.of(req).errorHandler());
return;
} else {
HttpUtils.resultToResponse(req, result);
}
// the Req object will do the rendering
if (!req.isAsync()) {
req.done();
}
}
#location 14
#vulnerability type NULL_DEREFERENCE |
Below is the vulnerable code, please generate the patch based on the following information. | #fixed code
@Test(timeout = 30000)
public void testHikariPool() {
Conf.HIKARI.set("maximumPoolSize", 234);
JdbcClient jdbc = JDBC.api();
jdbc.h2("hikari-test");
jdbc.dataSource(HikariFactory.createDataSourceFor(jdbc));
jdbc.execute("create table abc (id int, name varchar)");
jdbc.execute("insert into abc values (?, ?)", 123, "xyz");
final Map<String, ?> expected = U.map("id", 123, "name", "xyz");
Msc.benchmarkMT(100, "select", 100000, () -> {
Map<String, Object> record = U.single(JDBC.query("select id, name from abc").all());
record = Msc.lowercase(record);
eq(record, expected);
});
HikariDataSource hikari = (HikariDataSource) jdbc.dataSource();
eq(hikari.getMaximumPoolSize(), 234);
} | #vulnerable code
@Test(timeout = 30000)
public void testHikariPool() {
JdbcClient jdbc = JDBC.api();
jdbc.h2("hikari-test");
jdbc.pool(new HikariConnectionPool(jdbc));
jdbc.execute("create table abc (id int, name varchar)");
jdbc.execute("insert into abc values (?, ?)", 123, "xyz");
final Map<String, ?> expected = U.map("id", 123, "name", "xyz");
Msc.benchmarkMT(100, "select", 100000, () -> {
Map<String, Object> record = U.single(JDBC.query("select id, name from abc").all());
record = Msc.lowercase(record);
eq(record, expected);
});
isTrue(jdbc.pool() instanceof HikariConnectionPool);
}
#location 6
#vulnerability type RESOURCE_LEAK |
Below is the vulnerable code, please generate the patch based on the following information. | #fixed code
@Override
public void reset() {
super.reset();
isGet.value = false;
isKeepAlive.value = false;
verb.reset();
uri.reset();
path.reset();
query.reset();
protocol.reset();
body.reset();
multipartBoundary.reset();
params.reset();
headersKV.reset();
headers.reset();
cookies.reset();
data.reset();
files.reset();
parsedParams = false;
parsedHeaders = false;
parsedBody = false;
resetResponse();
} | #vulnerable code
@Override
public void reset() {
super.reset();
isGet.value = false;
isKeepAlive.value = false;
verb.reset();
uri.reset();
path.reset();
query.reset();
protocol.reset();
body.reset();
multipartBoundary.reset();
params.reset();
headersKV.reset();
headers.reset();
cookies.reset();
data.reset();
files.reset();
parsedParams = false;
parsedHeaders = false;
parsedBody = false;
total = -1;
writesBody = false;
bodyPos = -1;
hasContentType = false;
responses = null;
responseCode = -1;
}
#location 29
#vulnerability type THREAD_SAFETY_VIOLATION |
Below is the vulnerable code, please generate the patch based on the following information. | #fixed code
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
ScanParams that = (ScanParams) o;
if (!Arrays.equals(packages, that.packages)) return false;
if (matching != null ? !matching.equals(that.matching) : that.matching != null) return false;
if (!Arrays.equals(annotated, that.annotated)) return false;
if (classLoader != null ? !classLoader.equals(that.classLoader) : that.classLoader != null) return false;
if (!Arrays.equals(classpath, that.classpath)) return false;
return bytecodeFilter != null ? bytecodeFilter.equals(that.bytecodeFilter) : that.bytecodeFilter == null;
} | #vulnerable code
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
ScanParams that = (ScanParams) o;
if (!Arrays.equals(packages, that.packages)) return false;
if (matching != null ? !matching.equals(that.matching) : that.matching != null) return false;
if (!Arrays.equals(annotated, that.annotated)) return false;
return classLoader != null ? classLoader.equals(that.classLoader) : that.classLoader == null;
}
#location 9
#vulnerability type THREAD_SAFETY_VIOLATION |
Below is the vulnerable code, please generate the patch based on the following information. | #fixed code
@Override
public String get() {
return count > 0 ? String.format("%s:[%s..%s..%s]#%s", sum, min, sum / count, max, count) : "" + ticks;
} | #vulnerable code
@Override
public String get() {
return count > 0 ? String.format("[%s..%s..%s]/%s", min, sum / count, max, count) : null;
}
#location 3
#vulnerability type THREAD_SAFETY_VIOLATION |
Below is the vulnerable code, please generate the patch based on the following information. | #fixed code
@Override
public HttpExchangeBody goBack(int steps) {
String dest = "/";
List<String> stack = session(SESSION_PAGE_STACK, null);
if (stack != null) {
if (!stack.isEmpty()) {
dest = stack.get(stack.size() - 1);
}
for (int i = 0; i < steps; i++) {
if (!stack.isEmpty()) {
stack.remove(stack.size() - 1);
if (!stack.isEmpty()) {
dest = stack.remove(stack.size() - 1);
}
}
}
}
return redirect(dest);
} | #vulnerable code
@Override
public HttpExchangeBody goBack(int steps) {
List<String> stack = session(SESSION_PAGE_STACK, null);
String dest = !stack.isEmpty() ? stack.get(stack.size() - 1) : "/";
for (int i = 0; i < steps; i++) {
if (stack != null && !stack.isEmpty()) {
stack.remove(stack.size() - 1);
if (!stack.isEmpty()) {
dest = stack.remove(stack.size() - 1);
}
}
}
return redirect(dest);
}
#location 5
#vulnerability type NULL_DEREFERENCE |
Below is the vulnerable code, please generate the patch based on the following information. | #fixed code
public void process(Channel ctx) {
if (ctx.isInitial()) {
return;
}
Buf buf = ctx.input();
RapidoidHelper helper = ctx.helper();
Range[] ranges = helper.ranges1.ranges;
Ranges hdrs = helper.ranges2;
BoolWrap isGet = helper.booleans[0];
BoolWrap isKeepAlive = helper.booleans[1];
Range verb = ranges[ranges.length - 1];
Range uri = ranges[ranges.length - 2];
Range path = ranges[ranges.length - 3];
Range query = ranges[ranges.length - 4];
Range protocol = ranges[ranges.length - 5];
Range body = ranges[ranges.length - 6];
HTTP_PARSER.parse(buf, isGet, isKeepAlive, body, verb, uri, path, query, protocol, hdrs, helper);
// the listener may override all the request dispatching and handler execution
if (!listener.request(this, ctx, isGet, isKeepAlive, body, verb, uri, path, query, protocol, hdrs)) {
return;
}
HttpStatus status = HttpStatus.NOT_FOUND;
FastHttpHandler handler = findFandler(ctx, buf, isGet, verb, path);
if (handler != null) {
Map<String, Object> params = null;
if (handler.needsParams()) {
params = U.map();
KeyValueRanges paramsKV = helper.pairs1.reset();
KeyValueRanges headersKV = helper.pairs2.reset();
HTTP_PARSER.parseParams(buf, paramsKV, query);
// parse URL parameters as data
Map<String, Object> data = U.cast(paramsKV.toMap(buf, true, true));
if (!isGet.value) {
KeyValueRanges postedKV = helper.pairs3.reset();
KeyValueRanges filesKV = helper.pairs4.reset();
// parse posted body as data
HTTP_PARSER.parsePosted(buf, headersKV, body, postedKV, filesKV, helper, data);
}
// filter special data values
Map<String, Object> special = findSpecialData(data);
if (special != null) {
data.keySet().removeAll(special.keySet());
} else {
special = U.cast(Collections.EMPTY_MAP);
}
// put all data directly as parameters
params.putAll(data);
params.put(DATA, data);
params.put(SPECIAL, special);
// finally, the HTTP info
params.put(VERB, verb.str(buf));
params.put(URI, uri.str(buf));
params.put(PATH, path.str(buf));
params.put(CLIENT_ADDRESS, ctx.address());
if (handler.needsHeadersAndCookies()) {
KeyValueRanges cookiesKV = helper.pairs5.reset();
HTTP_PARSER.parseHeadersIntoKV(buf, hdrs, headersKV, cookiesKV, helper);
Map<String, Object> headers = U.cast(headersKV.toMap(buf, true, true));
Map<String, Object> cookies = U.cast(cookiesKV.toMap(buf, true, true));
params.put(HEADERS, headers);
params.put(COOKIES, cookies);
params.put(HOST, U.get(headers, "Host", null));
params.put(FORWARDED_FOR, U.get(headers, "X-Forwarded-For", null));
}
}
status = handler.handle(ctx, isKeepAlive.value, params);
}
if (status == HttpStatus.NOT_FOUND) {
ctx.write(HTTP_404_NOT_FOUND);
listener.notFound(this, ctx, isGet, isKeepAlive, body, verb, uri, path, query, protocol, hdrs);
}
if (status != HttpStatus.ASYNC) {
ctx.closeIf(!isKeepAlive.value);
}
} | #vulnerable code
public void process(Channel ctx) {
if (ctx.isInitial()) {
return;
}
Buf buf = ctx.input();
RapidoidHelper helper = ctx.helper();
Range[] ranges = helper.ranges1.ranges;
Ranges hdrs = helper.ranges2;
BoolWrap isGet = helper.booleans[0];
BoolWrap isKeepAlive = helper.booleans[1];
Range verb = ranges[ranges.length - 1];
Range uri = ranges[ranges.length - 2];
Range path = ranges[ranges.length - 3];
Range query = ranges[ranges.length - 4];
Range protocol = ranges[ranges.length - 5];
Range body = ranges[ranges.length - 6];
HTTP_PARSER.parse(buf, isGet, isKeepAlive, body, verb, uri, path, query, protocol, hdrs, helper);
HttpStatus status = HttpStatus.NOT_FOUND;
FastHttpHandler handler = findFandler(ctx, buf, isGet, verb, path);
if (handler != null) {
Map<String, Object> params = null;
if (handler.needsParams()) {
params = U.map();
KeyValueRanges paramsKV = helper.pairs1.reset();
KeyValueRanges headersKV = helper.pairs2.reset();
HTTP_PARSER.parseParams(buf, paramsKV, query);
// parse URL parameters as data
Map<String, Object> data = U.cast(paramsKV.toMap(buf, true, true));
if (!isGet.value) {
KeyValueRanges postedKV = helper.pairs3.reset();
KeyValueRanges filesKV = helper.pairs4.reset();
// parse posted body as data
HTTP_PARSER.parsePosted(buf, headersKV, body, postedKV, filesKV, helper, data);
}
// filter special data values
Map<String, Object> special = findSpecialData(data);
if (special != null) {
data.keySet().removeAll(special.keySet());
} else {
special = U.cast(Collections.EMPTY_MAP);
}
// put all data directly as parameters
params.putAll(data);
params.put(DATA, data);
params.put(SPECIAL, special);
// finally, the HTTP info
params.put(VERB, verb.str(buf));
params.put(URI, uri.str(buf));
params.put(PATH, path.str(buf));
params.put(CLIENT_ADDRESS, ctx.address());
if (handler.needsHeadersAndCookies()) {
KeyValueRanges cookiesKV = helper.pairs5.reset();
HTTP_PARSER.parseHeadersIntoKV(buf, hdrs, headersKV, cookiesKV, helper);
Map<String, Object> headers = U.cast(headersKV.toMap(buf, true, true));
Map<String, Object> cookies = U.cast(cookiesKV.toMap(buf, true, true));
params.put(HEADERS, headers);
params.put(COOKIES, cookies);
params.put(HOST, U.get(headers, "Host", null));
params.put(FORWARDED_FOR, U.get(headers, "X-Forwarded-For", null));
}
}
status = handler.handle(ctx, isKeepAlive.value, params);
}
if (status == HttpStatus.NOT_FOUND) {
ctx.write(HTTP_404_NOT_FOUND);
}
if (status != HttpStatus.ASYNC) {
ctx.closeIf(!isKeepAlive.value);
}
}
#location 26
#vulnerability type THREAD_SAFETY_VIOLATION |
Below is the vulnerable code, please generate the patch based on the following information. | #fixed code
private void addInfo(List<Object> info, final GroupOf<?> group, List<? extends Manageable> items, List<String> columns) {
columns.add("(Actions)");
final String groupName = group.name();
final String kind = group.kind();
info.add(breadcrumb(kind, groupName));
Grid grid = grid(items)
.columns(columns)
.headers(columns)
.toUri(new Mapper<Manageable, String>() {
@Override
public String map(Manageable handle) throws Exception {
return Msc.specialUri("manageables", kind, Msc.urlEncode(handle.id()));
}
})
.pageSize(20);
info.add(grid);
} | #vulnerable code
private void addInfo(List<Object> info, final GroupOf<?> group, List<? extends Manageable> items, List<String> columns) {
columns.add("(Actions)");
final String groupName = group.name();
String type = U.first(items).getManageableType();
info.add(breadcrumb(type, groupName));
Grid grid = grid(items)
.columns(columns)
.headers(columns)
.toUri(new Mapper<Manageable, String>() {
@Override
public String map(Manageable handle) throws Exception {
return Msc.uri("_manageables", handle.getClass().getSimpleName(), Msc.urlEncode(handle.id()));
}
})
.pageSize(20);
info.add(grid);
}
#location 5
#vulnerability type NULL_DEREFERENCE |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.