input
stringlengths 205
73.3k
| output
stringlengths 64
73.2k
| instruction
stringclasses 1
value |
---|---|---|
#vulnerable code
@Test
public void certificateReadThrowsRuntimeException()
throws ExecutionException, InterruptedException, IOException {
MockTokenServerTransport transport = new MockTokenServerTransport();
transport.addServiceAccount(ServiceAccount.EDITOR.getEmail(), ACCESS_TOKEN);
InputStream inputStream =
new InputStream() {
@Override
public int read() throws IOException {
throw new IOException("Expected");
}
};
FirebaseCredential credential =
FirebaseCredentials.fromCertificate(inputStream, transport, Utils.getDefaultJsonFactory());
try {
Tasks.await(credential.getAccessToken(false));
Assert.fail();
} catch (Exception e) {
Assert.assertEquals("java.io.IOException: Failed to read service account", e.getMessage());
Assert.assertEquals("Expected", e.getCause().getCause().getMessage());
}
}
#location 16
#vulnerability type RESOURCE_LEAK | #fixed code
@Test
public void certificateReadThrowsRuntimeException()
throws ExecutionException, InterruptedException {
MockTokenServerTransport transport = new MockTokenServerTransport();
transport.addServiceAccount(ServiceAccount.EDITOR.getEmail(), ACCESS_TOKEN);
InputStream inputStream =
new InputStream() {
@Override
public int read() throws IOException {
throw new IOException("Expected");
}
};
try {
FirebaseCredentials.fromCertificate(inputStream, transport, Utils.getDefaultJsonFactory());
Assert.fail();
} catch (IOException e) {
Assert.assertEquals("Expected", e.getMessage());
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
public ConnectionContext getConnectionContext() {
return new ConnectionContext(
this.getLogger(),
wrapAuthTokenProvider(this.getAuthTokenProvider()),
this.getExecutorService(),
this.isPersistenceEnabled(),
FirebaseDatabase.getSdkVersion(),
this.getUserAgent());
}
#location 3
#vulnerability type THREAD_SAFETY_VIOLATION | #fixed code
public ConnectionContext getConnectionContext() {
return new ConnectionContext(
this.logger,
wrapAuthTokenProvider(this.getAuthTokenProvider()),
this.getExecutorService(),
this.isPersistenceEnabled(),
FirebaseDatabase.getSdkVersion(),
this.getUserAgent());
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
private static String streamToString(InputStream inputStream) throws IOException {
StringBuilder stringBuilder = new StringBuilder();
Reader reader = new InputStreamReader(inputStream, StandardCharsets.UTF_8);
char[] buffer = new char[256];
int length;
while ((length = reader.read(buffer)) != -1) {
stringBuilder.append(buffer, 0, length);
}
inputStream.close();
return stringBuilder.toString();
}
#location 10
#vulnerability type RESOURCE_LEAK | #fixed code
private static String streamToString(InputStream inputStream) throws IOException {
InputStreamReader reader = new InputStreamReader(inputStream, StandardCharsets.UTF_8);
return CharStreams.toString(reader);
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Test
public void refreshTokenReadThrowsRuntimeException()
throws ExecutionException, InterruptedException, IOException {
MockTokenServerTransport transport = new MockTokenServerTransport();
transport.addServiceAccount(ServiceAccount.EDITOR.getEmail(), ACCESS_TOKEN);
InputStream inputStream =
new InputStream() {
@Override
public int read() throws IOException {
throw new IOException("Expected");
}
};
FirebaseCredential credential =
FirebaseCredentials.fromRefreshToken(inputStream, transport, Utils.getDefaultJsonFactory());
try {
Tasks.await(credential.getAccessToken(false));
Assert.fail();
} catch (Exception e) {
Assert.assertEquals("java.io.IOException: Failed to read refresh token", e.getMessage());
Assert.assertEquals("Expected", e.getCause().getCause().getMessage());
}
}
#location 16
#vulnerability type RESOURCE_LEAK | #fixed code
@Test
public void refreshTokenReadThrowsRuntimeException()
throws ExecutionException, InterruptedException {
MockTokenServerTransport transport = new MockTokenServerTransport();
transport.addServiceAccount(ServiceAccount.EDITOR.getEmail(), ACCESS_TOKEN);
InputStream inputStream =
new InputStream() {
@Override
public int read() throws IOException {
throw new IOException("Expected");
}
};
try {
FirebaseCredentials.fromRefreshToken(inputStream, transport, Utils.getDefaultJsonFactory());
Assert.fail();
} catch (IOException e) {
Assert.assertEquals("Expected", e.getMessage());
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Test
public void canConvertDoubles() throws IOException {
List<Double> doubles = Arrays.asList(Double.MAX_VALUE, Double.MIN_VALUE, Double.MIN_NORMAL);
for (Double original : doubles) {
String jsonString = JsonMapper.serializeJsonValue(original);
double converted = (Double) JsonMapper.parseJsonValue(jsonString);
assertEquals(original, converted, 0);
}
}
#location 6
#vulnerability type NULL_DEREFERENCE | #fixed code
@Test
public void canConvertDoubles() throws IOException {
List<Double> doubles = Arrays.asList(Double.MAX_VALUE, Double.MIN_VALUE, Double.MIN_NORMAL);
for (Double original : doubles) {
String jsonString = JsonMapper.serializeJson(original);
double converted = (Double) JsonMapper.parseJsonValue(jsonString);
assertEquals(original, converted, 0);
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Test
public void canConvertLongs() throws IOException {
List<Long> longs = Arrays.asList(Long.MAX_VALUE, Long.MIN_VALUE);
for (Long original : longs) {
String jsonString = JsonMapper.serializeJsonValue(original);
long converted = (Long) JsonMapper.parseJsonValue(jsonString);
assertEquals((long) original, converted);
}
}
#location 6
#vulnerability type NULL_DEREFERENCE | #fixed code
@Test
public void canConvertLongs() throws IOException {
List<Long> longs = Arrays.asList(Long.MAX_VALUE, Long.MIN_VALUE);
for (Long original : longs) {
String jsonString = JsonMapper.serializeJson(original);
long converted = (Long) JsonMapper.parseJsonValue(jsonString);
assertEquals((long) original, converted);
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Test
public void testDeleteInstanceIdError() throws Exception {
final MockLowLevelHttpResponse response = new MockLowLevelHttpResponse();
MockHttpTransport transport = new MockHttpTransport.Builder()
.setLowLevelHttpResponse(response)
.build();
FirebaseOptions options = FirebaseOptions.builder()
.setCredentials(new MockGoogleCredentials("test-token"))
.setProjectId("test-project")
.setHttpTransport(transport)
.build();
FirebaseApp app = FirebaseApp.initializeApp(options);
// Disable retries by passing a regular HttpRequestFactory.
FirebaseInstanceId instanceId = new FirebaseInstanceId(app, transport.createRequestFactory());
TestResponseInterceptor interceptor = new TestResponseInterceptor();
instanceId.setInterceptor(interceptor);
try {
for (int statusCode : ERROR_CODES.keySet()) {
response.setStatusCode(statusCode).setContent("test error");
try {
instanceId.deleteInstanceIdAsync("test-iid").get();
fail("No error thrown for HTTP error");
} catch (ExecutionException e) {
assertTrue(e.getCause() instanceof FirebaseInstanceIdException);
checkFirebaseInstanceIdException((FirebaseInstanceIdException) e.getCause(), statusCode);
}
assertNotNull(interceptor.getResponse());
HttpRequest request = interceptor.getResponse().getRequest();
assertEquals(HttpMethods.DELETE, request.getRequestMethod());
assertEquals(TEST_URL, request.getUrl().toString());
}
} finally {
app.delete();
}
}
#location 32
#vulnerability type NULL_DEREFERENCE | #fixed code
@Test
public void testDeleteInstanceIdError() throws Exception {
final MockLowLevelHttpResponse response = new MockLowLevelHttpResponse();
MockHttpTransport transport = new MockHttpTransport.Builder()
.setLowLevelHttpResponse(response)
.build();
FirebaseOptions options = APP_OPTIONS.toBuilder()
.setHttpTransport(transport)
.build();
FirebaseApp app = FirebaseApp.initializeApp(options);
// Disable retries by passing a regular HttpRequestFactory.
FirebaseInstanceId instanceId = new FirebaseInstanceId(app, transport.createRequestFactory());
TestResponseInterceptor interceptor = new TestResponseInterceptor();
instanceId.setInterceptor(interceptor);
try {
for (int statusCode : ERROR_CODES.keySet()) {
response.setStatusCode(statusCode).setContent("test error");
try {
instanceId.deleteInstanceIdAsync("test-iid").get();
fail("No error thrown for HTTP error");
} catch (ExecutionException e) {
assertTrue(e.getCause() instanceof FirebaseInstanceIdException);
checkFirebaseInstanceIdException((FirebaseInstanceIdException) e.getCause(), statusCode);
}
assertNotNull(interceptor.getResponse());
HttpRequest request = interceptor.getResponse().getRequest();
assertEquals(HttpMethods.DELETE, request.getRequestMethod());
assertEquals(TEST_URL, request.getUrl().toString());
}
} finally {
app.delete();
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
private static String streamToString(InputStream inputStream) throws IOException {
StringBuilder stringBuilder = new StringBuilder();
Reader reader = new InputStreamReader(inputStream, StandardCharsets.UTF_8);
char[] buffer = new char[256];
int length;
while ((length = reader.read(buffer)) != -1) {
stringBuilder.append(buffer, 0, length);
}
inputStream.close();
return stringBuilder.toString();
}
#location 11
#vulnerability type RESOURCE_LEAK | #fixed code
private static String streamToString(InputStream inputStream) throws IOException {
InputStreamReader reader = new InputStreamReader(inputStream, StandardCharsets.UTF_8);
return CharStreams.toString(reader);
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
public static void main(String[] args)
{
String source = System.getProperty("source");
String destination = System.getProperty("destination");
if (source == null) {
help();
return;
}
int threads = getThreadsNumber();
boolean removeDeprecatedNodes = getRemoveDeprecatedNodes();
logger.info("Threads Number = " + threads);
Reader reader = new Reader(source, threads);
Node root = reader.read();
Writer writer = new Writer(destination, root, removeDeprecatedNodes);
writer.write();
}
#location 16
#vulnerability type NULL_DEREFERENCE | #fixed code
public static void main(String[] args) {
Configuration cfg = parseLegacyConfiguration();
if (cfg == null) {
cfg = parseConfiguration(args);
}
if (cfg == null) {
Options options = createOptions();
printHelp(options);
return;
}
String sourceAddress = cfg.source();
String destinationAddress = cfg.target();
int threads = cfg.workers();
boolean removeDeprecatedNodes = !cfg.copyOnly();
LOGGER.info("using " + threads + " concurrent workers to copy data");
Reader reader = new Reader(sourceAddress, threads);
Node root = reader.read();
if (root != null) {
Writer writer = new Writer(destinationAddress, root, removeDeprecatedNodes);
writer.write();
} else {
LOGGER.error("FAILED");
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
private List<ApiParamDoc> getQueryParamsFromSpringAnnotation(Method method, Class<?> controller) {
List<ApiParamDoc> apiParamDocs = new ArrayList<ApiParamDoc>();
if(controller.isAnnotationPresent(RequestMapping.class)) {
RequestMapping requestMapping = controller.getAnnotation(RequestMapping.class);
if(requestMapping.params().length > 0) {
for (String param : requestMapping.params()) {
String[] splitParam = param.split("=");
if(splitParam != null) {
apiParamDocs.add(new ApiParamDoc(splitParam[0], null, JSONDocTypeBuilder.build(new JSONDocType(), String.class, null), "true", new String[]{splitParam[1]}, null, null));
} else {
apiParamDocs.add(new ApiParamDoc(param, null, JSONDocTypeBuilder.build(new JSONDocType(), String.class, null), "true", new String[]{}, null, null));
}
}
}
}
if(controller.isAnnotationPresent(RequestMapping.class)) {
RequestMapping requestMapping = method.getAnnotation(RequestMapping.class);
if(requestMapping.params().length > 0) {
apiParamDocs.clear();
for (String param : requestMapping.params()) {
String[] splitParam = param.split("=");
if(splitParam.length > 1) {
apiParamDocs.add(new ApiParamDoc(splitParam[0], "", JSONDocTypeBuilder.build(new JSONDocType(), String.class, null), "true", new String[]{splitParam[1]}, null, null));
} else {
apiParamDocs.add(new ApiParamDoc(param, "", JSONDocTypeBuilder.build(new JSONDocType(), String.class, null), "true", new String[]{}, null, null));
}
}
}
}
return apiParamDocs;
}
#location 24
#vulnerability type NULL_DEREFERENCE | #fixed code
private List<ApiParamDoc> getQueryParamsFromSpringAnnotation(Method method, Class<?> controller) {
List<ApiParamDoc> apiParamDocs = new ArrayList<ApiParamDoc>();
if(controller.isAnnotationPresent(RequestMapping.class)) {
RequestMapping requestMapping = controller.getAnnotation(RequestMapping.class);
if(requestMapping.params().length > 0) {
for (String param : requestMapping.params()) {
String[] splitParam = param.split("=");
if(splitParam != null) {
apiParamDocs.add(new ApiParamDoc(splitParam[0], null, JSONDocTypeBuilder.build(new JSONDocType(), String.class, null), "true", new String[]{splitParam[1]}, null, null));
} else {
apiParamDocs.add(new ApiParamDoc(param, null, JSONDocTypeBuilder.build(new JSONDocType(), String.class, null), "true", new String[]{}, null, null));
}
}
}
}
if(method.isAnnotationPresent(RequestMapping.class)) {
RequestMapping requestMapping = method.getAnnotation(RequestMapping.class);
if(requestMapping.params().length > 0) {
apiParamDocs.clear();
for (String param : requestMapping.params()) {
String[] splitParam = param.split("=");
if(splitParam.length > 1) {
apiParamDocs.add(new ApiParamDoc(splitParam[0], "", JSONDocTypeBuilder.build(new JSONDocType(), String.class, null), "true", new String[]{splitParam[1]}, null, null));
} else {
apiParamDocs.add(new ApiParamDoc(param, "", JSONDocTypeBuilder.build(new JSONDocType(), String.class, null), "true", new String[]{}, null, null));
}
}
}
}
return apiParamDocs;
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@SuppressWarnings("resource")
@Override
public CBORParser createParser(File f) throws IOException {
return _createParser(new FileInputStream(f), _createContext(f, true));
}
#location 4
#vulnerability type RESOURCE_LEAK | #fixed code
@SuppressWarnings("resource")
@Override
public CBORParser createParser(File f) throws IOException {
IOContext ctxt = _createContext(f, true);
return _createParser(_decorate(new FileInputStream(f), ctxt), ctxt);
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
private JsonToken _handleNestedKey(int tag) throws IOException
{
int wireType = (tag & 0x7);
int id = (tag >> 3);
ProtobufField f;
if ((_currentField == null) || (f = _currentField.nextOrThisIf(id)) == null) {
f = _currentMessage.field(id);
}
_parsingContext.setCurrentName(f.name);
if (!f.isValidFor(wireType)) {
_reportIncompatibleType(f, wireType);
}
// array?
if (f.repeated) {
if (f.packed) {
_state = STATE_ARRAY_START_PACKED;
} else {
_state = STATE_ARRAY_START;
}
} else {
_state = STATE_NESTED_VALUE;
}
_currentField = f;
return (_currToken = JsonToken.FIELD_NAME);
}
#location 10
#vulnerability type NULL_DEREFERENCE | #fixed code
private JsonToken _handleNestedKey(int tag) throws IOException
{
int wireType = (tag & 0x7);
int id = (tag >> 3);
ProtobufField f;
if ((_currentField == null) || (f = _currentField.nextOrThisIf(id)) == null) {
f = _currentMessage.field(id);
}
// Note: may be null; if so, value needs to be skipped
if (f == null) {
return _skipUnknownField(id, wireType);
}
_parsingContext.setCurrentName(f.name);
if (!f.isValidFor(wireType)) {
_reportIncompatibleType(f, wireType);
}
// array?
if (f.repeated) {
if (f.packed) {
_state = STATE_ARRAY_START_PACKED;
} else {
_state = STATE_ARRAY_START;
}
} else {
_state = STATE_NESTED_VALUE;
}
_currentField = f;
return (_currToken = JsonToken.FIELD_NAME);
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
private JsonToken _handleNestedKey(int tag) throws IOException
{
int wireType = (tag & 0x7);
int id = (tag >> 3);
ProtobufField f;
if ((_currentField == null) || (f = _currentField.nextOrThisIf(id)) == null) {
f = _currentMessage.field(id);
}
_parsingContext.setCurrentName(f.name);
if (!f.isValidFor(wireType)) {
_reportIncompatibleType(f, wireType);
}
// array?
if (f.repeated) {
if (f.packed) {
_state = STATE_ARRAY_START_PACKED;
} else {
_state = STATE_ARRAY_START;
}
} else {
_state = STATE_NESTED_VALUE;
}
_currentField = f;
return (_currToken = JsonToken.FIELD_NAME);
}
#location 10
#vulnerability type NULL_DEREFERENCE | #fixed code
private JsonToken _handleNestedKey(int tag) throws IOException
{
int wireType = (tag & 0x7);
int id = (tag >> 3);
ProtobufField f;
if (_currentField != null) {
if ((f = _currentField.nextOrThisIf(id)) == null) {
if ((f = _currentMessage.field(id)) == null) {
return _skipUnknownField(id, wireType);
}
}
} else {
if ((f = _currentMessage.field(id)) == null) {
return _skipUnknownField(id, wireType);
}
}
if ((_currentField == null) || (f = _currentField.nextOrThisIf(id)) == null) {
f = _currentMessage.field(id);
}
// Note: may be null; if so, value needs to be skipped
if (f == null) {
return _skipUnknownField(id, wireType);
}
_parsingContext.setCurrentName(f.name);
if (!f.isValidFor(wireType)) {
_reportIncompatibleType(f, wireType);
}
// array?
if (f.repeated) {
if (f.packed) {
_state = STATE_ARRAY_START_PACKED;
} else {
_state = STATE_ARRAY_START;
}
} else {
_state = STATE_NESTED_VALUE;
}
_currentField = f;
return (_currToken = JsonToken.FIELD_NAME);
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Test
public void testMemoryAreas() {
assertEquals(
500000L,
registry.getSampleValue(
MemoryPoolsExports.MEMORY_USED_METRIC,
new String[]{"area"},
new String[]{"heap"}),
.0000001);
assertEquals(
1000000L,
registry.getSampleValue(
MemoryPoolsExports.MEMORY_LIMIT_METRIC,
new String[]{"area"},
new String[]{"heap"}),
.0000001);
assertEquals(
10000L,
registry.getSampleValue(
MemoryPoolsExports.MEMORY_USED_METRIC,
new String[]{"area"},
new String[]{"nonheap"}),
.0000001);
assertEquals(
20000L,
registry.getSampleValue(
MemoryPoolsExports.MEMORY_LIMIT_METRIC,
new String[]{"area"},
new String[]{"nonheap"}),
.0000001);
}
#location 5
#vulnerability type NULL_DEREFERENCE | #fixed code
@Test
public void testMemoryAreas() {
assertEquals(
500000L,
registry.getSampleValue(
"jvm_memory_bytes_used",
new String[]{"area"},
new String[]{"heap"}),
.0000001);
assertEquals(
1000000L,
registry.getSampleValue(
"jvm_memory_bytes_committed",
new String[]{"area"},
new String[]{"heap"}),
.0000001);
assertEquals(
2000000L,
registry.getSampleValue(
"jvm_memory_bytes_max",
new String[]{"area"},
new String[]{"heap"}),
.0000001);
assertEquals(
10000L,
registry.getSampleValue(
"jvm_memory_bytes_used",
new String[]{"area"},
new String[]{"nonheap"}),
.0000001);
assertEquals(
20000L,
registry.getSampleValue(
"jvm_memory_bytes_committed",
new String[]{"area"},
new String[]{"nonheap"}),
.0000001);
assertEquals(
3000000L,
registry.getSampleValue(
"jvm_memory_bytes_max",
new String[]{"area"},
new String[]{"nonheap"}),
.0000001);
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Test
public void testGarbageCollectorExports() {
assertEquals(
100L,
registry.getSampleValue(
GarbageCollectorExports.COLLECTIONS_COUNT_METRIC,
new String[]{"gc"},
new String[]{"MyGC1"}),
.0000001);
assertEquals(
10d,
registry.getSampleValue(
GarbageCollectorExports.COLLECTIONS_TIME_METRIC,
new String[]{"gc"},
new String[]{"MyGC1"}),
.0000001);
assertEquals(
200L,
registry.getSampleValue(
GarbageCollectorExports.COLLECTIONS_COUNT_METRIC,
new String[]{"gc"},
new String[]{"MyGC2"}),
.0000001);
assertEquals(
20d,
registry.getSampleValue(
GarbageCollectorExports.COLLECTIONS_TIME_METRIC,
new String[]{"gc"},
new String[]{"MyGC2"}),
.0000001);
}
#location 5
#vulnerability type NULL_DEREFERENCE | #fixed code
@Test
public void testGarbageCollectorExports() {
assertEquals(
100L,
registry.getSampleValue(
"jvm_gc_collection_seconds_count",
new String[]{"gc"},
new String[]{"MyGC1"}),
.0000001);
assertEquals(
10d,
registry.getSampleValue(
"jvm_gc_collection_seconds_sum",
new String[]{"gc"},
new String[]{"MyGC1"}),
.0000001);
assertEquals(
200L,
registry.getSampleValue(
"jvm_gc_collection_seconds_count",
new String[]{"gc"},
new String[]{"MyGC2"}),
.0000001);
assertEquals(
20d,
registry.getSampleValue(
"jvm_gc_collection_seconds_sum",
new String[]{"gc"},
new String[]{"MyGC2"}),
.0000001);
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Test
public void testMemoryPools() {
assertEquals(
500000L,
registry.getSampleValue(
MemoryPoolsExports.POOLS_USED_METRIC,
new String[]{"pool"},
new String[]{"PS-Eden-Space"}),
.0000001);
assertEquals(
1000000L,
registry.getSampleValue(
MemoryPoolsExports.POOLS_LIMIT_METRIC,
new String[]{"pool"},
new String[]{"PS-Eden-Space"}),
.0000001);
assertEquals(
10000L,
registry.getSampleValue(
MemoryPoolsExports.POOLS_USED_METRIC,
new String[]{"pool"},
new String[]{"PS-Old-Gen"}),
.0000001);
assertEquals(
20000L,
registry.getSampleValue(
MemoryPoolsExports.POOLS_LIMIT_METRIC,
new String[]{"pool"},
new String[]{"PS-Old-Gen"}),
.0000001);
}
#location 5
#vulnerability type NULL_DEREFERENCE | #fixed code
@Test
public void testMemoryPools() {
assertEquals(
500000L,
registry.getSampleValue(
"jvm_memory_pool_bytes_used",
new String[]{"pool"},
new String[]{"PS Eden Space"}),
.0000001);
assertEquals(
1000000L,
registry.getSampleValue(
"jvm_memory_pool_bytes_committed",
new String[]{"pool"},
new String[]{"PS Eden Space"}),
.0000001);
assertEquals(
2000000L,
registry.getSampleValue(
"jvm_memory_pool_bytes_max",
new String[]{"pool"},
new String[]{"PS Eden Space"}),
.0000001);
assertEquals(
10000L,
registry.getSampleValue(
"jvm_memory_pool_bytes_used",
new String[]{"pool"},
new String[]{"PS Old Gen"}),
.0000001);
assertEquals(
20000L,
registry.getSampleValue(
"jvm_memory_pool_bytes_committed",
new String[]{"pool"},
new String[]{"PS Old Gen"}),
.0000001);
assertEquals(
3000000L,
registry.getSampleValue(
"jvm_memory_pool_bytes_max",
new String[]{"pool"},
new String[]{"PS Old Gen"}),
.0000001);
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Test
public void priceFormat() {
assertEquals("%7.2f ", INSTRUMENTS.get("FOO").getPriceFormat());
}
#location 3
#vulnerability type NULL_DEREFERENCE | #fixed code
@Test
public void priceFormat() {
assertEquals("%7.2f ", FRACTIONS.get("FOO").getPriceFormat());
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
private static void main(Config config) throws IOException {
MarketData marketData = marketData(config);
MarketReportServer marketReport = marketReport(config);
List<String> instruments = config.getStringList("instruments");
MatchingEngine engine = new MatchingEngine(instruments, marketData, marketReport);
OrderEntryServer orderEntry = orderEntry(config, engine);
marketData.version();
new Events(marketData, marketReport, orderEntry).run();
}
#location 14
#vulnerability type RESOURCE_LEAK | #fixed code
private static void main(Config config) throws IOException {
MarketData marketData = marketData(config);
MarketReporting marketReporting = marketReporting(config);
List<String> instruments = config.getStringList("instruments");
MatchingEngine engine = new MatchingEngine(instruments, marketData, marketReporting);
OrderEntryServer orderEntry = orderEntry(config, engine);
marketData.version();
new Events(marketData, marketReporting, orderEntry).run();
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
private static void main(Config config, boolean taq) throws IOException {
NetworkInterface multicastInterface = Configs.getNetworkInterface(config, "market-data.multicast-interface");
InetAddress multicastGroup = Configs.getInetAddress(config, "market-data.multicast-group");
int multicastPort = Configs.getPort(config, "market-data.multicast-port");
InetAddress requestAddress = Configs.getInetAddress(config, "market-data.request-address");
int requestPort = Configs.getPort(config, "market-data.request-port");
List<String> instruments = config.getStringList("instruments");
MarketDataListener listener = taq ? new TAQFormat() : new DisplayFormat(instruments);
Market market = new Market(listener);
for (String instrument : instruments)
market.open(encodeLong(instrument));
MarketDataProcessor processor = new MarketDataProcessor(market, listener);
MoldUDP64Client transport = MoldUDP64Client.open(multicastInterface,
new InetSocketAddress(multicastGroup, multicastPort),
new InetSocketAddress(requestAddress, requestPort),
new PMDParser(processor));
transport.run();
}
#location 24
#vulnerability type RESOURCE_LEAK | #fixed code
private static void main(Config config, boolean taq) throws IOException {
NetworkInterface multicastInterface = Configs.getNetworkInterface(config, "market-data.multicast-interface");
InetAddress multicastGroup = Configs.getInetAddress(config, "market-data.multicast-group");
int multicastPort = Configs.getPort(config, "market-data.multicast-port");
InetAddress requestAddress = Configs.getInetAddress(config, "market-data.request-address");
int requestPort = Configs.getPort(config, "market-data.request-port");
List<String> instruments = config.getStringList("instruments");
MarketDataListener listener = taq ? new TAQFormat() : new DisplayFormat(instruments);
Market market = new Market(listener);
for (String instrument : instruments)
market.open(encodeLong(instrument));
MarketDataProcessor processor = new MarketDataProcessor(market, listener);
MoldUDP64.receive(multicastInterface, new InetSocketAddress(multicastGroup, multicastPort),
new InetSocketAddress(requestAddress, requestPort), new PMDParser(processor));
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
private static void main(Config config, boolean taq) throws IOException {
NetworkInterface multicastInterface = Configs.getNetworkInterface(config, "market-data.multicast-interface");
InetAddress multicastGroup = Configs.getInetAddress(config, "market-data.multicast-group");
int multicastPort = Configs.getPort(config, "market-data.multicast-port");
InetAddress requestAddress = Configs.getInetAddress(config, "market-data.request-address");
int requestPort = Configs.getPort(config, "market-data.request-port");
List<String> instruments = config.getStringList("instruments");
MarketDataListener listener = taq ? new TAQFormat() : new DisplayFormat(instruments);
MarketDataClient client = MarketDataClient.open(multicastInterface,
new InetSocketAddress(multicastGroup, multicastPort),
new InetSocketAddress(requestAddress, requestPort),
instruments, listener);
while (true)
client.receive();
}
#location 12
#vulnerability type RESOURCE_LEAK | #fixed code
private static void main(Config config, boolean taq) throws IOException {
NetworkInterface multicastInterface = Configs.getNetworkInterface(config, "market-data.multicast-interface");
InetAddress multicastGroup = Configs.getInetAddress(config, "market-data.multicast-group");
int multicastPort = Configs.getPort(config, "market-data.multicast-port");
InetAddress requestAddress = Configs.getInetAddress(config, "market-data.request-address");
int requestPort = Configs.getPort(config, "market-data.request-port");
List<String> instruments = config.getStringList("instruments");
MarketDataListener listener = taq ? new TAQFormat() : new DisplayFormat(instruments);
Market market = new Market(listener);
for (String instrument : instruments)
market.open(encodeLong(instrument));
MarketDataProcessor processor = new MarketDataProcessor(market, listener);
MoldUDP64Client transport = MoldUDP64Client.open(multicastInterface,
new InetSocketAddress(multicastGroup, multicastPort),
new InetSocketAddress(requestAddress, requestPort),
new PMDParser(processor));
while (true)
transport.receive();
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Test
public void priceFractionDigits() {
assertEquals(2, INSTRUMENTS.get("FOO").getPriceFractionDigits());
}
#location 3
#vulnerability type NULL_DEREFERENCE | #fixed code
@Test
public void priceFractionDigits() {
assertEquals(2, FRACTIONS.get("FOO").getPriceFractionDigits());
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
private static void main(Config config, boolean tsv) throws IOException {
NetworkInterface multicastInterface = Configs.getNetworkInterface(config, "trade-report.multicast-interface");
InetAddress multicastGroup = Configs.getInetAddress(config, "trade-report.multicast-group");
int multicastPort = Configs.getPort(config, "trade-report.multicast-port");
InetAddress requestAddress = Configs.getInetAddress(config, "trade-report.request-address");
int requestPort = Configs.getPort(config, "trade-report.request-port");
MarketReportListener listener = tsv ? new TSVFormat() : new DisplayFormat();
MoldUDP64Client transport = MoldUDP64Client.open(multicastInterface,
new InetSocketAddress(multicastGroup, multicastPort),
new InetSocketAddress(requestAddress, requestPort),
new PMRParser(listener));
transport.run();
}
#location 15
#vulnerability type RESOURCE_LEAK | #fixed code
private static void main(Config config, boolean tsv) throws IOException {
NetworkInterface multicastInterface = Configs.getNetworkInterface(config, "trade-report.multicast-interface");
InetAddress multicastGroup = Configs.getInetAddress(config, "trade-report.multicast-group");
int multicastPort = Configs.getPort(config, "trade-report.multicast-port");
InetAddress requestAddress = Configs.getInetAddress(config, "trade-report.request-address");
int requestPort = Configs.getPort(config, "trade-report.request-port");
MarketReportListener listener = tsv ? new TSVFormat() : new DisplayFormat();
MoldUDP64.receive(multicastInterface, new InetSocketAddress(multicastGroup, multicastPort),
new InetSocketAddress(requestAddress, requestPort), new PMRParser(listener));
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
private static void listen(boolean taq, Config config) throws IOException {
List<String> instruments = config.getStringList("instruments");
MarketDataListener listener = taq ? new TAQFormat() : new DisplayFormat(instruments);
Market market = new Market(listener);
for (String instrument : instruments)
market.open(ASCII.packLong(instrument));
MarketDataProcessor processor = new MarketDataProcessor(market, listener);
listen(config, new PMDParser(processor));
}
#location 13
#vulnerability type RESOURCE_LEAK | #fixed code
private static void listen(boolean taq, Config config) throws IOException {
Instruments instruments = Instruments.fromConfig(config, "instruments");
MarketDataListener listener = taq ? new TAQFormat(instruments) : new DisplayFormat(instruments);
Market market = new Market(listener);
for (Instrument instrument : instruments)
market.open(instrument.asLong());
MarketDataProcessor processor = new MarketDataProcessor(market, listener);
listen(config, new PMDParser(processor));
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Test
public void priceFactor() {
assertEquals(100.0, INSTRUMENTS.get("FOO").getPriceFactor(), 0.0);
}
#location 3
#vulnerability type NULL_DEREFERENCE | #fixed code
@Test
public void priceFactor() {
assertEquals(100.0, FRACTIONS.get("FOO").getPriceFactor(), 0.0);
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
boolean add(Side side, long price, long quantity) {
Long2LongRBTreeMap levels = getLevels(side);
long size = levels.get(price);
levels.put(price, size + quantity);
return price == levels.firstLongKey();
}
#location 4
#vulnerability type NULL_DEREFERENCE | #fixed code
OrderBook(long instrument) {
this.instrument = instrument;
this.bids = new Long2LongRBTreeMap(BidComparator.INSTANCE);
this.asks = new Long2LongRBTreeMap(AskComparator.INSTANCE);
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
public void run() throws IOException {
ConsoleReader reader = new ConsoleReader();
reader.addCompleter(new StringsCompleter(Commands.names().castToList()));
printf("Type 'help' for help.\n");
while (!closed) {
String line = reader.readLine("> ");
if (line == null)
break;
Scanner scanner = scan(line);
if (!scanner.hasNext())
continue;
Command command = Commands.find(scanner.next());
if (command == null) {
printf("error: Unknown command\n");
continue;
}
try {
command.execute(this, scanner);
} catch (CommandException e) {
printf("Usage: %s\n", command.getUsage());
} catch (ClosedChannelException e) {
printf("error: Connection closed\n");
}
}
close();
}
#location 8
#vulnerability type RESOURCE_LEAK | #fixed code
public void run() throws IOException {
LineReader reader = LineReaderBuilder.builder()
.completer(new StringsCompleter(Commands.names().castToList()))
.build();
printf("Type 'help' for help.\n");
while (!closed) {
String line = reader.readLine("> ");
if (line == null)
break;
Scanner scanner = scan(line);
if (!scanner.hasNext())
continue;
Command command = Commands.find(scanner.next());
if (command == null) {
printf("error: Unknown command\n");
continue;
}
try {
command.execute(this, scanner);
} catch (CommandException e) {
printf("Usage: %s\n", command.getUsage());
} catch (ClosedChannelException e) {
printf("error: Connection closed\n");
}
}
close();
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
private static void listen(boolean taq, Config config) throws IOException {
List<String> instruments = config.getStringList("instruments");
MarketDataListener listener = taq ? new TAQFormat() : new DisplayFormat(instruments);
Market market = new Market(listener);
for (String instrument : instruments)
market.open(ASCII.packLong(instrument));
MarketDataProcessor processor = new MarketDataProcessor(market, listener);
listen(config, new PMDParser(processor));
}
#location 4
#vulnerability type RESOURCE_LEAK | #fixed code
private static void listen(boolean taq, Config config) throws IOException {
Instruments instruments = Instruments.fromConfig(config, "instruments");
MarketDataListener listener = taq ? new TAQFormat(instruments) : new DisplayFormat(instruments);
Market market = new Market(listener);
for (Instrument instrument : instruments)
market.open(instrument.asLong());
MarketDataProcessor processor = new MarketDataProcessor(market, listener);
listen(config, new PMDParser(processor));
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
public void add(long instrument, long orderId, Side side, long price, long size) {
if (orders.containsKey(orderId))
return;
OrderBook book = books.get(instrument);
if (book == null)
return;
Order order = book.add(side, price, size);
orders.put(orderId, order);
if (order.isOnBestLevel())
book.bbo(listener);
}
#location 12
#vulnerability type NULL_DEREFERENCE | #fixed code
public void add(long instrument, long orderId, Side side, long price, long size) {
if (orders.containsKey(orderId))
return;
OrderBook book = books.get(instrument);
if (book == null)
return;
Order order = new Order(book, side, price, size);
book.add(side, price, size);
orders.put(orderId, order);
if (order.isOnBestLevel())
book.bbo(listener);
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
public void run() throws IOException {
ConsoleReader reader = new ConsoleReader();
reader.addCompleter(new StringsCompleter(Commands.names().castToList()));
printf("Type 'help' for help.\n");
while (!closed) {
String line = reader.readLine("> ");
if (line == null)
break;
Scanner scanner = scan(line);
if (!scanner.hasNext())
continue;
Command command = Commands.find(scanner.next());
if (command == null) {
printf("error: Unknown command\n");
continue;
}
try {
command.execute(this, scanner);
} catch (CommandException e) {
printf("Usage: %s\n", command.getUsage());
} catch (ClosedChannelException e) {
printf("error: Connection closed\n");
}
}
close();
}
#location 10
#vulnerability type RESOURCE_LEAK | #fixed code
public void run() throws IOException {
LineReader reader = LineReaderBuilder.builder()
.completer(new StringsCompleter(Commands.names().castToList()))
.build();
printf("Type 'help' for help.\n");
while (!closed) {
String line = reader.readLine("> ");
if (line == null)
break;
Scanner scanner = scan(line);
if (!scanner.hasNext())
continue;
Command command = Commands.find(scanner.next());
if (command == null) {
printf("error: Unknown command\n");
continue;
}
try {
command.execute(this, scanner);
} catch (CommandException e) {
printf("Usage: %s\n", command.getUsage());
} catch (ClosedChannelException e) {
printf("error: Connection closed\n");
}
}
close();
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
boolean update(Side side, long price, long quantity) {
Long2LongRBTreeMap levels = getLevels(side);
long oldSize = levels.get(price);
long newSize = oldSize + quantity;
boolean onBestLevel = price == levels.firstLongKey();
if (newSize > 0)
levels.put(price, newSize);
else
levels.remove(price);
return onBestLevel;
}
#location 4
#vulnerability type NULL_DEREFERENCE | #fixed code
OrderBook(long instrument) {
this.instrument = instrument;
this.bids = new Long2LongRBTreeMap(BidComparator.INSTANCE);
this.asks = new Long2LongRBTreeMap(AskComparator.INSTANCE);
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
private static void main(Config config) throws IOException {
MarketDataServer marketData = marketData(config);
String marketReportSession = config.getString("market-report.session");
InetAddress marketReportMulticastGroup = Configs.getInetAddress(config, "market-report.multicast-group");
int marketReportMulticastPort = Configs.getPort(config, "market-report.multicast-port");
int marketReportRequestPort = Configs.getPort(config, "market-report.request-port");
MarketReportServer marketReport = MarketReportServer.create(marketReportSession,
new InetSocketAddress(marketReportMulticastGroup, marketReportMulticastPort),
marketReportRequestPort);
List<String> instruments = config.getStringList("instruments");
MatchingEngine engine = new MatchingEngine(instruments, marketData, marketReport);
int orderEntryPort = Configs.getPort(config, "order-entry.port");
OrderEntryServer orderEntry = OrderEntryServer.create(orderEntryPort, engine);
marketData.version();
new Events(marketData, marketReport, orderEntry).run();
}
#location 23
#vulnerability type RESOURCE_LEAK | #fixed code
private static void main(Config config) throws IOException {
MarketDataServer marketData = marketData(config);
MarketReportServer marketReport = marketReport(config);
List<String> instruments = config.getStringList("instruments");
MatchingEngine engine = new MatchingEngine(instruments, marketData, marketReport);
int orderEntryPort = Configs.getPort(config, "order-entry.port");
OrderEntryServer orderEntry = OrderEntryServer.create(orderEntryPort, engine);
marketData.version();
new Events(marketData, marketReport, orderEntry).run();
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Override
public void run(ApplicationArguments args) throws Exception {
try {
// 测试 Redis连接是否正常
redisService.exists("febs_test");
} catch (Exception e) {
log.error(" ____ __ _ _ ");
log.error("| |_ / /\\ | | | |");
log.error("|_| /_/--\\ |_| |_|__");
log.error(" ");
log.error("FEBS启动失败,{}", e.getMessage());
log.error("Redis连接异常,请检查Redis连接配置并确保Redis服务已启动");
// 关闭 FEBS
context.close();
}
if (context.isActive()) {
InetAddress address = InetAddress.getLocalHost();
String url = String.format("http://%s:%s", address.getHostAddress(), port);
String loginUrl = febsProperties.getShiro().getLoginUrl();
if (StringUtils.isNotBlank(contextPath))
url += contextPath;
if (StringUtils.isNotBlank(loginUrl))
url += loginUrl;
log.info(" __ ___ _ ___ _ ____ _____ ____ ");
log.info("/ /` / / \\ | |\\/| | |_) | | | |_ | | | |_ ");
log.info("\\_\\_, \\_\\_/ |_| | |_| |_|__ |_|__ |_| |_|__ ");
log.info(" ");
log.info("FEBS 权限系统启动完毕,地址:{}", url);
boolean auto = febsProperties.isAutoOpenBrowser();
String[] autoEnv = febsProperties.getAutoOpenBrowserEnv();
int i = Arrays.binarySearch(autoEnv, active);
if (auto && i > 0) {
String osName = System.getProperty("os.name").toLowerCase();
if (osName.contains("windows")) {// 默认为windows时才自动打开页面
//使用默认浏览器打开系统登录页
Runtime.getRuntime().exec("cmd /c start " + url);
}
}
}
}
#location 34
#vulnerability type NULL_DEREFERENCE | #fixed code
@Override
public void run(ApplicationArguments args) throws Exception {
try {
// 测试 Redis连接是否正常
redisService.exists("febs_test");
} catch (Exception e) {
log.error(" ____ __ _ _ ");
log.error("| |_ / /\\ | | | |");
log.error("|_| /_/--\\ |_| |_|__");
log.error(" ");
log.error("FEBS启动失败,{}", e.getMessage());
log.error("Redis连接异常,请检查Redis连接配置并确保Redis服务已启动");
// 关闭 FEBS
context.close();
}
if (context.isActive()) {
InetAddress address = InetAddress.getLocalHost();
String url = String.format("http://%s:%s", address.getHostAddress(), port);
String loginUrl = febsProperties.getShiro().getLoginUrl();
if (StringUtils.isNotBlank(contextPath))
url += contextPath;
if (StringUtils.isNotBlank(loginUrl))
url += loginUrl;
log.info(" __ ___ _ ___ _ ____ _____ ____ ");
log.info("/ /` / / \\ | |\\/| | |_) | | | |_ | | | |_ ");
log.info("\\_\\_, \\_\\_/ |_| | |_| |_|__ |_|__ |_| |_|__ ");
log.info(" ");
log.info("FEBS 权限系统启动完毕,地址:{}", url);
boolean auto = febsProperties.isAutoOpenBrowser();
String[] autoEnv = febsProperties.getAutoOpenBrowserEnv();
if (auto && ArrayUtils.contains(autoEnv, active)) {
String os = System.getProperty("os.name");
// 默认为 windows时才自动打开页面
if (StringUtils.containsIgnoreCase(os, "windows")) {
//使用默认浏览器打开系统登录页
Runtime.getRuntime().exec("cmd /c start " + url);
}
}
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
private String[] extendArgs(String file, String oldargs[], int offset)
throws ArgumentParserException {
List<String> list = new ArrayList<String>();
BufferedReader reader;
try {
reader = new BufferedReader(new InputStreamReader(
new FileInputStream(file), "utf-8"));
String line;
while ((line = reader.readLine()) != null) {
list.add(line);
}
} catch (IOException e) {
throw new ArgumentParserException(String.format(
"Could not read arguments from file '%s'", file), e, this);
}
String newargs[] = new String[list.size() + oldargs.length - offset];
list.toArray(newargs);
System.arraycopy(oldargs, offset, newargs, list.size(), oldargs.length
- offset);
return newargs;
}
#location 12
#vulnerability type RESOURCE_LEAK | #fixed code
private String[] extendArgs(String file, String oldargs[], int offset)
throws ArgumentParserException {
List<String> list = new ArrayList<String>();
BufferedReader reader = null;
try {
reader = new BufferedReader(new InputStreamReader(
new FileInputStream(file), "utf-8"));
String line;
while ((line = reader.readLine()) != null) {
list.add(line);
}
} catch (IOException e) {
throw new ArgumentParserException(String.format(
"Could not read arguments from file '%s'", file), e, this);
} finally {
try {
if(reader != null) {
reader.close();
}
} catch(IOException e) {}
}
String newargs[] = new String[list.size() + oldargs.length - offset];
list.toArray(newargs);
System.arraycopy(oldargs, offset, newargs, list.size(), oldargs.length
- offset);
return newargs;
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
public void saveResource(String resourcePath, boolean replace) {
if (resourcePath == null || resourcePath.equals("")) {
throw new IllegalArgumentException("ResourcePath cannot be null or empty");
}
resourcePath = resourcePath.replace('\\', '/');
InputStream in = getResource(resourcePath);
if (in == null) {
throw new IllegalArgumentException("The embedded resource '" + resourcePath + "' cannot be found in " + getFile());
}
File outFile = new File(getDataFolder(), resourcePath);
int lastIndex = resourcePath.lastIndexOf('/');
File outDir = new File(getDataFolder(), resourcePath.substring(0, lastIndex >= 0 ? lastIndex : 0));
if (!outDir.exists()) {
outDir.mkdirs();
}
try {
if (!outFile.exists() || replace) {
OutputStream out = new FileOutputStream(outFile);
byte[] buf = new byte[1024];
int len;
while ((len = in.read(buf)) > 0) {
out.write(buf, 0, len);
}
out.close();
in.close();
} else {
Logger.getLogger(JavaPlugin.class.getName()).log(Level.WARNING, "Could not save " + outFile.getName() + " to " + outFile + " because " + outFile.getName() + " already exists.");
}
} catch (IOException ex) {
Logger.getLogger(JavaPlugin.class.getName()).log(Level.SEVERE, "Could not save " + outFile.getName() + " to " + outFile, ex);
}
}
#location 33
#vulnerability type RESOURCE_LEAK | #fixed code
public void saveResource(String resourcePath, boolean replace) {
if (resourcePath == null || resourcePath.equals("")) {
throw new IllegalArgumentException("ResourcePath cannot be null or empty");
}
resourcePath = resourcePath.replace('\\', '/');
InputStream in = getResource(resourcePath);
if (in == null) {
throw new IllegalArgumentException("The embedded resource '" + resourcePath + "' cannot be found in " + getFile());
}
File outFile = new File(getDataFolder(), resourcePath);
int lastIndex = resourcePath.lastIndexOf('/');
File outDir = new File(getDataFolder(), resourcePath.substring(0, lastIndex >= 0 ? lastIndex : 0));
if (!outDir.exists()) {
outDir.mkdirs();
}
try {
if (!outFile.exists() || replace) {
OutputStream out = new FileOutputStream(outFile);
byte[] buf = new byte[1024];
int len;
while ((len = in.read(buf)) > 0) {
out.write(buf, 0, len);
}
out.close();
in.close();
} else {
getLogger().log(Level.WARNING, "Could not save " + outFile.getName() + " to " + outFile + " because " + outFile.getName() + " already exists.");
}
} catch (IOException ex) {
getLogger().log(Level.SEVERE, "Could not save " + outFile.getName() + " to " + outFile, ex);
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
public void load(File file) throws FileNotFoundException, IOException, InvalidConfigurationException {
Validate.notNull(file, "File cannot be null");
load(new FileInputStream(file));
}
#location 4
#vulnerability type RESOURCE_LEAK | #fixed code
public void load(File file) throws FileNotFoundException, IOException, InvalidConfigurationException {
Validate.notNull(file, "File cannot be null");
final FileInputStream stream = new FileInputStream(file);
load(new InputStreamReader(stream, UTF8_OVERRIDE && !UTF_BIG ? Charsets.UTF_8 : Charset.defaultCharset()));
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
public Plugin loadPlugin(File file) throws InvalidPluginException, InvalidDescriptionException, UnknownDependencyException {
JavaPlugin result = null;
PluginDescriptionFile description = null;
if (!file.exists()) {
throw new InvalidPluginException(new FileNotFoundException(String.format("%s does not exist", file.getPath())));
}
try {
JarFile jar = new JarFile(file);
JarEntry entry = jar.getJarEntry("plugin.yml");
if (entry == null) {
throw new InvalidPluginException(new FileNotFoundException("Jar does not contain plugin.yml"));
}
InputStream stream = jar.getInputStream(entry);
description = new PluginDescriptionFile(stream);
stream.close();
jar.close();
} catch (IOException ex) {
throw new InvalidPluginException(ex);
} catch (YAMLException ex) {
throw new InvalidPluginException(ex);
}
File dataFolder = new File(file.getParentFile(), description.getName());
File oldDataFolder = getDataFolder(file);
// Found old data folder
if (dataFolder.equals(oldDataFolder)) {
// They are equal -- nothing needs to be done!
} else if (dataFolder.isDirectory() && oldDataFolder.isDirectory()) {
server.getLogger().log( Level.INFO, String.format(
"While loading %s (%s) found old-data folder: %s next to the new one: %s",
description.getName(),
file,
oldDataFolder,
dataFolder
));
} else if (oldDataFolder.isDirectory() && !dataFolder.exists()) {
if (!oldDataFolder.renameTo(dataFolder)) {
throw new InvalidPluginException(new Exception("Unable to rename old data folder: '" + oldDataFolder + "' to: '" + dataFolder + "'"));
}
server.getLogger().log( Level.INFO, String.format(
"While loading %s (%s) renamed data folder: '%s' to '%s'",
description.getName(),
file,
oldDataFolder,
dataFolder
));
}
if (dataFolder.exists() && !dataFolder.isDirectory()) {
throw new InvalidPluginException(new Exception(String.format(
"Projected datafolder: '%s' for %s (%s) exists and is not a directory",
dataFolder,
description.getName(),
file
)));
}
ArrayList<String> depend;
try {
depend = (ArrayList)description.getDepend();
if(depend == null) {
depend = new ArrayList<String>();
}
} catch (ClassCastException ex) {
throw new InvalidPluginException(ex);
}
for(String pluginName : depend) {
if(loaders == null) {
throw new UnknownDependencyException(pluginName);
}
PluginClassLoader current = loaders.get(pluginName);
if(current == null) {
throw new UnknownDependencyException(pluginName);
}
}
PluginClassLoader loader = null;
try {
URL[] urls = new URL[1];
urls[0] = file.toURI().toURL();
loader = new PluginClassLoader(this, urls, getClass().getClassLoader());
Class<?> jarClass = Class.forName(description.getMain(), true, loader);
Class<? extends JavaPlugin> plugin = jarClass.asSubclass(JavaPlugin.class);
Constructor<? extends JavaPlugin> constructor = plugin.getConstructor();
result = constructor.newInstance();
result.initialize(this, server, description, dataFolder, file, loader);
} catch (Throwable ex) {
throw new InvalidPluginException(ex);
}
loaders.put(description.getName(), (PluginClassLoader)loader);
return (Plugin)result;
}
#location 13
#vulnerability type RESOURCE_LEAK | #fixed code
public Plugin loadPlugin(File file) throws InvalidPluginException, InvalidDescriptionException, UnknownDependencyException {
return loadPlugin(file, false);
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Override
public boolean execute(CommandSender sender, String currentAlias, String[] args) {
if (!testPermission(sender)) return true;
if (args.length < 1 || args.length > 4) {
sender.sendMessage(ChatColor.RED + "Usage: " + usageMessage);
return false;
}
Player player;
if (args.length == 1 || args.length == 3) {
if (sender instanceof Player) {
player = (Player) sender;
} else {
sender.sendMessage("Please provide a player!");
return true;
}
} else {
player = Bukkit.getPlayerExact(args[0]);
}
if (player == null) {
sender.sendMessage("Player not found: " + args[0]);
}
if (args.length < 3) {
Player target = Bukkit.getPlayerExact(args[args.length - 1]);
if (target == null) {
sender.sendMessage("Can't find user " + args[args.length - 1] + ". No tp.");
}
player.teleport(target, TeleportCause.COMMAND);
sender.sendMessage("Teleported " + player.getName() + " to " + target.getName());
} else if (player.getWorld() != null) {
int x = getInteger(sender, args[args.length - 3], -30000000, 30000000);
int y = getInteger(sender, args[args.length - 2], 0, 256);
int z = getInteger(sender, args[args.length - 1], -30000000, 30000000);
Location location = new Location(player.getWorld(), x, y, z);
player.teleport(location);
sender.sendMessage("Teleported " + player.getName() + " to " + x + "," + y + "," + z);
}
return true;
}
#location 32
#vulnerability type NULL_DEREFERENCE | #fixed code
@Override
public boolean execute(CommandSender sender, String currentAlias, String[] args) {
if (!testPermission(sender)) return true;
if (args.length < 1 || args.length > 4) {
sender.sendMessage(ChatColor.RED + "Usage: " + usageMessage);
return false;
}
Player player;
if (args.length == 1 || args.length == 3) {
if (sender instanceof Player) {
player = (Player) sender;
} else {
sender.sendMessage("Please provide a player!");
return true;
}
} else {
player = Bukkit.getPlayerExact(args[0]);
}
if (player == null) {
sender.sendMessage("Player not found: " + args[0]);
return true;
}
if (args.length < 3) {
Player target = Bukkit.getPlayerExact(args[args.length - 1]);
if (target == null) {
sender.sendMessage("Can't find user " + args[args.length - 1] + ". No tp.");
return true;
}
player.teleport(target, TeleportCause.COMMAND);
Command.broadcastCommandMessage(sender, "Teleported " + player.getName() + " to " + target.getName());
} else if (player.getWorld() != null) {
int x = getInteger(sender, args[args.length - 3], -30000000, 30000000);
int y = getInteger(sender, args[args.length - 2], 0, 256);
int z = getInteger(sender, args[args.length - 1], -30000000, 30000000);
Location location = new Location(player.getWorld(), x, y, z);
player.teleport(location);
Command.broadcastCommandMessage(sender, "Teleported " + player.getName() + " to " + + x + "," + y + "," + z);
}
return true;
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
public void recalculatePermissions() {
dirtyPermissions = true;
}
#location 2
#vulnerability type THREAD_SAFETY_VIOLATION | #fixed code
public void recalculatePermissions() {
clearPermissions();
Set<Permission> defaults = Bukkit.getServer().getPluginManager().getDefaultPermissions(isOp());
Bukkit.getServer().getPluginManager().subscribeToDefaultPerms(isOp(), parent);
for (Permission perm : defaults) {
String name = perm.getName().toLowerCase();
permissions.put(name, new PermissionAttachmentInfo(parent, name, null, true));
Bukkit.getServer().getPluginManager().subscribeToPermission(name, parent);
calculateChildPermissions(perm.getChildren(), false, null);
}
for (PermissionAttachment attachment : attachments) {
calculateChildPermissions(attachment.getPermissions(), false, attachment);
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
public static String getArchName() {
String osArch = System.getProperty("os.arch");
if(osArch.startsWith("arm")) {
// Java 1.8 introduces a system property to determine armel or armhf
if(System.getProperty("sun.arch.abi") != null && System.getProperty("sun.arch.abi").startsWith("gnueabihf")) {
return translateArchNameToFolderName("armhf");
}
// For java7, we stil need to if run some shell commands to determine ABI of JVM
if(System.getProperty("os.name").contains("Linux")) {
String javaHome = System.getProperty("java.home");
try {
// determine if first JVM found uses ARM hard-float ABI
int exitCode = Runtime.getRuntime().exec("which readelf").waitFor();
if(exitCode == 0) {
String[] cmdarray = {"/bin/sh", "-c", "find '" + javaHome +
"' -name 'libjvm.so' | head -1 | xargs readelf -A | " +
"grep 'Tag_ABI_VFP_args: VFP registers'"};
exitCode = Runtime.getRuntime().exec(cmdarray).waitFor();
if (exitCode == 0) {
return translateArchNameToFolderName("armhf");
}
} else {
System.err.println("WARNING! readelf not found. Cannot check if running on an armhf system, " +
"armel architecture will be presumed.");
}
}
catch(IOException e) {
// ignored: fall back to "arm" arch (soft-float ABI)
}
catch(InterruptedException e) {
// ignored: fall back to "arm" arch (soft-float ABI)
}
}
}
else {
String lc = osArch.toLowerCase(Locale.US);
if(archMapping.containsKey(lc))
return archMapping.get(lc);
}
return translateArchNameToFolderName(osArch);
}
#location 18
#vulnerability type RESOURCE_LEAK | #fixed code
public static String getArchName() {
String osArch = System.getProperty("os.arch");
if(osArch.startsWith("arm")) {
osArch = resolveArmArchType();
}
else {
String lc = osArch.toLowerCase(Locale.US);
if(archMapping.containsKey(lc))
return archMapping.get(lc);
}
return translateArchNameToFolderName(osArch);
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
int enable_load_extension(boolean enable) throws SQLException
{
return call("sqlite3_enable_load_extension", handle, enable ? 1 : 0);
}
#location 3
#vulnerability type THREAD_SAFETY_VIOLATION | #fixed code
int shared_cache(boolean enable) throws SQLException
{
// The shared cache is per-process, so it is useless as
// each nested connection is its own process.
return -1;
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
public void setMaxRows(int max) throws SQLException {
checkOpen();
if (max < 0)
throw new SQLException("max row count must be >= 0");
rs.maxRows = max;
}
#location 2
#vulnerability type THREAD_SAFETY_VIOLATION | #fixed code
public void setMaxRows(int max) throws SQLException {
//checkOpen();
if (max < 0)
throw new SQLException("max row count must be >= 0");
rs.maxRows = max;
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
private static boolean extractAndLoadLibraryFile(String libFolderForCurrentOS, String libraryFileName,
String targetFolder)
{
String nativeLibraryFilePath = libFolderForCurrentOS + "/" + libraryFileName;
final String prefix = "sqlite-3.6.4-";
String extractedLibFileName = prefix + libraryFileName;
File extractedLibFile = new File(targetFolder, extractedLibFileName);
try
{
if (extractedLibFile.exists())
{
// test md5sum value
String md5sum1 = md5sum(SQLiteJDBCLoader.class.getResourceAsStream(nativeLibraryFilePath));
String md5sum2 = md5sum(new FileInputStream(extractedLibFile));
if (md5sum1.equals(md5sum2))
{
return loadNativeLibrary(targetFolder, extractedLibFileName);
}
else
{
// remove old native library file
boolean deletionSucceeded = extractedLibFile.delete();
if (!deletionSucceeded)
{
throw new IOException("failed to remove existing native library file: "
+ extractedLibFile.getAbsolutePath());
}
}
}
// extract file into the current directory
InputStream reader = SQLiteJDBCLoader.class.getResourceAsStream(nativeLibraryFilePath);
FileOutputStream writer = new FileOutputStream(extractedLibFile);
byte[] buffer = new byte[1024];
int bytesRead = 0;
while ((bytesRead = reader.read(buffer)) != -1)
{
writer.write(buffer, 0, bytesRead);
}
writer.close();
reader.close();
if (!System.getProperty("os.name").contains("Windows"))
{
try
{
Runtime.getRuntime().exec(new String[] { "chmod", "755", extractedLibFile.getAbsolutePath() })
.waitFor();
}
catch (Throwable e)
{}
}
return loadNativeLibrary(targetFolder, extractedLibFileName);
}
catch (IOException e)
{
System.err.println(e.getMessage());
return false;
}
catch (NoSuchAlgorithmException e)
{
System.err.println(e.getMessage());
return false;
}
}
#location 16
#vulnerability type RESOURCE_LEAK | #fixed code
private static boolean extractAndLoadLibraryFile(String libFolderForCurrentOS, String libraryFileName,
String targetFolder)
{
String nativeLibraryFilePath = libFolderForCurrentOS + "/" + libraryFileName;
final String prefix = String.format("sqlite-%s-", getVersion());
String extractedLibFileName = prefix + libraryFileName;
File extractedLibFile = new File(targetFolder, extractedLibFileName);
try
{
if (extractedLibFile.exists())
{
// test md5sum value
String md5sum1 = md5sum(SQLiteJDBCLoader.class.getResourceAsStream(nativeLibraryFilePath));
String md5sum2 = md5sum(new FileInputStream(extractedLibFile));
if (md5sum1.equals(md5sum2))
{
return loadNativeLibrary(targetFolder, extractedLibFileName);
}
else
{
// remove old native library file
boolean deletionSucceeded = extractedLibFile.delete();
if (!deletionSucceeded)
{
throw new IOException("failed to remove existing native library file: "
+ extractedLibFile.getAbsolutePath());
}
}
}
// extract file into the current directory
InputStream reader = SQLiteJDBCLoader.class.getResourceAsStream(nativeLibraryFilePath);
FileOutputStream writer = new FileOutputStream(extractedLibFile);
byte[] buffer = new byte[1024];
int bytesRead = 0;
while ((bytesRead = reader.read(buffer)) != -1)
{
writer.write(buffer, 0, bytesRead);
}
writer.close();
reader.close();
if (!System.getProperty("os.name").contains("Windows"))
{
try
{
Runtime.getRuntime().exec(new String[] { "chmod", "755", extractedLibFile.getAbsolutePath() })
.waitFor();
}
catch (Throwable e)
{}
}
return loadNativeLibrary(targetFolder, extractedLibFileName);
}
catch (IOException e)
{
System.err.println(e.getMessage());
return false;
}
catch (NoSuchAlgorithmException e)
{
System.err.println(e.getMessage());
return false;
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
public static String getArchName() {
String osArch = System.getProperty("os.arch");
if(osArch.startsWith("arm")) {
// Java 1.8 introduces a system property to determine armel or armhf
if(System.getProperty("sun.arch.abi") != null && System.getProperty("sun.arch.abi").startsWith("gnueabihf")) {
return translateArchNameToFolderName("armhf");
}
// For java7, we stil need to if run some shell commands to determine ABI of JVM
if(System.getProperty("os.name").contains("Linux")) {
String javaHome = System.getProperty("java.home");
try {
// determine if first JVM found uses ARM hard-float ABI
int exitCode = Runtime.getRuntime().exec("which readelf").waitFor();
if(exitCode == 0) {
String[] cmdarray = {"/bin/sh", "-c", "find '" + javaHome +
"' -name 'libjvm.so' | head -1 | xargs readelf -A | " +
"grep 'Tag_ABI_VFP_args: VFP registers'"};
exitCode = Runtime.getRuntime().exec(cmdarray).waitFor();
if (exitCode == 0) {
return translateArchNameToFolderName("armhf");
}
} else {
System.err.println("WARNING! readelf not found. Cannot check if running on an armhf system, " +
"armel architecture will be presumed.");
}
}
catch(IOException e) {
// ignored: fall back to "arm" arch (soft-float ABI)
}
catch(InterruptedException e) {
// ignored: fall back to "arm" arch (soft-float ABI)
}
}
}
else {
String lc = osArch.toLowerCase(Locale.US);
if(archMapping.containsKey(lc))
return archMapping.get(lc);
}
return translateArchNameToFolderName(osArch);
}
#location 13
#vulnerability type RESOURCE_LEAK | #fixed code
public static String getArchName() {
String osArch = System.getProperty("os.arch");
if(osArch.startsWith("arm")) {
osArch = resolveArmArchType();
}
else {
String lc = osArch.toLowerCase(Locale.US);
if(archMapping.containsKey(lc))
return archMapping.get(lc);
}
return translateArchNameToFolderName(osArch);
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
public int getMaxRows() throws SQLException {
checkOpen();
return rs.maxRows;
}
#location 2
#vulnerability type THREAD_SAFETY_VIOLATION | #fixed code
public int getMaxRows() throws SQLException {
//checkOpen();
return rs.maxRows;
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
public static String getArchName() {
String osArch = System.getProperty("os.arch");
if(osArch.startsWith("arm")) {
// Java 1.8 introduces a system property to determine armel or armhf
if(System.getProperty("sun.arch.abi") != null && System.getProperty("sun.arch.abi").startsWith("gnueabihf")) {
return translateArchNameToFolderName("armhf");
}
// For java7, we stil need to if run some shell commands to determine ABI of JVM
if(System.getProperty("os.name").contains("Linux")) {
String javaHome = System.getProperty("java.home");
try {
// determine if first JVM found uses ARM hard-float ABI
int exitCode = Runtime.getRuntime().exec("which readelf").waitFor();
if(exitCode == 0) {
String[] cmdarray = {"/bin/sh", "-c", "find '" + javaHome +
"' -name 'libjvm.so' | head -1 | xargs readelf -A | " +
"grep 'Tag_ABI_VFP_args: VFP registers'"};
exitCode = Runtime.getRuntime().exec(cmdarray).waitFor();
if (exitCode == 0) {
return translateArchNameToFolderName("armhf");
}
} else {
System.err.println("WARNING! readelf not found. Cannot check if running on an armhf system, " +
"armel architecture will be presumed.");
}
}
catch(IOException e) {
// ignored: fall back to "arm" arch (soft-float ABI)
}
catch(InterruptedException e) {
// ignored: fall back to "arm" arch (soft-float ABI)
}
}
}
else {
String lc = osArch.toLowerCase(Locale.US);
if(archMapping.containsKey(lc))
return archMapping.get(lc);
}
return translateArchNameToFolderName(osArch);
}
#location 9
#vulnerability type NULL_DEREFERENCE | #fixed code
public static String getArchName() {
String osArch = System.getProperty("os.arch");
if(osArch.startsWith("arm")) {
osArch = resolveArmArchType();
}
else {
String lc = osArch.toLowerCase(Locale.US);
if(archMapping.containsKey(lc))
return archMapping.get(lc);
}
return translateArchNameToFolderName(osArch);
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
private static boolean extractAndLoadLibraryFile(String libFolderForCurrentOS, String libraryFileName,
String targetFolder) {
String nativeLibraryFilePath = libFolderForCurrentOS + "/" + libraryFileName;
// Include architecture name in temporary filename in order to avoid conflicts
// when multiple JVMs with different architectures running at the same time
String uuid = UUID.randomUUID().toString();
String extractedLibFileName = String.format("sqlite-%s-%s-%s", getVersion(), uuid, libraryFileName);
String extractedLckFileName = extractedLibFileName + ".lck";
File extractedLibFile = new File(targetFolder, extractedLibFileName);
File extractedLckFile = new File(targetFolder, extractedLckFileName);
try {
// Extract a native library file into the target directory
InputStream reader = SQLiteJDBCLoader.class.getResourceAsStream(nativeLibraryFilePath);
FileOutputStream writer = new FileOutputStream(extractedLibFile);
try {
byte[] buffer = new byte[8192];
int bytesRead = 0;
while((bytesRead = reader.read(buffer)) != -1) {
writer.write(buffer, 0, bytesRead);
}
}
finally {
if(!extractedLckFile.exists()) {
new FileOutputStream(extractedLckFile).close();
}
// Delete the extracted lib file on JVM exit.
extractedLibFile.deleteOnExit();
extractedLckFile.deleteOnExit();
if(writer != null) {
writer.close();
}
if(reader != null) {
reader.close();
}
}
// Set executable (x) flag to enable Java to load the native library
extractedLibFile.setReadable(true);
extractedLibFile.setWritable(true, true);
extractedLibFile.setExecutable(true);
// Check whether the contents are properly copied from the resource folder
{
InputStream nativeIn = SQLiteJDBCLoader.class.getResourceAsStream(nativeLibraryFilePath);
InputStream extractedLibIn = new FileInputStream(extractedLibFile);
try {
if(!contentsEquals(nativeIn, extractedLibIn)) {
throw new RuntimeException(String.format("Failed to write a native library file at %s", extractedLibFile));
}
}
finally {
if(nativeIn != null) {
nativeIn.close();
}
if(extractedLibIn != null) {
extractedLibIn.close();
}
}
}
return loadNativeLibrary(targetFolder, extractedLibFileName);
}
catch(IOException e) {
System.err.println(e.getMessage());
return false;
}
}
#location 66
#vulnerability type RESOURCE_LEAK | #fixed code
private static boolean extractAndLoadLibraryFile(String libFolderForCurrentOS, String libraryFileName,
String targetFolder) {
String nativeLibraryFilePath = libFolderForCurrentOS + "/" + libraryFileName;
// Include architecture name in temporary filename in order to avoid conflicts
// when multiple JVMs with different architectures running at the same time
String uuid = UUID.randomUUID().toString();
String extractedLibFileName = String.format("sqlite-%s-%s-%s", getVersion(), uuid, libraryFileName);
String extractedLckFileName = extractedLibFileName + ".lck";
File extractedLibFile = new File(targetFolder, extractedLibFileName);
File extractedLckFile = new File(targetFolder, extractedLckFileName);
try {
// Extract a native library file into the target directory
InputStream reader = SQLiteJDBCLoader.class.getResourceAsStream(nativeLibraryFilePath);
FileOutputStream writer = new FileOutputStream(extractedLibFile);
if(!extractedLckFile.exists()) {
new FileOutputStream(extractedLckFile).close();
}
try {
byte[] buffer = new byte[8192];
int bytesRead = 0;
while((bytesRead = reader.read(buffer)) != -1) {
writer.write(buffer, 0, bytesRead);
}
}
finally {
// Delete the extracted lib file on JVM exit.
extractedLibFile.deleteOnExit();
extractedLckFile.deleteOnExit();
if(writer != null) {
writer.close();
}
if(reader != null) {
reader.close();
}
}
// Set executable (x) flag to enable Java to load the native library
extractedLibFile.setReadable(true);
extractedLibFile.setWritable(true, true);
extractedLibFile.setExecutable(true);
// Check whether the contents are properly copied from the resource folder
{
InputStream nativeIn = SQLiteJDBCLoader.class.getResourceAsStream(nativeLibraryFilePath);
InputStream extractedLibIn = new FileInputStream(extractedLibFile);
try {
if(!contentsEquals(nativeIn, extractedLibIn)) {
throw new RuntimeException(String.format("Failed to write a native library file at %s", extractedLibFile));
}
}
finally {
if(nativeIn != null) {
nativeIn.close();
}
if(extractedLibIn != null) {
extractedLibIn.close();
}
}
}
return loadNativeLibrary(targetFolder, extractedLibFileName);
}
catch(IOException e) {
System.err.println(e.getMessage());
return false;
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Test
public void basicBusyHandler() throws Exception {
final int[] calls = {0};
BusyHandler.setHandler(conn, new BusyHandler() {
@Override
protected int callback(int nbPrevInvok) throws SQLException {
assertEquals(nbPrevInvok, calls[0]);
calls[0]++;
if (nbPrevInvok <= 1) {
return 1;
} else {
return 0;
}
}
});
BusyWork busyWork = new BusyWork();
busyWork.start();
// I let busyWork prepare a huge insert
Thread.sleep(1000);
synchronized(busyWork){
try{
workWork();
} catch(SQLException ex) {
assertEquals(SQLiteErrorCode.SQLITE_BUSY.code, ex.getErrorCode());
}
}
busyWork.interrupt();
assertEquals(3, calls[0]);
}
#location 4
#vulnerability type THREAD_SAFETY_VIOLATION | #fixed code
@Test
public void basicBusyHandler() throws Exception {
final int[] calls = {0};
BusyHandler.setHandler(conn, new BusyHandler() {
@Override
protected int callback(int nbPrevInvok) throws SQLException {
assertEquals(nbPrevInvok, calls[0]);
calls[0]++;
if (nbPrevInvok <= 1) {
return 1;
} else {
return 0;
}
}
});
BusyWork busyWork = new BusyWork();
busyWork.start();
// let busyWork block inside insert
busyWork.lockedLatch.await();
try{
workWork();
fail("Should throw SQLITE_BUSY exception");
} catch(SQLException ex) {
assertEquals(SQLiteErrorCode.SQLITE_BUSY.code, ex.getErrorCode());
}
busyWork.completeLatch.countDown();
busyWork.join();
assertEquals(3, calls[0]);
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
private static boolean extractAndLoadLibraryFile(String libFolderForCurrentOS, String libraryFileName,
String targetFolder) {
String nativeLibraryFilePath = libFolderForCurrentOS + "/" + libraryFileName;
// Include architecture name in temporary filename in order to avoid conflicts
// when multiple JVMs with different architectures running at the same time
String uuid = UUID.randomUUID().toString();
String extractedLibFileName = String.format("sqlite-%s-%s-%s", getVersion(), uuid, libraryFileName);
File extractedLibFile = new File(targetFolder, extractedLibFileName);
try {
// Extract a native library file into the target directory
InputStream reader = SQLiteJDBCLoader.class.getResourceAsStream(nativeLibraryFilePath);
FileOutputStream writer = new FileOutputStream(extractedLibFile);
try {
byte[] buffer = new byte[8192];
int bytesRead = 0;
while((bytesRead = reader.read(buffer)) != -1) {
writer.write(buffer, 0, bytesRead);
}
} finally {
// Delete the extracted lib file on JVM exit.
extractedLibFile.deleteOnExit();
if(writer != null) {
writer.close();
}
if(reader != null) {
reader.close();
}
}
// Set executable (x) flag to enable Java to load the native library
extractedLibFile.setReadable(true);
extractedLibFile.setWritable(true, true);
extractedLibFile.setExecutable(true);
// Check whether the contents are properly copied from the resource folder
{
InputStream nativeIn = SQLiteJDBCLoader.class.getResourceAsStream(nativeLibraryFilePath);
InputStream extractedLibIn = new FileInputStream(extractedLibFile);
try {
if(!contentsEquals(nativeIn, extractedLibIn)) {
throw new RuntimeException(String.format("Failed to write a native library file at %s", extractedLibFile));
}
} finally {
if(nativeIn != null) {
nativeIn.close();
}
if(extractedLibIn != null) {
extractedLibIn.close();
}
}
}
return loadNativeLibrary(targetFolder, extractedLibFileName);
} catch(IOException e) {
System.err.println(e.getMessage());
return false;
}
}
#location 43
#vulnerability type RESOURCE_LEAK | #fixed code
private static boolean extractAndLoadLibraryFile(String libFolderForCurrentOS, String libraryFileName,
String targetFolder) {
String nativeLibraryFilePath = libFolderForCurrentOS + "/" + libraryFileName;
// Include architecture name in temporary filename in order to avoid conflicts
// when multiple JVMs with different architectures running at the same time
String uuid = UUID.randomUUID().toString();
String extractedLibFileName = String.format("sqlite-%s-%s-%s", getVersion(), uuid, libraryFileName);
String extractedLckFileName = extractedLibFileName + ".lck";
File extractedLibFile = new File(targetFolder, extractedLibFileName);
File extractedLckFile = new File(targetFolder, extractedLckFileName);
try {
// Extract a native library file into the target directory
InputStream reader = SQLiteJDBCLoader.class.getResourceAsStream(nativeLibraryFilePath);
FileOutputStream writer = new FileOutputStream(extractedLibFile);
try {
byte[] buffer = new byte[8192];
int bytesRead = 0;
while((bytesRead = reader.read(buffer)) != -1) {
writer.write(buffer, 0, bytesRead);
}
} finally {
if (!extractedLckFile.exists()) {
new FileOutputStream(extractedLckFile).close();
}
// Delete the extracted lib file on JVM exit.
extractedLibFile.deleteOnExit();
extractedLckFile.deleteOnExit();
if(writer != null) {
writer.close();
}
if(reader != null) {
reader.close();
}
}
// Set executable (x) flag to enable Java to load the native library
extractedLibFile.setReadable(true);
extractedLibFile.setWritable(true, true);
extractedLibFile.setExecutable(true);
// Check whether the contents are properly copied from the resource folder
{
InputStream nativeIn = SQLiteJDBCLoader.class.getResourceAsStream(nativeLibraryFilePath);
InputStream extractedLibIn = new FileInputStream(extractedLibFile);
try {
if(!contentsEquals(nativeIn, extractedLibIn)) {
throw new RuntimeException(String.format("Failed to write a native library file at %s", extractedLibFile));
}
} finally {
if(nativeIn != null) {
nativeIn.close();
}
if(extractedLibIn != null) {
extractedLibIn.close();
}
}
}
return loadNativeLibrary(targetFolder, extractedLibFileName);
} catch(IOException e) {
System.err.println(e.getMessage());
return false;
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
public Map<String,Class<?>> getTypeMap() throws SQLException {
synchronized (typeMap) {
if (this.typeMap == null) {
this.typeMap = new HashMap<String, Class<?>>();
}
return this.typeMap;
}
}
#location 2
#vulnerability type THREAD_SAFETY_VIOLATION | #fixed code
public Map<String,Class<?>> getTypeMap() throws SQLException {
synchronized (this) {
if (this.typeMap == null) {
this.typeMap = new HashMap<String, Class<?>>();
}
return this.typeMap;
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Test
public void testUnregister() throws Exception {
final int[] calls = {0};
BusyHandler.setHandler(conn, new BusyHandler() {
@Override
protected int callback(int nbPrevInvok) throws SQLException {
assertEquals(nbPrevInvok, calls[0]);
calls[0]++;
if (nbPrevInvok <= 1) {
return 1;
} else {
return 0;
}
}
});
BusyWork busyWork = new BusyWork();
busyWork.start();
// I let busyWork prepare a huge insert
Thread.sleep(1000);
synchronized(busyWork){
try{
workWork();
} catch(SQLException ex) {
assertEquals(SQLiteErrorCode.SQLITE_BUSY.code, ex.getErrorCode());
}
}
assertEquals(3, calls[0]);
int totalCalls = calls[0];
BusyHandler.clearHandler(conn);
busyWork = new BusyWork();
busyWork.start();
// I let busyWork prepare a huge insert
Thread.sleep(1000);
synchronized(busyWork){
try{
workWork();
} catch(SQLException ex) {
assertEquals(SQLiteErrorCode.SQLITE_BUSY.code, ex.getErrorCode());
}
}
busyWork.interrupt();
assertEquals(totalCalls, calls[0]);
}
#location 32
#vulnerability type THREAD_SAFETY_VIOLATION | #fixed code
@Test
public void testUnregister() throws Exception {
final int[] calls = {0};
BusyHandler.setHandler(conn, new BusyHandler() {
@Override
protected int callback(int nbPrevInvok) throws SQLException {
assertEquals(nbPrevInvok, calls[0]);
calls[0]++;
if (nbPrevInvok <= 1) {
return 1;
} else {
return 0;
}
}
});
BusyWork busyWork = new BusyWork();
busyWork.start();
// let busyWork block inside insert
busyWork.lockedLatch.await();
try{
workWork();
fail("Should throw SQLITE_BUSY exception");
} catch(SQLException ex) {
assertEquals(SQLiteErrorCode.SQLITE_BUSY.code, ex.getErrorCode());
}
busyWork.completeLatch.countDown();
busyWork.join();
assertEquals(3, calls[0]);
int totalCalls = calls[0];
BusyHandler.clearHandler(conn);
busyWork = new BusyWork();
busyWork.start();
// let busyWork block inside insert
busyWork.lockedLatch.await();
try{
workWork();
fail("Should throw SQLITE_BUSY exception");
} catch(SQLException ex) {
assertEquals(SQLiteErrorCode.SQLITE_BUSY.code, ex.getErrorCode());
}
busyWork.completeLatch.countDown();
busyWork.join();
assertEquals(totalCalls, calls[0]);
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
public static String getArchName() {
String osArch = System.getProperty("os.arch");
if(osArch.startsWith("arm")) {
// Java 1.8 introduces a system property to determine armel or armhf
if(System.getProperty("sun.arch.abi") != null && System.getProperty("sun.arch.abi").startsWith("gnueabihf")) {
return translateArchNameToFolderName("armhf");
}
// For java7, we stil need to if run some shell commands to determine ABI of JVM
if(System.getProperty("os.name").contains("Linux")) {
String javaHome = System.getProperty("java.home");
try {
// determine if first JVM found uses ARM hard-float ABI
int exitCode = Runtime.getRuntime().exec("which readelf").waitFor();
if(exitCode == 0) {
String[] cmdarray = {"/bin/sh", "-c", "find '" + javaHome +
"' -name 'libjvm.so' | head -1 | xargs readelf -A | " +
"grep 'Tag_ABI_VFP_args: VFP registers'"};
exitCode = Runtime.getRuntime().exec(cmdarray).waitFor();
if (exitCode == 0) {
return translateArchNameToFolderName("armhf");
}
} else {
System.err.println("WARNING! readelf not found. Cannot check if running on an armhf system, " +
"armel architecture will be presumed.");
}
}
catch(IOException e) {
// ignored: fall back to "arm" arch (soft-float ABI)
}
catch(InterruptedException e) {
// ignored: fall back to "arm" arch (soft-float ABI)
}
}
}
else {
String lc = osArch.toLowerCase(Locale.US);
if(archMapping.containsKey(lc))
return archMapping.get(lc);
}
return translateArchNameToFolderName(osArch);
}
#location 5
#vulnerability type NULL_DEREFERENCE | #fixed code
public static String getArchName() {
String osArch = System.getProperty("os.arch");
if(osArch.startsWith("arm")) {
osArch = resolveArmArchType();
}
else {
String lc = osArch.toLowerCase(Locale.US);
if(archMapping.containsKey(lc))
return archMapping.get(lc);
}
return translateArchNameToFolderName(osArch);
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
public boolean execute(String sql) throws SQLException {
internalClose();
SQLExtension ext = ExtendedCommand.parse(sql);
if (ext != null) {
ext.execute(db);
return false;
}
this.sql = sql;
boolean success = false;
try {
db.prepare(this);
final boolean result = exec();
success = true;
return result;
} finally {
if (!success) {
internalClose();
}
}
}
#location 2
#vulnerability type THREAD_SAFETY_VIOLATION | #fixed code
public boolean execute(String sql) throws SQLException {
internalClose();
SQLExtension ext = ExtendedCommand.parse(sql);
if (ext != null) {
ext.execute(db);
return false;
}
this.sql = sql;
db.prepare(this);
return exec();
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
public void setTypeMap(Map map) throws SQLException {
synchronized (typeMap) {
this.typeMap = map;
}
}
#location 2
#vulnerability type THREAD_SAFETY_VIOLATION | #fixed code
public void setTypeMap(Map map) throws SQLException {
synchronized (this) {
this.typeMap = map;
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
private static boolean extractAndLoadLibraryFile(String libFolderForCurrentOS, String libraryFileName,
String targetFolder) {
String nativeLibraryFilePath = libFolderForCurrentOS + "/" + libraryFileName;
// Include architecture name in temporary filename in order to avoid conflicts
// when multiple JVMs with different architectures running at the same time
String uuid = UUID.randomUUID().toString();
String extractedLibFileName = String.format("sqlite-%s-%s-%s", getVersion(), uuid, libraryFileName);
File extractedLibFile = new File(targetFolder, extractedLibFileName);
try {
// Extract a native library file into the target directory
InputStream reader = SQLiteJDBCLoader.class.getResourceAsStream(nativeLibraryFilePath);
FileOutputStream writer = new FileOutputStream(extractedLibFile);
try {
byte[] buffer = new byte[8192];
int bytesRead = 0;
while((bytesRead = reader.read(buffer)) != -1) {
writer.write(buffer, 0, bytesRead);
}
} finally {
// Delete the extracted lib file on JVM exit.
extractedLibFile.deleteOnExit();
if(writer != null) {
writer.close();
}
if(reader != null) {
reader.close();
}
}
// Set executable (x) flag to enable Java to load the native library
extractedLibFile.setReadable(true);
extractedLibFile.setWritable(true, true);
extractedLibFile.setExecutable(true);
// Check whether the contents are properly copied from the resource folder
{
InputStream nativeIn = SQLiteJDBCLoader.class.getResourceAsStream(nativeLibraryFilePath);
InputStream extractedLibIn = new FileInputStream(extractedLibFile);
try {
if(!contentsEquals(nativeIn, extractedLibIn)) {
throw new RuntimeException(String.format("Failed to write a native library file at %s", extractedLibFile));
}
} finally {
if(nativeIn != null) {
nativeIn.close();
}
if(extractedLibIn != null) {
extractedLibIn.close();
}
}
}
return loadNativeLibrary(targetFolder, extractedLibFileName);
} catch(IOException e) {
System.err.println(e.getMessage());
return false;
}
}
#location 56
#vulnerability type RESOURCE_LEAK | #fixed code
private static boolean extractAndLoadLibraryFile(String libFolderForCurrentOS, String libraryFileName,
String targetFolder) {
String nativeLibraryFilePath = libFolderForCurrentOS + "/" + libraryFileName;
// Include architecture name in temporary filename in order to avoid conflicts
// when multiple JVMs with different architectures running at the same time
String uuid = UUID.randomUUID().toString();
String extractedLibFileName = String.format("sqlite-%s-%s-%s", getVersion(), uuid, libraryFileName);
String extractedLckFileName = extractedLibFileName + ".lck";
File extractedLibFile = new File(targetFolder, extractedLibFileName);
File extractedLckFile = new File(targetFolder, extractedLckFileName);
try {
// Extract a native library file into the target directory
InputStream reader = SQLiteJDBCLoader.class.getResourceAsStream(nativeLibraryFilePath);
FileOutputStream writer = new FileOutputStream(extractedLibFile);
try {
byte[] buffer = new byte[8192];
int bytesRead = 0;
while((bytesRead = reader.read(buffer)) != -1) {
writer.write(buffer, 0, bytesRead);
}
} finally {
if (!extractedLckFile.exists()) {
new FileOutputStream(extractedLckFile).close();
}
// Delete the extracted lib file on JVM exit.
extractedLibFile.deleteOnExit();
extractedLckFile.deleteOnExit();
if(writer != null) {
writer.close();
}
if(reader != null) {
reader.close();
}
}
// Set executable (x) flag to enable Java to load the native library
extractedLibFile.setReadable(true);
extractedLibFile.setWritable(true, true);
extractedLibFile.setExecutable(true);
// Check whether the contents are properly copied from the resource folder
{
InputStream nativeIn = SQLiteJDBCLoader.class.getResourceAsStream(nativeLibraryFilePath);
InputStream extractedLibIn = new FileInputStream(extractedLibFile);
try {
if(!contentsEquals(nativeIn, extractedLibIn)) {
throw new RuntimeException(String.format("Failed to write a native library file at %s", extractedLibFile));
}
} finally {
if(nativeIn != null) {
nativeIn.close();
}
if(extractedLibIn != null) {
extractedLibIn.close();
}
}
}
return loadNativeLibrary(targetFolder, extractedLibFileName);
} catch(IOException e) {
System.err.println(e.getMessage());
return false;
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
private static boolean extractAndLoadLibraryFile(String libFolderForCurrentOS, String libraryFileName,
String targetFolder)
{
String nativeLibraryFilePath = libFolderForCurrentOS + "/" + libraryFileName;
final String prefix = "sqlite-3.6.4-";
String extractedLibFileName = prefix + libraryFileName;
File extractedLibFile = new File(targetFolder, extractedLibFileName);
try
{
if (extractedLibFile.exists())
{
// test md5sum value
String md5sum1 = md5sum(SQLiteJDBCLoader.class.getResourceAsStream(nativeLibraryFilePath));
String md5sum2 = md5sum(new FileInputStream(extractedLibFile));
if (md5sum1.equals(md5sum2))
{
return loadNativeLibrary(targetFolder, extractedLibFileName);
}
else
{
// remove old native library file
boolean deletionSucceeded = extractedLibFile.delete();
if (!deletionSucceeded)
{
throw new IOException("failed to remove existing native library file: "
+ extractedLibFile.getAbsolutePath());
}
}
}
// extract file into the current directory
InputStream reader = SQLiteJDBCLoader.class.getResourceAsStream(nativeLibraryFilePath);
FileOutputStream writer = new FileOutputStream(extractedLibFile);
byte[] buffer = new byte[1024];
int bytesRead = 0;
while ((bytesRead = reader.read(buffer)) != -1)
{
writer.write(buffer, 0, bytesRead);
}
writer.close();
reader.close();
if (!System.getProperty("os.name").contains("Windows"))
{
try
{
Runtime.getRuntime().exec(new String[] { "chmod", "755", extractedLibFile.getAbsolutePath() })
.waitFor();
}
catch (Throwable e)
{}
}
return loadNativeLibrary(targetFolder, extractedLibFileName);
}
catch (IOException e)
{
System.err.println(e.getMessage());
return false;
}
catch (NoSuchAlgorithmException e)
{
System.err.println(e.getMessage());
return false;
}
}
#location 52
#vulnerability type RESOURCE_LEAK | #fixed code
private static boolean extractAndLoadLibraryFile(String libFolderForCurrentOS, String libraryFileName,
String targetFolder)
{
String nativeLibraryFilePath = libFolderForCurrentOS + "/" + libraryFileName;
final String prefix = String.format("sqlite-%s-", getVersion());
String extractedLibFileName = prefix + libraryFileName;
File extractedLibFile = new File(targetFolder, extractedLibFileName);
try
{
if (extractedLibFile.exists())
{
// test md5sum value
String md5sum1 = md5sum(SQLiteJDBCLoader.class.getResourceAsStream(nativeLibraryFilePath));
String md5sum2 = md5sum(new FileInputStream(extractedLibFile));
if (md5sum1.equals(md5sum2))
{
return loadNativeLibrary(targetFolder, extractedLibFileName);
}
else
{
// remove old native library file
boolean deletionSucceeded = extractedLibFile.delete();
if (!deletionSucceeded)
{
throw new IOException("failed to remove existing native library file: "
+ extractedLibFile.getAbsolutePath());
}
}
}
// extract file into the current directory
InputStream reader = SQLiteJDBCLoader.class.getResourceAsStream(nativeLibraryFilePath);
FileOutputStream writer = new FileOutputStream(extractedLibFile);
byte[] buffer = new byte[1024];
int bytesRead = 0;
while ((bytesRead = reader.read(buffer)) != -1)
{
writer.write(buffer, 0, bytesRead);
}
writer.close();
reader.close();
if (!System.getProperty("os.name").contains("Windows"))
{
try
{
Runtime.getRuntime().exec(new String[] { "chmod", "755", extractedLibFile.getAbsolutePath() })
.waitFor();
}
catch (Throwable e)
{}
}
return loadNativeLibrary(targetFolder, extractedLibFileName);
}
catch (IOException e)
{
System.err.println(e.getMessage());
return false;
}
catch (NoSuchAlgorithmException e)
{
System.err.println(e.getMessage());
return false;
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@GetMapping()
public String profile(ModelMap mmap)
{
SysUser user = getUser();
user.setSex(dictDataService.selectDictLabel("sys_user_sex", user.getSex()));
mmap.put("user", user);
mmap.put("roleGroup", userService.selectUserRoleGroup(user.getUserId()));
mmap.put("postGroup", userService.selectUserPostGroup(user.getUserId()));
return prefix + "/profile";
}
#location 5
#vulnerability type NULL_DEREFERENCE | #fixed code
@GetMapping()
public String profile(ModelMap mmap)
{
SysUser user = getSysUser();
user.setSex(dictDataService.selectDictLabel("sys_user_sex", user.getSex()));
mmap.put("user", user);
mmap.put("roleGroup", userService.selectUserRoleGroup(user.getUserId()));
mmap.put("postGroup", userService.selectUserPostGroup(user.getUserId()));
return prefix + "/profile";
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@GetMapping("/checkPassword")
@ResponseBody
public boolean checkPassword(String password)
{
SysUser user = getUser();
String encrypt = new Md5Hash(user.getLoginName() + password + user.getSalt()).toHex().toString();
if (user.getPassword().equals(encrypt))
{
return true;
}
return false;
}
#location 7
#vulnerability type NULL_DEREFERENCE | #fixed code
@GetMapping("/checkPassword")
@ResponseBody
public boolean checkPassword(String password)
{
SysUser user = getSysUser();
String encrypt = new Md5Hash(user.getLoginName() + password + user.getSalt()).toHex().toString();
if (user.getPassword().equals(encrypt))
{
return true;
}
return false;
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Async
protected void handleLog(final JoinPoint joinPoint, final Exception e)
{
try
{
// 获得注解
Log controllerLog = getAnnotationLog(joinPoint);
if (controllerLog == null)
{
return;
}
// 获取当前的用户
User currentUser = ShiroUtils.getUser();
// *========数据库日志=========*//
OperLog operLog = new OperLog();
operLog.setStatus(BusinessStatus.SUCCESS);
// 请求的地址
String ip = ShiroUtils.getIp();
operLog.setOperIp(ip);
// 操作地点
operLog.setOperLocation(AddressUtils.getRealAddressByIP(ip));
operLog.setOperUrl(ServletUtils.getRequest().getRequestURI());
if (currentUser != null)
{
operLog.setOperName(currentUser.getLoginName());
operLog.setDeptName(currentUser.getDept().getDeptName());
}
if (e != null)
{
operLog.setStatus(BusinessStatus.FAIL);
operLog.setErrorMsg(StringUtils.substring(e.getMessage(), 0, 2000));
}
// 设置方法名称
String className = joinPoint.getTarget().getClass().getName();
String methodName = joinPoint.getSignature().getName();
operLog.setMethod(className + "." + methodName + "()");
// 处理设置注解上的参数
getControllerMethodDescription(controllerLog, operLog);
// 保存数据库
operLogService.insertOperlog(operLog);
}
catch (Exception exp)
{
// 记录本地异常日志
log.error("==前置通知异常==");
log.error("异常信息:{}", exp.getMessage());
exp.printStackTrace();
}
}
#location 29
#vulnerability type NULL_DEREFERENCE | #fixed code
@Async
protected void handleLog(final JoinPoint joinPoint, final Exception e)
{
try
{
// 获得注解
Log controllerLog = getAnnotationLog(joinPoint);
if (controllerLog == null)
{
return;
}
// 获取当前的用户
User currentUser = ShiroUtils.getUser();
// *========数据库日志=========*//
OperLog operLog = new OperLog();
operLog.setStatus(BusinessStatus.SUCCESS);
// 请求的地址
String ip = ShiroUtils.getIp();
operLog.setOperIp(ip);
// 操作地点
operLog.setOperLocation(AddressUtils.getRealAddressByIP(ip));
operLog.setOperUrl(ServletUtils.getRequest().getRequestURI());
if (currentUser != null)
{
operLog.setOperName(currentUser.getLoginName());
if (StringUtils.isNotNull(currentUser.getDept())
&& StringUtils.isEmpty(currentUser.getDept().getDeptName()))
{
operLog.setDeptName(currentUser.getDept().getDeptName());
}
}
if (e != null)
{
operLog.setStatus(BusinessStatus.FAIL);
operLog.setErrorMsg(StringUtils.substring(e.getMessage(), 0, 2000));
}
// 设置方法名称
String className = joinPoint.getTarget().getClass().getName();
String methodName = joinPoint.getSignature().getName();
operLog.setMethod(className + "." + methodName + "()");
// 处理设置注解上的参数
getControllerMethodDescription(controllerLog, operLog);
// 保存数据库
operLogService.insertOperlog(operLog);
}
catch (Exception exp)
{
// 记录本地异常日志
log.error("==前置通知异常==");
log.error("异常信息:{}", exp.getMessage());
exp.printStackTrace();
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@GetMapping("/checkPassword")
@ResponseBody
public boolean checkPassword(String password)
{
SysUser user = getUser();
String encrypt = new Md5Hash(user.getLoginName() + password + user.getSalt()).toHex().toString();
if (user.getPassword().equals(encrypt))
{
return true;
}
return false;
}
#location 6
#vulnerability type NULL_DEREFERENCE | #fixed code
@GetMapping("/checkPassword")
@ResponseBody
public boolean checkPassword(String password)
{
SysUser user = getSysUser();
String encrypt = new Md5Hash(user.getLoginName() + password + user.getSalt()).toHex().toString();
if (user.getPassword().equals(encrypt))
{
return true;
}
return false;
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
public static String getLoginName()
{
return getUser().getLoginName();
}
#location 3
#vulnerability type NULL_DEREFERENCE | #fixed code
public static String getLoginName()
{
return getSysUser().getLoginName();
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
public String getLoginName()
{
return getUser().getLoginName();
}
#location 3
#vulnerability type NULL_DEREFERENCE | #fixed code
public String getLoginName()
{
return getSysUser().getLoginName();
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
public static Long getUserId()
{
return getUser().getUserId().longValue();
}
#location 3
#vulnerability type NULL_DEREFERENCE | #fixed code
public static Long getUserId()
{
return getSysUser().getUserId().longValue();
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
public Long getUserId()
{
return getUser().getUserId();
}
#location 3
#vulnerability type NULL_DEREFERENCE | #fixed code
public Long getUserId()
{
return getSysUser().getUserId();
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
public static Long getUserId()
{
return getUser().getUserId().longValue();
}
#location 3
#vulnerability type NULL_DEREFERENCE | #fixed code
public static Long getUserId()
{
return getSysUser().getUserId().longValue();
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
public List<T> importExcel(String sheetName, InputStream input) throws Exception
{
List<T> list = new ArrayList<T>();
Workbook workbook = WorkbookFactory.create(input);
Sheet sheet = null;
if (StringUtils.isNotEmpty(sheetName))
{
// 如果指定sheet名,则取指定sheet中的内容.
sheet = workbook.getSheet(sheetName);
}
else
{
// 如果传入的sheet名不存在则默认指向第1个sheet.
sheet = workbook.getSheetAt(0);
}
if (sheet == null)
{
throw new IOException("文件sheet不存在");
}
int rows = sheet.getPhysicalNumberOfRows();
if (rows > 0)
{
// 有数据时才处理 得到类的所有field.
Field[] allFields = clazz.getDeclaredFields();
// 定义一个map用于存放列的序号和field.
Map<Integer, Field> fieldsMap = new HashMap<Integer, Field>();
for (int col = 0; col < allFields.length; col++)
{
Field field = allFields[col];
// 将有注解的field存放到map中.
if (field.isAnnotationPresent(Excel.class))
{
// 设置类的私有字段属性可访问.
field.setAccessible(true);
fieldsMap.put(col, field);
}
}
for (int i = 1; i < rows; i++)
{
// 从第2行开始取数据,默认第一行是表头.
Row row = sheet.getRow(i);
int cellNum = sheet.getRow(0).getPhysicalNumberOfCells();
T entity = null;
for (int j = 0; j < cellNum; j++)
{
Cell cell = row.getCell(j);
if (cell == null)
{
continue;
}
else
{
// 先设置Cell的类型,然后就可以把纯数字作为String类型读进来了
row.getCell(j).setCellType(Cell.CELL_TYPE_STRING);
cell = row.getCell(j);
}
String c = cell.getStringCellValue();
if (StringUtils.isEmpty(c))
{
continue;
}
// 如果不存在实例则新建.
entity = (entity == null ? clazz.newInstance() : entity);
// 从map中得到对应列的field.
Field field = fieldsMap.get(j + 1);
// 取得类型,并根据对象类型设置值.
Class<?> fieldType = field.getType();
if (String.class == fieldType)
{
field.set(entity, String.valueOf(c));
}
else if ((Integer.TYPE == fieldType) || (Integer.class == fieldType))
{
field.set(entity, Integer.parseInt(c));
}
else if ((Long.TYPE == fieldType) || (Long.class == fieldType))
{
field.set(entity, Long.valueOf(c));
}
else if ((Float.TYPE == fieldType) || (Float.class == fieldType))
{
field.set(entity, Float.valueOf(c));
}
else if ((Short.TYPE == fieldType) || (Short.class == fieldType))
{
field.set(entity, Short.valueOf(c));
}
else if ((Double.TYPE == fieldType) || (Double.class == fieldType))
{
field.set(entity, Double.valueOf(c));
}
else if (Character.TYPE == fieldType)
{
if ((c != null) && (c.length() > 0))
{
field.set(entity, Character.valueOf(c.charAt(0)));
}
}
else if (java.util.Date.class == fieldType)
{
if (cell.getCellType() == Cell.CELL_TYPE_NUMERIC)
{
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
cell.setCellValue(sdf.format(cell.getNumericCellValue()));
c = sdf.format(cell.getNumericCellValue());
}
else
{
c = cell.getStringCellValue();
}
}
else if (java.math.BigDecimal.class == fieldType)
{
c = cell.getStringCellValue();
}
}
if (entity != null)
{
list.add(entity);
}
}
}
return list;
}
#location 73
#vulnerability type NULL_DEREFERENCE | #fixed code
public List<T> importExcel(String sheetName, InputStream input) throws Exception
{
List<T> list = new ArrayList<T>();
Workbook workbook = WorkbookFactory.create(input);
Sheet sheet = null;
if (StringUtils.isNotEmpty(sheetName))
{
// 如果指定sheet名,则取指定sheet中的内容.
sheet = workbook.getSheet(sheetName);
}
else
{
// 如果传入的sheet名不存在则默认指向第1个sheet.
sheet = workbook.getSheetAt(0);
}
if (sheet == null)
{
throw new IOException("文件sheet不存在");
}
int rows = sheet.getPhysicalNumberOfRows();
if (rows > 0)
{
// 默认序号
int serialNum = 0;
// 有数据时才处理 得到类的所有field.
Field[] allFields = clazz.getDeclaredFields();
// 定义一个map用于存放列的序号和field.
Map<Integer, Field> fieldsMap = new HashMap<Integer, Field>();
for (int col = 0; col < allFields.length; col++)
{
Field field = allFields[col];
// 将有注解的field存放到map中.
if (field.isAnnotationPresent(Excel.class))
{
// 设置类的私有字段属性可访问.
field.setAccessible(true);
fieldsMap.put(++serialNum, field);
}
}
for (int i = 1; i < rows; i++)
{
// 从第2行开始取数据,默认第一行是表头.
Row row = sheet.getRow(i);
int cellNum = serialNum;
T entity = null;
for (int j = 0; j < cellNum; j++)
{
Cell cell = row.getCell(j);
if (cell == null)
{
continue;
}
else
{
// 先设置Cell的类型,然后就可以把纯数字作为String类型读进来了
row.getCell(j).setCellType(CellType.STRING);
cell = row.getCell(j);
}
String c = cell.getStringCellValue();
if (StringUtils.isEmpty(c))
{
continue;
}
// 如果不存在实例则新建.
entity = (entity == null ? clazz.newInstance() : entity);
// 从map中得到对应列的field.
Field field = fieldsMap.get(j + 1);
// 取得类型,并根据对象类型设置值.
Class<?> fieldType = field.getType();
if (String.class == fieldType)
{
field.set(entity, String.valueOf(c));
}
else if ((Integer.TYPE == fieldType) || (Integer.class == fieldType))
{
field.set(entity, Integer.parseInt(c));
}
else if ((Long.TYPE == fieldType) || (Long.class == fieldType))
{
field.set(entity, Long.valueOf(c));
}
else if ((Float.TYPE == fieldType) || (Float.class == fieldType))
{
field.set(entity, Float.valueOf(c));
}
else if ((Short.TYPE == fieldType) || (Short.class == fieldType))
{
field.set(entity, Short.valueOf(c));
}
else if ((Double.TYPE == fieldType) || (Double.class == fieldType))
{
field.set(entity, Double.valueOf(c));
}
else if (Character.TYPE == fieldType)
{
if ((c != null) && (c.length() > 0))
{
field.set(entity, Character.valueOf(c.charAt(0)));
}
}
else if (java.util.Date.class == fieldType)
{
if (cell.getCellTypeEnum() == CellType.NUMERIC)
{
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
cell.setCellValue(sdf.format(cell.getNumericCellValue()));
c = sdf.format(cell.getNumericCellValue());
}
else
{
c = cell.getStringCellValue();
}
}
else if (java.math.BigDecimal.class == fieldType)
{
c = cell.getStringCellValue();
}
}
if (entity != null)
{
list.add(entity);
}
}
}
return list;
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
protected void clearState() {
setConnection(null);
offeredCapabilities = Collections.emptyList();
activeSenders.clear();
activeRequestResponseClients.clear();
failAllCreationRequests();
// make sure we make configured number of attempts to re-connect
connectAttempts = new AtomicInteger(0);
}
#location 4
#vulnerability type THREAD_SAFETY_VIOLATION | #fixed code
protected void clearState() {
setConnection(null);
activeSenders.clear();
activeRequestResponseClients.clear();
failAllCreationRequests();
// make sure we make configured number of attempts to re-connect
connectAttempts = new AtomicInteger(0);
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
protected void onClose(final MqttEndpoint endpoint) {
metrics.decrementMqttConnections(getCredentials(endpoint.auth()).getTenantId());
}
#location 2
#vulnerability type NULL_DEREFERENCE | #fixed code
protected void onClose(final MqttEndpoint endpoint) {
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Test
public void testGetOrCreateSenderFailsOnConnectionFailure(final TestContext ctx) {
// GIVEN a client that tries to create a telemetry sender for "tenant"
ProtonConnection con = mock(ProtonConnection.class);
DisconnectHandlerProvidingConnectionFactory connectionFactory = new DisconnectHandlerProvidingConnectionFactory(con);
final Async connected = ctx.async();
final Async disconnected = ctx.async();
HonoClientImpl client = new HonoClientImpl(vertx, connectionFactory);
client.connect(new ProtonClientOptions(), ctx.asyncAssertSuccess(ok -> connected.complete()));
connected.await(200);
client.getOrCreateSender("telemetry/tenant", creationResultHandler -> {
ctx.assertFalse(disconnected.isCompleted());
}, ctx.asyncAssertFailure(cause -> {
disconnected.complete();
}));
// WHEN the underlying connection fails
connectionFactory.getDisconnectHandler().handle(con);
// THEN all creation requests are failed
disconnected.await(200);
}
#location 20
#vulnerability type NULL_DEREFERENCE | #fixed code
@Test
public void testGetOrCreateSenderFailsOnConnectionFailure(final TestContext ctx) {
// GIVEN a client that tries to create a telemetry sender for "tenant"
final Async connected = ctx.async();
final HonoClientImpl client = new HonoClientImpl(vertx, connectionFactory);
client.connect(new ProtonClientOptions(), ctx.asyncAssertSuccess(ok -> connected.complete()));
connected.await();
final Async disconnected = ctx.async();
client.getOrCreateSender(
"telemetry/tenant",
() -> Future.future(),
ctx.asyncAssertFailure(cause -> {
disconnected.complete();
}));
// WHEN the underlying connection fails
connectionFactory.getDisconnectHandler().handle(con);
// THEN all creation requests are failed
disconnected.await();
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
private void sendRegistrationData(final ProtonDelivery delivery, final Message msg) {
final ResourceIdentifier messageAddress = ResourceIdentifier.fromString(
MessageHelper.getAnnotation(msg, APP_PROPERTY_RESOURCE_ID));
checkPermission(messageAddress, permissionGranted -> {
if (permissionGranted) {
vertx.runOnContext(run -> {
final JsonObject registrationMsg = RegistrationConstants.getRegistrationMsg(msg);
vertx.eventBus().send(EVENT_BUS_ADDRESS_REGISTRATION_IN, registrationMsg,
result -> {
// TODO check for correct session here...?
final String replyTo = msg.getReplyTo();
if (replyTo != null) {
final JsonObject message = (JsonObject) result.result().body();
message.put(APP_PROPERTY_CORRELATION_ID, createCorrelationId(msg));
vertx.eventBus().send(replyTo, message);
} else {
LOG.debug("No reply-to address provided, cannot send reply to client.");
}
});
ProtonHelper.accepted(delivery, true);
});
} else {
LOG.debug("client is not authorized to register devices at [{}]", messageAddress);
MessageHelper.rejected(delivery, UNAUTHORIZED_ACCESS.toString(),
"client is not authorized to register devices at " + messageAddress);
}
});
}
#location 2
#vulnerability type NULL_DEREFERENCE | #fixed code
private void sendRegistrationData(final ProtonDelivery delivery, final Message msg) {
vertx.runOnContext(run -> {
final JsonObject registrationMsg = RegistrationConstants.getRegistrationMsg(msg);
vertx.eventBus().send(EVENT_BUS_ADDRESS_REGISTRATION_IN, registrationMsg,
result -> {
// TODO check for correct session here...?
final String replyTo = msg.getReplyTo();
if (replyTo != null) {
final JsonObject message = (JsonObject) result.result().body();
message.put(APP_PROPERTY_CORRELATION_ID, createCorrelationId(msg));
vertx.eventBus().send(replyTo, message);
} else {
LOG.debug("No reply-to address provided, cannot send reply to client.");
}
});
ProtonHelper.accepted(delivery, true);
});
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
public static Optional<TimeUntilDisconnectNotification> fromMessage(final Message msg) {
if (MessageHelper.isDeviceCurrentlyConnected(msg)) {
final String tenantId = MessageHelper.getTenantIdAnnotation(msg);
final String deviceId = MessageHelper.getDeviceId(msg);
if (tenantId != null && deviceId != null) {
final Integer ttd = MessageHelper.getTimeUntilDisconnect(msg);
final Instant creationTime = Instant.ofEpochMilli(msg.getCreationTime());
final TimeUntilDisconnectNotification notification =
new TimeUntilDisconnectNotification(tenantId, deviceId, getReadyUntilInstantFromTtd(ttd, creationTime));
return Optional.of(notification);
}
}
return Optional.empty();
}
#location 12
#vulnerability type NULL_DEREFERENCE | #fixed code
public static Optional<TimeUntilDisconnectNotification> fromMessage(final Message msg) {
final Integer ttd = MessageHelper.getTimeUntilDisconnect(msg);
if (ttd == null) {
return Optional.empty();
} else if (ttd == 0 || MessageHelper.isDeviceCurrentlyConnected(msg)) {
final String tenantId = MessageHelper.getTenantIdAnnotation(msg);
final String deviceId = MessageHelper.getDeviceId(msg);
if (tenantId != null && deviceId != null) {
final Instant creationTime = Instant.ofEpochMilli(msg.getCreationTime());
final TimeUntilDisconnectNotification notification =
new TimeUntilDisconnectNotification(tenantId, deviceId, getReadyUntilInstantFromTtd(ttd, creationTime));
return Optional.of(notification);
}
}
return Optional.empty();
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Test
public void testGetOrCreateRequestResponseClientFailsOnConnectionFailure(final TestContext ctx) {
// GIVEN a client that tries to create a registration client for "tenant"
ProtonConnection con = mock(ProtonConnection.class);
DisconnectHandlerProvidingConnectionFactory connectionFactory = new DisconnectHandlerProvidingConnectionFactory(con);
final Async connected = ctx.async();
final Async disconnected = ctx.async();
HonoClientImpl client = new HonoClientImpl(vertx, connectionFactory);
client.connect(new ProtonClientOptions(), ctx.asyncAssertSuccess(ok -> connected.complete()));
connected.await(200);
client.getOrCreateRequestResponseClient("registration/tenant", creationResultHandler -> {
ctx.assertFalse(disconnected.isCompleted());
}, ctx.asyncAssertFailure(cause -> {
disconnected.complete();
}));
// WHEN the underlying connection fails
connectionFactory.getDisconnectHandler().handle(con);
// THEN all creation requests are failed
disconnected.await(200);
}
#location 20
#vulnerability type NULL_DEREFERENCE | #fixed code
@Test
public void testGetOrCreateRequestResponseClientFailsOnConnectionFailure(final TestContext ctx) {
// GIVEN a client that tries to create a registration client for "tenant"
final Async connected = ctx.async();
final HonoClientImpl client = new HonoClientImpl(vertx, connectionFactory);
client.connect(new ProtonClientOptions(), ctx.asyncAssertSuccess(ok -> connected.complete()));
connected.await();
final Async creationFailure = ctx.async();
client.getOrCreateRequestResponseClient(
"registration/tenant",
() -> {
ctx.assertFalse(creationFailure.isCompleted());
return Future.future();
},
ctx.asyncAssertFailure(cause -> creationFailure.complete()));
// WHEN the underlying connection fails
connectionFactory.getDisconnectHandler().handle(con);
// THEN all creation requests are failed
creationFailure.await();
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
private R getRequestResponseResult(final Message message) {
final Integer status = MessageHelper.getApplicationProperty(
message.getApplicationProperties(),
MessageHelper.APP_PROPERTY_STATUS,
Integer.class);
final String payload = MessageHelper.getPayload(message);
final CacheDirective cacheDirective = CacheDirective.from(MessageHelper.getCacheDirective(message));
return getResult(status, payload, cacheDirective);
}
#location 9
#vulnerability type NULL_DEREFERENCE | #fixed code
private R getRequestResponseResult(final Message message) {
final Integer status = MessageHelper.getApplicationProperty(
message.getApplicationProperties(),
MessageHelper.APP_PROPERTY_STATUS,
Integer.class);
if (status == null) {
return null;
} else {
final String payload = MessageHelper.getPayload(message);
final CacheDirective cacheDirective = CacheDirective.from(MessageHelper.getCacheDirective(message));
return getResult(status, payload, cacheDirective);
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Test
public void testCreateEventConsumerFailsOnConnectionFailure(final TestContext ctx) {
// GIVEN a client that already tries to create a telemetry sender for "tenant"
ProtonConnection con = mock(ProtonConnection.class);
DisconnectHandlerProvidingConnectionFactory connectionFactory = new DisconnectHandlerProvidingConnectionFactory(con);
final Async connected = ctx.async();
HonoClientImpl client = new HonoClientImpl(vertx, connectionFactory);
client.connect(new ProtonClientOptions(), ctx.asyncAssertSuccess(ok -> connected.complete()));
connected.await(200);
final Async disconnected = ctx.async();
client.createEventConsumer("tenant", msg -> {}, ctx.asyncAssertFailure(cause -> {
disconnected.complete();
}));
// WHEN the underlying connection fails
connectionFactory.getDisconnectHandler().handle(con);
// THEN all creation requests are failed
disconnected.await(200);
}
#location 18
#vulnerability type NULL_DEREFERENCE | #fixed code
@Test
public void testCreateEventConsumerFailsOnConnectionFailure(final TestContext ctx) {
// GIVEN a client that already tries to create a telemetry sender for "tenant"
final Async connected = ctx.async();
final HonoClientImpl client = new HonoClientImpl(vertx, connectionFactory);
client.connect(new ProtonClientOptions(), ctx.asyncAssertSuccess(ok -> connected.complete()));
connected.await();
final Async disconnected = ctx.async();
client.createEventConsumer("tenant", msg -> {}, ctx.asyncAssertFailure(cause -> {
disconnected.complete();
}));
// WHEN the underlying connection fails
connectionFactory.getDisconnectHandler().handle(con);
// THEN all creation requests are failed
disconnected.await();
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Test
public void testConnectTriesToReconnectOnFailedConnectAttempt(final TestContext ctx) {
// GIVEN a client that cannot connect to the server
ProtonConnection con = mock(ProtonConnection.class);
// expect the connection factory to fail twice and succeed on third connect attempt
DisconnectHandlerProvidingConnectionFactory connectionFactory = new DisconnectHandlerProvidingConnectionFactory(con, 1, 2);
HonoClientImpl client = new HonoClientImpl(vertx, connectionFactory);
// WHEN trying to connect
Async disconnectHandlerInvocation = ctx.async();
Async connectionEstablished = ctx.async();
Handler<ProtonConnection> disconnectHandler = failedCon -> disconnectHandlerInvocation.complete();
client.connect(
new ProtonClientOptions().setReconnectAttempts(1),
ctx.asyncAssertSuccess(ok -> connectionEstablished.complete()),
disconnectHandler);
// THEN the client repeatedly tries to connect
connectionEstablished.await(4 * Constants.DEFAULT_RECONNECT_INTERVAL_MILLIS);
// and sets the disconnect handler provided as a param in the connect method invocation
connectionFactory.getDisconnectHandler().handle(con);
disconnectHandlerInvocation.await(1000);
}
#location 22
#vulnerability type NULL_DEREFERENCE | #fixed code
@Test
public void testConnectTriesToReconnectOnFailedConnectAttempt(final TestContext ctx) {
// GIVEN a client that cannot connect to the server
// expect the connection factory to fail twice and succeed on third connect attempt
connectionFactory = new DisconnectHandlerProvidingConnectionFactory(con, 1, 2);
final HonoClientImpl client = new HonoClientImpl(vertx, connectionFactory);
// WHEN trying to connect
Async disconnectHandlerInvocation = ctx.async();
Async connectionEstablished = ctx.async();
client.connect(
new ProtonClientOptions().setReconnectAttempts(1),
ctx.asyncAssertSuccess(ok -> connectionEstablished.complete()),
failedCon -> disconnectHandlerInvocation.complete());
// THEN the client repeatedly tries to connect
connectionEstablished.await(4 * Constants.DEFAULT_RECONNECT_INTERVAL_MILLIS);
// and sets the disconnect handler provided as a param in the connect method invocation
connectionFactory.getDisconnectHandler().handle(con);
disconnectHandlerInvocation.await();
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Test
public void testCreateTelemetryConsumerFailsOnConnectionFailure(final TestContext ctx) {
// GIVEN a client that already tries to create a telemetry sender for "tenant"
ProtonConnection con = mock(ProtonConnection.class);
DisconnectHandlerProvidingConnectionFactory connectionFactory = new DisconnectHandlerProvidingConnectionFactory(con);
final Async connected = ctx.async();
final Async disconnected = ctx.async();
HonoClientImpl client = new HonoClientImpl(vertx, connectionFactory);
client.connect(new ProtonClientOptions(), ctx.asyncAssertSuccess(ok -> connected.complete()));
connected.await(200);
client.createTelemetryConsumer("tenant", msg -> {}, ctx.asyncAssertFailure(cause -> {
disconnected.complete();
}));
// WHEN the underlying connection fails
connectionFactory.getDisconnectHandler().handle(con);
// THEN all creation requests are failed
disconnected.await(200);
}
#location 18
#vulnerability type NULL_DEREFERENCE | #fixed code
@Test
public void testCreateTelemetryConsumerFailsOnConnectionFailure(final TestContext ctx) {
// GIVEN a client that already tries to create a telemetry sender for "tenant"
final Async connected = ctx.async();
final HonoClientImpl client = new HonoClientImpl(vertx, connectionFactory);
client.connect(new ProtonClientOptions(), ctx.asyncAssertSuccess(ok -> connected.complete()));
connected.await();
final Async disconnected = ctx.async();
client.createTelemetryConsumer("tenant", msg -> {}, ctx.asyncAssertFailure(cause -> {
disconnected.complete();
}));
// WHEN the underlying connection fails
connectionFactory.getDisconnectHandler().handle(con);
// THEN all creation requests are failed
disconnected.await();
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Test
public void testDownstreamDisconnectTriggersReconnect(final TestContext ctx) {
final ProtonConnection connectionToCreate = mock(ProtonConnection.class);
when(connectionToCreate.getRemoteContainer()).thenReturn("server");
// expect the connection factory to be invoked twice
// first on initial connection
// second on re-connect attempt
DisconnectHandlerProvidingConnectionFactory connectionFactory = new DisconnectHandlerProvidingConnectionFactory(connectionToCreate, 2);
// GIVEN an client connected to a server
final Async connected = ctx.async();
HonoClientImpl client = new HonoClientImpl(vertx, connectionFactory);
client.connect(new ProtonClientOptions().setReconnectAttempts(1), ctx.asyncAssertSuccess(ok -> connected.complete()));
connected.await(200);
// WHEN the downstream connection fails
connectionFactory.getDisconnectHandler().handle(connectionToCreate);
// THEN the adapter tries to reconnect to the downstream container
connectionFactory.await(1, TimeUnit.SECONDS);
}
#location 18
#vulnerability type NULL_DEREFERENCE | #fixed code
@Test
public void testDownstreamDisconnectTriggersReconnect(final TestContext ctx) {
// expect the connection factory to be invoked twice
// first on initial connection
// second on re-connect attempt
connectionFactory = new DisconnectHandlerProvidingConnectionFactory(con, 2);
// GIVEN an client connected to a server
final Async connected = ctx.async();
final HonoClientImpl client = new HonoClientImpl(vertx, connectionFactory);
client.connect(new ProtonClientOptions().setReconnectAttempts(1), ctx.asyncAssertSuccess(ok -> connected.complete()));
connected.await();
// WHEN the downstream connection fails
connectionFactory.getDisconnectHandler().handle(con);
// THEN the adapter reconnects to the downstream container
connectionFactory.await(1, TimeUnit.SECONDS);
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
private void sendTelemetryData(final LinkWrapper link, final ProtonDelivery delivery, final Message msg) {
if (!delivery.remotelySettled()) {
LOG.trace("received un-settled telemetry message on link [{}]", link.getLinkId());
}
final ResourceIdentifier messageAddress = ResourceIdentifier.fromString(MessageHelper.getAnnotation(msg, APP_PROPERTY_RESOURCE_ID));
checkDeviceExists(messageAddress, deviceExists -> {
if (deviceExists) {
vertx.runOnContext(run -> {
final String messageId = UUID.randomUUID().toString();
final AmqpMessage amqpMessage = AmqpMessage.of(msg, delivery);
vertx.sharedData().getLocalMap(dataAddress).put(messageId, amqpMessage);
sendAtMostOnce(link, messageId, delivery);
});
} else {
LOG.debug("Device {}/{} does not exist, rejecting message.",
messageAddress.getTenantId(), messageAddress.getDeviceId());
ProtonHelper.rejected(delivery, true);
onLinkDetach(link);
}
});
}
#location 5
#vulnerability type NULL_DEREFERENCE | #fixed code
private void sendTelemetryData(final LinkWrapper link, final ProtonDelivery delivery, final Message msg) {
if (!delivery.remotelySettled()) {
LOG.trace("received un-settled telemetry message on link [{}]", link.getLinkId());
}
final ResourceIdentifier messageAddress = ResourceIdentifier.fromString(getAnnotation(msg, APP_PROPERTY_RESOURCE_ID, String.class));
checkDeviceExists(messageAddress, deviceExists -> {
if (deviceExists) {
vertx.runOnContext(run -> {
final String messageId = UUID.randomUUID().toString();
final AmqpMessage amqpMessage = AmqpMessage.of(msg, delivery);
vertx.sharedData().getLocalMap(dataAddress).put(messageId, amqpMessage);
sendAtMostOnce(link, messageId, delivery);
});
} else {
LOG.debug("device {}/{} does not exist, closing link",
messageAddress.getTenantId(), messageAddress.getDeviceId());
MessageHelper.rejected(delivery, AmqpError.PRECONDITION_FAILED.toString(), "device does not exist");
onLinkDetach(link);
}
});
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Test
public void TestEachOnce() throws IOException {
//Each record exactly once - see commit b8f6d6dfaf11cce7d8cba54e6011e8684ade0e85, issue #68
Assert.assertArrayEquals(new int[] { 0, 1 }, getRecordIndexesInReader(getReaderFor("unenclosed-json-simple.json", 0, 63)));
Assert.assertArrayEquals(new int[] { 2, 3 }, getRecordIndexesInReader(getReaderFor("unenclosed-json-simple.json", 63, 121)));
Assert.assertArrayEquals(new int[] { 4 }, getRecordIndexesInReader(getReaderFor("unenclosed-json-simple.json", 121, 187)));
Assert.assertArrayEquals(new int[] { 5, 6 }, getRecordIndexesInReader(getReaderFor("unenclosed-json-simple.json", 187, 264)));
Assert.assertArrayEquals(new int[] { 7, 8 }, getRecordIndexesInReader(getReaderFor("unenclosed-json-simple.json", 264, 352)));
Assert.assertArrayEquals(new int[] { 9 }, getRecordIndexesInReader(getReaderFor("unenclosed-json-simple.json", 352, 412)));
Assert.assertArrayEquals(new int[] { 0 }, getRecordIndexesInReader(getReaderFor("unenclosed-json-simple.json", 0, 23)));
Assert.assertArrayEquals(new int[] { 1 }, getRecordIndexesInReader(getReaderFor("unenclosed-json-simple.json", 23, 41)));
// Assert.assertArrayEquals(new int[] { 2, 3 }, getRecordIndexesInReader(getReaderFor("unenclosed-json-simple.json", 41, 123)));
}
#location 11
#vulnerability type RESOURCE_LEAK | #fixed code
@Test
public void TestEachOnce() throws Exception {
//Each record exactly once - see commit b8f6d6dfaf11cce7d8cba54e6011e8684ade0e85, issue #68
Assert.assertArrayEquals(new int[] { 0, 1 }, getRecordIndexesInReader(getReaderFor("unenclosed-json-simple.json", 0, 63)));
Assert.assertArrayEquals(new int[] { 2, 3 }, getRecordIndexesInReader(getReaderFor("unenclosed-json-simple.json", 63, 121)));
Assert.assertArrayEquals(new int[] { 4 }, getRecordIndexesInReader(getReaderFor("unenclosed-json-simple.json", 121, 187)));
Assert.assertArrayEquals(new int[] { 5, 6 }, getRecordIndexesInReader(getReaderFor("unenclosed-json-simple.json", 187, 264)));
Assert.assertArrayEquals(new int[] { 7, 8 }, getRecordIndexesInReader(getReaderFor("unenclosed-json-simple.json", 264, 352)));
Assert.assertArrayEquals(new int[] { 9 }, getRecordIndexesInReader(getReaderFor("unenclosed-json-simple.json", 352, 412)));
Assert.assertArrayEquals(new int[] { 0 }, getRecordIndexesInReader(getReaderFor("unenclosed-json-simple.json", 0, 23)));
Assert.assertArrayEquals(new int[] { 1 }, getRecordIndexesInReader(getReaderFor("unenclosed-json-simple.json", 23, 41)));
// Assert.assertArrayEquals(new int[] { 2, 3 }, getRecordIndexesInReader(getReaderFor("unenclosed-json-simple.json", 41, 123)));
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Test
public void TestArbitrarySplitLocations() throws IOException {
//int totalSize = 415;
//int [] recordBreaks = new int[] { 0, 40, 80, 120, 160, 200, 240, 280, 320, 372 };
Assert.assertArrayEquals(new int[] { 0 }, getRecordIndexesInReader(getReaderFor("unenclosed-json-simple.json", 0, 40)));
Assert.assertArrayEquals(new int[] { 0, 1 }, getRecordIndexesInReader(getReaderFor("unenclosed-json-simple.json", 0, 41)));
Assert.assertArrayEquals(new int[] { 0, 1 }, getRecordIndexesInReader(getReaderFor("unenclosed-json-simple.json", 0, 42)));
Assert.assertArrayEquals(new int[] { 1, 2, 3 }, getRecordIndexesInReader(getReaderFor("unenclosed-json-simple.json", 39, 123)));
Assert.assertArrayEquals(new int[] { 1, 2, 3 }, getRecordIndexesInReader(getReaderFor("unenclosed-json-simple.json", 20, 123)));
Assert.assertArrayEquals(new int[] { 1, 2, 3 }, getRecordIndexesInReader(getReaderFor("unenclosed-json-simple.json", 40, 123)));
Assert.assertArrayEquals(new int[] { 2, 3 }, getRecordIndexesInReader(getReaderFor("unenclosed-json-simple.json", 41, 123)));
Assert.assertArrayEquals(new int[] { 6, 7, 8 }, getRecordIndexesInReader(getReaderFor("unenclosed-json-simple.json", 240, 340)));
Assert.assertArrayEquals(new int[] { 9 }, getRecordIndexesInReader(getReaderFor("unenclosed-json-simple.json", 353, 415)));
Assert.assertArrayEquals(new int[] { 9 }, getRecordIndexesInReader(getReaderFor("unenclosed-json-simple.json", 354, 415)));
Assert.assertArrayEquals(new int[] { 9 }, getRecordIndexesInReader(getReaderFor("unenclosed-json-simple.json", 355, 415)));
}
#location 12
#vulnerability type RESOURCE_LEAK | #fixed code
@Test
public void TestArbitrarySplitLocations() throws Exception {
//int totalSize = 415;
//int [] recordBreaks = new int[] { 0, 40, 80, 120, 160, 200, 240, 280, 320, 372 };
Assert.assertArrayEquals(new int[] { 0 }, getRecordIndexesInReader(getReaderFor("unenclosed-json-simple.json", 0, 40)));
Assert.assertArrayEquals(new int[] { 0, 1 }, getRecordIndexesInReader(getReaderFor("unenclosed-json-simple.json", 0, 41)));
Assert.assertArrayEquals(new int[] { 0, 1 }, getRecordIndexesInReader(getReaderFor("unenclosed-json-simple.json", 0, 42)));
Assert.assertArrayEquals(new int[] { 1, 2, 3 }, getRecordIndexesInReader(getReaderFor("unenclosed-json-simple.json", 39, 123)));
Assert.assertArrayEquals(new int[] { 1, 2, 3 }, getRecordIndexesInReader(getReaderFor("unenclosed-json-simple.json", 20, 123)));
Assert.assertArrayEquals(new int[] { 1, 2, 3 }, getRecordIndexesInReader(getReaderFor("unenclosed-json-simple.json", 40, 123)));
Assert.assertArrayEquals(new int[] { 2, 3 }, getRecordIndexesInReader(getReaderFor("unenclosed-json-simple.json", 41, 123)));
Assert.assertArrayEquals(new int[] { 6, 7, 8 }, getRecordIndexesInReader(getReaderFor("unenclosed-json-simple.json", 240, 340)));
Assert.assertArrayEquals(new int[] { 9 }, getRecordIndexesInReader(getReaderFor("unenclosed-json-simple.json", 353, 415)));
Assert.assertArrayEquals(new int[] { 9 }, getRecordIndexesInReader(getReaderFor("unenclosed-json-simple.json", 354, 415)));
Assert.assertArrayEquals(new int[] { 9 }, getRecordIndexesInReader(getReaderFor("unenclosed-json-simple.json", 355, 415)));
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Test
public void TestEscCloseLast() throws IOException {
//int [] recordBreaks = new int[] { 0, 75, 146, 218, 290, 362, , , };
Assert.assertArrayEquals(new int[] { 0 }, getRecordIndexesInReader(getReaderFor("unenclosed-json-esc4.json", 0, 44)));
Assert.assertArrayEquals(new int[] {0, 1}, getRecordIndexesInReader(getReaderFor("unenclosed-json-esc4.json", 0, 45)));
Assert.assertArrayEquals(new int[] {0, 1}, getRecordIndexesInReader(getReaderFor("unenclosed-json-esc4.json", 0, 46)));
Assert.assertArrayEquals(new int[] {1,2,3}, getRecordIndexesInReader(getReaderFor("unenclosed-json-esc4.json", 19, 140)));
Assert.assertArrayEquals(new int[] {1,2,3}, getRecordIndexesInReader(getReaderFor("unenclosed-json-esc4.json", 25, 140)));
Assert.assertArrayEquals(new int[] {1,2,3}, getRecordIndexesInReader(getReaderFor("unenclosed-json-esc4.json", 44, 140)));
}
#location 5
#vulnerability type RESOURCE_LEAK | #fixed code
@Test
public void TestEscCloseLast() throws Exception {
//int [] recordBreaks = new int[] { 0, 75, 146, 218, 290, 362, , , };
Assert.assertArrayEquals(new int[] { 0 }, getRecordIndexesInReader(getReaderFor("unenclosed-json-esc4.json", 0, 44)));
Assert.assertArrayEquals(new int[] {0, 1}, getRecordIndexesInReader(getReaderFor("unenclosed-json-esc4.json", 0, 45)));
Assert.assertArrayEquals(new int[] {0, 1}, getRecordIndexesInReader(getReaderFor("unenclosed-json-esc4.json", 0, 46)));
Assert.assertArrayEquals(new int[] {1,2,3}, getRecordIndexesInReader(getReaderFor("unenclosed-json-esc4.json", 19, 140)));
Assert.assertArrayEquals(new int[] {1,2,3}, getRecordIndexesInReader(getReaderFor("unenclosed-json-esc4.json", 25, 140)));
Assert.assertArrayEquals(new int[] {1,2,3}, getRecordIndexesInReader(getReaderFor("unenclosed-json-esc4.json", 44, 140)));
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Test
public void TestIntOnly() throws Exception { // Is this valid for GeoJSON?
Configuration config = new Configuration();
Text value = new Text();
SerDe jserde = new GeoJsonSerDe();
Properties proptab = new Properties();
proptab.setProperty(HiveShims.serdeConstants.LIST_COLUMNS, "num");
proptab.setProperty(HiveShims.serdeConstants.LIST_COLUMN_TYPES, "int");
jserde.initialize(config, proptab);
StructObjectInspector rowOI = (StructObjectInspector)jserde.getObjectInspector();
value.set("{\"properties\":{\"num\":7}}");
Object row = jserde.deserialize(value);
StructField f0 = rowOI.getStructFieldRef("num");
Object fieldData = rowOI.getStructFieldData(row, f0);
Assert.assertEquals(7, ((IntWritable)fieldData).get());
value.set("{\"properties\":{\"num\":9}}");
row = jserde.deserialize(value);
f0 = rowOI.getStructFieldRef("num");
fieldData = rowOI.getStructFieldData(row, f0);
Assert.assertEquals(9, ((IntWritable)fieldData).get());
}
#location 15
#vulnerability type NULL_DEREFERENCE | #fixed code
@Test
public void TestIntOnly() throws Exception { // Is this valid for GeoJSON?
ArrayList<Object> stuff = new ArrayList<Object>();
Properties proptab = new Properties();
proptab.setProperty(HiveShims.serdeConstants.LIST_COLUMNS, "num");
proptab.setProperty(HiveShims.serdeConstants.LIST_COLUMN_TYPES, "int");
SerDe jserde = mkSerDe(proptab);
StructObjectInspector rowOI = (StructObjectInspector)jserde.getObjectInspector();
//value.set("{\"properties\":{\"num\":7}}");
addWritable(stuff, 7);
Object row = runSerDe(stuff, jserde, rowOI);
Object fieldData = getField("num", row, rowOI);
Assert.assertEquals(7, ((IntWritable)fieldData).get());
stuff.clear();
addWritable(stuff, 9);
row = runSerDe(stuff, jserde, rowOI);
fieldData = getField("num", row, rowOI);
Assert.assertEquals(9, ((IntWritable)fieldData).get());
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Test
public void TestEscQuoteLast() throws IOException {
//int [] recordBreaks = new int[] { 0, 75, 146, 218, 290, 362, , , };
Assert.assertArrayEquals(new int[] { 0 }, getRecordIndexesInReader(getReaderFor("unenclosed-json-esc1.json", 0, 44)));
Assert.assertArrayEquals(new int[] {0, 1}, getRecordIndexesInReader(getReaderFor("unenclosed-json-esc1.json", 0, 45)));
Assert.assertArrayEquals(new int[] {0, 1}, getRecordIndexesInReader(getReaderFor("unenclosed-json-esc1.json", 0, 46)));
Assert.assertArrayEquals(new int[] {1,2,3}, getRecordIndexesInReader(getReaderFor("unenclosed-json-esc1.json", 19, 140)));
Assert.assertArrayEquals(new int[] {1,2,3}, getRecordIndexesInReader(getReaderFor("unenclosed-json-esc1.json", 25, 140)));
Assert.assertArrayEquals(new int[] {1,2,3}, getRecordIndexesInReader(getReaderFor("unenclosed-json-esc1.json", 44, 140)));
}
#location 6
#vulnerability type RESOURCE_LEAK | #fixed code
@Test
public void TestEscQuoteLast() throws Exception {
//int [] recordBreaks = new int[] { 0, 75, 146, 218, 290, 362, , , };
Assert.assertArrayEquals(new int[] { 0 }, getRecordIndexesInReader(getReaderFor("unenclosed-json-esc1.json", 0, 44)));
Assert.assertArrayEquals(new int[] {0, 1}, getRecordIndexesInReader(getReaderFor("unenclosed-json-esc1.json", 0, 45)));
Assert.assertArrayEquals(new int[] {0, 1}, getRecordIndexesInReader(getReaderFor("unenclosed-json-esc1.json", 0, 46)));
Assert.assertArrayEquals(new int[] {1,2,3}, getRecordIndexesInReader(getReaderFor("unenclosed-json-esc1.json", 19, 140)));
Assert.assertArrayEquals(new int[] {1,2,3}, getRecordIndexesInReader(getReaderFor("unenclosed-json-esc1.json", 25, 140)));
Assert.assertArrayEquals(new int[] {1,2,3}, getRecordIndexesInReader(getReaderFor("unenclosed-json-esc1.json", 44, 140)));
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Test
public void TestArbitrarySplitLocations() throws Exception {
//int totalSize = 415;
//int [] recordBreaks = new int[] { 0, 40, 80, 120, 160, 200, 240, 280, 320, 372 };
Assert.assertArrayEquals(new int[] { 0 }, getRecordIndexesInReader(getReaderFor("unenclosed-json-simple.json", 0, 40)));
Assert.assertArrayEquals(new int[] { 0, 1 }, getRecordIndexesInReader(getReaderFor("unenclosed-json-simple.json", 0, 41)));
Assert.assertArrayEquals(new int[] { 0, 1 }, getRecordIndexesInReader(getReaderFor("unenclosed-json-simple.json", 0, 42)));
Assert.assertArrayEquals(new int[] { 1, 2, 3 }, getRecordIndexesInReader(getReaderFor("unenclosed-json-simple.json", 39, 123)));
Assert.assertArrayEquals(new int[] { 1, 2, 3 }, getRecordIndexesInReader(getReaderFor("unenclosed-json-simple.json", 20, 123)));
Assert.assertArrayEquals(new int[] { 1, 2, 3 }, getRecordIndexesInReader(getReaderFor("unenclosed-json-simple.json", 40, 123)));
Assert.assertArrayEquals(new int[] { 2, 3 }, getRecordIndexesInReader(getReaderFor("unenclosed-json-simple.json", 41, 123)));
Assert.assertArrayEquals(new int[] { 6, 7, 8 }, getRecordIndexesInReader(getReaderFor("unenclosed-json-simple.json", 240, 340)));
Assert.assertArrayEquals(new int[] { 9 }, getRecordIndexesInReader(getReaderFor("unenclosed-json-simple.json", 353, 415)));
Assert.assertArrayEquals(new int[] { 9 }, getRecordIndexesInReader(getReaderFor("unenclosed-json-simple.json", 354, 415)));
Assert.assertArrayEquals(new int[] { 9 }, getRecordIndexesInReader(getReaderFor("unenclosed-json-simple.json", 355, 415)));
}
#location 11
#vulnerability type RESOURCE_LEAK | #fixed code
@Test
public void TestArbitrarySplitLocations() throws Exception {
//int totalSize = 415;
//int [] recordBreaks = new int[] { 0, 40, 80, 120, 160, 200, 240, 280, 320, 372 };
Assert.assertArrayEquals(new int[] { 0 }, getRecordIndexesInReader(getReaderFor("unenclosed-json-simple.json", 0, 40)));
Assert.assertArrayEquals(new int[] { 0, 1 }, getRecordIndexesInReader(getReaderFor("unenclosed-json-simple.json", 0, 41)));
Assert.assertArrayEquals(new int[] { 0, 1 }, getRecordIndexesInReader(getReaderFor("unenclosed-json-simple.json", 0, 42)));
Assert.assertArrayEquals(new int[] { 1, 2, 3 }, getRecordIndexesInReader(getReaderFor("unenclosed-json-simple.json", 39, 123)));
Assert.assertArrayEquals(new int[] { 1, 2, 3 }, getRecordIndexesInReader(getReaderFor("unenclosed-json-simple.json", 20, 123)));
Assert.assertArrayEquals(new int[] { 1, 2, 3 }, getRecordIndexesInReader(getReaderFor("unenclosed-json-simple.json", 40, 123)));
Assert.assertArrayEquals(new int[] { 2, 3 }, getRecordIndexesInReader(getReaderFor("unenclosed-json-simple.json", 41, 123)));
Assert.assertArrayEquals(new int[] { 6, 7, 8 }, getRecordIndexesInReader(getReaderFor("unenclosed-json-simple.json", 240, 340)));
Assert.assertArrayEquals(new int[] { 9 }, getRecordIndexesInReader(getReaderFor("unenclosed-json-simple.json", 353, 415)));
Assert.assertArrayEquals(new int[] { 9 }, getRecordIndexesInReader(getReaderFor("unenclosed-json-simple.json", 354, 415)));
Assert.assertArrayEquals(new int[] { 9 }, getRecordIndexesInReader(getReaderFor("unenclosed-json-simple.json", 355, 415)));
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Test
public void TestArbitrarySplitLocations() throws Exception {
//int totalSize = 415;
//int [] recordBreaks = new int[] { 0, 40, 80, 120, 160, 200, 240, 280, 320, 372 };
Assert.assertArrayEquals(new int[] { 0 }, getRecordIndexesInReader(getReaderFor("unenclosed-json-simple.json", 0, 40)));
Assert.assertArrayEquals(new int[] { 0, 1 }, getRecordIndexesInReader(getReaderFor("unenclosed-json-simple.json", 0, 41)));
Assert.assertArrayEquals(new int[] { 0, 1 }, getRecordIndexesInReader(getReaderFor("unenclosed-json-simple.json", 0, 42)));
Assert.assertArrayEquals(new int[] { 1, 2, 3 }, getRecordIndexesInReader(getReaderFor("unenclosed-json-simple.json", 39, 123)));
Assert.assertArrayEquals(new int[] { 1, 2, 3 }, getRecordIndexesInReader(getReaderFor("unenclosed-json-simple.json", 20, 123)));
Assert.assertArrayEquals(new int[] { 1, 2, 3 }, getRecordIndexesInReader(getReaderFor("unenclosed-json-simple.json", 40, 123)));
Assert.assertArrayEquals(new int[] { 2, 3 }, getRecordIndexesInReader(getReaderFor("unenclosed-json-simple.json", 41, 123)));
Assert.assertArrayEquals(new int[] { 6, 7, 8 }, getRecordIndexesInReader(getReaderFor("unenclosed-json-simple.json", 240, 340)));
Assert.assertArrayEquals(new int[] { 9 }, getRecordIndexesInReader(getReaderFor("unenclosed-json-simple.json", 353, 415)));
Assert.assertArrayEquals(new int[] { 9 }, getRecordIndexesInReader(getReaderFor("unenclosed-json-simple.json", 354, 415)));
Assert.assertArrayEquals(new int[] { 9 }, getRecordIndexesInReader(getReaderFor("unenclosed-json-simple.json", 355, 415)));
}
#location 14
#vulnerability type RESOURCE_LEAK | #fixed code
@Test
public void TestArbitrarySplitLocations() throws Exception {
//int totalSize = 415;
//int [] recordBreaks = new int[] { 0, 40, 80, 120, 160, 200, 240, 280, 320, 372 };
Assert.assertArrayEquals(new int[] { 0 }, getRecordIndexesInReader(getReaderFor("unenclosed-json-simple.json", 0, 40)));
Assert.assertArrayEquals(new int[] { 0, 1 }, getRecordIndexesInReader(getReaderFor("unenclosed-json-simple.json", 0, 41)));
Assert.assertArrayEquals(new int[] { 0, 1 }, getRecordIndexesInReader(getReaderFor("unenclosed-json-simple.json", 0, 42)));
Assert.assertArrayEquals(new int[] { 1, 2, 3 }, getRecordIndexesInReader(getReaderFor("unenclosed-json-simple.json", 39, 123)));
Assert.assertArrayEquals(new int[] { 1, 2, 3 }, getRecordIndexesInReader(getReaderFor("unenclosed-json-simple.json", 20, 123)));
Assert.assertArrayEquals(new int[] { 1, 2, 3 }, getRecordIndexesInReader(getReaderFor("unenclosed-json-simple.json", 40, 123)));
Assert.assertArrayEquals(new int[] { 2, 3 }, getRecordIndexesInReader(getReaderFor("unenclosed-json-simple.json", 41, 123)));
Assert.assertArrayEquals(new int[] { 6, 7, 8 }, getRecordIndexesInReader(getReaderFor("unenclosed-json-simple.json", 240, 340)));
Assert.assertArrayEquals(new int[] { 9 }, getRecordIndexesInReader(getReaderFor("unenclosed-json-simple.json", 353, 415)));
Assert.assertArrayEquals(new int[] { 9 }, getRecordIndexesInReader(getReaderFor("unenclosed-json-simple.json", 354, 415)));
Assert.assertArrayEquals(new int[] { 9 }, getRecordIndexesInReader(getReaderFor("unenclosed-json-simple.json", 355, 415)));
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Test
public void testGeomFromPointShape() throws UDFArgumentException {
final double longitude = 12.224;
final double latitude = 51.829;
Point point = new Point(longitude, latitude);
byte[] esriShape = GeometryEngine.geometryToEsriShape(point);
assertNotNull("The point writable must not be null!", esriShape);
BytesWritable shapeAsWritable = new BytesWritable(esriShape);
assertNotNull("The shape writable must not be null!", shapeAsWritable);
ST_GeomFromShape fromShape = new ST_GeomFromShape();
BytesWritable geometryAsWritable = fromShape.evaluate(shapeAsWritable);
ST_X getX = new ST_X();
DoubleWritable xAsWritable = getX.evaluate(geometryAsWritable);
assertNotNull("The x writable must not be null!", xAsWritable);
ST_Y getY = new ST_Y();
DoubleWritable yAsWritable = getY.evaluate(geometryAsWritable);
assertNotNull("The y writable must not be null!", yAsWritable);
assertEquals("Longitude is different!", longitude, xAsWritable.get(), Epsilon);
assertEquals("Latitude is different!", latitude, yAsWritable.get(), Epsilon);
ST_SRID getWkid = new ST_SRID();
IntWritable wkidAsWritable = getWkid.evaluate(geometryAsWritable);
assertNotNull("The wkid writable must not be null!", wkidAsWritable);
assertEquals("The wkid is different!", 0, wkidAsWritable.get());
}
#location 23
#vulnerability type NULL_DEREFERENCE | #fixed code
@Test
public void testGeomFromPointShape() throws UDFArgumentException {
Point point = createFirstLocation();
byte[] esriShape = GeometryEngine.geometryToEsriShape(point);
assertNotNull("The point writable must not be null!", esriShape);
BytesWritable shapeAsWritable = new BytesWritable(esriShape);
assertNotNull("The shape writable must not be null!", shapeAsWritable);
final int wkid = 4326;
ST_GeomFromShape fromShape = new ST_GeomFromShape();
BytesWritable geometryAsWritable = fromShape.evaluate(shapeAsWritable, wkid);
assertNotNull("The geometry writable must not be null!", geometryAsWritable);
validatePoint(point, wkid, geometryAsWritable);
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Test
public void TestEscSlashLast() throws IOException {
//int [] recordBreaks = new int[] { 0, 75, 146, 218, 290, 362, , , };
Assert.assertArrayEquals(new int[] { 0 }, getRecordIndexesInReader(getReaderFor("unenclosed-json-esc3.json", 0, 44)));
Assert.assertArrayEquals(new int[] {0, 1}, getRecordIndexesInReader(getReaderFor("unenclosed-json-esc3.json", 0, 45)));
Assert.assertArrayEquals(new int[] {0, 1}, getRecordIndexesInReader(getReaderFor("unenclosed-json-esc3.json", 0, 46)));
Assert.assertArrayEquals(new int[] {1,2,3}, getRecordIndexesInReader(getReaderFor("unenclosed-json-esc3.json", 19, 140)));
Assert.assertArrayEquals(new int[] {1,2,3}, getRecordIndexesInReader(getReaderFor("unenclosed-json-esc3.json", 26, 140)));
Assert.assertArrayEquals(new int[] {1,2,3}, getRecordIndexesInReader(getReaderFor("unenclosed-json-esc3.json", 44, 140)));
}
#location 7
#vulnerability type RESOURCE_LEAK | #fixed code
@Test
public void TestEscSlashLast() throws Exception {
//int [] recordBreaks = new int[] { 0, 75, 146, 218, 290, 362, , , };
Assert.assertArrayEquals(new int[] { 0 }, getRecordIndexesInReader(getReaderFor("unenclosed-json-esc3.json", 0, 44)));
Assert.assertArrayEquals(new int[] {0, 1}, getRecordIndexesInReader(getReaderFor("unenclosed-json-esc3.json", 0, 45)));
Assert.assertArrayEquals(new int[] {0, 1}, getRecordIndexesInReader(getReaderFor("unenclosed-json-esc3.json", 0, 46)));
Assert.assertArrayEquals(new int[] {1,2,3}, getRecordIndexesInReader(getReaderFor("unenclosed-json-esc3.json", 19, 140)));
Assert.assertArrayEquals(new int[] {1,2,3}, getRecordIndexesInReader(getReaderFor("unenclosed-json-esc3.json", 26, 140)));
Assert.assertArrayEquals(new int[] {1,2,3}, getRecordIndexesInReader(getReaderFor("unenclosed-json-esc3.json", 44, 140)));
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Test
public void TestArbitrarySplitLocations() throws Exception {
//int totalSize = 415;
//int [] recordBreaks = new int[] { 0, 40, 80, 120, 160, 200, 240, 280, 320, 372 };
Assert.assertArrayEquals(new int[] { 0 }, getRecordIndexesInReader(getReaderFor("unenclosed-json-simple.json", 0, 40)));
Assert.assertArrayEquals(new int[] { 0, 1 }, getRecordIndexesInReader(getReaderFor("unenclosed-json-simple.json", 0, 41)));
Assert.assertArrayEquals(new int[] { 0, 1 }, getRecordIndexesInReader(getReaderFor("unenclosed-json-simple.json", 0, 42)));
Assert.assertArrayEquals(new int[] { 1, 2, 3 }, getRecordIndexesInReader(getReaderFor("unenclosed-json-simple.json", 39, 123)));
Assert.assertArrayEquals(new int[] { 1, 2, 3 }, getRecordIndexesInReader(getReaderFor("unenclosed-json-simple.json", 20, 123)));
Assert.assertArrayEquals(new int[] { 1, 2, 3 }, getRecordIndexesInReader(getReaderFor("unenclosed-json-simple.json", 40, 123)));
Assert.assertArrayEquals(new int[] { 2, 3 }, getRecordIndexesInReader(getReaderFor("unenclosed-json-simple.json", 41, 123)));
Assert.assertArrayEquals(new int[] { 6, 7, 8 }, getRecordIndexesInReader(getReaderFor("unenclosed-json-simple.json", 240, 340)));
Assert.assertArrayEquals(new int[] { 9 }, getRecordIndexesInReader(getReaderFor("unenclosed-json-simple.json", 353, 415)));
Assert.assertArrayEquals(new int[] { 9 }, getRecordIndexesInReader(getReaderFor("unenclosed-json-simple.json", 354, 415)));
Assert.assertArrayEquals(new int[] { 9 }, getRecordIndexesInReader(getReaderFor("unenclosed-json-simple.json", 355, 415)));
}
#location 9
#vulnerability type RESOURCE_LEAK | #fixed code
@Test
public void TestArbitrarySplitLocations() throws Exception {
//int totalSize = 415;
//int [] recordBreaks = new int[] { 0, 40, 80, 120, 160, 200, 240, 280, 320, 372 };
Assert.assertArrayEquals(new int[] { 0 }, getRecordIndexesInReader(getReaderFor("unenclosed-json-simple.json", 0, 40)));
Assert.assertArrayEquals(new int[] { 0, 1 }, getRecordIndexesInReader(getReaderFor("unenclosed-json-simple.json", 0, 41)));
Assert.assertArrayEquals(new int[] { 0, 1 }, getRecordIndexesInReader(getReaderFor("unenclosed-json-simple.json", 0, 42)));
Assert.assertArrayEquals(new int[] { 1, 2, 3 }, getRecordIndexesInReader(getReaderFor("unenclosed-json-simple.json", 39, 123)));
Assert.assertArrayEquals(new int[] { 1, 2, 3 }, getRecordIndexesInReader(getReaderFor("unenclosed-json-simple.json", 20, 123)));
Assert.assertArrayEquals(new int[] { 1, 2, 3 }, getRecordIndexesInReader(getReaderFor("unenclosed-json-simple.json", 40, 123)));
Assert.assertArrayEquals(new int[] { 2, 3 }, getRecordIndexesInReader(getReaderFor("unenclosed-json-simple.json", 41, 123)));
Assert.assertArrayEquals(new int[] { 6, 7, 8 }, getRecordIndexesInReader(getReaderFor("unenclosed-json-simple.json", 240, 340)));
Assert.assertArrayEquals(new int[] { 9 }, getRecordIndexesInReader(getReaderFor("unenclosed-json-simple.json", 353, 415)));
Assert.assertArrayEquals(new int[] { 9 }, getRecordIndexesInReader(getReaderFor("unenclosed-json-simple.json", 354, 415)));
Assert.assertArrayEquals(new int[] { 9 }, getRecordIndexesInReader(getReaderFor("unenclosed-json-simple.json", 355, 415)));
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Test
public void TestGeomFirst() throws IOException {
Assert.assertArrayEquals(new int[] { 1 }, getRecordIndexesInReader(getReaderFor("unenclosed-json-geom-first.json", 32, 54)));
Assert.assertArrayEquals(new int[] { 1 }, getRecordIndexesInReader(getReaderFor("unenclosed-json-geom-first.json", 48, 54)));
Assert.assertArrayEquals(new int[] { 1 }, getRecordIndexesInReader(getReaderFor("unenclosed-json-geom-first.json", 49, 54)));
Assert.assertArrayEquals(new int[] { 0 }, getRecordIndexesInReader(getReaderFor("unenclosed-json-geom-first.json", 0, 52), true));
}
#location 6
#vulnerability type RESOURCE_LEAK | #fixed code
@Test
public void TestGeomFirst() throws Exception {
Assert.assertArrayEquals(new int[] { 1 }, getRecordIndexesInReader(getReaderFor("unenclosed-json-geom-first.json", 32, 54)));
Assert.assertArrayEquals(new int[] { 1 }, getRecordIndexesInReader(getReaderFor("unenclosed-json-geom-first.json", 48, 54)));
Assert.assertArrayEquals(new int[] { 1 }, getRecordIndexesInReader(getReaderFor("unenclosed-json-geom-first.json", 49, 54)));
Assert.assertArrayEquals(new int[] { 0 }, getRecordIndexesInReader(getReaderFor("unenclosed-json-geom-first.json", 0, 52), true));
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Test
public void TestArbitrarySplitLocations() throws IOException {
//int totalSize = 415;
//int [] recordBreaks = new int[] { 0, 40, 80, 120, 160, 200, 240, 280, 320, 372 };
Assert.assertArrayEquals(new int[] { 0 }, getRecordIndexesInReader(getReaderFor("unenclosed-json-simple.json", 0, 40)));
Assert.assertArrayEquals(new int[] { 0, 1 }, getRecordIndexesInReader(getReaderFor("unenclosed-json-simple.json", 0, 41)));
Assert.assertArrayEquals(new int[] { 0, 1 }, getRecordIndexesInReader(getReaderFor("unenclosed-json-simple.json", 0, 42)));
Assert.assertArrayEquals(new int[] { 1, 2, 3 }, getRecordIndexesInReader(getReaderFor("unenclosed-json-simple.json", 39, 123)));
Assert.assertArrayEquals(new int[] { 1, 2, 3 }, getRecordIndexesInReader(getReaderFor("unenclosed-json-simple.json", 20, 123)));
Assert.assertArrayEquals(new int[] { 1, 2, 3 }, getRecordIndexesInReader(getReaderFor("unenclosed-json-simple.json", 40, 123)));
Assert.assertArrayEquals(new int[] { 2, 3 }, getRecordIndexesInReader(getReaderFor("unenclosed-json-simple.json", 41, 123)));
Assert.assertArrayEquals(new int[] { 6, 7, 8 }, getRecordIndexesInReader(getReaderFor("unenclosed-json-simple.json", 240, 340)));
Assert.assertArrayEquals(new int[] { 9 }, getRecordIndexesInReader(getReaderFor("unenclosed-json-simple.json", 353, 415)));
Assert.assertArrayEquals(new int[] { 9 }, getRecordIndexesInReader(getReaderFor("unenclosed-json-simple.json", 354, 415)));
Assert.assertArrayEquals(new int[] { 9 }, getRecordIndexesInReader(getReaderFor("unenclosed-json-simple.json", 355, 415)));
}
#location 11
#vulnerability type RESOURCE_LEAK | #fixed code
@Test
public void TestArbitrarySplitLocations() throws Exception {
//int totalSize = 415;
//int [] recordBreaks = new int[] { 0, 40, 80, 120, 160, 200, 240, 280, 320, 372 };
Assert.assertArrayEquals(new int[] { 0 }, getRecordIndexesInReader(getReaderFor("unenclosed-json-simple.json", 0, 40)));
Assert.assertArrayEquals(new int[] { 0, 1 }, getRecordIndexesInReader(getReaderFor("unenclosed-json-simple.json", 0, 41)));
Assert.assertArrayEquals(new int[] { 0, 1 }, getRecordIndexesInReader(getReaderFor("unenclosed-json-simple.json", 0, 42)));
Assert.assertArrayEquals(new int[] { 1, 2, 3 }, getRecordIndexesInReader(getReaderFor("unenclosed-json-simple.json", 39, 123)));
Assert.assertArrayEquals(new int[] { 1, 2, 3 }, getRecordIndexesInReader(getReaderFor("unenclosed-json-simple.json", 20, 123)));
Assert.assertArrayEquals(new int[] { 1, 2, 3 }, getRecordIndexesInReader(getReaderFor("unenclosed-json-simple.json", 40, 123)));
Assert.assertArrayEquals(new int[] { 2, 3 }, getRecordIndexesInReader(getReaderFor("unenclosed-json-simple.json", 41, 123)));
Assert.assertArrayEquals(new int[] { 6, 7, 8 }, getRecordIndexesInReader(getReaderFor("unenclosed-json-simple.json", 240, 340)));
Assert.assertArrayEquals(new int[] { 9 }, getRecordIndexesInReader(getReaderFor("unenclosed-json-simple.json", 353, 415)));
Assert.assertArrayEquals(new int[] { 9 }, getRecordIndexesInReader(getReaderFor("unenclosed-json-simple.json", 354, 415)));
Assert.assertArrayEquals(new int[] { 9 }, getRecordIndexesInReader(getReaderFor("unenclosed-json-simple.json", 355, 415)));
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Ignore // May not be guaranteed behavior
public void TestComma() throws IOException {
//int [] recordBreaks = new int[] { 0, 57, 111, , };
int[] rslt = getRecordIndexesInReader(getReaderFor("unenclosed-json-comma.json", 0, 222), true);
Assert.assertEquals(4, rslt.length);
int[] before = null, after = null;
before = getRecordIndexesInReader(getReaderFor("unenclosed-json-comma.json", 0, 56), true);
after = getRecordIndexesInReader(getReaderFor("unenclosed-json-comma.json", 56, 222), true);
Assert.assertEquals(4, before.length + after.length);
before = getRecordIndexesInReader(getReaderFor("unenclosed-json-comma.json", 0, 57), true);
after = getRecordIndexesInReader(getReaderFor("unenclosed-json-comma.json", 57, 222), true);
Assert.assertEquals(4, before.length + after.length);
before = getRecordIndexesInReader(getReaderFor("unenclosed-json-comma.json", 0, 58), true);
after = getRecordIndexesInReader(getReaderFor("unenclosed-json-comma.json", 58, 222), true);
Assert.assertEquals(4, before.length + after.length);
}
#location 8
#vulnerability type RESOURCE_LEAK | #fixed code
@Ignore // May not be guaranteed behavior
public void TestComma() throws Exception {
//int [] recordBreaks = new int[] { 0, 57, 111, , };
int[] rslt = getRecordIndexesInReader(getReaderFor("unenclosed-json-comma.json", 0, 222), true);
Assert.assertEquals(4, rslt.length);
int[] before = null, after = null;
before = getRecordIndexesInReader(getReaderFor("unenclosed-json-comma.json", 0, 56), true);
after = getRecordIndexesInReader(getReaderFor("unenclosed-json-comma.json", 56, 222), true);
Assert.assertEquals(4, before.length + after.length);
before = getRecordIndexesInReader(getReaderFor("unenclosed-json-comma.json", 0, 57), true);
after = getRecordIndexesInReader(getReaderFor("unenclosed-json-comma.json", 57, 222), true);
Assert.assertEquals(4, before.length + after.length);
before = getRecordIndexesInReader(getReaderFor("unenclosed-json-comma.json", 0, 58), true);
after = getRecordIndexesInReader(getReaderFor("unenclosed-json-comma.json", 58, 222), true);
Assert.assertEquals(4, before.length + after.length);
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Test
public void TestEscAposLast() throws IOException {
//int [] recordBreaks = new int[] { 0, 75, 146, 218, 290, 362, , , };
Assert.assertArrayEquals(new int[] { 0 }, getRecordIndexesInReader(getReaderFor("unenclosed-json-esc2.json", 0, 44)));
Assert.assertArrayEquals(new int[] {0, 1}, getRecordIndexesInReader(getReaderFor("unenclosed-json-esc2.json", 0, 45)));
Assert.assertArrayEquals(new int[] {0, 1}, getRecordIndexesInReader(getReaderFor("unenclosed-json-esc2.json", 0, 46)));
Assert.assertArrayEquals(new int[] {1,2,3}, getRecordIndexesInReader(getReaderFor("unenclosed-json-esc2.json", 19, 140)));
Assert.assertArrayEquals(new int[] {1,2,3}, getRecordIndexesInReader(getReaderFor("unenclosed-json-esc2.json", 26, 140)));
Assert.assertArrayEquals(new int[] {1,2,3}, getRecordIndexesInReader(getReaderFor("unenclosed-json-esc2.json", 43, 140)));
}
#location 7
#vulnerability type RESOURCE_LEAK | #fixed code
@Test
public void TestEscAposLast() throws Exception {
//int [] recordBreaks = new int[] { 0, 75, 146, 218, 290, 362, , , };
Assert.assertArrayEquals(new int[] { 0 }, getRecordIndexesInReader(getReaderFor("unenclosed-json-esc2.json", 0, 44)));
Assert.assertArrayEquals(new int[] {0, 1}, getRecordIndexesInReader(getReaderFor("unenclosed-json-esc2.json", 0, 45)));
Assert.assertArrayEquals(new int[] {0, 1}, getRecordIndexesInReader(getReaderFor("unenclosed-json-esc2.json", 0, 46)));
Assert.assertArrayEquals(new int[] {1,2,3}, getRecordIndexesInReader(getReaderFor("unenclosed-json-esc2.json", 19, 140)));
Assert.assertArrayEquals(new int[] {1,2,3}, getRecordIndexesInReader(getReaderFor("unenclosed-json-esc2.json", 26, 140)));
Assert.assertArrayEquals(new int[] {1,2,3}, getRecordIndexesInReader(getReaderFor("unenclosed-json-esc2.json", 43, 140)));
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Ignore // May not be guaranteed behavior
public void TestComma() throws IOException {
//int [] recordBreaks = new int[] { 0, 57, 111, , };
int[] rslt = getRecordIndexesInReader(getReaderFor("unenclosed-json-comma.json", 0, 222), true);
Assert.assertEquals(4, rslt.length);
int[] before = null, after = null;
before = getRecordIndexesInReader(getReaderFor("unenclosed-json-comma.json", 0, 56), true);
after = getRecordIndexesInReader(getReaderFor("unenclosed-json-comma.json", 56, 222), true);
Assert.assertEquals(4, before.length + after.length);
before = getRecordIndexesInReader(getReaderFor("unenclosed-json-comma.json", 0, 57), true);
after = getRecordIndexesInReader(getReaderFor("unenclosed-json-comma.json", 57, 222), true);
Assert.assertEquals(4, before.length + after.length);
before = getRecordIndexesInReader(getReaderFor("unenclosed-json-comma.json", 0, 58), true);
after = getRecordIndexesInReader(getReaderFor("unenclosed-json-comma.json", 58, 222), true);
Assert.assertEquals(4, before.length + after.length);
}
#location 7
#vulnerability type RESOURCE_LEAK | #fixed code
@Ignore // May not be guaranteed behavior
public void TestComma() throws Exception {
//int [] recordBreaks = new int[] { 0, 57, 111, , };
int[] rslt = getRecordIndexesInReader(getReaderFor("unenclosed-json-comma.json", 0, 222), true);
Assert.assertEquals(4, rslt.length);
int[] before = null, after = null;
before = getRecordIndexesInReader(getReaderFor("unenclosed-json-comma.json", 0, 56), true);
after = getRecordIndexesInReader(getReaderFor("unenclosed-json-comma.json", 56, 222), true);
Assert.assertEquals(4, before.length + after.length);
before = getRecordIndexesInReader(getReaderFor("unenclosed-json-comma.json", 0, 57), true);
after = getRecordIndexesInReader(getReaderFor("unenclosed-json-comma.json", 57, 222), true);
Assert.assertEquals(4, before.length + after.length);
before = getRecordIndexesInReader(getReaderFor("unenclosed-json-comma.json", 0, 58), true);
after = getRecordIndexesInReader(getReaderFor("unenclosed-json-comma.json", 58, 222), true);
Assert.assertEquals(4, before.length + after.length);
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Test
public void TestEscCloseLast() throws IOException {
//int [] recordBreaks = new int[] { 0, 75, 146, 218, 290, 362, , , };
Assert.assertArrayEquals(new int[] { 0 }, getRecordIndexesInReader(getReaderFor("unenclosed-json-esc4.json", 0, 44)));
Assert.assertArrayEquals(new int[] {0, 1}, getRecordIndexesInReader(getReaderFor("unenclosed-json-esc4.json", 0, 45)));
Assert.assertArrayEquals(new int[] {0, 1}, getRecordIndexesInReader(getReaderFor("unenclosed-json-esc4.json", 0, 46)));
Assert.assertArrayEquals(new int[] {1,2,3}, getRecordIndexesInReader(getReaderFor("unenclosed-json-esc4.json", 19, 140)));
Assert.assertArrayEquals(new int[] {1,2,3}, getRecordIndexesInReader(getReaderFor("unenclosed-json-esc4.json", 25, 140)));
Assert.assertArrayEquals(new int[] {1,2,3}, getRecordIndexesInReader(getReaderFor("unenclosed-json-esc4.json", 44, 140)));
}
#location 7
#vulnerability type RESOURCE_LEAK | #fixed code
@Test
public void TestEscCloseLast() throws Exception {
//int [] recordBreaks = new int[] { 0, 75, 146, 218, 290, 362, , , };
Assert.assertArrayEquals(new int[] { 0 }, getRecordIndexesInReader(getReaderFor("unenclosed-json-esc4.json", 0, 44)));
Assert.assertArrayEquals(new int[] {0, 1}, getRecordIndexesInReader(getReaderFor("unenclosed-json-esc4.json", 0, 45)));
Assert.assertArrayEquals(new int[] {0, 1}, getRecordIndexesInReader(getReaderFor("unenclosed-json-esc4.json", 0, 46)));
Assert.assertArrayEquals(new int[] {1,2,3}, getRecordIndexesInReader(getReaderFor("unenclosed-json-esc4.json", 19, 140)));
Assert.assertArrayEquals(new int[] {1,2,3}, getRecordIndexesInReader(getReaderFor("unenclosed-json-esc4.json", 25, 140)));
Assert.assertArrayEquals(new int[] {1,2,3}, getRecordIndexesInReader(getReaderFor("unenclosed-json-esc4.json", 44, 140)));
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Test
public void TestGeomFirst() throws IOException {
Assert.assertArrayEquals(new int[] { 1 }, getRecordIndexesInReader(getReaderFor("unenclosed-json-geom-first.json", 32, 54)));
Assert.assertArrayEquals(new int[] { 1 }, getRecordIndexesInReader(getReaderFor("unenclosed-json-geom-first.json", 48, 54)));
Assert.assertArrayEquals(new int[] { 1 }, getRecordIndexesInReader(getReaderFor("unenclosed-json-geom-first.json", 49, 54)));
Assert.assertArrayEquals(new int[] { 0 }, getRecordIndexesInReader(getReaderFor("unenclosed-json-geom-first.json", 0, 52), true));
}
#location 4
#vulnerability type RESOURCE_LEAK | #fixed code
@Test
public void TestGeomFirst() throws Exception {
Assert.assertArrayEquals(new int[] { 1 }, getRecordIndexesInReader(getReaderFor("unenclosed-json-geom-first.json", 32, 54)));
Assert.assertArrayEquals(new int[] { 1 }, getRecordIndexesInReader(getReaderFor("unenclosed-json-geom-first.json", 48, 54)));
Assert.assertArrayEquals(new int[] { 1 }, getRecordIndexesInReader(getReaderFor("unenclosed-json-geom-first.json", 49, 54)));
Assert.assertArrayEquals(new int[] { 0 }, getRecordIndexesInReader(getReaderFor("unenclosed-json-geom-first.json", 0, 52), true));
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Test
public void TestEscQuoteLast() throws IOException {
//int [] recordBreaks = new int[] { 0, 75, 146, 218, 290, 362, , , };
Assert.assertArrayEquals(new int[] { 0 }, getRecordIndexesInReader(getReaderFor("unenclosed-json-esc1.json", 0, 44)));
Assert.assertArrayEquals(new int[] {0, 1}, getRecordIndexesInReader(getReaderFor("unenclosed-json-esc1.json", 0, 45)));
Assert.assertArrayEquals(new int[] {0, 1}, getRecordIndexesInReader(getReaderFor("unenclosed-json-esc1.json", 0, 46)));
Assert.assertArrayEquals(new int[] {1,2,3}, getRecordIndexesInReader(getReaderFor("unenclosed-json-esc1.json", 19, 140)));
Assert.assertArrayEquals(new int[] {1,2,3}, getRecordIndexesInReader(getReaderFor("unenclosed-json-esc1.json", 25, 140)));
Assert.assertArrayEquals(new int[] {1,2,3}, getRecordIndexesInReader(getReaderFor("unenclosed-json-esc1.json", 44, 140)));
}
#location 5
#vulnerability type RESOURCE_LEAK | #fixed code
@Test
public void TestEscQuoteLast() throws Exception {
//int [] recordBreaks = new int[] { 0, 75, 146, 218, 290, 362, , , };
Assert.assertArrayEquals(new int[] { 0 }, getRecordIndexesInReader(getReaderFor("unenclosed-json-esc1.json", 0, 44)));
Assert.assertArrayEquals(new int[] {0, 1}, getRecordIndexesInReader(getReaderFor("unenclosed-json-esc1.json", 0, 45)));
Assert.assertArrayEquals(new int[] {0, 1}, getRecordIndexesInReader(getReaderFor("unenclosed-json-esc1.json", 0, 46)));
Assert.assertArrayEquals(new int[] {1,2,3}, getRecordIndexesInReader(getReaderFor("unenclosed-json-esc1.json", 19, 140)));
Assert.assertArrayEquals(new int[] {1,2,3}, getRecordIndexesInReader(getReaderFor("unenclosed-json-esc1.json", 25, 140)));
Assert.assertArrayEquals(new int[] {1,2,3}, getRecordIndexesInReader(getReaderFor("unenclosed-json-esc1.json", 44, 140)));
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Test
public void TestEscape() throws IOException { // Issue #68
//int [] recordBreaks = new int[] { 0, 44, 88, 137, 181, 229, 270, 311, 354 }; //length 395
Assert.assertArrayEquals(new int[] { 0 }, getRecordIndexesInReader(getReaderFor("unenclosed-json-escape.json", 0, 44)));
Assert.assertArrayEquals(new int[] {0, 1}, getRecordIndexesInReader(getReaderFor("unenclosed-json-escape.json", 0, 45)));
Assert.assertArrayEquals(new int[] {0, 1}, getRecordIndexesInReader(getReaderFor("unenclosed-json-escape.json", 0, 46)));
Assert.assertArrayEquals(new int[] {1,2,3}, getRecordIndexesInReader(getReaderFor("unenclosed-json-escape.json", 43, 140)));
Assert.assertArrayEquals(new int[] {1,2,3}, getRecordIndexesInReader(getReaderFor("unenclosed-json-escape.json", 19, 140)));
Assert.assertArrayEquals(new int[] {1,2,3}, getRecordIndexesInReader(getReaderFor("unenclosed-json-escape.json", 44, 140)));
Assert.assertArrayEquals(new int[] {2, 3}, getRecordIndexesInReader(getReaderFor("unenclosed-json-escape.json", 45, 140)));
Assert.assertArrayEquals(new int[] {4,5,6}, getRecordIndexesInReader(getReaderFor("unenclosed-json-escape.json", 181, 289)));
Assert.assertArrayEquals(new int[] { 8 }, getRecordIndexesInReader(getReaderFor("unenclosed-json-escape.json", 336, 400))); // 7|{}"
Assert.assertArrayEquals(new int[] { 1 }, getRecordIndexesInReader(getReaderFor("unenclosed-json-escape.json", 14, 45)));
Assert.assertArrayEquals(new int[] { 1 }, getRecordIndexesInReader(getReaderFor("unenclosed-json-escape.json", 22, 45)));
Assert.assertArrayEquals(new int[] { 1 }, getRecordIndexesInReader(getReaderFor("unenclosed-json-escape.json", 23, 45)));
Assert.assertArrayEquals(new int[] { 1 }, getRecordIndexesInReader(getReaderFor("unenclosed-json-escape.json", 24, 45)));
Assert.assertArrayEquals(new int[] { 1 }, getRecordIndexesInReader(getReaderFor("unenclosed-json-escape.json", 25, 45)));
Assert.assertArrayEquals(new int[] { 1 }, getRecordIndexesInReader(getReaderFor("unenclosed-json-escape.json", 44, 68)));
Assert.assertArrayEquals(new int[] { 1 }, getRecordIndexesInReader(getReaderFor("unenclosed-json-escape.json", 44, 69)));
}
#location 4
#vulnerability type RESOURCE_LEAK | #fixed code
@Test
public void TestEscape() throws Exception { // Issue #68
//int [] recordBreaks = new int[] { 0, 44, 88, 137, 181, 229, 270, 311, 354 }; //length 395
Assert.assertArrayEquals(new int[] { 0 }, getRecordIndexesInReader(getReaderFor("unenclosed-json-escape.json", 0, 44)));
Assert.assertArrayEquals(new int[] {0, 1}, getRecordIndexesInReader(getReaderFor("unenclosed-json-escape.json", 0, 45)));
Assert.assertArrayEquals(new int[] {0, 1}, getRecordIndexesInReader(getReaderFor("unenclosed-json-escape.json", 0, 46)));
Assert.assertArrayEquals(new int[] {1,2,3}, getRecordIndexesInReader(getReaderFor("unenclosed-json-escape.json", 43, 140)));
Assert.assertArrayEquals(new int[] {1,2,3}, getRecordIndexesInReader(getReaderFor("unenclosed-json-escape.json", 19, 140)));
Assert.assertArrayEquals(new int[] {1,2,3}, getRecordIndexesInReader(getReaderFor("unenclosed-json-escape.json", 44, 140)));
Assert.assertArrayEquals(new int[] {2, 3}, getRecordIndexesInReader(getReaderFor("unenclosed-json-escape.json", 45, 140)));
Assert.assertArrayEquals(new int[] {4,5,6}, getRecordIndexesInReader(getReaderFor("unenclosed-json-escape.json", 181, 289)));
Assert.assertArrayEquals(new int[] { 8 }, getRecordIndexesInReader(getReaderFor("unenclosed-json-escape.json", 336, 400))); // 7|{}"
Assert.assertArrayEquals(new int[] { 1 }, getRecordIndexesInReader(getReaderFor("unenclosed-json-escape.json", 14, 45)));
Assert.assertArrayEquals(new int[] { 1 }, getRecordIndexesInReader(getReaderFor("unenclosed-json-escape.json", 22, 45)));
Assert.assertArrayEquals(new int[] { 1 }, getRecordIndexesInReader(getReaderFor("unenclosed-json-escape.json", 23, 45)));
Assert.assertArrayEquals(new int[] { 1 }, getRecordIndexesInReader(getReaderFor("unenclosed-json-escape.json", 24, 45)));
Assert.assertArrayEquals(new int[] { 1 }, getRecordIndexesInReader(getReaderFor("unenclosed-json-escape.json", 25, 45)));
Assert.assertArrayEquals(new int[] { 1 }, getRecordIndexesInReader(getReaderFor("unenclosed-json-escape.json", 44, 68)));
Assert.assertArrayEquals(new int[] { 1 }, getRecordIndexesInReader(getReaderFor("unenclosed-json-escape.json", 44, 69)));
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Test
public void TestEscPoints() throws IOException {
//int [] recordBreaks = new int[] { 0, 75, 146, 218, 290, 362, , , };
Assert.assertArrayEquals(new int[] { 0 }, getRecordIndexesInReader(getReaderFor("unenclosed-json-esc-points.json", 0, 74), true));
Assert.assertArrayEquals(new int[] {0, 75}, getRecordIndexesInReader(getReaderFor("unenclosed-json-esc-points.json", 0, 76), true));
Assert.assertArrayEquals(new int[] {75, 146}, getRecordIndexesInReader(getReaderFor("unenclosed-json-esc-points.json", 70, 148), true));
}
#location 6
#vulnerability type RESOURCE_LEAK | #fixed code
@Test
public void TestEscPoints() throws Exception {
//int [] recordBreaks = new int[] { 0, 75, 146, 218, 290, 362, , , };
Assert.assertArrayEquals(new int[] { 0 }, getRecordIndexesInReader(getReaderFor("unenclosed-json-esc-points.json", 0, 74), true));
Assert.assertArrayEquals(new int[] {0, 75}, getRecordIndexesInReader(getReaderFor("unenclosed-json-esc-points.json", 0, 76), true));
Assert.assertArrayEquals(new int[] {75, 146}, getRecordIndexesInReader(getReaderFor("unenclosed-json-esc-points.json", 70, 148), true));
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Test
public void TestEscSlashLast() throws IOException {
//int [] recordBreaks = new int[] { 0, 75, 146, 218, 290, 362, , , };
Assert.assertArrayEquals(new int[] { 0 }, getRecordIndexesInReader(getReaderFor("unenclosed-json-esc3.json", 0, 44)));
Assert.assertArrayEquals(new int[] {0, 1}, getRecordIndexesInReader(getReaderFor("unenclosed-json-esc3.json", 0, 45)));
Assert.assertArrayEquals(new int[] {0, 1}, getRecordIndexesInReader(getReaderFor("unenclosed-json-esc3.json", 0, 46)));
Assert.assertArrayEquals(new int[] {1,2,3}, getRecordIndexesInReader(getReaderFor("unenclosed-json-esc3.json", 19, 140)));
Assert.assertArrayEquals(new int[] {1,2,3}, getRecordIndexesInReader(getReaderFor("unenclosed-json-esc3.json", 26, 140)));
Assert.assertArrayEquals(new int[] {1,2,3}, getRecordIndexesInReader(getReaderFor("unenclosed-json-esc3.json", 44, 140)));
}
#location 4
#vulnerability type RESOURCE_LEAK | #fixed code
@Test
public void TestEscSlashLast() throws Exception {
//int [] recordBreaks = new int[] { 0, 75, 146, 218, 290, 362, , , };
Assert.assertArrayEquals(new int[] { 0 }, getRecordIndexesInReader(getReaderFor("unenclosed-json-esc3.json", 0, 44)));
Assert.assertArrayEquals(new int[] {0, 1}, getRecordIndexesInReader(getReaderFor("unenclosed-json-esc3.json", 0, 45)));
Assert.assertArrayEquals(new int[] {0, 1}, getRecordIndexesInReader(getReaderFor("unenclosed-json-esc3.json", 0, 46)));
Assert.assertArrayEquals(new int[] {1,2,3}, getRecordIndexesInReader(getReaderFor("unenclosed-json-esc3.json", 19, 140)));
Assert.assertArrayEquals(new int[] {1,2,3}, getRecordIndexesInReader(getReaderFor("unenclosed-json-esc3.json", 26, 140)));
Assert.assertArrayEquals(new int[] {1,2,3}, getRecordIndexesInReader(getReaderFor("unenclosed-json-esc3.json", 44, 140)));
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Test
public void TestArbitrarySplitLocations() throws Exception {
//int totalSize = 415;
//int [] recordBreaks = new int[] { 0, 40, 80, 120, 160, 200, 240, 280, 320, 372 };
Assert.assertArrayEquals(new int[] { 0 }, getRecordIndexesInReader(getReaderFor("unenclosed-json-simple.json", 0, 40)));
Assert.assertArrayEquals(new int[] { 0, 1 }, getRecordIndexesInReader(getReaderFor("unenclosed-json-simple.json", 0, 41)));
Assert.assertArrayEquals(new int[] { 0, 1 }, getRecordIndexesInReader(getReaderFor("unenclosed-json-simple.json", 0, 42)));
Assert.assertArrayEquals(new int[] { 1, 2, 3 }, getRecordIndexesInReader(getReaderFor("unenclosed-json-simple.json", 39, 123)));
Assert.assertArrayEquals(new int[] { 1, 2, 3 }, getRecordIndexesInReader(getReaderFor("unenclosed-json-simple.json", 20, 123)));
Assert.assertArrayEquals(new int[] { 1, 2, 3 }, getRecordIndexesInReader(getReaderFor("unenclosed-json-simple.json", 40, 123)));
Assert.assertArrayEquals(new int[] { 2, 3 }, getRecordIndexesInReader(getReaderFor("unenclosed-json-simple.json", 41, 123)));
Assert.assertArrayEquals(new int[] { 6, 7, 8 }, getRecordIndexesInReader(getReaderFor("unenclosed-json-simple.json", 240, 340)));
Assert.assertArrayEquals(new int[] { 9 }, getRecordIndexesInReader(getReaderFor("unenclosed-json-simple.json", 353, 415)));
Assert.assertArrayEquals(new int[] { 9 }, getRecordIndexesInReader(getReaderFor("unenclosed-json-simple.json", 354, 415)));
Assert.assertArrayEquals(new int[] { 9 }, getRecordIndexesInReader(getReaderFor("unenclosed-json-simple.json", 355, 415)));
}
#location 12
#vulnerability type RESOURCE_LEAK | #fixed code
@Test
public void TestArbitrarySplitLocations() throws Exception {
//int totalSize = 415;
//int [] recordBreaks = new int[] { 0, 40, 80, 120, 160, 200, 240, 280, 320, 372 };
Assert.assertArrayEquals(new int[] { 0 }, getRecordIndexesInReader(getReaderFor("unenclosed-json-simple.json", 0, 40)));
Assert.assertArrayEquals(new int[] { 0, 1 }, getRecordIndexesInReader(getReaderFor("unenclosed-json-simple.json", 0, 41)));
Assert.assertArrayEquals(new int[] { 0, 1 }, getRecordIndexesInReader(getReaderFor("unenclosed-json-simple.json", 0, 42)));
Assert.assertArrayEquals(new int[] { 1, 2, 3 }, getRecordIndexesInReader(getReaderFor("unenclosed-json-simple.json", 39, 123)));
Assert.assertArrayEquals(new int[] { 1, 2, 3 }, getRecordIndexesInReader(getReaderFor("unenclosed-json-simple.json", 20, 123)));
Assert.assertArrayEquals(new int[] { 1, 2, 3 }, getRecordIndexesInReader(getReaderFor("unenclosed-json-simple.json", 40, 123)));
Assert.assertArrayEquals(new int[] { 2, 3 }, getRecordIndexesInReader(getReaderFor("unenclosed-json-simple.json", 41, 123)));
Assert.assertArrayEquals(new int[] { 6, 7, 8 }, getRecordIndexesInReader(getReaderFor("unenclosed-json-simple.json", 240, 340)));
Assert.assertArrayEquals(new int[] { 9 }, getRecordIndexesInReader(getReaderFor("unenclosed-json-simple.json", 353, 415)));
Assert.assertArrayEquals(new int[] { 9 }, getRecordIndexesInReader(getReaderFor("unenclosed-json-simple.json", 354, 415)));
Assert.assertArrayEquals(new int[] { 9 }, getRecordIndexesInReader(getReaderFor("unenclosed-json-simple.json", 355, 415)));
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Test
public void TestEscQuoteLast() throws IOException {
//int [] recordBreaks = new int[] { 0, 75, 146, 218, 290, 362, , , };
Assert.assertArrayEquals(new int[] { 0 }, getRecordIndexesInReader(getReaderFor("unenclosed-json-esc1.json", 0, 44)));
Assert.assertArrayEquals(new int[] {0, 1}, getRecordIndexesInReader(getReaderFor("unenclosed-json-esc1.json", 0, 45)));
Assert.assertArrayEquals(new int[] {0, 1}, getRecordIndexesInReader(getReaderFor("unenclosed-json-esc1.json", 0, 46)));
Assert.assertArrayEquals(new int[] {1,2,3}, getRecordIndexesInReader(getReaderFor("unenclosed-json-esc1.json", 19, 140)));
Assert.assertArrayEquals(new int[] {1,2,3}, getRecordIndexesInReader(getReaderFor("unenclosed-json-esc1.json", 25, 140)));
Assert.assertArrayEquals(new int[] {1,2,3}, getRecordIndexesInReader(getReaderFor("unenclosed-json-esc1.json", 44, 140)));
}
#location 7
#vulnerability type RESOURCE_LEAK | #fixed code
@Test
public void TestEscQuoteLast() throws Exception {
//int [] recordBreaks = new int[] { 0, 75, 146, 218, 290, 362, , , };
Assert.assertArrayEquals(new int[] { 0 }, getRecordIndexesInReader(getReaderFor("unenclosed-json-esc1.json", 0, 44)));
Assert.assertArrayEquals(new int[] {0, 1}, getRecordIndexesInReader(getReaderFor("unenclosed-json-esc1.json", 0, 45)));
Assert.assertArrayEquals(new int[] {0, 1}, getRecordIndexesInReader(getReaderFor("unenclosed-json-esc1.json", 0, 46)));
Assert.assertArrayEquals(new int[] {1,2,3}, getRecordIndexesInReader(getReaderFor("unenclosed-json-esc1.json", 19, 140)));
Assert.assertArrayEquals(new int[] {1,2,3}, getRecordIndexesInReader(getReaderFor("unenclosed-json-esc1.json", 25, 140)));
Assert.assertArrayEquals(new int[] {1,2,3}, getRecordIndexesInReader(getReaderFor("unenclosed-json-esc1.json", 44, 140)));
} | 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.