input
stringlengths 205
73.3k
| output
stringlengths 64
73.2k
| instruction
stringclasses 1
value |
|---|---|---|
#vulnerable code
@Override
public void close() throws IOException {
if (this.queueFrontIndexPageFactory != null) {
this.queueFrontIndexPageFactory.releaseCachedPages();
}
if (dequeueFuture != null) {
/* Cancel the future but don't interrupt running tasks
because they might perform further work not refering to the queue
*/
dequeueFuture.cancel(false);
}
this.innerArray.close();
}
#location 11
#vulnerability type THREAD_SAFETY_VIOLATION
|
#fixed code
@Override
public void close() throws IOException {
if (this.queueFrontIndexPageFactory != null) {
this.queueFrontIndexPageFactory.releaseCachedPages();
}
synchronized (futureLock) {
/* Cancel the future but don't interrupt running tasks
because they might perform further work not refering to the queue
*/
if (peekFuture != null) {
peekFuture.cancel(false);
}
if (dequeueFuture != null) {
dequeueFuture.cancel(false);
}
}
this.innerArray.close();
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
@Test
public void testConstructor5(){
ClassCastInputCSVException e = new ClassCastInputCSVException(Integer.valueOf(23), String.class, ANONYMOUS_CSVCONTEXT, PROCESSOR);
assertEquals(ANONYMOUS_CSVCONTEXT, e.getCsvContext());
assertEquals(PROCESSOR, e.getOffendingProcessor());
e.printStackTrace();
// test with null received value
e = new ClassCastInputCSVException(null, String.class, ANONYMOUS_CSVCONTEXT, PROCESSOR);
assertEquals(ANONYMOUS_CSVCONTEXT, e.getCsvContext());
assertEquals(PROCESSOR, e.getOffendingProcessor());
e.printStackTrace();
// test with null received, expected, context and processor
e = new ClassCastInputCSVException(null, null, (CSVContext) null, (CellProcessor) null);
assertNull(e.getMessage());
assertNull(e.getCsvContext());
assertNull(e.getOffendingProcessor());
e.printStackTrace();
}
#location 15
#vulnerability type NULL_DEREFERENCE
|
#fixed code
@Test
public void testConstructor5() {
ClassCastInputCSVException e = new ClassCastInputCSVException(Integer.valueOf(23), String.class,
ANONYMOUS_CSVCONTEXT, PROCESSOR);
assertEquals(ANONYMOUS_CSVCONTEXT, e.getCsvContext());
assertEquals(PROCESSOR, e.getOffendingProcessor());
e.printStackTrace();
// test with null received value
e = new ClassCastInputCSVException(null, String.class, ANONYMOUS_CSVCONTEXT, PROCESSOR);
assertEquals(ANONYMOUS_CSVCONTEXT, e.getCsvContext());
assertEquals(PROCESSOR, e.getOffendingProcessor());
e.printStackTrace();
// test with null received, expected, context and processor
try {
e = new ClassCastInputCSVException(null, null, (CSVContext) null, (CellProcessor) null);
fail("should have thrown NullPointerException");
}
catch(NullPointerException npe) {}
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
@Test
public void testConstructor3() {
NullInputException e = new NullInputException(MSG, ANONYMOUS_CSVCONTEXT, THROWABLE);
assertEquals(CONCATENATED_MSG, e.getMessage());
assertEquals(ANONYMOUS_CSVCONTEXT, e.getCsvContext());
assertEquals(THROWABLE, e.getCause());
e.printStackTrace();
// test with null msg, context and throwable
e = new NullInputException(null, (CSVContext) null, (Throwable) null);
assertNull(e.getMessage());
assertNull(e.getCsvContext());
assertNull(e.getCause());
e.printStackTrace();
}
#location 10
#vulnerability type NULL_DEREFERENCE
|
#fixed code
@Test
public void testConstructor3() {
NullInputException e = new NullInputException(MSG, ANONYMOUS_CSVCONTEXT, THROWABLE);
assertEquals(MSG, e.getMessage());
assertEquals(ANONYMOUS_CSVCONTEXT, e.getCsvContext());
assertEquals(THROWABLE, e.getCause());
e.printStackTrace();
// test with null msg, context and throwable
e = new NullInputException(null, (CSVContext) null, (Throwable) null);
assertNull(e.getMessage());
assertNull(e.getCsvContext());
assertNull(e.getCause());
e.printStackTrace();
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
@Test
public void testProcesssedRead() throws Exception {
UserBean user;
final String[] header = inFile.getCSVHeader(true);
user = inFile.read(UserBean.class, header, processors);
Assert.assertEquals("read elem ", "Klaus", user.getUsername());
Assert.assertEquals("read elem ", "qwexyKiks", user.getPassword());
final Date cal = new Date(2007 - 1900, 10 - 1, 1);
Assert.assertEquals(cal, user.getDate());
Assert.assertEquals("read elem ", 4328, user.getZip());
Assert.assertEquals("read elem ", "New York", user.getTown());
}
#location 7
#vulnerability type NULL_DEREFERENCE
|
#fixed code
@Test
public void testProcesssedRead() throws Exception {
UserBean user;
final String[] header = inFile.getCSVHeader(true);
assertThat(header[2], is("date"));
user = inFile.read(UserBean.class, header, processors);
Assert.assertEquals("read elem ", "Klaus", user.getUsername());
Assert.assertEquals("read elem ", "qwexyKiks", user.getPassword());
final Date cal = new Date(2007 - 1900, 10 - 1, 1);
Assert.assertEquals(cal, user.getDate());
Assert.assertEquals("read elem ", 4328, user.getZip());
Assert.assertEquals("read elem ", "New York", user.getTown());
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
@Test
public void testGetHeaderNoCheck() throws IOException {
assertEquals(4, abstractReader.getCsvHeader(false).length);
assertEquals(4, abstractReader.getCsvHeader(false).length);
assertEquals(4, abstractReader.getCsvHeader(false).length);
assertNull(abstractReader.getCsvHeader(false)); // should be EOF
}
#location 3
#vulnerability type NULL_DEREFERENCE
|
#fixed code
@Test
public void testGetHeaderNoCheck() throws IOException {
assertEquals(4, abstractReader.getHeader(false).length);
assertEquals(4, abstractReader.getHeader(false).length);
assertEquals(4, abstractReader.getHeader(false).length);
assertNull(abstractReader.getHeader(false)); // should be EOF
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
@Test
public void testConstructor2() {
NullInputException e = new NullInputException(MSG, PROCESSOR, THROWABLE);
assertEquals(CONCATENATED_MSG, e.getMessage());
assertEquals(PROCESSOR, e.getOffendingProcessor());
assertEquals(THROWABLE, e.getCause());
e.printStackTrace();
// test with null msg, processor and throwable
e = new NullInputException(null, (CellProcessor) null, (Throwable) null);
assertNull(e.getMessage());
assertNull(e.getOffendingProcessor());
assertNull(e.getCause());
e.printStackTrace();
}
#location 10
#vulnerability type NULL_DEREFERENCE
|
#fixed code
@Test
public void testConstructor2() {
NullInputException e = new NullInputException(MSG, PROCESSOR, THROWABLE);
assertEquals(MSG, e.getMessage());
assertEquals(PROCESSOR, e.getOffendingProcessor());
assertEquals(THROWABLE, e.getCause());
e.printStackTrace();
// test with null msg, processor and throwable
e = new NullInputException(null, (CellProcessor) null, (Throwable) null);
assertNull(e.getMessage());
assertNull(e.getOffendingProcessor());
assertNull(e.getCause());
e.printStackTrace();
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
@Test
public void should_escape() {
final TestClass absWriter = new TestClass(new StringWriter(), CsvPreference.EXCEL_PREFERENCE);
assertThat(columnsToWrite.length, is(expectedReadResultsFromColumnToWrite.length));
for( int i = 0; i < columnsToWrite.length; i++ ) {
Assert.assertEquals(expectedReadResultsFromColumnToWrite[i], absWriter.escapeString(columnsToWrite[i]));
// assertThat(absWriter.escapeString(columnsToWrite[i]), is(expectedOutput[i]));
}
}
#location 9
#vulnerability type RESOURCE_LEAK
|
#fixed code
@Test
public void should_escape() {
final MockWriter absWriter = new MockWriter(new StringWriter(), CsvPreference.EXCEL_PREFERENCE);
assertThat(columnsToWrite.length, is(expectedReadResultsFromColumnToWrite.length));
for( int i = 0; i < columnsToWrite.length; i++ ) {
Assert.assertEquals(expectedReadResultsFromColumnToWrite[i], absWriter.escapeString(columnsToWrite[i]));
// assertThat(absWriter.escapeString(columnsToWrite[i]), is(expectedOutput[i]));
}
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
@Test
public void testConstuctor5(){
SuperCSVException e = new SuperCSVException(MSG, ANONYMOUS_CSVCONTEXT, THROWABLE);
assertEquals(CONCATENATED_MSG, e.getMessage());
assertEquals(ANONYMOUS_CSVCONTEXT, e.getCsvContext());
assertEquals(THROWABLE, e.getCause());
e.printStackTrace();
// test with null msg, context and throwable
e = new SuperCSVException(null, (CSVContext) null, (Throwable) null);
assertNull(e.getMessage());
assertNull(e.getCsvContext());
assertNull(e.getCause());
e.printStackTrace();
}
#location 10
#vulnerability type NULL_DEREFERENCE
|
#fixed code
@Test
public void testConstuctor5(){
SuperCSVException e = new SuperCSVException(MSG, ANONYMOUS_CSVCONTEXT, THROWABLE);
assertEquals(MSG, e.getMessage());
assertEquals(ANONYMOUS_CSVCONTEXT, e.getCsvContext());
assertEquals(THROWABLE, e.getCause());
e.printStackTrace();
// test with null msg, context and throwable
e = new SuperCSVException(null, (CSVContext) null, (Throwable) null);
assertNull(e.getMessage());
assertNull(e.getCsvContext());
assertNull(e.getCause());
e.printStackTrace();
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
@Test
public void testConstructor2(){
SuperCSVReflectionException e = new SuperCSVReflectionException(MSG, THROWABLE);
assertEquals(CONCATENATED_MSG, e.getMessage());
assertEquals(THROWABLE, e.getCause());
e.printStackTrace();
// test with null msg
e = new SuperCSVReflectionException(null, null);
assertNull(e.getMessage());
assertNull(e.getCause());
e.printStackTrace();
}
#location 9
#vulnerability type NULL_DEREFERENCE
|
#fixed code
@Test
public void testConstructor2(){
SuperCSVReflectionException e = new SuperCSVReflectionException(MSG, THROWABLE);
assertEquals(MSG, e.getMessage());
assertEquals(THROWABLE, e.getCause());
e.printStackTrace();
// test with null msg
e = new SuperCSVReflectionException(null, null);
assertNull(e.getMessage());
assertNull(e.getCause());
e.printStackTrace();
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
@Test
public void testConstuctor3(){
SuperCSVException e = new SuperCSVException(MSG, ANONYMOUS_CSVCONTEXT, THROWABLE);
assertEquals(CONCATENATED_MSG, e.getMessage());
assertEquals(ANONYMOUS_CSVCONTEXT, e.getCsvContext());
assertEquals(THROWABLE, e.getCause());
e.printStackTrace();
// test with null msg, context and throwable
e = new SuperCSVException(null, (CSVContext) null, (Throwable) null);
assertNull(e.getMessage());
assertNull(e.getCsvContext());
assertNull(e.getCause());
e.printStackTrace();
}
#location 10
#vulnerability type NULL_DEREFERENCE
|
#fixed code
@Test
public void testConstuctor3(){
SuperCSVException e = new SuperCSVException(MSG, ANONYMOUS_CSVCONTEXT, THROWABLE);
assertEquals(MSG, e.getMessage());
assertEquals(ANONYMOUS_CSVCONTEXT, e.getCsvContext());
assertEquals(THROWABLE, e.getCause());
e.printStackTrace();
// test with null msg, context and throwable
e = new SuperCSVException(null, (CSVContext) null, (Throwable) null);
assertNull(e.getMessage());
assertNull(e.getCsvContext());
assertNull(e.getCause());
e.printStackTrace();
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
@Test
public void testConstuctor6(){
SuperCSVException e = new SuperCSVException(MSG, ANONYMOUS_CSVCONTEXT, PROCESSOR, THROWABLE);
assertEquals(CONCATENATED_MSG, e.getMessage());
assertEquals(ANONYMOUS_CSVCONTEXT, e.getCsvContext());
assertEquals(PROCESSOR, e.getOffendingProcessor());
assertEquals(THROWABLE, e.getCause());
e.printStackTrace();
// test with null msg, context, processor and throwable
e = new SuperCSVException(null, null, null, null);
assertNull(e.getMessage());
assertNull(e.getCsvContext());
assertNull(e.getOffendingProcessor());
assertNull(e.getCause());
e.printStackTrace();
}
#location 11
#vulnerability type NULL_DEREFERENCE
|
#fixed code
@Test
public void testConstuctor6(){
SuperCSVException e = new SuperCSVException(MSG, ANONYMOUS_CSVCONTEXT, PROCESSOR, THROWABLE);
assertEquals(MSG, e.getMessage());
assertEquals(ANONYMOUS_CSVCONTEXT, e.getCsvContext());
assertEquals(PROCESSOR, e.getOffendingProcessor());
assertEquals(THROWABLE, e.getCause());
e.printStackTrace();
// test with null msg, context, processor and throwable
e = new SuperCSVException(null, null, null, null);
assertNull(e.getMessage());
assertNull(e.getCsvContext());
assertNull(e.getOffendingProcessor());
assertNull(e.getCause());
e.printStackTrace();
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
@Test
public void testConstructor1(){
ClassCastInputCSVException e = new ClassCastInputCSVException(MSG, ANONYMOUS_CSVCONTEXT, THROWABLE);
assertEquals(CONCATENATED_MSG, e.getMessage());
assertEquals(ANONYMOUS_CSVCONTEXT, e.getCsvContext());
assertEquals(THROWABLE, e.getCause());
e.printStackTrace();
// test with null msg, context and throwable
e = new ClassCastInputCSVException(null, (CSVContext) null, (Throwable) null);
assertNull(e.getMessage());
assertNull(e.getCsvContext());
assertNull(e.getCause());
e.printStackTrace();
}
#location 10
#vulnerability type NULL_DEREFERENCE
|
#fixed code
@Test
public void testConstructor1() {
ClassCastInputCSVException e = new ClassCastInputCSVException(MSG, ANONYMOUS_CSVCONTEXT, THROWABLE);
assertEquals(MSG, e.getMessage());
assertEquals(ANONYMOUS_CSVCONTEXT, e.getCsvContext());
assertEquals(THROWABLE, e.getCause());
e.printStackTrace();
// test with null msg, context and throwable
e = new ClassCastInputCSVException(null, (CSVContext) null, (Throwable) null);
assertNull(e.getMessage());
assertNull(e.getCsvContext());
assertNull(e.getCause());
e.printStackTrace();
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
@Override
public String getConversationId() {
return getViewCache().getCurrentConversationId();
}
#location 3
#vulnerability type THREAD_SAFETY_VIOLATION
|
#fixed code
@Override
public String getConversationId() {
return null;
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
@Test
public void moduleThrowingInitExceptionShouldBeMarkedForReinitializationOnlyTheFirstTime() throws InterruptedException {
final TxDrivenModule mockModule = createMockModule();
when(mockModule.getConfiguration()).thenReturn(NullTxDrivenModuleConfiguration.getInstance());
doThrow(new NeedsInitializationException()).when(mockModule).beforeCommit(any(ImprovedTransactionData.class));
GraphAwareRuntime runtime = GraphAwareRuntimeFactory.createRuntime(database);
runtime.registerModule(mockModule);
runtime.start();
try (Transaction tx = database.beginTx()) {
database.createNode();
tx.success();
}
long firstFailureTimestamp;
try (Transaction tx = database.beginTx()) {
firstFailureTimestamp = Long.valueOf(getRuntimeRoot().getProperty(GA_PREFIX + RUNTIME + "_" + MOCK).toString().replaceFirst(FORCE_INITIALIZATION, ""));
}
Thread.sleep(1);
try (Transaction tx = database.beginTx()) {
database.createNode();
tx.success();
}
long secondFailureTimestamp;
try (Transaction tx = database.beginTx()) {
secondFailureTimestamp = Long.valueOf(getRuntimeRoot().getProperty(GA_PREFIX + RUNTIME + "_" + MOCK).toString().replaceFirst(FORCE_INITIALIZATION, ""));
}
assertEquals(firstFailureTimestamp, secondFailureTimestamp);
}
#location 19
#vulnerability type NULL_DEREFERENCE
|
#fixed code
@Test
public void moduleThrowingInitExceptionShouldBeMarkedForReinitializationOnlyTheFirstTime() throws InterruptedException {
final TxDrivenModule mockModule = createMockModule();
when(mockModule.getConfiguration()).thenReturn(NullTxDrivenModuleConfiguration.getInstance());
doThrow(new NeedsInitializationException()).when(mockModule).beforeCommit(any(ImprovedTransactionData.class));
GraphAwareRuntime runtime = GraphAwareRuntimeFactory.createRuntime(database);
runtime.registerModule(mockModule);
runtime.start();
try (Transaction tx = database.beginTx()) {
database.createNode();
tx.success();
}
long firstFailureTimestamp;
try (Transaction tx = database.beginTx()) {
firstFailureTimestamp = repository.getModuleMetadata(mockModule).timestamp();
}
Thread.sleep(1);
try (Transaction tx = database.beginTx()) {
database.createNode();
tx.success();
}
long secondFailureTimestamp;
try (Transaction tx = database.beginTx()) {
secondFailureTimestamp = repository.getModuleMetadata(mockModule).timestamp();
}
assertEquals(firstFailureTimestamp, secondFailureTimestamp);
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
@Override
protected void startJetty() {
ApplicationContext rootContext = createRootApplicationContext();
HandlerList handlerList = findHandlerList();
SessionManager sessionManager = findSessionManager(handlerList);
addHandlers(handlerList, sessionManager, rootContext);
addFilters();
super.startJetty();
}
#location 9
#vulnerability type RESOURCE_LEAK
|
#fixed code
@Override
protected void startJetty() {
rootContext = createRootApplicationContext();
HandlerList handlerList = findHandlerList();
SessionManager sessionManager = findSessionManager(handlerList);
addHandlers(handlerList, sessionManager, rootContext);
addFilters();
super.startJetty();
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
private static <K, V> V getSingleValue(Map<K, V> map) {
return getSingle(map.entrySet()).getValue();
}
#location 2
#vulnerability type NULL_DEREFERENCE
|
#fixed code
private static <K, V> V getSingleValue(Map<K, V> map) {
return getSingleOrNull(map.entrySet()).getValue();
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
@Test
public void verifyRandomWalkerModuleCorrectlyGeneratesReasonablePageRankMeasurements() throws InterruptedException {
// firstly, generate a graph
final int numberOfNodes = 10;
GraphGenerator graphGenerator = new Neo4jGraphGenerator(database);
LOG.info("Generating Barabasi-Albert social network graph with {} nodes...", numberOfNodes);
graphGenerator.generateGraph(new BasicGeneratorConfiguration(numberOfNodes, new BarabasiAlbertGraphRelationshipGenerator(
new BarabasiAlbertConfig(numberOfNodes, 5)), SocialNetworkNodeCreator.getInstance(), SocialNetworkRelationshipCreator
.getInstance()));
LOG.info("Computing adjacency matrix for graph...");
// secondly, compute the adjacency matrix for this graph
NetworkMatrixFactory networkMatrixFactory = new NetworkMatrixFactory(database);
try (Transaction tx = database.beginTx()) {
LOG.info("Computing page rank based on adjacency matrix...");
// thirdly, compute the page rank of this graph based on the adjacency matrix
PageRank pageRank = new PageRank();
NetworkMatrix transitionMatrix = networkMatrixFactory.getTransitionMatrix();
List<RankNodePair> pageRankResult = pageRank.getPageRankPairs(transitionMatrix, 0.85); // Sergei's & Larry's suggestion is to use .85 to become rich;)
LOG.info(pageRankResult.toString());
LOG.info("Applying random graph walker module to page rank graph");
// fourthly, run the rage rank module to compute the random walker's page rank
GraphAwareRuntime runtime = GraphAwareRuntimeFactory.createRuntime(database);
runtime.registerModule(pageRankModule);
runtime.start();
LOG.info("Waiting for module walker to do its work");
TimeUnit.SECONDS.sleep(30);
// finally, compare both page rank metrics and verify the module is producing what it should
// XXX: I understand this is WIP, but why does this return a list if it's called get..Map?
// YYY: I call it a Map, since it is effectivelly the inverse of the Node, Integer hashMap from the NetworkMatrixFactory
// and it is used only to map the indices from of the pagerank values back to the Nodes. Quite clumsy, on todo list ;)
// List<Node> indexMap = networkMatrixFactory.getIndexMap();
LOG.info("The highest PageRank in the network is: " + pageRankResult.get(0).node().getProperty("name").toString());
//LOG.info("Top of the rank map is: {}", indexMap.get(0).getProperty("name"));
int topRank = 0;
Node topNode = null;
for (RankNodePair pair : pageRankResult) {
System.out.printf("%s\t%s\t%s\n", pair.node().getProperty("name"),
"NeoRank: " + pair.node().getProperty(RandomWalkerPageRankModule.PAGE_RANK_PROPERTY_KEY).toString(), "PageRank: " + pair.rank());
int rank = (int) pair.node().getProperty(RandomWalkerPageRankModule.PAGE_RANK_PROPERTY_KEY);
if (rank > topRank) {
topRank = rank;
topNode = pair.node();
}
}
LOG.info("The highest NeoRank in the network is: " + topNode.getProperty("name").toString());
}
}
#location 61
#vulnerability type NULL_DEREFERENCE
|
#fixed code
@Test
public void verifyRandomWalkerModuleCorrectlyGeneratesReasonablePageRankMeasurements() throws InterruptedException {
// firstly, generate a graph
final int numberOfNodes = 50;
GraphGenerator graphGenerator = new Neo4jGraphGenerator(database);
LOG.info("Generating Barabasi-Albert social network graph with {} nodes...", numberOfNodes);
graphGenerator.generateGraph(new BasicGeneratorConfiguration(numberOfNodes, new BarabasiAlbertGraphRelationshipGenerator(
new BarabasiAlbertConfig(numberOfNodes, 2)), SocialNetworkNodeCreator.getInstance(), SocialNetworkRelationshipCreator
.getInstance()));
LOG.info("Computing adjacency matrix for graph...");
// secondly, compute the adjacency matrix for this graph
NetworkMatrixFactory networkMatrixFactory = new NetworkMatrixFactory(database);
try (Transaction tx = database.beginTx()) {
LOG.info("Computing page rank based on adjacency matrix...");
// thirdly, compute the page rank of this graph based on the adjacency matrix
PageRank pageRank = new PageRank();
NetworkMatrix transitionMatrix = networkMatrixFactory.getTransitionMatrix();
List<RankNodePair> pageRankResult = pageRank.getPageRankPairs(transitionMatrix, 0.85); // Sergei's & Larry's suggestion is to use .85 to become rich;)
//LOG.info(pageRankResult.toString());
LOG.info("Applying random graph walker module to page rank graph");
// fourthly, run the rage rank module to compute the random walker's page rank
GraphAwareRuntime runtime = GraphAwareRuntimeFactory.createRuntime(database);
runtime.registerModule(pageRankModule);
runtime.start();
LOG.info("Waiting for module walker to do its work");
TimeUnit.SECONDS.sleep(30);
// finally, compare both page rank metrics and verify the module is producing what it should
// List<Node> indexMap = networkMatrixFactory.getIndexMap();
LOG.info("The highest PageRank in the network is: " + pageRankResult.get(0).node().getProperty("name").toString());
//LOG.info("Top of the rank map is: {}", indexMap.get(0).getProperty("name"));
ArrayList<RankNodePair> neoRank = new ArrayList<>();
for (RankNodePair pair : pageRankResult) {
Node node = pair.node();
int rank = (int) pair.node().getProperty(RandomWalkerPageRankModule.PAGE_RANK_PROPERTY_KEY);
//System.out.printf("%s\t%s\t%s\n", node.getProperty("name"),
// "NeoRank: " + rank, "PageRank: " + pair.rank());
neoRank.add(new RankNodePair(rank, node));
}
sort(neoRank, new RankNodePairComparator());
LOG.info("The highest NeoRank in the network is: " + neoRank.get(0).node().getProperty("name").toString());
// Perform an analysis of the results:
LOG.info("Analysing results:");
analyseResults(RankNodePair.convertToRankedNodeList(pageRankResult), RankNodePair.convertToRankedNodeList(neoRank));
}
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
@Override
protected void startJetty() {
ApplicationContext rootContext = createRootApplicationContext();
HandlerList handlerList = findHandlerList();
SessionManager sessionManager = findSessionManager(handlerList);
addHandlers(handlerList, sessionManager, rootContext);
addFilters();
super.startJetty();
}
#location 14
#vulnerability type RESOURCE_LEAK
|
#fixed code
@Override
protected void startJetty() {
rootContext = createRootApplicationContext();
HandlerList handlerList = findHandlerList();
SessionManager sessionManager = findSessionManager(handlerList);
addHandlers(handlerList, sessionManager, rootContext);
addFilters();
super.startJetty();
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
@Test
public void moduleThrowingInitExceptionShouldBeMarkedForReinitialization() {
final TxDrivenModule mockModule = createMockModule();
when(mockModule.getConfiguration()).thenReturn(NullTxDrivenModuleConfiguration.getInstance());
Mockito.doThrow(new NeedsInitializationException()).when(mockModule).beforeCommit(any(ImprovedTransactionData.class));
GraphAwareRuntime runtime = GraphAwareRuntimeFactory.createRuntime(database);
runtime.registerModule(mockModule);
runtime.start();
try (Transaction tx = database.beginTx()) {
assertTrue(getRuntimeRoot().getProperty(GA_PREFIX + RUNTIME + "_" + MOCK).toString().startsWith(CONFIG));
tx.success();
}
try (Transaction tx = database.beginTx()) {
database.createNode();
tx.success();
}
try (Transaction tx = database.beginTx()) {
assertTrue(getRuntimeRoot().getProperty(GA_PREFIX + RUNTIME + "_" + MOCK).toString().startsWith(FORCE_INITIALIZATION));
tx.success();
}
}
#location 13
#vulnerability type NULL_DEREFERENCE
|
#fixed code
@Test
public void moduleThrowingInitExceptionShouldBeMarkedForReinitialization() {
final TxDrivenModule mockModule = createMockModule();
when(mockModule.getConfiguration()).thenReturn(NullTxDrivenModuleConfiguration.getInstance());
Mockito.doThrow(new NeedsInitializationException()).when(mockModule).beforeCommit(any(ImprovedTransactionData.class));
GraphAwareRuntime runtime = GraphAwareRuntimeFactory.createRuntime(database);
runtime.registerModule(mockModule);
runtime.start();
try (Transaction tx = database.beginTx()) {
TxDrivenModuleMetadata moduleMetadata = repository.getModuleMetadata(mockModule);
assertEquals(NullTxDrivenModuleConfiguration.getInstance(), moduleMetadata.getConfig());
assertFalse(moduleMetadata.needsInitialization());
assertEquals(-1, moduleMetadata.timestamp());
}
try (Transaction tx = database.beginTx()) {
database.createNode();
tx.success();
}
try (Transaction tx = database.beginTx()) {
TxDrivenModuleMetadata moduleMetadata = repository.getModuleMetadata(mockModule);
assertEquals(NullTxDrivenModuleConfiguration.getInstance(), moduleMetadata.getConfig());
assertTrue(moduleMetadata.needsInitialization());
assertTrue(moduleMetadata.timestamp() > System.currentTimeMillis() - 1000);
}
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
public void load(InputStream input) throws IOException {
BufferedReader reader = new BufferedReader(new InputStreamReader(input));
for (;;) {
String line = reader.readLine();
if (line == null) {
break;
}
line = line.trim();
if (line.isEmpty()) {
continue;
}
putFromLine(line);
}
}
#location 7
#vulnerability type RESOURCE_LEAK
|
#fixed code
public void load(InputStream input) throws IOException {
BufferedReader reader = new BufferedReader(new InputStreamReader(input, "UTF-8"));
for (;;) {
String line = reader.readLine();
if (line == null) {
break;
}
line = line.trim();
if (line.isEmpty()) {
continue;
}
putFromLine(line);
}
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
public void javaUtilLogging() {
String tainted = System.getProperty("");
String safe = "safe";
Logger logger = Logger.getLogger(Logging.class.getName());
logger.setLevel(Level.ALL);
ConsoleHandler handler = new ConsoleHandler();
handler.setLevel(Level.ALL);
logger.addHandler(handler);
logger.config(tainted);
logger.entering(tainted, safe);
logger.entering("safe", safe, tainted);
logger.entering(safe, "safe", new String[]{tainted});
logger.exiting(safe, tainted);
logger.exiting(safe, "safe", tainted);
logger.fine(tainted);
logger.finer(tainted.trim());
logger.finest(tainted);
logger.info(tainted);
logger.log(Level.INFO, tainted);
logger.log(Level.INFO, tainted, safe);
logger.log(Level.INFO, "safe", new String[]{tainted});
logger.log(Level.INFO, tainted, new Exception());
logger.logp(Level.INFO, tainted, safe, "safe");
logger.logp(Level.INFO, safe, "safe", tainted, safe);
logger.logp(Level.INFO, "safe", safe.toLowerCase(), safe, new String[]{tainted});
logger.logp(Level.INFO, tainted, safe, safe, new Exception());
logger.logp(Level.INFO, tainted, "safe", (Supplier<String>) null);
logger.logp(Level.INFO, "safe", tainted, new Exception(), (Supplier<String>) null);
logger.logrb(Level.INFO, safe, safe, (ResourceBundle) null, "safe", tainted);
logger.logrb(Level.INFO, tainted, safe, (ResourceBundle) null, safe, new Exception());
logger.logrb(Level.INFO, tainted, safe, "bundle", safe);
logger.logrb(Level.INFO, safe, tainted, "bundle", safe, safe);
logger.logrb(Level.INFO, tainted, "safe", "bundle", safe, new String[]{safe});
logger.logrb(Level.INFO, safe, safe, "bundle", tainted, new Exception());
logger.severe(tainted + "safe" + safe);
logger.throwing("safe", tainted, new Exception());
logger.warning(tainted);
// these should not be reported
logger.fine(safe);
logger.log(Level.INFO, "safe".toUpperCase(), safe + safe);
logger.logp(Level.INFO, safe, safe, safe, new String[]{safe});
logger.logrb(Level.INFO, safe, safe, tainted + "bundle", safe); // bundle name can be tainted
logger.throwing(safe, safe, new Exception());
}
#location 17
#vulnerability type NULL_DEREFERENCE
|
#fixed code
public void javaUtilLogging() {
String tainted = req.getParameter("test");
String safe = "safe";
Logger logger = Logger.getLogger(Logging.class.getName());
logger.setLevel(Level.ALL);
ConsoleHandler handler = new ConsoleHandler();
handler.setLevel(Level.ALL);
logger.addHandler(handler);
logger.config(tainted);
logger.entering(tainted, safe);
logger.entering("safe", safe, tainted);
logger.entering(safe, "safe", new String[]{tainted});
logger.exiting(safe, tainted);
logger.exiting(safe, "safe", tainted);
logger.fine(tainted);
logger.finer(tainted.trim());
logger.finest(tainted);
logger.info(tainted);
logger.log(Level.INFO, tainted);
logger.log(Level.INFO, tainted, safe);
logger.log(Level.INFO, "safe", new String[]{tainted});
logger.log(Level.INFO, tainted, new Exception());
logger.logp(Level.INFO, tainted, safe, "safe");
logger.logp(Level.INFO, safe, "safe", tainted, safe);
logger.logp(Level.INFO, "safe", safe.toLowerCase(), safe, new String[]{tainted});
logger.logp(Level.INFO, tainted, safe, safe, new Exception());
logger.logp(Level.INFO, tainted, "safe", (Supplier<String>) null);
logger.logp(Level.INFO, "safe", tainted, new Exception(), (Supplier<String>) null);
logger.logrb(Level.INFO, safe, safe, (ResourceBundle) null, "safe", tainted);
logger.logrb(Level.INFO, tainted, safe, (ResourceBundle) null, safe, new Exception());
logger.logrb(Level.INFO, tainted, safe, "bundle", safe);
logger.logrb(Level.INFO, safe, tainted, "bundle", safe, safe);
logger.logrb(Level.INFO, tainted, "safe", "bundle", safe, new String[]{safe});
logger.logrb(Level.INFO, safe, safe, "bundle", tainted, new Exception());
logger.severe(tainted + "safe" + safe);
logger.throwing("safe", tainted, new Exception());
logger.warning(tainted);
// these should not be reported
logger.fine(safe);
logger.log(Level.INFO, "safe".toUpperCase(), safe + safe);
logger.logp(Level.INFO, safe, safe, safe, new String[]{safe});
logger.logrb(Level.INFO, safe, safe, tainted + "bundle", safe); // bundle name can be tainted
logger.throwing(safe, safe, new Exception());
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
private byte[] buildFakePluginJar() throws IOException {
ClassLoader cl = getClass().getClassLoader();
ByteArrayOutputStream buffer = new ByteArrayOutputStream();
JarOutputStream jar = new JarOutputStream(buffer);
//Add files to the jar stream
for (String resource : Arrays.asList("findbugs.xml", "messages.xml", "META-INF/MANIFEST.MF")) {
jar.putNextEntry(new ZipEntry(resource));
jar.write(IOUtils.toByteArray(cl.getResourceAsStream("metadata/" + resource)));
}
jar.finish();
return buffer.toByteArray();
}
#location 12
#vulnerability type RESOURCE_LEAK
|
#fixed code
private byte[] buildFakePluginJar() throws IOException, URISyntaxException {
ClassLoader cl = getClass().getClassLoader();
ByteArrayOutputStream buffer = new ByteArrayOutputStream();
JarOutputStream jar = new JarOutputStream(buffer);
final URL metadata = cl.getResource("metadata");
if (metadata != null) {
final File dir = new File(metadata.toURI());
//Add files to the jar stream
addFilesToStream(cl, jar, dir, "");
}
jar.finish();
jar.close();
return buffer.toByteArray();
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
private void visitInvoke(InvokeInstruction obj) {
assert obj != null;
TaintMethodSummary methodSummary = getMethodSummary(obj);
Taint taint = getMethodTaint(methodSummary);
assert taint != null;
if (taint.isUnknown()) {
taint.addTaintLocation(getTaintLocation(), false);
}
taintMutableArguments(methodSummary, obj);
transferTaintToMutables(methodSummary, taint); // adds variable index to taint too
modelInstruction(obj, getNumWordsConsumed(obj), getNumWordsProduced(obj), new Taint(taint));
}
#location 4
#vulnerability type NULL_DEREFERENCE
|
#fixed code
private void visitInvoke(InvokeInstruction obj) {
assert obj != null;
TaintMethodSummary methodSummary = getMethodSummary(obj);
Taint taint = getMethodTaint(methodSummary);
assert taint != null;
if (taint.isUnknown()) {
taint.addLocation(getTaintLocation(), false);
}
taintMutableArguments(methodSummary, obj);
transferTaintToMutables(methodSummary, taint); // adds variable index to taint too
modelInstruction(obj, getNumWordsConsumed(obj), getNumWordsProduced(obj), new Taint(taint));
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
private void visitInvoke(InvokeInstruction obj) {
assert obj != null;
try {
TaintMethodConfig methodConfig = getMethodConfig(obj);
ObjectType realInstanceClass = (methodConfig == null) ?
null : methodConfig.getOutputTaint().getRealInstanceClass();
Taint taint = getMethodTaint(methodConfig);
assert taint != null;
if (FindSecBugsGlobalConfig.getInstance().isDebugTaintState()) {
taint.setDebugInfo(obj.getMethodName(cpg) + "()"); //TODO: Deprecated debug info
}
taint.addSource(new UnknownSource(UnknownSourceType.RETURN,taint.getState()).setSignatureMethod(obj.getClassName(cpg).replace(".","/")+"."+obj.getMethodName(cpg)+obj.getSignature(cpg)));
if (taint.isUnknown()) {
taint.addLocation(getTaintLocation(), false);
}
taintMutableArguments(methodConfig, obj);
transferTaintToMutables(methodConfig, taint); // adds variable index to taint too
Taint taintCopy = new Taint(taint);
// return type is not always the instance type
taintCopy.setRealInstanceClass(realInstanceClass);
TaintFrame tf = getFrame();
int stackDepth = tf.getStackDepth();
int nbParam = getNumWordsConsumed(obj);
List<Taint> parameters = new ArrayList<>(nbParam);
for(int i=0;i<Math.min(stackDepth,nbParam);i++) {
parameters.add(new Taint(tf.getStackValue(i)));
}
modelInstruction(obj, getNumWordsConsumed(obj), getNumWordsProduced(obj), taintCopy);
for(TaintFrameAdditionalVisitor visitor : visitors) {
try {
visitor.visitInvoke(obj, methodGen, getFrame() , parameters, cpg);
}
catch (Throwable e) {
LOG.log(Level.SEVERE,"Error while executing "+visitor.getClass().getName(),e);
}
}
} catch (Exception e) {
String className = ClassName.toSlashedClassName(obj.getReferenceType(cpg).toString());
String methodName = obj.getMethodName(cpg);
String signature = obj.getSignature(cpg);
throw new RuntimeException("Unable to call " + className + '.' + methodName + signature, e);
}
}
#location 6
#vulnerability type NULL_DEREFERENCE
|
#fixed code
private void visitInvoke(InvokeInstruction obj) {
assert obj != null;
try {
TaintMethodConfig methodConfig = getMethodConfig(obj);
Taint taint = getMethodTaint(methodConfig);
assert taint != null;
if (FindSecBugsGlobalConfig.getInstance().isDebugTaintState()) {
taint.setDebugInfo(obj.getMethodName(cpg) + "()"); //TODO: Deprecated debug info
}
taint.addSource(new UnknownSource(UnknownSourceType.RETURN,taint.getState()).setSignatureMethod(obj.getClassName(cpg).replace(".","/")+"."+obj.getMethodName(cpg)+obj.getSignature(cpg)));
if (taint.isUnknown()) {
taint.addLocation(getTaintLocation(), false);
}
taintMutableArguments(methodConfig, obj);
transferTaintToMutables(methodConfig, taint); // adds variable index to taint too
Taint taintCopy = new Taint(taint);
// return type is not always the instance type
taintCopy.setRealInstanceClass(methodConfig != null && methodConfig.getOutputTaint() != null ? methodConfig.getOutputTaint().getRealInstanceClass() : null);
TaintFrame tf = getFrame();
int stackDepth = tf.getStackDepth();
int nbParam = getNumWordsConsumed(obj);
List<Taint> parameters = new ArrayList<>(nbParam);
for(int i=0;i<Math.min(stackDepth,nbParam);i++) {
parameters.add(new Taint(tf.getStackValue(i)));
}
modelInstruction(obj, getNumWordsConsumed(obj), getNumWordsProduced(obj), taintCopy);
for(TaintFrameAdditionalVisitor visitor : visitors) {
try {
visitor.visitInvoke(obj, methodGen, getFrame() , parameters, cpg);
}
catch (Throwable e) {
LOG.log(Level.SEVERE,"Error while executing "+visitor.getClass().getName(),e);
}
}
} catch (Exception e) {
String className = ClassName.toSlashedClassName(obj.getReferenceType(cpg).toString());
String methodName = obj.getMethodName(cpg);
String signature = obj.getSignature(cpg);
throw new RuntimeException("Unable to call " + className + '.' + methodName + signature, e);
}
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
private static List<String> loadFileContent(String path) {
try {
InputStream in = TaintAnalysis.class.getClassLoader().getResourceAsStream(path);
BufferedReader stream = new BufferedReader(new InputStreamReader(in));
String line;
List<String> content = new ArrayList<String>();
while ((line = stream.readLine()) != null) {
content.add(line.trim());
}
stream.close();
return content;
} catch (IOException e) {
LOG.log(Level.SEVERE, "Unable to load data from {0}", path);
}
return new ArrayList<String>();
}
#location 12
#vulnerability type RESOURCE_LEAK
|
#fixed code
private static List<String> loadFileContent(String path) {
BufferedReader stream = null;
try {
InputStream in = TaintAnalysis.class.getClassLoader().getResourceAsStream(path);
stream = new BufferedReader(new InputStreamReader(in, "utf-8"));
String line;
List<String> content = new ArrayList<String>();
while ((line = stream.readLine()) != null) {
content.add(line.trim());
}
return content;
} catch (IOException ex) {
assert false : ex.getMessage();
} finally {
IO.close(stream);
}
return new ArrayList<String>();
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
private static List<String> loadFileContent(String path) {
BufferedReader stream = null;
try {
InputStream in = TaintAnalysis.class.getClassLoader().getResourceAsStream(path);
stream = new BufferedReader(new InputStreamReader(in, "utf-8"));
String line;
List<String> content = new ArrayList<String>();
while ((line = stream.readLine()) != null) {
content.add(line.trim());
}
return content;
} catch (IOException ex) {
assert false : ex.getMessage();
} finally {
IO.close(stream);
}
return new ArrayList<String>();
}
#location 15
#vulnerability type RESOURCE_LEAK
|
#fixed code
private static List<String> loadFileContent(String path) {
try (InputStream in = TaintAnalysis.class.getClassLoader().getResourceAsStream(path);
BufferedReader stream = new BufferedReader(new InputStreamReader(in, "utf-8"))) {
String line;
List<String> content = new ArrayList<String>();
while ((line = stream.readLine()) != null) {
content.add(line.trim());
}
return content;
} catch (IOException ex) {
assert false : ex.getMessage();
}
return new ArrayList<String>();
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
private byte[] buildFakePluginJar() throws IOException {
ClassLoader cl = getClass().getClassLoader();
ByteArrayOutputStream buffer = new ByteArrayOutputStream();
JarOutputStream jar = new JarOutputStream(buffer);
//Add files to the jar stream
for (String resource : Arrays.asList("findbugs.xml", "messages.xml", "META-INF/MANIFEST.MF")) {
jar.putNextEntry(new ZipEntry(resource));
jar.write(IOUtils.toByteArray(cl.getResourceAsStream("metadata/" + resource)));
}
jar.finish();
return buffer.toByteArray();
}
#location 14
#vulnerability type RESOURCE_LEAK
|
#fixed code
private byte[] buildFakePluginJar() throws IOException, URISyntaxException {
ClassLoader cl = getClass().getClassLoader();
ByteArrayOutputStream buffer = new ByteArrayOutputStream();
JarOutputStream jar = new JarOutputStream(buffer);
final URL metadata = cl.getResource("metadata");
if (metadata != null) {
final File dir = new File(metadata.toURI());
//Add files to the jar stream
addFilesToStream(cl, jar, dir, "");
}
jar.finish();
jar.close();
return buffer.toByteArray();
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
public static void main(String[] args) throws IOException {
Function<LookupResult, Integer> resultTransformer = new Function<LookupResult, Integer>() {
@Nullable
@Override
public Integer apply(@Nullable LookupResult input) {
return input.weight();
}
};
DnsSrvResolver resolver = DnsSrvResolvers.newBuilder()
.cachingLookups(true)
.retainingDataOnFailures(true)
.dnsLookupTimeoutMillis(1000)
.build();
DnsSrvWatcher<LookupResult> watcher = DnsSrvResolvers.newWatcherBuilder(resolver)
.polling(1, TimeUnit.SECONDS)
.build();
boolean quit = false;
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
while (!quit) {
System.out.print("Enter a SRV name (empty to quit): ");
String line = in.readLine();
if (line == null || line.isEmpty()) {
quit = true;
} else {
try {
ChangeNotifier<LookupResult> notifier = watcher.watch(line);
notifier.setListener(new ChangeListener(line), false);
}
catch (DnsException e) {
e.printStackTrace(System.out);
}
}
}
}
#location 7
#vulnerability type RESOURCE_LEAK
|
#fixed code
public static void main(String[] args) throws IOException {
Function<LookupResult, Integer> resultTransformer = new Function<LookupResult, Integer>() {
@Nullable
@Override
public Integer apply(@Nullable LookupResult input) {
return input.weight();
}
};
DnsSrvResolver resolver = DnsSrvResolvers.newBuilder()
.cachingLookups(true)
.retainingDataOnFailures(true)
.dnsLookupTimeoutMillis(1000)
.build();
DnsSrvWatcher<LookupResult> watcher = DnsSrvResolvers.newWatcherBuilder(resolver)
.polling(1, TimeUnit.SECONDS)
.build();
boolean quit = false;
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
while (!quit) {
System.out.print("Enter a SRV name (empty to quit): ");
String line = in.readLine();
if (line == null || line.isEmpty()) {
quit = true;
} else {
try {
ChangeNotifier<LookupResult> notifier = watcher.watch(line);
notifier.setListener(new ChangeListener(line), false);
}
catch (DnsException e) {
e.printStackTrace(System.out);
}
}
}
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
@Override
public Set<T> current() {
ImmutableSet.Builder<T> records = ImmutableSet.builder();
for (final ChangeNotifier<T> changeNotifier : changeNotifiers) {
records.addAll(changeNotifier.current());
}
return records.build();
}
#location 2
#vulnerability type CHECKERS_IMMUTABLE_CAST
|
#fixed code
@Override
public Set<T> current() {
return records;
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
public static void main(String[] args) throws ExecutionException, InterruptedException, IOException {
DnsSrvResolver resolver = DnsSrvResolvers.newBuilder()
.cachingLookups(true)
.retainingDataOnFailures(true)
.metered(REPORTER)
.dnsLookupTimeoutMillis(1000)
.build();
boolean quit = false;
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
while (!quit) {
System.out.print("Enter a SRV name: ");
String line = in.readLine();
if (line == null) {
quit = true;
} else {
try {
List<HostAndPort> nodes = resolver.resolve(line);
for (HostAndPort node : nodes) {
System.out.println(node);
}
}
catch (DnsException e) {
e.printStackTrace(System.out);
}
}
}
}
#location 24
#vulnerability type RESOURCE_LEAK
|
#fixed code
public static void main(String[] args) throws ExecutionException, InterruptedException, IOException {
DnsSrvResolver resolver = DnsSrvResolvers.newBuilder()
.cachingLookups(true)
.retainingDataOnFailures(true)
.metered(REPORTER)
.dnsLookupTimeoutMillis(1000)
.build();
boolean quit = false;
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
while (!quit) {
System.out.print("Enter a SRV name: ");
String line = in.readLine();
if (line == null || line.isEmpty()) {
quit = true;
} else {
try {
List<HostAndPort> nodes = resolver.resolve(line);
for (HostAndPort node : nodes) {
System.out.println(node);
}
}
catch (DnsException e) {
e.printStackTrace(System.out);
}
}
}
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
public static void main(String[] args) throws IOException {
Function<LookupResult, Integer> resultTransformer = new Function<LookupResult, Integer>() {
@Nullable
@Override
public Integer apply(@Nullable LookupResult input) {
return input.weight();
}
};
DnsSrvResolver resolver = DnsSrvResolvers.newBuilder()
.cachingLookups(true)
.retainingDataOnFailures(true)
.dnsLookupTimeoutMillis(1000)
.build();
DnsSrvWatcher<LookupResult> watcher = DnsSrvResolvers.newWatcherBuilder(resolver)
.polling(1, TimeUnit.SECONDS)
.build();
boolean quit = false;
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
while (!quit) {
System.out.print("Enter a SRV name (empty to quit): ");
String line = in.readLine();
if (line == null || line.isEmpty()) {
quit = true;
} else {
try {
ChangeNotifier<LookupResult> notifier = watcher.watch(line);
notifier.setListener(new ChangeListener(line), false);
}
catch (DnsException e) {
e.printStackTrace(System.out);
}
}
}
}
#location 7
#vulnerability type RESOURCE_LEAK
|
#fixed code
public static void main(String[] args) throws IOException {
Function<LookupResult, Integer> resultTransformer = new Function<LookupResult, Integer>() {
@Nullable
@Override
public Integer apply(@Nullable LookupResult input) {
return input.weight();
}
};
DnsSrvResolver resolver = DnsSrvResolvers.newBuilder()
.cachingLookups(true)
.retainingDataOnFailures(true)
.dnsLookupTimeoutMillis(1000)
.build();
DnsSrvWatcher<LookupResult> watcher = DnsSrvResolvers.newWatcherBuilder(resolver)
.polling(1, TimeUnit.SECONDS)
.build();
boolean quit = false;
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
while (!quit) {
System.out.print("Enter a SRV name (empty to quit): ");
String line = in.readLine();
if (line == null || line.isEmpty()) {
quit = true;
} else {
try {
ChangeNotifier<LookupResult> notifier = watcher.watch(line);
notifier.setListener(new ChangeListener(line), false);
}
catch (DnsException e) {
e.printStackTrace(System.out);
}
}
}
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
private Set<T> aggregateSet() {
ImmutableSet.Builder<T> records = ImmutableSet.builder();
for (final ChangeNotifier<T> changeNotifier : changeNotifiers) {
records.addAll(changeNotifier.current());
}
return records.build();
}
#location 1
#vulnerability type CHECKERS_IMMUTABLE_CAST
|
#fixed code
private Set<T> aggregateSet() {
if (areAllInitial(changeNotifiers)) {
return ChangeNotifiers.initialEmptyDataInstance();
}
ImmutableSet.Builder<T> records = ImmutableSet.builder();
for (final ChangeNotifier<T> changeNotifier : changeNotifiers) {
records.addAll(changeNotifier.current());
}
return records.build();
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
public static void main(String[] args) throws IOException {
DnsSrvResolver resolver = DnsSrvResolvers.newBuilder()
.cachingLookups(true)
.retainingDataOnFailures(true)
.dnsLookupTimeoutMillis(1000)
.build();
PollingDnsSrvResolver<String> poller = DnsSrvResolvers.pollingResolver(resolver,
new Function<LookupResult, String>() {
@Nullable
@Override
public String apply(@Nullable LookupResult input) {
return input.toString() + System.currentTimeMillis() / 5000;
}
}
);
boolean quit = false;
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
while (!quit) {
System.out.print("Enter a SRV name (empty to quit): ");
String line = in.readLine();
if (line == null || line.isEmpty()) {
quit = true;
} else {
try {
poller.poll(line, 1, TimeUnit.SECONDS)
.setListener(new EndpointListener(line), false);
}
catch (DnsException e) {
e.printStackTrace(System.out);
}
}
}
}
#location 14
#vulnerability type RESOURCE_LEAK
|
#fixed code
public static void main(String[] args) throws IOException {
Function<LookupResult, Integer> resultTransformer = new Function<LookupResult, Integer>() {
@Nullable
@Override
public Integer apply(@Nullable LookupResult input) {
return input.weight();
}
};
DnsSrvResolver resolver = DnsSrvResolvers.newBuilder()
.cachingLookups(true)
.retainingDataOnFailures(true)
.dnsLookupTimeoutMillis(1000)
.build();
DnsSrvWatcher<LookupResult> watcher = DnsSrvResolvers.newWatcherBuilder(resolver)
.polling(1, TimeUnit.SECONDS)
.build();
boolean quit = false;
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
while (!quit) {
System.out.print("Enter a SRV name (empty to quit): ");
String line = in.readLine();
if (line == null || line.isEmpty()) {
quit = true;
} else {
try {
ChangeNotifier<LookupResult> notifier = watcher.watch(line);
notifier.setListener(new ChangeListener(line), false);
}
catch (DnsException e) {
e.printStackTrace(System.out);
}
}
}
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
@Override
public boolean putConfig(String dataId, String content, long timeoutMills) {
ConfigFuture configFuture = new ConfigFuture(dataId, content, ConfigFuture.ConfigOperation.PUT, timeoutMills);
etcdConfigExecutor.execute(() -> {
complete(getClient().getKVClient().put(ByteSequence.from(dataId, UTF_8), ByteSequence.from(content, UTF_8)), configFuture);
});
return (Boolean) configFuture.get();
}
#location 4
#vulnerability type THREAD_SAFETY_VIOLATION
|
#fixed code
@Override
public boolean putConfig(String dataId, String content, long timeoutMills) {
ConfigFuture configFuture = new ConfigFuture(dataId, content, ConfigFuture.ConfigOperation.PUT, timeoutMills);
etcdConfigExecutor.execute(() -> complete(getClient().getKVClient().put(ByteSequence.from(dataId, UTF_8), ByteSequence.from(content, UTF_8)), configFuture));
return (Boolean) configFuture.get();
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
@Override
public BranchStatus branchRollback(BranchType branchType, String xid, long branchId, String resourceId, String applicationData) throws TransactionException {
TCCResource tccResource = (TCCResource) tccResourceCache.get(resourceId);
if (tccResource == null) {
throw new ShouldNeverHappenException("TCC resource is not exist, resourceId:" + resourceId);
}
Object targetTCCBean = tccResource.getTargetBean();
Method rollbackMethod = tccResource.getRollbackMethod();
if (targetTCCBean == null || rollbackMethod == null) {
throw new ShouldNeverHappenException("TCC resource is not available, resourceId:" + resourceId);
}
try {
boolean result = false;
//BusinessActionContext
BusinessActionContext businessActionContext = getBusinessActionContext(xid, branchId, resourceId, applicationData);
Object ret = rollbackMethod.invoke(targetTCCBean, businessActionContext);
LOGGER.info("TCC resource rollback result :" + ret + ", xid:" + xid + ", branchId:" + branchId + ", resourceId:" + resourceId);
if (ret != null && ret instanceof TwoPhaseResult) {
result = ((TwoPhaseResult) ret).isSuccess();
} else {
result = (boolean) ret;
}
return result ? BranchStatus.PhaseTwo_Rollbacked : BranchStatus.PhaseTwo_RollbackFailed_Retryable;
} catch (Throwable t) {
String msg = String.format("rollback TCC resource error, resourceId: %s, xid: %s.", resourceId, xid);
LOGGER.error(msg, t);
throw new FrameworkException(t, msg);
}
}
#location 21
#vulnerability type NULL_DEREFERENCE
|
#fixed code
@Override
public BranchStatus branchRollback(BranchType branchType, String xid, long branchId, String resourceId, String applicationData) throws TransactionException {
TCCResource tccResource = (TCCResource) tccResourceCache.get(resourceId);
if (tccResource == null) {
throw new ShouldNeverHappenException("TCC resource is not exist, resourceId:" + resourceId);
}
Object targetTCCBean = tccResource.getTargetBean();
Method rollbackMethod = tccResource.getRollbackMethod();
if (targetTCCBean == null || rollbackMethod == null) {
throw new ShouldNeverHappenException("TCC resource is not available, resourceId:" + resourceId);
}
try {
boolean result = false;
//BusinessActionContext
BusinessActionContext businessActionContext = getBusinessActionContext(xid, branchId, resourceId, applicationData);
Object ret = rollbackMethod.invoke(targetTCCBean, businessActionContext);
LOGGER.info("TCC resource rollback result :" + ret + ", xid:" + xid + ", branchId:" + branchId + ", resourceId:" + resourceId);
if (ret != null) {
if (ret instanceof TwoPhaseResult) {
result = ((TwoPhaseResult) ret).isSuccess();
} else {
result = (boolean) ret;
}
}
return result ? BranchStatus.PhaseTwo_Rollbacked : BranchStatus.PhaseTwo_RollbackFailed_Retryable;
} catch (Throwable t) {
String msg = String.format("rollback TCC resource error, resourceId: %s, xid: %s.", resourceId, xid);
LOGGER.error(msg, t);
throw new FrameworkException(t, msg);
}
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
public static RegistryService getInstance() {
ConfigType configType = null;
try {
configType = ConfigType.getType(
ConfigurationFactory.FILE_INSTANCE.getConfig(
ConfigurationKeys.FILE_ROOT_REGISTRY + ConfigurationKeys.FILE_CONFIG_SPLIT_CHAR
+ ConfigurationKeys.FILE_ROOT_TYPE));
} catch (Exception exx) {
LOGGER.error(exx.getMessage());
}
RegistryService registryService;
switch (configType) {
case Nacos:
registryService = NacosRegistryServiceImpl.getInstance();
break;
case File:
registryService = FileRegistryServiceImpl.getInstance();
break;
default:
throw new NotSupportYetException("not support register type:" + configType);
}
return registryService;
}
#location 12
#vulnerability type NULL_DEREFERENCE
|
#fixed code
public static RegistryService getInstance() {
RegistryType registryType = null;
try {
registryType = RegistryType.getType(
ConfigurationFactory.FILE_INSTANCE.getConfig(
ConfigurationKeys.FILE_ROOT_REGISTRY + ConfigurationKeys.FILE_CONFIG_SPLIT_CHAR
+ ConfigurationKeys.FILE_ROOT_TYPE));
} catch (Exception exx) {
LOGGER.error(exx.getMessage());
}
RegistryService registryService;
switch (registryType) {
case Nacos:
registryService = NacosRegistryServiceImpl.getInstance();
break;
case File:
registryService = FileRegistryServiceImpl.getInstance();
break;
default:
throw new NotSupportYetException("not support register type:" + registryType);
}
return registryService;
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
@Override
public boolean removeConfig(String dataId, long timeoutMills) {
ConfigFuture configFuture = new ConfigFuture(dataId, null, ConfigOperation.REMOVE, timeoutMills);
configOperateExecutor.submit(new ConfigOperateRunnable(configFuture));
return (Boolean)configFuture.get(timeoutMills, TimeUnit.MILLISECONDS);
}
#location 5
#vulnerability type NULL_DEREFERENCE
|
#fixed code
@Override
public boolean removeConfig(String dataId, long timeoutMills) {
ConfigFuture configFuture = new ConfigFuture(dataId, null, ConfigOperation.REMOVE, timeoutMills);
configOperateExecutor.submit(new ConfigOperateRunnable(configFuture));
return (Boolean)configFuture.get();
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
public static <T, S extends Statement> T execute(SQLRecognizer sqlRecognizer,
StatementProxy<S> statementProxy,
StatementCallback<T, S> statementCallback,
Object... args) throws SQLException {
if (!RootContext.inGlobalTransaction()) {
// Just work as original statement
return statementCallback.execute(statementProxy.getTargetStatement(), args);
}
if (sqlRecognizer == null) {
sqlRecognizer = SQLVisitorFactory.get(
statementProxy.getTargetSQL(),
statementProxy.getConnectionProxy().getDbType());
}
Executor<T> executor = null;
switch (sqlRecognizer.getSQLType()) {
case INSERT:
executor = new InsertExecutor<T, S>(statementProxy, statementCallback, sqlRecognizer);
break;
case UPDATE:
executor = new UpdateExecutor<T, S>(statementProxy, statementCallback, sqlRecognizer);
break;
case DELETE:
executor = new DeleteExecutor<T, S>(statementProxy, statementCallback, sqlRecognizer);
break;
case SELECT_FOR_UPDATE:
executor = new SelectForUpdateExecutor(statementProxy, statementCallback, sqlRecognizer);
break;
default:
executor = new PlainExecutor<T, S>(statementProxy, statementCallback, sqlRecognizer);
break;
}
T rs = null;
try {
rs = executor.execute(args);
} catch (Throwable ex) {
if (ex instanceof SQLException) {
throw (SQLException) ex;
} else {
// Turn everything into SQLException
new SQLException(ex);
}
}
return rs;
}
#location 17
#vulnerability type NULL_DEREFERENCE
|
#fixed code
public static <T, S extends Statement> T execute(SQLRecognizer sqlRecognizer,
StatementProxy<S> statementProxy,
StatementCallback<T, S> statementCallback,
Object... args) throws SQLException {
if (!RootContext.inGlobalTransaction()) {
// Just work as original statement
return statementCallback.execute(statementProxy.getTargetStatement(), args);
}
if (sqlRecognizer == null) {
sqlRecognizer = SQLVisitorFactory.get(
statementProxy.getTargetSQL(),
statementProxy.getConnectionProxy().getDbType());
}
Executor<T> executor = null;
if (sqlRecognizer == null) {
executor = new PlainExecutor<T, S>(statementProxy, statementCallback);
} else {
switch (sqlRecognizer.getSQLType()) {
case INSERT:
executor = new InsertExecutor<T, S>(statementProxy, statementCallback, sqlRecognizer);
break;
case UPDATE:
executor = new UpdateExecutor<T, S>(statementProxy, statementCallback, sqlRecognizer);
break;
case DELETE:
executor = new DeleteExecutor<T, S>(statementProxy, statementCallback, sqlRecognizer);
break;
case SELECT_FOR_UPDATE:
executor = new SelectForUpdateExecutor(statementProxy, statementCallback, sqlRecognizer);
break;
default:
executor = new PlainExecutor<T, S>(statementProxy, statementCallback);
break;
}
}
T rs = null;
try {
rs = executor.execute(args);
} catch (Throwable ex) {
if (ex instanceof SQLException) {
throw (SQLException) ex;
} else {
// Turn everything into SQLException
new SQLException(ex);
}
}
return rs;
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
@Override
public BranchStatus branchCommit(BranchType branchType, String xid, long branchId, String resourceId, String applicationData) throws TransactionException {
TCCResource tccResource = (TCCResource) tccResourceCache.get(resourceId);
if(tccResource == null){
throw new ShouldNeverHappenException("TCC resource is not exist, resourceId:" + resourceId);
}
Object targetTCCBean = tccResource.getTargetBean();
Method commitMethod = tccResource.getCommitMethod();
if(targetTCCBean == null || commitMethod == null){
throw new ShouldNeverHappenException("TCC resource is not available, resourceId:" + resourceId);
}
try {
boolean result = false;
//BusinessActionContext
BusinessActionContext businessActionContext = getBusinessActionContext(xid, branchId, resourceId, applicationData);
Object ret = commitMethod.invoke(targetTCCBean, businessActionContext);
LOGGER.info("TCC resource commit result :" + ret + ", xid:" + xid + ", branchId:" + branchId + ", resourceId:" + resourceId);
if(ret != null && ret instanceof TwoPhaseResult){
result = ((TwoPhaseResult)ret).isSuccess();
}else {
result = (boolean) ret;
}
return result ? BranchStatus.PhaseTwo_Committed:BranchStatus.PhaseTwo_CommitFailed_Retryable;
}catch (Throwable t){
String msg = String.format("commit TCC resource error, resourceId: %s, xid: %s.", resourceId, xid);
LOGGER.error(msg , t);
throw new FrameworkException(t, msg);
}
}
#location 21
#vulnerability type NULL_DEREFERENCE
|
#fixed code
@Override
public BranchStatus branchCommit(BranchType branchType, String xid, long branchId, String resourceId, String applicationData) throws TransactionException {
TCCResource tccResource = (TCCResource) tccResourceCache.get(resourceId);
if(tccResource == null){
throw new ShouldNeverHappenException("TCC resource is not exist, resourceId:" + resourceId);
}
Object targetTCCBean = tccResource.getTargetBean();
Method commitMethod = tccResource.getCommitMethod();
if(targetTCCBean == null || commitMethod == null){
throw new ShouldNeverHappenException("TCC resource is not available, resourceId:" + resourceId);
}
try {
boolean result = false;
//BusinessActionContext
BusinessActionContext businessActionContext = getBusinessActionContext(xid, branchId, resourceId, applicationData);
Object ret = commitMethod.invoke(targetTCCBean, businessActionContext);
LOGGER.info("TCC resource commit result :" + ret + ", xid:" + xid + ", branchId:" + branchId + ", resourceId:" + resourceId);
if (ret != null) {
if (ret instanceof TwoPhaseResult) {
result = ((TwoPhaseResult) ret).isSuccess();
} else {
result = (boolean) ret;
}
}
return result ? BranchStatus.PhaseTwo_Committed:BranchStatus.PhaseTwo_CommitFailed_Retryable;
}catch (Throwable t){
String msg = String.format("commit TCC resource error, resourceId: %s, xid: %s.", resourceId, xid);
LOGGER.error(msg , t);
throw new FrameworkException(t, msg);
}
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
public static long generateUUID() {
long id = UUID.incrementAndGet();
if (id >= UUID_INTERNAL * (serverNodeId + 1)) {
synchronized (UUID) {
if (UUID.get() >= id) {
id -= UUID_INTERNAL;
UUID.set(id);
}
}
}
return id;
}
#location 3
#vulnerability type THREAD_SAFETY_VIOLATION
|
#fixed code
public static long generateUUID() {
long id = UUID.incrementAndGet();
if (id >= getMaxUUID()) {
synchronized (UUID) {
if (UUID.get() >= id) {
id -= UUID_INTERNAL;
UUID.set(id);
}
}
}
return id;
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
@Override
public Object invoke(ServiceTaskState serviceTaskState, Object... input) {
ServiceTaskStateImpl state = (ServiceTaskStateImpl) serviceTaskState;
Object bean = applicationContext.getBean(state.getServiceName());
Method method = state.getMethod();
if (method == null) {
synchronized (state) {
method = state.getMethod();
if (method == null) {
method = findMethod(bean.getClass(), state.getServiceMethod(), state.getParameterTypes());
if (method != null) {
state.setMethod(method);
}
}
}
}
if (method == null) {
throw new EngineExecutionException("No such method[" + state.getServiceMethod() + "] on BeanClass[" + bean.getClass() + "]", FrameworkErrorCode.NoSuchMethod);
}
Object[] args = new Object[method.getParameterCount()];
try {
Class[] paramTypes = method.getParameterTypes();
if (input != null && input.length > 0) {
int len = input.length < paramTypes.length ? input.length : paramTypes.length;
for (int i = 0; i < len; i++) {
args[i] = toJavaObject(input[i], paramTypes[i]);
}
}
} catch (Exception e) {
throw new EngineExecutionException(e, "Input to java object error, Method[" + state.getServiceMethod() + "] on BeanClass[" + bean.getClass() + "]", FrameworkErrorCode.InvalidParameter);
}
return invokeMethod(bean, method, args);
}
#location 8
#vulnerability type THREAD_SAFETY_VIOLATION
|
#fixed code
@Override
public Object invoke(ServiceTaskState serviceTaskState, Object... input) {
ServiceTaskStateImpl state = (ServiceTaskStateImpl) serviceTaskState;
if(state.isAsync()){
if(threadPoolExecutor == null){
if(LOGGER.isWarnEnabled()){
LOGGER.warn("threadPoolExecutor is null, Service[{}.{}] cannot execute asynchronously, executing synchronously now. stateName: {}", state.getServiceName(), state.getServiceMethod(), state.getName());
}
return doInvoke(state, input);
}
if(LOGGER.isInfoEnabled()){
LOGGER.info("Submit Service[{}.{}] to asynchronously executing. stateName: {}", state.getServiceName(), state.getServiceMethod(), state.getName());
}
threadPoolExecutor.execute(new Runnable() {
@Override
public void run() {
doInvoke(state, input);
}
});
return null;
}
else{
return doInvoke(state, input);
}
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
@Override
public DataSource generateDataSource() {
DruidDataSource ds = new DruidDataSource();
ds.setDriverClassName(getDriverClassName());
ds.setUrl(getUrl());
ds.setUsername(getUser());
ds.setPassword(getPassword());
ds.setInitialSize(getMinConn());
ds.setMaxActive(getMaxConn());
ds.setMinIdle(getMinConn());
ds.setMaxWait(5000);
ds.setTimeBetweenEvictionRunsMillis(120000);
ds.setMinEvictableIdleTimeMillis(300000);
ds.setTestWhileIdle(true);
ds.setTestOnBorrow(true);
ds.setPoolPreparedStatements(true);
ds.setMaxPoolPreparedStatementPerConnectionSize(20);
ds.setValidationQuery(getValidationQuery(getDBType()));
ds.setDefaultAutoCommit(true);
return ds;
}
#location 20
#vulnerability type RESOURCE_LEAK
|
#fixed code
@Override
public DataSource generateDataSource() {
DruidDataSource ds = new DruidDataSource();
ds.setDriverClassName(getDriverClassName());
ds.setDriverClassLoader(getDriverClassLoader());
ds.setUrl(getUrl());
ds.setUsername(getUser());
ds.setPassword(getPassword());
ds.setInitialSize(getMinConn());
ds.setMaxActive(getMaxConn());
ds.setMinIdle(getMinConn());
ds.setMaxWait(5000);
ds.setTimeBetweenEvictionRunsMillis(120000);
ds.setMinEvictableIdleTimeMillis(300000);
ds.setTestWhileIdle(true);
ds.setTestOnBorrow(true);
ds.setPoolPreparedStatements(true);
ds.setMaxPoolPreparedStatementPerConnectionSize(20);
ds.setValidationQuery(getValidationQuery(getDBType()));
ds.setDefaultAutoCommit(true);
return ds;
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
public static Configuration getInstance() {
ConfigType configType = null;
try {
configType = ConfigType.getType(
FILE_INSTANCE.getConfig(ConfigurationKeys.FILE_ROOT_CONFIG + ConfigurationKeys.FILE_CONFIG_SPLIT_CHAR
+ ConfigurationKeys.FILE_ROOT_TYPE));
} catch (Exception exx) {
LOGGER.error(exx.getMessage());
}
Configuration configuration;
switch (configType) {
case Nacos:
try {
configuration = new NacosConfiguration();
} catch (NacosException e) {
throw new RuntimeException(e);
}
break;
case Apollo:
try {
configuration = ApolloConfiguration.getInstance();
} catch (ApolloConfigException e) {
throw new RuntimeException(e);
}
break;
case File:
String pathDataId = ConfigurationKeys.FILE_ROOT_CONFIG + ConfigurationKeys.FILE_CONFIG_SPLIT_CHAR
+ FILE_TYPE + ConfigurationKeys.FILE_CONFIG_SPLIT_CHAR
+ NAME_KEY;
String name = FILE_INSTANCE.getConfig(pathDataId);
configuration = new FileConfiguration(name);
break;
default:
throw new NotSupportYetException("not support register type:" + configType);
}
return configuration;
}
#location 11
#vulnerability type NULL_DEREFERENCE
|
#fixed code
public static Configuration getInstance() {
ConfigType configType = null;
String configTypeName = null;
try {
configTypeName = FILE_INSTANCE.getConfig(ConfigurationKeys.FILE_ROOT_CONFIG + ConfigurationKeys.FILE_CONFIG_SPLIT_CHAR
+ ConfigurationKeys.FILE_ROOT_TYPE);
configType = ConfigType.getType(configTypeName);
} catch (Exception exx) {
throw new NotSupportYetException("not support register type: " + configTypeName);
}
Configuration configuration;
switch (configType) {
case Nacos:
try {
configuration = new NacosConfiguration();
} catch (NacosException e) {
throw new RuntimeException(e);
}
break;
case Apollo:
try {
configuration = ApolloConfiguration.getInstance();
} catch (ApolloConfigException e) {
throw new RuntimeException(e);
}
break;
case File:
String pathDataId = ConfigurationKeys.FILE_ROOT_CONFIG + ConfigurationKeys.FILE_CONFIG_SPLIT_CHAR
+ FILE_TYPE + ConfigurationKeys.FILE_CONFIG_SPLIT_CHAR
+ NAME_KEY;
String name = FILE_INSTANCE.getConfig(pathDataId);
configuration = new FileConfiguration(name);
break;
default:
throw new NotSupportYetException("not support register type:" + configType);
}
return configuration;
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
@Test
public void testRestoredFromFileRollbackRetry() throws Exception {
SessionHolder.init(".");
GlobalSession globalSession = new GlobalSession("demo-app", "my_test_tx_group", "test", 6000);
globalSession.addSessionLifecycleListener(SessionHolder.getRootSessionManager());
globalSession.begin();
BranchSession branchSession1 = SessionHelper.newBranchByGlobal(globalSession, BranchType.AT, RESOURCE_ID,
"ta:1", "xxx");
branchSession1.lock();
globalSession.addBranch(branchSession1);
LockManager lockManager = LockManagerFactory.get();
Assert.assertFalse(lockManager.isLockable(0L, RESOURCE_ID, "ta:1"));
globalSession.changeStatus(GlobalStatus.Rollbacking);
globalSession.changeBranchStatus(branchSession1, BranchStatus.PhaseTwo_RollbackFailed_Retryable);
globalSession.changeStatus(GlobalStatus.RollbackRetrying);
lockManager.cleanAllLocks();
Assert.assertTrue(lockManager.isLockable(0L, RESOURCE_ID, "ta:1"));
// Re-init SessionHolder: restore sessions from file
SessionHolder.init(".");
long tid = globalSession.getTransactionId();
GlobalSession reloadSession = SessionHolder.findGlobalSession(tid);
Assert.assertEquals(reloadSession.getStatus(), GlobalStatus.RollbackRetrying);
GlobalSession sessionInRetryRollbackingQueue = SessionHolder.getRetryRollbackingSessionManager()
.findGlobalSession(tid);
Assert.assertTrue(reloadSession == sessionInRetryRollbackingQueue);
BranchSession reloadBranchSession = reloadSession.getBranch(branchSession1.getBranchId());
Assert.assertEquals(reloadBranchSession.getStatus(), BranchStatus.PhaseTwo_RollbackFailed_Retryable);
// Lock is held by session in RollbackRetrying status
Assert.assertFalse(lockManager.isLockable(0L, RESOURCE_ID, "ta:1"));
}
#location 3
#vulnerability type RESOURCE_LEAK
|
#fixed code
@Test
public void testRestoredFromFileRollbackRetry() throws Exception {
SessionHolder.init("file");
GlobalSession globalSession = new GlobalSession("demo-app", "my_test_tx_group", "test", 6000);
globalSession.addSessionLifecycleListener(SessionHolder.getRootSessionManager());
globalSession.begin();
BranchSession branchSession1 = SessionHelper.newBranchByGlobal(globalSession, BranchType.AT, RESOURCE_ID,
"ta:1", "xxx");
branchSession1.lock();
globalSession.addBranch(branchSession1);
LockManager lockManager = LockManagerFactory.get();
Assert.assertFalse(lockManager.isLockable(0L, RESOURCE_ID, "ta:1"));
globalSession.changeStatus(GlobalStatus.Rollbacking);
globalSession.changeBranchStatus(branchSession1, BranchStatus.PhaseTwo_RollbackFailed_Retryable);
globalSession.changeStatus(GlobalStatus.RollbackRetrying);
lockManager.cleanAllLocks();
Assert.assertTrue(lockManager.isLockable(0L, RESOURCE_ID, "ta:1"));
// Re-init SessionHolder: restore sessions from file
SessionHolder.init("file");
long tid = globalSession.getTransactionId();
GlobalSession reloadSession = SessionHolder.findGlobalSession(tid);
Assert.assertEquals(reloadSession.getStatus(), GlobalStatus.RollbackRetrying);
GlobalSession sessionInRetryRollbackingQueue = SessionHolder.getRetryRollbackingSessionManager()
.findGlobalSession(tid);
Assert.assertTrue(reloadSession == sessionInRetryRollbackingQueue);
BranchSession reloadBranchSession = reloadSession.getBranch(branchSession1.getBranchId());
Assert.assertEquals(reloadBranchSession.getStatus(), BranchStatus.PhaseTwo_RollbackFailed_Retryable);
// Lock is held by session in RollbackRetrying status
Assert.assertFalse(lockManager.isLockable(0L, RESOURCE_ID, "ta:1"));
//clear
reloadSession.addSessionLifecycleListener(SessionHolder.getRootSessionManager());
reloadSession.end();
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
@Override
public void addConfigListener(String dataId, ConfigChangeListener listener) {
configListenersMap.putIfAbsent(dataId, new ArrayList<>());
configChangeNotifiersMap.putIfAbsent(dataId, new ArrayList<>());
ConfigChangeNotifier configChangeNotifier = new ConfigChangeNotifier(dataId, listener);
configChangeNotifiersMap.get(dataId).add(configChangeNotifier);
if (null != listener.getExecutor()) {
listener.getExecutor().submit(configChangeNotifier);
} else {
consulConfigExecutor.submit(configChangeNotifier);
}
}
#location 3
#vulnerability type THREAD_SAFETY_VIOLATION
|
#fixed code
@Override
public void addConfigListener(String dataId, ConfigChangeListener listener) {
configListenersMap.putIfAbsent(dataId, new ArrayList<>());
configChangeNotifiersMap.putIfAbsent(dataId, new ArrayList<>());
ConfigChangeNotifier configChangeNotifier = new ConfigChangeNotifier(dataId, listener);
configChangeNotifiersMap.get(dataId).add(configChangeNotifier);
if (null != listener.getExecutor()) {
listener.getExecutor().submit(configChangeNotifier);
} else {
consulNotifierExecutor.submit(configChangeNotifier);
}
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
@Test
public void testBigDataWrite() throws Exception {
File seataFile = Files.newTemporaryFile();
try {
FileTransactionStoreManager fileTransactionStoreManager = new FileTransactionStoreManager(seataFile.getAbsolutePath(), null);
BranchSession branchSessionA = Mockito.mock(BranchSession.class);
GlobalSession global = new GlobalSession();
Mockito.when(branchSessionA.encode())
.thenReturn(createBigBranchSessionData(global, (byte) 'A'));
Mockito.when(branchSessionA.getApplicationData())
.thenReturn(new String(createBigApplicationData((byte) 'A')));
BranchSession branchSessionB = Mockito.mock(BranchSession.class);
Mockito.when(branchSessionB.encode())
.thenReturn(createBigBranchSessionData(global, (byte) 'B'));
Mockito.when(branchSessionB.getApplicationData())
.thenReturn(new String(createBigApplicationData((byte) 'B')));
Assertions.assertTrue(fileTransactionStoreManager.writeSession(TransactionStoreManager.LogOperation.BRANCH_ADD, branchSessionA));
Assertions.assertTrue(fileTransactionStoreManager.writeSession(TransactionStoreManager.LogOperation.BRANCH_ADD, branchSessionB));
List<TransactionWriteStore> list = fileTransactionStoreManager.readWriteStore(2000, false);
Assertions.assertNotNull(list);
Assertions.assertEquals(2, list.size());
BranchSession loadedBranchSessionA = (BranchSession) list.get(0).getSessionRequest();
Assertions.assertEquals(branchSessionA.getApplicationData(), loadedBranchSessionA.getApplicationData());
BranchSession loadedBranchSessionB = (BranchSession) list.get(1).getSessionRequest();
Assertions.assertEquals(branchSessionB.getApplicationData(), loadedBranchSessionB.getApplicationData());
} finally {
Assertions.assertTrue(seataFile.delete());
}
}
#location 19
#vulnerability type RESOURCE_LEAK
|
#fixed code
@Test
public void testBigDataWrite() throws Exception {
File seataFile = Files.newTemporaryFile();
FileTransactionStoreManager fileTransactionStoreManager = null;
try {
fileTransactionStoreManager = new FileTransactionStoreManager(seataFile.getAbsolutePath(), null);
BranchSession branchSessionA = Mockito.mock(BranchSession.class);
GlobalSession global = new GlobalSession();
Mockito.when(branchSessionA.encode())
.thenReturn(createBigBranchSessionData(global, (byte) 'A'));
Mockito.when(branchSessionA.getApplicationData())
.thenReturn(new String(createBigApplicationData((byte) 'A')));
BranchSession branchSessionB = Mockito.mock(BranchSession.class);
Mockito.when(branchSessionB.encode())
.thenReturn(createBigBranchSessionData(global, (byte) 'B'));
Mockito.when(branchSessionB.getApplicationData())
.thenReturn(new String(createBigApplicationData((byte) 'B')));
Assertions.assertTrue(fileTransactionStoreManager.writeSession(TransactionStoreManager.LogOperation.BRANCH_ADD, branchSessionA));
Assertions.assertTrue(fileTransactionStoreManager.writeSession(TransactionStoreManager.LogOperation.BRANCH_ADD, branchSessionB));
List<TransactionWriteStore> list = fileTransactionStoreManager.readWriteStore(2000, false);
Assertions.assertNotNull(list);
Assertions.assertEquals(2, list.size());
BranchSession loadedBranchSessionA = (BranchSession) list.get(0).getSessionRequest();
Assertions.assertEquals(branchSessionA.getApplicationData(), loadedBranchSessionA.getApplicationData());
BranchSession loadedBranchSessionB = (BranchSession) list.get(1).getSessionRequest();
Assertions.assertEquals(branchSessionB.getApplicationData(), loadedBranchSessionB.getApplicationData());
} finally {
if (null != fileTransactionStoreManager) {
fileTransactionStoreManager.shutdown();
}
Assertions.assertTrue(seataFile.delete());
}
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
@Override
public void encode(ChannelHandlerContext ctx, Object msg, ByteBuf out) {
try {
if (msg instanceof RpcMessage) {
RpcMessage rpcMessage = (RpcMessage) msg;
int fullLength = 13;
int headLength = 0;
// count head
byte[] headBytes = null;
Map<String, String> headMap = rpcMessage.getHeadMap();
if (headMap != null && !headMap.isEmpty()) {
headBytes = HeadMapSerializer.getInstance().encode(headMap);
headLength = headBytes.length;
fullLength += headLength;
}
byte[] bodyBytes = null;
byte messageType = rpcMessage.getMessageType();
if (messageType != ProtocolConstants.MSGTYPE_HEARTBEAT_REQUEST
&& messageType != ProtocolConstants.MSGTYPE_HEARTBEAT_RESPONSE) {
// heartbeat has no body
Codec codec = CodecFactory.getCodec(rpcMessage.getCodec());
bodyBytes = codec.encode(rpcMessage.getBody());
fullLength += bodyBytes.length;
}
out.writeBytes(ProtocolConstants.MAGIC_CODE_BYTES);
out.writeByte(ProtocolConstants.VERSION);
out.writeInt(fullLength);
out.writeShort(headLength);
out.writeByte(messageType);
out.writeByte(rpcMessage.getCodec());
out.writeByte(rpcMessage.getCompressor());
out.writeInt(rpcMessage.getId());
if (headBytes != null) {
out.writeBytes(headBytes);
}
if (bodyBytes != null) {
out.writeBytes(bodyBytes);
}
} else {
throw new UnsupportedOperationException("Not support this class:" + msg.getClass());
}
} catch (Throwable e) {
LOGGER.error("Encode request error!", e);
}
}
#location 15
#vulnerability type NULL_DEREFERENCE
|
#fixed code
@Override
public void encode(ChannelHandlerContext ctx, Object msg, ByteBuf out) {
try {
if (msg instanceof RpcMessage) {
RpcMessage rpcMessage = (RpcMessage) msg;
int fullLength = ProtocolConstants.V1_HEAD_LENGTH;
int headLength = ProtocolConstants.V1_HEAD_LENGTH;
byte messageType = rpcMessage.getMessageType();
out.writeBytes(ProtocolConstants.MAGIC_CODE_BYTES);
out.writeByte(ProtocolConstants.VERSION);
// full Length(4B) and head length(2B) will fix in the end.
out.writerIndex(out.writerIndex() + 6);
out.writeByte(messageType);
out.writeByte(rpcMessage.getCodec());
out.writeByte(rpcMessage.getCompressor());
out.writeInt(rpcMessage.getId());
// direct write head with zero-copy
Map<String, String> headMap = rpcMessage.getHeadMap();
if (headMap != null && !headMap.isEmpty()) {
int headMapBytesLength = HeadMapSerializer.getInstance().encode(headMap, out);
headLength += headMapBytesLength;
fullLength += headMapBytesLength;
}
byte[] bodyBytes = null;
if (messageType != ProtocolConstants.MSGTYPE_HEARTBEAT_REQUEST
&& messageType != ProtocolConstants.MSGTYPE_HEARTBEAT_RESPONSE) {
// heartbeat has no body
Codec codec = CodecFactory.getCodec(rpcMessage.getCodec());
bodyBytes = codec.encode(rpcMessage.getBody());
fullLength += bodyBytes.length;
}
if (bodyBytes != null) {
out.writeBytes(bodyBytes);
}
// fix fullLength and headLength
int writeIndex = out.writerIndex();
// skip magic code(2B) + version(1B)
out.writerIndex(writeIndex - fullLength + 3);
out.writeInt(fullLength);
out.writeShort(headLength);
out.writerIndex(writeIndex);
} else {
throw new UnsupportedOperationException("Not support this class:" + msg.getClass());
}
} catch (Throwable e) {
LOGGER.error("Encode request error!", e);
}
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
public static long generateUUID() {
long id = UUID.incrementAndGet();
if (id >= getMaxUUID()) {
synchronized (UUID) {
if (UUID.get() >= id) {
id -= UUID_INTERNAL;
UUID.set(id);
}
}
}
return id;
}
#location 3
#vulnerability type THREAD_SAFETY_VIOLATION
|
#fixed code
public static long generateUUID() {
return IdWorker.getInstance().nextId();
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
public static void main(String[] args) throws InterruptedException, TimeoutException, ExecutionException {
ProtocolV1Client client = new ProtocolV1Client();
client.connect("127.0.0.1", 8811, 500);
Map<String, String> head = new HashMap<>();
head.put("tracerId", "xxadadadada");
head.put("token", "adadadad");
BranchCommitRequest body = new BranchCommitRequest();
body.setBranchId(12345L);
body.setApplicationData("application");
body.setBranchType(BranchType.AT);
body.setResourceId("resource-1234");
body.setXid("xid-1234");
RpcMessage rpcMessage = new RpcMessage();
rpcMessage.setId(client.idGenerator.incrementAndGet());
rpcMessage.setCodec(CodecType.SEATA.getCode());
rpcMessage.setCompressor(ProtocolConstants.CONFIGURED_COMPRESSOR);
rpcMessage.setHeadMap(head);
rpcMessage.setBody(body);
rpcMessage.setMessageType(ProtocolConstants.MSGTYPE_RESQUEST);
Future future = client.send(rpcMessage.getId(), rpcMessage);
RpcMessage resp = (RpcMessage) future.get(200, TimeUnit.SECONDS);
System.out.println(resp.getId() + " " + resp.getBody());
}
#location 25
#vulnerability type NULL_DEREFERENCE
|
#fixed code
public static void main(String[] args) {
ProtocolV1Client client = new ProtocolV1Client();
client.connect("127.0.0.1", 8811, 500);
Map<String, String> head = new HashMap<>();
head.put("tracerId", "xxadadadada");
head.put("token", "adadadad");
BranchCommitRequest body = new BranchCommitRequest();
body.setBranchId(12345L);
body.setApplicationData("application");
body.setBranchType(BranchType.AT);
body.setResourceId("resource-1234");
body.setXid("xid-1234");
final int threads = 50;
final AtomicLong cnt = new AtomicLong(0);
final ThreadPoolExecutor service1 = new ThreadPoolExecutor(threads, threads, 0L, TimeUnit.MILLISECONDS,
new SynchronousQueue<Runnable>(), new NamedThreadFactory("client-", false));// 无队列
for (int i = 0; i < threads; i++) {
service1.execute(() -> {
while (true) {
try {
Future future = client.sendRpc(head, body);
RpcMessage resp = (RpcMessage) future.get(200, TimeUnit.MILLISECONDS);
if (resp != null) {
cnt.incrementAndGet();
}
} catch (Exception e) {
// ignore
}
}
});
}
Thread thread = new Thread(new Runnable() {
private long last = 0;
@Override
public void run() {
while (true) {
long count = cnt.get();
long tps = count - last;
LOGGER.error("last 1s invoke: {}, queue: {}", tps, service1.getQueue().size());
last = count;
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
}
}
}
}, "Print-tps-THREAD");
thread.start();
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
@Override
public void subscribe(String cluster, Watch.Listener listener) throws Exception {
listenerMap.putIfAbsent(cluster, new HashSet<>());
listenerMap.get(cluster).add(listener);
EtcdWatcher watcher = watcherMap.computeIfAbsent(cluster, w -> new EtcdWatcher(listener));
EXECUTOR_SERVICE.submit(watcher);
}
#location 4
#vulnerability type THREAD_SAFETY_VIOLATION
|
#fixed code
@Override
public void subscribe(String cluster, Watch.Listener listener) throws Exception {
listenerMap.putIfAbsent(cluster, new HashSet<>());
listenerMap.get(cluster).add(listener);
EtcdWatcher watcher = watcherMap.computeIfAbsent(cluster, w -> new EtcdWatcher(listener));
executorService.submit(watcher);
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
@Override
public boolean putConfigIfAbsent(String dataId, String content, long timeoutMills) {
ConfigFuture configFuture = new ConfigFuture(dataId, content, ConfigFuture.ConfigOperation.PUTIFABSENT, timeoutMills);
consulConfigExecutor.execute(() -> {
PutParams putParams = new PutParams();
//Setting CAS to 0 means that this is an atomic operation, created when key does not exist.
putParams.setCas(CAS);
complete(getConsulClient().setKVValue(dataId, content, putParams), configFuture);
});
return (Boolean) configFuture.get();
}
#location 4
#vulnerability type THREAD_SAFETY_VIOLATION
|
#fixed code
@Override
public boolean putConfigIfAbsent(String dataId, String content, long timeoutMills) {
ConfigFuture configFuture = new ConfigFuture(dataId, content, ConfigFuture.ConfigOperation.PUTIFABSENT, timeoutMills);
consulNotifierExecutor.execute(() -> {
PutParams putParams = new PutParams();
//Setting CAS to 0 means that this is an atomic operation, created when key does not exist.
putParams.setCas(CAS);
complete(getConsulClient().setKVValue(dataId, content, putParams), configFuture);
});
return (Boolean) configFuture.get();
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
public void testRestoredFromFile2() throws Exception {
SessionHolder.init(".");
GlobalSession globalSession = new GlobalSession("demo-app", "my_test_tx_group", "test", 6000);
globalSession.addSessionLifecycleListener(SessionHolder.getRootSessionManager());
globalSession.begin();
// Re-init SessionHolder: restore sessions from file
SessionHolder.init(".");
}
#location 2
#vulnerability type RESOURCE_LEAK
|
#fixed code
public void testRestoredFromFile2() throws Exception {
SessionHolder.init("file");
GlobalSession globalSession = new GlobalSession("demo-app", "my_test_tx_group", "test", 6000);
globalSession.addSessionLifecycleListener(SessionHolder.getRootSessionManager());
globalSession.begin();
// Re-init SessionHolder: restore sessions from file
SessionHolder.init("file");
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
private static TableMeta resultSetMetaToSchema(ResultSetMetaData rsmd, DatabaseMetaData dbmd, String tableName)
throws SQLException {
String schemaName = rsmd.getSchemaName(1);
String catalogName = rsmd.getCatalogName(1);
TableMeta tm = new TableMeta();
tm.setTableName(tableName);
ResultSet rs1 = dbmd.getColumns(catalogName, schemaName, tableName, "%");
while (rs1.next()) {
ColumnMeta col = new ColumnMeta();
col.setTableCat(rs1.getString("TABLE_CAT"));
col.setTableSchemaName(rs1.getString("TABLE_SCHEM"));
col.setTableName(rs1.getString("TABLE_NAME"));
col.setColumnName(rs1.getString("COLUMN_NAME"));
col.setDataType(rs1.getInt("DATA_TYPE"));
col.setDataTypeName(rs1.getString("TYPE_NAME"));
col.setColumnSize(rs1.getInt("COLUMN_SIZE"));
col.setDecimalDigits(rs1.getInt("DECIMAL_DIGITS"));
col.setNumPrecRadix(rs1.getInt("NUM_PREC_RADIX"));
col.setNullAble(rs1.getInt("NULLABLE"));
col.setRemarks(rs1.getString("REMARKS"));
col.setColumnDef(rs1.getString("COLUMN_DEF"));
col.setSqlDataType(rs1.getInt("SQL_DATA_TYPE"));
col.setSqlDatetimeSub(rs1.getInt("SQL_DATETIME_SUB"));
col.setCharOctetLength(rs1.getInt("CHAR_OCTET_LENGTH"));
col.setOrdinalPosition(rs1.getInt("ORDINAL_POSITION"));
col.setIsNullAble(rs1.getString("IS_NULLABLE"));
col.setIsAutoincrement(rs1.getString("IS_AUTOINCREMENT"));
tm.getAllColumns().put(col.getColumnName(), col);
}
ResultSet rs2 = dbmd.getIndexInfo(catalogName, schemaName, tableName, false, true);
String indexName = "";
while (rs2.next()) {
indexName = rs2.getString("INDEX_NAME");
String colName = rs2.getString("COLUMN_NAME");
ColumnMeta col = tm.getAllColumns().get(colName);
if (tm.getAllIndexes().containsKey(indexName)) {
IndexMeta index = tm.getAllIndexes().get(indexName);
index.getValues().add(col);
} else {
IndexMeta index = new IndexMeta();
index.setIndexName(indexName);
index.setNonUnique(rs2.getBoolean("NON_UNIQUE"));
index.setIndexQualifier(rs2.getString("INDEX_QUALIFIER"));
index.setIndexName(rs2.getString("INDEX_NAME"));
index.setType(rs2.getShort("TYPE"));
index.setOrdinalPosition(rs2.getShort("ORDINAL_POSITION"));
index.setAscOrDesc(rs2.getString("ASC_OR_DESC"));
index.setCardinality(rs2.getInt("CARDINALITY"));
index.getValues().add(col);
if ("PRIMARY".equalsIgnoreCase(indexName) || indexName.equalsIgnoreCase(
rsmd.getTableName(1) + "_pkey")) {
index.setIndextype(IndexType.PRIMARY);
} else if (!index.isNonUnique()) {
index.setIndextype(IndexType.Unique);
} else {
index.setIndextype(IndexType.Normal);
}
tm.getAllIndexes().put(indexName, index);
}
}
if(tm.getAllIndexes().isEmpty()){
throw new ShouldNeverHappenException("Could not found any index in the table: " + tableName);
}
IndexMeta index = tm.getAllIndexes().get(indexName);
if (index.getIndextype().value() != 0) {
if ("H2 JDBC Driver".equals(dbmd.getDriverName())) {
if (indexName.length() > 11 && "PRIMARY_KEY".equalsIgnoreCase(indexName.substring(0, 11))) {
index.setIndextype(IndexType.PRIMARY);
}
} else if (dbmd.getDriverName() != null && dbmd.getDriverName().toLowerCase().indexOf("postgresql") >= 0) {
if ((tableName + "_pkey").equalsIgnoreCase(indexName)) {
index.setIndextype(IndexType.PRIMARY);
}
}
}
return tm;
}
#location 71
#vulnerability type NULL_DEREFERENCE
|
#fixed code
private static TableMeta resultSetMetaToSchema(ResultSetMetaData rsmd, DatabaseMetaData dbmd, String tableName)
throws SQLException {
String schemaName = rsmd.getSchemaName(1);
String catalogName = rsmd.getCatalogName(1);
TableMeta tm = new TableMeta();
tm.setTableName(tableName);
ResultSet rsColumns = dbmd.getColumns(catalogName, schemaName, tableName, "%");
ResultSet rsIndex = dbmd.getIndexInfo(catalogName, schemaName, tableName, false, true);
try {
while (rsColumns.next()) {
ColumnMeta col = new ColumnMeta();
col.setTableCat(rsColumns.getString("TABLE_CAT"));
col.setTableSchemaName(rsColumns.getString("TABLE_SCHEM"));
col.setTableName(rsColumns.getString("TABLE_NAME"));
col.setColumnName(rsColumns.getString("COLUMN_NAME"));
col.setDataType(rsColumns.getInt("DATA_TYPE"));
col.setDataTypeName(rsColumns.getString("TYPE_NAME"));
col.setColumnSize(rsColumns.getInt("COLUMN_SIZE"));
col.setDecimalDigits(rsColumns.getInt("DECIMAL_DIGITS"));
col.setNumPrecRadix(rsColumns.getInt("NUM_PREC_RADIX"));
col.setNullAble(rsColumns.getInt("NULLABLE"));
col.setRemarks(rsColumns.getString("REMARKS"));
col.setColumnDef(rsColumns.getString("COLUMN_DEF"));
col.setSqlDataType(rsColumns.getInt("SQL_DATA_TYPE"));
col.setSqlDatetimeSub(rsColumns.getInt("SQL_DATETIME_SUB"));
col.setCharOctetLength(rsColumns.getInt("CHAR_OCTET_LENGTH"));
col.setOrdinalPosition(rsColumns.getInt("ORDINAL_POSITION"));
col.setIsNullAble(rsColumns.getString("IS_NULLABLE"));
col.setIsAutoincrement(rsColumns.getString("IS_AUTOINCREMENT"));
tm.getAllColumns().put(col.getColumnName(), col);
}
while (rsIndex.next()) {
String indexName = rsIndex.getString("INDEX_NAME");
String colName = rsIndex.getString("COLUMN_NAME");
ColumnMeta col = tm.getAllColumns().get(colName);
if (tm.getAllIndexes().containsKey(indexName)) {
IndexMeta index = tm.getAllIndexes().get(indexName);
index.getValues().add(col);
} else {
IndexMeta index = new IndexMeta();
index.setIndexName(indexName);
index.setNonUnique(rsIndex.getBoolean("NON_UNIQUE"));
index.setIndexQualifier(rsIndex.getString("INDEX_QUALIFIER"));
index.setIndexName(rsIndex.getString("INDEX_NAME"));
index.setType(rsIndex.getShort("TYPE"));
index.setOrdinalPosition(rsIndex.getShort("ORDINAL_POSITION"));
index.setAscOrDesc(rsIndex.getString("ASC_OR_DESC"));
index.setCardinality(rsIndex.getInt("CARDINALITY"));
index.getValues().add(col);
if ("PRIMARY".equalsIgnoreCase(indexName)) {
index.setIndextype(IndexType.PRIMARY);
} else if (!index.isNonUnique()) {
index.setIndextype(IndexType.Unique);
} else {
index.setIndextype(IndexType.Normal);
}
tm.getAllIndexes().put(indexName, index);
}
}
if (tm.getAllIndexes().isEmpty()) {
throw new ShouldNeverHappenException("Could not found any index in the table: " + tableName);
}
} finally {
if (rsColumns != null) {
rsColumns.close();
}
if (rsIndex != null) {
rsIndex.close();
}
}
return tm;
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
@Override
public String getConfig(String dataId, String defaultValue, long timeoutMills) {
ConfigFuture configFuture = new ConfigFuture(dataId, defaultValue, ConfigFuture.ConfigOperation.GET, timeoutMills);
etcdConfigExecutor.execute(() -> {
complete(getClient().getKVClient().get(ByteSequence.from(dataId, UTF_8)), configFuture);
});
return (String) configFuture.get();
}
#location 4
#vulnerability type THREAD_SAFETY_VIOLATION
|
#fixed code
@Override
public String getConfig(String dataId, String defaultValue, long timeoutMills) {
ConfigFuture configFuture = new ConfigFuture(dataId, defaultValue, ConfigFuture.ConfigOperation.GET, timeoutMills);
etcdConfigExecutor.execute(() -> complete(getClient().getKVClient().get(ByteSequence.from(dataId, UTF_8)), configFuture));
return (String) configFuture.get();
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
@Override
public String getConfig(String dataId, String defaultValue, long timeoutMills) {
ConfigFuture configFuture = new ConfigFuture(dataId, defaultValue, ConfigFuture.ConfigOperation.GET, timeoutMills);
consulConfigExecutor.execute(() -> {
complete(getConsulClient().getKVValue(dataId), configFuture);
});
return (String) configFuture.get();
}
#location 4
#vulnerability type THREAD_SAFETY_VIOLATION
|
#fixed code
@Override
public String getConfig(String dataId, String defaultValue, long timeoutMills) {
ConfigFuture configFuture = new ConfigFuture(dataId, defaultValue, ConfigFuture.ConfigOperation.GET, timeoutMills);
consulNotifierExecutor.execute(() -> {
complete(getConsulClient().getKVValue(dataId), configFuture);
});
return (String) configFuture.get();
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
@Override
public BranchStatus branchCommit(BranchType branchType, String xid, long branchId, String resourceId,
String applicationData)
throws TransactionException {
try {
BranchCommitRequest request = new BranchCommitRequest();
request.setXid(xid);
request.setBranchId(branchId);
request.setResourceId(resourceId);
request.setApplicationData(applicationData);
request.setBranchType(branchType);
GlobalSession globalSession = SessionHolder.findGlobalSession(xid);
if (globalSession == null) {
return BranchStatus.PhaseTwo_Committed;
}
if(BranchType.SAGA.equals(branchType)){
Map<String,Channel> channels = ChannelManager.getRmChannels();
if(channels == null || channels.size() == 0){
LOGGER.error("Failed to commit SAGA global[" + globalSession.getXid() + ", RM channels is empty.");
return BranchStatus.PhaseTwo_CommitFailed_Retryable;
}
String sagaResourceId = globalSession.getApplicationId() + "#" + globalSession.getTransactionServiceGroup();
Channel sagaChannel = channels.get(sagaResourceId);
if(sagaChannel == null){
LOGGER.error("Failed to commit SAGA global[" + globalSession.getXid() + ", cannot find channel by resourceId["+sagaResourceId+"]");
return BranchStatus.PhaseTwo_CommitFailed_Retryable;
}
BranchCommitResponse response = (BranchCommitResponse)messageSender.sendSyncRequest(sagaChannel, request);
return response.getBranchStatus();
}
else{
BranchSession branchSession = globalSession.getBranch(branchId);
BranchCommitResponse response = (BranchCommitResponse)messageSender.sendSyncRequest(resourceId,
branchSession.getClientId(), request);
return response.getBranchStatus();
}
} catch (IOException | TimeoutException e) {
throw new BranchTransactionException(FailedToSendBranchCommitRequest, String.format("Send branch commit failed, xid = %s branchId = %s", xid, branchId), e);
}
}
#location 39
#vulnerability type NULL_DEREFERENCE
|
#fixed code
@Override
public BranchStatus branchCommit(BranchType branchType, String xid, long branchId, String resourceId,
String applicationData)
throws TransactionException {
try {
BranchCommitRequest request = new BranchCommitRequest();
request.setXid(xid);
request.setBranchId(branchId);
request.setResourceId(resourceId);
request.setApplicationData(applicationData);
request.setBranchType(branchType);
GlobalSession globalSession = SessionHolder.findGlobalSession(xid);
if (globalSession == null) {
return BranchStatus.PhaseTwo_Committed;
}
if (BranchType.SAGA.equals(branchType)) {
Map<String,Channel> channels = ChannelManager.getRmChannels();
if (channels == null || channels.size() == 0) {
LOGGER.error("Failed to commit SAGA global[" + globalSession.getXid() + ", RM channels is empty.");
return BranchStatus.PhaseTwo_CommitFailed_Retryable;
}
String sagaResourceId = globalSession.getApplicationId() + "#" + globalSession.getTransactionServiceGroup();
Channel sagaChannel = channels.get(sagaResourceId);
if (sagaChannel == null) {
LOGGER.error("Failed to commit SAGA global[" + globalSession.getXid() + ", cannot find channel by resourceId["+sagaResourceId+"]");
return BranchStatus.PhaseTwo_CommitFailed_Retryable;
}
BranchCommitResponse response = (BranchCommitResponse)messageSender.sendSyncRequest(sagaChannel, request);
return response.getBranchStatus();
} else {
BranchSession branchSession = globalSession.getBranch(branchId);
if (null != branchSession) {
BranchCommitResponse response = (BranchCommitResponse)messageSender.sendSyncRequest(resourceId,
branchSession.getClientId(), request);
return response.getBranchStatus();
} else {
return BranchStatus.PhaseTwo_Committed;
}
}
} catch (IOException | TimeoutException e) {
throw new BranchTransactionException(FailedToSendBranchCommitRequest, String.format("Send branch commit failed, xid = %s branchId = %s", xid, branchId), e);
}
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
protected Connection getConnectionProxy(Connection connection) throws SQLException {
Connection physicalConn = connection.unwrap(Connection.class);
XAConnection xaConnection = XAUtils.createXAConnection(physicalConn, this);
ConnectionProxyXA connectionProxyXA = new ConnectionProxyXA(connection, xaConnection, this, RootContext.getXID());
connectionProxyXA.init();
return connectionProxyXA;
}
#location 6
#vulnerability type RESOURCE_LEAK
|
#fixed code
protected Connection getConnectionProxy(Connection connection) throws SQLException {
if (!RootContext.inGlobalTransaction()) {
return connection;
}
return getConnectionProxyXA(connection);
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
@Override
public boolean removeConfig(String dataId, long timeoutMills) {
ConfigFuture configFuture = new ConfigFuture(dataId, null, ConfigFuture.ConfigOperation.REMOVE, timeoutMills);
consulConfigExecutor.execute(() -> {
complete(getConsulClient().deleteKVValue(dataId), configFuture);
});
return (Boolean) configFuture.get();
}
#location 4
#vulnerability type THREAD_SAFETY_VIOLATION
|
#fixed code
@Override
public boolean removeConfig(String dataId, long timeoutMills) {
ConfigFuture configFuture = new ConfigFuture(dataId, null, ConfigFuture.ConfigOperation.REMOVE, timeoutMills);
consulNotifierExecutor.execute(() -> {
complete(getConsulClient().deleteKVValue(dataId), configFuture);
});
return (Boolean) configFuture.get();
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
@Test
public void testRestoredFromFileCommitRetry() throws Exception {
SessionHolder.init(".");
GlobalSession globalSession = new GlobalSession("demo-app", "my_test_tx_group", "test", 6000);
globalSession.addSessionLifecycleListener(SessionHolder.getRootSessionManager());
globalSession.begin();
BranchSession branchSession1 = SessionHelper.newBranchByGlobal(globalSession, BranchType.AT, RESOURCE_ID,
"ta:1", "xxx");
branchSession1.lock();
globalSession.addBranch(branchSession1);
LockManager lockManager = LockManagerFactory.get();
Assert.assertFalse(lockManager.isLockable(0L, RESOURCE_ID, "ta:1"));
globalSession.changeStatus(GlobalStatus.Committing);
globalSession.changeBranchStatus(branchSession1, BranchStatus.PhaseTwo_CommitFailed_Retryable);
globalSession.changeStatus(GlobalStatus.CommitRetrying);
lockManager.cleanAllLocks();
Assert.assertTrue(lockManager.isLockable(0L, RESOURCE_ID, "ta:1"));
// Re-init SessionHolder: restore sessions from file
SessionHolder.init(".");
long tid = globalSession.getTransactionId();
GlobalSession reloadSession = SessionHolder.findGlobalSession(tid);
Assert.assertEquals(reloadSession.getStatus(), GlobalStatus.CommitRetrying);
GlobalSession sessionInRetryCommittingQueue = SessionHolder.getRetryCommittingSessionManager()
.findGlobalSession(tid);
Assert.assertTrue(reloadSession == sessionInRetryCommittingQueue);
BranchSession reloadBranchSession = reloadSession.getBranch(branchSession1.getBranchId());
Assert.assertEquals(reloadBranchSession.getStatus(), BranchStatus.PhaseTwo_CommitFailed_Retryable);
// Lock is held by session in CommitRetrying status
Assert.assertFalse(lockManager.isLockable(0L, RESOURCE_ID, "ta:1"));
}
#location 3
#vulnerability type RESOURCE_LEAK
|
#fixed code
@Test
public void testRestoredFromFileCommitRetry() throws Exception {
SessionHolder.init("file");
GlobalSession globalSession = new GlobalSession("demo-app", "my_test_tx_group", "test", 6000);
globalSession.addSessionLifecycleListener(SessionHolder.getRootSessionManager());
globalSession.begin();
BranchSession branchSession1 = SessionHelper.newBranchByGlobal(globalSession, BranchType.AT, RESOURCE_ID,
"ta:1", "xxx");
branchSession1.lock();
globalSession.addBranch(branchSession1);
LockManager lockManager = LockManagerFactory.get();
Assert.assertFalse(lockManager.isLockable(0L, RESOURCE_ID, "ta:1"));
globalSession.changeStatus(GlobalStatus.Committing);
globalSession.changeBranchStatus(branchSession1, BranchStatus.PhaseTwo_CommitFailed_Retryable);
globalSession.changeStatus(GlobalStatus.CommitRetrying);
lockManager.cleanAllLocks();
Assert.assertTrue(lockManager.isLockable(0L, RESOURCE_ID, "ta:1"));
// Re-init SessionHolder: restore sessions from file
SessionHolder.init("file");
long tid = globalSession.getTransactionId();
GlobalSession reloadSession = SessionHolder.findGlobalSession(tid);
Assert.assertEquals(reloadSession.getStatus(), GlobalStatus.CommitRetrying);
GlobalSession sessionInRetryCommittingQueue = SessionHolder.getRetryCommittingSessionManager()
.findGlobalSession(tid);
Assert.assertTrue(reloadSession == sessionInRetryCommittingQueue);
BranchSession reloadBranchSession = reloadSession.getBranch(branchSession1.getBranchId());
Assert.assertEquals(reloadBranchSession.getStatus(), BranchStatus.PhaseTwo_CommitFailed_Retryable);
// Lock is held by session in CommitRetrying status
Assert.assertFalse(lockManager.isLockable(0L, RESOURCE_ID, "ta:1"));
//clear
reloadSession.addSessionLifecycleListener(SessionHolder.getRootSessionManager());
reloadSession.end();
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
@Override
public Object invoke(ServiceTaskState serviceTaskState, Object... input) {
ServiceTaskStateImpl state = (ServiceTaskStateImpl) serviceTaskState;
Object bean = applicationContext.getBean(state.getServiceName());
Method method = state.getMethod();
if (method == null) {
synchronized (state) {
method = state.getMethod();
if (method == null) {
method = findMethod(bean.getClass(), state.getServiceMethod(), state.getParameterTypes());
if (method != null) {
state.setMethod(method);
}
}
}
}
if (method == null) {
throw new EngineExecutionException("No such method[" + state.getServiceMethod() + "] on BeanClass[" + bean.getClass() + "]", FrameworkErrorCode.NoSuchMethod);
}
Object[] args = new Object[method.getParameterCount()];
try {
Class[] paramTypes = method.getParameterTypes();
if (input != null && input.length > 0) {
int len = input.length < paramTypes.length ? input.length : paramTypes.length;
for (int i = 0; i < len; i++) {
args[i] = toJavaObject(input[i], paramTypes[i]);
}
}
} catch (Exception e) {
throw new EngineExecutionException(e, "Input to java object error, Method[" + state.getServiceMethod() + "] on BeanClass[" + bean.getClass() + "]", FrameworkErrorCode.InvalidParameter);
}
return invokeMethod(bean, method, args);
}
#location 6
#vulnerability type THREAD_SAFETY_VIOLATION
|
#fixed code
@Override
public Object invoke(ServiceTaskState serviceTaskState, Object... input) {
ServiceTaskStateImpl state = (ServiceTaskStateImpl) serviceTaskState;
if(state.isAsync()){
if(threadPoolExecutor == null){
if(LOGGER.isWarnEnabled()){
LOGGER.warn("threadPoolExecutor is null, Service[{}.{}] cannot execute asynchronously, executing synchronously now. stateName: {}", state.getServiceName(), state.getServiceMethod(), state.getName());
}
return doInvoke(state, input);
}
if(LOGGER.isInfoEnabled()){
LOGGER.info("Submit Service[{}.{}] to asynchronously executing. stateName: {}", state.getServiceName(), state.getServiceMethod(), state.getName());
}
threadPoolExecutor.execute(new Runnable() {
@Override
public void run() {
doInvoke(state, input);
}
});
return null;
}
else{
return doInvoke(state, input);
}
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
public static void refresh(final DataSourceProxy dataSourceProxy){
ConcurrentMap<String, TableMeta> tableMetaMap = TABLE_META_CACHE.asMap();
for (Entry<String, TableMeta> entry : tableMetaMap.entrySet()) {
try {
TableMeta tableMeta = fetchSchema(dataSourceProxy, entry.getValue().getTableName());
if (tableMeta == null){
LOGGER.error("get table meta error");
}
if (!tableMeta.equals(entry.getValue())){
TABLE_META_CACHE.put(entry.getKey(), tableMeta);
LOGGER.info("table meta change was found, update table meta cache automatically.");
}
} catch (SQLException e) {
LOGGER.error("get table meta error:{}", e.getMessage(), e);
}
}
}
#location 9
#vulnerability type NULL_DEREFERENCE
|
#fixed code
public static void refresh(final DataSourceProxy dataSourceProxy){
ConcurrentMap<String, TableMeta> tableMetaMap = TABLE_META_CACHE.asMap();
for (Entry<String, TableMeta> entry : tableMetaMap.entrySet()) {
String key = getCacheKey(dataSourceProxy, entry.getValue().getTableName());
if(entry.getKey().equals(key)){
try {
TableMeta tableMeta = fetchSchema(dataSourceProxy, entry.getValue().getTableName());
if (!tableMeta.equals(entry.getValue())){
TABLE_META_CACHE.put(entry.getKey(), tableMeta);
LOGGER.info("table meta change was found, update table meta cache automatically.");
}
} catch (SQLException e) {
LOGGER.error("get table meta error:{}", e.getMessage(), e);
}
}
}
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
public static byte[] decompress(byte[] bytes) {
if (bytes == null) {
throw new NullPointerException("bytes is null");
}
ByteArrayOutputStream out = null;
GZIPInputStream gunzip = null;
try {
out = new ByteArrayOutputStream();
gunzip = new GZIPInputStream(new ByteArrayInputStream(bytes));
byte[] buffer = new byte[BUFFER_SIZE];
int n;
while ((n = gunzip.read(buffer)) > -1) {
out.write(buffer, 0, n);
}
gunzip.close();
return out.toByteArray();
} catch (IOException e) {
throw new RuntimeException("gzip decompress error", e);
} finally {
IOUtil.close(out);
}
}
#location 17
#vulnerability type RESOURCE_LEAK
|
#fixed code
public static byte[] decompress(byte[] bytes) {
if (bytes == null) {
throw new NullPointerException("bytes is null");
}
ByteArrayOutputStream out = new ByteArrayOutputStream();
try (GZIPInputStream gunzip = new GZIPInputStream(new ByteArrayInputStream(bytes))) {
byte[] buffer = new byte[BUFFER_SIZE];
int n;
while ((n = gunzip.read(buffer)) > -1) {
out.write(buffer, 0, n);
}
return out.toByteArray();
} catch (IOException e) {
throw new RuntimeException("gzip decompress error", e);
}
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
@Test
public void testRestoredFromFile() throws Exception {
SessionHolder.init(".");
GlobalSession globalSession = new GlobalSession("demo-app", "my_test_tx_group", "test", 6000);
globalSession.addSessionLifecycleListener(SessionHolder.getRootSessionManager());
globalSession.begin();
BranchSession branchSession1 = SessionHelper.newBranchByGlobal(globalSession, BranchType.AT, RESOURCE_ID,
"ta:1,2;tb:3", "xxx");
branchSession1.lock();
globalSession.addBranch(branchSession1);
LockManager lockManager = LockManagerFactory.get();
Assert.assertFalse(lockManager.isLockable(0L, RESOURCE_ID, "ta:1"));
Assert.assertFalse(lockManager.isLockable(0L, RESOURCE_ID, "ta:2"));
Assert.assertFalse(lockManager.isLockable(0L, RESOURCE_ID, "tb:3"));
Assert.assertTrue(lockManager.isLockable(0L, RESOURCE_ID, "ta:4"));
Assert.assertTrue(lockManager.isLockable(0L, RESOURCE_ID, "tb:5"));
lockManager.cleanAllLocks();
Assert.assertTrue(lockManager.isLockable(0L, RESOURCE_ID, "ta:1"));
Assert.assertTrue(lockManager.isLockable(0L, RESOURCE_ID, "ta:2"));
Assert.assertTrue(lockManager.isLockable(0L, RESOURCE_ID, "tb:3"));
// Re-init SessionHolder: restore sessions from file
SessionHolder.init(".");
long tid = globalSession.getTransactionId();
GlobalSession reloadSession = SessionHolder.findGlobalSession(tid);
Assert.assertNotNull(reloadSession);
Assert.assertFalse(globalSession == reloadSession);
Assert.assertEquals(globalSession.getApplicationId(), reloadSession.getApplicationId());
Assert.assertFalse(lockManager.isLockable(0L, RESOURCE_ID, "ta:1"));
Assert.assertFalse(lockManager.isLockable(0L, RESOURCE_ID, "ta:2"));
Assert.assertFalse(lockManager.isLockable(0L, RESOURCE_ID, "tb:3"));
Assert.assertTrue(lockManager.isLockable(globalSession.getTransactionId(), RESOURCE_ID, "tb:3"));
}
#location 3
#vulnerability type RESOURCE_LEAK
|
#fixed code
@Test
public void testRestoredFromFile() throws Exception {
SessionHolder.init("file");
GlobalSession globalSession = new GlobalSession("demo-app", "my_test_tx_group", "test", 6000);
globalSession.addSessionLifecycleListener(SessionHolder.getRootSessionManager());
globalSession.begin();
BranchSession branchSession1 = SessionHelper.newBranchByGlobal(globalSession, BranchType.AT, RESOURCE_ID,
"ta:1,2;tb:3", "xxx");
branchSession1.lock();
globalSession.addBranch(branchSession1);
LockManager lockManager = LockManagerFactory.get();
Assert.assertFalse(lockManager.isLockable(0L, RESOURCE_ID, "ta:1"));
Assert.assertFalse(lockManager.isLockable(0L, RESOURCE_ID, "ta:2"));
Assert.assertFalse(lockManager.isLockable(0L, RESOURCE_ID, "tb:3"));
Assert.assertTrue(lockManager.isLockable(0L, RESOURCE_ID, "ta:4"));
Assert.assertTrue(lockManager.isLockable(0L, RESOURCE_ID, "tb:5"));
lockManager.cleanAllLocks();
Assert.assertTrue(lockManager.isLockable(0L, RESOURCE_ID, "ta:1"));
Assert.assertTrue(lockManager.isLockable(0L, RESOURCE_ID, "ta:2"));
Assert.assertTrue(lockManager.isLockable(0L, RESOURCE_ID, "tb:3"));
// Re-init SessionHolder: restore sessions from file
SessionHolder.init("file");
long tid = globalSession.getTransactionId();
GlobalSession reloadSession = SessionHolder.findGlobalSession(tid);
Assert.assertNotNull(reloadSession);
Assert.assertFalse(globalSession == reloadSession);
Assert.assertEquals(globalSession.getApplicationId(), reloadSession.getApplicationId());
Assert.assertFalse(lockManager.isLockable(0L, RESOURCE_ID, "ta:1"));
Assert.assertFalse(lockManager.isLockable(0L, RESOURCE_ID, "ta:2"));
Assert.assertFalse(lockManager.isLockable(0L, RESOURCE_ID, "tb:3"));
Assert.assertTrue(lockManager.isLockable(globalSession.getTransactionId(), RESOURCE_ID, "tb:3"));
//clear
reloadSession.addSessionLifecycleListener(SessionHolder.getRootSessionManager());
reloadSession.end();
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
@Override
public void addConfigListener(String dataId, ConfigChangeListener listener) {
configListenersMap.putIfAbsent(dataId, new ArrayList<>());
configChangeNotifiersMap.putIfAbsent(dataId, new ArrayList<>());
ConfigChangeNotifier configChangeNotifier = new ConfigChangeNotifier(dataId, listener);
configChangeNotifiersMap.get(dataId).add(configChangeNotifier);
if (null != listener.getExecutor()) {
listener.getExecutor().submit(configChangeNotifier);
} else {
consulConfigExecutor.submit(configChangeNotifier);
}
}
#location 10
#vulnerability type THREAD_SAFETY_VIOLATION
|
#fixed code
@Override
public void addConfigListener(String dataId, ConfigChangeListener listener) {
configListenersMap.putIfAbsent(dataId, new ArrayList<>());
configChangeNotifiersMap.putIfAbsent(dataId, new ArrayList<>());
ConfigChangeNotifier configChangeNotifier = new ConfigChangeNotifier(dataId, listener);
configChangeNotifiersMap.get(dataId).add(configChangeNotifier);
if (null != listener.getExecutor()) {
listener.getExecutor().submit(configChangeNotifier);
} else {
consulNotifierExecutor.submit(configChangeNotifier);
}
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
@Override
public boolean putConfig(String dataId, String content, long timeoutMills) {
ConfigFuture configFuture = new ConfigFuture(dataId, content, ConfigFuture.ConfigOperation.PUT, timeoutMills);
consulConfigExecutor.execute(() -> {
complete(getConsulClient().setKVValue(dataId, content), configFuture);
});
return (Boolean) configFuture.get();
}
#location 4
#vulnerability type THREAD_SAFETY_VIOLATION
|
#fixed code
@Override
public boolean putConfig(String dataId, String content, long timeoutMills) {
ConfigFuture configFuture = new ConfigFuture(dataId, content, ConfigFuture.ConfigOperation.PUT, timeoutMills);
consulNotifierExecutor.execute(() -> {
complete(getConsulClient().setKVValue(dataId, content), configFuture);
});
return (Boolean) configFuture.get();
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
@Test
public void testRestoredFromFileAsyncCommitting() throws Exception {
SessionHolder.init(".");
GlobalSession globalSession = new GlobalSession("demo-app", "my_test_tx_group", "test", 6000);
globalSession.addSessionLifecycleListener(SessionHolder.getRootSessionManager());
globalSession.begin();
BranchSession branchSession1 = SessionHelper.newBranchByGlobal(globalSession, BranchType.AT, RESOURCE_ID,
"ta:1", "xxx");
Assert.assertTrue(branchSession1.lock());
globalSession.addBranch(branchSession1);
LockManager lockManager = LockManagerFactory.get();
Assert.assertFalse(lockManager.isLockable(0L, RESOURCE_ID, "ta:1"));
globalSession.changeStatus(GlobalStatus.AsyncCommitting);
lockManager.cleanAllLocks();
Assert.assertTrue(lockManager.isLockable(0L, RESOURCE_ID, "ta:1"));
// Re-init SessionHolder: restore sessions from file
SessionHolder.init(".");
long tid = globalSession.getTransactionId();
GlobalSession reloadSession = SessionHolder.findGlobalSession(tid);
Assert.assertEquals(reloadSession.getStatus(), GlobalStatus.AsyncCommitting);
GlobalSession sessionInAsyncCommittingQueue = SessionHolder.getAsyncCommittingSessionManager()
.findGlobalSession(tid);
Assert.assertTrue(reloadSession == sessionInAsyncCommittingQueue);
// No locking for session in AsyncCommitting status
Assert.assertTrue(lockManager.isLockable(0L, RESOURCE_ID, "ta:1"));
}
#location 3
#vulnerability type RESOURCE_LEAK
|
#fixed code
@Test
public void testRestoredFromFileAsyncCommitting() throws Exception {
SessionHolder.init("file");
GlobalSession globalSession = new GlobalSession("demo-app", "my_test_tx_group", "test", 6000);
globalSession.addSessionLifecycleListener(SessionHolder.getRootSessionManager());
globalSession.begin();
BranchSession branchSession1 = SessionHelper.newBranchByGlobal(globalSession, BranchType.AT, RESOURCE_ID,
"ta:1", "xxx");
Assert.assertTrue(branchSession1.lock());
globalSession.addBranch(branchSession1);
LockManager lockManager = LockManagerFactory.get();
Assert.assertFalse(lockManager.isLockable(0L, RESOURCE_ID, "ta:1"));
globalSession.changeStatus(GlobalStatus.AsyncCommitting);
lockManager.cleanAllLocks();
Assert.assertTrue(lockManager.isLockable(0L, RESOURCE_ID, "ta:1"));
// Re-init SessionHolder: restore sessions from file
SessionHolder.init("file");
long tid = globalSession.getTransactionId();
GlobalSession reloadSession = SessionHolder.findGlobalSession(tid);
Assert.assertEquals(reloadSession.getStatus(), GlobalStatus.AsyncCommitting);
GlobalSession sessionInAsyncCommittingQueue = SessionHolder.getAsyncCommittingSessionManager()
.findGlobalSession(tid);
Assert.assertTrue(reloadSession == sessionInAsyncCommittingQueue);
// No locking for session in AsyncCommitting status
Assert.assertTrue(lockManager.isLockable(0L, RESOURCE_ID, "ta:1"));
//clear
reloadSession.addSessionLifecycleListener(SessionHolder.getRootSessionManager());
reloadSession.end();
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
@Test
public void refreshTest_0() {
MockDriver mockDriver = new MockDriver(columnMetas, indexMetas);
DruidDataSource druidDataSource = new DruidDataSource();
druidDataSource.setUrl("jdbc:mock:xxx");
druidDataSource.setDriver(mockDriver);
DataSourceProxy dataSourceProxy = new DataSourceProxy(druidDataSource);
TableMeta tableMeta = getTableMetaCache().getTableMeta(dataSourceProxy, "t1");
//change the columns meta
columnMetas =
new Object[][] {
new Object[] {"", "", "t1", "id", Types.INTEGER, "INTEGER", 64, 0, 10, 1, "", "", 0, 0, 64, 1, "NO", "YES"},
new Object[] {"", "", "t1", "name1", Types.VARCHAR, "VARCHAR", 65, 0, 10, 0, "", "", 0, 0, 64, 2, "YES",
"NO"},
new Object[] {"", "", "t1", "name2", Types.VARCHAR, "VARCHAR", 64, 0, 10, 0, "", "", 0, 0, 64, 3, "YES",
"NO"},
new Object[] {"", "", "t1", "name3", Types.VARCHAR, "VARCHAR", 64, 0, 10, 0, "", "", 0, 0, 64, 4, "YES",
"NO"}
};
mockDriver.setMockColumnsMetasReturnValue(columnMetas);
getTableMetaCache().refresh(dataSourceProxy);
}
#location 24
#vulnerability type RESOURCE_LEAK
|
#fixed code
@Test
public void refreshTest_0() throws SQLException {
MockDriver mockDriver = new MockDriver(columnMetas, indexMetas);
DruidDataSource druidDataSource = new DruidDataSource();
druidDataSource.setUrl("jdbc:mock:xxx");
druidDataSource.setDriver(mockDriver);
DataSourceProxy dataSourceProxy = new DataSourceProxy(druidDataSource);
TableMeta tableMeta = getTableMetaCache().getTableMeta(dataSourceProxy.getPlainConnection(), "t1",
dataSourceProxy.getResourceId());
//change the columns meta
columnMetas =
new Object[][] {
new Object[] {"", "", "t1", "id", Types.INTEGER, "INTEGER", 64, 0, 10, 1, "", "", 0, 0, 64, 1, "NO", "YES"},
new Object[] {"", "", "t1", "name1", Types.VARCHAR, "VARCHAR", 65, 0, 10, 0, "", "", 0, 0, 64, 2, "YES",
"NO"},
new Object[] {"", "", "t1", "name2", Types.VARCHAR, "VARCHAR", 64, 0, 10, 0, "", "", 0, 0, 64, 3, "YES",
"NO"},
new Object[] {"", "", "t1", "name3", Types.VARCHAR, "VARCHAR", 64, 0, 10, 0, "", "", 0, 0, 64, 4, "YES",
"NO"}
};
mockDriver.setMockColumnsMetasReturnValue(columnMetas);
getTableMetaCache().refresh(dataSourceProxy.getPlainConnection(), dataSourceProxy.getResourceId());
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
@Override
public void addConfigListener(String dataId, ConfigChangeListener listener) {
configListenersMap.putIfAbsent(dataId, new ArrayList<>());
configChangeNotifiersMap.putIfAbsent(dataId, new ArrayList<>());
ConfigChangeNotifier configChangeNotifier = new ConfigChangeNotifier(dataId, listener);
configChangeNotifiersMap.get(dataId).add(configChangeNotifier);
if (null != listener.getExecutor()) {
listener.getExecutor().submit(configChangeNotifier);
} else {
consulConfigExecutor.submit(configChangeNotifier);
}
}
#location 6
#vulnerability type THREAD_SAFETY_VIOLATION
|
#fixed code
@Override
public void addConfigListener(String dataId, ConfigChangeListener listener) {
configListenersMap.putIfAbsent(dataId, new ArrayList<>());
configChangeNotifiersMap.putIfAbsent(dataId, new ArrayList<>());
ConfigChangeNotifier configChangeNotifier = new ConfigChangeNotifier(dataId, listener);
configChangeNotifiersMap.get(dataId).add(configChangeNotifier);
if (null != listener.getExecutor()) {
listener.getExecutor().submit(configChangeNotifier);
} else {
consulNotifierExecutor.submit(configChangeNotifier);
}
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
@Override
public void subscribe(String cluster, Watch.Listener listener) throws Exception {
listenerMap.putIfAbsent(cluster, new HashSet<>());
listenerMap.get(cluster).add(listener);
EtcdWatcher watcher = watcherMap.computeIfAbsent(cluster, w -> new EtcdWatcher(listener));
EXECUTOR_SERVICE.submit(watcher);
}
#location 5
#vulnerability type THREAD_SAFETY_VIOLATION
|
#fixed code
@Override
public void subscribe(String cluster, Watch.Listener listener) throws Exception {
listenerMap.putIfAbsent(cluster, new HashSet<>());
listenerMap.get(cluster).add(listener);
EtcdWatcher watcher = watcherMap.computeIfAbsent(cluster, w -> new EtcdWatcher(listener));
executorService.submit(watcher);
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
@Override
public boolean removeConfig(String dataId, long timeoutMills) {
ConfigFuture configFuture = new ConfigFuture(dataId, null, ConfigOperation.REMOVE, timeoutMills);
configOperateExecutor.submit(new ConfigOperateRunnable(configFuture));
return (Boolean)configFuture.get();
}
#location 5
#vulnerability type NULL_DEREFERENCE
|
#fixed code
@Override
public boolean removeConfig(String dataId, long timeoutMills) {
ConfigFuture configFuture = new ConfigFuture(dataId, null, ConfigOperation.REMOVE, timeoutMills);
configOperateExecutor.submit(new ConfigOperateRunnable(configFuture));
return (Boolean)configFuture.get(timeoutMills, TimeUnit.MILLISECONDS);
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
public void registerResource(String resourceGroupId, String resourceId) {
if (LOGGER.isInfoEnabled()) {
LOGGER.info("register to RM resourceId:" + resourceId);
}
if (getClientChannelManager().getChannels().isEmpty()) {
getClientChannelManager().reconnect(transactionServiceGroup);
return;
}
synchronized (getClientChannelManager().getChannels()) {
for (Map.Entry<String, Channel> entry : getClientChannelManager().getChannels().entrySet()) {
String serverAddress = entry.getKey();
Channel rmChannel = entry.getValue();
if (LOGGER.isInfoEnabled()) {
LOGGER.info("register resource, resourceId:" + resourceId);
}
sendRegisterMessage(serverAddress, rmChannel, resourceId);
}
}
}
#location 6
#vulnerability type THREAD_SAFETY_VIOLATION
|
#fixed code
public void registerResource(String resourceGroupId, String resourceId) {
if (LOGGER.isInfoEnabled()) {
LOGGER.info("register to RM resourceId:{}", resourceId);
}
if (getClientChannelManager().getChannels().isEmpty()) {
getClientChannelManager().reconnect(transactionServiceGroup);
return;
}
synchronized (getClientChannelManager().getChannels()) {
for (Map.Entry<String, Channel> entry : getClientChannelManager().getChannels().entrySet()) {
String serverAddress = entry.getKey();
Channel rmChannel = entry.getValue();
if (LOGGER.isInfoEnabled()) {
LOGGER.info("register resource, resourceId:{}", resourceId);
}
sendRegisterMessage(serverAddress, rmChannel, resourceId);
}
}
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
@Override
public BranchStatus branchRollback(BranchType branchType, String xid, long branchId, String resourceId,
String applicationData) throws TransactionException {
try {
BranchRollbackRequest request = new BranchRollbackRequest();
request.setXid(xid);
request.setBranchId(branchId);
request.setResourceId(resourceId);
request.setApplicationData(applicationData);
request.setBranchType(branchType);
GlobalSession globalSession = SessionHolder.findGlobalSession(xid);
if (globalSession == null) {
return BranchStatus.PhaseTwo_Rollbacked;
}
if (BranchType.SAGA.equals(branchType)) {
Map<String, Channel> channels = ChannelManager.getRmChannels();
if (channels == null || channels.size() == 0) {
LOGGER.error(
"Failed to rollback SAGA global[" + globalSession.getXid() + ", RM channels is empty.");
return BranchStatus.PhaseTwo_RollbackFailed_Retryable;
}
String sagaResourceId = globalSession.getApplicationId() + "#" + globalSession
.getTransactionServiceGroup();
Channel sagaChannel = channels.get(sagaResourceId);
if (sagaChannel == null) {
LOGGER.error("Failed to rollback SAGA global[" + globalSession.getXid()
+ ", cannot find channel by resourceId[" + sagaResourceId + "]");
return BranchStatus.PhaseTwo_RollbackFailed_Retryable;
}
BranchRollbackResponse response = (BranchRollbackResponse)messageSender.sendSyncRequest(sagaChannel,
request);
return response.getBranchStatus();
} else {
BranchSession branchSession = globalSession.getBranch(branchId);
BranchRollbackResponse response = (BranchRollbackResponse)messageSender.sendSyncRequest(resourceId,
branchSession.getClientId(), request);
return response.getBranchStatus();
}
} catch (IOException | TimeoutException e) {
throw new BranchTransactionException(FailedToSendBranchRollbackRequest,
String.format("Send branch rollback failed, xid = %s branchId = %s", xid, branchId), e);
}
}
#location 41
#vulnerability type NULL_DEREFERENCE
|
#fixed code
@Override
public BranchStatus branchRollback(BranchType branchType, String xid, long branchId, String resourceId,
String applicationData) throws TransactionException {
try {
BranchRollbackRequest request = new BranchRollbackRequest();
request.setXid(xid);
request.setBranchId(branchId);
request.setResourceId(resourceId);
request.setApplicationData(applicationData);
request.setBranchType(branchType);
GlobalSession globalSession = SessionHolder.findGlobalSession(xid);
if (globalSession == null) {
return BranchStatus.PhaseTwo_Rollbacked;
}
if (BranchType.SAGA.equals(branchType)) {
Map<String, Channel> channels = ChannelManager.getRmChannels();
if (channels == null || channels.size() == 0) {
LOGGER.error(
"Failed to rollback SAGA global[" + globalSession.getXid() + ", RM channels is empty.");
return BranchStatus.PhaseTwo_RollbackFailed_Retryable;
}
String sagaResourceId = globalSession.getApplicationId() + "#" + globalSession
.getTransactionServiceGroup();
Channel sagaChannel = channels.get(sagaResourceId);
if (sagaChannel == null) {
LOGGER.error("Failed to rollback SAGA global[" + globalSession.getXid()
+ ", cannot find channel by resourceId[" + sagaResourceId + "]");
return BranchStatus.PhaseTwo_RollbackFailed_Retryable;
}
BranchRollbackResponse response = (BranchRollbackResponse) messageSender.sendSyncRequest(sagaChannel,
request);
return response.getBranchStatus();
} else {
BranchSession branchSession = globalSession.getBranch(branchId);
if (null != branchSession) {
BranchRollbackResponse response = (BranchRollbackResponse) messageSender.sendSyncRequest(resourceId,
branchSession.getClientId(), request);
return response.getBranchStatus();
} else {
return BranchStatus.PhaseTwo_Rollbacked;
}
}
} catch (IOException | TimeoutException e) {
throw new BranchTransactionException(FailedToSendBranchRollbackRequest,
String.format("Send branch rollback failed, xid = %s branchId = %s", xid, branchId), e);
}
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
@Test
public void testReadingEscapedXml() throws Exception {
xmlRecordReader.close();
xmlRecordReader = new XmlRecordReader("website", getDataSource("/websites.xml"));
xmlRecordReader.open();
XmlRecord record = xmlRecordReader.readRecord();
assertThat(record.getPayload()).isXmlEqualTo("<website name=\"google\" url=\"http://www.google.com?query=test&sort=asc\"/>");
record = xmlRecordReader.readRecord();
assertThat(record.getPayload()).isXmlEqualTo("<website name=\"l'equipe\" url=\"http://www.lequipe.fr\"/>");
record = xmlRecordReader.readRecord();
assertThat(record.getPayload()).isXmlEqualTo("<website name=\"l"internaute.com\" url=\"http://www.linternaute.com\"/>");
record = xmlRecordReader.readRecord();
assertThat(record.getPayload()).isXmlEqualTo("<website name=\"google\">http://www.google.com?query=test&sort=asc</website>");
record = xmlRecordReader.readRecord();
assertThat(record.getPayload()).isXmlEqualTo("<website name=\"test\"><test>foo</test></website>");
record = xmlRecordReader.readRecord();
assertThat(record).isNull();
}
#location 16
#vulnerability type NULL_DEREFERENCE
|
#fixed code
@Test
public void testReadingEscapedXml() throws Exception {
// given
xmlRecordReader = new XmlRecordReader("website", getDataSource("/websites.xml"));
xmlRecordReader.open();
// when
XmlRecord record1 = xmlRecordReader.readRecord();
XmlRecord record2 = xmlRecordReader.readRecord();
XmlRecord record3 = xmlRecordReader.readRecord();
XmlRecord record4 = xmlRecordReader.readRecord();
XmlRecord record5 = xmlRecordReader.readRecord();
XmlRecord record6 = xmlRecordReader.readRecord();
// then
assertThat(record1.getPayload()).isXmlEqualTo("<website name=\"google\" url=\"http://www.google.com?query=test&sort=asc\"/>");
assertThat(record2.getPayload()).isXmlEqualTo("<website name=\"l'equipe\" url=\"http://www.lequipe.fr\"/>");
assertThat(record3.getPayload()).isXmlEqualTo("<website name=\"l"internaute.com\" url=\"http://www.linternaute.com\"/>");
assertThat(record4.getPayload()).isXmlEqualTo("<website name=\"google\">http://www.google.com?query=test&sort=asc</website>");
assertThat(record5.getPayload()).isXmlEqualTo("<website name=\"test\"><test>foo</test></website>");
assertThat(record6).isNull();
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
@Before
public void setUp() throws Exception {
when(record.getPayload()).thenReturn(PAYLOAD);
file = new File(JAVA_IO_TMPDIR + FILE_SEPARATOR + "test.txt");
file.createNewFile();
writer = new FileRecordWriter(new FileWriter(file));
}
#location 6
#vulnerability type RESOURCE_LEAK
|
#fixed code
@Before
public void setUp() throws Exception {
Files.createFile(path);
record1 = new StringRecord(header, "foo");
record2 = new StringRecord(header, "bar");
writer = new FileRecordWriter(path);
writer.open();
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
public static void main(String[] args) throws Exception {
//Create queues
BlockingQueue<Record> appleQueue = new LinkedBlockingQueue<Record>();
BlockingQueue<Record> orangeQueue = new LinkedBlockingQueue<Record>();
BlockingQueue<Record> defaultQueue = new LinkedBlockingQueue<Record>();
// Build easy batch engines
Engine engine1 = buildBatchEngine(appleQueue);
Engine engine2 = buildBatchEngine(orangeQueue);
Engine engine3 = buildBatchEngine(defaultQueue);
//create a 3 threads pool to call Easy Batch engines in parallel
ExecutorService executorService = Executors.newFixedThreadPool(3);
//submit workers to executor service
Future<Report> reportFuture1 = executorService.submit(engine1);
Future<Report> reportFuture2 = executorService.submit(engine2);
Future<Report> reportFuture3 = executorService.submit(engine3);
//create a content based record dispatcher to dispatch records to previously created queues
RecordDispatcher recordDispatcher = new ContentBasedRecordDispatcherBuilder()
.when(new AppleRecordPredicate()).dispatchTo(appleQueue)
.when(new OrangeRecordPredicate()).dispatchTo(orangeQueue)
.otherwise(defaultQueue)
.build();
//read data source and dispatch record to queues based on their content
StringRecordReader stringRecordReader = new StringRecordReader("1,apple\n2,orange\n3,banana\n4,apple\n5,pear");
stringRecordReader.open();
while (stringRecordReader.hasNextRecord()) {
Record record = stringRecordReader.readNextRecord();
recordDispatcher.dispatchRecord(record);
}
stringRecordReader.close();
//send poison records when all input data has been dispatched to workers
recordDispatcher.dispatchRecord(new PoisonRecord());
//wait for easy batch instances termination and get partial reports
Report report1 = reportFuture1.get();
Report report2 = reportFuture2.get();
Report report3 = reportFuture3.get();
//merge partial reports into a global one
ReportMerger reportMerger = new DefaultReportMerger();
Report finalReport = reportMerger.mergerReports(report1, report2, report3);
System.out.println(finalReport);
//shutdown executor service
executorService.shutdown();
}
#location 35
#vulnerability type RESOURCE_LEAK
|
#fixed code
public static void main(String[] args) throws Exception {
String fruits = "1,apple\n2,orange\n3,banana\n4,apple\n5,pear";
// Create queues
BlockingQueue<Record> appleQueue = new LinkedBlockingQueue<Record>();
BlockingQueue<Record> orangeQueue = new LinkedBlockingQueue<Record>();
BlockingQueue<Record> defaultQueue = new LinkedBlockingQueue<Record>();
// Create a content based record dispatcher to dispatch records to according queues based on their content
ContentBasedRecordDispatcher recordDispatcher = new ContentBasedRecordDispatcherBuilder()
.when(new AppleRecordPredicate()).dispatchTo(appleQueue)
.when(new OrangeRecordPredicate()).dispatchTo(orangeQueue)
.otherwise(defaultQueue)
.build();
// Build a master engine that will read records from the data source and dispatch them to worker engines
Engine masterEngine = aNewEngine()
.reader(new StringRecordReader(fruits))
.processor(recordDispatcher)
.batchProcessEventListener(new PoisonRecordBroadcaster(recordDispatcher))
.build();
// Build easy batch engines
Engine workerEngine1 = buildWorkerEngine(appleQueue);
Engine workerEngine2 = buildWorkerEngine(orangeQueue);
Engine workerEngine3 = buildWorkerEngine(defaultQueue);
// Create a threads pool to call Easy Batch engines in parallel
ExecutorService executorService = Executors.newFixedThreadPool(THREAD_POOL_SIZE);
// Submit master and worker engines to executor service
executorService.submit(masterEngine);
executorService.submit(workerEngine1);
executorService.submit(workerEngine2);
executorService.submit(workerEngine3);
// Shutdown executor service
executorService.shutdown();
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
public static void main(String[] args) throws Exception {
// Input file tweets.csv
File tweets = new File(args[0]);
//Create queues
BlockingQueue<Record> queue1 = new LinkedBlockingQueue<Record>();
BlockingQueue<Record> queue2 = new LinkedBlockingQueue<Record>();
// Build easy batch engines
Engine engine1 = buildBatchEngine(queue1);
Engine engine2 = buildBatchEngine(queue2);
//create a 2 threads pool to call engines in parallel
ExecutorService executorService = Executors.newFixedThreadPool(THREAD_POOL_SIZE);
//submit workers to executor service
Future<Report> reportFuture1 = executorService.submit(engine1);
Future<Report> reportFuture2 = executorService.submit(engine2);
//create a record dispatcher to dispatch records to previously created queues
RecordDispatcher recordDispatcher = new RoundRobinRecordDispatcher(Arrays.asList(queue1, queue2));
//read data source and dispatch records to queues in round-robin fashion
FlatFileRecordReader flatFileRecordReader = new FlatFileRecordReader(tweets);
flatFileRecordReader.open();
while (flatFileRecordReader.hasNextRecord()) {
Record record = flatFileRecordReader.readNextRecord();
recordDispatcher.dispatchRecord(record);
}
flatFileRecordReader.close();
//send poison records when all input data has been dispatched to workers
recordDispatcher.dispatchRecord(new PoisonRecord());
//wait for easy batch instances termination and get partial reports
Report report1 = reportFuture1.get();
Report report2 = reportFuture2.get();
//merge partial reports into a global one
ReportMerger reportMerger = new DefaultReportMerger();
Report finalReport = reportMerger.mergerReports(report1, report2);
System.out.println(finalReport);
//shutdown executor service
executorService.shutdown();
}
#location 30
#vulnerability type RESOURCE_LEAK
|
#fixed code
public static void main(String[] args) throws Exception {
// Input file tweets.csv
File tweets = new File(args[0]);
// Create queues
BlockingQueue<Record> queue1 = new LinkedBlockingQueue<Record>();
BlockingQueue<Record> queue2 = new LinkedBlockingQueue<Record>();
// Create a round robin record dispatcher that will be used to distribute records to worker engines
RoundRobinRecordDispatcher roundRobinRecordDispatcher = new RoundRobinRecordDispatcher(Arrays.asList(queue1, queue2));
// Build a master engine that will read records from the data source and dispatch them to worker engines
Engine masterEngine = aNewEngine()
.reader(new FlatFileRecordReader(tweets))
.processor(roundRobinRecordDispatcher)
.batchProcessEventListener(new PoisonRecordBroadcaster(roundRobinRecordDispatcher))
.build();
// Build worker engines
Engine workerEngine1 = buildWorkerEngine(queue1);
Engine workerEngine2 = buildWorkerEngine(queue2);
// Create a thread pool to call master and worker engines in parallel
ExecutorService executorService = Executors.newFixedThreadPool(THREAD_POOL_SIZE);
// Submit workers to executor service
executorService.submit(masterEngine);
executorService.submit(workerEngine1);
executorService.submit(workerEngine2);
// Shutdown executor service
executorService.shutdown();
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
public void configure() throws BatchConfigurationException {
/*
* Configure CB4J logger
*/
logger.setUseParentHandlers(false);
ConsoleHandler consoleHandler = new ConsoleHandler();
consoleHandler.setFormatter(new LogFormatter());
logger.addHandler(consoleHandler);
logger.info("Configuration started at : " + new Date());
/*
* Configure record reader parameters
*/
String inputData = configurationProperties.getProperty(BatchConstants.INPUT_DATA_PATH);
String encoding = configurationProperties.getProperty(BatchConstants.INPUT_DATA_ENCODING);
final String skipHeaderProperty = configurationProperties.getProperty(BatchConstants.INPUT_DATA_SKIP_HEADER);
//check if input data file is specified
if (inputData == null) {
String error = "Configuration failed : input data file is mandatory but was not specified";
logger.severe(error);
throw new BatchConfigurationException(error);
}
try {
boolean skipHeader;
if (skipHeaderProperty != null) {
skipHeader = Boolean.valueOf(skipHeaderProperty);
} else {
skipHeader = BatchConstants.DEFAULT_SKIP_HEADER;
logger.warning("Skip header property not specified, default to false");
}
if (encoding == null || (encoding != null && encoding.length() == 0)) {
encoding = System.getProperty("file.encoding");
logger.warning("No encoding specified for input data, using system default encoding : " + encoding);
} else {
if (Charset.availableCharsets().get(encoding) != null && !Charset.isSupported(encoding)) {
logger.warning("Encoding '" + encoding + "' not supported, using system default encoding : " + System.getProperty("file.encoding"));
encoding = System.getProperty("file.encoding");
} else {
logger.config("Using '" + encoding + "' encoding for input file reading");
}
}
recordReader = new RecordReaderImpl(inputData, encoding, skipHeader);
logger.config("Data input file : " + inputData);
} catch (FileNotFoundException e) {
String error = "Configuration failed : input data file '" + inputData + "' could not be opened";
logger.severe(error);
throw new BatchConfigurationException(error);
}
/*
* Configure record parser parameters
* Convention over configuration : default separator is ","
*/
String recordSizeProperty = configurationProperties.getProperty(BatchConstants.INPUT_RECORD_SIZE);
try {
if (recordSizeProperty == null || (recordSizeProperty != null && recordSizeProperty.length() == 0)) {
String error = "Record size property is not set";
logger.severe(error);
throw new BatchConfigurationException(error);
}
int recordSize = Integer.parseInt(recordSizeProperty);
String fieldsSeparator = configurationProperties.getProperty(BatchConstants.INPUT_FIELD_SEPARATOR);
if (fieldsSeparator == null || (fieldsSeparator != null && fieldsSeparator.length() == 0)) {
fieldsSeparator = BatchConstants.DEFAULT_FIELD_SEPARATOR;
logger.warning("No field separator specified, using default : '" + fieldsSeparator + "'");
}
logger.config("Record size specified : " + recordSize);
logger.config("Fields separator specified : '" + fieldsSeparator + "'");
recordParser = new RecordParserImpl(recordSize, fieldsSeparator);
} catch (NumberFormatException e) {
String error = "Record size property is not recognized as a number : " + recordSizeProperty;
logger.severe(error);
throw new BatchConfigurationException(error);
}
/*
* Configure loggers for ignored/rejected records
*/
ReportFormatter reportFormatter = new ReportFormatter();
String outputIgnored = configurationProperties.getProperty(BatchConstants.OUTPUT_DATA_IGNORED);
if (outputIgnored == null || (outputIgnored != null && outputIgnored.length() == 0)) {
outputIgnored = BatchConfigurationUtil.removeExtension(inputData) + BatchConstants.DEFAULT_IGNORED_SUFFIX;
logger.warning("No log file specified for ignored records, using default : " + outputIgnored);
}
try {
FileHandler ignoredRecordsHandler = new FileHandler(outputIgnored);
ignoredRecordsHandler.setFormatter(reportFormatter);
Logger ignoredRecordsReporter = Logger.getLogger(BatchConstants.LOGGER_CB4J_IGNORED);
ignoredRecordsReporter.addHandler(ignoredRecordsHandler);
} catch (IOException e) {
String error = "Unable to use file for ignored records : " + outputIgnored;
logger.severe(error);
throw new BatchConfigurationException(error);
}
String outputRejected = configurationProperties.getProperty(BatchConstants.OUTPUT_DATA_REJECTED);
if (outputRejected == null || (outputRejected != null && outputRejected.length() == 0)) {
outputRejected = BatchConfigurationUtil.removeExtension(inputData) + BatchConstants.DEFAULT_REJECTED_SUFFIX;
logger.warning("No log file specified for rejected records, using default : " + outputRejected);
}
try {
FileHandler rejectedRecordsHandler = new FileHandler(outputRejected);
rejectedRecordsHandler.setFormatter(reportFormatter);
Logger rejectedRecordsReporter = Logger.getLogger(BatchConstants.LOGGER_CB4J_REJECTED);
rejectedRecordsReporter.addHandler(rejectedRecordsHandler);
} catch (IOException e) {
String error = "Unable to use file for rejected records : " + outputRejected;
logger.severe(error);
throw new BatchConfigurationException(error);
}
/*
* Configure batch reporter : if no custom reporter registered, use default implementation
*/
if (batchReporter == null) {
batchReporter = new DefaultBatchReporterImpl();
}
/*
* Configure record validator with provided validators : : if no custom validator registered, use default implementation
*/
if (recordValidator == null) {
recordValidator = new DefaultRecordValidatorImpl(fieldValidators);
}
/*
* Check record mapper
*/
if (recordMapper == null) {
String error = "Configuration failed : no record mapper registered";
logger.severe(error);
throw new BatchConfigurationException(error);
}
/*
* Check record processor
*/
if (recordProcessor == null) {
String error = "Configuration failed : no record processor registered";
logger.severe(error);
throw new BatchConfigurationException(error);
}
/*
* Configure JMX MBean
*/
MBeanServer mbs = ManagementFactory.getPlatformMBeanServer();
ObjectName name;
try {
name = new ObjectName("net.benas.cb4j.jmx:type=BatchMonitorMBean");
BatchMonitorMBean batchMonitorMBean = new BatchMonitor(batchReporter);
mbs.registerMBean(batchMonitorMBean, name);
logger.info("CB4J JMX MBean registered successfully as: " + name.getCanonicalName());
} catch (Exception e) {
String error = "Unable to register CB4J JMX MBean. Root exception is :" + e.getMessage();
logger.warning(error);
}
logger.info("Configuration successful");
logger.info("Configuration parameters details : " + configurationProperties);
}
#location 48
#vulnerability type RESOURCE_LEAK
|
#fixed code
public void configure() throws BatchConfigurationException {
/*
* Configure CB4J logger
*/
configureCB4JLogger();
logger.info("Configuration started at : " + new Date());
/*
* Configure record reader
*/
configureRecordReader();
/*
* Configure record parser
*/
configureRecordParser();
/*
* Configure loggers for ignored/rejected records
*/
configureIgnoredAndRejectedRecordsLoggers();
/*
* Configure batch reporter : if no custom reporter registered, use default implementation
*/
if (batchReporter == null) {
batchReporter = new DefaultBatchReporterImpl();
}
/*
* Configure record validator with provided validators : if no custom validator registered, use default implementation
*/
if (recordValidator == null) {
recordValidator = new DefaultRecordValidatorImpl(fieldValidators);
}
/*
* Check record mapper
*/
if (recordMapper == null) {
String error = "Configuration failed : no record mapper registered";
logger.severe(error);
throw new BatchConfigurationException(error);
}
/*
* Check record processor
*/
if (recordProcessor == null) {
String error = "Configuration failed : no record processor registered";
logger.severe(error);
throw new BatchConfigurationException(error);
}
/*
* register JMX MBean
*/
configureJmxMBean();
logger.info("Configuration successful");
logger.info("Configuration parameters details : " + configurationProperties);
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
@Override
public void open() throws Exception {
currentRecordNumber = 0;
scanner = new Scanner(new FileInputStream(input), charsetName);
}
#location 4
#vulnerability type RESOURCE_LEAK
|
#fixed code
@Override
public void open() throws Exception {
currentRecordNumber = 0;
scanner = new Scanner(input, charsetName);
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
public static void main(String[] args) throws Exception {
// Input file tweets.csv
File tweets = new File(args[0]);
//Create queues
BlockingQueue<Record> queue1 = new LinkedBlockingQueue<Record>();
BlockingQueue<Record> queue2 = new LinkedBlockingQueue<Record>();
// Build easy batch engines
Engine engine1 = buildBatchEngine(queue1);
Engine engine2 = buildBatchEngine(queue2);
//create a 2 threads pool to call engines in parallel
ExecutorService executorService = Executors.newFixedThreadPool(THREAD_POOL_SIZE);
//submit workers to executor service
Future<Report> reportFuture1 = executorService.submit(engine1);
Future<Report> reportFuture2 = executorService.submit(engine2);
//create a record dispatcher to dispatch records to previously created queues
RecordDispatcher recordDispatcher = new RoundRobinRecordDispatcher(Arrays.asList(queue1, queue2));
//read data source and dispatch records to queues in round-robin fashion
FlatFileRecordReader flatFileRecordReader = new FlatFileRecordReader(tweets);
flatFileRecordReader.open();
while (flatFileRecordReader.hasNextRecord()) {
Record record = flatFileRecordReader.readNextRecord();
recordDispatcher.dispatchRecord(record);
}
flatFileRecordReader.close();
//send poison records when all input data has been dispatched to workers
recordDispatcher.dispatchRecord(new PoisonRecord());
//wait for easy batch instances termination and get partial reports
Report report1 = reportFuture1.get();
Report report2 = reportFuture2.get();
//merge partial reports into a global one
ReportMerger reportMerger = new DefaultReportMerger();
Report finalReport = reportMerger.mergerReports(report1, report2);
System.out.println(finalReport);
//shutdown executor service
executorService.shutdown();
}
#location 31
#vulnerability type RESOURCE_LEAK
|
#fixed code
public static void main(String[] args) throws Exception {
// Input file tweets.csv
File tweets = new File(args[0]);
// Create queues
BlockingQueue<Record> queue1 = new LinkedBlockingQueue<Record>();
BlockingQueue<Record> queue2 = new LinkedBlockingQueue<Record>();
// Create a round robin record dispatcher that will be used to distribute records to worker engines
RoundRobinRecordDispatcher roundRobinRecordDispatcher = new RoundRobinRecordDispatcher(Arrays.asList(queue1, queue2));
// Build a master engine that will read records from the data source and dispatch them to worker engines
Engine masterEngine = aNewEngine()
.reader(new FlatFileRecordReader(tweets))
.processor(roundRobinRecordDispatcher)
.batchProcessEventListener(new PoisonRecordBroadcaster(roundRobinRecordDispatcher))
.build();
// Build worker engines
Engine workerEngine1 = buildWorkerEngine(queue1);
Engine workerEngine2 = buildWorkerEngine(queue2);
// Create a thread pool to call master and worker engines in parallel
ExecutorService executorService = Executors.newFixedThreadPool(THREAD_POOL_SIZE);
// Submit workers to executor service
executorService.submit(masterEngine);
executorService.submit(workerEngine1);
executorService.submit(workerEngine2);
// Shutdown executor service
executorService.shutdown();
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
@Test
public void integrationTest() throws Exception {
File inputTweets = new File(this.getClass().getResource("/tweets-in.xls").toURI());
File outputTweets = new File(this.getClass().getResource("/tweets-out.xls").toURI());
Job job = JobBuilder.aNewJob()
.reader(new MsExcelRecordReader(inputTweets))
.mapper(new MsExcelRecordMapper(Tweet.class, "id", "user", "message"))
.marshaller(new MsExcelRecordMarshaller<>(Tweet.class, "id", "user", "message"))
.writer(new MsExcelRecordWriter(outputTweets, SHEET_NAME))
.build();
JobReport report = JobExecutor.execute(job);
assertThat(report).isNotNull();
assertThat(report.getMetrics().getTotalCount()).isEqualTo(2);
assertThat(report.getMetrics().getSuccessCount()).isEqualTo(2);
assertThat(report.getStatus()).isEqualTo(JobStatus.COMPLETED);
HSSFWorkbook workbook = new HSSFWorkbook(new FileInputStream(outputTweets));
HSSFSheet sheet = workbook.getSheet(SHEET_NAME);
HSSFRow firstRow = sheet.getRow(1);
assertThat(firstRow.getCell(0).getNumericCellValue()).isEqualTo(1.0);
assertThat(firstRow.getCell(1).getStringCellValue()).isEqualTo("foo");
assertThat(firstRow.getCell(2).getStringCellValue()).isEqualTo("hi");
HSSFRow secondRow = sheet.getRow(2);
assertThat(secondRow.getCell(0).getNumericCellValue()).isEqualTo(2.0);
assertThat(secondRow.getCell(1).getStringCellValue()).isEqualTo("bar");
assertThat(secondRow.getCell(2).getStringCellValue()).isEqualTo("hello");
}
#location 22
#vulnerability type RESOURCE_LEAK
|
#fixed code
@Test
public void integrationTest() throws Exception {
File inputTweets = new File(this.getClass().getResource("/tweets-in.xlsx").toURI());
File outputTweets = new File(this.getClass().getResource("/tweets-out.xlsx").toURI());
Job job = JobBuilder.aNewJob()
.reader(new MsExcelRecordReader(inputTweets))
.mapper(new MsExcelRecordMapper(Tweet.class, "id", "user", "message"))
.marshaller(new MsExcelRecordMarshaller<>(Tweet.class, "id", "user", "message"))
.writer(new MsExcelRecordWriter(outputTweets, SHEET_NAME))
.build();
JobReport report = JobExecutor.execute(job);
assertThat(report).isNotNull();
assertThat(report.getMetrics().getTotalCount()).isEqualTo(2);
assertThat(report.getMetrics().getSuccessCount()).isEqualTo(2);
assertThat(report.getStatus()).isEqualTo(JobStatus.COMPLETED);
XSSFWorkbook workbook = new XSSFWorkbook(new FileInputStream(outputTweets));
XSSFSheet sheet = workbook.getSheet(SHEET_NAME);
XSSFRow row = sheet.getRow(1);
assertThat(row.getCell(0).getNumericCellValue()).isEqualTo(1.0);
assertThat(row.getCell(1).getStringCellValue()).isEqualTo("foo");
assertThat(row.getCell(2).getStringCellValue()).isEqualTo("hi");
row = sheet.getRow(2);
assertThat(row.getCell(0).getNumericCellValue()).isEqualTo(2.0);
assertThat(row.getCell(1).getStringCellValue()).isEqualTo("bar");
assertThat(row.getCell(2).getStringCellValue()).isEqualTo("hello");
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
@Test
public void testXmlRecordReading() throws Exception {
String expectedDataSourceName = dataSource.getAbsolutePath();
XmlRecord xmlRecord = xmlFileRecordReader.readRecord();
assertThat(xmlRecord.getHeader().getNumber()).isEqualTo(1L);
assertThat(xmlRecord.getHeader().getSource()).isEqualTo(expectedDataSourceName);
assertThat(xmlRecord.getPayload()).isEqualTo("<data>1</data>");
xmlRecord = xmlFileRecordReader.readRecord();
assertThat(xmlRecord.getHeader().getNumber()).isEqualTo(2L);
assertThat(xmlRecord.getHeader().getSource()).isEqualTo(expectedDataSourceName);
assertThat(xmlRecord.getPayload()).isEqualTo("<data>2</data>");
xmlRecord = xmlFileRecordReader.readRecord();
assertThat(xmlRecord.getHeader().getNumber()).isEqualTo(3L);
assertThat(xmlRecord.getHeader().getSource()).isEqualTo(expectedDataSourceName);
assertThat(xmlRecord.getPayload()).isEqualTo("<data>3</data>");
xmlRecord = xmlFileRecordReader.readRecord();
assertThat(xmlRecord.getHeader().getNumber()).isEqualTo(4L);
assertThat(xmlRecord.getHeader().getSource()).isEqualTo(expectedDataSourceName);
assertThat(xmlRecord.getPayload()).isEqualTo("<data>4</data>");
xmlRecord = xmlFileRecordReader.readRecord();
assertThat(xmlRecord.getHeader().getNumber()).isEqualTo(5L);
assertThat(xmlRecord.getHeader().getSource()).isEqualTo(expectedDataSourceName);
assertThat(xmlRecord.getPayload()).isEqualTo("<data>5</data>");
xmlRecord = xmlFileRecordReader.readRecord();
assertThat(xmlRecord).isNull();
}
#location 26
#vulnerability type NULL_DEREFERENCE
|
#fixed code
@Test
public void testXmlRecordReading() throws Exception {
// given
dataSource = new File("src/test/resources/data.xml");
xmlFileRecordReader = new XmlFileRecordReader(dataSource, "data");
xmlFileRecordReader.open();
String expectedDataSourceName = dataSource.getAbsolutePath();
// when
XmlRecord xmlRecord1 = xmlFileRecordReader.readRecord();
XmlRecord xmlRecord2 = xmlFileRecordReader.readRecord();
XmlRecord xmlRecord3 = xmlFileRecordReader.readRecord();
XmlRecord xmlRecord4 = xmlFileRecordReader.readRecord();
// then
assertThat(xmlRecord1.getHeader().getNumber()).isEqualTo(1L);
assertThat(xmlRecord1.getHeader().getSource()).isEqualTo(expectedDataSourceName);
assertThat(xmlRecord1.getPayload()).isEqualTo("<data>1</data>");
assertThat(xmlRecord2.getHeader().getNumber()).isEqualTo(2L);
assertThat(xmlRecord2.getHeader().getSource()).isEqualTo(expectedDataSourceName);
assertThat(xmlRecord2.getPayload()).isEqualTo("<data>2</data>");
assertThat(xmlRecord3.getHeader().getNumber()).isEqualTo(3L);
assertThat(xmlRecord3.getHeader().getSource()).isEqualTo(expectedDataSourceName);
assertThat(xmlRecord3.getPayload()).isEqualTo("<data>3</data>");
assertThat(xmlRecord4).isNull();
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
@Override
public StringRecord processRecord(final Record<P> record) throws Exception {
StringWriter stringWriter = new StringWriter();
CSVPrinter csvPrinter = new CSVPrinter(stringWriter, csvFormat);
Iterable<Object> iterable = fieldExtractor.extractFields(record.getPayload());
csvPrinter.printRecord(iterable);
csvPrinter.flush();
return new StringRecord(record.getHeader(), stringWriter.toString());
}
#location 7
#vulnerability type RESOURCE_LEAK
|
#fixed code
@Override
public StringRecord processRecord(final Record<P> record) throws Exception {
StringWriter stringWriter = new StringWriter();
CSVPrinter csvPrinter = new CSVPrinter(stringWriter, csvFormat);
Iterable<Object> iterable = fieldExtractor.extractFields(record.getPayload());
csvPrinter.printRecord(iterable);
csvPrinter.flush();
csvPrinter.close();
return new StringRecord(record.getHeader(), stringWriter.toString());
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
@Test
public void testReadingXmlWithCustomNamespace() throws Exception {
xmlRecordReader.close();
xmlRecordReader = new XmlRecordReader("bean", getDataSource("/beans.xml"));
xmlRecordReader.open();
XmlRecord record = xmlRecordReader.readRecord();
assertThat(record.getPayload()).isXmlEqualTo("<bean id=\"foo\" class=\"java.lang.String\"><description>foo bean</description></bean>");
record = xmlRecordReader.readRecord();
assertThat(record.getPayload()).isXmlEqualTo("<bean id=\"bar\" class=\"java.lang.String\"/>");
record = xmlRecordReader.readRecord();
assertThat(record).isNull();
}
#location 11
#vulnerability type NULL_DEREFERENCE
|
#fixed code
@Test
public void testReadingXmlWithCustomNamespace() throws Exception {
// given
xmlRecordReader = new XmlRecordReader("bean", getDataSource("/beans.xml"));
xmlRecordReader.open();
// when
XmlRecord record1 = xmlRecordReader.readRecord();
XmlRecord record2 = xmlRecordReader.readRecord();
XmlRecord record3 = xmlRecordReader.readRecord();
// then
assertThat(record1.getPayload()).isXmlEqualTo("<bean id=\"foo\" class=\"java.lang.String\"><description>foo bean</description></bean>");
assertThat(record2.getPayload()).isXmlEqualTo("<bean id=\"bar\" class=\"java.lang.String\"/>");
assertThat(record3).isNull();
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
@Test
public void testReadingEscapedXml() throws Exception {
xmlRecordReader.close();
xmlRecordReader = new XmlRecordReader("website", getDataSource("/websites.xml"));
xmlRecordReader.open();
XmlRecord record = xmlRecordReader.readRecord();
assertThat(record.getPayload()).isXmlEqualTo("<website name=\"google\" url=\"http://www.google.com?query=test&sort=asc\"/>");
record = xmlRecordReader.readRecord();
assertThat(record.getPayload()).isXmlEqualTo("<website name=\"l'equipe\" url=\"http://www.lequipe.fr\"/>");
record = xmlRecordReader.readRecord();
assertThat(record.getPayload()).isXmlEqualTo("<website name=\"l"internaute.com\" url=\"http://www.linternaute.com\"/>");
record = xmlRecordReader.readRecord();
assertThat(record.getPayload()).isXmlEqualTo("<website name=\"google\">http://www.google.com?query=test&sort=asc</website>");
record = xmlRecordReader.readRecord();
assertThat(record.getPayload()).isXmlEqualTo("<website name=\"test\"><test>foo</test></website>");
record = xmlRecordReader.readRecord();
assertThat(record).isNull();
}
#location 19
#vulnerability type NULL_DEREFERENCE
|
#fixed code
@Test
public void testReadingEscapedXml() throws Exception {
// given
xmlRecordReader = new XmlRecordReader("website", getDataSource("/websites.xml"));
xmlRecordReader.open();
// when
XmlRecord record1 = xmlRecordReader.readRecord();
XmlRecord record2 = xmlRecordReader.readRecord();
XmlRecord record3 = xmlRecordReader.readRecord();
XmlRecord record4 = xmlRecordReader.readRecord();
XmlRecord record5 = xmlRecordReader.readRecord();
XmlRecord record6 = xmlRecordReader.readRecord();
// then
assertThat(record1.getPayload()).isXmlEqualTo("<website name=\"google\" url=\"http://www.google.com?query=test&sort=asc\"/>");
assertThat(record2.getPayload()).isXmlEqualTo("<website name=\"l'equipe\" url=\"http://www.lequipe.fr\"/>");
assertThat(record3.getPayload()).isXmlEqualTo("<website name=\"l"internaute.com\" url=\"http://www.linternaute.com\"/>");
assertThat(record4.getPayload()).isXmlEqualTo("<website name=\"google\">http://www.google.com?query=test&sort=asc</website>");
assertThat(record5.getPayload()).isXmlEqualTo("<website name=\"test\"><test>foo</test></website>");
assertThat(record6).isNull();
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
@Test
public void testXmlRecordReading() throws Exception {
String expectedDataSourceName = dataSource.getAbsolutePath();
XmlRecord xmlRecord = xmlFileRecordReader.readRecord();
assertThat(xmlRecord.getHeader().getNumber()).isEqualTo(1L);
assertThat(xmlRecord.getHeader().getSource()).isEqualTo(expectedDataSourceName);
assertThat(xmlRecord.getPayload()).isEqualTo("<data>1</data>");
xmlRecord = xmlFileRecordReader.readRecord();
assertThat(xmlRecord.getHeader().getNumber()).isEqualTo(2L);
assertThat(xmlRecord.getHeader().getSource()).isEqualTo(expectedDataSourceName);
assertThat(xmlRecord.getPayload()).isEqualTo("<data>2</data>");
xmlRecord = xmlFileRecordReader.readRecord();
assertThat(xmlRecord.getHeader().getNumber()).isEqualTo(3L);
assertThat(xmlRecord.getHeader().getSource()).isEqualTo(expectedDataSourceName);
assertThat(xmlRecord.getPayload()).isEqualTo("<data>3</data>");
xmlRecord = xmlFileRecordReader.readRecord();
assertThat(xmlRecord.getHeader().getNumber()).isEqualTo(4L);
assertThat(xmlRecord.getHeader().getSource()).isEqualTo(expectedDataSourceName);
assertThat(xmlRecord.getPayload()).isEqualTo("<data>4</data>");
xmlRecord = xmlFileRecordReader.readRecord();
assertThat(xmlRecord.getHeader().getNumber()).isEqualTo(5L);
assertThat(xmlRecord.getHeader().getSource()).isEqualTo(expectedDataSourceName);
assertThat(xmlRecord.getPayload()).isEqualTo("<data>5</data>");
xmlRecord = xmlFileRecordReader.readRecord();
assertThat(xmlRecord).isNull();
}
#location 16
#vulnerability type NULL_DEREFERENCE
|
#fixed code
@Test
public void testXmlRecordReading() throws Exception {
// given
dataSource = new File("src/test/resources/data.xml");
xmlFileRecordReader = new XmlFileRecordReader(dataSource, "data");
xmlFileRecordReader.open();
String expectedDataSourceName = dataSource.getAbsolutePath();
// when
XmlRecord xmlRecord1 = xmlFileRecordReader.readRecord();
XmlRecord xmlRecord2 = xmlFileRecordReader.readRecord();
XmlRecord xmlRecord3 = xmlFileRecordReader.readRecord();
XmlRecord xmlRecord4 = xmlFileRecordReader.readRecord();
// then
assertThat(xmlRecord1.getHeader().getNumber()).isEqualTo(1L);
assertThat(xmlRecord1.getHeader().getSource()).isEqualTo(expectedDataSourceName);
assertThat(xmlRecord1.getPayload()).isEqualTo("<data>1</data>");
assertThat(xmlRecord2.getHeader().getNumber()).isEqualTo(2L);
assertThat(xmlRecord2.getHeader().getSource()).isEqualTo(expectedDataSourceName);
assertThat(xmlRecord2.getPayload()).isEqualTo("<data>2</data>");
assertThat(xmlRecord3.getHeader().getNumber()).isEqualTo(3L);
assertThat(xmlRecord3.getHeader().getSource()).isEqualTo(expectedDataSourceName);
assertThat(xmlRecord3.getPayload()).isEqualTo("<data>3</data>");
assertThat(xmlRecord4).isNull();
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
@Test
public void testRecordLimit() throws Exception {
List<String> dataSource = Arrays.asList("foo", "bar", "baz");
JobReport jobReport = aNewJob()
.reader(new IterableRecordReader(dataSource))
.limit(2)
.processor(new RecordCollector())
.call();
assertThat(jobReport.getMetrics().getTotalCount()).isEqualTo(2);
assertThat(jobReport.getMetrics().getSuccessCount()).isEqualTo(2);
List<GenericRecord> records = (List<GenericRecord>) jobReport.getResult();
assertThat(records).isNotNull().hasSize(2);
assertThat(records.get(0).getPayload()).isNotNull().isEqualTo("foo");
assertThat(records.get(1).getPayload()).isNotNull().isEqualTo("bar");
}
#location 17
#vulnerability type NULL_DEREFERENCE
|
#fixed code
@Test
public void testRecordLimit() throws Exception {
List<String> dataSource = Arrays.asList("foo", "bar", "baz");
JobReport jobReport = aNewJob()
.reader(new IterableRecordReader(dataSource))
.limit(2)
.processor(new RecordCollector())
.call();
assertThat(jobReport.getMetrics().getTotalCount()).isEqualTo(2);
assertThat(jobReport.getMetrics().getSuccessCount()).isEqualTo(2);
List<GenericRecord> records = (List<GenericRecord>) jobReport.getResult();
assertThat(records).extracting("payload").containsExactly("foo", "bar");
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
@Test
public void testReadingEscapedXml() throws Exception {
xmlRecordReader.close();
xmlRecordReader = new XmlRecordReader("website", getDataSource("/websites.xml"));
xmlRecordReader.open();
XmlRecord record = xmlRecordReader.readRecord();
assertThat(record.getPayload()).isXmlEqualTo("<website name=\"google\" url=\"http://www.google.com?query=test&sort=asc\"/>");
record = xmlRecordReader.readRecord();
assertThat(record.getPayload()).isXmlEqualTo("<website name=\"l'equipe\" url=\"http://www.lequipe.fr\"/>");
record = xmlRecordReader.readRecord();
assertThat(record.getPayload()).isXmlEqualTo("<website name=\"l"internaute.com\" url=\"http://www.linternaute.com\"/>");
record = xmlRecordReader.readRecord();
assertThat(record.getPayload()).isXmlEqualTo("<website name=\"google\">http://www.google.com?query=test&sort=asc</website>");
record = xmlRecordReader.readRecord();
assertThat(record.getPayload()).isXmlEqualTo("<website name=\"test\"><test>foo</test></website>");
record = xmlRecordReader.readRecord();
assertThat(record).isNull();
}
#location 13
#vulnerability type NULL_DEREFERENCE
|
#fixed code
@Test
public void testReadingEscapedXml() throws Exception {
// given
xmlRecordReader = new XmlRecordReader("website", getDataSource("/websites.xml"));
xmlRecordReader.open();
// when
XmlRecord record1 = xmlRecordReader.readRecord();
XmlRecord record2 = xmlRecordReader.readRecord();
XmlRecord record3 = xmlRecordReader.readRecord();
XmlRecord record4 = xmlRecordReader.readRecord();
XmlRecord record5 = xmlRecordReader.readRecord();
XmlRecord record6 = xmlRecordReader.readRecord();
// then
assertThat(record1.getPayload()).isXmlEqualTo("<website name=\"google\" url=\"http://www.google.com?query=test&sort=asc\"/>");
assertThat(record2.getPayload()).isXmlEqualTo("<website name=\"l'equipe\" url=\"http://www.lequipe.fr\"/>");
assertThat(record3.getPayload()).isXmlEqualTo("<website name=\"l"internaute.com\" url=\"http://www.linternaute.com\"/>");
assertThat(record4.getPayload()).isXmlEqualTo("<website name=\"google\">http://www.google.com?query=test&sort=asc</website>");
assertThat(record5.getPayload()).isXmlEqualTo("<website name=\"test\"><test>foo</test></website>");
assertThat(record6).isNull();
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
@Test
public void testXmlRecordReading() throws Exception {
String expectedDataSourceName = dataSource.getAbsolutePath();
XmlRecord xmlRecord = xmlFileRecordReader.readRecord();
assertThat(xmlRecord.getHeader().getNumber()).isEqualTo(1L);
assertThat(xmlRecord.getHeader().getSource()).isEqualTo(expectedDataSourceName);
assertThat(xmlRecord.getPayload()).isEqualTo("<data>1</data>");
xmlRecord = xmlFileRecordReader.readRecord();
assertThat(xmlRecord.getHeader().getNumber()).isEqualTo(2L);
assertThat(xmlRecord.getHeader().getSource()).isEqualTo(expectedDataSourceName);
assertThat(xmlRecord.getPayload()).isEqualTo("<data>2</data>");
xmlRecord = xmlFileRecordReader.readRecord();
assertThat(xmlRecord.getHeader().getNumber()).isEqualTo(3L);
assertThat(xmlRecord.getHeader().getSource()).isEqualTo(expectedDataSourceName);
assertThat(xmlRecord.getPayload()).isEqualTo("<data>3</data>");
xmlRecord = xmlFileRecordReader.readRecord();
assertThat(xmlRecord.getHeader().getNumber()).isEqualTo(4L);
assertThat(xmlRecord.getHeader().getSource()).isEqualTo(expectedDataSourceName);
assertThat(xmlRecord.getPayload()).isEqualTo("<data>4</data>");
xmlRecord = xmlFileRecordReader.readRecord();
assertThat(xmlRecord.getHeader().getNumber()).isEqualTo(5L);
assertThat(xmlRecord.getHeader().getSource()).isEqualTo(expectedDataSourceName);
assertThat(xmlRecord.getPayload()).isEqualTo("<data>5</data>");
xmlRecord = xmlFileRecordReader.readRecord();
assertThat(xmlRecord).isNull();
}
#location 6
#vulnerability type NULL_DEREFERENCE
|
#fixed code
@Test
public void testXmlRecordReading() throws Exception {
// given
dataSource = new File("src/test/resources/data.xml");
xmlFileRecordReader = new XmlFileRecordReader(dataSource, "data");
xmlFileRecordReader.open();
String expectedDataSourceName = dataSource.getAbsolutePath();
// when
XmlRecord xmlRecord1 = xmlFileRecordReader.readRecord();
XmlRecord xmlRecord2 = xmlFileRecordReader.readRecord();
XmlRecord xmlRecord3 = xmlFileRecordReader.readRecord();
XmlRecord xmlRecord4 = xmlFileRecordReader.readRecord();
// then
assertThat(xmlRecord1.getHeader().getNumber()).isEqualTo(1L);
assertThat(xmlRecord1.getHeader().getSource()).isEqualTo(expectedDataSourceName);
assertThat(xmlRecord1.getPayload()).isEqualTo("<data>1</data>");
assertThat(xmlRecord2.getHeader().getNumber()).isEqualTo(2L);
assertThat(xmlRecord2.getHeader().getSource()).isEqualTo(expectedDataSourceName);
assertThat(xmlRecord2.getPayload()).isEqualTo("<data>2</data>");
assertThat(xmlRecord3.getHeader().getNumber()).isEqualTo(3L);
assertThat(xmlRecord3.getHeader().getSource()).isEqualTo(expectedDataSourceName);
assertThat(xmlRecord3.getPayload()).isEqualTo("<data>3</data>");
assertThat(xmlRecord4).isNull();
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
@Test
public void testXmlRecordReading() throws Exception {
String expectedDataSourceName = dataSource.getAbsolutePath();
XmlRecord xmlRecord = xmlFileRecordReader.readRecord();
assertThat(xmlRecord.getHeader().getNumber()).isEqualTo(1L);
assertThat(xmlRecord.getHeader().getSource()).isEqualTo(expectedDataSourceName);
assertThat(xmlRecord.getPayload()).isEqualTo("<data>1</data>");
xmlRecord = xmlFileRecordReader.readRecord();
assertThat(xmlRecord.getHeader().getNumber()).isEqualTo(2L);
assertThat(xmlRecord.getHeader().getSource()).isEqualTo(expectedDataSourceName);
assertThat(xmlRecord.getPayload()).isEqualTo("<data>2</data>");
xmlRecord = xmlFileRecordReader.readRecord();
assertThat(xmlRecord.getHeader().getNumber()).isEqualTo(3L);
assertThat(xmlRecord.getHeader().getSource()).isEqualTo(expectedDataSourceName);
assertThat(xmlRecord.getPayload()).isEqualTo("<data>3</data>");
xmlRecord = xmlFileRecordReader.readRecord();
assertThat(xmlRecord.getHeader().getNumber()).isEqualTo(4L);
assertThat(xmlRecord.getHeader().getSource()).isEqualTo(expectedDataSourceName);
assertThat(xmlRecord.getPayload()).isEqualTo("<data>4</data>");
xmlRecord = xmlFileRecordReader.readRecord();
assertThat(xmlRecord.getHeader().getNumber()).isEqualTo(5L);
assertThat(xmlRecord.getHeader().getSource()).isEqualTo(expectedDataSourceName);
assertThat(xmlRecord.getPayload()).isEqualTo("<data>5</data>");
xmlRecord = xmlFileRecordReader.readRecord();
assertThat(xmlRecord).isNull();
}
#location 21
#vulnerability type NULL_DEREFERENCE
|
#fixed code
@Test
public void testXmlRecordReading() throws Exception {
// given
dataSource = new File("src/test/resources/data.xml");
xmlFileRecordReader = new XmlFileRecordReader(dataSource, "data");
xmlFileRecordReader.open();
String expectedDataSourceName = dataSource.getAbsolutePath();
// when
XmlRecord xmlRecord1 = xmlFileRecordReader.readRecord();
XmlRecord xmlRecord2 = xmlFileRecordReader.readRecord();
XmlRecord xmlRecord3 = xmlFileRecordReader.readRecord();
XmlRecord xmlRecord4 = xmlFileRecordReader.readRecord();
// then
assertThat(xmlRecord1.getHeader().getNumber()).isEqualTo(1L);
assertThat(xmlRecord1.getHeader().getSource()).isEqualTo(expectedDataSourceName);
assertThat(xmlRecord1.getPayload()).isEqualTo("<data>1</data>");
assertThat(xmlRecord2.getHeader().getNumber()).isEqualTo(2L);
assertThat(xmlRecord2.getHeader().getSource()).isEqualTo(expectedDataSourceName);
assertThat(xmlRecord2.getPayload()).isEqualTo("<data>2</data>");
assertThat(xmlRecord3.getHeader().getNumber()).isEqualTo(3L);
assertThat(xmlRecord3.getHeader().getSource()).isEqualTo(expectedDataSourceName);
assertThat(xmlRecord3.getPayload()).isEqualTo("<data>3</data>");
assertThat(xmlRecord4).isNull();
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
@Test
public void integrationTest() throws Exception {
File inputTweets = new File(this.getClass().getResource("/tweets-in.xls").toURI());
File outputTweets = new File(this.getClass().getResource("/tweets-out.xls").toURI());
Job job = JobBuilder.aNewJob()
.reader(new MsExcelRecordReader(inputTweets))
.mapper(new MsExcelRecordMapper(Tweet.class, "id", "user", "message"))
.marshaller(new MsExcelRecordMarshaller<>(Tweet.class, "id", "user", "message"))
.writer(new MsExcelRecordWriter(outputTweets, SHEET_NAME))
.build();
JobReport report = JobExecutor.execute(job);
assertThat(report).isNotNull();
assertThat(report.getMetrics().getTotalCount()).isEqualTo(2);
assertThat(report.getMetrics().getSuccessCount()).isEqualTo(2);
assertThat(report.getStatus()).isEqualTo(JobStatus.COMPLETED);
HSSFWorkbook workbook = new HSSFWorkbook(new FileInputStream(outputTweets));
HSSFSheet sheet = workbook.getSheet(SHEET_NAME);
HSSFRow firstRow = sheet.getRow(1);
assertThat(firstRow.getCell(0).getNumericCellValue()).isEqualTo(1.0);
assertThat(firstRow.getCell(1).getStringCellValue()).isEqualTo("foo");
assertThat(firstRow.getCell(2).getStringCellValue()).isEqualTo("hi");
HSSFRow secondRow = sheet.getRow(2);
assertThat(secondRow.getCell(0).getNumericCellValue()).isEqualTo(2.0);
assertThat(secondRow.getCell(1).getStringCellValue()).isEqualTo("bar");
assertThat(secondRow.getCell(2).getStringCellValue()).isEqualTo("hello");
}
#location 11
#vulnerability type RESOURCE_LEAK
|
#fixed code
@Test
public void integrationTest() throws Exception {
File inputTweets = new File(this.getClass().getResource("/tweets-in.xlsx").toURI());
File outputTweets = new File(this.getClass().getResource("/tweets-out.xlsx").toURI());
Job job = JobBuilder.aNewJob()
.reader(new MsExcelRecordReader(inputTweets))
.mapper(new MsExcelRecordMapper(Tweet.class, "id", "user", "message"))
.marshaller(new MsExcelRecordMarshaller<>(Tweet.class, "id", "user", "message"))
.writer(new MsExcelRecordWriter(outputTweets, SHEET_NAME))
.build();
JobReport report = JobExecutor.execute(job);
assertThat(report).isNotNull();
assertThat(report.getMetrics().getTotalCount()).isEqualTo(2);
assertThat(report.getMetrics().getSuccessCount()).isEqualTo(2);
assertThat(report.getStatus()).isEqualTo(JobStatus.COMPLETED);
XSSFWorkbook workbook = new XSSFWorkbook(new FileInputStream(outputTweets));
XSSFSheet sheet = workbook.getSheet(SHEET_NAME);
XSSFRow row = sheet.getRow(1);
assertThat(row.getCell(0).getNumericCellValue()).isEqualTo(1.0);
assertThat(row.getCell(1).getStringCellValue()).isEqualTo("foo");
assertThat(row.getCell(2).getStringCellValue()).isEqualTo("hi");
row = sheet.getRow(2);
assertThat(row.getCell(0).getNumericCellValue()).isEqualTo(2.0);
assertThat(row.getCell(1).getStringCellValue()).isEqualTo("bar");
assertThat(row.getCell(2).getStringCellValue()).isEqualTo("hello");
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
@Test
public void integrationTest() throws Exception {
File inputTweets = new File(this.getClass().getResource("/tweets-in.xlsx").toURI());
File outputTweets = new File(this.getClass().getResource("/tweets-out.xlsx").toURI());
String[] fields = {"id", "user", "message"};
Job job = JobBuilder.aNewJob()
.reader(new MsExcelRecordReader(inputTweets))
.mapper(new MsExcelRecordMapper<>(Tweet.class, fields))
.marshaller(new MsExcelRecordMarshaller<>(Tweet.class, fields))
.writer(new MsExcelRecordWriter(outputTweets, SHEET_NAME))
.build();
JobReport report = new JobExecutor().execute(job);
assertThat(report).isNotNull();
assertThat(report.getMetrics().getReadCount()).isEqualTo(2);
assertThat(report.getMetrics().getWriteCount()).isEqualTo(2);
assertThat(report.getStatus()).isEqualTo(JobStatus.COMPLETED);
XSSFWorkbook workbook = new XSSFWorkbook(new FileInputStream(outputTweets));
XSSFSheet sheet = workbook.getSheet(SHEET_NAME);
XSSFRow row = sheet.getRow(1);
assertThat(row.getCell(0).getNumericCellValue()).isEqualTo(1.0);
assertThat(row.getCell(1).getStringCellValue()).isEqualTo("foo");
assertThat(row.getCell(2).getStringCellValue()).isEqualTo("hi");
row = sheet.getRow(2);
assertThat(row.getCell(0).getNumericCellValue()).isEqualTo(2.0);
assertThat(row.getCell(1).getStringCellValue()).isEqualTo("bar");
assertThat(row.getCell(2).getStringCellValue()).isEqualTo("hello");
}
#location 15
#vulnerability type RESOURCE_LEAK
|
#fixed code
@Test
public void integrationTest() throws Exception {
Path inputTweets = Paths.get("src/test/resources/tweets-in.xlsx");
Path outputTweets = Paths.get("src/test/resources/tweets-out.xlsx");
String[] fields = {"id", "user", "message"};
Job job = JobBuilder.aNewJob()
.reader(new MsExcelRecordReader(inputTweets))
.mapper(new MsExcelRecordMapper<>(Tweet.class, fields))
.marshaller(new MsExcelRecordMarshaller<>(Tweet.class, fields))
.writer(new MsExcelRecordWriter(outputTweets, SHEET_NAME))
.build();
JobReport report = new JobExecutor().execute(job);
assertThat(report).isNotNull();
assertThat(report.getMetrics().getReadCount()).isEqualTo(2);
assertThat(report.getMetrics().getWriteCount()).isEqualTo(2);
assertThat(report.getStatus()).isEqualTo(JobStatus.COMPLETED);
XSSFWorkbook workbook = new XSSFWorkbook(new FileInputStream(outputTweets.toFile()));
XSSFSheet sheet = workbook.getSheet(SHEET_NAME);
XSSFRow row = sheet.getRow(1);
assertThat(row.getCell(0).getNumericCellValue()).isEqualTo(1.0);
assertThat(row.getCell(1).getStringCellValue()).isEqualTo("foo");
assertThat(row.getCell(2).getStringCellValue()).isEqualTo("hi");
row = sheet.getRow(2);
assertThat(row.getCell(0).getNumericCellValue()).isEqualTo(2.0);
assertThat(row.getCell(1).getStringCellValue()).isEqualTo("bar");
assertThat(row.getCell(2).getStringCellValue()).isEqualTo("hello");
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
@Test
@SuppressWarnings("unchecked")
public void integrationTest() throws Exception {
String dataSource = "foo" + LINE_SEPARATOR + "" + LINE_SEPARATOR + "bar" + LINE_SEPARATOR + "" + LINE_SEPARATOR;
JobReport jobReport = aNewJob()
.reader(new StringRecordReader(dataSource))
.filter(new EmptyRecordFilter())
.processor(new RecordCollector())
.call();
assertThat(jobReport).isNotNull();
assertThat(jobReport.getMetrics().getTotalCount()).isEqualTo(4);
assertThat(jobReport.getMetrics().getFilteredCount()).isEqualTo(2);
assertThat(jobReport.getMetrics().getSuccessCount()).isEqualTo(2);
List<StringRecord> records = (List<StringRecord>) jobReport.getResult();
assertThat(records).hasSize(2);
assertThat(records.get(0).getPayload()).isEqualTo("foo");
assertThat(records.get(1).getPayload()).isEqualTo("bar");
}
#location 19
#vulnerability type NULL_DEREFERENCE
|
#fixed code
@Test
@SuppressWarnings("unchecked")
public void integrationTest() throws Exception {
String dataSource = "foo" + LINE_SEPARATOR + "" + LINE_SEPARATOR + "bar" + LINE_SEPARATOR + "" + LINE_SEPARATOR;
JobReport jobReport = aNewJob()
.reader(new StringRecordReader(dataSource))
.filter(new EmptyRecordFilter())
.processor(new RecordCollector())
.call();
assertThat(jobReport).isNotNull();
assertThat(jobReport.getMetrics().getTotalCount()).isEqualTo(4);
assertThat(jobReport.getMetrics().getFilteredCount()).isEqualTo(2);
assertThat(jobReport.getMetrics().getSuccessCount()).isEqualTo(2);
List<StringRecord> records = (List<StringRecord>) jobReport.getResult();
assertThat(records).extracting("payload").containsExactly("foo", "bar");
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
@Test
public void testReadingEscapedXml() throws Exception {
xmlRecordReader.close();
xmlRecordReader = new XmlRecordReader("website", getDataSource("/websites.xml"));
xmlRecordReader.open();
XmlRecord record = xmlRecordReader.readRecord();
assertThat(record.getPayload()).isXmlEqualTo("<website name=\"google\" url=\"http://www.google.com?query=test&sort=asc\"/>");
record = xmlRecordReader.readRecord();
assertThat(record.getPayload()).isXmlEqualTo("<website name=\"l'equipe\" url=\"http://www.lequipe.fr\"/>");
record = xmlRecordReader.readRecord();
assertThat(record.getPayload()).isXmlEqualTo("<website name=\"l"internaute.com\" url=\"http://www.linternaute.com\"/>");
record = xmlRecordReader.readRecord();
assertThat(record.getPayload()).isXmlEqualTo("<website name=\"google\">http://www.google.com?query=test&sort=asc</website>");
record = xmlRecordReader.readRecord();
assertThat(record.getPayload()).isXmlEqualTo("<website name=\"test\"><test>foo</test></website>");
record = xmlRecordReader.readRecord();
assertThat(record).isNull();
}
#location 10
#vulnerability type NULL_DEREFERENCE
|
#fixed code
@Test
public void testReadingEscapedXml() throws Exception {
// given
xmlRecordReader = new XmlRecordReader("website", getDataSource("/websites.xml"));
xmlRecordReader.open();
// when
XmlRecord record1 = xmlRecordReader.readRecord();
XmlRecord record2 = xmlRecordReader.readRecord();
XmlRecord record3 = xmlRecordReader.readRecord();
XmlRecord record4 = xmlRecordReader.readRecord();
XmlRecord record5 = xmlRecordReader.readRecord();
XmlRecord record6 = xmlRecordReader.readRecord();
// then
assertThat(record1.getPayload()).isXmlEqualTo("<website name=\"google\" url=\"http://www.google.com?query=test&sort=asc\"/>");
assertThat(record2.getPayload()).isXmlEqualTo("<website name=\"l'equipe\" url=\"http://www.lequipe.fr\"/>");
assertThat(record3.getPayload()).isXmlEqualTo("<website name=\"l"internaute.com\" url=\"http://www.linternaute.com\"/>");
assertThat(record4.getPayload()).isXmlEqualTo("<website name=\"google\">http://www.google.com?query=test&sort=asc</website>");
assertThat(record5.getPayload()).isXmlEqualTo("<website name=\"test\"><test>foo</test></website>");
assertThat(record6).isNull();
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
@Test
public void testXmlRecordReading() throws Exception {
String expectedDataSourceName = dataSource.getAbsolutePath();
XmlRecord xmlRecord = xmlFileRecordReader.readRecord();
assertThat(xmlRecord.getHeader().getNumber()).isEqualTo(1L);
assertThat(xmlRecord.getHeader().getSource()).isEqualTo(expectedDataSourceName);
assertThat(xmlRecord.getPayload()).isEqualTo("<data>1</data>");
xmlRecord = xmlFileRecordReader.readRecord();
assertThat(xmlRecord.getHeader().getNumber()).isEqualTo(2L);
assertThat(xmlRecord.getHeader().getSource()).isEqualTo(expectedDataSourceName);
assertThat(xmlRecord.getPayload()).isEqualTo("<data>2</data>");
xmlRecord = xmlFileRecordReader.readRecord();
assertThat(xmlRecord.getHeader().getNumber()).isEqualTo(3L);
assertThat(xmlRecord.getHeader().getSource()).isEqualTo(expectedDataSourceName);
assertThat(xmlRecord.getPayload()).isEqualTo("<data>3</data>");
xmlRecord = xmlFileRecordReader.readRecord();
assertThat(xmlRecord.getHeader().getNumber()).isEqualTo(4L);
assertThat(xmlRecord.getHeader().getSource()).isEqualTo(expectedDataSourceName);
assertThat(xmlRecord.getPayload()).isEqualTo("<data>4</data>");
xmlRecord = xmlFileRecordReader.readRecord();
assertThat(xmlRecord.getHeader().getNumber()).isEqualTo(5L);
assertThat(xmlRecord.getHeader().getSource()).isEqualTo(expectedDataSourceName);
assertThat(xmlRecord.getPayload()).isEqualTo("<data>5</data>");
xmlRecord = xmlFileRecordReader.readRecord();
assertThat(xmlRecord).isNull();
}
#location 11
#vulnerability type NULL_DEREFERENCE
|
#fixed code
@Test
public void testXmlRecordReading() throws Exception {
// given
dataSource = new File("src/test/resources/data.xml");
xmlFileRecordReader = new XmlFileRecordReader(dataSource, "data");
xmlFileRecordReader.open();
String expectedDataSourceName = dataSource.getAbsolutePath();
// when
XmlRecord xmlRecord1 = xmlFileRecordReader.readRecord();
XmlRecord xmlRecord2 = xmlFileRecordReader.readRecord();
XmlRecord xmlRecord3 = xmlFileRecordReader.readRecord();
XmlRecord xmlRecord4 = xmlFileRecordReader.readRecord();
// then
assertThat(xmlRecord1.getHeader().getNumber()).isEqualTo(1L);
assertThat(xmlRecord1.getHeader().getSource()).isEqualTo(expectedDataSourceName);
assertThat(xmlRecord1.getPayload()).isEqualTo("<data>1</data>");
assertThat(xmlRecord2.getHeader().getNumber()).isEqualTo(2L);
assertThat(xmlRecord2.getHeader().getSource()).isEqualTo(expectedDataSourceName);
assertThat(xmlRecord2.getPayload()).isEqualTo("<data>2</data>");
assertThat(xmlRecord3.getHeader().getNumber()).isEqualTo(3L);
assertThat(xmlRecord3.getHeader().getSource()).isEqualTo(expectedDataSourceName);
assertThat(xmlRecord3.getPayload()).isEqualTo("<data>3</data>");
assertThat(xmlRecord4).isNull();
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
@Test
public void integrationTest() throws Exception {
File inputTweets = new File(this.getClass().getResource("/tweets-in.xls").toURI());
File outputTweets = new File(this.getClass().getResource("/tweets-out.xls").toURI());
Job job = JobBuilder.aNewJob()
.reader(new MsExcelRecordReader(inputTweets))
.filter(new HeaderRecordFilter())
.mapper(new MsExcelRecordMapper(Tweet.class, "id", "user", "message"))
//.marshaller(new MsExcelRecordMarshaller<>(Tweet.class, "id", "user", "message"))
//.writer(new MsExcelRecordWriter(outputTweets))
.writer(new StandardOutputRecordWriter())
.build();
JobReport report = JobExecutor.execute(job);
assertThat(report).isNotNull();
assertThat(report.getMetrics().getTotalCount()).isEqualTo(3);
assertThat(report.getMetrics().getFilteredCount()).isEqualTo(1);
assertThat(report.getMetrics().getSuccessCount()).isEqualTo(2);
}
#location 13
#vulnerability type RESOURCE_LEAK
|
#fixed code
@Test
public void integrationTest() throws Exception {
File inputTweets = new File(this.getClass().getResource("/tweets-in.xls").toURI());
File outputTweets = new File(this.getClass().getResource("/tweets-out.xls").toURI());
Job job = JobBuilder.aNewJob()
.reader(new MsExcelRecordReader(inputTweets))
.filter(new HeaderRecordFilter())
.mapper(new MsExcelRecordMapper(Tweet.class, "id", "user", "message"))
.marshaller(new MsExcelRecordMarshaller<>(Tweet.class, "id", "user", "message"))
.writer(new MsExcelRecordWriter(outputTweets))
.build();
JobReport report = JobExecutor.execute(job);
assertThat(report).isNotNull();
assertThat(report.getMetrics().getTotalCount()).isEqualTo(3);
assertThat(report.getMetrics().getFilteredCount()).isEqualTo(1);
assertThat(report.getMetrics().getSuccessCount()).isEqualTo(2);
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
@Test
public void testReadingEscapedXml() throws Exception {
xmlRecordReader.close();
xmlRecordReader = new XmlRecordReader("website", getDataSource("/websites.xml"));
xmlRecordReader.open();
XmlRecord record = xmlRecordReader.readRecord();
assertThat(record.getPayload()).isXmlEqualTo("<website name=\"google\" url=\"http://www.google.com?query=test&sort=asc\"/>");
record = xmlRecordReader.readRecord();
assertThat(record.getPayload()).isXmlEqualTo("<website name=\"l'equipe\" url=\"http://www.lequipe.fr\"/>");
record = xmlRecordReader.readRecord();
assertThat(record.getPayload()).isXmlEqualTo("<website name=\"l"internaute.com\" url=\"http://www.linternaute.com\"/>");
record = xmlRecordReader.readRecord();
assertThat(record.getPayload()).isXmlEqualTo("<website name=\"google\">http://www.google.com?query=test&sort=asc</website>");
record = xmlRecordReader.readRecord();
assertThat(record.getPayload()).isXmlEqualTo("<website name=\"test\"><test>foo</test></website>");
record = xmlRecordReader.readRecord();
assertThat(record).isNull();
}
#location 7
#vulnerability type NULL_DEREFERENCE
|
#fixed code
@Test
public void testReadingEscapedXml() throws Exception {
// given
xmlRecordReader = new XmlRecordReader("website", getDataSource("/websites.xml"));
xmlRecordReader.open();
// when
XmlRecord record1 = xmlRecordReader.readRecord();
XmlRecord record2 = xmlRecordReader.readRecord();
XmlRecord record3 = xmlRecordReader.readRecord();
XmlRecord record4 = xmlRecordReader.readRecord();
XmlRecord record5 = xmlRecordReader.readRecord();
XmlRecord record6 = xmlRecordReader.readRecord();
// then
assertThat(record1.getPayload()).isXmlEqualTo("<website name=\"google\" url=\"http://www.google.com?query=test&sort=asc\"/>");
assertThat(record2.getPayload()).isXmlEqualTo("<website name=\"l'equipe\" url=\"http://www.lequipe.fr\"/>");
assertThat(record3.getPayload()).isXmlEqualTo("<website name=\"l"internaute.com\" url=\"http://www.linternaute.com\"/>");
assertThat(record4.getPayload()).isXmlEqualTo("<website name=\"google\">http://www.google.com?query=test&sort=asc</website>");
assertThat(record5.getPayload()).isXmlEqualTo("<website name=\"test\"><test>foo</test></website>");
assertThat(record6).isNull();
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
@Test
public void testReadingXmlWithCustomNamespace() throws Exception {
xmlRecordReader.close();
xmlRecordReader = new XmlRecordReader("bean", getDataSource("/beans.xml"));
xmlRecordReader.open();
XmlRecord record = xmlRecordReader.readRecord();
assertThat(record.getPayload()).isXmlEqualTo("<bean id=\"foo\" class=\"java.lang.String\"><description>foo bean</description></bean>");
record = xmlRecordReader.readRecord();
assertThat(record.getPayload()).isXmlEqualTo("<bean id=\"bar\" class=\"java.lang.String\"/>");
record = xmlRecordReader.readRecord();
assertThat(record).isNull();
}
#location 8
#vulnerability type NULL_DEREFERENCE
|
#fixed code
@Test
public void testReadingXmlWithCustomNamespace() throws Exception {
// given
xmlRecordReader = new XmlRecordReader("bean", getDataSource("/beans.xml"));
xmlRecordReader.open();
// when
XmlRecord record1 = xmlRecordReader.readRecord();
XmlRecord record2 = xmlRecordReader.readRecord();
XmlRecord record3 = xmlRecordReader.readRecord();
// then
assertThat(record1.getPayload()).isXmlEqualTo("<bean id=\"foo\" class=\"java.lang.String\"><description>foo bean</description></bean>");
assertThat(record2.getPayload()).isXmlEqualTo("<bean id=\"bar\" class=\"java.lang.String\"/>");
assertThat(record3).isNull();
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
@Override
public String validateRecord(Record record) {
String error = super.validateRecord(record);
if (error.length() == 0){//no errors after applying declared validators on each field => all fields are valid
//add custom validation : field 2 content must starts with field 1 content
final String content1 = record.getFieldContentByIndex(1);
final String content2 = record.getFieldContentByIndex(2);
if (!content2.startsWith(content1))
return "field 2 content [" + content2 + "] must start with field 1 content [" + content1 + "]";
}
return "";
}
#location 5
#vulnerability type NULL_DEREFERENCE
|
#fixed code
@Override
public String validateRecord(Record record) {
String error = super.validateRecord(record);
if (error == null){//no errors after applying declared validators on each field => all fields are valid
//add custom validation : field 2 content must start with field's 1 content
final String content1 = record.getFieldContentByIndex(1);
final String content2 = record.getFieldContentByIndex(2);
if (!content2.startsWith(content1))
return "field 2 content [" + content2 + "] must start with field's 1 content [" + content1 + "]";
}
return null;
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
@Override
public void run() {
final SingleWriterRecorder recorder =
new SingleWriterRecorder(
config.lowestTrackableValue,
config.highestTrackableValue,
config.numberOfSignificantValueDigits
);
Histogram intervalHistogram = null;
HiccupRecorder hiccupRecorder;
final long uptimeAtInitialStartTime = ManagementFactory.getRuntimeMXBean().getUptime();
long now = System.currentTimeMillis();
long jvmStartTime = now - uptimeAtInitialStartTime;
long reportingStartTime = jvmStartTime;
if (config.inputFileName == null) {
// Normal operating mode.
// Launch a hiccup recorder, a process termination monitor, and an optional control process:
hiccupRecorder = this.createHiccupRecorder(recorder);
if (config.terminateWithStdInput) {
new TerminateWithStdInputReader();
}
if (config.controlProcessCommand != null) {
new ExecProcess(config.controlProcessCommand, "ControlProcess", log, config.verbose);
}
} else {
// Take input from file instead of sampling it ourselves.
// Launch an input hiccup recorder, but no termination monitoring or control process:
hiccupRecorder = new InputRecorder(recorder, config.inputFileName);
}
histogramLogWriter.outputComment("[Logged with " + getVersionString() + "]");
histogramLogWriter.outputLogFormatVersion();
try {
final long startTime;
if (config.inputFileName == null) {
// Normal operating mode:
if (config.startDelayMs > 0) {
// Run hiccup recorder during startDelayMs time to let code warm up:
hiccupRecorder.start();
while (config.startDelayMs > System.currentTimeMillis() - jvmStartTime) {
Thread.sleep(100);
}
hiccupRecorder.terminate();
hiccupRecorder.join();
recorder.reset();
hiccupRecorder = new HiccupRecorder(recorder, config.allocateObjects);
}
hiccupRecorder.start();
startTime = System.currentTimeMillis();
if (config.startTimeAtZero) {
reportingStartTime = startTime;
}
histogramLogWriter.outputStartTime(reportingStartTime);
histogramLogWriter.setBaseTime(reportingStartTime);
} else {
// Reading from input file, not sampling ourselves...:
hiccupRecorder.start();
reportingStartTime = startTime = hiccupRecorder.getCurrentTimeMsecWithDelay(0);
histogramLogWriter.outputComment("[Data read from input file \"" + config.inputFileName + "\" at " + new Date() + "]");
}
histogramLogWriter.outputLegend();
long nextReportingTime = startTime + config.reportingIntervalMs;
while ((now > 0) && ((config.runTimeMs == 0) || (config.runTimeMs > now - startTime))) {
now = hiccupRecorder.getCurrentTimeMsecWithDelay(nextReportingTime); // could return -1 to indicate termination
if (now > nextReportingTime) {
// Get the latest interval histogram and give the recorder a fresh Histogram for the next interval
intervalHistogram = recorder.getIntervalHistogram(intervalHistogram);
while (now > nextReportingTime) {
nextReportingTime += config.reportingIntervalMs;
}
if (intervalHistogram.getTotalCount() > 0) {
histogramLogWriter.outputIntervalHistogram(intervalHistogram);
}
}
}
} catch (InterruptedException e) {
if (config.verbose) {
log.println("# HiccupMeter terminating...");
}
}
try {
hiccupRecorder.terminate();
hiccupRecorder.join();
} catch (InterruptedException e) {
if (config.verbose) {
log.println("# HiccupMeter terminate/join interrupted");
}
}
}
#location 50
#vulnerability type RESOURCE_LEAK
|
#fixed code
@Override
public void run() {
final SingleWriterRecorder recorder =
new SingleWriterRecorder(
config.lowestTrackableValue,
config.highestTrackableValue,
config.numberOfSignificantValueDigits
);
Histogram intervalHistogram = null;
HiccupRecorder hiccupRecorder;
final long uptimeAtInitialStartTime = ManagementFactory.getRuntimeMXBean().getUptime();
long now = System.currentTimeMillis();
long jvmStartTime = now - uptimeAtInitialStartTime;
long reportingStartTime = jvmStartTime;
if (config.inputFileName == null) {
// Normal operating mode.
// Launch a hiccup recorder, a process termination monitor, and an optional control process:
hiccupRecorder = this.createHiccupRecorder(recorder);
if (config.terminateWithStdInput) {
new TerminateWithStdInputReader();
}
if (config.controlProcessCommand != null) {
new ExecProcess(config.controlProcessCommand, "ControlProcess", log, config.verbose);
}
} else {
// Take input from file instead of sampling it ourselves.
// Launch an input hiccup recorder, but no termination monitoring or control process:
hiccupRecorder = new InputRecorder(recorder, config.inputFileName);
}
histogramLogWriter.outputComment("[Logged with " + getVersionString() + "]");
histogramLogWriter.outputLogFormatVersion();
try {
final long startTime;
if (config.inputFileName == null) {
// Normal operating mode:
if (config.startDelayMs > 0) {
// Run hiccup recorder during startDelayMs time to let code warm up:
hiccupRecorder.start();
while (config.startDelayMs > System.currentTimeMillis() - jvmStartTime) {
Thread.sleep(100);
}
hiccupRecorder.terminate();
hiccupRecorder.join();
recorder.reset();
hiccupRecorder = new HiccupRecorder(recorder, config.allocateObjects);
}
hiccupRecorder.start();
startTime = System.currentTimeMillis();
if (config.startTimeAtZero) {
reportingStartTime = startTime;
}
histogramLogWriter.outputStartTime(reportingStartTime);
histogramLogWriter.setBaseTime(reportingStartTime);
} else {
// Reading from input file, not sampling ourselves...:
hiccupRecorder.start();
reportingStartTime = startTime = hiccupRecorder.getCurrentTimeMsecWithDelay(0);
histogramLogWriter.outputComment("[Data read from input file \"" + config.inputFileName + "\" at " + new Date() + "]");
}
histogramLogWriter.outputLegend();
long nextReportingTime = startTime + config.reportingIntervalMs;
long intervalStartTimeMsec = 0;
while ((now > 0) && ((config.runTimeMs == 0) || (config.runTimeMs > now - startTime))) {
now = hiccupRecorder.getCurrentTimeMsecWithDelay(nextReportingTime); // could return -1 to indicate termination
if (now > nextReportingTime) {
// Get the latest interval histogram and give the recorder a fresh Histogram for the next interval
intervalHistogram = recorder.getIntervalHistogram(intervalHistogram);
while (now > nextReportingTime) {
nextReportingTime += config.reportingIntervalMs;
}
if (config.inputFileName != null) {
// When read from input file, use timestamps from file input for start/end of log intervals:
intervalHistogram.setStartTimeStamp(intervalStartTimeMsec);
intervalHistogram.setEndTimeStamp(now);
intervalStartTimeMsec = now;
}
if (intervalHistogram.getTotalCount() > 0) {
histogramLogWriter.outputIntervalHistogram(intervalHistogram);
}
}
}
} catch (InterruptedException e) {
if (config.verbose) {
log.println("# HiccupMeter terminating...");
}
}
try {
hiccupRecorder.terminate();
hiccupRecorder.join();
} catch (InterruptedException e) {
if (config.verbose) {
log.println("# HiccupMeter terminate/join interrupted");
}
}
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#vulnerable code
public void init() {
KafkaConsumer kafkaConsumer=new KafkaConsumer(getProperties());
//kafka消费消息,接收MQTT发来的消息
kafkaConsumer.subscribe(Arrays.asList(conf.get("mqttwk.broker.kafka.producer.topic")));
int sum=0;
while (true) {
ConsumerRecords<String, String> records = kafkaConsumer.poll(500);
for (ConsumerRecord<String, String> record : records) {
log.debugf("offset = %d, key = %s, value = %s%n", record.offset(), record.key(), new String(HexUtil.decodeHex(record.value())));
log.debugf("总计收到 %s条",++sum);
}
}
}
#location 11
#vulnerability type RESOURCE_LEAK
|
#fixed code
public void init() {
KafkaConsumer kafkaConsumer=new KafkaConsumer(getProperties());
//kafka消费消息,接收MQTT发来的消息
kafkaConsumer.subscribe(Arrays.asList(conf.get("mqttwk.broker.kafka.producer.topic")));
int sum=0;
while (true) {
ConsumerRecords<String, String> records = kafkaConsumer.poll(Duration.ofMillis(500));
for (ConsumerRecord<String, String> record : records) {
log.debugf("offset = %d, key = %s, value = %s%n", record.offset(), record.key(), new String(HexUtil.decodeHex(record.value())));
log.debugf("总计收到 %s条",++sum);
}
}
}
|
Below is the vulnerable code, please generate the patch based on the following information.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.