output
stringlengths 64
73.2k
| input
stringlengths 208
73.3k
| instruction
stringclasses 1
value |
---|---|---|
#fixed code
@Test
public void testEntriesNeg55To105InRrd() throws IOException, FontFormatException {
createGaugeRrd(165);
RrdDb rrd = RrdDb.getBuilder().setPath(jrbFileName).build();
for(int i=0; i<160; i++) {
long timestamp = startTime + 1 + (i * 60);
Sample sample = rrd.createSample();
sample.setAndUpdate(timestamp + ":" + (i -55));
}
rrd.close();
prepareGraph();
expectMajorGridLine("-120");
expectMajorGridLine(" -60");
expectMajorGridLine(" 0");
expectMajorGridLine(" 60");
expectMajorGridLine(" 120");
run();
} | #vulnerable code
@Test
public void testEntriesNeg55To105InRrd() throws IOException, FontFormatException {
createGaugeRrd(165);
RrdDb rrd = new RrdDb(jrbFileName);
for(int i=0; i<160; i++) {
long timestamp = startTime + 1 + (i * 60);
Sample sample = rrd.createSample();
sample.setAndUpdate(timestamp + ":" + (i -55));
}
rrd.close();
prepareGraph();
expectMajorGridLine("-120");
expectMajorGridLine(" -60");
expectMajorGridLine(" 0");
expectMajorGridLine(" 60");
expectMajorGridLine(" 120");
run();
}
#location 10
#vulnerability type RESOURCE_LEAK | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Test
public void testBackendFactory() throws IOException {
RrdNioBackendFactory factory = (RrdNioBackendFactory) RrdBackendFactory.getFactory("NIO");
File rrdfile = testFolder.newFile("testfile");
RrdBackend be = factory.open(rrdfile.getCanonicalPath(), false);
be.setLength(10);
be.writeDouble(0, 0);
be.close();
DataInputStream is = new DataInputStream(new FileInputStream(rrdfile));
Double d = is.readDouble();
Assert.assertEquals("write to NIO failed", 0, d, 1e-10);
is.close();
} | #vulnerable code
@Test
public void testBackendFactory() throws IOException {
RrdNioBackendFactory factory = (RrdNioBackendFactory) RrdBackendFactory.getFactory("NIO");
File rrdfile = testFolder.newFile("testfile");
RrdBackend be = factory.open(rrdfile.getCanonicalPath(), false);
be.setLength(10);
be.writeDouble(0, 0);
be.close();
DataInputStream is = new DataInputStream(new FileInputStream(rrdfile));
Double d = is.readDouble();
Assert.assertEquals("write to NIO failed", 0, d, 1e-10);
}
#location 12
#vulnerability type RESOURCE_LEAK | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Test
public void testOneEntryInRrd() throws IOException, FontFormatException {
createGaugeRrd(100);
RrdDb rrd = RrdDb.getBuilder().setPath(jrbFileName).build();
long nowSeconds = new Date().getTime();
long fiveMinutesAgo = nowSeconds - (5 * 60);
Sample sample = rrd.createSample();
sample.setAndUpdate(fiveMinutesAgo+":10");
rrd.close();
prepareGraph();
checkForBasicGraph();
} | #vulnerable code
@Test
public void testOneEntryInRrd() throws IOException, FontFormatException {
createGaugeRrd(100);
RrdDb rrd = new RrdDb(jrbFileName);
long nowSeconds = new Date().getTime();
long fiveMinutesAgo = nowSeconds - (5 * 60);
Sample sample = rrd.createSample();
sample.setAndUpdate(fiveMinutesAgo+":10");
rrd.close();
prepareGraph();
checkForBasicGraph();
}
#location 12
#vulnerability type RESOURCE_LEAK | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Test
public void testEntriesNeg80To80InRrd() throws IOException, FontFormatException {
createGaugeRrd(180);
RrdDb rrd = RrdDb.getBuilder().setPath(jrbFileName).build();
for(int i=0; i<160; i++) {
long timestamp = startTime + 1 + (i * 60);
Sample sample = rrd.createSample();
sample.setAndUpdate(timestamp + ":" + (i -80));
}
rrd.close();
prepareGraph();
// Original
expectMinorGridLines(3);
expectMajorGridLine(" -50");
expectMinorGridLines(4);
expectMajorGridLine(" 0");
expectMinorGridLines(4);
expectMajorGridLine(" 50");
expectMinorGridLines(3);
run();
} | #vulnerable code
@Test
public void testEntriesNeg80To80InRrd() throws IOException, FontFormatException {
createGaugeRrd(180);
RrdDb rrd = new RrdDb(jrbFileName);
for(int i=0; i<160; i++) {
long timestamp = startTime + 1 + (i * 60);
Sample sample = rrd.createSample();
sample.setAndUpdate(timestamp + ":" + (i -80));
}
rrd.close();
prepareGraph();
// Original
expectMinorGridLines(3);
expectMajorGridLine(" -50");
expectMinorGridLines(4);
expectMajorGridLine(" 0");
expectMinorGridLines(4);
expectMajorGridLine(" 50");
expectMinorGridLines(3);
run();
}
#location 10
#vulnerability type RESOURCE_LEAK | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Test
public void shouldGetPlaylistsForUser_async() throws Exception {
final String accessToken = "someAccessToken";
final Api api = Api.builder().build();
final UserPlaylistsRequest request = api
.getPlaylistsForUser("wizzler")
.accessToken(accessToken)
.limit(10)
.offset(2)
.httpManager(TestUtil.MockedHttpManager.returningJson("user-playlists.json"))
.build();
final CountDownLatch asyncCompleted = new CountDownLatch(1);
final SettableFuture<Paging<PlaylistSimplified>> playlistsPageFuture = request.getAsync();
Futures.addCallback(playlistsPageFuture, new FutureCallback<Paging<PlaylistSimplified>>() {
@Override
public void onSuccess(Paging<PlaylistSimplified> playlistsPage) {
assertTrue(playlistsPage.getTotal() >= 0);
assertNull(playlistsPage.getNext());
assertEquals("https://api.spotify.com/v1/users/wizzler/playlists?offset=0&limit=10", playlistsPage.getPrevious());
assertEquals(10, playlistsPage.getLimit());
assertEquals(2, playlistsPage.getOffset());
assertEquals("https://api.spotify.com/v1/users/wizzler/playlists?offset=2&limit=10", playlistsPage.getHref());
final PlaylistSimplified simplePlaylist = playlistsPage.getItems().get(0);
final String playlistId = simplePlaylist.getId();
assertNotNull(playlistId);
assertTrue(playlistId.length() > 0);
assertEquals(false, simplePlaylist.getIsCollaborative());
assertEquals("http://open.spotify.com/user/wizzler/playlist/" + playlistId, simplePlaylist.getExternalUrls().get("spotify"));
assertNotNull(simplePlaylist.getName());
assertNotNull(simplePlaylist.getOwner());
assertNotNull(simplePlaylist.getIsPublicAccess());
assertNotNull(simplePlaylist.getTracks().getHref());
assertNotNull(simplePlaylist.getTracks().getTotal());
assertEquals(ObjectType.PLAYLIST, simplePlaylist.getType());
assertEquals("spotify:user:wizzler:playlist:" + playlistId, simplePlaylist.getUri());
assertEquals(1, simplePlaylist.getImages().size());
assertEquals("https://i.scdn.co/image/418ce596327dc3a0f4d377db80421bffb3b94a9a", simplePlaylist.getImages().get(0).getUrl());
assertEquals(0, simplePlaylist.getImages().get(0).getWidth());
assertEquals(0, simplePlaylist.getImages().get(0).getHeight());
asyncCompleted.countDown();
}
@Override
public void onFailure(Throwable throwable) {
fail("Failed to resolve future" + throwable.getMessage());
}
});
asyncCompleted.await(1, TimeUnit.SECONDS);
} | #vulnerable code
@Test
public void shouldGetPlaylistsForUser_async() throws Exception {
final String accessToken = "someAccessToken";
final Api api = Api.builder().build();
final UserPlaylistsRequest request = api
.getPlaylistsForUser("wizzler")
.accessToken(accessToken)
.limit(10)
.offset(2)
.httpManager(TestUtil.MockedHttpManager.returningJson("user-playlists.json"))
.build();
final CountDownLatch asyncCompleted = new CountDownLatch(1);
final SettableFuture<Paging<PlaylistSimplified>> playlistsPageFuture = request.getAsync();
Futures.addCallback(playlistsPageFuture, new FutureCallback<Paging<PlaylistSimplified>>() {
@Override
public void onSuccess(Paging<PlaylistSimplified> playlistsPage) {
assertTrue(playlistsPage.getTotal() >= 0);
assertNull(playlistsPage.getNext());
assertEquals("https://api.spotify.com/v1/users/wizzler/playlists?offset=0&limit=10", playlistsPage.getPrevious());
assertEquals(10, playlistsPage.getLimit());
assertEquals(2, playlistsPage.getOffset());
assertEquals("https://api.spotify.com/v1/users/wizzler/playlists?offset=2&limit=10", playlistsPage.getHref());
final PlaylistSimplified simplePlaylist = playlistsPage.getItems().get(0);
final String playlistId = simplePlaylist.getId();
assertNotNull(playlistId);
assertTrue(playlistId.length() > 0);
assertEquals(false, simplePlaylist.getIsCollaborative());
assertEquals("http://open.spotify.com/user/wizzler/playlist/" + playlistId, simplePlaylist.getExternalUrls().get("spotify"));
assertNotNull(simplePlaylist.getName());
assertNotNull(simplePlaylist.getOwner());
assertNotNull(simplePlaylist.getIsPublicAccess());
assertNotNull(simplePlaylist.getTracks().getHref());
assertNotNull(simplePlaylist.getTracks().getTotal());
assertEquals(ObjectType.PLAYLIST, simplePlaylist.getType());
assertEquals("spotify:user:wizzler:playlist:" + playlistId, simplePlaylist.getUri());
assertEquals(1, simplePlaylist.getImages().size());
assertEquals("https://i.scdn.co/image/418ce596327dc3a0f4d377db80421bffb3b94a9a", simplePlaylist.getImages().get(0).getUrl());
assertNull(simplePlaylist.getImages().get(0).getWidth());
assertNull(simplePlaylist.getImages().get(0).getHeight());
asyncCompleted.countDown();
}
@Override
public void onFailure(Throwable throwable) {
fail("Failed to resolve future" + throwable.getMessage());
}
});
asyncCompleted.await(1, TimeUnit.SECONDS);
}
#location 11
#vulnerability type RESOURCE_LEAK | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Test
public void shouldCreateFeaturedPlaylistsRequest() {
final String accessToken = "myAccessToken";
final Api api = Api.builder()
.accessToken(accessToken)
.build();
Calendar calendar = Calendar.getInstance();
calendar.set(2014, Calendar.DECEMBER, 22, 13, 59, 30);
Date timestamp = calendar.getTime();
final Request request = api
.getFeaturedPlaylists()
.country("SE")
.locale("es_MX")
.limit(5)
.offset(1)
.timestamp(timestamp)
.build();
DateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
assertEquals("https://api.spotify.com:443/v1/browse/featured-playlists", request.toString());
assertHasHeader(request.toUrl(), "Authorization", "Bearer " + accessToken);
assertHasParameter(request.toUrl(), "limit", "5");
assertHasParameter(request.toUrl(), "offset", "1");
assertHasParameter(request.toUrl(), "country", "SE");
assertHasParameter(request.toUrl(), "locale", "es_MX");
assertHasParameter(request.toUrl(), "timestamp", format.format(timestamp));
} | #vulnerable code
@Test
public void shouldCreateFeaturedPlaylistsRequest() {
final String accessToken = "myAccessToken";
final Api api = Api.builder()
.accessToken(accessToken)
.build();
Calendar calendar = Calendar.getInstance();
calendar.set(2014, 11, 22, 13, 59, 30);
Date timestamp = calendar.getTime();
final Request request = api
.getFeaturedPlaylists()
.country("SE")
.locale("es_MX")
.limit(5)
.offset(1)
.timestamp(timestamp)
.build();
DateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
assertEquals("https://api.spotify.com:443/v1/browse/featured-playlists", request.toString());
assertHasHeader(request.toUrl(), "Authorization", "Bearer " + accessToken);
assertHasParameter(request.toUrl(), "limit", "5");
assertHasParameter(request.toUrl(), "offset", "1");
assertHasParameter(request.toUrl(), "country", "SE");
assertHasParameter(request.toUrl(), "locale", "es_MX");
assertHasParameter(request.toUrl(), "timestamp", format.format(timestamp));
}
#location 7
#vulnerability type RESOURCE_LEAK | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Test
public void shouldGetAlbumResult_sync() throws Exception {
final Api api = Api.DEFAULT_API;
final HttpManager mockedHttpManager = TestUtil.MockedHttpManager.returningJson("album.json");
final AlbumRequest request = api.getAlbum("7e0ij2fpWaxOEHv5fUYZjd").httpManager(mockedHttpManager).build();
Album album = request.get();
assertNotNull(album);
assertEquals("0sNOF9WDwhWunNAHPD3Baj", album.getId());
} | #vulnerable code
@Test
public void shouldGetAlbumResult_sync() throws Exception {
final Api api = Api.DEFAULT_API;
final HttpManager mockedHttpManager = TestUtil.MockedHttpManager.returningJson("album.json");
final AlbumRequest request = api.album().id("7e0ij2fpWaxOEHv5fUYZjd").httpManager(mockedHttpManager).build();
Album album = request.getAlbum();
assertNotNull(album);
assertEquals("0sNOF9WDwhWunNAHPD3Baj", album.getId());
}
#location 10
#vulnerability type NULL_DEREFERENCE | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Test
public void shouldGetPlaylistsForUser_sync() throws Exception {
final String accessToken = "myVeryLongAccessToken";
final Api api = Api.builder().build();
final UserPlaylistsRequest request = api
.getPlaylistsForUser("wizzler")
.accessToken(accessToken)
.httpManager(TestUtil.MockedHttpManager.returningJson("user-playlists.json"))
.build();
final Paging<PlaylistSimplified> playlistsPage = request.get();
assertTrue(playlistsPage.getTotal() >= 0);
assertNull(playlistsPage.getNext());
assertEquals("https://api.spotify.com/v1/users/wizzler/playlists?offset=0&limit=10", playlistsPage.getPrevious());
assertEquals(10, playlistsPage.getLimit());
assertEquals(2, playlistsPage.getOffset());
assertEquals("https://api.spotify.com/v1/users/wizzler/playlists?offset=2&limit=10", playlistsPage.getHref());
final PlaylistSimplified simplePlaylist = playlistsPage.getItems().get(0);
final String playlistId = simplePlaylist.getId();
assertNotNull(playlistId);
assertTrue(playlistId.length() > 0);
assertEquals(false, simplePlaylist.getIsCollaborative());
assertEquals("http://open.spotify.com/user/wizzler/playlist/" + playlistId, simplePlaylist.getExternalUrls().get("spotify"));
assertNotNull(simplePlaylist.getName());
assertNotNull(simplePlaylist.getOwner());
assertNotNull(simplePlaylist.getIsPublicAccess());
assertNotNull(simplePlaylist.getTracks().getHref());
assertNotNull(simplePlaylist.getTracks().getTotal());
assertEquals(ObjectType.PLAYLIST, simplePlaylist.getType());
assertEquals("spotify:user:wizzler:playlist:" + playlistId, simplePlaylist.getUri());
assertEquals(1, simplePlaylist.getImages().size());
assertEquals("https://i.scdn.co/image/418ce596327dc3a0f4d377db80421bffb3b94a9a", simplePlaylist.getImages().get(0).getUrl());
assertEquals(0, simplePlaylist.getImages().get(0).getWidth());
assertEquals(0, simplePlaylist.getImages().get(0).getHeight());
} | #vulnerable code
@Test
public void shouldGetPlaylistsForUser_sync() throws Exception {
final String accessToken = "myVeryLongAccessToken";
final Api api = Api.builder().build();
final UserPlaylistsRequest request = api
.getPlaylistsForUser("wizzler")
.accessToken(accessToken)
.httpManager(TestUtil.MockedHttpManager.returningJson("user-playlists.json"))
.build();
final Paging<PlaylistSimplified> playlistsPage = request.get();
assertTrue(playlistsPage.getTotal() >= 0);
assertNull(playlistsPage.getNext());
assertEquals("https://api.spotify.com/v1/users/wizzler/playlists?offset=0&limit=10", playlistsPage.getPrevious());
assertEquals(10, playlistsPage.getLimit());
assertEquals(2, playlistsPage.getOffset());
assertEquals("https://api.spotify.com/v1/users/wizzler/playlists?offset=2&limit=10", playlistsPage.getHref());
final PlaylistSimplified simplePlaylist = playlistsPage.getItems().get(0);
final String playlistId = simplePlaylist.getId();
assertNotNull(playlistId);
assertTrue(playlistId.length() > 0);
assertEquals(false, simplePlaylist.getIsCollaborative());
assertEquals("http://open.spotify.com/user/wizzler/playlist/" + playlistId, simplePlaylist.getExternalUrls().get("spotify"));
assertNotNull(simplePlaylist.getName());
assertNotNull(simplePlaylist.getOwner());
assertNotNull(simplePlaylist.getIsPublicAccess());
assertNotNull(simplePlaylist.getTracks().getHref());
assertNotNull(simplePlaylist.getTracks().getTotal());
assertEquals(ObjectType.PLAYLIST, simplePlaylist.getType());
assertEquals("spotify:user:wizzler:playlist:" + playlistId, simplePlaylist.getUri());
assertEquals(1, simplePlaylist.getImages().size());
assertEquals("https://i.scdn.co/image/418ce596327dc3a0f4d377db80421bffb3b94a9a", simplePlaylist.getImages().get(0).getUrl());
assertNull(simplePlaylist.getImages().get(0).getWidth());
assertNull(simplePlaylist.getImages().get(0).getHeight());
}
#location 9
#vulnerability type RESOURCE_LEAK | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
private static String readFromFile(File file) throws IOException {
BufferedReader in = new BufferedReader(new InputStreamReader(new FileInputStream(file), "UTF8"));
StringBuilder out = new StringBuilder();
String line;
while ((line = in.readLine()) != null) {
out.append(line);
}
in.close();
return out.toString();
} | #vulnerable code
private static String readFromFile(File file) throws IOException {
Reader reader = new FileReader(file);
CharBuffer charBuffer = CharBuffer.allocate(MAX_TEST_DATA_FILE_SIZE);
reader.read(charBuffer);
charBuffer.position(0);
return charBuffer.toString();
}
#location 4
#vulnerability type RESOURCE_LEAK | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Test
public void shouldCreateFeaturedPlaylistsRequest() {
final String accessToken = "myAccessToken";
final Api api = Api.builder()
.accessToken(accessToken)
.build();
Calendar calendar = Calendar.getInstance();
calendar.set(2014, Calendar.DECEMBER, 22, 13, 59, 30);
Date timestamp = calendar.getTime();
final Request request = api
.getFeaturedPlaylists()
.country("SE")
.locale("es_MX")
.limit(5)
.offset(1)
.timestamp(timestamp)
.build();
DateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
assertEquals("https://api.spotify.com:443/v1/browse/featured-playlists", request.toString());
assertHasHeader(request.toUrl(), "Authorization", "Bearer " + accessToken);
assertHasParameter(request.toUrl(), "limit", "5");
assertHasParameter(request.toUrl(), "offset", "1");
assertHasParameter(request.toUrl(), "country", "SE");
assertHasParameter(request.toUrl(), "locale", "es_MX");
assertHasParameter(request.toUrl(), "timestamp", format.format(timestamp));
} | #vulnerable code
@Test
public void shouldCreateFeaturedPlaylistsRequest() {
final String accessToken = "myAccessToken";
final Api api = Api.builder()
.accessToken(accessToken)
.build();
Calendar calendar = Calendar.getInstance();
calendar.set(2014, 11, 22, 13, 59, 30);
Date timestamp = calendar.getTime();
final Request request = api
.getFeaturedPlaylists()
.country("SE")
.locale("es_MX")
.limit(5)
.offset(1)
.timestamp(timestamp)
.build();
DateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
assertEquals("https://api.spotify.com:443/v1/browse/featured-playlists", request.toString());
assertHasHeader(request.toUrl(), "Authorization", "Bearer " + accessToken);
assertHasParameter(request.toUrl(), "limit", "5");
assertHasParameter(request.toUrl(), "offset", "1");
assertHasParameter(request.toUrl(), "country", "SE");
assertHasParameter(request.toUrl(), "locale", "es_MX");
assertHasParameter(request.toUrl(), "timestamp", format.format(timestamp));
}
#location 26
#vulnerability type NULL_DEREFERENCE | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
private static String readFromFile(File file) throws IOException {
BufferedReader in = new BufferedReader(new InputStreamReader(new FileInputStream(file), "UTF8"));
StringBuilder out = new StringBuilder();
String line;
while ((line = in.readLine()) != null) {
out.append(line);
}
in.close();
return out.toString();
} | #vulnerable code
private static String readFromFile(File file) throws IOException {
Reader reader = new FileReader(file);
CharBuffer charBuffer = CharBuffer.allocate(MAX_TEST_DATA_FILE_SIZE);
reader.read(charBuffer);
charBuffer.position(0);
return charBuffer.toString();
}
#location 4
#vulnerability type RESOURCE_LEAK | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
public void bindScope(Class<? extends Annotation> annotationType,
Scope scope) {
Scope existing = scopes.get(nonNull(annotationType, "annotation type"));
if (existing != null) {
addError(source(), ErrorMessages.DUPLICATE_SCOPES, existing,
annotationType, scope);
}
else {
scopes.put(annotationType, nonNull(scope, "scope"));
}
} | #vulnerable code
public void bindScope(Class<? extends Annotation> annotationType,
Scope scope) {
ensureNotCreated();
Scope existing = scopes.get(nonNull(annotationType, "annotation type"));
if (existing != null) {
addError(source(), ErrorMessages.DUPLICATE_SCOPES, existing,
annotationType, scope);
}
else {
scopes.put(annotationType, nonNull(scope, "scope"));
}
}
#location 3
#vulnerability type THREAD_SAFETY_VIOLATION | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
public <T> LinkedBindingBuilderImpl<T> link(Key<T> key) {
LinkedBindingBuilderImpl<T> builder =
new LinkedBindingBuilderImpl<T>(this, key).from(source());
linkedBindingBuilders.add(builder);
return builder;
} | #vulnerable code
public <T> LinkedBindingBuilderImpl<T> link(Key<T> key) {
ensureNotCreated();
LinkedBindingBuilderImpl<T> builder =
new LinkedBindingBuilderImpl<T>(this, key).from(source());
linkedBindingBuilders.add(builder);
return builder;
}
#location 2
#vulnerability type THREAD_SAFETY_VIOLATION | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
void addError(Object source, String message, Object... arguments) {
new ConfigurationErrorHandler(source).handle(message, arguments);
} | #vulnerable code
void putBinding(Binding<?> binding) {
Key<?> key = binding.getKey();
Map<Key<?>, Binding<?>> bindings = container.internalBindings();
Binding<?> original = bindings.get(key);
if (bindings.containsKey(key)) {
addError(binding.getSource(), ErrorMessages.BINDING_ALREADY_SET, key,
original.getSource());
}
else {
bindings.put(key, binding);
}
}
#location 3
#vulnerability type THREAD_SAFETY_VIOLATION | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
public <T> BindingBuilderImpl<T> bind(Key<T> key) {
BindingBuilderImpl<T> builder = new BindingBuilderImpl<T>(this, key, source());
bindingBuilders.add(builder);
return builder;
} | #vulnerable code
public <T> BindingBuilderImpl<T> bind(Key<T> key) {
ensureNotCreated();
BindingBuilderImpl<T> builder = new BindingBuilderImpl<T>(this, key, source());
bindingBuilders.add(builder);
return builder;
}
#location 2
#vulnerability type THREAD_SAFETY_VIOLATION | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
InternalContext(InjectorOptions options, Object[] toClear) {
this.options = options;
this.toClear = toClear;
this.enterCount = 1;
} | #vulnerable code
java.util.List<com.google.inject.spi.DependencyAndSource> getDependencyChain() {
com.google.common.collect.ImmutableList.Builder<com.google.inject.spi.DependencyAndSource>
builder = com.google.common.collect.ImmutableList.builder();
for (int i = 0; i < dependencyStackSize; i += 2) {
Object evenEntry = dependencyStack[i];
Dependency<?> dependency;
if (evenEntry instanceof com.google.inject.Key) {
dependency = Dependency.get((com.google.inject.Key<?>) evenEntry);
} else {
dependency = (Dependency<?>) evenEntry;
}
builder.add(new com.google.inject.spi.DependencyAndSource(dependency, dependencyStack[i + 1]));
}
return builder.build();
}
#location 1
#vulnerability type CHECKERS_IMMUTABLE_CAST | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
public ConstantBindingBuilderImpl bindConstant(
Class<? extends Annotation> annotationType) {
return bind(source(), Key.strategyFor(annotationType));
} | #vulnerable code
public ConstantBindingBuilderImpl bindConstant(
Class<? extends Annotation> annotationType) {
ensureNotCreated();
return bind(source(), Key.strategyFor(annotationType));
}
#location 3
#vulnerability type THREAD_SAFETY_VIOLATION | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
public ConstantBindingBuilderImpl bindConstant(Annotation annotation) {
return bind(source(), Key.strategyFor(annotation));
} | #vulnerable code
public ConstantBindingBuilderImpl bindConstant(Annotation annotation) {
ensureNotCreated();
return bind(source(), Key.strategyFor(annotation));
}
#location 2
#vulnerability type THREAD_SAFETY_VIOLATION | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
void addError(Object source, String message, Object... arguments) {
configurationErrorHandler.handle(source, message, arguments);
} | #vulnerable code
void putBinding(Binding<?> binding) {
Key<?> key = binding.getKey();
Map<Key<?>, Binding<?>> bindings = container.internalBindings();
Binding<?> original = bindings.get(key);
// Binding to Locator<?> is not allowed.
if (key.getRawType().equals(Locator.class)) {
addError(binding.getSource(), ErrorMessages.CANNOT_BIND_TO_LOCATOR);
return;
}
if (bindings.containsKey(key)) {
addError(binding.getSource(), ErrorMessages.BINDING_ALREADY_SET, key,
original.getSource());
}
else {
bindings.put(key, binding);
}
}
#location 3
#vulnerability type THREAD_SAFETY_VIOLATION | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
public void bindInterceptor(Matcher<? super Class<?>> classMatcher,
Matcher<? super Method> methodMatcher, MethodInterceptor... interceptors) {
proxyFactoryBuilder.intercept(classMatcher, methodMatcher, interceptors);
} | #vulnerable code
public void bindInterceptor(Matcher<? super Class<?>> classMatcher,
Matcher<? super Method> methodMatcher, MethodInterceptor... interceptors) {
ensureNotCreated();
proxyFactoryBuilder.intercept(classMatcher, methodMatcher, interceptors);
}
#location 3
#vulnerability type THREAD_SAFETY_VIOLATION | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Override
protected void doHealthCheck(Health.Builder builder) throws Exception {
AdminClient adminClient = null;
try {
final Status status = healthStatusThreadLocal.get();
//If one of the kafka streams binders (kstream, ktable, globalktable) was down before on the same request,
//retrieve that from the theadlocal storage where it was saved before. This is done in order to avoid
//the duration of the total health check since in the case of Kafka Streams each binder tries to do
//its own health check and since we already know that this is DOWN, simply pass that information along.
if (status == Status.DOWN) {
builder.withDetail("No topic information available", "Kafka broker is not reachable");
builder.status(Status.DOWN);
}
else {
adminClient = AdminClient.create(this.adminClientProperties);
final ListTopicsResult listTopicsResult = adminClient.listTopics();
listTopicsResult.listings().get(this.configurationProperties.getHealthTimeout(), TimeUnit.SECONDS);
if (this.kafkaStreamsBindingInformationCatalogue.getStreamsBuilderFactoryBeans().isEmpty()) {
builder.withDetail("No Kafka Streams bindings have been established", "Kafka Streams binder did not detect any processors");
builder.status(Status.UNKNOWN);
}
else {
boolean up = true;
for (KafkaStreams kStream : kafkaStreamsRegistry.getKafkaStreams()) {
up &= kStream.state().isRunning();
builder.withDetails(buildDetails(kStream));
}
builder.status(up ? Status.UP : Status.DOWN);
}
}
}
catch (Exception e) {
builder.withDetail("No topic information available", "Kafka broker is not reachable");
builder.status(Status.DOWN);
builder.withException(e);
//Store binder down status into a thread local storage.
healthStatusThreadLocal.set(Status.DOWN);
}
finally {
// Close admin client immediately.
if (adminClient != null) {
adminClient.close(Duration.ofSeconds(0));
}
}
} | #vulnerable code
@Override
protected void doHealthCheck(Health.Builder builder) throws Exception {
AdminClient adminClient = null;
try {
final Status status = healthStatusThreadLocal.get();
//If one of the kafka streams binders (kstream, ktable, globalktable) was down before on the same request,
//retrieve that from the theadlocal storage where it was saved before. This is done in order to avoid
//the duration of the total health check since in the case of Kafka Streams each binder tries to do
//its own health check and since we already know that this is DOWN, simply pass that information along.
if (status == Status.DOWN) {
builder.withDetail("No topic information available", "Kafka broker is not reachable");
builder.status(Status.DOWN);
}
else {
adminClient = AdminClient.create(this.adminClientProperties);
final ListTopicsResult listTopicsResult = adminClient.listTopics();
listTopicsResult.listings().get(this.configurationProperties.getHealthTimeout(), TimeUnit.SECONDS);
if (this.kafkaStreamsBindingInformationCatalogue.getStreamsBuilderFactoryBeans().isEmpty()) {
builder.withDetail("No Kafka Streams bindings have been established", "Kafka Streams binder did not detect any processors");
builder.status(Status.UNKNOWN);
}
else {
boolean up = true;
for (KafkaStreams kStream : kafkaStreamsRegistry.getKafkaStreams()) {
up &= kStream.state().isRunning();
builder.withDetails(buildDetails(kStream));
}
builder.status(up ? Status.UP : Status.DOWN);
}
}
}
catch (Exception e) {
builder.withDetail("No topic information available", "Kafka broker is not reachable");
builder.status(Status.DOWN);
builder.withException(e);
//Store binder down status into a thread local storage.
healthStatusThreadLocal.set(Status.DOWN);
}
finally {
// Close admin client immediately.
adminClient.close(Duration.ofSeconds(0));
}
}
#location 43
#vulnerability type NULL_DEREFERENCE | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Override
protected double evaluateFunction(final Access1D<?> solution) {
final MatrixStore<Double> tmpX = this.getSolutionX();
return tmpX.transpose().multiply(this.getMatrixQ().multiply(tmpX)).multiply(0.5).subtract(tmpX.transpose().multiply(this.getMatrixC())).doubleValue(0L);
} | #vulnerable code
@Override
protected double evaluateFunction(final Access1D<?> solution) {
final MatrixStore<Double> tmpX = this.getMatrixX();
return tmpX.transpose().multiply(this.getMatrixQ().multiply(tmpX)).multiply(0.5).subtract(tmpX.transpose().multiply(this.getMatrixC())).doubleValue(0L);
}
#location 6
#vulnerability type NULL_DEREFERENCE | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
public MatrixStore<N> getInverse() {
return this.getInverse(this.preallocate(new Structure2D() {
public long countRows() {
return myTransposed ? myBidiagonal.getColDim() : myBidiagonal.getRowDim();
}
public long countColumns() {
return myTransposed ? myBidiagonal.getRowDim() : myBidiagonal.getColDim();
}
}));
} | #vulnerable code
public MatrixStore<N> getInverse() {
if (myInverse == null) {
final MatrixStore<N> tmpQ1 = this.getQ1();
final MatrixStore<N> tmpD = this.getD();
final int tmpRowDim = (int) tmpD.countRows();
final int tmpColDim = (int) tmpQ1.countRows();
final PhysicalStore<N> tmpMtrx = this.makeZero(tmpRowDim, tmpColDim);
double tmpSingularValue;
final int rank = this.getRank();
for (int i = 0; i < rank; i++) {
tmpSingularValue = tmpD.doubleValue(i, i);
for (int j = 0; j < tmpColDim; j++) {
tmpMtrx.set(i, j, tmpQ1.toScalar(j, i).conjugate().divide(tmpSingularValue).getNumber());
}
}
myInverse = this.getQ2().multiply(tmpMtrx);
}
return myInverse;
}
#location 21
#vulnerability type NULL_DEREFERENCE | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
public MatrixStore<N> getInverse(final DecompositionStore<N> preallocated) {
if (myInverse == null) {
final MatrixStore<N> tmpQ1 = this.getQ1();
final Array1D<Double> tmpSingulars = this.getSingularValues();
final MatrixStore<N> tmpQ2 = this.getQ2();
final int tmpRowDim = (int) tmpSingulars.count();
final int tmpColDim = (int) tmpQ1.countRows();
final PhysicalStore<N> tmpMtrx = this.makeZero(tmpRowDim, tmpColDim);
double tmpValue;
final int rank = this.getRank();
for (int i = 0; i < rank; i++) {
tmpValue = tmpSingulars.doubleValue(i);
for (int j = 0; j < tmpColDim; j++) {
tmpMtrx.set(i, j, tmpQ1.toScalar(j, i).conjugate().divide(tmpValue).getNumber());
}
}
preallocated.fillByMultiplying(tmpQ2, tmpMtrx);
myInverse = preallocated;
}
return myInverse;
} | #vulnerable code
public MatrixStore<N> getInverse(final DecompositionStore<N> preallocated) {
if (myInverse == null) {
preallocated.fillAll(this.scalar().zero().getNumber());
final PhysicalStore<N> tmpMtrx = preallocated;
final MatrixStore<N> tmpQ1 = this.getQ1();
final MatrixStore<N> tmpD = this.getD();
final int tmpColDim = (int) tmpQ1.countRows();
double tmpSingularValue;
final int rank = this.getRank();
for (int i = 0; i < rank; i++) {
tmpSingularValue = tmpD.doubleValue(i, i);
for (int j = 0; j < tmpColDim; j++) {
tmpMtrx.set(i, j, tmpQ1.toScalar(j, i).conjugate().divide(tmpSingularValue).getNumber());
}
}
myInverse = this.getQ2().multiply(tmpMtrx);
}
return myInverse;
}
#location 22
#vulnerability type NULL_DEREFERENCE | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
public MatrixStore<N> getInverse() {
return this.getInverse(this.preallocate(new Structure2D() {
public long countRows() {
return myTransposed ? myBidiagonal.getColDim() : myBidiagonal.getRowDim();
}
public long countColumns() {
return myTransposed ? myBidiagonal.getRowDim() : myBidiagonal.getColDim();
}
}));
} | #vulnerable code
public MatrixStore<N> getInverse() {
if (myInverse == null) {
final MatrixStore<N> tmpQ1 = this.getQ1();
final MatrixStore<N> tmpD = this.getD();
final int tmpRowDim = (int) tmpD.countRows();
final int tmpColDim = (int) tmpQ1.countRows();
final PhysicalStore<N> tmpMtrx = this.makeZero(tmpRowDim, tmpColDim);
double tmpSingularValue;
final int rank = this.getRank();
for (int i = 0; i < rank; i++) {
tmpSingularValue = tmpD.doubleValue(i, i);
for (int j = 0; j < tmpColDim; j++) {
tmpMtrx.set(i, j, tmpQ1.toScalar(j, i).conjugate().divide(tmpSingularValue).getNumber());
}
}
myInverse = this.getQ2().multiply(tmpMtrx);
}
return myInverse;
}
#location 8
#vulnerability type NULL_DEREFERENCE | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
private boolean isFeasible() {
boolean retVal = true;
final MatrixStore<Double> tmpSE = this.getSE();
for (int i = 0; retVal && (i < tmpSE.countRows()); i++) {
if (!options.slack.isZero(tmpSE.doubleValue(i))) {
retVal = false;
}
}
return retVal;
} | #vulnerable code
private boolean isFeasible() {
boolean retVal = true;
final MatrixStore<Double> tmpAEX = this.getAEX();
final MatrixStore<Double> tmpBE = this.getMatrixBE();
for (int i = 0; retVal && (i < tmpBE.countRows()); i++) {
if (options.slack.isDifferent(tmpBE.doubleValue(i), tmpAEX.doubleValue(i))) {
retVal = false;
}
}
return retVal;
}
#location 8
#vulnerability type NULL_DEREFERENCE | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
public MatrixStore<N> getInverse(final DecompositionStore<N> preallocated) {
if (myInverse == null) {
final MatrixStore<N> tmpQ1 = this.getQ1();
final Array1D<Double> tmpSingulars = this.getSingularValues();
final MatrixStore<N> tmpQ2 = this.getQ2();
final int tmpRowDim = (int) tmpSingulars.count();
final int tmpColDim = (int) tmpQ1.countRows();
final PhysicalStore<N> tmpMtrx = this.makeZero(tmpRowDim, tmpColDim);
double tmpValue;
final int rank = this.getRank();
for (int i = 0; i < rank; i++) {
tmpValue = tmpSingulars.doubleValue(i);
for (int j = 0; j < tmpColDim; j++) {
tmpMtrx.set(i, j, tmpQ1.toScalar(j, i).conjugate().divide(tmpValue).getNumber());
}
}
preallocated.fillByMultiplying(tmpQ2, tmpMtrx);
myInverse = preallocated;
}
return myInverse;
} | #vulnerable code
public MatrixStore<N> getInverse(final DecompositionStore<N> preallocated) {
if (myInverse == null) {
preallocated.fillAll(this.scalar().zero().getNumber());
final PhysicalStore<N> tmpMtrx = preallocated;
final MatrixStore<N> tmpQ1 = this.getQ1();
final MatrixStore<N> tmpD = this.getD();
final int tmpColDim = (int) tmpQ1.countRows();
double tmpSingularValue;
final int rank = this.getRank();
for (int i = 0; i < rank; i++) {
tmpSingularValue = tmpD.doubleValue(i, i);
for (int j = 0; j < tmpColDim; j++) {
tmpMtrx.set(i, j, tmpQ1.toScalar(j, i).conjugate().divide(tmpSingularValue).getNumber());
}
}
myInverse = this.getQ2().multiply(tmpMtrx);
}
return myInverse;
}
#location 16
#vulnerability type NULL_DEREFERENCE | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Override
protected double evaluateFunction(final Access1D<?> solution) {
final MatrixStore<Double> tmpX = this.getMatrixX();
return tmpX.transpose().multiply(this.getMatrixQ().multiply(tmpX)).multiply(0.5).subtract(tmpX.transpose().multiply(this.getMatrixC())).doubleValue(0L);
} | #vulnerable code
@Override
protected double evaluateFunction(final Access1D<?> solution) {
final MatrixStore<Double> tmpX = this.getX();
return tmpX.transpose().multiply(this.getQ().multiply(tmpX)).multiply(0.5).subtract(tmpX.transpose().multiply(this.getC())).doubleValue(0L);
}
#location 6
#vulnerability type NULL_DEREFERENCE | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
public N remove(final long key) {
final int index = myStorage.index(key);
final N oldValue = index >= 0 ? myStorage.getInternally(index) : null;
myStorage.remove(key, index);
return oldValue;
} | #vulnerable code
public N remove(final long key) {
final N tmpOldVal = myStorage.get(key);
myStorage.set(key, 0.0);
return tmpOldVal;
}
#location 3
#vulnerability type THREAD_SAFETY_VIOLATION | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
public MatrixStore<N> getInverse(final DecompositionStore<N> preallocated) {
if (myInverse == null) {
final MatrixStore<N> tmpQ1 = this.getQ1();
final Array1D<Double> tmpSingulars = this.getSingularValues();
final MatrixStore<N> tmpQ2 = this.getQ2();
final PhysicalStore<N> tmpMtrx = tmpQ2.copy();
final Scalar.Factory<N> tmpScalar = this.scalar();
final BinaryFunction<N> tmpDivide = this.function().divide();
final N tmpZero = tmpScalar.zero().getNumber();
final int rank = this.getRank();
for (int i = 0; i < rank; i++) {
tmpMtrx.modifyColumn(0L, i, tmpDivide.second(tmpScalar.cast(tmpSingulars.doubleValue(i))));
}
final long tmpCountColumns = tmpMtrx.countColumns();
for (int i = rank; i < tmpCountColumns; i++) {
tmpMtrx.fillColumn(0L, i, tmpZero);
}
preallocated.fillByMultiplying(tmpMtrx, tmpQ1.conjugate());
myInverse = preallocated;
}
return myInverse;
} | #vulnerable code
public MatrixStore<N> getInverse(final DecompositionStore<N> preallocated) {
if (myInverse == null) {
final MatrixStore<N> tmpQ1 = this.getQ1();
final Array1D<Double> tmpSingulars = this.getSingularValues();
final MatrixStore<N> tmpQ2 = this.getQ2();
final int tmpRowDim = (int) tmpSingulars.count();
final int tmpColDim = (int) tmpQ1.countRows();
final PhysicalStore<N> tmpMtrx = this.makeZero(tmpRowDim, tmpColDim);
double tmpValue;
final int rank = this.getRank();
for (int i = 0; i < rank; i++) {
tmpValue = tmpSingulars.doubleValue(i);
for (int j = 0; j < tmpColDim; j++) {
tmpMtrx.set(i, j, tmpQ1.toScalar(j, i).conjugate().divide(tmpValue).getNumber());
}
}
preallocated.fillByMultiplying(tmpQ2, tmpMtrx);
myInverse = preallocated;
}
return myInverse;
}
#location 10
#vulnerability type NULL_DEREFERENCE | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
public static void main(final String[] args) {
final Array1D<Double> doubles = Array1D.factory(Primitive32Array.FACTORY).makeFilled(10, new Uniform());
System.out.println(doubles.toString());
final Array1D<Double> rollingMedian = Array1D.PRIMITIVE32.makeZero(doubles.size());
rollingMedian.set(0, doubles.get(0));
System.out.printf("%1$s -> %1$s\n", doubles.get(0));
final Array1D<Double> someSamples2 = doubles.subList(0, 2);
final double mean2 = SampleSet.wrap(someSamples2).getMean();
rollingMedian.set(1, mean2);
System.out.printf("%s -> %s\n", someSamples2.toString(), mean2);
for (int i = 2; i < doubles.length; i++) {
final Array1D<Double> someSamples = doubles.subList(i - 2, i + 1);
final double mean = SampleSet.wrap(someSamples).getMean();
rollingMedian.set(i, mean);
System.out.printf("%s -> %s\n", someSamples.toString(), mean2);
}
System.out.println(rollingMedian.toString());
for (int i = 0; i < doubles.length; i++) {
final int first = Math.max(0, i - 2);
final int limit = i + 1;
final double mean = doubles.aggregateRange(first, limit, Aggregator.AVERAGE);
rollingMedian.set(i, mean);
}
System.out.println(rollingMedian.toString());
final SampleSet samples = SampleSet.make();
for (int i = 0; i < doubles.length; i++) {
final int first = Math.max(0, i - 2);
final int limit = i + 1;
samples.swap(doubles.sliceRange(first, limit));
final double mean = samples.getMean();
rollingMedian.set(i, mean);
}
System.out.println(rollingMedian.toString());
final PrimitiveDenseStore org = MatrixUtils.makeSPD(10);
final Eigenvalue<Double> evd = Eigenvalue.PRIMITIVE.make(true);
evd.decompose(org);
final MatrixStore<Double> expSquared = org.multiply(org);
final MatrixStore<Double> v = evd.getV();
final MatrixStore<Double> d = evd.getD().logical().diagonal(false).get();
final Array1D<ComplexNumber> values = evd.getEigenvalues();
final MatrixStore<Double> ident = v.multiply(v.conjugate());
final MatrixStore<Double> actSquared = v.multiply(d).multiply(d).multiply(v.conjugate());
TestUtils.assertEquals(expSquared, actSquared);
final PhysicalStore<Double> copied = v.copy();
copied.loopRow(0, (r, c) -> copied.modifyColumn(c, PrimitiveFunction.MULTIPLY.second(values.doubleValue(c) * values.doubleValue(c))));
final MatrixStore<Double> actSquared2 = copied.multiply(v.conjugate());
TestUtils.assertEquals(expSquared, actSquared2);
final MatrixStore<Double> matrix = org;
matrix.logical().limits(3, 3).offsets(1, 1).get();
matrix.logical().offsets(1, 1).get();
} | #vulnerable code
public static void main(final String[] args) {
final Array1D<Double> doubles = Array1D.factory(Primitive32Array.FACTORY).makeFilled(10, new Uniform());
System.out.println(doubles.toString());
final Array1D<Double> rollingMedian = Array1D.PRIMITIVE32.makeZero(doubles.size());
rollingMedian.set(0, doubles.get(0));
System.out.printf("%1$s -> %1$s\n", doubles.get(0));
final Array1D<Double> someSamples2 = doubles.subList(0, 2);
final double mean2 = SampleSet.wrap(someSamples2).getMean();
rollingMedian.set(1, mean2);
System.out.printf("%s -> %s\n", someSamples2.toString(), mean2);
for (int i = 2; i < doubles.length; i++) {
final Array1D<Double> someSamples = doubles.subList(i - 2, i + 1);
final double mean = SampleSet.wrap(someSamples).getMean();
rollingMedian.set(i, mean);
System.out.printf("%s -> %s\n", someSamples.toString(), mean2);
}
System.out.println(rollingMedian.toString());
for (int i = 0; i < doubles.length; i++) {
final int first = Math.max(0, i - 2);
final int limit = i + 1;
final double mean = doubles.aggregateRange(first, limit, Aggregator.AVERAGE);
rollingMedian.set(i, mean);
}
System.out.println(rollingMedian.toString());
final SampleSet samples = SampleSet.make();
for (int i = 0; i < doubles.length; i++) {
final int first = Math.max(0, i - 2);
final int limit = i + 1;
samples.swap(doubles.sliceRange(first, limit));
final double mean = samples.getMean();
rollingMedian.set(i, mean);
}
System.out.println(rollingMedian.toString());
final PrimitiveDenseStore org = MatrixUtils.makeSPD(10);
final Eigenvalue<Double> evd = Eigenvalue.PRIMITIVE.make(true);
evd.decompose(org);
final MatrixStore<Double> expSquared = org.multiply(org);
final MatrixStore<Double> v = evd.getV();
final MatrixStore<Double> d = evd.getD().logical().diagonal(false).get();
final Array1D<ComplexNumber> values = evd.getEigenvalues();
final MatrixStore<Double> ident = v.multiply(v.conjugate());
final MatrixStore<Double> actSquared = v.multiply(d).multiply(d).multiply(v.conjugate());
TestUtils.assertEquals(expSquared, actSquared);
final PhysicalStore<Double> copied = v.copy();
copied.loopRow(0, (r, c) -> copied.modifyColumn(c, PrimitiveFunction.MULTIPLY.second(values.doubleValue(c) * values.doubleValue(c))));
final MatrixStore<Double> actSquared2 = copied.multiply(v.conjugate());
TestUtils.assertEquals(expSquared, actSquared2);
final MatrixStore<Double> matrix = null;
matrix.logical().limits(3, 3).offsets(1, 1).get();
matrix.logical().offsets(1, 1).get();
}
#location 70
#vulnerability type NULL_DEREFERENCE | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
void doTestFeedForward(final Factory<Double, ?> factory) {
int counter = 0;
ArtificialNeuralNetwork network = this.getInitialNetwork(factory);
NetworkInvoker invoker = network.newInvoker();
for (Data triplet : this.getTestCases()) {
if ((triplet.input != null) && (triplet.expected != null)) {
TestUtils.assertEquals(triplet.expected, invoker.invoke(triplet.input), this.precision());
counter++;
}
}
if (counter == 0) {
TestUtils.fail(TEST_DID_NOT_DO_ANYTHING);
}
} | #vulnerable code
void doTestFeedForward(Factory<Double, ?> factory) {
int counter = 0;
ArtificialNeuralNetwork network = this.getInitialNetwork(factory).get();
for (Data triplet : this.getTestCases()) {
if ((triplet.input != null) && (triplet.expected != null)) {
TestUtils.assertEquals(triplet.expected, network.invoke(triplet.input), this.precision());
counter++;
}
}
if (counter == 0) {
TestUtils.fail(TEST_DID_NOT_DO_ANYTHING);
}
}
#location 9
#vulnerability type NULL_DEREFERENCE | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
public int getRank() {
final double tolerance = s[0] * this.getDimensionalEpsilon();
int rank = 0;
for (int i = 0; i < s.length; i++) {
if (s[i] > tolerance) {
rank++;
}
}
return rank;
} | #vulnerable code
public int getRank() {
final Array1D<Double> tmpSingularValues = this.getSingularValues();
int retVal = tmpSingularValues.size();
// Tolerance based on min-dim but should be max-dim
final double tmpTolerance = retVal * (tmpSingularValues.doubleValue(0) * PrimitiveMath.MACHINE_EPSILON);
for (int i = retVal - 1; i >= 0; i--) {
if (tmpSingularValues.doubleValue(i) <= tmpTolerance) {
retVal--;
} else {
return retVal;
}
}
return retVal;
}
#location 4
#vulnerability type NULL_DEREFERENCE | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
public MatrixStore<N> getInverse(final DecompositionStore<N> preallocated) {
if (myInverse == null) {
final MatrixStore<N> tmpQ1 = this.getQ1();
final Array1D<Double> tmpSingulars = this.getSingularValues();
final MatrixStore<N> tmpQ2 = this.getQ2();
final PhysicalStore<N> tmpMtrx = tmpQ2.copy();
final Scalar.Factory<N> tmpScalar = this.scalar();
final BinaryFunction<N> tmpDivide = this.function().divide();
final N tmpZero = tmpScalar.zero().getNumber();
final int rank = this.getRank();
for (int i = 0; i < rank; i++) {
tmpMtrx.modifyColumn(0L, i, tmpDivide.second(tmpScalar.cast(tmpSingulars.doubleValue(i))));
}
final long tmpCountColumns = tmpMtrx.countColumns();
for (int i = rank; i < tmpCountColumns; i++) {
tmpMtrx.fillColumn(0L, i, tmpZero);
}
preallocated.fillByMultiplying(tmpMtrx, tmpQ1.conjugate());
myInverse = preallocated;
}
return myInverse;
} | #vulnerable code
public MatrixStore<N> getInverse(final DecompositionStore<N> preallocated) {
if (myInverse == null) {
final MatrixStore<N> tmpQ1 = this.getQ1();
final Array1D<Double> tmpSingulars = this.getSingularValues();
final MatrixStore<N> tmpQ2 = this.getQ2();
final int tmpRowDim = (int) tmpSingulars.count();
final int tmpColDim = (int) tmpQ1.countRows();
final PhysicalStore<N> tmpMtrx = this.makeZero(tmpRowDim, tmpColDim);
double tmpValue;
final int rank = this.getRank();
for (int i = 0; i < rank; i++) {
tmpValue = tmpSingulars.doubleValue(i);
for (int j = 0; j < tmpColDim; j++) {
tmpMtrx.set(i, j, tmpQ1.toScalar(j, i).conjugate().divide(tmpValue).getNumber());
}
}
preallocated.fillByMultiplying(tmpQ2, tmpMtrx);
myInverse = preallocated;
}
return myInverse;
}
#location 9
#vulnerability type NULL_DEREFERENCE | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
public static MathProgSysModel make(final File file) {
final MathProgSysModel retVal = new MathProgSysModel();
String line;
FileSection section = null;
try (BufferedReader reader = new BufferedReader(new FileReader(file))) {
// Returns the content of a line MINUS the newline.
// Returns null only for the END of the stream.
// Returns an empty String if two newlines appear in a row.
while ((line = reader.readLine()) != null) {
// BasicLogger.debug("Line: {}", line);
if ((line.length() == 0) || line.startsWith(COMMENT) || line.startsWith(COMMENT_REF)) {
// Skip this line
} else if (line.startsWith(SPACE)) {
retVal.parseSectionLine(section, line);
} else {
section = retVal.identifySection(line);
}
}
} catch (IOException xcptn) {
xcptn.printStackTrace();
}
return retVal;
} | #vulnerable code
public static MathProgSysModel make(final File file) {
final MathProgSysModel retVal = new MathProgSysModel();
String tmpLine;
FileSection tmpSection = null;
try {
final BufferedReader tmpBufferedFileReader = new BufferedReader(new FileReader(file));
//readLine is a bit quirky :
//it returns the content of a line MINUS the newline.
//it returns null only for the END of the stream.
//it returns an empty String if two newlines appear in a row.
while ((tmpLine = tmpBufferedFileReader.readLine()) != null) {
// BasicLogger.debug("Line: {}", tmpLine);
if ((tmpLine.length() == 0) || tmpLine.startsWith(COMMENT) || tmpLine.startsWith(COMMENT_REF)) {
// Skip this line
} else if (tmpLine.startsWith(SPACE)) {
retVal.parseSectionLine(tmpSection, tmpLine);
} else {
tmpSection = retVal.identifySection(tmpLine);
}
}
tmpBufferedFileReader.close();
} catch (final FileNotFoundException anException) {
anException.printStackTrace();
} catch (final IOException anException) {
anException.printStackTrace();
}
return retVal;
}
#location 31
#vulnerability type RESOURCE_LEAK | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
public boolean isAnyExpressionQuadratic() {
boolean retVal = false;
for (Expression value : myExpressions.values()) {
retVal |= value.isAnyQuadraticFactorNonZero() && (value.isConstraint() || value.isObjective());
}
return retVal;
} | #vulnerable code
public boolean isAnyExpressionQuadratic() {
boolean retVal = false;
String tmpExpressionKey;
for (final Iterator<String> tmpIterator = myExpressions.keySet().iterator(); !retVal && tmpIterator.hasNext();) {
tmpExpressionKey = tmpIterator.next();
final Expression tmpExpression = myExpressions.get(tmpExpressionKey);
retVal |= tmpExpression.isAnyQuadraticFactorNonZero() && (tmpExpression.isConstraint() || tmpExpression.isObjective());
}
return retVal;
}
#location 9
#vulnerability type NULL_DEREFERENCE | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
public MatrixStore<N> getInverse() {
return this.getInverse(this.preallocate(new Structure2D() {
public long countRows() {
return myTransposed ? myBidiagonal.getColDim() : myBidiagonal.getRowDim();
}
public long countColumns() {
return myTransposed ? myBidiagonal.getRowDim() : myBidiagonal.getColDim();
}
}));
} | #vulnerable code
public MatrixStore<N> getInverse() {
if (myInverse == null) {
final MatrixStore<N> tmpQ1 = this.getQ1();
final MatrixStore<N> tmpD = this.getD();
final int tmpRowDim = (int) tmpD.countRows();
final int tmpColDim = (int) tmpQ1.countRows();
final PhysicalStore<N> tmpMtrx = this.makeZero(tmpRowDim, tmpColDim);
double tmpSingularValue;
final int rank = this.getRank();
for (int i = 0; i < rank; i++) {
tmpSingularValue = tmpD.doubleValue(i, i);
for (int j = 0; j < tmpColDim; j++) {
tmpMtrx.set(i, j, tmpQ1.toScalar(j, i).conjugate().divide(tmpSingularValue).getNumber());
}
}
myInverse = this.getQ2().multiply(tmpMtrx);
}
return myInverse;
}
#location 9
#vulnerability type NULL_DEREFERENCE | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
public void testXhtmlParsing() throws Exception {
String path = "/test-documents/testXHTML.html";
Metadata metadata = new Metadata();
String content = Tika.parseToString(
HtmlParserTest.class.getResourceAsStream(path), metadata);
assertEquals("application/xhtml+xml", metadata.get(Metadata.CONTENT_TYPE));
assertEquals("XHTML test document", metadata.get(Metadata.TITLE));
assertEquals("Tika Developers", metadata.get("Author"));
assertEquals("5", metadata.get("refresh"));
assertTrue(content.contains("ability of Apache Tika"));
assertTrue(content.contains("extract content"));
assertTrue(content.contains("an XHTML document"));
} | #vulnerable code
public void testXhtmlParsing() throws Exception {
Parser parser = new AutoDetectParser(); // Should auto-detect!
ContentHandler handler = new BodyContentHandler();
Metadata metadata = new Metadata();
InputStream stream = HtmlParserTest.class.getResourceAsStream(
"/test-documents/testXHTML.html");
try {
parser.parse(stream, handler, metadata);
} finally {
stream.close();
}
assertEquals("application/xhtml+xml", metadata.get(Metadata.CONTENT_TYPE));
assertEquals("XHTML test document", metadata.get(Metadata.TITLE));
String content = handler.toString();
assertEquals("Tika Developers", metadata.get("Author"));
assertEquals("5", metadata.get("refresh"));
assertTrue(content.contains("ability of Apache Tika"));
assertTrue(content.contains("extract content"));
assertTrue(content.contains("an XHTML document"));
}
#location 9
#vulnerability type NULL_DEREFERENCE | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
public void extract(InputStream input) throws Exception {
RereadableInputStream ris = new RereadableInputStream(input,
MEMORY_THRESHOLD);
try {
// First, extract properties
this.reader = new POIFSReader();
this.reader.registerListener(new PropertiesReaderListener(),
SummaryInformation.DEFAULT_STREAM_NAME);
if (input.available() > 0) {
reader.read(ris);
}
while (ris.read() != -1) {
}
ris.rewind();
// Extract document full text
this.text = extractText(ris);
} finally {
ris.close();
}
} | #vulnerable code
public void extract(InputStream input) throws Exception {
// First, extract properties
this.reader = new POIFSReader();
this.reader.registerListener(new PropertiesReaderListener(),
SummaryInformation.DEFAULT_STREAM_NAME);
RereadableInputStream ris = new RereadableInputStream(input,
MEMORY_THRESHOLD);
if (input.available() > 0) {
reader.read(ris);
}
while (ris.read() != -1) {
}
ris.rewind();
// Extract document full text
this.text = extractText(ris);
}
#location 17
#vulnerability type RESOURCE_LEAK | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
public static Parser getParser(File file, LiusConfig tc)
throws IOException, LiusException {
if(!file.canRead()) {
throw new IOException("Cannot read input file " + file.getAbsoluteFile());
}
String mimeType = MimeTypesUtils.getMimeType(file);
ParserConfig pc = tc.getParserConfig(mimeType);
if(pc==null) {
throw new LiusException(
"No ParserConfig available for mime-type '" + mimeType + "'"
+ " for file " + file.getName()
);
}
String className = pc.getParserClass();
Parser parser = null;
Class<?> parserClass = null;
if (className != null) {
try {
logger.debug(
"Loading parser class = " + className
+ " MimeType = " + mimeType
+ " for file " + file.getName()
);
parserClass = Class.forName(className);
parser = (Parser) parserClass.newInstance();
} catch (ClassNotFoundException e) {
logger.error(e.getMessage());
} catch (InstantiationException e) {
logger.error(e.getMessage());
} catch (IllegalAccessException e) {
logger.error(e.getMessage());
}
parser.setMimeType(mimeType);
parser.configure(tc);
parser.setInputStream(new FileInputStream(file));
}
return parser;
} | #vulnerable code
public static Parser getParser(File file, LiusConfig tc)
throws IOException, LiusException {
String mimeType = MimeTypesUtils.getMimeType(file);
ParserConfig pc = tc.getParserConfig(mimeType);
String className = pc.getParserClass();
Parser parser = null;
Class<?> parserClass = null;
if (className != null) {
try {
logger.info("Loading parser class = " + className
+ " MimeType = " + mimeType);
parserClass = Class.forName(className);
parser = (Parser) parserClass.newInstance();
} catch (ClassNotFoundException e) {
logger.error(e.getMessage());
} catch (InstantiationException e) {
logger.error(e.getMessage());
} catch (IllegalAccessException e) {
logger.error(e.getMessage());
}
parser.setMimeType(mimeType);
parser.configure(tc);
parser.setInputStream(new FileInputStream(file));
}
return parser;
}
#location 5
#vulnerability type NULL_DEREFERENCE | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
public void testClassParsing() throws Exception {
String path = "/test-documents/AutoDetectParser.class";
Metadata metadata = new Metadata();
String content = Tika.parseToString(
ClassParserTest.class.getResourceAsStream(path), metadata);
assertEquals("AutoDetectParser", metadata.get(Metadata.TITLE));
assertEquals(
"AutoDetectParser.class",
metadata.get(Metadata.RESOURCE_NAME_KEY));
assertTrue(content.contains("package org.apache.tika.parser;"));
assertTrue(content.contains(
"class AutoDetectParser extends CompositeParser"));
assertTrue(content.contains(
"private org.apache.tika.mime.MimeTypes types"));
assertTrue(content.contains(
"public void parse("
+ "java.io.InputStream, org.xml.sax.ContentHandler,"
+ " org.apache.tika.metadata.Metadata) throws"
+ " java.io.IOException, org.xml.sax.SAXException,"
+ " org.apache.tika.exception.TikaException;"));
assertTrue(content.contains(
"private byte[] getPrefix(java.io.InputStream, int)"
+ " throws java.io.IOException;"));
} | #vulnerable code
public void testClassParsing() throws Exception {
Parser parser = new AutoDetectParser(); // Should auto-detect!
ContentHandler handler = new BodyContentHandler();
Metadata metadata = new Metadata();
InputStream stream = ClassParserTest.class.getResourceAsStream(
"/test-documents/AutoDetectParser.class");
try {
parser.parse(stream, handler, metadata);
} finally {
stream.close();
}
assertEquals("AutoDetectParser", metadata.get(Metadata.TITLE));
assertEquals(
"AutoDetectParser.class",
metadata.get(Metadata.RESOURCE_NAME_KEY));
String content = handler.toString();
assertTrue(content.contains("package org.apache.tika.parser;"));
assertTrue(content.contains(
"class AutoDetectParser extends CompositeParser"));
assertTrue(content.contains(
"private org.apache.tika.mime.MimeTypes types"));
assertTrue(content.contains(
"public void parse("
+ "java.io.InputStream, org.xml.sax.ContentHandler,"
+ " org.apache.tika.metadata.Metadata) throws"
+ " java.io.IOException, org.xml.sax.SAXException,"
+ " org.apache.tika.exception.TikaException;"));
assertTrue(content.contains(
"private byte[] getPrefix(java.io.InputStream, int)"
+ " throws java.io.IOException;"));
}
#location 9
#vulnerability type NULL_DEREFERENCE | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
public void test() throws IOException {
InputStream is = createTestInputStream();
RereadableInputStream ris = new RereadableInputStream(is,
MEMORY_THRESHOLD);
try {
for (int pass = 0; pass < NUM_PASSES; pass++) {
for (int byteNum = 0; byteNum < TEST_SIZE; byteNum++) {
int byteRead = ris.read();
assertEquals("Pass = " + pass + ", byte num should be "
+ byteNum + " but is " + byteRead + ".", byteNum,
byteRead);
}
ris.rewind();
}
} finally {
// The RereadableInputStream should close the original input
// stream (if it hasn't already).
ris.close();
}
} | #vulnerable code
public void test() throws IOException {
File file = createTestFile();
InputStream is = new BufferedInputStream(new FileInputStream(file));
RereadableInputStream ris = new RereadableInputStream(is,
MEMORY_THRESHOLD);
try {
for (int pass = 0; pass < NUM_PASSES; pass++) {
for (int byteNum = 0; byteNum < TEST_SIZE; byteNum++) {
int byteRead = ris.read();
assertEquals("Pass = " + pass + ", byte num should be "
+ byteNum + " but is " + byteRead + ".", byteNum,
byteRead);
}
ris.rewind();
}
} finally {
is.close();
ris.close();
}
}
#location 15
#vulnerability type RESOURCE_LEAK | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
public void parse(
InputStream stream, ContentHandler handler, Metadata metadata)
throws IOException, SAXException, TikaException {
metadata.set(Metadata.CONTENT_TYPE, "text/plain");
// CharsetDetector expects a stream to support marks
if (!stream.markSupported()) {
stream = new BufferedInputStream(stream);
}
// Detect the content encoding (the stream is reset to the beginning)
// TODO: Better use of the possible encoding hint in input metadata
CharsetMatch match = new CharsetDetector().setText(stream).detect();
if (match != null) {
metadata.set(Metadata.CONTENT_ENCODING, match.getName());
// Is the encoding language-specific (KOI8-R, SJIS, etc.)?
String language = match.getLanguage();
if (language != null) {
metadata.set(Metadata.CONTENT_LANGUAGE, match.getLanguage());
metadata.set(Metadata.LANGUAGE, match.getLanguage());
}
}
String encoding = metadata.get(Metadata.CONTENT_ENCODING);
if (encoding == null) {
throw new TikaException(
"Text encoding could not be detected and no encoding"
+ " hint is available in document metadata");
}
try {
Reader reader =
new BufferedReader(new InputStreamReader(stream, encoding));
// TIKA-240: Drop the BOM when extracting plain text
reader.mark(1);
int bom = reader.read();
if (bom != '\ufeff') { // zero-width no-break space
reader.reset();
}
XHTMLContentHandler xhtml =
new XHTMLContentHandler(handler, metadata);
xhtml.startDocument();
xhtml.startElement("p");
char[] buffer = new char[4096];
int n = reader.read(buffer);
while (n != -1) {
xhtml.characters(buffer, 0, n);
n = reader.read(buffer);
}
xhtml.endElement("p");
xhtml.endDocument();
} catch (UnsupportedEncodingException e) {
throw new TikaException(
"Unsupported text encoding: " + encoding, e);
}
} | #vulnerable code
public void parse(
InputStream stream, ContentHandler handler, Metadata metadata)
throws IOException, SAXException, TikaException {
CharsetDetector detector = new CharsetDetector();
// Use the declared character encoding, if available
String encoding = metadata.get(Metadata.CONTENT_ENCODING);
if (encoding != null) {
detector.setDeclaredEncoding(encoding);
}
// CharsetDetector expects a stream to support marks
if (!stream.markSupported()) {
stream = new BufferedInputStream(stream);
}
detector.setText(stream);
CharsetMatch match = detector.detect();
if (match == null) {
throw new TikaException("Unable to detect character encoding");
}
Reader reader = new BufferedReader(match.getReader());
// TIKA-240: Drop the BOM when extracting plain text
reader.mark(1);
int bom = reader.read();
if (bom != '\ufeff') { // zero-width no-break space
reader.reset();
}
metadata.set(Metadata.CONTENT_TYPE, "text/plain");
metadata.set(Metadata.CONTENT_ENCODING, match.getName());
String language = match.getLanguage();
if (language != null) {
metadata.set(Metadata.CONTENT_LANGUAGE, match.getLanguage());
metadata.set(Metadata.LANGUAGE, match.getLanguage());
}
XHTMLContentHandler xhtml = new XHTMLContentHandler(handler, metadata);
xhtml.startDocument();
xhtml.startElement("p");
char[] buffer = new char[4096];
for (int n = reader.read(buffer); n != -1; n = reader.read(buffer)) {
xhtml.characters(buffer, 0, n);
}
xhtml.endElement("p");
xhtml.endDocument();
}
#location 47
#vulnerability type RESOURCE_LEAK | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
public void parse(
InputStream stream, ContentHandler handler, Metadata metadata)
throws IOException, SAXException, TikaException {
// Protect the stream from being closed by CyberNeko
stream = new CloseShieldInputStream(stream);
// Prepare the HTML content handler that generates proper
// XHTML events to records relevant document metadata
XHTMLContentHandler xhtml = new XHTMLContentHandler(handler, metadata);
XPathParser xpath = new XPathParser(null, "");
Matcher body = xpath.parse("/HTML/BODY//node()");
Matcher title = xpath.parse("/HTML/HEAD/TITLE//node()");
handler = new TeeContentHandler(
new MatchingContentHandler(getBodyHandler(xhtml), body),
new MatchingContentHandler(getTitleHandler(metadata), title));
// Parse the HTML document
xhtml.startDocument();
SAXParser parser = new SAXParser();
parser.setContentHandler(handler);
parser.parse(new InputSource(Utils.getUTF8Reader(stream, metadata)));
xhtml.endDocument();
} | #vulnerable code
public void parse(
InputStream stream, ContentHandler handler, Metadata metadata)
throws IOException, SAXException, TikaException {
SAXParser parser = new SAXParser();
parser.setContentHandler(
new TitleExtractingContentHandler(handler, metadata));
parser.parse(new InputSource(Utils.getUTF8Reader(
new CloseShieldInputStream(stream), metadata)));
}
#location 7
#vulnerability type RESOURCE_LEAK | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
private MagicMatch readMatch(Element element) throws MimeTypeException {
String offset = null;
String value = null;
String mask = null;
String type = null;
NamedNodeMap attrs = element.getAttributes();
for (int i = 0; i < attrs.getLength(); i++) {
Attr attr = (Attr) attrs.item(i);
if (attr.getName().equals(MATCH_OFFSET_ATTR)) {
offset = attr.getValue();
} else if (attr.getName().equals(MATCH_TYPE_ATTR)) {
type = attr.getValue();
} else if (attr.getName().equals(MATCH_VALUE_ATTR)) {
value = attr.getValue();
} else if (attr.getName().equals(MATCH_MASK_ATTR)) {
mask = attr.getValue();
}
}
// Parse OffSet
int offStart = 0;
int offEnd = 0;
if (offset != null) {
int colon = offset.indexOf(':');
if (colon == -1) {
offStart = Integer.parseInt(offset);
offEnd = offStart;
} else {
offStart = Integer.parseInt(offset.substring(0, colon));
offEnd = Integer.parseInt(offset.substring(colon + 1));
offEnd = Math.max(offStart, offEnd);
}
}
return new MagicMatch(offStart, offEnd, type, mask, value);
} | #vulnerable code
private MagicMatch readMatch(Element element) throws MimeTypeException {
String offset = null;
String value = null;
String mask = null;
String type = null;
NamedNodeMap attrs = element.getAttributes();
for (int i = 0; i < attrs.getLength(); i++) {
Attr attr = (Attr) attrs.item(i);
if (attr.getName().equals(MATCH_OFFSET_ATTR)) {
offset = attr.getValue();
} else if (attr.getName().equals(MATCH_TYPE_ATTR)) {
type = attr.getValue();
} else if (attr.getName().equals(MATCH_VALUE_ATTR)) {
value = attr.getValue();
} else if (attr.getName().equals(MATCH_MASK_ATTR)) {
mask = attr.getValue();
}
}
// Parse OffSet
String[] offsets = offset.split(":");
int offStart = 0;
int offEnd = 0;
try {
offStart = Integer.parseInt(offsets[0]);
} catch (Exception e) {
// WARN log + avoid loading
}
try {
offEnd = Integer.parseInt(offsets[1]);
} catch (Exception e) {
// WARN log
}
offEnd = Math.max(offStart, offEnd);
return new MagicMatch(offStart, offEnd, type, mask, value);
}
#location 22
#vulnerability type NULL_DEREFERENCE | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
public void parse(
InputStream stream, ContentHandler handler, Metadata metadata)
throws IOException, SAXException, TikaException {
ZipInputStream zip = new ZipInputStream(stream);
ZipEntry entry = zip.getNextEntry();
while (entry != null) {
if (entry.getName().equals("mimetype")) {
String type = IOUtils.toString(zip, "UTF-8");
metadata.set(Metadata.CONTENT_TYPE, type);
} else if (entry.getName().equals("meta.xml")) {
meta.parse(zip, new DefaultHandler(), metadata);
} else if (entry.getName().equals("content.xml")) {
content.parse(zip, handler, metadata);
}
entry = zip.getNextEntry();
}
} | #vulnerable code
public void parse(
InputStream stream, ContentHandler handler, Metadata metadata)
throws IOException, SAXException, TikaException {
ZipInputStream zip = new ZipInputStream(stream);
ZipEntry entry = zip.getNextEntry();
while (entry != null) {
if (entry.getName().equals("mimetype")) {
StringBuilder buffer = new StringBuilder();
Reader reader = new InputStreamReader(zip, "UTF-8");
for (int ch = reader.read(); ch != -1; ch = reader.read()) {
buffer.append((char) ch);
}
metadata.set(Metadata.CONTENT_TYPE, buffer.toString());
} else if (entry.getName().equals("meta.xml")) {
meta.parse(zip, new DefaultHandler(), metadata);
} else if (entry.getName().equals("content.xml")) {
content.parse(zip, handler, metadata);
}
entry = zip.getNextEntry();
}
}
#location 13
#vulnerability type RESOURCE_LEAK | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
public void parse(
InputStream stream, ContentHandler handler, Metadata metadata)
throws IOException, SAXException, TikaException {
// We need buffering to enable MIME magic detection before parsing
if (!stream.markSupported()) {
stream = new BufferedInputStream(stream);
}
// Automatically detect the MIME type of the document
MediaType type = types.detect(stream, metadata);
metadata.set(Metadata.CONTENT_TYPE, type.toString());
// TIKA-216: Zip bomb prevention
CountingInputStream count = new CountingInputStream(stream);
SecureContentHandler secure = new SecureContentHandler(handler, count);
// Parse the document
try {
super.parse(count, secure, metadata);
} catch (SAXException e) {
// Convert zip bomb exceptions to TikaExceptions
secure.throwIfCauseOf(e);
throw e;
}
} | #vulnerable code
public void parse(
InputStream stream, ContentHandler handler, Metadata metadata)
throws IOException, SAXException, TikaException {
// We need buffering to enable MIME magic detection before parsing
if (!stream.markSupported()) {
stream = new BufferedInputStream(stream);
}
// Automatically detect the MIME type of the document
MediaType type = types.detect(stream, metadata);
metadata.set(Metadata.CONTENT_TYPE, type.toString());
// TIKA-216: Zip bomb prevention
CountingInputStream count = new CountingInputStream(stream);
SecureContentHandler secure = new SecureContentHandler(handler, count);
// Parse the document
super.parse(count, secure, metadata);
}
#location 18
#vulnerability type RESOURCE_LEAK | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
protected String parse(InputStream stream, Iterable<Content> contents)
throws IOException, TikaException {
StringBuilder sb = new StringBuilder();
BufferedReader br = new BufferedReader(new InputStreamReader(stream));
int charAsInt;
while ((charAsInt = br.read()) != -1) {
sb.append((char) charAsInt);
}
return sb.toString();
} | #vulnerable code
protected String parse(InputStream stream, Iterable<Content> contents)
throws IOException, TikaException {
StringBuffer sb = new StringBuffer();
BufferedReader br = new BufferedReader(new InputStreamReader(stream));
String line = null;
while ((line = br.readLine()) != null) {
sb.append(line);
sb.append(" ");
}
return sb.toString();
}
#location 10
#vulnerability type RESOURCE_LEAK | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
private static Field findSingleFieldUsingStrategy(FieldMatcherStrategy strategy, Object object,
boolean checkHierarchy, Class<?> startClass) {
assertObjectInGetInternalStateIsNotNull(object);
Field foundField = null;
final Class<?> originalStartClass = startClass;
while (startClass != null) {
final Field[] declaredFields = startClass.getDeclaredFields();
for (Field field : declaredFields) {
if (strategy.matches(field) && hasFieldProperModifier(object, field)) {
if (foundField != null) {
throw new TooManyFieldsFoundException("Two or more fields matching " + strategy + ".");
}
foundField = field;
}
}
if (foundField != null) {
break;
} else if (!checkHierarchy) {
break;
}
startClass = startClass.getSuperclass();
}
if (foundField == null) {
strategy.notFound(originalStartClass, !isClass(object));
return null;
}
foundField.setAccessible(true);
return foundField;
} | #vulnerable code
private static Field findSingleFieldUsingStrategy(FieldMatcherStrategy strategy, Object object,
boolean checkHierarchy, Class<?> startClass) {
assertObjectInGetInternalStateIsNotNull(object);
Field foundField = null;
final Class<?> originalStartClass = startClass;
while (startClass != null) {
final Field[] declaredFields = startClass.getDeclaredFields();
for (Field field : declaredFields) {
if (strategy.matches(field) && hasFieldProperModifier(object, field)) {
if (foundField != null) {
throw new TooManyFieldsFoundException("Two or more fields matching " + strategy + ".");
}
foundField = field;
}
}
if (foundField != null) {
break;
} else if (checkHierarchy == false) {
break;
}
startClass = startClass.getSuperclass();
}
if (foundField == null) {
strategy.notFound(originalStartClass, !isClass(object));
}
foundField.setAccessible(true);
return foundField;
}
#location 26
#vulnerability type NULL_DEREFERENCE | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
public boolean getBooleanSetting(String key) {
Boolean result = null;
if (this.getSettings().containsKey(key)) {
Object foo = this.getSettings().get(key);
if (foo instanceof String) {
result = Boolean.valueOf((String)foo);
} else if (foo instanceof Boolean) {
result = (Boolean)foo;
}
}
return result != null ? result : false;
} | #vulnerable code
public boolean getBooleanSetting(String key) {
Boolean result = null;
if (this.getSettings().containsKey(key)) {
Object foo = this.getSettings().get(key);
if (foo instanceof String) {
result = Boolean.valueOf((String)foo);
} else if (foo instanceof Boolean) {
result = (Boolean)foo;
}
}
return result;
}
#location 11
#vulnerability type NULL_DEREFERENCE | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
private String handleTypeName(String typeName) {
if (getTypeNames() == null && getTypeNames().size() == 0) {
return null;
}
String[] tokens = typeName.split(",");
boolean foundIt = false;
for (String token : tokens) {
String[] keys = token.split("=");
for (String key : keys) {
// we want the next item in the array.
if (foundIt) {
return key;
}
if (getTypeNames().contains(key)) {
foundIt = true;
}
}
}
return null;
} | #vulnerable code
private String handleTypeName(String typeName) {
String[] tokens = typeName.split(",");
boolean foundIt = false;
for (String token : tokens) {
String[] keys = token.split("=");
for (String key : keys) {
// we want the next item in the array.
if (foundIt) {
return key;
}
if (getTypeNames().contains(key)) {
foundIt = true;
}
}
}
return null;
}
#location 11
#vulnerability type NULL_DEREFERENCE | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
public void doWrite(Query query) throws Exception {
List<String> typeNames = this.getTypeNames();
DatagramSocket socket = (DatagramSocket) pool.borrowObject(this.address);
try {
for (Result result : query.getResults()) {
if (isDebugEnabled()) {
log.debug(result.toString());
}
Map<String, Object> resultValues = result.getValues();
if (resultValues != null) {
for (Entry<String, Object> values : resultValues.entrySet()) {
if (JmxUtils.isNumeric(values.getValue())) {
StringBuilder sb = new StringBuilder();
sb.append(JmxUtils.getKeyString(query, result, values, typeNames, rootPrefix));
sb.append(":");
sb.append(values.getValue().toString());
sb.append("|");
sb.append(bucketType);
sb.append("\n");
String line = sb.toString();
byte[] sendData = line.getBytes();
if (isDebugEnabled()) {
log.debug("StatsD Message: " + line.trim());
}
DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length);
socket.send(sendPacket);
}
}
}
}
} finally {
pool.returnObject(address, socket);
}
} | #vulnerable code
public void doWrite(Query query) throws Exception {
List<String> typeNames = this.getTypeNames();
DatagramSocket socket = new DatagramSocket();
try {
for (Result result : query.getResults()) {
if (isDebugEnabled()) {
log.debug(result.toString());
}
Map<String, Object> resultValues = result.getValues();
if (resultValues != null) {
for (Entry<String, Object> values : resultValues.entrySet()) {
if (JmxUtils.isNumeric(values.getValue())) {
StringBuilder sb = new StringBuilder();
sb.append(JmxUtils.getKeyString(query, result, values, typeNames, rootPrefix));
sb.append(":");
sb.append(values.getValue().toString());
sb.append("|");
sb.append("c\n");
String line = sb.toString();
byte[] sendData = sb.toString().trim().getBytes();
if (isDebugEnabled()) {
log.debug("StatsD Message: " + line.trim());
}
DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, ipAddress, port);
socket.send(sendPacket);
}
}
}
}
} finally {
if (socket != null && ! socket.isClosed()) {
socket.close();
}
}
}
#location 39
#vulnerability type RESOURCE_LEAK | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Override
protected void finishOutput() throws IOException {
} | #vulnerable code
@Override
protected void finishOutput() throws IOException {
try {
this.out.flush();
} catch (IOException e) {
log.error("flush failed");
throw e;
}
// Read and log the response from the server for diagnostic purposes.
InputStreamReader socketInputStream = new InputStreamReader(socket.getInputStream());
BufferedReader bufferedSocketInputStream = new BufferedReader(socketInputStream);
String line;
while (socketInputStream.ready() && (line = bufferedSocketInputStream.readLine()) != null) {
log.warn("OpenTSDB says: " + line);
}
}
#location 8
#vulnerability type RESOURCE_LEAK | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
public static void processQuery(MBeanServerConnection mbeanServer, Query query) throws Exception {
List<Result> resList = new ArrayList<Result>();
ObjectName oName = new ObjectName(query.getObj());
Set<ObjectName> queryNames = mbeanServer.queryNames(oName, null);
for (ObjectName queryName : queryNames) {
MBeanInfo info = mbeanServer.getMBeanInfo(queryName);
ObjectInstance oi = mbeanServer.getObjectInstance(queryName);
List<String> queryAttributes = query.getAttr();
if (queryAttributes == null || queryAttributes.size() == 0) {
MBeanAttributeInfo[] attrs = info.getAttributes();
for (MBeanAttributeInfo attrInfo : attrs) {
query.addAttr(attrInfo.getName());
}
}
try {
if (query.getAttr() != null && query.getAttr().size() > 0) {
log.debug("Started query: " + query);
AttributeList al = mbeanServer.getAttributes(queryName, query.getAttr().toArray(new String[query.getAttr().size()]));
for (Attribute attribute : al.asList()) {
getResult(resList, info, oi, (Attribute)attribute, query);
}
if (log.isDebugEnabled()) {
log.debug("Finished query.");
}
query.setResults(resList);
// Now run the filters.
runFiltersForQuery(query);
if (log.isDebugEnabled()) {
log.debug("Finished running filters: " + query);
}
}
} catch (UnmarshalException ue) {
if (ue.getCause() != null && ue.getCause() instanceof ClassNotFoundException) {
log.debug("Bad unmarshall, continuing. This is probably ok and due to something like this: " +
"http://ehcache.org/xref/net/sf/ehcache/distribution/RMICacheManagerPeerListener.html#52", ue.getMessage());
}
}
}
} | #vulnerable code
public static void processQuery(MBeanServerConnection mbeanServer, Query query) throws Exception {
List<Result> resList = new ArrayList<Result>();
ObjectName oName = new ObjectName(query.getObj());
Set<ObjectName> queryNames = mbeanServer.queryNames(oName, null);
for (ObjectName queryName : queryNames) {
MBeanInfo info = mbeanServer.getMBeanInfo(queryName);
ObjectInstance oi = mbeanServer.getObjectInstance(queryName);
List<String> queryAttributes = query.getAttr();
if (queryAttributes == null || queryAttributes.size() == 0) {
MBeanAttributeInfo[] attrs = info.getAttributes();
for (MBeanAttributeInfo attrInfo : attrs) {
query.addAttr(attrInfo.getName());
}
}
AttributeList al = mbeanServer.getAttributes(queryName, query.getAttr().toArray(new String[query.getAttr().size()]));
for (Attribute attribute : al.asList()) {
getResult(resList, info, oi, (Attribute)attribute, query);
}
}
if (log.isDebugEnabled()) {
log.debug("Executed query: " + query);
}
query.setResults(resList);
// Now run the filters.
runFiltersForQuery(query);
if (log.isDebugEnabled()) {
log.debug("Finished running filters: " + query);
}
}
#location 19
#vulnerability type NULL_DEREFERENCE | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Override
public NodeSet eval(final XPContext ctx) {
final IndexIterator it = ctx.local.data.ids(index);
final IntList il = new IntList();
while(it.more()) {
ctx.checkStop();
il.add(it.next());
}
ctx.local = new NodeSet(il.finish(), ctx);
return ctx.local;
} | #vulnerable code
@Override
public NodeSet eval(final XPContext ctx) {
ctx.local = new NodeSet(ctx.local.data.ids(index)[0], ctx);
return ctx.local;
}
#location 3
#vulnerability type NULL_DEREFERENCE | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
private IndexIterator getFuzzy(final byte[] tok, final int e) {
int[][] ft = null;
byte[] to;
int i = 0;
final int is = li.readBytes(0, 1L)[0];
int ts = li.readBytes(1L, 2L)[0];
int dif = Math.abs(tok.length - ts);
while (i < is && dif > e) {
i++;
ts = li.readBytes(1L + i * 5L, 1L + i * 5L + 1L)[0];
dif = Math.abs(tok.length - ts);
}
if (i == is) return null;
int p;
int pe;
while (i < is && dif <= e) {
p = li.readInt(1L + i * 5L + 1L);
pe = li.readInt(1L + (i + 1) * 5L + 1L);
while(p < pe) {
to = ti.readBytes(p, p + ts);
if (calcEQ(to, 0, tok, e)) {
//System.out.println(new String(to));
// read data
ft = FTUnion.calculateFTOr(ft,
finish(getData(getPointerOnData(p, ts), getDataSize(p, ts))));
}
p += ts + 4L + 5L;
}
i++;
ts = li.readBytes(1L + i * 5L, 1L + i * 5L + 1L)[0];
dif = Math.abs(tok.length - ts);
}
return new IndexArrayIterator(ft);
} | #vulnerable code
private IndexIterator getFuzzy(final byte[] tok, final int e) {
int[][] ft = null;
byte[] to;
int dif;
int i = 0;
final int is = li.readBytes(0, 1L)[0];
int ts = li.readBytes(1L, 2L)[0];
dif = (tok.length - ts < 0) ?
ts - tok.length : tok.length - ts;
while (i < is && dif > e) {
i++;
ts = li.readBytes(1L + i * 5L, 1L + i * 5L + 1L)[0];
dif = (tok.length - ts < 0) ?
ts - tok.length : tok.length - ts;
}
if (i == is) return null;
int p;
int pe;
while (i < is && dif <= e) {
p = li.readInt(1L + i * 5L + 1L);
pe = li.readInt(1L + (i + 1) * 5L + 1L);
while(p < pe) {
to = ti.readBytes(p, p + ts);
if (calcEQ(to, 0, tok, e)) {
//System.out.println(new String(to));
// read data
ft = FTUnion.calculateFTOr(ft,
finish(getData(getPointerOnData(p, ts), getDataSize(p, ts))));
}
p += ts + 4L + 5L;
}
i++;
ts = li.readBytes(1L + i * 5L, 1L + i * 5L + 1L)[0];
dif = (tok.length - ts < 0) ?
ts - tok.length : tok.length - ts;
}
return new IndexArrayIterator(ft[0], ft[1]);
}
#location 43
#vulnerability type NULL_DEREFERENCE | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
public void actionPerformed(final ActionEvent e) {
if(e == null) {
if(GUIProp.execrt) query(false);
return;
}
final Object source = e.getSource();
int cp = 0;
final int cs = panel.getComponentCount();
for(int c = 0; c < cs; c++) if(panel.getComponent(c) == source) cp = c;
if((cp & 1) == 0) {
// ComboBox with tags/attributes
final BaseXCombo combo = (BaseXCombo) source;
panel.remove(cp + 1);
if(combo.getSelectedIndex() != 0) {
final String item = combo.getSelectedItem().toString();
final StatsKey key = GUI.context.data().stats.get(Token.token(item));
switch(key.kind) {
case INT:
addSlider(key.min, key.max, cp + 1, item.equals("@size"),
item.equals("@mtime"), true);
break;
case DBL:
addSlider(key.min, key.max, cp + 1, false, false, false);
break;
case CAT:
addCombo(keys(key.cats), cp + 1);
break;
case TEXT:
addInput(cp + 1);
break;
case NONE:
final BaseXLabel label = new BaseXLabel("");
label.setBorder(new EmptyBorder(3, 0, 0, 0));
panel.add(label, cp + 1);
break;
}
if(cp + 2 == cs) addKeys(cp + 2);
panel.validate();
panel.repaint();
} else {
panel.add(new BaseXLabel(""), cp + 1);
if(cp + 4 == cs && ((BaseXCombo) panel.getComponent(cp + 2)).
getSelectedIndex() == 0) {
panel.remove(cp + 2);
panel.remove(cp + 2);
panel.validate();
panel.repaint();
}
}
}
if(GUIProp.execrt) query(false);
} | #vulnerable code
public void actionPerformed(final ActionEvent e) {
if(e == null) {
if(GUIProp.execrt) query(false);
return;
}
final Object source = e.getSource();
int cp = 0;
final int cs = panel.getComponentCount();
for(int c = 0; c < cs; c++) if(panel.getComponent(c) == source) cp = c;
if((cp & 1) == 0) {
// ComboBox with tags/attributes
final BaseXCombo combo = (BaseXCombo) source;
panel.remove(cp + 1);
if(combo.getSelectedIndex() != 0) {
final String item = combo.getSelectedItem().toString();
final StatsKey key = GUI.context.data().stats.get(Token.token(item));
switch(key.kind) {
case INT:
addSlider(key.min, key.max, cp + 1, item.equals("@size"),
item.equals("@mtime"), true);
break;
case DBL:
addSlider(key.min, key.max, cp + 1, false, false, false);
break;
case CAT:
addCombo(keys(key.cats), cp + 1);
break;
case TEXT:
addInput(cp + 1);
break;
case NONE:
//final BaseXLabel label = new BaseXLabel("(no texts available)");
final BaseXLabel label = new BaseXLabel("");
label.setBorder(new EmptyBorder(3, 0, 0, 0));
panel.add(label, cp + 1);
break;
}
if(cp + 2 == cs) addKeys(cp + 2);
panel.validate();
panel.repaint();
} else {
panel.add(new BaseXLabel(""), cp + 1);
if(cp + 4 == cs && ((BaseXCombo) panel.getComponent(cp + 2)).
getSelectedIndex() == 0) {
panel.remove(cp + 2);
panel.remove(cp + 2);
panel.validate();
panel.repaint();
}
}
}
if(GUIProp.execrt) query(false);
}
#location 21
#vulnerability type NULL_DEREFERENCE | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Override
public NodeSet eval(final XPContext ctx) {
final IndexIterator it = ctx.local.data.ids(index);
final IntList il = new IntList();
while(it.more()) {
ctx.checkStop();
il.add(it.next());
}
return ctx.local;
} | #vulnerable code
@Override
public NodeSet eval(final XPContext ctx) {
ctx.local = new NodeSet(ctx.local.data.ids(index)[0], ctx);
return ctx.local;
}
#location 3
#vulnerability type NULL_DEREFERENCE | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
private IndexIterator getFuzzy(final byte[] tok, final int e) {
IndexArrayIterator it = new IndexArrayIterator(0);
byte[] to;
int i = 0;
final int is = li.readBytes(0, 1L)[0];
int ts = li.readBytes(1L, 2L)[0];
int dif = Math.abs(tok.length - ts);
while (i < is && dif > e) {
i++;
ts = li.readBytes(1L + i * 5L, 1L + i * 5L + 1L)[0];
dif = Math.abs(tok.length - ts);
}
if (i == is) return null;
int p;
int pe;
while (i < is && dif <= e) {
p = li.readInt(1L + i * 5L + 1L);
pe = li.readInt(1L + (i + 1) * 5L + 1L);
while(p < pe) {
to = ti.readBytes(p, p + ts);
if (calcEQ(to, 0, tok, e)) {
// read data
it = IndexArrayIterator.merge(getData(getPointerOnData(p, ts),
getDataSize(p, ts)), it);
}
p += ts + 4L + 5L;
}
i++;
ts = li.readBytes(1L + i * 5L, 1L + i * 5L + 1L)[0];
dif = Math.abs(tok.length - ts);
}
return it;
} | #vulnerable code
private IndexIterator getFuzzy(final byte[] tok, final int e) {
int[][] ft = null;
byte[] to;
int i = 0;
final int is = li.readBytes(0, 1L)[0];
int ts = li.readBytes(1L, 2L)[0];
int dif = Math.abs(tok.length - ts);
while (i < is && dif > e) {
i++;
ts = li.readBytes(1L + i * 5L, 1L + i * 5L + 1L)[0];
dif = Math.abs(tok.length - ts);
}
if (i == is) return null;
int p;
int pe;
while (i < is && dif <= e) {
p = li.readInt(1L + i * 5L + 1L);
pe = li.readInt(1L + (i + 1) * 5L + 1L);
while(p < pe) {
to = ti.readBytes(p, p + ts);
if (calcEQ(to, 0, tok, e)) {
// read data
ft = FTTrie.calculateFTOr(ft,
finish(getData(getPointerOnData(p, ts), getDataSize(p, ts))));
}
p += ts + 4L + 5L;
}
i++;
ts = li.readBytes(1L + i * 5L, 1L + i * 5L + 1L)[0];
dif = Math.abs(tok.length - ts);
}
return new IndexArrayIterator(ft, true);
}
#location 36
#vulnerability type NULL_DEREFERENCE | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Override
public IndexIterator ids(final IndexToken ind) {
if(ind.range()) return idRange((RangeToken) ind);
final FTTokenizer ft = (FTTokenizer) ind;
final byte[] tok = ft.get();
if(ft.fz) {
int k = Prop.lserr;
if(k == 0) k = Math.max(1, tok.length >> 2);
final int[][] ids = getNodeFuzzy(0, null, -1, tok, 0, 0, 0, k);
return new IndexArrayIterator(ids);
}
if(ft.wc) {
final int pw = Token.indexOf(tok, '.');
if(pw != -1) {
final int[][] ids = getNodeFromTrieWithWildCard(tok, pw);
return new IndexArrayIterator(ids);
}
}
if(!cs && ft.cs) {
// case insensitive index create - check real case with dbdata
int[][] ids = getNodeFromTrieRecursive(0, Token.lc(tok), false);
if(ids == null) {
return null;
}
byte[] tokenFromDB;
byte[] textFromDB;
int[][] rIds = new int[2][ids[0].length];
int count = 0;
int readId;
int i = 0;
// check real case of each result node
while(i < ids[0].length) {
// get date from disk
readId = ids[0][i];
textFromDB = data.text(ids[0][i]);
tokenFromDB = new byte[tok.length];
System.arraycopy(textFromDB, ids[1][i], tokenFromDB, 0, tok.length);
// check unique node ones
while(i < ids[0].length && readId == ids[0][i]) {
System.arraycopy(textFromDB, ids[1][i], tokenFromDB, 0, tok.length);
readId = ids[0][i];
// check unique node ones
// compare token from db with token from query
if(Token.eq(tokenFromDB, tok)) {
rIds[0][count] = ids[0][i];
rIds[1][count++] = ids[1][i];
// jump over same ids
while(i < ids[0].length && readId == ids[0][i])
i++;
break;
}
i++;
}
}
return new IndexArrayIterator(rIds, count);
}
final int[][] tmp = getNodeFromTrieRecursive(0, tok, ft.cs);
return new IndexArrayIterator(tmp);
} | #vulnerable code
@Override
public IndexIterator ids(final IndexToken ind) {
if(ind.range()) return idRange((RangeToken) ind);
final FTTokenizer ft = (FTTokenizer) ind;
final byte[] tok = ft.get();
if(ft.fz) {
int k = Prop.lserr;
if(k == 0) k = Math.max(1, tok.length >> 2);
final int[][] ids = getNodeFuzzy(0, null, -1, tok, 0, 0, 0, k);
return new IndexArrayIterator(ids[0], ids[1]);
}
if(ft.wc) {
final int pw = Token.indexOf(tok, '.');
if(pw != -1) {
final int[][] ids = getNodeFromTrieWithWildCard(tok, pw);
return new IndexArrayIterator(ids[0], ids[1]);
}
}
if(!cs && ft.cs) {
// case insensitive index create - check real case with dbdata
int[][] ids = getNodeFromTrieRecursive(0, Token.lc(tok), false);
if(ids == null) {
return null;
}
byte[] tokenFromDB;
byte[] textFromDB;
int[][] rIds = new int[2][ids[0].length];
int count = 0;
int readId;
int i = 0;
// check real case of each result node
while(i < ids[0].length) {
// get date from disk
readId = ids[0][i];
textFromDB = data.text(ids[0][i]);
tokenFromDB = new byte[tok.length];
System.arraycopy(textFromDB, ids[1][i], tokenFromDB, 0, tok.length);
// check unique node ones
while(i < ids[0].length && readId == ids[0][i]) {
System.arraycopy(textFromDB, ids[1][i], tokenFromDB, 0, tok.length);
readId = ids[0][i];
// check unique node ones
// compare token from db with token from query
if(Token.eq(tokenFromDB, tok)) {
rIds[0][count] = ids[0][i];
rIds[1][count++] = ids[1][i];
// jump over same ids
while(i < ids[0].length && readId == ids[0][i])
i++;
break;
}
i++;
}
}
if(count == 0) return null;
final int[][] tmp = new int[2][count];
System.arraycopy(rIds[0], 0, tmp[0], 0, count);
System.arraycopy(rIds[1], 0, tmp[1], 0, count);
return new IndexArrayIterator(tmp[0], tmp[1]);
}
final int[][] tmp = getNodeFromTrieRecursive(0, tok, ft.cs);
return new IndexArrayIterator(tmp[0], tmp[1]);
}
#location 71
#vulnerability type NULL_DEREFERENCE | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
private void drawTemperature(final Graphics g, final int level) {
// array with all rects of a level
// System.out.print("RectCount: " + rectCount + " level "
// + level + " size :"
// + parentList.size);
final RealRect[] tRect = new RealRect[rectCount];
final Data data = GUI.context.data();
final int size = parentList.size;
final HashMap<Integer, Double> temp = new HashMap<Integer, Double>();
double x = 0;
final int y = 1 * level * fontHeight * 2;
final double width = this.getSize().width - 1;
final double ratio = width / size;
final int minSpace = 35; // minimum Space for Tags
final boolean space = ratio > minSpace ? true : false;
int r = 0;
for(int i = 0; i < size; i++) {
final int pre = parentList.list[i];
if(pre == -1) {
x += ratio;
continue;
}
int nodeKind = data.kind(pre);
final int nodeSize = data.size(pre, nodeKind);
final double nodePercent = nodeSize / (double) sumNodeSizeInLine;
g.setColor(Color.black);
final int l = (int) ratio; //rectangle length
final int h = fontHeight; //rectangle height
g.drawRect((int) x, y, l, h);
tRect[r++] = new RealRect(pre, (int) x, y, (int) x + l, y + h);
int c = (int) Math.rint(255 * nodePercent * 40);
c = c > 255 ? 255 : c;
g.setColor(new Color(c, 0, 255 - c));
g.fillRect((int) x + 1, y + 1, l - 1, h - 1);
final double boxMiddle = x + ratio / 2f;
if(space) {
String s = "";
switch(nodeKind) {
case Data.ELEM:
s = Token.string(data.tag(pre));
g.setColor(Color.WHITE);
break;
case Data.COMM:
s = Token.string(data.text(pre));
g.setColor(Color.GREEN);
break;
case Data.PI:
s = Token.string(data.text(pre));
g.setColor(Color.PINK);
break;
case Data.DOC:
s = Token.string(data.text(pre));
g.setColor(Color.BLUE);
break;
default:
s = Token.string(data.text(pre));
g.setColor(Color.YELLOW);
}
Token.string(data.text(pre));
int textWidth = 0;
while((textWidth = BaseXLayout.width(g, s)) + 4 > ratio) {
s = s.substring(0, s.length() / 2).concat("?");
}
g.drawString(s, (int) boxMiddle - textWidth / 2, y + fontHeight - 2);
}
if(parentPos != null) {
final double parentMiddle = parentPos.get(data.parent(pre, nodeKind));
g.setColor(new Color(c, 0, 255 - c, 100));
g.drawLine((int) boxMiddle, y - 1, (int) parentMiddle, y - fontHeight
+ 1);
// final int line = Math.round(fontHeight / 4f);
// g.drawLine((int) boxMiddle, y, (int) boxMiddle, y - line);
// g.drawLine((int) boxMiddle, y - line,
// (int) parentMiddle, y - line);
// g.drawLine((int) parentMiddle, y - line, (int) parentMiddle, y
// - fontHeight);
}
if(nodeSize > 0) temp.put(pre, boxMiddle);
x += ratio;
}
rects.add(tRect);
parentPos = temp;
} | #vulnerable code
private void drawTemperature(final Graphics g, final int level) {
// array with all rects of a level
// System.out.print("RectCount: " + rectCount + " level "
// + level + " size :"
// + parentList.size);
final RealRect[] tRect = new RealRect[rectCount];
final Data data = GUI.context.data();
final int size = parentList.size;
final HashMap<Integer, Double> temp = new HashMap<Integer, Double>();
double x = 0;
final int y = 1 * level * fontHeight * 2;
final double width = this.getSize().width - 1;
final double ratio = width / size;
final int minSpace = 35; // minimum Space for Tags
final boolean space = ratio > minSpace ? true : false;
int r = 0;
for(int i = 0; i < size; i++) {
final int pre = parentList.list[i];
if(pre == -1) {
x += ratio;
continue;
}
final int nodeSize = data.size(pre, Data.ELEM);
final double nodePercent = nodeSize / (double) sumNodeSizeInLine;
g.setColor(Color.black);
final int l = (int) ratio; //rectangle length
final int h = fontHeight; //rectangle height
g.drawRect((int) x, y, l, h);
tRect[r++] = new RealRect(pre, (int) x, y, (int) x + l, y + h);
int c = (int) Math.rint(255 * nodePercent * 40);
c = c > 255 ? 255 : c;
g.setColor(new Color(c, 0, 255 - c));
g.fillRect((int) x + 1, y + 1, l - 1, h - 1);
final double boxMiddle = x + ratio / 2f;
g.setColor(Color.WHITE);
if(space) {
String s = Token.string(data.tag(pre));
int textWidth = 0;
while((textWidth = BaseXLayout.width(g, s)) + 4 > ratio) {
s = s.substring(0, s.length() / 2).concat("?");
}
g.drawString(s, (int) boxMiddle - textWidth / 2, y + fontHeight - 2);
}
if(parentPos != null) {
final double parentMiddle = parentPos.get(data.parent(pre, Data.ELEM));
g.setColor(new Color(c, 0, 255 - c, 100));
g.drawLine((int) boxMiddle, y - 1, (int) parentMiddle, y - fontHeight
+ 1);
// final int line = Math.round(fontHeight / 4f);
// g.drawLine((int) boxMiddle, y, (int) boxMiddle, y - line);
// g.drawLine((int) boxMiddle, y - line,
// (int) parentMiddle, y - line);
// g.drawLine((int) parentMiddle, y - line, (int) parentMiddle, y
// - fontHeight);
}
if(nodeSize > 0) temp.put(pre, boxMiddle);
x += ratio;
}
rects.add(tRect);
parentPos = temp;
}
#location 60
#vulnerability type NULL_DEREFERENCE | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
public void locateMain(final String cmd)
throws IOException {
GetOpts g = new GetOpts(cmd, "chl:V:", 1);
char version = (char) -1;
int limit = -1;
// get all Options
int ch = g.getopt();
while (ch != -1) {
switch (ch) {
case 'c':
//Suppress normal output; instead print a
//count of matching file names.
cFlag = true;
break;
case 'h':
printHelp();
fAccomplished = true;
break;
case 'l':
// Limit output to number of file names and exit.
limit = Integer.parseInt(g.getOptarg());
lFlag = true;
break;
case 'V':
version = g.getOptarg().charAt(0);
break;
case ':':
fError = true;
out.print("ls: missing argument");
break;
case '?':
fError = true;
out.print("ls: illegal option");
break;
}
if(fError || fAccomplished) {
// more options ?
return;
}
ch = g.getopt();
}
fileToFind = g.getPath();
if(fileToFind == null) {
out.print("usage: locate [-l limit] [-c] [-h] -V 1 ...");
out.print(NL);
return;
}
fileToFindByte = Token.token(fileToFind);
// Version - 1 = use table
// 2 = use xquery
// 3 = use xquery + index
switch (version) {
case '1':
fileToFind = FSUtils.transformToRegex(fileToFind);
locateTable(FSUtils.getROOTDIR(), limit);
break;
case '2':
locateXQuery(limit);
break;
case '3':
out.print("Not yet implemented");
break;
default:
locateXQuery(limit);
break;
}
if(cFlag) {
printCount();
}
} | #vulnerable code
public void locateMain(final String cmd)
throws IOException {
GetOpts g = new GetOpts(cmd, "chl:V:", 1);
char version = (char) -1;
int limit = -1;
// get all Options
int ch = g.getopt();
while (ch != -1) {
switch (ch) {
case 'c':
//Suppress normal output; instead print a
//count of matching file names.
cFlag = true;
break;
case 'h':
printHelp();
fAccomplished = true;
break;
case 'l':
// Limit output to number of file names and exit.
limit = Integer.parseInt(g.getOptarg());
lFlag = true;
break;
case 'V':
version = g.getOptarg().charAt(0);
break;
case ':':
fError = true;
out.print("ls: missing argument");
break;
case '?':
fError = true;
out.print("ls: illegal option");
break;
}
if(fError || fAccomplished) {
// more options ?
return;
}
ch = g.getopt();
}
fileToFind = g.getPath();
fileToFindByte = Token.token(fileToFind);
if(fileToFind == null) {
out.print("usage: locate [-l limit] [-c] [-h] -V 1 ...");
out.print(NL);
}
// Version - 1 = use table
// 2 = use xquery
// 3 = use xquery + index
switch (version) {
case '1':
locateTable(FSUtils.getROOTDIR(), limit);
break;
case '2':
locateXQuery(limit);
break;
case '3':
out.print("Not yet implemented");
break;
default:
locateXQuery(limit);
break;
}
if(cFlag) {
printCount();
}
}
#location 45
#vulnerability type NULL_DEREFERENCE | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
ConfigURIFactory(ClassLoader classLoader, VariablesExpander expander) {
this.classLoader = classLoader;
this.expander = expander;
} | #vulnerable code
URI newURI(String spec) throws URISyntaxException {
String expanded = expand(spec);
if (expanded.startsWith(CLASSPATH_PROTOCOL)) {
String path = expanded.substring(CLASSPATH_PROTOCOL.length());
URL url = classLoader.getResource(path);
if (url == null)
return null;
return url.toURI();
} else {
return new URI(expanded);
}
}
#location 3
#vulnerability type NULL_DEREFERENCE | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
public static void main(String[] args) throws Exception {
InputStream in = XmlSpike.class.getResourceAsStream("Config.xml");
Properties props = load(in);
File file = new File("target/test-resources/props.xml");
file.getParentFile().mkdirs();
ByteArrayOutputStream propertiesxmlformat = new ByteArrayOutputStream();
props.storeToXML(propertiesxmlformat, "test");
String propsXmlString = propertiesxmlformat.toString();
System.out.println("java xml properties format:" + propsXmlString);
Properties props2 = new Properties();
props2.loadFromXML(new FileInputStream(file));
Properties props3 = load(new FileInputStream(file));
props.store(System.out, "props");
props2.store(System.out, "props2");
props3.store(System.out, "props3");
} | #vulnerable code
public static void main(String[] args) throws Exception {
SAXParserFactory factory = SAXParserFactory.newInstance();
SAXParser parser = factory.newSAXParser();
InputStream in = XmlSpike.class.getResourceAsStream("Config.xml");
String input = convertStreamToString(in);
System.out.println("input:\n" + input);
StringWriter output = new StringWriter();
PrintWriter pw = new PrintWriter(output);
XmlToPropsHandler h = new XmlToPropsHandler(pw);
parser.parse(new StringInputStream(input), h);
pw.flush();
System.out.println("output:\n" + output);
File file = new File("target/test-resources/props.xml");
file.getParentFile().mkdirs();
Properties props = new Properties();
props.load(new StringInputStream(output.toString()));
ByteArrayOutputStream propertiesxmlformat = new ByteArrayOutputStream();
props.storeToXML(propertiesxmlformat, "test");
String propsXmlString = propertiesxmlformat.toString();
System.out.println("java xml properties format:" + propsXmlString);
boolean isJavaProp = propsXmlString.contains("http://java.sun.com/dtd/properties.dtd");
System.out.println("isJavaProp: " + isJavaProp);
}
#location 24
#vulnerability type RESOURCE_LEAK | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Before
public void before() throws Throwable {
save(new Properties() {{
setProperty("someValue", "10");
}});
reloadableConfig = ConfigFactory.create(ReloadableConfig.class);
} | #vulnerable code
@Before
public void before() throws Throwable {
synchronized (target) {
save(new Properties() {{
setProperty("someValue", "10");
}});
reloadableConfig = ConfigFactory.create(ReloadableConfig.class);
}
}
#location 3
#vulnerability type THREAD_SAFETY_VIOLATION | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Test
public void shouldReturnTheResourceForAClass() throws IOException {
ConfigURLStreamHandler handler = new ConfigURLStreamHandler(SampleConfig.class.getClassLoader(),
new SystemVariablesExpander());
ConfigURLStreamHandler spy = spy(handler);
ConfigFactory.getPropertiesFor(SampleConfig.class, spy);
URL expected =
new URL(null, "classpath:org/aeonbits/owner/SampleConfig.properties", handler);
verify(spy, times(1)).openConnection(eq(expected));
} | #vulnerable code
@Test
public void shouldReturnTheResourceForAClass() throws IOException {
ConfigURLStreamHandler handler = new ConfigURLStreamHandler(SampleConfig.class.getClassLoader(),
new SystemVariablesExpander());
ConfigURLStreamHandler spy = spy(handler);
ConfigFactory.getStreamFor(SampleConfig.class, spy);
URL expected =
new URL(null, "classpath:org/aeonbits/owner/SampleConfig.properties", handler);
verify(spy, times(1)).openConnection(eq(expected));
}
#location 7
#vulnerability type RESOURCE_LEAK | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
PropertiesManager(Class<? extends Config> clazz, Properties properties, ScheduledExecutorService scheduler,
Map<?, ?>... imports) {
this.clazz = clazz;
this.properties = properties;
this.imports = imports;
handler = new ConfigURLStreamHandler(clazz.getClassLoader(), expander);
sources = clazz.getAnnotation(Sources.class);
LoadPolicy loadPolicy = clazz.getAnnotation(LoadPolicy.class);
loadType = (loadPolicy != null) ? loadPolicy.value() : FIRST;
setupHotReload(clazz, scheduler);
} | #vulnerable code
void syncReloadCheck() {
if (hotReloadLogic != null && hotReloadLogic.isSync())
hotReloadLogic.checkAndReload(lastLoadTime);
}
#location 3
#vulnerability type THREAD_SAFETY_VIOLATION | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
static String expandUserHome(String text) {
if (text.equals("~")) {
return system.getProperty("user.home");
} else if (text.indexOf("~/") == 0 || text.indexOf("file:~/") == 0 || text.indexOf("jar:file:~/") == 0) {
String safeHome = system.getProperty("user.home").replace("\\", "\\\\");
return text.replaceFirst("~/", safeHome + "/");
}
return text;
} | #vulnerable code
static String expandUserHome(String text) {
if (text.equals("~")) {
return System.getProperty("user.home");
} else if (text.indexOf("~/") == 0 || text.indexOf("file:~/") == 0 || text.indexOf("jar:file:~/") == 0) {
String safeHome = System.getProperty("user.home").replace("\\", "\\\\");
return text.replaceFirst("~/", safeHome + "/");
}
return text;
}
#location 5
#vulnerability type NULL_DEREFERENCE | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
public static Properties load(InputStream inputStream) throws ParserConfigurationException, SAXException,
IOException {
SAXParserFactory factory = SAXParserFactory.newInstance();
factory.setValidating(true);
factory.setNamespaceAware(true);
SAXParser parser = factory.newSAXParser();
Properties props = new Properties();
XmlToPropsHandler h = new XmlToPropsHandler(props);
parser.setProperty("http://xml.org/sax/properties/lexical-handler", h);
parser.parse(inputStream, h);
System.out.println("Output:\n");
props.store(System.out, "output");
return props;
} | #vulnerable code
public static Properties load(InputStream inputStream) throws ParserConfigurationException, SAXException,
IOException {
SAXParserFactory factory = SAXParserFactory.newInstance();
factory.setValidating(true);
factory.setNamespaceAware(true);
SAXParser parser = factory.newSAXParser();
StringWriter output = new StringWriter();
PrintWriter pw = new PrintWriter(output);
XmlToPropsHandler h = new XmlToPropsHandler(pw);
parser.setProperty("http://xml.org/sax/properties/lexical-handler", h);
parser.parse(inputStream, h);
pw.flush();
output.flush();
System.out.println("Output:\n" + output);
Properties props = new Properties();
props.load(new StringReader(output.toString()));
return props;
}
#location 14
#vulnerability type RESOURCE_LEAK | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
private static void storeJar(File target, String entryName, Properties props) throws IOException {
byte[] bytes = toBytes(props);
InputStream input = new ByteArrayInputStream(bytes);
try {
FileOutputStream fileOutputStream = new FileOutputStream(target);
try {
JarOutputStream output = new JarOutputStream(fileOutputStream);
try {
ZipEntry entry = new ZipEntry(entryName);
output.putNextEntry(entry);
byte[] buffer = new byte[4096];
int size;
while ((size = input.read(buffer)) != -1)
output.write(buffer, 0, size);
} finally {
output.close();
}
} finally {
fileOutputStream.close();
}
} finally {
input.close();
}
} | #vulnerable code
private static void storeJar(File target, String entryName, Properties props) throws IOException {
byte[] bytes = toBytes(props);
InputStream input = new ByteArrayInputStream(bytes);
JarOutputStream output = new JarOutputStream(new FileOutputStream(target));
try {
ZipEntry entry = new ZipEntry(entryName);
output.putNextEntry(entry);
byte[] buffer = new byte[4096];
int size;
while ((size = input.read(buffer)) != -1)
output.write(buffer, 0, size);
} finally {
input.close();
output.close();
}
}
#location 4
#vulnerability type RESOURCE_LEAK | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
public static void save(File target, Properties p) throws IOException {
File parent = target.getParentFile();
parent.mkdirs();
if (isWindows()) {
store(new FileOutputStream(target), p);
} else {
File tempFile = createTempFile(target.getName(), ".temp", parent);
store(new FileOutputStream(tempFile), p);
rename(tempFile, target);
}
} | #vulnerable code
public static void save(File target, Properties p) throws IOException {
File parent = target.getParentFile();
parent.mkdirs();
if (isWindows()) {
p.store(new FileWriter(target), "saved for test");
} else {
File tempFile = File.createTempFile(target.getName(), "temp", parent);
p.store(new FileWriter(tempFile), "saved for test");
if (!tempFile.renameTo(target))
throw new IOException(String.format("Failed to overwrite %s to %s", tempFile.toString(),
target.toString()));
}
}
#location 5
#vulnerability type RESOURCE_LEAK | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Test
public void multiThreadedReloadTest() throws Throwable {
Object lock = new Object();
ReaderThread[] readers = newArray(20, new ReaderThread(reloadableConfig, lock, 100));
WriterThread[] writers = newArray(5, new WriterThread(reloadableConfig, lock, 70));
start(readers, writers);
notifyAll(lock);
join(readers, writers);
assertNoErrors(readers, writers);
} | #vulnerable code
@Test
public void multiThreadedReloadTest() throws Throwable {
Object lock = new Object();
ReaderThread[] readers = newArray(20, new ReaderThread(reloadableConfig, lock, 100));
WriterThread[] writers = newArray(5, new WriterThread(reloadableConfig, lock, 70));
start(readers, writers);
synchronized (lock) {
lock.notifyAll();
}
join(readers, writers);
assertNoErrors(readers, writers);
}
#location 5
#vulnerability type THREAD_SAFETY_VIOLATION | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Test
public void multiThreadedReloadTest() throws Throwable {
Object lock = new Object();
ReaderThread[] readers = newArray(20, new ReaderThread(reloadableConfig, lock, 100));
WriterThread[] writers = newArray(5, new WriterThread(reloadableConfig, lock, 70));
start(readers, writers);
notifyAll(lock);
join(readers, writers);
assertNoErrors(readers, writers);
} | #vulnerable code
@Test
public void multiThreadedReloadTest() throws Throwable {
Object lock = new Object();
ReaderThread[] readers = newArray(20, new ReaderThread(reloadableConfig, lock, 100));
WriterThread[] writers = newArray(5, new WriterThread(reloadableConfig, lock, 70));
start(readers, writers);
synchronized (lock) {
lock.notifyAll();
}
join(readers, writers);
assertNoErrors(readers, writers);
}
#location 6
#vulnerability type THREAD_SAFETY_VIOLATION | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@After
public void after() throws Throwable {
target.delete();
} | #vulnerable code
@After
public void after() throws Throwable {
synchronized (target) {
target.delete();
}
}
#location 3
#vulnerability type THREAD_SAFETY_VIOLATION | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
public static void save(File target, Properties p) throws IOException {
File parent = target.getParentFile();
parent.mkdirs();
if (isWindows()) {
store(target, p);
} else {
File tempFile = createTempFile(target.getName(), ".temp", parent);
store(tempFile, p);
rename(tempFile, target);
}
} | #vulnerable code
public static void save(File target, Properties p) throws IOException {
File parent = target.getParentFile();
parent.mkdirs();
if (isWindows()) {
store(new FileOutputStream(target), p);
} else {
File tempFile = createTempFile(target.getName(), ".temp", parent);
store(new FileOutputStream(tempFile), p);
rename(tempFile, target);
}
}
#location 8
#vulnerability type RESOURCE_LEAK | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
LoadersManager() {
registerLoader(new PropertiesLoader());
registerLoader(new XMLLoader());
} | #vulnerable code
InputStream getInputStream(URL url) throws IOException {
URLConnection conn = url.openConnection();
if (conn == null)
return null;
return conn.getInputStream();
}
#location 5
#vulnerability type RESOURCE_LEAK | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Test
public void multiThreadedReloadTest() throws Throwable {
Object lock = new Object();
ReaderThread[] readers = newArray(20, new ReaderThread(reloadableConfig, lock, 100));
WriterThread[] writers = newArray(5, new WriterThread(reloadableConfig, lock, 70));
start(readers, writers);
notifyAll(lock);
join(readers, writers);
assertNoErrors(readers, writers);
} | #vulnerable code
@Test
public void multiThreadedReloadTest() throws Throwable {
Object lock = new Object();
ReaderThread[] readers = newArray(20, new ReaderThread(reloadableConfig, lock, 100));
WriterThread[] writers = newArray(5, new WriterThread(reloadableConfig, lock, 70));
start(readers, writers);
synchronized (lock) {
lock.notifyAll();
}
join(readers, writers);
assertNoErrors(readers, writers);
}
#location 6
#vulnerability type THREAD_SAFETY_VIOLATION | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Test
public void shouldLoadURLFromSpecifiedSource() throws IOException {
final URL[] lastURL = { null };
ConfigURLStreamHandler handler = new ConfigURLStreamHandler(SampleConfigWithSource.class.getClassLoader(),
new SystemVariablesExpander()) {
@Override
protected URLConnection openConnection(URL url) throws IOException {
lastURL[0] = url;
return super.openConnection(url);
}
};
ConfigFactory.getPropertiesFor(SampleConfigWithSource.class, handler);
URL expected = new URL(null, "classpath:org/aeonbits/owner/FooBar.properties",
handler);
assertEquals(expected, lastURL[0]);
} | #vulnerable code
@Test
public void shouldLoadURLFromSpecifiedSource() throws IOException {
final URL[] lastURL = { null };
ConfigURLStreamHandler handler = new ConfigURLStreamHandler(SampleConfigWithSource.class.getClassLoader(),
new SystemVariablesExpander()) {
@Override
protected URLConnection openConnection(URL url) throws IOException {
lastURL[0] = url;
return super.openConnection(url);
}
};
ConfigFactory.getStreamFor(SampleConfigWithSource.class, handler);
URL expected = new URL(null, "classpath:org/aeonbits/owner/FooBar.properties",
handler);
assertEquals(expected, lastURL[0]);
}
#location 13
#vulnerability type RESOURCE_LEAK | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Override
public Object execute() {
// Configure command before execution
introspector.getHystrixProperties()
.entrySet()
.forEach(entry -> setProperty(entry.getKey(), entry.getValue()));
// Ensure our internal state is consistent with Hystrix
if (introspector.hasCircuitBreaker()) {
breakerHelper.ensureConsistentState();
LOGGER.info("Enter: breaker for " + getCommandKey() + " in state " + breakerHelper.getState());
}
// Record state of breaker
boolean wasBreakerOpen = isCircuitBreakerOpen();
// Track invocation in a bulkhead
if (introspector.hasBulkhead()) {
bulkheadHelper.trackInvocation(this);
}
// Execute command
Object result = null;
Throwable throwable = null;
long startNanos = System.nanoTime();
try {
result = super.execute();
} catch (Throwable t) {
throwable = t;
}
executionTime = System.nanoTime() - startNanos;
boolean hasFailed = (throwable != null);
if (introspector.hasCircuitBreaker()) {
// Keep track of failure ratios
breakerHelper.pushResult(throwable == null);
// Query breaker states
boolean breakerWillOpen = false;
boolean isClosedNow = !isCircuitBreakerOpen();
/*
* Special logic for MP circuit breakers to support failOn. If not a
* throwable to fail on, restore underlying breaker and return.
*/
if (hasFailed) {
final Throwable throwableFinal = throwable;
Class<? extends Throwable>[] throwableClasses = introspector.getCircuitBreaker().failOn();
boolean failOn = Arrays.asList(throwableClasses)
.stream()
.anyMatch(c -> c.isAssignableFrom(throwableFinal.getClass()));
if (!failOn) {
restoreBreaker(); // clears Hystrix counters
updateMetricsAfter(throwable, wasBreakerOpen, isClosedNow, breakerWillOpen);
throw ExceptionUtil.wrapThrowable(throwable);
}
}
/*
* Special logic for MP circuit breakers to support an arbitrary success
* threshold used to return a breaker back to its CLOSED state. Hystrix
* only supports a threshold of 1 here, so additional logic is required.
*/
synchronized (breakerHelper.getSyncObject()) {
// If failure ratio exceeded, then switch state to OPEN_MP
if (breakerHelper.getState() == CircuitBreakerHelper.State.CLOSED_MP) {
double failureRatio = breakerHelper.getFailureRatio();
if (failureRatio >= introspector.getCircuitBreaker().failureRatio()) {
breakerWillOpen = true;
breakerHelper.setState(CircuitBreakerHelper.State.OPEN_MP);
runTripBreaker();
}
}
// If latest run failed, may need to switch state to OPEN_MP
if (hasFailed) {
if (breakerHelper.getState() == CircuitBreakerHelper.State.HALF_OPEN_MP) {
// If failed and in HALF_OPEN_MP, we need to force breaker to open
runTripBreaker();
breakerHelper.setState(CircuitBreakerHelper.State.OPEN_MP);
}
updateMetricsAfter(throwable, wasBreakerOpen, isClosedNow, breakerWillOpen);
throw ExceptionUtil.wrapThrowable(throwable);
}
// Check next state of breaker based on outcome
if (wasBreakerOpen && isClosedNow) {
// Last called was successful
breakerHelper.incSuccessCount();
// We stay in HALF_OPEN_MP until successThreshold is reached
if (breakerHelper.getSuccessCount() < introspector.getCircuitBreaker().successThreshold()) {
breakerHelper.setState(CircuitBreakerHelper.State.HALF_OPEN_MP);
} else {
breakerHelper.setState(CircuitBreakerHelper.State.CLOSED_MP);
breakerHelper.resetCommandData();
}
}
}
updateMetricsAfter(throwable, wasBreakerOpen, isClosedNow, breakerWillOpen);
}
// Untrack invocation in a bulkhead
if (introspector.hasBulkhead()) {
bulkheadHelper.untrackInvocation(this);
}
// Display circuit breaker state at exit
if (introspector.hasCircuitBreaker()) {
LOGGER.info("Exit: breaker for " + getCommandKey() + " in state " + breakerHelper.getState());
}
// Outcome of execution
if (throwable != null) {
throw ExceptionUtil.wrapThrowable(throwable);
} else {
return result;
}
} | #vulnerable code
@Override
public Object execute() {
// Configure command before execution
introspector.getHystrixProperties()
.entrySet()
.forEach(entry -> setProperty(entry.getKey(), entry.getValue()));
// Ensure our internal state is consistent with Hystrix
if (introspector.hasCircuitBreaker()) {
breakerHelper.ensureConsistentState();
LOGGER.info("Enter: breaker for " + getCommandKey() + " in state " + breakerHelper.getState());
}
// Record state of breaker
boolean wasBreakerOpen = isCircuitBreakerOpen();
// Track invocation in a bulkhead
if (introspector.hasBulkhead()) {
bulkheadHelper.trackInvocation(this);
}
// Execute command
Object result = null;
Throwable throwable = null;
long startNanos = System.nanoTime();
try {
result = super.execute();
} catch (Throwable t) {
throwable = t;
}
executionTime = System.nanoTime() - startNanos;
boolean hasFailed = (throwable != null);
if (introspector.hasCircuitBreaker()) {
// Keep track of failure ratios
breakerHelper.pushResult(throwable == null);
// Query breaker states
boolean breakerWillOpen = false;
boolean isClosedNow = !isCircuitBreakerOpen();
/*
* Special logic for MP circuit breakers to support failOn. If not a
* throwable to fail on, restore underlying breaker and return.
*/
if (hasFailed) {
final Throwable throwableFinal = throwable;
Class<? extends Throwable>[] throwableClasses = introspector.getCircuitBreaker().failOn();
boolean failOn = Arrays.asList(throwableClasses)
.stream()
.anyMatch(c -> c.isAssignableFrom(throwableFinal.getClass()));
if (!failOn) {
restoreBreaker(); // clears Hystrix counters
updateMetricsAfter(throwable, wasBreakerOpen, breakerWillOpen);
throw ExceptionUtil.wrapThrowable(throwable);
}
}
/*
* Special logic for MP circuit breakers to support an arbitrary success
* threshold used to return a breaker back to its CLOSED state. Hystrix
* only supports a threshold of 1 here, so additional logic is required.
*/
synchronized (breakerHelper.getSyncObject()) {
// If failure ratio exceeded, then switch state to OPEN_MP
if (breakerHelper.getState() == CircuitBreakerHelper.State.CLOSED_MP) {
double failureRatio = breakerHelper.getFailureRatio();
if (failureRatio >= introspector.getCircuitBreaker().failureRatio()) {
breakerWillOpen = true;
breakerHelper.setState(CircuitBreakerHelper.State.OPEN_MP);
runTripBreaker();
}
}
// If latest run failed, may need to switch state to OPEN_MP
if (hasFailed) {
if (breakerHelper.getState() == CircuitBreakerHelper.State.HALF_OPEN_MP) {
// If failed and in HALF_OPEN_MP, we need to force breaker to open
runTripBreaker();
breakerHelper.setState(CircuitBreakerHelper.State.OPEN_MP);
}
updateMetricsAfter(throwable, wasBreakerOpen, breakerWillOpen);
throw ExceptionUtil.wrapThrowable(throwable);
}
// Check next state of breaker based on outcome
if (wasBreakerOpen && isClosedNow) {
// Last called was successful
breakerHelper.incSuccessCount();
// We stay in HALF_OPEN_MP until successThreshold is reached
if (breakerHelper.getSuccessCount() < introspector.getCircuitBreaker().successThreshold()) {
breakerHelper.setState(CircuitBreakerHelper.State.HALF_OPEN_MP);
} else {
breakerHelper.setState(CircuitBreakerHelper.State.CLOSED_MP);
breakerHelper.resetCommandData();
}
}
}
updateMetricsAfter(throwable, wasBreakerOpen, breakerWillOpen);
}
// Untrack invocation in a bulkhead
if (introspector.hasBulkhead()) {
bulkheadHelper.untrackInvocation(this);
}
// Display circuit breaker state at exit
if (introspector.hasCircuitBreaker()) {
LOGGER.info("Exit: breaker for " + getCommandKey() + " in state " + breakerHelper.getState());
}
// Outcome of execution
if (throwable != null) {
throw ExceptionUtil.wrapThrowable(throwable);
} else {
return result;
}
}
#location 32
#vulnerability type THREAD_SAFETY_VIOLATION | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Override
public Object execute() {
// Configure command before execution
introspector.getHystrixProperties()
.entrySet()
.forEach(entry -> setProperty(entry.getKey(), entry.getValue()));
// Ensure our internal state is consistent with Hystrix
if (introspector.hasCircuitBreaker()) {
breakerHelper.ensureConsistentState();
LOGGER.info("Enter: breaker for " + getCommandKey() + " in state " + breakerHelper.getState());
}
// Record state of breaker
boolean wasBreakerOpen = isCircuitBreakerOpen();
// Track invocation in a bulkhead
if (introspector.hasBulkhead()) {
bulkheadHelper.trackInvocation(this);
}
// Execute command
Object result = null;
Throwable throwable = null;
long startNanos = System.nanoTime();
try {
result = super.execute();
} catch (Throwable t) {
throwable = t;
}
executionTime = System.nanoTime() - startNanos;
boolean hasFailed = (throwable != null);
if (introspector.hasCircuitBreaker()) {
// Keep track of failure ratios
breakerHelper.pushResult(throwable == null);
// Query breaker states
boolean breakerWillOpen = false;
boolean isClosedNow = !isCircuitBreakerOpen();
/*
* Special logic for MP circuit breakers to support failOn. If not a
* throwable to fail on, restore underlying breaker and return.
*/
if (hasFailed) {
final Throwable throwableFinal = throwable;
Class<? extends Throwable>[] throwableClasses = introspector.getCircuitBreaker().failOn();
boolean failOn = Arrays.asList(throwableClasses)
.stream()
.anyMatch(c -> c.isAssignableFrom(throwableFinal.getClass()));
if (!failOn) {
restoreBreaker(); // clears Hystrix counters
updateMetricsAfter(throwable, wasBreakerOpen, isClosedNow, breakerWillOpen);
throw ExceptionUtil.wrapThrowable(throwable);
}
}
/*
* Special logic for MP circuit breakers to support an arbitrary success
* threshold used to return a breaker back to its CLOSED state. Hystrix
* only supports a threshold of 1 here, so additional logic is required.
*/
synchronized (breakerHelper.getSyncObject()) {
// If failure ratio exceeded, then switch state to OPEN_MP
if (breakerHelper.getState() == CircuitBreakerHelper.State.CLOSED_MP) {
double failureRatio = breakerHelper.getFailureRatio();
if (failureRatio >= introspector.getCircuitBreaker().failureRatio()) {
breakerWillOpen = true;
breakerHelper.setState(CircuitBreakerHelper.State.OPEN_MP);
runTripBreaker();
}
}
// If latest run failed, may need to switch state to OPEN_MP
if (hasFailed) {
if (breakerHelper.getState() == CircuitBreakerHelper.State.HALF_OPEN_MP) {
// If failed and in HALF_OPEN_MP, we need to force breaker to open
runTripBreaker();
breakerHelper.setState(CircuitBreakerHelper.State.OPEN_MP);
}
updateMetricsAfter(throwable, wasBreakerOpen, isClosedNow, breakerWillOpen);
throw ExceptionUtil.wrapThrowable(throwable);
}
// Check next state of breaker based on outcome
if (wasBreakerOpen && isClosedNow) {
// Last called was successful
breakerHelper.incSuccessCount();
// We stay in HALF_OPEN_MP until successThreshold is reached
if (breakerHelper.getSuccessCount() < introspector.getCircuitBreaker().successThreshold()) {
breakerHelper.setState(CircuitBreakerHelper.State.HALF_OPEN_MP);
} else {
breakerHelper.setState(CircuitBreakerHelper.State.CLOSED_MP);
breakerHelper.resetCommandData();
}
}
}
updateMetricsAfter(throwable, wasBreakerOpen, isClosedNow, breakerWillOpen);
}
// Untrack invocation in a bulkhead
if (introspector.hasBulkhead()) {
bulkheadHelper.untrackInvocation(this);
}
// Display circuit breaker state at exit
if (introspector.hasCircuitBreaker()) {
LOGGER.info("Exit: breaker for " + getCommandKey() + " in state " + breakerHelper.getState());
}
// Outcome of execution
if (throwable != null) {
throw ExceptionUtil.wrapThrowable(throwable);
} else {
return result;
}
} | #vulnerable code
@Override
public Object execute() {
// Configure command before execution
introspector.getHystrixProperties()
.entrySet()
.forEach(entry -> setProperty(entry.getKey(), entry.getValue()));
// Ensure our internal state is consistent with Hystrix
if (introspector.hasCircuitBreaker()) {
breakerHelper.ensureConsistentState();
LOGGER.info("Enter: breaker for " + getCommandKey() + " in state " + breakerHelper.getState());
}
// Record state of breaker
boolean wasBreakerOpen = isCircuitBreakerOpen();
// Track invocation in a bulkhead
if (introspector.hasBulkhead()) {
bulkheadHelper.trackInvocation(this);
}
// Execute command
Object result = null;
Throwable throwable = null;
long startNanos = System.nanoTime();
try {
result = super.execute();
} catch (Throwable t) {
throwable = t;
}
executionTime = System.nanoTime() - startNanos;
boolean hasFailed = (throwable != null);
if (introspector.hasCircuitBreaker()) {
// Keep track of failure ratios
breakerHelper.pushResult(throwable == null);
// Query breaker states
boolean breakerWillOpen = false;
boolean isClosedNow = !isCircuitBreakerOpen();
/*
* Special logic for MP circuit breakers to support failOn. If not a
* throwable to fail on, restore underlying breaker and return.
*/
if (hasFailed) {
final Throwable throwableFinal = throwable;
Class<? extends Throwable>[] throwableClasses = introspector.getCircuitBreaker().failOn();
boolean failOn = Arrays.asList(throwableClasses)
.stream()
.anyMatch(c -> c.isAssignableFrom(throwableFinal.getClass()));
if (!failOn) {
restoreBreaker(); // clears Hystrix counters
updateMetricsAfter(throwable, wasBreakerOpen, breakerWillOpen);
throw ExceptionUtil.wrapThrowable(throwable);
}
}
/*
* Special logic for MP circuit breakers to support an arbitrary success
* threshold used to return a breaker back to its CLOSED state. Hystrix
* only supports a threshold of 1 here, so additional logic is required.
*/
synchronized (breakerHelper.getSyncObject()) {
// If failure ratio exceeded, then switch state to OPEN_MP
if (breakerHelper.getState() == CircuitBreakerHelper.State.CLOSED_MP) {
double failureRatio = breakerHelper.getFailureRatio();
if (failureRatio >= introspector.getCircuitBreaker().failureRatio()) {
breakerWillOpen = true;
breakerHelper.setState(CircuitBreakerHelper.State.OPEN_MP);
runTripBreaker();
}
}
// If latest run failed, may need to switch state to OPEN_MP
if (hasFailed) {
if (breakerHelper.getState() == CircuitBreakerHelper.State.HALF_OPEN_MP) {
// If failed and in HALF_OPEN_MP, we need to force breaker to open
runTripBreaker();
breakerHelper.setState(CircuitBreakerHelper.State.OPEN_MP);
}
updateMetricsAfter(throwable, wasBreakerOpen, breakerWillOpen);
throw ExceptionUtil.wrapThrowable(throwable);
}
// Check next state of breaker based on outcome
if (wasBreakerOpen && isClosedNow) {
// Last called was successful
breakerHelper.incSuccessCount();
// We stay in HALF_OPEN_MP until successThreshold is reached
if (breakerHelper.getSuccessCount() < introspector.getCircuitBreaker().successThreshold()) {
breakerHelper.setState(CircuitBreakerHelper.State.HALF_OPEN_MP);
} else {
breakerHelper.setState(CircuitBreakerHelper.State.CLOSED_MP);
breakerHelper.resetCommandData();
}
}
}
updateMetricsAfter(throwable, wasBreakerOpen, breakerWillOpen);
}
// Untrack invocation in a bulkhead
if (introspector.hasBulkhead()) {
bulkheadHelper.untrackInvocation(this);
}
// Display circuit breaker state at exit
if (introspector.hasCircuitBreaker()) {
LOGGER.info("Exit: breaker for " + getCommandKey() + " in state " + breakerHelper.getState());
}
// Outcome of execution
if (throwable != null) {
throw ExceptionUtil.wrapThrowable(throwable);
} else {
return result;
}
}
#location 68
#vulnerability type THREAD_SAFETY_VIOLATION | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Override
public Object execute() {
// Configure command before execution
introspector.getHystrixProperties()
.entrySet()
.forEach(entry -> setProperty(entry.getKey(), entry.getValue()));
// Ensure our internal state is consistent with Hystrix
if (introspector.hasCircuitBreaker()) {
breakerHelper.ensureConsistentState();
LOGGER.info("Circuit breaker for " + getCommandKey() + " in state " + breakerHelper.getState());
}
// Record state of breaker
boolean wasBreakerOpen = isCircuitBreakerOpen();
// Execute command
Object result = null;
Throwable throwable = null;
long startNanos = System.nanoTime();
try {
result = super.execute();
} catch (Throwable t) {
throwable = t;
}
executionTime = System.nanoTime() - startNanos;
boolean hasFailed = (throwable != null);
if (introspector.hasCircuitBreaker()) {
// Keep track of failure ratios
breakerHelper.pushResult(throwable == null);
// Query breaker states
boolean breakerWillOpen = false;
boolean isClosedNow = !isCircuitBreakerOpen();
/*
* Special logic for MP circuit breakers to support failOn. If not a
* throwable to fail on, restore underlying breaker and return.
*/
if (hasFailed) {
final Throwable throwableFinal = throwable;
Class<? extends Throwable>[] throwableClasses = introspector.getCircuitBreaker().failOn();
boolean failOn = Arrays.asList(throwableClasses)
.stream()
.anyMatch(c -> c.isAssignableFrom(throwableFinal.getClass()));
if (!failOn) {
restoreBreaker(); // clears Hystrix counters
updateMetricsAfter(throwable, wasBreakerOpen, breakerWillOpen);
throw ExceptionUtil.wrapThrowable(throwable);
}
}
/*
* Special logic for MP circuit breakers to support an arbitrary success
* threshold use to return a breaker back to its CLOSED state. Hystrix
* only supports a threshold of 1 here, so additional logic is required.
*/
synchronized (breakerHelper.getSyncObject()) {
if (hasFailed) {
if (breakerHelper.getState() == CircuitBreakerHelper.State.HALF_OPEN_MP) {
// If failed and in HALF_OPEN_MP, we need to force breaker to open
runTripBreaker();
breakerHelper.setState(CircuitBreakerHelper.State.OPEN_MP);
} else if (breakerHelper.getState() == CircuitBreakerHelper.State.CLOSED_MP) {
// Determine if breaker will open given failure ratio
double failureRatio = breakerHelper.getFailureRatio();
if (failureRatio >= introspector.getCircuitBreaker().failureRatio()) {
breakerWillOpen = true;
breakerHelper.setState(CircuitBreakerHelper.State.OPEN_MP);
}
}
updateMetricsAfter(throwable, wasBreakerOpen, breakerWillOpen);
throw ExceptionUtil.wrapThrowable(throwable);
}
if (wasBreakerOpen && isClosedNow) {
// Last called was successful
breakerHelper.incSuccessCount();
// We stay in HALF_OPEN_MP until successThreshold is reached
if (breakerHelper.getSuccessCount() < introspector.getCircuitBreaker().successThreshold()) {
breakerHelper.setState(CircuitBreakerHelper.State.HALF_OPEN_MP);
} else {
breakerHelper.setState(CircuitBreakerHelper.State.CLOSED_MP);
breakerHelper.resetCommandData();
}
}
}
updateMetricsAfter(throwable, wasBreakerOpen, breakerWillOpen);
}
// Update bulkhead helper
if (introspector.hasBulkhead()) {
bulkheadHelper.removeCommand(this);
}
// Outcome of execution
if (throwable != null) {
throw ExceptionUtil.wrapThrowable(throwable);
} else {
return result;
}
} | #vulnerable code
@Override
public Object execute() {
// Configure command before execution
introspector.getHystrixProperties()
.entrySet()
.forEach(entry -> setProperty(entry.getKey(), entry.getValue()));
// Record state of breaker
boolean wasBreakerOpen = isCircuitBreakerOpen();
// Execute command
Object result = null;
Throwable throwable = null;
long startNanos = System.nanoTime();
try {
result = super.execute();
} catch (Throwable t) {
throwable = t;
}
executionTime = System.nanoTime() - startNanos;
boolean hasFailed = (throwable != null);
if (introspector.hasCircuitBreaker()) {
// Keep track of failure ratios
breakerHelper.pushResult(throwable == null);
// Query breaker states
boolean breakerWillOpen = false;
boolean isClosedNow = !isCircuitBreakerOpen();
/*
* Special logic for MP circuit breakers to support failOn. If not a
* throwable to fail on, restore underlying breaker and return.
*/
if (hasFailed) {
final Throwable throwableFinal = throwable;
Class<? extends Throwable>[] throwableClasses = introspector.getCircuitBreaker().failOn();
boolean failOn = Arrays.asList(throwableClasses)
.stream()
.anyMatch(c -> c.isAssignableFrom(throwableFinal.getClass()));
if (!failOn) {
restoreBreaker(); // clears Hystrix counters
updateMetricsAfter(throwable, wasBreakerOpen, breakerWillOpen);
throw ExceptionUtil.wrapThrowable(throwable);
}
}
/*
* Special logic for MP circuit breakers to support an arbitrary success
* threshold use to return a breaker back to its CLOSED state. Hystrix
* only supports a threshold of 1 here, so additional logic is required.
*/
synchronized (breakerHelper.getSyncObject()) {
if (hasFailed) {
if (breakerHelper.getState() == CircuitBreakerHelper.State.HALF_OPEN_MP) {
// If failed and in HALF_OPEN_MP, we need to force braker to open
runTripBreaker();
breakerHelper.setState(CircuitBreakerHelper.State.OPEN_MP);
} else if (breakerHelper.getState() == CircuitBreakerHelper.State.CLOSED_MP) {
// Determine if breaker will open given failure ratio
double failureRatio = breakerHelper.getFailureRatio();
if (failureRatio >= introspector.getCircuitBreaker().failureRatio()) {
breakerWillOpen = true;
breakerHelper.setState(CircuitBreakerHelper.State.OPEN_MP);
}
}
updateMetricsAfter(throwable, wasBreakerOpen, breakerWillOpen);
throw ExceptionUtil.wrapThrowable(throwable);
}
if (wasBreakerOpen && isClosedNow) {
// We stay in HALF_OPEN_MP until successThreshold is reached
if (breakerHelper.getSuccessCount() < introspector.getCircuitBreaker().successThreshold()) {
breakerHelper.setState(CircuitBreakerHelper.State.HALF_OPEN_MP);
breakerHelper.incSuccessCount();
} else {
breakerHelper.setState(CircuitBreakerHelper.State.CLOSED_MP);
}
}
}
updateMetricsAfter(throwable, wasBreakerOpen, breakerWillOpen);
}
// Update bulkhead helper
if (introspector.hasBulkhead()) {
bulkheadHelper.removeCommand(this);
}
// Outcome of execution
if (throwable != null) {
throw ExceptionUtil.wrapThrowable(throwable);
} else {
return result;
}
}
#location 25
#vulnerability type THREAD_SAFETY_VIOLATION | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Override
protected Optional<Instant> dataStamp() {
// the URL may not be an HTTP URL
try {
URLConnection urlConnection = url.openConnection();
if (urlConnection instanceof HttpURLConnection) {
HttpURLConnection connection = (HttpURLConnection) urlConnection;
try {
connection.setRequestMethod(HEAD_METHOD);
if (connection.getLastModified() != 0) {
return Optional.of(Instant.ofEpochMilli(connection.getLastModified()));
}
} finally {
connection.disconnect();
}
}
} catch (IOException ex) {
LOGGER.log(Level.FINE, ex, () -> "Configuration at url '" + url + "' HEAD is not accessible.");
}
Optional<Instant> timestamp = Optional.of(Instant.MAX);
LOGGER.finer("Missing HEAD '" + url + "' response header 'Last-Modified'. Used time '"
+ timestamp + "' as a content timestamp.");
return timestamp;
} | #vulnerable code
@Override
protected Optional<Instant> dataStamp() {
try {
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod(HEAD_METHOD);
if (connection.getLastModified() != 0) {
return Optional.of(Instant.ofEpochMilli(connection.getLastModified()));
}
} catch (IOException ex) {
LOGGER.log(Level.FINE, ex, () -> "Configuration at url '" + url + "' HEAD is not accessible.");
}
Optional<Instant> timestamp = Optional.of(Instant.MAX);
LOGGER.finer("Missing HEAD '" + url + "' response header 'Last-Modified'. Used time '"
+ timestamp + "' as a content timestamp.");
return timestamp;
}
#location 7
#vulnerability type RESOURCE_LEAK | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Override
public Object execute() {
// Configure command before execution
introspector.getHystrixProperties()
.entrySet()
.forEach(entry -> setProperty(entry.getKey(), entry.getValue()));
// Ensure our internal state is consistent with Hystrix
if (introspector.hasCircuitBreaker()) {
breakerHelper.ensureConsistentState();
LOGGER.info("Enter: breaker for " + getCommandKey() + " in state " + breakerHelper.getState());
}
// Record state of breaker
boolean wasBreakerOpen = isCircuitBreakerOpen();
// Track invocation in a bulkhead
if (introspector.hasBulkhead()) {
bulkheadHelper.trackInvocation(this);
}
// Execute command
Object result = null;
Throwable throwable = null;
long startNanos = System.nanoTime();
try {
result = super.execute();
} catch (Throwable t) {
throwable = t;
}
executionTime = System.nanoTime() - startNanos;
boolean hasFailed = (throwable != null);
if (introspector.hasCircuitBreaker()) {
// Keep track of failure ratios
breakerHelper.pushResult(throwable == null);
// Query breaker states
boolean breakerWillOpen = false;
boolean isClosedNow = !isCircuitBreakerOpen();
/*
* Special logic for MP circuit breakers to support failOn. If not a
* throwable to fail on, restore underlying breaker and return.
*/
if (hasFailed) {
final Throwable throwableFinal = throwable;
Class<? extends Throwable>[] throwableClasses = introspector.getCircuitBreaker().failOn();
boolean failOn = Arrays.asList(throwableClasses)
.stream()
.anyMatch(c -> c.isAssignableFrom(throwableFinal.getClass()));
if (!failOn) {
restoreBreaker(); // clears Hystrix counters
updateMetricsAfter(throwable, wasBreakerOpen, isClosedNow, breakerWillOpen);
throw ExceptionUtil.wrapThrowable(throwable);
}
}
/*
* Special logic for MP circuit breakers to support an arbitrary success
* threshold used to return a breaker back to its CLOSED state. Hystrix
* only supports a threshold of 1 here, so additional logic is required.
*/
synchronized (breakerHelper.getSyncObject()) {
// If failure ratio exceeded, then switch state to OPEN_MP
if (breakerHelper.getState() == CircuitBreakerHelper.State.CLOSED_MP) {
double failureRatio = breakerHelper.getFailureRatio();
if (failureRatio >= introspector.getCircuitBreaker().failureRatio()) {
breakerWillOpen = true;
breakerHelper.setState(CircuitBreakerHelper.State.OPEN_MP);
runTripBreaker();
}
}
// If latest run failed, may need to switch state to OPEN_MP
if (hasFailed) {
if (breakerHelper.getState() == CircuitBreakerHelper.State.HALF_OPEN_MP) {
// If failed and in HALF_OPEN_MP, we need to force breaker to open
runTripBreaker();
breakerHelper.setState(CircuitBreakerHelper.State.OPEN_MP);
}
updateMetricsAfter(throwable, wasBreakerOpen, isClosedNow, breakerWillOpen);
throw ExceptionUtil.wrapThrowable(throwable);
}
// Check next state of breaker based on outcome
if (wasBreakerOpen && isClosedNow) {
// Last called was successful
breakerHelper.incSuccessCount();
// We stay in HALF_OPEN_MP until successThreshold is reached
if (breakerHelper.getSuccessCount() < introspector.getCircuitBreaker().successThreshold()) {
breakerHelper.setState(CircuitBreakerHelper.State.HALF_OPEN_MP);
} else {
breakerHelper.setState(CircuitBreakerHelper.State.CLOSED_MP);
breakerHelper.resetCommandData();
}
}
}
updateMetricsAfter(throwable, wasBreakerOpen, isClosedNow, breakerWillOpen);
}
// Untrack invocation in a bulkhead
if (introspector.hasBulkhead()) {
bulkheadHelper.untrackInvocation(this);
}
// Display circuit breaker state at exit
if (introspector.hasCircuitBreaker()) {
LOGGER.info("Exit: breaker for " + getCommandKey() + " in state " + breakerHelper.getState());
}
// Outcome of execution
if (throwable != null) {
throw ExceptionUtil.wrapThrowable(throwable);
} else {
return result;
}
} | #vulnerable code
@Override
public Object execute() {
// Configure command before execution
introspector.getHystrixProperties()
.entrySet()
.forEach(entry -> setProperty(entry.getKey(), entry.getValue()));
// Ensure our internal state is consistent with Hystrix
if (introspector.hasCircuitBreaker()) {
breakerHelper.ensureConsistentState();
LOGGER.info("Enter: breaker for " + getCommandKey() + " in state " + breakerHelper.getState());
}
// Record state of breaker
boolean wasBreakerOpen = isCircuitBreakerOpen();
// Track invocation in a bulkhead
if (introspector.hasBulkhead()) {
bulkheadHelper.trackInvocation(this);
}
// Execute command
Object result = null;
Throwable throwable = null;
long startNanos = System.nanoTime();
try {
result = super.execute();
} catch (Throwable t) {
throwable = t;
}
executionTime = System.nanoTime() - startNanos;
boolean hasFailed = (throwable != null);
if (introspector.hasCircuitBreaker()) {
// Keep track of failure ratios
breakerHelper.pushResult(throwable == null);
// Query breaker states
boolean breakerWillOpen = false;
boolean isClosedNow = !isCircuitBreakerOpen();
/*
* Special logic for MP circuit breakers to support failOn. If not a
* throwable to fail on, restore underlying breaker and return.
*/
if (hasFailed) {
final Throwable throwableFinal = throwable;
Class<? extends Throwable>[] throwableClasses = introspector.getCircuitBreaker().failOn();
boolean failOn = Arrays.asList(throwableClasses)
.stream()
.anyMatch(c -> c.isAssignableFrom(throwableFinal.getClass()));
if (!failOn) {
restoreBreaker(); // clears Hystrix counters
updateMetricsAfter(throwable, wasBreakerOpen, breakerWillOpen);
throw ExceptionUtil.wrapThrowable(throwable);
}
}
/*
* Special logic for MP circuit breakers to support an arbitrary success
* threshold used to return a breaker back to its CLOSED state. Hystrix
* only supports a threshold of 1 here, so additional logic is required.
*/
synchronized (breakerHelper.getSyncObject()) {
// If failure ratio exceeded, then switch state to OPEN_MP
if (breakerHelper.getState() == CircuitBreakerHelper.State.CLOSED_MP) {
double failureRatio = breakerHelper.getFailureRatio();
if (failureRatio >= introspector.getCircuitBreaker().failureRatio()) {
breakerWillOpen = true;
breakerHelper.setState(CircuitBreakerHelper.State.OPEN_MP);
runTripBreaker();
}
}
// If latest run failed, may need to switch state to OPEN_MP
if (hasFailed) {
if (breakerHelper.getState() == CircuitBreakerHelper.State.HALF_OPEN_MP) {
// If failed and in HALF_OPEN_MP, we need to force breaker to open
runTripBreaker();
breakerHelper.setState(CircuitBreakerHelper.State.OPEN_MP);
}
updateMetricsAfter(throwable, wasBreakerOpen, breakerWillOpen);
throw ExceptionUtil.wrapThrowable(throwable);
}
// Check next state of breaker based on outcome
if (wasBreakerOpen && isClosedNow) {
// Last called was successful
breakerHelper.incSuccessCount();
// We stay in HALF_OPEN_MP until successThreshold is reached
if (breakerHelper.getSuccessCount() < introspector.getCircuitBreaker().successThreshold()) {
breakerHelper.setState(CircuitBreakerHelper.State.HALF_OPEN_MP);
} else {
breakerHelper.setState(CircuitBreakerHelper.State.CLOSED_MP);
breakerHelper.resetCommandData();
}
}
}
updateMetricsAfter(throwable, wasBreakerOpen, breakerWillOpen);
}
// Untrack invocation in a bulkhead
if (introspector.hasBulkhead()) {
bulkheadHelper.untrackInvocation(this);
}
// Display circuit breaker state at exit
if (introspector.hasCircuitBreaker()) {
LOGGER.info("Exit: breaker for " + getCommandKey() + " in state " + breakerHelper.getState());
}
// Outcome of execution
if (throwable != null) {
throw ExceptionUtil.wrapThrowable(throwable);
} else {
return result;
}
}
#location 37
#vulnerability type THREAD_SAFETY_VIOLATION | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Test
public void testFromSystemPropertiesDescription() {
ConfigSource configSource = ConfigSources.systemProperties();
assertThat(configSource.description(), is("SystemPropertiesConfig"));
} | #vulnerable code
@Test
public void testFromSystemPropertiesDescription() {
ConfigSource configSource = ConfigSources.systemProperties();
assertThat(configSource.description(), is("MapConfig[sys-props]"));
}
#location 5
#vulnerability type RESOURCE_LEAK | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Override
public Object execute() {
boolean lockRemoved = false;
try {
// Configure command before execution
introspector.getHystrixProperties()
.entrySet()
.forEach(entry -> setProperty(entry.getKey(), entry.getValue()));
// Get lock and check breaker delay
if (introspector.hasCircuitBreaker()) {
breakerHelper.lock(); // acquire exclusive access to command data
// OPEN_MP -> HALF_OPEN_MP
if (breakerHelper.getState() == State.OPEN_MP) {
long delayNanos = TimeUtil.convertToNanos(introspector.getCircuitBreaker().delay(),
introspector.getCircuitBreaker().delayUnit());
if (breakerHelper.getCurrentStateNanos() > delayNanos) {
breakerHelper.setState(State.HALF_OPEN_MP);
}
}
logCircuitBreakerState("Enter");
}
// Record state of breaker
boolean wasBreakerOpen = isCircuitBreakerOpen();
// Track invocation in a bulkhead
if (introspector.hasBulkhead()) {
bulkheadHelper.trackInvocation(this);
}
// Execute command
Object result = null;
Throwable throwable = null;
long startNanos = System.nanoTime();
try {
result = super.execute();
} catch (Throwable t) {
throwable = t;
}
executionTime = System.nanoTime() - startNanos;
boolean hasFailed = (throwable != null);
if (introspector.hasCircuitBreaker()) {
// Keep track of failure ratios
breakerHelper.pushResult(throwable == null);
// Query breaker states
boolean breakerOpening = false;
boolean isClosedNow = !wasBreakerOpen;
/*
* Special logic for MP circuit breakers to support failOn. If not a
* throwable to fail on, restore underlying breaker and return.
*/
if (hasFailed) {
final Throwable throwableFinal = throwable;
Class<? extends Throwable>[] throwableClasses = introspector.getCircuitBreaker().failOn();
boolean failOn = Arrays.asList(throwableClasses)
.stream()
.anyMatch(c -> c.isAssignableFrom(throwableFinal.getClass()));
if (!failOn) {
updateMetricsAfter(throwable, wasBreakerOpen, isClosedNow, breakerOpening);
logCircuitBreakerState("Exit 1");
throw ExceptionUtil.toWrappedException(throwable);
}
}
// CLOSED_MP -> OPEN_MP
if (breakerHelper.getState() == State.CLOSED_MP) {
double failureRatio = breakerHelper.getFailureRatio();
if (failureRatio >= introspector.getCircuitBreaker().failureRatio()) {
breakerHelper.setState(State.OPEN_MP);
breakerOpening = true;
}
}
// HALF_OPEN_MP -> OPEN_MP
if (hasFailed) {
if (breakerHelper.getState() == State.HALF_OPEN_MP) {
breakerHelper.setState(State.OPEN_MP);
}
updateMetricsAfter(throwable, wasBreakerOpen, isClosedNow, breakerOpening);
logCircuitBreakerState("Exit 2");
throw ExceptionUtil.toWrappedException(throwable);
}
// Otherwise, increment success count
breakerHelper.incSuccessCount();
// HALF_OPEN_MP -> CLOSED_MP
if (breakerHelper.getState() == State.HALF_OPEN_MP) {
if (breakerHelper.getSuccessCount() == introspector.getCircuitBreaker().successThreshold()) {
breakerHelper.setState(State.CLOSED_MP);
breakerHelper.resetCommandData();
lockRemoved = true;
isClosedNow = true;
}
}
updateMetricsAfter(throwable, wasBreakerOpen, isClosedNow, breakerOpening);
}
// Untrack invocation in a bulkhead
if (introspector.hasBulkhead()) {
bulkheadHelper.untrackInvocation(this);
}
// Display circuit breaker state at exit
logCircuitBreakerState("Exit 3");
// Outcome of execution
if (throwable != null) {
throw ExceptionUtil.toWrappedException(throwable);
} else {
return result;
}
} finally {
// Free lock unless command data was reset
if (introspector.hasCircuitBreaker() && !lockRemoved) {
breakerHelper.unlock();
}
}
} | #vulnerable code
@Override
public Object execute() {
// Configure command before execution
introspector.getHystrixProperties()
.entrySet()
.forEach(entry -> setProperty(entry.getKey(), entry.getValue()));
// Ensure our internal state is consistent with Hystrix
if (introspector.hasCircuitBreaker()) {
breakerHelper.ensureConsistentState();
LOGGER.info("Enter: breaker for " + getCommandKey() + " in state " + breakerHelper.getState());
}
// Record state of breaker
boolean wasBreakerOpen = isCircuitBreakerOpen();
// Track invocation in a bulkhead
if (introspector.hasBulkhead()) {
bulkheadHelper.trackInvocation(this);
}
// Execute command
Object result = null;
Throwable throwable = null;
long startNanos = System.nanoTime();
try {
result = super.execute();
} catch (Throwable t) {
throwable = t;
}
executionTime = System.nanoTime() - startNanos;
boolean hasFailed = (throwable != null);
if (introspector.hasCircuitBreaker()) {
// Keep track of failure ratios
breakerHelper.pushResult(throwable == null);
// Query breaker states
boolean breakerWillOpen = false;
boolean isClosedNow = !isCircuitBreakerOpen();
/*
* Special logic for MP circuit breakers to support failOn. If not a
* throwable to fail on, restore underlying breaker and return.
*/
if (hasFailed) {
final Throwable throwableFinal = throwable;
Class<? extends Throwable>[] throwableClasses = introspector.getCircuitBreaker().failOn();
boolean failOn = Arrays.asList(throwableClasses)
.stream()
.anyMatch(c -> c.isAssignableFrom(throwableFinal.getClass()));
if (!failOn) {
restoreBreaker(); // clears Hystrix counters
updateMetricsAfter(throwable, wasBreakerOpen, isClosedNow, breakerWillOpen);
throw ExceptionUtil.toWrappedException(throwable);
}
}
/*
* Special logic for MP circuit breakers to support an arbitrary success
* threshold used to return a breaker back to its CLOSED state. Hystrix
* only supports a threshold of 1 here, so additional logic is required.
*/
synchronized (breakerHelper.getSyncObject()) {
// If failure ratio exceeded, then switch state to OPEN_MP
if (breakerHelper.getState() == CircuitBreakerHelper.State.CLOSED_MP) {
double failureRatio = breakerHelper.getFailureRatio();
if (failureRatio >= introspector.getCircuitBreaker().failureRatio()) {
breakerWillOpen = true;
breakerHelper.setState(CircuitBreakerHelper.State.OPEN_MP);
runTripBreaker();
}
}
// If latest run failed, may need to switch state to OPEN_MP
if (hasFailed) {
if (breakerHelper.getState() == CircuitBreakerHelper.State.HALF_OPEN_MP) {
// If failed and in HALF_OPEN_MP, we need to force breaker to open
runTripBreaker();
breakerHelper.setState(CircuitBreakerHelper.State.OPEN_MP);
}
updateMetricsAfter(throwable, wasBreakerOpen, isClosedNow, breakerWillOpen);
throw ExceptionUtil.toWrappedException(throwable);
}
// Check next state of breaker based on outcome
if (wasBreakerOpen && isClosedNow) {
// Last called was successful
breakerHelper.incSuccessCount();
// We stay in HALF_OPEN_MP until successThreshold is reached
if (breakerHelper.getSuccessCount() < introspector.getCircuitBreaker().successThreshold()) {
breakerHelper.setState(CircuitBreakerHelper.State.HALF_OPEN_MP);
} else {
breakerHelper.setState(CircuitBreakerHelper.State.CLOSED_MP);
breakerHelper.resetCommandData();
}
}
}
updateMetricsAfter(throwable, wasBreakerOpen, isClosedNow, breakerWillOpen);
}
// Untrack invocation in a bulkhead
if (introspector.hasBulkhead()) {
bulkheadHelper.untrackInvocation(this);
}
// Display circuit breaker state at exit
if (introspector.hasCircuitBreaker()) {
LOGGER.info("Exit: breaker for " + getCommandKey() + " in state " + breakerHelper.getState());
}
// Outcome of execution
if (throwable != null) {
throw ExceptionUtil.toWrappedException(throwable);
} else {
return result;
}
}
#location 32
#vulnerability type THREAD_SAFETY_VIOLATION | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Override
public Object execute() {
boolean lockRemoved = false;
try {
// Configure command before execution
introspector.getHystrixProperties()
.entrySet()
.forEach(entry -> setProperty(entry.getKey(), entry.getValue()));
// Get lock and check breaker delay
if (introspector.hasCircuitBreaker()) {
breakerHelper.lock(); // acquire exclusive access to command data
// OPEN_MP -> HALF_OPEN_MP
if (breakerHelper.getState() == State.OPEN_MP) {
long delayNanos = TimeUtil.convertToNanos(introspector.getCircuitBreaker().delay(),
introspector.getCircuitBreaker().delayUnit());
if (breakerHelper.getCurrentStateNanos() > delayNanos) {
breakerHelper.setState(State.HALF_OPEN_MP);
}
}
logCircuitBreakerState("Enter");
}
// Record state of breaker
boolean wasBreakerOpen = isCircuitBreakerOpen();
// Track invocation in a bulkhead
if (introspector.hasBulkhead()) {
bulkheadHelper.trackInvocation(this);
}
// Execute command
Object result = null;
Throwable throwable = null;
long startNanos = System.nanoTime();
try {
result = super.execute();
} catch (Throwable t) {
throwable = t;
}
executionTime = System.nanoTime() - startNanos;
boolean hasFailed = (throwable != null);
if (introspector.hasCircuitBreaker()) {
// Keep track of failure ratios
breakerHelper.pushResult(throwable == null);
// Query breaker states
boolean breakerOpening = false;
boolean isClosedNow = !wasBreakerOpen;
/*
* Special logic for MP circuit breakers to support failOn. If not a
* throwable to fail on, restore underlying breaker and return.
*/
if (hasFailed) {
final Throwable throwableFinal = throwable;
Class<? extends Throwable>[] throwableClasses = introspector.getCircuitBreaker().failOn();
boolean failOn = Arrays.asList(throwableClasses)
.stream()
.anyMatch(c -> c.isAssignableFrom(throwableFinal.getClass()));
if (!failOn) {
updateMetricsAfter(throwable, wasBreakerOpen, isClosedNow, breakerOpening);
logCircuitBreakerState("Exit 1");
throw ExceptionUtil.toWrappedException(throwable);
}
}
// CLOSED_MP -> OPEN_MP
if (breakerHelper.getState() == State.CLOSED_MP) {
double failureRatio = breakerHelper.getFailureRatio();
if (failureRatio >= introspector.getCircuitBreaker().failureRatio()) {
breakerHelper.setState(State.OPEN_MP);
breakerOpening = true;
}
}
// HALF_OPEN_MP -> OPEN_MP
if (hasFailed) {
if (breakerHelper.getState() == State.HALF_OPEN_MP) {
breakerHelper.setState(State.OPEN_MP);
}
updateMetricsAfter(throwable, wasBreakerOpen, isClosedNow, breakerOpening);
logCircuitBreakerState("Exit 2");
throw ExceptionUtil.toWrappedException(throwable);
}
// Otherwise, increment success count
breakerHelper.incSuccessCount();
// HALF_OPEN_MP -> CLOSED_MP
if (breakerHelper.getState() == State.HALF_OPEN_MP) {
if (breakerHelper.getSuccessCount() == introspector.getCircuitBreaker().successThreshold()) {
breakerHelper.setState(State.CLOSED_MP);
breakerHelper.resetCommandData();
lockRemoved = true;
isClosedNow = true;
}
}
updateMetricsAfter(throwable, wasBreakerOpen, isClosedNow, breakerOpening);
}
// Untrack invocation in a bulkhead
if (introspector.hasBulkhead()) {
bulkheadHelper.untrackInvocation(this);
}
// Display circuit breaker state at exit
logCircuitBreakerState("Exit 3");
// Outcome of execution
if (throwable != null) {
throw ExceptionUtil.toWrappedException(throwable);
} else {
return result;
}
} finally {
// Free lock unless command data was reset
if (introspector.hasCircuitBreaker() && !lockRemoved) {
breakerHelper.unlock();
}
}
} | #vulnerable code
@Override
public Object execute() {
// Configure command before execution
introspector.getHystrixProperties()
.entrySet()
.forEach(entry -> setProperty(entry.getKey(), entry.getValue()));
// Ensure our internal state is consistent with Hystrix
if (introspector.hasCircuitBreaker()) {
breakerHelper.ensureConsistentState();
LOGGER.info("Enter: breaker for " + getCommandKey() + " in state " + breakerHelper.getState());
}
// Record state of breaker
boolean wasBreakerOpen = isCircuitBreakerOpen();
// Track invocation in a bulkhead
if (introspector.hasBulkhead()) {
bulkheadHelper.trackInvocation(this);
}
// Execute command
Object result = null;
Throwable throwable = null;
long startNanos = System.nanoTime();
try {
result = super.execute();
} catch (Throwable t) {
throwable = t;
}
executionTime = System.nanoTime() - startNanos;
boolean hasFailed = (throwable != null);
if (introspector.hasCircuitBreaker()) {
// Keep track of failure ratios
breakerHelper.pushResult(throwable == null);
// Query breaker states
boolean breakerWillOpen = false;
boolean isClosedNow = !isCircuitBreakerOpen();
/*
* Special logic for MP circuit breakers to support failOn. If not a
* throwable to fail on, restore underlying breaker and return.
*/
if (hasFailed) {
final Throwable throwableFinal = throwable;
Class<? extends Throwable>[] throwableClasses = introspector.getCircuitBreaker().failOn();
boolean failOn = Arrays.asList(throwableClasses)
.stream()
.anyMatch(c -> c.isAssignableFrom(throwableFinal.getClass()));
if (!failOn) {
restoreBreaker(); // clears Hystrix counters
updateMetricsAfter(throwable, wasBreakerOpen, isClosedNow, breakerWillOpen);
throw ExceptionUtil.toWrappedException(throwable);
}
}
/*
* Special logic for MP circuit breakers to support an arbitrary success
* threshold used to return a breaker back to its CLOSED state. Hystrix
* only supports a threshold of 1 here, so additional logic is required.
*/
synchronized (breakerHelper.getSyncObject()) {
// If failure ratio exceeded, then switch state to OPEN_MP
if (breakerHelper.getState() == CircuitBreakerHelper.State.CLOSED_MP) {
double failureRatio = breakerHelper.getFailureRatio();
if (failureRatio >= introspector.getCircuitBreaker().failureRatio()) {
breakerWillOpen = true;
breakerHelper.setState(CircuitBreakerHelper.State.OPEN_MP);
runTripBreaker();
}
}
// If latest run failed, may need to switch state to OPEN_MP
if (hasFailed) {
if (breakerHelper.getState() == CircuitBreakerHelper.State.HALF_OPEN_MP) {
// If failed and in HALF_OPEN_MP, we need to force breaker to open
runTripBreaker();
breakerHelper.setState(CircuitBreakerHelper.State.OPEN_MP);
}
updateMetricsAfter(throwable, wasBreakerOpen, isClosedNow, breakerWillOpen);
throw ExceptionUtil.toWrappedException(throwable);
}
// Check next state of breaker based on outcome
if (wasBreakerOpen && isClosedNow) {
// Last called was successful
breakerHelper.incSuccessCount();
// We stay in HALF_OPEN_MP until successThreshold is reached
if (breakerHelper.getSuccessCount() < introspector.getCircuitBreaker().successThreshold()) {
breakerHelper.setState(CircuitBreakerHelper.State.HALF_OPEN_MP);
} else {
breakerHelper.setState(CircuitBreakerHelper.State.CLOSED_MP);
breakerHelper.resetCommandData();
}
}
}
updateMetricsAfter(throwable, wasBreakerOpen, isClosedNow, breakerWillOpen);
}
// Untrack invocation in a bulkhead
if (introspector.hasBulkhead()) {
bulkheadHelper.untrackInvocation(this);
}
// Display circuit breaker state at exit
if (introspector.hasCircuitBreaker()) {
LOGGER.info("Exit: breaker for " + getCommandKey() + " in state " + breakerHelper.getState());
}
// Outcome of execution
if (throwable != null) {
throw ExceptionUtil.toWrappedException(throwable);
} else {
return result;
}
}
#location 68
#vulnerability type THREAD_SAFETY_VIOLATION | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Override
public Object execute() {
// Configure command before execution
introspector.getHystrixProperties()
.entrySet()
.forEach(entry -> setProperty(entry.getKey(), entry.getValue()));
// Ensure our internal state is consistent with Hystrix
if (introspector.hasCircuitBreaker()) {
breakerHelper.ensureConsistentState();
LOGGER.info("Enter: breaker for " + getCommandKey() + " in state " + breakerHelper.getState());
}
// Record state of breaker
boolean wasBreakerOpen = isCircuitBreakerOpen();
// Track invocation in a bulkhead
if (introspector.hasBulkhead()) {
bulkheadHelper.trackInvocation(this);
}
// Execute command
Object result = null;
Throwable throwable = null;
long startNanos = System.nanoTime();
try {
result = super.execute();
} catch (Throwable t) {
throwable = t;
}
executionTime = System.nanoTime() - startNanos;
boolean hasFailed = (throwable != null);
if (introspector.hasCircuitBreaker()) {
// Keep track of failure ratios
breakerHelper.pushResult(throwable == null);
// Query breaker states
boolean breakerWillOpen = false;
boolean isClosedNow = !isCircuitBreakerOpen();
/*
* Special logic for MP circuit breakers to support failOn. If not a
* throwable to fail on, restore underlying breaker and return.
*/
if (hasFailed) {
final Throwable throwableFinal = throwable;
Class<? extends Throwable>[] throwableClasses = introspector.getCircuitBreaker().failOn();
boolean failOn = Arrays.asList(throwableClasses)
.stream()
.anyMatch(c -> c.isAssignableFrom(throwableFinal.getClass()));
if (!failOn) {
restoreBreaker(); // clears Hystrix counters
updateMetricsAfter(throwable, wasBreakerOpen, isClosedNow, breakerWillOpen);
throw ExceptionUtil.wrapThrowable(throwable);
}
}
/*
* Special logic for MP circuit breakers to support an arbitrary success
* threshold used to return a breaker back to its CLOSED state. Hystrix
* only supports a threshold of 1 here, so additional logic is required.
*/
synchronized (breakerHelper.getSyncObject()) {
// If failure ratio exceeded, then switch state to OPEN_MP
if (breakerHelper.getState() == CircuitBreakerHelper.State.CLOSED_MP) {
double failureRatio = breakerHelper.getFailureRatio();
if (failureRatio >= introspector.getCircuitBreaker().failureRatio()) {
breakerWillOpen = true;
breakerHelper.setState(CircuitBreakerHelper.State.OPEN_MP);
runTripBreaker();
}
}
// If latest run failed, may need to switch state to OPEN_MP
if (hasFailed) {
if (breakerHelper.getState() == CircuitBreakerHelper.State.HALF_OPEN_MP) {
// If failed and in HALF_OPEN_MP, we need to force breaker to open
runTripBreaker();
breakerHelper.setState(CircuitBreakerHelper.State.OPEN_MP);
}
updateMetricsAfter(throwable, wasBreakerOpen, isClosedNow, breakerWillOpen);
throw ExceptionUtil.wrapThrowable(throwable);
}
// Check next state of breaker based on outcome
if (wasBreakerOpen && isClosedNow) {
// Last called was successful
breakerHelper.incSuccessCount();
// We stay in HALF_OPEN_MP until successThreshold is reached
if (breakerHelper.getSuccessCount() < introspector.getCircuitBreaker().successThreshold()) {
breakerHelper.setState(CircuitBreakerHelper.State.HALF_OPEN_MP);
} else {
breakerHelper.setState(CircuitBreakerHelper.State.CLOSED_MP);
breakerHelper.resetCommandData();
}
}
}
updateMetricsAfter(throwable, wasBreakerOpen, isClosedNow, breakerWillOpen);
}
// Untrack invocation in a bulkhead
if (introspector.hasBulkhead()) {
bulkheadHelper.untrackInvocation(this);
}
// Display circuit breaker state at exit
if (introspector.hasCircuitBreaker()) {
LOGGER.info("Exit: breaker for " + getCommandKey() + " in state " + breakerHelper.getState());
}
// Outcome of execution
if (throwable != null) {
throw ExceptionUtil.wrapThrowable(throwable);
} else {
return result;
}
} | #vulnerable code
@Override
public Object execute() {
// Configure command before execution
introspector.getHystrixProperties()
.entrySet()
.forEach(entry -> setProperty(entry.getKey(), entry.getValue()));
// Ensure our internal state is consistent with Hystrix
if (introspector.hasCircuitBreaker()) {
breakerHelper.ensureConsistentState();
LOGGER.info("Enter: breaker for " + getCommandKey() + " in state " + breakerHelper.getState());
}
// Record state of breaker
boolean wasBreakerOpen = isCircuitBreakerOpen();
// Track invocation in a bulkhead
if (introspector.hasBulkhead()) {
bulkheadHelper.trackInvocation(this);
}
// Execute command
Object result = null;
Throwable throwable = null;
long startNanos = System.nanoTime();
try {
result = super.execute();
} catch (Throwable t) {
throwable = t;
}
executionTime = System.nanoTime() - startNanos;
boolean hasFailed = (throwable != null);
if (introspector.hasCircuitBreaker()) {
// Keep track of failure ratios
breakerHelper.pushResult(throwable == null);
// Query breaker states
boolean breakerWillOpen = false;
boolean isClosedNow = !isCircuitBreakerOpen();
/*
* Special logic for MP circuit breakers to support failOn. If not a
* throwable to fail on, restore underlying breaker and return.
*/
if (hasFailed) {
final Throwable throwableFinal = throwable;
Class<? extends Throwable>[] throwableClasses = introspector.getCircuitBreaker().failOn();
boolean failOn = Arrays.asList(throwableClasses)
.stream()
.anyMatch(c -> c.isAssignableFrom(throwableFinal.getClass()));
if (!failOn) {
restoreBreaker(); // clears Hystrix counters
updateMetricsAfter(throwable, wasBreakerOpen, breakerWillOpen);
throw ExceptionUtil.wrapThrowable(throwable);
}
}
/*
* Special logic for MP circuit breakers to support an arbitrary success
* threshold used to return a breaker back to its CLOSED state. Hystrix
* only supports a threshold of 1 here, so additional logic is required.
*/
synchronized (breakerHelper.getSyncObject()) {
// If failure ratio exceeded, then switch state to OPEN_MP
if (breakerHelper.getState() == CircuitBreakerHelper.State.CLOSED_MP) {
double failureRatio = breakerHelper.getFailureRatio();
if (failureRatio >= introspector.getCircuitBreaker().failureRatio()) {
breakerWillOpen = true;
breakerHelper.setState(CircuitBreakerHelper.State.OPEN_MP);
runTripBreaker();
}
}
// If latest run failed, may need to switch state to OPEN_MP
if (hasFailed) {
if (breakerHelper.getState() == CircuitBreakerHelper.State.HALF_OPEN_MP) {
// If failed and in HALF_OPEN_MP, we need to force breaker to open
runTripBreaker();
breakerHelper.setState(CircuitBreakerHelper.State.OPEN_MP);
}
updateMetricsAfter(throwable, wasBreakerOpen, breakerWillOpen);
throw ExceptionUtil.wrapThrowable(throwable);
}
// Check next state of breaker based on outcome
if (wasBreakerOpen && isClosedNow) {
// Last called was successful
breakerHelper.incSuccessCount();
// We stay in HALF_OPEN_MP until successThreshold is reached
if (breakerHelper.getSuccessCount() < introspector.getCircuitBreaker().successThreshold()) {
breakerHelper.setState(CircuitBreakerHelper.State.HALF_OPEN_MP);
} else {
breakerHelper.setState(CircuitBreakerHelper.State.CLOSED_MP);
breakerHelper.resetCommandData();
}
}
}
updateMetricsAfter(throwable, wasBreakerOpen, breakerWillOpen);
}
// Untrack invocation in a bulkhead
if (introspector.hasBulkhead()) {
bulkheadHelper.untrackInvocation(this);
}
// Display circuit breaker state at exit
if (introspector.hasCircuitBreaker()) {
LOGGER.info("Exit: breaker for " + getCommandKey() + " in state " + breakerHelper.getState());
}
// Outcome of execution
if (throwable != null) {
throw ExceptionUtil.wrapThrowable(throwable);
} else {
return result;
}
}
#location 112
#vulnerability type THREAD_SAFETY_VIOLATION | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Override
public Object execute() {
boolean lockRemoved = false;
try {
// Configure command before execution
introspector.getHystrixProperties()
.entrySet()
.forEach(entry -> setProperty(entry.getKey(), entry.getValue()));
// Get lock and check breaker delay
if (introspector.hasCircuitBreaker()) {
breakerHelper.lock(); // acquire exclusive access to command data
// OPEN_MP -> HALF_OPEN_MP
if (breakerHelper.getState() == State.OPEN_MP) {
long delayNanos = TimeUtil.convertToNanos(introspector.getCircuitBreaker().delay(),
introspector.getCircuitBreaker().delayUnit());
if (breakerHelper.getCurrentStateNanos() > delayNanos) {
breakerHelper.setState(State.HALF_OPEN_MP);
}
}
logCircuitBreakerState("Enter");
}
// Record state of breaker
boolean wasBreakerOpen = isCircuitBreakerOpen();
// Track invocation in a bulkhead
if (introspector.hasBulkhead()) {
bulkheadHelper.trackInvocation(this);
}
// Execute command
Object result = null;
Throwable throwable = null;
long startNanos = System.nanoTime();
try {
result = super.execute();
} catch (Throwable t) {
throwable = t;
}
executionTime = System.nanoTime() - startNanos;
boolean hasFailed = (throwable != null);
if (introspector.hasCircuitBreaker()) {
// Keep track of failure ratios
breakerHelper.pushResult(throwable == null);
// Query breaker states
boolean breakerOpening = false;
boolean isClosedNow = !wasBreakerOpen;
/*
* Special logic for MP circuit breakers to support failOn. If not a
* throwable to fail on, restore underlying breaker and return.
*/
if (hasFailed) {
final Throwable throwableFinal = throwable;
Class<? extends Throwable>[] throwableClasses = introspector.getCircuitBreaker().failOn();
boolean failOn = Arrays.asList(throwableClasses)
.stream()
.anyMatch(c -> c.isAssignableFrom(throwableFinal.getClass()));
if (!failOn) {
updateMetricsAfter(throwable, wasBreakerOpen, isClosedNow, breakerOpening);
logCircuitBreakerState("Exit 1");
throw ExceptionUtil.toWrappedException(throwable);
}
}
// CLOSED_MP -> OPEN_MP
if (breakerHelper.getState() == State.CLOSED_MP) {
double failureRatio = breakerHelper.getFailureRatio();
if (failureRatio >= introspector.getCircuitBreaker().failureRatio()) {
breakerHelper.setState(State.OPEN_MP);
breakerOpening = true;
}
}
// HALF_OPEN_MP -> OPEN_MP
if (hasFailed) {
if (breakerHelper.getState() == State.HALF_OPEN_MP) {
breakerHelper.setState(State.OPEN_MP);
}
updateMetricsAfter(throwable, wasBreakerOpen, isClosedNow, breakerOpening);
logCircuitBreakerState("Exit 2");
throw ExceptionUtil.toWrappedException(throwable);
}
// Otherwise, increment success count
breakerHelper.incSuccessCount();
// HALF_OPEN_MP -> CLOSED_MP
if (breakerHelper.getState() == State.HALF_OPEN_MP) {
if (breakerHelper.getSuccessCount() == introspector.getCircuitBreaker().successThreshold()) {
breakerHelper.setState(State.CLOSED_MP);
breakerHelper.resetCommandData();
lockRemoved = true;
isClosedNow = true;
}
}
updateMetricsAfter(throwable, wasBreakerOpen, isClosedNow, breakerOpening);
}
// Untrack invocation in a bulkhead
if (introspector.hasBulkhead()) {
bulkheadHelper.untrackInvocation(this);
}
// Display circuit breaker state at exit
logCircuitBreakerState("Exit 3");
// Outcome of execution
if (throwable != null) {
throw ExceptionUtil.toWrappedException(throwable);
} else {
return result;
}
} finally {
// Free lock unless command data was reset
if (introspector.hasCircuitBreaker() && !lockRemoved) {
breakerHelper.unlock();
}
}
} | #vulnerable code
@Override
public Object execute() {
// Configure command before execution
introspector.getHystrixProperties()
.entrySet()
.forEach(entry -> setProperty(entry.getKey(), entry.getValue()));
// Ensure our internal state is consistent with Hystrix
if (introspector.hasCircuitBreaker()) {
breakerHelper.ensureConsistentState();
LOGGER.info("Enter: breaker for " + getCommandKey() + " in state " + breakerHelper.getState());
}
// Record state of breaker
boolean wasBreakerOpen = isCircuitBreakerOpen();
// Track invocation in a bulkhead
if (introspector.hasBulkhead()) {
bulkheadHelper.trackInvocation(this);
}
// Execute command
Object result = null;
Throwable throwable = null;
long startNanos = System.nanoTime();
try {
result = super.execute();
} catch (Throwable t) {
throwable = t;
}
executionTime = System.nanoTime() - startNanos;
boolean hasFailed = (throwable != null);
if (introspector.hasCircuitBreaker()) {
// Keep track of failure ratios
breakerHelper.pushResult(throwable == null);
// Query breaker states
boolean breakerWillOpen = false;
boolean isClosedNow = !isCircuitBreakerOpen();
/*
* Special logic for MP circuit breakers to support failOn. If not a
* throwable to fail on, restore underlying breaker and return.
*/
if (hasFailed) {
final Throwable throwableFinal = throwable;
Class<? extends Throwable>[] throwableClasses = introspector.getCircuitBreaker().failOn();
boolean failOn = Arrays.asList(throwableClasses)
.stream()
.anyMatch(c -> c.isAssignableFrom(throwableFinal.getClass()));
if (!failOn) {
restoreBreaker(); // clears Hystrix counters
updateMetricsAfter(throwable, wasBreakerOpen, isClosedNow, breakerWillOpen);
throw ExceptionUtil.toWrappedException(throwable);
}
}
/*
* Special logic for MP circuit breakers to support an arbitrary success
* threshold used to return a breaker back to its CLOSED state. Hystrix
* only supports a threshold of 1 here, so additional logic is required.
*/
synchronized (breakerHelper.getSyncObject()) {
// If failure ratio exceeded, then switch state to OPEN_MP
if (breakerHelper.getState() == CircuitBreakerHelper.State.CLOSED_MP) {
double failureRatio = breakerHelper.getFailureRatio();
if (failureRatio >= introspector.getCircuitBreaker().failureRatio()) {
breakerWillOpen = true;
breakerHelper.setState(CircuitBreakerHelper.State.OPEN_MP);
runTripBreaker();
}
}
// If latest run failed, may need to switch state to OPEN_MP
if (hasFailed) {
if (breakerHelper.getState() == CircuitBreakerHelper.State.HALF_OPEN_MP) {
// If failed and in HALF_OPEN_MP, we need to force breaker to open
runTripBreaker();
breakerHelper.setState(CircuitBreakerHelper.State.OPEN_MP);
}
updateMetricsAfter(throwable, wasBreakerOpen, isClosedNow, breakerWillOpen);
throw ExceptionUtil.toWrappedException(throwable);
}
// Check next state of breaker based on outcome
if (wasBreakerOpen && isClosedNow) {
// Last called was successful
breakerHelper.incSuccessCount();
// We stay in HALF_OPEN_MP until successThreshold is reached
if (breakerHelper.getSuccessCount() < introspector.getCircuitBreaker().successThreshold()) {
breakerHelper.setState(CircuitBreakerHelper.State.HALF_OPEN_MP);
} else {
breakerHelper.setState(CircuitBreakerHelper.State.CLOSED_MP);
breakerHelper.resetCommandData();
}
}
}
updateMetricsAfter(throwable, wasBreakerOpen, isClosedNow, breakerWillOpen);
}
// Untrack invocation in a bulkhead
if (introspector.hasBulkhead()) {
bulkheadHelper.untrackInvocation(this);
}
// Display circuit breaker state at exit
if (introspector.hasCircuitBreaker()) {
LOGGER.info("Exit: breaker for " + getCommandKey() + " in state " + breakerHelper.getState());
}
// Outcome of execution
if (throwable != null) {
throw ExceptionUtil.toWrappedException(throwable);
} else {
return result;
}
}
#location 37
#vulnerability type THREAD_SAFETY_VIOLATION | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Override
public Object execute() {
// Configure command before execution
introspector.getHystrixProperties()
.entrySet()
.forEach(entry -> setProperty(entry.getKey(), entry.getValue()));
// Ensure our internal state is consistent with Hystrix
if (introspector.hasCircuitBreaker()) {
breakerHelper.ensureConsistentState();
LOGGER.info("Circuit breaker for " + getCommandKey() + " in state " + breakerHelper.getState());
}
// Record state of breaker
boolean wasBreakerOpen = isCircuitBreakerOpen();
// Track invocation in a bulkhead
if (introspector.hasBulkhead()) {
bulkheadHelper.trackInvocation(this);
}
// Execute command
Object result = null;
Throwable throwable = null;
long startNanos = System.nanoTime();
try {
result = super.execute();
} catch (Throwable t) {
throwable = t;
}
executionTime = System.nanoTime() - startNanos;
boolean hasFailed = (throwable != null);
if (introspector.hasCircuitBreaker()) {
// Keep track of failure ratios
breakerHelper.pushResult(throwable == null);
// Query breaker states
boolean breakerWillOpen = false;
boolean isClosedNow = !isCircuitBreakerOpen();
/*
* Special logic for MP circuit breakers to support failOn. If not a
* throwable to fail on, restore underlying breaker and return.
*/
if (hasFailed) {
final Throwable throwableFinal = throwable;
Class<? extends Throwable>[] throwableClasses = introspector.getCircuitBreaker().failOn();
boolean failOn = Arrays.asList(throwableClasses)
.stream()
.anyMatch(c -> c.isAssignableFrom(throwableFinal.getClass()));
if (!failOn) {
restoreBreaker(); // clears Hystrix counters
updateMetricsAfter(throwable, wasBreakerOpen, breakerWillOpen);
throw ExceptionUtil.wrapThrowable(throwable);
}
}
/*
* Special logic for MP circuit breakers to support an arbitrary success
* threshold use to return a breaker back to its CLOSED state. Hystrix
* only supports a threshold of 1 here, so additional logic is required.
*/
synchronized (breakerHelper.getSyncObject()) {
if (hasFailed) {
if (breakerHelper.getState() == CircuitBreakerHelper.State.HALF_OPEN_MP) {
// If failed and in HALF_OPEN_MP, we need to force breaker to open
runTripBreaker();
breakerHelper.setState(CircuitBreakerHelper.State.OPEN_MP);
} else if (breakerHelper.getState() == CircuitBreakerHelper.State.CLOSED_MP) {
// Determine if breaker will open given failure ratio
double failureRatio = breakerHelper.getFailureRatio();
if (failureRatio >= introspector.getCircuitBreaker().failureRatio()) {
breakerWillOpen = true;
breakerHelper.setState(CircuitBreakerHelper.State.OPEN_MP);
}
}
updateMetricsAfter(throwable, wasBreakerOpen, breakerWillOpen);
throw ExceptionUtil.wrapThrowable(throwable);
}
if (wasBreakerOpen && isClosedNow) {
// Last called was successful
breakerHelper.incSuccessCount();
// We stay in HALF_OPEN_MP until successThreshold is reached
if (breakerHelper.getSuccessCount() < introspector.getCircuitBreaker().successThreshold()) {
breakerHelper.setState(CircuitBreakerHelper.State.HALF_OPEN_MP);
} else {
breakerHelper.setState(CircuitBreakerHelper.State.CLOSED_MP);
breakerHelper.resetCommandData();
}
}
}
updateMetricsAfter(throwable, wasBreakerOpen, breakerWillOpen);
}
// Untrack invocation in a bulkhead
if (introspector.hasBulkhead()) {
bulkheadHelper.untrackInvocation(this);
}
// Outcome of execution
if (throwable != null) {
throw ExceptionUtil.wrapThrowable(throwable);
} else {
return result;
}
} | #vulnerable code
@Override
public Object execute() {
// Configure command before execution
introspector.getHystrixProperties()
.entrySet()
.forEach(entry -> setProperty(entry.getKey(), entry.getValue()));
// Ensure our internal state is consistent with Hystrix
if (introspector.hasCircuitBreaker()) {
breakerHelper.ensureConsistentState();
LOGGER.info("Circuit breaker for " + getCommandKey() + " in state " + breakerHelper.getState());
}
// Record state of breaker
boolean wasBreakerOpen = isCircuitBreakerOpen();
// Execute command
Object result = null;
Throwable throwable = null;
long startNanos = System.nanoTime();
try {
result = super.execute();
} catch (Throwable t) {
throwable = t;
}
executionTime = System.nanoTime() - startNanos;
boolean hasFailed = (throwable != null);
if (introspector.hasCircuitBreaker()) {
// Keep track of failure ratios
breakerHelper.pushResult(throwable == null);
// Query breaker states
boolean breakerWillOpen = false;
boolean isClosedNow = !isCircuitBreakerOpen();
/*
* Special logic for MP circuit breakers to support failOn. If not a
* throwable to fail on, restore underlying breaker and return.
*/
if (hasFailed) {
final Throwable throwableFinal = throwable;
Class<? extends Throwable>[] throwableClasses = introspector.getCircuitBreaker().failOn();
boolean failOn = Arrays.asList(throwableClasses)
.stream()
.anyMatch(c -> c.isAssignableFrom(throwableFinal.getClass()));
if (!failOn) {
restoreBreaker(); // clears Hystrix counters
updateMetricsAfter(throwable, wasBreakerOpen, breakerWillOpen);
throw ExceptionUtil.wrapThrowable(throwable);
}
}
/*
* Special logic for MP circuit breakers to support an arbitrary success
* threshold use to return a breaker back to its CLOSED state. Hystrix
* only supports a threshold of 1 here, so additional logic is required.
*/
synchronized (breakerHelper.getSyncObject()) {
if (hasFailed) {
if (breakerHelper.getState() == CircuitBreakerHelper.State.HALF_OPEN_MP) {
// If failed and in HALF_OPEN_MP, we need to force breaker to open
runTripBreaker();
breakerHelper.setState(CircuitBreakerHelper.State.OPEN_MP);
} else if (breakerHelper.getState() == CircuitBreakerHelper.State.CLOSED_MP) {
// Determine if breaker will open given failure ratio
double failureRatio = breakerHelper.getFailureRatio();
if (failureRatio >= introspector.getCircuitBreaker().failureRatio()) {
breakerWillOpen = true;
breakerHelper.setState(CircuitBreakerHelper.State.OPEN_MP);
}
}
updateMetricsAfter(throwable, wasBreakerOpen, breakerWillOpen);
throw ExceptionUtil.wrapThrowable(throwable);
}
if (wasBreakerOpen && isClosedNow) {
// Last called was successful
breakerHelper.incSuccessCount();
// We stay in HALF_OPEN_MP until successThreshold is reached
if (breakerHelper.getSuccessCount() < introspector.getCircuitBreaker().successThreshold()) {
breakerHelper.setState(CircuitBreakerHelper.State.HALF_OPEN_MP);
} else {
breakerHelper.setState(CircuitBreakerHelper.State.CLOSED_MP);
breakerHelper.resetCommandData();
}
}
}
updateMetricsAfter(throwable, wasBreakerOpen, breakerWillOpen);
}
// Update bulkhead helper
if (introspector.hasBulkhead()) {
bulkheadHelper.removeCommand(this);
}
// Outcome of execution
if (throwable != null) {
throw ExceptionUtil.wrapThrowable(throwable);
} else {
return result;
}
}
#location 31
#vulnerability type THREAD_SAFETY_VIOLATION | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
protected void starting(Class<?> testClass, String testName) {
PARAMETERS_THREAD_LOCAL.set(sharedMutator.getEffectiveParameters(testClass, testName,
getDriverLifecycle()));
SharedWebDriver sharedWebDriver = getTestDriver(testClass, testName,
this::newWebDriver, this::failed,
getConfiguration(), PARAMETERS_THREAD_LOCAL.get());
setTestClassAndMethodValues(PARAMETERS_THREAD_LOCAL, TEST_CLASS, TEST_METHOD_NAME);
initFluent(sharedWebDriver.getDriver());
} | #vulnerable code
protected void starting(Class<?> testClass, String testName) {
PARAMETERS_THREAD_LOCAL.set(sharedMutator.getEffectiveParameters(testClass, testName,
getDriverLifecycle()));
SharedWebDriver sharedWebDriver;
try {
sharedWebDriver = SharedWebDriverContainer.INSTANCE.getSharedWebDriver(
PARAMETERS_THREAD_LOCAL.get(), null, this::newWebDriver, getConfiguration());
} catch (ExecutionException | InterruptedException e) {
this.failed(null, testClass, testName);
String causeMessage = getCauseMessage(e);
throw new WebDriverException("Browser failed to start, test [ " + testName + " ] execution interrupted."
+ (isEmpty(causeMessage) ? "" : "\nCaused by: [ " + causeMessage + "]"), e);
}
setTestClassAndMethodValues(PARAMETERS_THREAD_LOCAL, TEST_CLASS, TEST_METHOD_NAME);
initFluent(sharedWebDriver.getDriver());
}
#location 8
#vulnerability type NULL_DEREFERENCE | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
static String checkModelForParametrizedValue(String seleniumVersion, Model model) {
String version = getNamePropertyName(seleniumVersion);
if (nonNull(model.getProperties())) {
return model.getProperties().getProperty(version);
} else if (nonNull(System.getProperty(version))) {
return System.getProperty(version);
} else if (nonNull(model.getProfiles()) && model.getProfiles().size() > 0) {
return getVersionNameFromProfiles(version, model);
} else {
return null;
}
} | #vulnerable code
static String checkModelForParametrizedValue(String seleniumVersion, Model model) {
String version = getNamePropertyName(seleniumVersion);
String versionProp = null;
if (nonNull(seleniumVersion) && nonNull(model.getProperties())) {
versionProp = model.getProperties().getProperty(version);
} else if (nonNull(seleniumVersion) && nonNull(System.getProperty(version))) {
versionProp = System.getProperty(version);
} else if (nonNull(seleniumVersion) && nonNull(model.getProfiles()) && model.getProfiles().size() > 0) {
versionProp = model.getProfiles().stream()
.filter(prof ->
nonNull(prof.getProperties()) && nonNull(prof.getProperties().getProperty(version)))
.findAny()
.map(prof -> prof.getProperties().getProperty(version))
.orElse(null);
}
return versionProp;
}
#location 8
#vulnerability type NULL_DEREFERENCE | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Override
public void reset() {
proxyResultHolder.setResult(null);
} | #vulnerable code
@Override
public void reset() {
result = null;
}
#location 3
#vulnerability type THREAD_SAFETY_VIOLATION | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
protected void starting(Class<?> testClass, String testName) {
SharedDriverStrategy strategy = sdsr.getSharedDriverStrategy(testClass, testName);
if (strategy == SharedDriverStrategy.ONCE) {
synchronized (FluentTestRunnerAdapter.class) {
if (sharedDriver == null) {
initFluent(getDefaultDriver()).withDefaultUrl(getDefaultBaseUrl());
sharedDriver = getDriver();
Runtime.getRuntime().addShutdownHook(new SharedDriverOnceShutdownHook("SharedDriver-ONCE-ShutdownHook"));
} else {
initFluent(sharedDriver).withDefaultUrl(getDefaultBaseUrl());
}
}
} else if (strategy == SharedDriverStrategy.PER_CLASS) {
synchronized (FluentTestRunnerAdapter.class) {
if (!isSharedDriverPerClass) {
initFluent(getDefaultDriver()).withDefaultUrl(getDefaultBaseUrl());
sharedDriver = getDriver();
isSharedDriverPerClass = true;
} else {
initFluent(sharedDriver).withDefaultUrl(getDefaultBaseUrl());
}
}
} else {
initFluent(getDefaultDriver()).withDefaultUrl(getDefaultBaseUrl());
}
} | #vulnerable code
protected void starting(Class<?> testClass, String testName) {
SharedDriverStrategy strategy = sdsr.getSharedDriverStrategy(testClass, testName);
if (strategy == SharedDriverStrategy.ONCE) {
synchronized (this) {
if (sharedDriver == null) {
initFluent(getDefaultDriver()).withDefaultUrl(getDefaultBaseUrl());
sharedDriver = getDriver();
Runtime.getRuntime().addShutdownHook(new SharedDriverOnceShutdownHook("SharedDriver-ONCE-ShutdownHook"));
} else {
initFluent(sharedDriver).withDefaultUrl(getDefaultBaseUrl());
}
}
} else if (strategy == SharedDriverStrategy.PER_CLASS) {
synchronized (this) {
if (!isSharedDriverPerClass) {
initFluent(getDefaultDriver()).withDefaultUrl(getDefaultBaseUrl());
sharedDriver = getDriver();
isSharedDriverPerClass = true;
} else {
initFluent(sharedDriver).withDefaultUrl(getDefaultBaseUrl());
}
}
} else {
initFluent(getDefaultDriver()).withDefaultUrl(getDefaultBaseUrl());
}
init();
}
#location 7
#vulnerability type THREAD_SAFETY_VIOLATION | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
protected void starting(Class<?> testClass, String testName) {
PARAMETERS_THREAD_LOCAL.set(sharedMutator.getEffectiveParameters(testClass, testName,
getDriverLifecycle()));
SharedWebDriver sharedWebDriver = getTestDriver(testClass, testName,
this::newWebDriver, this::failed,
getConfiguration(), PARAMETERS_THREAD_LOCAL.get());
setTestClassAndMethodValues(PARAMETERS_THREAD_LOCAL, TEST_CLASS, TEST_METHOD_NAME);
initFluent(sharedWebDriver.getDriver());
} | #vulnerable code
protected void starting(Class<?> testClass, String testName) {
PARAMETERS_THREAD_LOCAL.set(sharedMutator.getEffectiveParameters(testClass, testName,
getDriverLifecycle()));
SharedWebDriver sharedWebDriver;
try {
sharedWebDriver = SharedWebDriverContainer.INSTANCE.getSharedWebDriver(
PARAMETERS_THREAD_LOCAL.get(), null, this::newWebDriver, getConfiguration());
} catch (ExecutionException | InterruptedException e) {
this.failed(testClass, testName);
String causeMessage = getCauseMessage(e);
throw new WebDriverException("Browser failed to start, test [ " + testName + " ] execution interrupted."
+ (isEmpty(causeMessage) ? "" : "\nCaused by: [ " + causeMessage + "]"), e);
}
setTestClassAndMethodValues(PARAMETERS_THREAD_LOCAL, TEST_CLASS, TEST_METHOD_NAME);
initFluent(sharedWebDriver.getDriver());
}
#location 8
#vulnerability type NULL_DEREFERENCE | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Override
public boolean loaded() {
return proxyResultHolder.isResultLoaded();
} | #vulnerable code
@Override
public boolean loaded() {
return result != null;
}
#location 3
#vulnerability type THREAD_SAFETY_VIOLATION | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
protected void starting(Class<?> testClass, String testName) {
PARAMETERS_THREAD_LOCAL.set(sharedMutator.getEffectiveParameters(testClass, testName,
getDriverLifecycle()));
SharedWebDriver sharedWebDriver;
try {
sharedWebDriver = getSharedWebDriver(PARAMETERS_THREAD_LOCAL.get(), null);
} catch (ExecutionException | InterruptedException e) {
this.failed(null, testClass, testName);
String causeMessage = getCauseMessage(e);
throw new WebDriverException("Browser failed to start, test [ " + testName + " ] execution interrupted."
+ (isEmpty(causeMessage) ? "" : "\nCaused by: [ " + causeMessage + "]"), e);
}
setTestClassAndMethodValues();
initFluent(sharedWebDriver.getDriver());
} | #vulnerable code
protected void starting(Class<?> testClass, String testName) {
PARAMETERS_THREAD_LOCAL.set(sharedMutator.getEffectiveParameters(testClass, testName,
getDriverLifecycle()));
SharedWebDriver sharedWebDriver;
try {
sharedWebDriver = getSharedWebDriver(PARAMETERS_THREAD_LOCAL.get());
} catch (ExecutionException | InterruptedException e) {
this.failed(null, testClass, testName);
String causeMessage = getCauseMessage(e);
throw new WebDriverException("Browser failed to start, test [ " + testName + " ] execution interrupted."
+ (isEmpty(causeMessage) ? "" : "\nCaused by: [ " + causeMessage + "]"), e);
}
initFluent(sharedWebDriver.getDriver());
}
#location 18
#vulnerability type NULL_DEREFERENCE | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Override
public boolean loaded() {
return result != null;
} | #vulnerable code
@Override
public boolean loaded() {
return proxyResultHolder.isResultLoaded();
}
#location 3
#vulnerability type THREAD_SAFETY_VIOLATION | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
protected void starting(Class<?> testClass, String testName) {
PARAMETERS_THREAD_LOCAL.set(sharedMutator.getEffectiveParameters(testClass, testName,
getDriverLifecycle()));
SharedWebDriver sharedWebDriver;
try {
sharedWebDriver = getSharedWebDriver(PARAMETERS_THREAD_LOCAL.get(), null);
} catch (ExecutionException | InterruptedException e) {
this.failed(testClass, testName);
String causeMessage = getCauseMessage(e);
throw new WebDriverException("Browser failed to start, test [ " + testName + " ] execution interrupted."
+ (isEmpty(causeMessage) ? "" : "\nCaused by: [ " + causeMessage + "]"), e);
}
setTestClassAndMethodValues();
initFluent(sharedWebDriver.getDriver());
} | #vulnerable code
protected void starting(Class<?> testClass, String testName) {
PARAMETERS_THREAD_LOCAL.set(sharedMutator.getEffectiveParameters(testClass, testName,
getDriverLifecycle()));
SharedWebDriver sharedWebDriver;
try {
sharedWebDriver = getSharedWebDriver(PARAMETERS_THREAD_LOCAL.get());
} catch (ExecutionException | InterruptedException e) {
this.failed(testClass, testName);
String causeMessage = getCauseMessage(e);
throw new WebDriverException("Browser failed to start, test [ " + testName + " ] execution interrupted."
+ (isEmpty(causeMessage) ? "" : "\nCaused by: [ " + causeMessage + "]"), e);
}
initFluent(sharedWebDriver.getDriver());
}
#location 17
#vulnerability type NULL_DEREFERENCE | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Override
@SuppressWarnings({"PMD.StdCyclomaticComplexity", "PMD.CyclomaticComplexity", "PMD.ModifiedCyclomaticComplexity",
"PMD.NPathComplexity"})
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
if (TO_STRING.equals(method)) {
return proxyToString(!loaded() ? null : (String) invoke(method, args));
}
if (!loaded()) {
if (EQUALS.equals(method)) {
LocatorHandler otherLocatorHandler = LocatorProxies.getLocatorHandler(args[0]);
if (otherLocatorHandler != null) {
if (!otherLocatorHandler.loaded() || args[0] == null) {
return equals(otherLocatorHandler);
} else {
return args[0].equals(proxy);
}
}
}
if (HASH_CODE.equals(method)) {
return HASH_CODE_SEED + locator.hashCode();
}
}
if (EQUALS.equals(method)) {
LocatorHandler otherLocatorHandler = LocatorProxies.getLocatorHandler(args[0]);
if (otherLocatorHandler != null && !otherLocatorHandler.loaded()) {
otherLocatorHandler.now();
return otherLocatorHandler.equals(this);
}
}
getLocatorResult();
return invokeWithRetry(method, args);
} | #vulnerable code
@Override
@SuppressWarnings({"PMD.StdCyclomaticComplexity", "PMD.CyclomaticComplexity", "PMD.ModifiedCyclomaticComplexity",
"PMD.NPathComplexity"})
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
if (TO_STRING.equals(method)) {
return proxyToString(result == null ? null : (String) invoke(method, args));
}
if (result == null) {
if (EQUALS.equals(method)) {
LocatorHandler otherLocatorHandler = LocatorProxies.getLocatorHandler(args[0]);
if (otherLocatorHandler != null) {
if (!otherLocatorHandler.loaded() || args[0] == null) {
return equals(otherLocatorHandler);
} else {
return args[0].equals(proxy);
}
}
}
if (HASH_CODE.equals(method)) {
return HASH_CODE_SEED + locator.hashCode();
}
}
if (EQUALS.equals(method)) {
LocatorHandler otherLocatorHandler = LocatorProxies.getLocatorHandler(args[0]);
if (otherLocatorHandler != null && !otherLocatorHandler.loaded()) {
otherLocatorHandler.now();
return otherLocatorHandler.equals(this);
}
}
getLocatorResult();
return invokeWithRetry(method, args);
}
#location 8
#vulnerability type THREAD_SAFETY_VIOLATION | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Override
public void reset() {
result = null;
} | #vulnerable code
@Override
public void reset() {
proxyResultHolder.setResult(null);
}
#location 3
#vulnerability type THREAD_SAFETY_VIOLATION | Below is the vulnerable code, please generate the patch based on the following information. |
Subsets and Splits