input
stringlengths 205
73.3k
| output
stringlengths 64
73.2k
| instruction
stringclasses 1
value |
---|---|---|
#vulnerable code
@Test
public void testCreatePool() throws SQLException, ClassNotFoundException {
BoneCPConfig mockConfig = createNiceMock(BoneCPConfig.class);
expect(mockConfig.getPartitionCount()).andReturn(1).anyTimes();
expect(mockConfig.getMaxConnectionsPerPartition()).andReturn(1).anyTimes();
expect(mockConfig.getMinConnectionsPerPartition()).andReturn(1).anyTimes();
expect(mockConfig.getIdleConnectionTestPeriodInMinutes()).andReturn(100L).anyTimes();
expect(mockConfig.getUsername()).andReturn("somethingbad").anyTimes();
expect(mockConfig.getPassword()).andReturn("somethingbad").anyTimes();
expect(mockConfig.getJdbcUrl()).andReturn("invalid").anyTimes();
// expect(mockConfig.getReleaseHelperThreads()).andReturn(1).once().andReturn(0).anyTimes();
replay(mockConfig);
try{
testClass.createPool(mockConfig);
fail("Should throw an exception");
} catch (RuntimeException e){
// do nothing
}
verify(mockConfig);
reset(mockConfig);
Class.forName(DRIVER);
mockConfig = createNiceMock(BoneCPConfig.class);
expect(mockConfig.getPartitionCount()).andReturn(1).anyTimes();
expect(mockConfig.getMaxConnectionsPerPartition()).andReturn(1).anyTimes();
expect(mockConfig.getMinConnectionsPerPartition()).andReturn(1).anyTimes();
expect(mockConfig.getIdleConnectionTestPeriodInMinutes()).andReturn(100L).anyTimes();
expect(mockConfig.getUsername()).andReturn(USERNAME).anyTimes();
expect(mockConfig.getPassword()).andReturn(PASSWORD).anyTimes();
expect(mockConfig.getJdbcUrl()).andReturn(URL).anyTimes();
replay(mockConfig);
try{
testClass.createPool(mockConfig);
} catch (RuntimeException e){
fail("Should pass");
}
verify(mockConfig);
}
#location 15
#vulnerability type RESOURCE_LEAK | #fixed code
@Test
public void testCreatePool() throws SQLException, ClassNotFoundException, CloneNotSupportedException {
BoneCPConfig mockConfig = createNiceMock(BoneCPConfig.class);
expect(mockConfig.getPartitionCount()).andReturn(1).anyTimes();
expect(mockConfig.getMaxConnectionsPerPartition()).andReturn(1).anyTimes();
expect(mockConfig.getMinConnectionsPerPartition()).andReturn(1).anyTimes();
expect(mockConfig.getIdleConnectionTestPeriodInMinutes()).andReturn(100L).anyTimes();
expect(mockConfig.getUsername()).andReturn("somethingbad").anyTimes();
expect(mockConfig.getPassword()).andReturn("somethingbad").anyTimes();
expect(mockConfig.getJdbcUrl()).andReturn("invalid").anyTimes();
// expect(mockConfig.getReleaseHelperThreads()).andReturn(1).once().andReturn(0).anyTimes();
replay(mockConfig);
try{
testClass.createPool(mockConfig);
fail("Should throw an exception");
} catch (RuntimeException e){
// do nothing
}
verify(mockConfig);
reset(mockConfig);
Class.forName(DRIVER);
mockConfig = createNiceMock(BoneCPConfig.class);
expect(mockConfig.getPartitionCount()).andReturn(1).anyTimes();
expect(mockConfig.getMaxConnectionsPerPartition()).andReturn(1).anyTimes();
expect(mockConfig.getMinConnectionsPerPartition()).andReturn(1).anyTimes();
expect(mockConfig.getIdleConnectionTestPeriodInMinutes()).andReturn(100L).anyTimes();
expect(mockConfig.getUsername()).andReturn(USERNAME).anyTimes();
expect(mockConfig.getPassword()).andReturn(PASSWORD).anyTimes();
expect(mockConfig.getJdbcUrl()).andReturn(URL).anyTimes();
expect(mockConfig.isLazyInit()).andReturn(false).anyTimes();
expect(mockConfig.clone()).andReturn(mockConfig).anyTimes();
replay(mockConfig);
try{
testClass.createPool(mockConfig);
} catch (RuntimeException e){
fail("Should pass: ");
}
verify(mockConfig);
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Test
public void initializer_same_key() {
App app = new App();
final AtomicBoolean called = new AtomicBoolean(false);
assertThat(called.get(), is(false));
app.initializer("foo", (theApp) -> {
called.set(true);
});
app.initializer("foo", (theApp) -> {
});
app.initialize();
assertThat(called.get(), is(false));
}
#location 12
#vulnerability type RESOURCE_LEAK | #fixed code
@Test
public void initializer_same_key() {
App app = new App(AppConfig.builder().signingSecret("secret").build());
final AtomicBoolean called = new AtomicBoolean(false);
assertThat(called.get(), is(false));
app.initializer("foo", (theApp) -> {
called.set(true);
});
app.initializer("foo", (theApp) -> {
});
app.initialize();
assertThat(called.get(), is(false));
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
public Request<?> toSlackRequest(HttpRequest<?> req, LinkedHashMap<String, String> body) {
String requestBody = body.entrySet().stream().map(e -> {
try {
String k = URLEncoder.encode(e.getKey(), "UTF-8");
String v = URLEncoder.encode(e.getValue(), "UTF-8");
return k + "=" + v;
} catch (UnsupportedEncodingException ex) {
return e.getKey() + "=" + e.getValue();
}
}).collect(Collectors.joining("&"));
RequestHeaders headers = new RequestHeaders(flatten(req.getHeaders().asMap()));
SlackRequestParser.HttpRequest rawRequest = SlackRequestParser.HttpRequest.builder()
.requestUri(req.getPath())
.queryString(flatten(req.getParameters().asMap()))
.headers(headers)
.requestBody(requestBody)
.remoteAddress(toString(req.getRemoteAddress().getAddress().getAddress()))
.build();
return requestParser.parse(rawRequest);
}
#location 11
#vulnerability type NULL_DEREFERENCE | #fixed code
public Request<?> toSlackRequest(HttpRequest<?> req, LinkedHashMap<String, String> body) {
String requestBody = body.entrySet().stream().map(e -> {
try {
String k = URLEncoder.encode(e.getKey(), "UTF-8");
String v = URLEncoder.encode(e.getValue(), "UTF-8");
return k + "=" + v;
} catch (UnsupportedEncodingException ex) {
return e.getKey() + "=" + e.getValue();
}
}).collect(Collectors.joining("&"));
RequestHeaders headers = new RequestHeaders(req.getHeaders().asMap());
SlackRequestParser.HttpRequest rawRequest = SlackRequestParser.HttpRequest.builder()
.requestUri(req.getPath())
.queryString(flatten(req.getParameters().asMap()))
.headers(headers)
.requestBody(requestBody)
.remoteAddress(toString(req.getRemoteAddress().getAddress().getAddress()))
.build();
return requestParser.parse(rawRequest);
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Test
public void rtmStart() throws Exception {
// TODO: "prefs" support
SlackConfig config = new SlackConfig();
config.setLibraryMaintainerMode(false);
config.getHttpClientResponseHandlers().add(new JsonDataRecordingListener());
Slack slack = Slack.getInstance(config);
String channelName = "test" + System.currentTimeMillis();
TestChannelGenerator channelGenerator = new TestChannelGenerator(testConfig, channelCreationToken);
Conversation channel = channelGenerator.createNewPublicChannel(channelName);
try {
String channelId = channel.getId();
// need to invite the bot user to the created channel before starting an RTM session
inviteBotUser(channelId);
Thread.sleep(3000);
try (RTMClient rtm = slack.rtmStart(botToken)) {
User user = rtm.getConnectedBotUser();
assertThat(user.getId(), is(notNullValue()));
assertThat(user.getTeamId(), is(notNullValue()));
assertThat(user.getName(), is(notNullValue()));
assertThat(user.getProfile(), is(notNullValue()));
assertThat(user.getProfile().getBotId(), is(notNullValue()));
verifyRTMClientBehavior(channelId, rtm);
}
} finally {
channelGenerator.archiveChannel(channel);
}
}
#location 32
#vulnerability type RESOURCE_LEAK | #fixed code
@Test
public void rtmStart() throws Exception {
// TODO: "prefs" support
SlackConfig config = new SlackConfig();
config.setLibraryMaintainerMode(false);
config.getHttpClientResponseHandlers().add(new JsonDataRecordingListener());
Slack slack = Slack.getInstance(config);
String channelName = "test" + System.currentTimeMillis();
TestChannelGenerator channelGenerator = new TestChannelGenerator(testConfig, channelCreationToken);
Conversation channel = channelGenerator.createNewPublicChannel(channelName);
try {
String channelId = channel.getId();
// need to invite the bot user to the created channel before starting an RTM session
inviteBotUser(channelId);
Thread.sleep(3000);
try (RTMClient rtm = slack.rtmStart(classicAppBotToken)) {
User user = rtm.getConnectedBotUser();
assertThat(user.getId(), is(notNullValue()));
assertThat(user.getTeamId(), is(notNullValue()));
assertThat(user.getName(), is(notNullValue()));
assertThat(user.getProfile(), is(notNullValue()));
assertThat(user.getProfile().getBotId(), is(notNullValue()));
verifyRTMClientBehavior(channelId, rtm);
}
} finally {
channelGenerator.archiveChannel(channel);
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Override
public Bot findBot(String enterpriseId, String teamId) {
AmazonS3 s3 = this.createS3Client();
String fullKey = getBotKey(enterpriseId, teamId);
if (isHistoricalDataEnabled()) {
fullKey = fullKey + "-latest";
}
if (s3.getObjectMetadata(bucketName, fullKey) == null && enterpriseId != null) {
String nonGridKey = getBotKey(null, teamId);
if (isHistoricalDataEnabled()) {
nonGridKey = nonGridKey + "-latest";
}
S3Object nonGridObject = s3.getObject(bucketName, nonGridKey);
if (nonGridObject != null) {
try {
Bot bot = toBot(nonGridObject);
bot.setEnterpriseId(enterpriseId); // the workspace seems to be in a Grid org now
save(s3, fullKey, JsonOps.toJsonString(bot), "AWS S3 putObject result of Bot data - {}");
return bot;
} catch (Exception e) {
log.error("Failed to save a new Bot data for enterprise_id: {}, team_id: {}", enterpriseId, teamId);
}
}
}
S3Object s3Object = s3.getObject(bucketName, fullKey);
try {
return toBot(s3Object);
} catch (IOException e) {
log.error("Failed to load Bot data for enterprise_id: {}, team_id: {}", enterpriseId, teamId);
return null;
}
}
#location 27
#vulnerability type NULL_DEREFERENCE | #fixed code
@Override
public Bot findBot(String enterpriseId, String teamId) {
AmazonS3 s3 = this.createS3Client();
String fullKey = getBotKey(enterpriseId, teamId);
if (isHistoricalDataEnabled()) {
fullKey = fullKey + "-latest";
}
if (getObjectMetadata(s3, fullKey) == null && enterpriseId != null) {
String nonGridKey = getBotKey(null, teamId);
if (isHistoricalDataEnabled()) {
nonGridKey = nonGridKey + "-latest";
}
S3Object nonGridObject = getObject(s3, nonGridKey);
if (nonGridObject != null) {
try {
Bot bot = toBot(nonGridObject);
bot.setEnterpriseId(enterpriseId); // the workspace seems to be in a Grid org now
save(s3, fullKey, JsonOps.toJsonString(bot), "AWS S3 putObject result of Bot data - {}");
return bot;
} catch (Exception e) {
log.error("Failed to save a new Bot data for enterprise_id: {}, team_id: {}", enterpriseId, teamId);
}
}
}
S3Object s3Object = getObject(s3, fullKey);
try {
return toBot(s3Object);
} catch (IOException e) {
log.error("Failed to load Bot data for enterprise_id: {}, team_id: {}", enterpriseId, teamId);
return null;
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Test
public void initializer_start() {
App app = new App();
final AtomicBoolean called = new AtomicBoolean(false);
assertThat(called.get(), is(false));
app.initializer("foo", (theApp) -> {
called.set(true);
});
app.start();
assertThat(called.get(), is(true));
}
#location 10
#vulnerability type RESOURCE_LEAK | #fixed code
@Test
public void initializer_start() {
App app = new App(AppConfig.builder().signingSecret("secret").build());
final AtomicBoolean called = new AtomicBoolean(false);
assertThat(called.get(), is(false));
app.initializer("foo", (theApp) -> {
called.set(true);
});
app.start();
assertThat(called.get(), is(true));
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Test
public void rtmStart() throws Exception {
// TODO: "prefs" support
SlackConfig config = new SlackConfig();
config.setLibraryMaintainerMode(false);
config.getHttpClientResponseHandlers().add(new JsonDataRecordingListener());
Slack slack = Slack.getInstance(config);
String channelName = "test" + System.currentTimeMillis();
TestChannelGenerator channelGenerator = new TestChannelGenerator(testConfig, channelCreationToken);
Conversation channel = channelGenerator.createNewPublicChannel(channelName);
try {
String channelId = channel.getId();
// need to invite the bot user to the created channel before starting an RTM session
inviteBotUser(channelId);
Thread.sleep(3000);
try (RTMClient rtm = slack.rtmStart(botToken)) {
User user = rtm.getConnectedBotUser();
assertThat(user.getId(), is(notNullValue()));
assertThat(user.getTeamId(), is(notNullValue()));
assertThat(user.getName(), is(notNullValue()));
assertThat(user.getProfile(), is(notNullValue()));
assertThat(user.getProfile().getBotId(), is(notNullValue()));
verifyRTMClientBehavior(channelId, rtm);
}
} finally {
channelGenerator.archiveChannel(channel);
}
}
#location 20
#vulnerability type RESOURCE_LEAK | #fixed code
@Test
public void rtmStart() throws Exception {
// TODO: "prefs" support
SlackConfig config = new SlackConfig();
config.setLibraryMaintainerMode(false);
config.getHttpClientResponseHandlers().add(new JsonDataRecordingListener());
Slack slack = Slack.getInstance(config);
String channelName = "test" + System.currentTimeMillis();
TestChannelGenerator channelGenerator = new TestChannelGenerator(testConfig, channelCreationToken);
Conversation channel = channelGenerator.createNewPublicChannel(channelName);
try {
String channelId = channel.getId();
// need to invite the bot user to the created channel before starting an RTM session
inviteBotUser(channelId);
Thread.sleep(3000);
try (RTMClient rtm = slack.rtmStart(classicAppBotToken)) {
User user = rtm.getConnectedBotUser();
assertThat(user.getId(), is(notNullValue()));
assertThat(user.getTeamId(), is(notNullValue()));
assertThat(user.getName(), is(notNullValue()));
assertThat(user.getProfile(), is(notNullValue()));
assertThat(user.getProfile().getBotId(), is(notNullValue()));
verifyRTMClientBehavior(channelId, rtm);
}
} finally {
channelGenerator.archiveChannel(channel);
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Test
public void initializer_called() {
App app = new App();
final AtomicBoolean called = new AtomicBoolean(false);
assertThat(called.get(), is(false));
app.initializer("foo", (theApp) -> {
called.set(true);
});
app.initialize();
assertThat(called.get(), is(true));
}
#location 10
#vulnerability type RESOURCE_LEAK | #fixed code
@Test
public void initializer_called() {
App app = new App(AppConfig.builder().signingSecret("secret").build());
final AtomicBoolean called = new AtomicBoolean(false);
assertThat(called.get(), is(false));
app.initializer("foo", (theApp) -> {
called.set(true);
});
app.initialize();
assertThat(called.get(), is(true));
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Test
public void test() throws Exception {
String channelName = "test" + System.currentTimeMillis();
TestChannelGenerator channelGenerator = new TestChannelGenerator(testConfig, channelCreationToken);
Conversation channel = channelGenerator.createNewPublicChannel(channelName);
try {
String channelId = channel.getId();
// need to invite the bot user to the created channel before starting an RTM session
inviteBotUser(channelId);
RTMEventsDispatcher dispatcher = RTMEventsDispatcherFactory.getInstance();
HelloHandler hello = new HelloHandler();
dispatcher.register(hello);
SubHelloHandler hello2 = new SubHelloHandler();
dispatcher.register(hello2);
dispatcher.register(new UserTypingHandler());
SlackTestConfig testConfig = SlackTestConfig.getInstance();
Slack slack = Slack.getInstance(testConfig.getConfig());
try (RTMClient rtm = slack.rtmConnect(classicAppBotToken)) {
rtm.addMessageHandler(dispatcher.toMessageHandler());
rtm.connect();
Thread.sleep(1000L);
assertThat(hello.counter.get(), is(1));
assertThat(hello2.counter.get(), is(1));
rtm.reconnect();
Thread.sleep(1000L);
assertThat(hello.counter.get(), is(2));
assertThat(hello2.counter.get(), is(2));
dispatcher.deregister(hello);
rtm.reconnect();
Thread.sleep(1000L);
assertThat(hello.counter.get(), is(2)); // should not be incremented
assertThat(hello2.counter.get(), is(3));
}
} finally {
channelGenerator.archiveChannel(channel);
}
}
#location 24
#vulnerability type RESOURCE_LEAK | #fixed code
@Test
public void test() throws Exception {
String channelName = "test" + System.currentTimeMillis();
TestChannelGenerator channelGenerator = new TestChannelGenerator(testConfig, channelCreationToken);
Conversation channel = channelGenerator.createNewPublicChannel(channelName);
try {
String channelId = channel.getId();
// need to invite the bot user to the created channel before starting an RTM session
inviteBotUser(channelId);
RTMEventsDispatcher dispatcher = RTMEventsDispatcherFactory.getInstance();
HelloHandler hello = new HelloHandler();
dispatcher.register(hello);
SubHelloHandler hello2 = new SubHelloHandler();
dispatcher.register(hello2);
dispatcher.register(new UserTypingHandler());
SlackTestConfig testConfig = SlackTestConfig.getInstance();
Slack slack = Slack.getInstance(testConfig.getConfig());
try (RTMClient rtm = slack.rtmConnect(classicAppBotToken)) {
rtm.addMessageHandler(dispatcher.toMessageHandler());
rtm.connect();
Thread.sleep(1000L);
assertThat(hello.counter.get(), is(1));
assertThat(hello2.counter.get(), is(1));
BotMessageHandler bot = new BotMessageHandler();
dispatcher.register(bot);
ChatPostMessageResponse chatPostMessage = slack.methods(classicAppBotToken)
.chatPostMessage(r -> r.channel(channelId).text("Hi!"));
assertThat(chatPostMessage.getError(), is(nullValue()));
Thread.sleep(1000L);
assertThat(bot.counter.get(), is(1));
rtm.reconnect();
Thread.sleep(1000L);
assertThat(hello.counter.get(), is(2));
assertThat(hello2.counter.get(), is(2));
dispatcher.deregister(hello);
rtm.reconnect();
Thread.sleep(1000L);
assertThat(hello.counter.get(), is(2)); // should not be incremented
assertThat(hello2.counter.get(), is(3));
}
} finally {
channelGenerator.archiveChannel(channel);
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Test
public void status() {
App app = new App();
assertThat(app.status(), is(App.Status.Stopped));
app.start();
assertThat(app.status(), is(App.Status.Running));
app.stop();
assertThat(app.status(), is(App.Status.Stopped));
app.start();
assertThat(app.status(), is(App.Status.Running));
app.stop();
assertThat(app.status(), is(App.Status.Stopped));
app.start();
app.start();
assertThat(app.status(), is(App.Status.Running));
}
#location 6
#vulnerability type RESOURCE_LEAK | #fixed code
@Test
public void status() {
App app = new App(AppConfig.builder().signingSecret("secret").build());
assertThat(app.status(), is(App.Status.Stopped));
app.start();
assertThat(app.status(), is(App.Status.Running));
app.stop();
assertThat(app.status(), is(App.Status.Stopped));
app.start();
assertThat(app.status(), is(App.Status.Running));
app.stop();
assertThat(app.status(), is(App.Status.Stopped));
app.start();
app.start();
assertThat(app.status(), is(App.Status.Running));
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Test
public void builder_config() {
App app = new App();
assertNotNull(app.config());
app = app.toBuilder().build();
assertNotNull(app.config());
app = app.toOAuthCallbackApp();
assertNotNull(app.config());
app = app.toOAuthStartApp();
assertNotNull(app.config());
}
#location 4
#vulnerability type RESOURCE_LEAK | #fixed code
@Test
public void builder_config() {
App app = new App(AppConfig.builder().signingSecret("secret").build());
assertNotNull(app.config());
app = app.toBuilder().build();
assertNotNull(app.config());
app = app.toOAuthCallbackApp();
assertNotNull(app.config());
app = app.toOAuthStartApp();
assertNotNull(app.config());
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
protected Request<?> toSlackRequest(ApiGatewayRequest awsReq) {
if (log.isDebugEnabled()) {
log.debug("AWS API Gateway Request: {}", awsReq);
}
SlackRequestParser.HttpRequest rawRequest = SlackRequestParser.HttpRequest.builder()
.requestUri(awsReq.getPath())
.queryString(toStringToStringListMap(awsReq.getQueryStringParameters()))
.headers(new RequestHeaders(toStringToStringListMap(awsReq.getHeaders())))
.requestBody(awsReq.getBody())
.remoteAddress(awsReq.getRequestContext().getIdentity() != null ? awsReq.getRequestContext().getIdentity().getSourceIp() : null)
.build();
return requestParser.parse(rawRequest);
}
#location 8
#vulnerability type NULL_DEREFERENCE | #fixed code
protected Request<?> toSlackRequest(ApiGatewayRequest awsReq) {
if (log.isDebugEnabled()) {
log.debug("AWS API Gateway Request: {}", awsReq);
}
RequestContext context = awsReq.getRequestContext();
SlackRequestParser.HttpRequest rawRequest = SlackRequestParser.HttpRequest.builder()
.requestUri(awsReq.getPath())
.queryString(toStringToStringListMap(awsReq.getQueryStringParameters()))
.headers(new RequestHeaders(toStringToStringListMap(awsReq.getHeaders())))
.requestBody(awsReq.getBody())
.remoteAddress(context != null && context.getIdentity() != null ? context.getIdentity().getSourceIp() : null)
.build();
return requestParser.parse(rawRequest);
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Test
public void builder_status() {
App app = new App();
assertNotNull(app.status());
assertThat(app.status(), is(App.Status.Stopped));
app = app.toBuilder().build();
assertThat(app.status(), is(App.Status.Stopped));
app = app.toOAuthCallbackApp();
assertThat(app.status(), is(App.Status.Stopped));
app = app.toOAuthStartApp();
assertThat(app.status(), is(App.Status.Stopped));
}
#location 5
#vulnerability type RESOURCE_LEAK | #fixed code
@Test
public void builder_status() {
App app = new App(AppConfig.builder().signingSecret("secret").build());
assertNotNull(app.status());
assertThat(app.status(), is(App.Status.Stopped));
app = app.toBuilder().build();
assertThat(app.status(), is(App.Status.Stopped));
app = app.toOAuthCallbackApp();
assertThat(app.status(), is(App.Status.Stopped));
app = app.toOAuthStartApp();
assertThat(app.status(), is(App.Status.Stopped));
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Override
public Installer findInstaller(String enterpriseId, String teamId, String userId) {
AmazonS3 s3 = this.createS3Client();
String fullKey = getInstallerKey(enterpriseId, teamId, userId);
if (isHistoricalDataEnabled()) {
fullKey = fullKey + "-latest";
}
if (s3.getObjectMetadata(bucketName, fullKey) == null && enterpriseId != null) {
String nonGridKey = getInstallerKey(null, teamId, userId);
if (isHistoricalDataEnabled()) {
nonGridKey = nonGridKey + "-latest";
}
S3Object nonGridObject = s3.getObject(bucketName, nonGridKey);
if (nonGridObject != null) {
try {
Installer installer = toInstaller(nonGridObject);
installer.setEnterpriseId(enterpriseId); // the workspace seems to be in a Grid org now
saveInstallerAndBot(installer);
return installer;
} catch (Exception e) {
log.error("Failed to save a new Installer data for enterprise_id: {}, team_id: {}, user_id: {}",
enterpriseId, teamId, userId);
}
}
}
S3Object s3Object = s3.getObject(bucketName, fullKey);
try {
return toInstaller(s3Object);
} catch (Exception e) {
log.error("Failed to save a new Installer data for enterprise_id: {}, team_id: {}, user_id: {}",
enterpriseId, teamId, userId);
return null;
}
}
#location 28
#vulnerability type NULL_DEREFERENCE | #fixed code
@Override
public Installer findInstaller(String enterpriseId, String teamId, String userId) {
AmazonS3 s3 = this.createS3Client();
String fullKey = getInstallerKey(enterpriseId, teamId, userId);
if (isHistoricalDataEnabled()) {
fullKey = fullKey + "-latest";
}
if (getObjectMetadata(s3, fullKey) == null && enterpriseId != null) {
String nonGridKey = getInstallerKey(null, teamId, userId);
if (isHistoricalDataEnabled()) {
nonGridKey = nonGridKey + "-latest";
}
S3Object nonGridObject = getObject(s3, nonGridKey);
if (nonGridObject != null) {
try {
Installer installer = toInstaller(nonGridObject);
installer.setEnterpriseId(enterpriseId); // the workspace seems to be in a Grid org now
saveInstallerAndBot(installer);
return installer;
} catch (Exception e) {
log.error("Failed to save a new Installer data for enterprise_id: {}, team_id: {}, user_id: {}",
enterpriseId, teamId, userId);
}
}
}
S3Object s3Object = getObject(s3, fullKey);
try {
return toInstaller(s3Object);
} catch (Exception e) {
log.error("Failed to save a new Installer data for enterprise_id: {}, team_id: {}, user_id: {}",
enterpriseId, teamId, userId);
return null;
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
public static void main(String[] args) throws Exception {
DebugProtocol protocol = new DebugProtocol(new EventListener() {
@Override
public void onPageLoad() {
//To change body of implemented methods use File | Settings | File Templates.
}
@Override
public void domHasChanged(Event event) {
//To change body of implemented methods use File | Settings | File Templates.
}
@Override
public void frameDied(JSONObject message) {
//To change body of implemented methods use File | Settings | File Templates.
}
}, "com.apple.mobilesafari");
System.out.println(protocol.sendCommand(DOM.getDocument()).toString(2));
}
#location 2
#vulnerability type RESOURCE_LEAK | #fixed code
public static void main(String[] args) throws Exception {
test();
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Test(expectedExceptions = UnexpectedAlertOpen.class)
public void cannotInteractWithAppWhenAlertOpen() throws Exception {
RemoteUIADriver driver = null;
try {
driver = getDriver();
RemoteUIATarget target = driver.getLocalTarget();
RemoteUIAApplication app = target.getFrontMostApp();
RemoteUIAWindow win = app.getMainWindow();
getAlert(win);
UIAElement el = win.findElements(new NameCriteria("Show Simple")).get(2);
// opens an alert.
el.tap();
// should throw.The alert prevent interacting with the background.
el.tap();
} finally {
if (driver != null) {
driver.quit();
}
}
}
#location 12
#vulnerability type NULL_DEREFERENCE | #fixed code
@Test(expectedExceptions = UnexpectedAlertOpen.class)
public void cannotInteractWithAppWhenAlertOpen() throws Exception {
RemoteUIADriver driver = null;
try {
driver = getDriver();
RemoteUIATarget target = driver.getLocalTarget();
RemoteUIAApplication app = target.getFrontMostApp();
RemoteUIAWindow win = app.getMainWindow();
getAlert(win);
Criteria c =
new AndCriteria(new TypeCriteria(UIAStaticText.class), new NameCriteria("Show Simple"));
UIAElement el = win.findElements(c).get(1);
// opens an alert.
el.tap();
// should throw.The alert prevent interacting with the background.
el.tap();
} finally {
if (driver != null) {
driver.quit();
}
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Test
public void canSwitchToTheWebViewAndFindByCSS() throws Exception {
IOSCapabilities safari = IOSCapabilities.iphone("UICatalog");
safari.setCapability(IOSCapabilities.TIME_HACK, false);
RemoteUIADriver driver = null;
try {
driver = new RemoteUIADriver(getRemoteURL(), SampleApps.uiCatalogCap());
Set<String> handles = driver.getWindowHandles();
Assert.assertEquals(handles.size(), 1);
UIAElement el = driver.findElement(new AndCriteria(new TypeCriteria(UIATableCell.class), new NameCriteria("Web",
MatchingStrategy.starts)));
el.tap();
handles = driver.getWindowHandles();
Assert.assertEquals(handles.size(), 2);
UIAElement back = driver
.findElement(new AndCriteria(new TypeCriteria(UIAButton.class), new NameCriteria("Back")));
back.tap();
handles = driver.getWindowHandles();
Assert.assertEquals(handles.size(), 1);
} finally {
driver.quit();
}
}
#location 14
#vulnerability type NULL_DEREFERENCE | #fixed code
@Test
public void canSwitchToTheWebViewAndFindByCSS() throws Exception {
IOSCapabilities safari = IOSCapabilities.iphone("UICatalog");
safari.setCapability(IOSCapabilities.TIME_HACK, false);
RemoteUIADriver driver = null;
try {
driver = new RemoteUIADriver(getRemoteURL(), SampleApps.uiCatalogCap());
Set<String> handles = driver.getWindowHandles();
Assert.assertEquals(handles.size(), 1);
UIAElement webCell = driver.findElement(new AndCriteria(new TypeCriteria(UIATableCell.class), new NameCriteria(
"Web", MatchingStrategy.starts)));
webCell.tap();
handles = driver.getWindowHandles();
Assert.assertEquals(handles.size(), 2);
driver.switchTo().window("Web");
final By by = By.cssSelector("a[href='http://store.apple.com/']");
new WebDriverWait(driver, 5).until(new ExpectedCondition<WebElement>() {
@Override
public WebElement apply(WebDriver d) {
return d.findElement(by);
}
});
WebElement el = driver.findElement(by);
Assert.assertEquals(el.getAttribute("href"), "http://store.apple.com/");
} finally {
driver.quit();
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
public View handle(HttpServletRequest req) throws IOSAutomationException {
String path = req.getPathInfo();
String pattern = "/resources/";
int end = path.indexOf(pattern) + pattern.length();
String resource = path.substring(end);
InputStream is = null;
if (resource.endsWith("lastScreen.png")) {
is = getModel().getLastScreenshotInputStream();
} else {
is = IDEServlet.class.getResourceAsStream("/" + resource);
}
String mime = getMimeType(resource);
if (is == null) {
throw new IOSAutomationException("error getting resource " + req.getPathInfo()
+ req.getQueryString());
}
return new ResourceView(is, mime);
}
#location 19
#vulnerability type RESOURCE_LEAK | #fixed code
public View handle(HttpServletRequest req) throws IOSAutomationException {
String path = req.getPathInfo();
String pattern = "/resources/";
int end = path.indexOf(pattern) + pattern.length();
String resource = path.substring(end);
InputStream is = null;
if (resource.endsWith("lastScreen.png")) {
//is = getModel().getLastScreenshotInputStream();
} else {
is = IDEServlet.class.getResourceAsStream("/" + resource);
}
String mime = getMimeType(resource);
if (is == null) {
throw new IOSAutomationException("error getting resource " + req.getPathInfo()
+ req.getQueryString());
}
return new ResourceView(is, mime);
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Override
public Response handle() throws Exception {
JSONObject payload = getRequest().getPayload();
String type = payload.getString("using");
String value = payload.getString("value");
RemoteWebElement element = null;
if (getRequest().hasVariable(":reference")) {
int id = Integer.parseInt(getRequest().getVariableValue(":reference"));
element = new RemoteWebElement(new NodeId(id), getSession());
} else {
element = getSession().getWebInspector().getDocument();
}
List<RemoteWebElement> res;
if ("link text".equals(type)) {
res = element.findElementsByLinkText(value, false);
} else if ("partial link text".equals(type)) {
res = element.findElementsByLinkText(value, true);
} else if ("xpath".equals(type)) {
res = element.findElementsByXpath(value);
} else {
String cssSelector = ToCSSSelectorConvertor.convertToCSSSelector(type, value);
res = element.findElementsByCSSSelector(cssSelector);
}
JSONArray array = new JSONArray();
List<JSONObject> list = new ArrayList<JSONObject>();
for (RemoteWebElement el : res) {
list.add(new JSONObject().put("ELEMENT", "" + el.getNodeId().getId()));
}
Response resp = new Response();
resp.setSessionId(getSession().getSessionId());
resp.setStatus(0);
resp.setValue(list);
return resp;
}
#location 13
#vulnerability type NULL_DEREFERENCE | #fixed code
@Override
public Response handle() throws Exception {
waitForPageToLoad();
int implicitWait = (Integer) getConf("implicit_wait", 0);
long deadline = System.currentTimeMillis() + implicitWait;
List<RemoteWebElement> elements = null;
do {
try {
elements = findElements();
if (elements.size() != 0) {
break;
}
} catch (NoSuchElementException e) {
//ignore.
} catch (RemoteExceptionException e2) {
// ignore.
// if the page is reloading, the previous nodeId won't be there anymore, resulting in a
// RemoteExceptionException: Could not find node with given id.Keep looking.
}
} while (System.currentTimeMillis() < deadline);
JSONArray array = new JSONArray();
List<JSONObject> list = new ArrayList<JSONObject>();
for (RemoteWebElement el : elements) {
list.add(new JSONObject().put("ELEMENT", "" + el.getNodeId().getId()));
}
Response resp = new Response();
resp.setSessionId(getSession().getSessionId());
resp.setStatus(0);
resp.setValue(list);
return resp;
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Override
public Set<String> getWindowHandles() {
try {
JSONObject payload = new JSONObject();
WebDriverLikeCommand command = WebDriverLikeCommand.WINDOW_HANDLES;
Path p = new Path(command).withSession(getSessionId());
WebDriverLikeRequest request = new WebDriverLikeRequest(command.method(), p, payload);
Response response = execute(request);
JSONArray array = ((JSONArray) response.getValue());
Set<String> handles = new HashSet<String>();
for (int i = 0; i < array.length(); i++) {
handles.add(array.getString(i));
}
return handles;
} catch (IOSAutomationException e) {
throw e;
} catch (Exception e) {
throw new IOSAutomationException("bug", e);
}
}
#location 11
#vulnerability type NULL_DEREFERENCE | #fixed code
@Override
public Set<String> getWindowHandles() {
WebDriverLikeRequest request = buildRequest(WebDriverLikeCommand.WINDOW_HANDLES);
List<String> all = execute(request);
Set<String> res = new HashSet<String>();
res.addAll(all);
return res;
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Override
public Response handle() throws Exception {
JSONObject payload = getRequest().getPayload();
String type = payload.getString("using");
String value = payload.getString("value");
RemoteWebElement element = null;
if (getRequest().hasVariable(":reference")) {
int id = Integer.parseInt(getRequest().getVariableValue(":reference"));
element = new RemoteWebElement(new NodeId(id), getSession());
} else {
element = getSession().getWebInspector().getDocument();
}
RemoteWebElement rwe;
if ("link text".equals(type)) {
rwe = element.findElementByLinkText(value, false);
} else if ("partial link text".equals(type)) {
rwe = element.findElementByLinkText(value, true);
} else if ("xpath".equals(type)) {
rwe = element.findElementByXpath(value);
} else {
String cssSelector = ToCSSSelectorConvertor.convertToCSSSelector(type, value);
rwe = element.findElementByCSSSelector(cssSelector);
}
JSONObject res = new JSONObject();
if (rwe == null) {
throw new NoSuchElementException("No element found for " + type + "=" + value);
} else {
res.put("ELEMENT", "" + rwe.getNodeId().getId());
Response resp = new Response();
resp.setSessionId(getSession().getSessionId());
resp.setStatus(0);
resp.setValue(res);
return resp;
}
}
#location 13
#vulnerability type NULL_DEREFERENCE | #fixed code
@Override
public Response handle() throws Exception {
waitForPageToLoad();
int implicitWait = (Integer) getConf("implicit_wait", 0);
long deadline = System.currentTimeMillis() + implicitWait;
RemoteWebElement rwe = null;
do {
try {
rwe = findElement();
break;
} catch (NoSuchElementException e) {
//ignore.
} catch (RemoteExceptionException e2) {
// ignore.
// if the page is reloading, the previous nodeId won't be there anymore, resulting in a
// RemoteExceptionException: Could not find node with given id.Keep looking.
}
} while (System.currentTimeMillis() < deadline);
if (rwe == null) {
throw new NoSuchElementException(
"No element found for " + getRequest().getPayload() + " after waiting for " + implicitWait
+ " ms.");
} else {
JSONObject res = new JSONObject();
res.put("ELEMENT", "" + rwe.getNodeId().getId());
Response resp = new Response();
resp.setSessionId(getSession().getSessionId());
resp.setStatus(0);
resp.setValue(res);
return resp;
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Override
public void onPageLoad() {
System.err.println("new page loaded");
pageLoaded = true;
reset();
}
#location 5
#vulnerability type THREAD_SAFETY_VIOLATION | #fixed code
@Override
public void onPageLoad() {
System.err.println("new page loaded");
pageLoaded = true;
reset();
try {
Thread.sleep(5000);
System.out.println(
"on page load:" + session.getWebInspector().getProtocol().sendCommand(DOM.getDocument())
.optJSONObject("root").optString("documentURL"));
} catch (Exception e) {
e.printStackTrace();
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Override
public void onPageLoad() {
System.err.println("new page loaded");
pageLoaded = true;
reset();
try {
Thread.sleep(5000);
System.out.println(
"on page load:" + session.getWebInspector().getProtocol().sendCommand(DOM.getDocument())
.optJSONObject("root").optString("documentURL"));
} catch (Exception e) {
e.printStackTrace();
}
}
#location 9
#vulnerability type THREAD_SAFETY_VIOLATION | #fixed code
@Override
public void onPageLoad() {
pageLoaded = true;
reset();
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
public void setValueNative(String value) throws Exception {
UIAElement el = getNativeElement();
WorkingMode origin = session.getMode();
try {
session.setMode(WorkingMode.Native);
UIARect rect = el.getRect();
int x = rect.getX() + rect.getWidth() - 1;
int y = rect.getY() + rect.getHeight() / 2;
// TODO freynaud : tap() should take a param like middle, topLeft,
// bottomRight to save 1 call.
session.getNativeDriver().tap(x, y);
RemoteUIAKeyboard keyboard = (RemoteUIAKeyboard) session.getNativeDriver().getKeyboard();
if ("\n".equals(value)) {
keyboard.findElement(new NameCriteria("Return")).tap();
} else {
keyboard.sendKeys(value);
}
Criteria iphone = new NameCriteria("Done");
Criteria ipad = new NameCriteria("Hide keyboard");
UIAButton but = session.getNativeDriver().findElement(new OrCriteria(ipad, iphone));
but.tap();
// session.getNativeDriver().pinchClose(300, 400, 50, 100, 1);
} finally {
session.setMode(origin);
}
}
#location 14
#vulnerability type NULL_DEREFERENCE | #fixed code
public void setValueNative(String value) throws Exception {
/*WebElement el = getNativeElement();
WorkingMode origin = session.getMode();
try {
session.setMode(WorkingMode.Native);
el.click();
RemoteUIAKeyboard keyboard = (RemoteUIAKeyboard) session.getNativeDriver().getKeyboard();
if ("\n".equals(value)) {
keyboard.findElement(new NameCriteria("Return")).tap();
} else {
keyboard.sendKeys(value);
}
Criteria iphone = new NameCriteria("Done");
Criteria ipad = new NameCriteria("Hide keyboard");
UIAButton but = session.getNativeDriver().findElement(new OrCriteria(ipad, iphone));
but.tap();
// session.getNativeDriver().pinchClose(300, 400, 50, 100, 1);
} finally {
session.setMode(origin);
}*/
WorkingMode origin = session.getMode();
session.setMode(WorkingMode.Native);
((JavascriptExecutor) nativeDriver).executeScript(getNativeElementClickOnItAndTypeUsingKeyboardScript(value));
session.setMode(origin);
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Override
public void onPageLoad() {
System.err.println("new page loaded");
pageLoaded = true;
reset();
try {
Thread.sleep(5000);
System.out.println(
"on page load:" + session.getWebInspector().getProtocol().sendCommand(DOM.getDocument())
.optJSONObject("root").optString("documentURL"));
} catch (Exception e) {
e.printStackTrace();
}
}
#location 5
#vulnerability type THREAD_SAFETY_VIOLATION | #fixed code
@Override
public void onPageLoad() {
pageLoaded = true;
reset();
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Override
public void onPageLoad() {
System.err.println("new page loaded");
pageLoaded = true;
reset();
try {
Thread.sleep(5000);
System.out.println(
"on page load:" + session.getWebInspector().getProtocol().sendCommand(DOM.getDocument())
.optJSONObject("root").optString("documentURL"));
} catch (Exception e) {
e.printStackTrace();
}
}
#location 9
#vulnerability type THREAD_SAFETY_VIOLATION | #fixed code
@Override
public void onPageLoad() {
pageLoaded = true;
reset();
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
private void typeURLNative(String url) {
WorkingMode base = getSession().getMode();
try {
getSession().setMode(WorkingMode.Native);
getAddressBar().tap();
RemoteUIAKeyboard keyboard = (RemoteUIAKeyboard)getSession().getNativeDriver().getKeyboard();
keyboard.sendKeys(url);
keyboard.findElement(new NameCriteria("Go")).tap();
} finally {
getSession().setMode(base);
}
}
#location 9
#vulnerability type NULL_DEREFERENCE | #fixed code
private void typeURLNative(String url) {
WorkingMode base = getSession().getMode();
try {
getSession().setMode(WorkingMode.Native);
getAddressBar().tap();
RemoteUIAKeyboard keyboard = (RemoteUIAKeyboard) getSession().getNativeDriver().getKeyboard();
keyboard.sendKeys(url);
keyboard.findElement(new NameCriteria("Go")).tap();
} finally {
getSession().setMode(base);
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
public static void persist(File screenshot, JSONObject tree, File dest)
throws FileNotFoundException, IOException, JSONException {
System.out.println(screenshot.getAbsolutePath());
FileWriter write = new FileWriter(dest);
IOUtils.copy(new StringReader(tree.toString(2)), new FileOutputStream(dest), "UTF-8");
System.out.println(dest.getAbsolutePath());
}
#location 4
#vulnerability type RESOURCE_LEAK | #fixed code
public static void persist(File screenshot, JSONObject tree, File dest) throws FileNotFoundException, IOException,
JSONException {
IOUtils.copy(new StringReader(tree.toString(2)), new FileOutputStream(dest), "UTF-8");
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Override
public void onPageLoad() {
System.err.println("new page loaded");
pageLoaded = true;
reset();
try {
Thread.sleep(5000);
System.out.println(
"on page load:" + session.getWebInspector().getProtocol().sendCommand(DOM.getDocument())
.optJSONObject("root").optString("documentURL"));
} catch (Exception e) {
e.printStackTrace();
}
}
#location 9
#vulnerability type NULL_DEREFERENCE | #fixed code
@Override
public void onPageLoad() {
pageLoaded = true;
reset();
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
public void setValueNative(String value) throws Exception {
UIAElement el = getNativeElement();
WorkingMode origin = session.getMode();
try {
session.setMode(WorkingMode.Native);
UIARect rect = el.getRect();
int x = rect.getX() + rect.getWidth() - 1;
int y = rect.getY() + rect.getHeight() / 2;
// TODO freynaud : tap() should take a param like middle, topLeft,
// bottomRight to save 1 call.
session.getNativeDriver().tap(x, y);
RemoteUIAKeyboard keyboard = (RemoteUIAKeyboard) session.getNativeDriver().getKeyboard();
if ("\n".equals(value)) {
keyboard.findElement(new NameCriteria("Return")).tap();
} else {
keyboard.sendKeys(value);
}
Criteria iphone = new NameCriteria("Done");
Criteria ipad = new NameCriteria("Hide keyboard");
UIAButton but = session.getNativeDriver().findElement(new OrCriteria(ipad, iphone));
but.tap();
// session.getNativeDriver().pinchClose(300, 400, 50, 100, 1);
} finally {
session.setMode(origin);
}
}
#location 16
#vulnerability type NULL_DEREFERENCE | #fixed code
public void setValueNative(String value) throws Exception {
/*WebElement el = getNativeElement();
WorkingMode origin = session.getMode();
try {
session.setMode(WorkingMode.Native);
el.click();
RemoteUIAKeyboard keyboard = (RemoteUIAKeyboard) session.getNativeDriver().getKeyboard();
if ("\n".equals(value)) {
keyboard.findElement(new NameCriteria("Return")).tap();
} else {
keyboard.sendKeys(value);
}
Criteria iphone = new NameCriteria("Done");
Criteria ipad = new NameCriteria("Hide keyboard");
UIAButton but = session.getNativeDriver().findElement(new OrCriteria(ipad, iphone));
but.tap();
// session.getNativeDriver().pinchClose(300, 400, 50, 100, 1);
} finally {
session.setMode(origin);
}*/
WorkingMode origin = session.getMode();
session.setMode(WorkingMode.Native);
((JavascriptExecutor) nativeDriver).executeScript(getNativeElementClickOnItAndTypeUsingKeyboardScript(value));
session.setMode(origin);
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
private File createTmpScript(String content) throws IOException {
File res = File.createTempFile(FILE_NAME, ".js");
BufferedWriter out = new BufferedWriter(new FileWriter(res));
out.write(content);
out.close();
return res;
}
#location 6
#vulnerability type RESOURCE_LEAK | #fixed code
private File createTmpScript(String content) throws IOException {
File res=null;
if (DEBUG){
res = new File("/Users/freynaud/Documents/debug.js");
}else {
res = File.createTempFile(FILE_NAME, ".js");
}
Writer writer = new FileWriter(res);
IOUtils.copy(IOUtils.toInputStream(content),writer, "UTF-8");
IOUtils.closeQuietly(writer);
return res;
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Test
public void testTrivialMethod() throws Exception {
lib.simple("com.jitlogic.zorka.spy.unittest.SomeClass", "someMethod",
"zorka:type=ZorkaStats,name=SomeClass", "stats");
Object obj = TestUtil.instrumentAndInstantiate(spy,
"com.jitlogic.zorka.spy.unittest.SomeClass");
assertNotNull(obj);
TestUtil.callMethod(obj, "someMethod");
checkStats("someMethod", 1, 0, 1);
}
#location 11
#vulnerability type NULL_DEREFERENCE | #fixed code
@Test
public void testTrivialMethod() throws Exception {
Object obj = makeCall("someMethod");
assertEquals(1, obj.getClass().getField("runCounter").get(obj));
checkStats("someMethod", 1, 0, 1);
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Override
public boolean onActivate(Item item, Player player) {
int[] faces = new int[]{3, 0, 1, 2};
this.meta = (faces[(player != null) ? player.getDirection() : 0] & 0x03) | ((~this.meta) & 0x04);
this.getLevel().setBlock(this, this, true);
this.getLevel().addSound(new DoorSound(this));
return true;
}
#location 4
#vulnerability type NULL_DEREFERENCE | #fixed code
@Override
public boolean onActivate(Item item, Player player) {
if (player == null) {
return false;
}
double rotation = (player.yaw - 90) % 360;
if (rotation < 0) {
rotation += 360.0;
}
int[][] faces = new int[][]{
{0, 2},
{1, 3}
};
int originDirection = this.meta & 0x01;
int direction;
if (originDirection == 0) {
if (rotation >= 0 && rotation < 180) {
direction = 2;
} else {
direction = 0;
}
} else {
if (rotation >= 90 && rotation < 270) {
direction = 3;
} else {
direction = 1;
}
}
this.meta = direction | ((~this.meta) & 0x04);
this.getLevel().setBlock(this, this, true);
this.getLevel().addSound(new DoorSound(this));
return true;
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Override
public void openSession(String identifier, String address, int port, long clientID) {
PlayerCreationEvent ev = new PlayerCreationEvent(this, Player.class, Player.class, null, address, port);
this.server.getPluginManager().callEvent(ev);
Class<? extends Player> clazz = ev.getPlayerClass();
try {
Constructor constructor = clazz.getConstructor(SourceInterface.class, Long.class, String.class, Integer.class);
Player player = (Player) constructor.newInstance(this, ev.getClientId(), ev.getAddress(), ev.getPort());
this.players.put(identifier, player);
this.identifiersACK.put(identifier, 0);
this.identifiers.put(player, identifier);
this.server.addPlayer(identifier, player);
} catch (NoSuchMethodException | InvocationTargetException | InstantiationException | IllegalAccessException e) {
e.printStackTrace();
}
}
#location 3
#vulnerability type NULL_DEREFERENCE | #fixed code
@Override
public void openSession(String identifier, String address, int port, long clientID) {
PlayerCreationEvent ev = new PlayerCreationEvent(this, Player.class, Player.class, null, address, port);
this.server.getPluginManager().callEvent(ev);
Class<? extends Player> clazz = ev.getPlayerClass();
try {
Constructor constructor = clazz.getConstructor(SourceInterface.class, Long.class, String.class, int.class);
Player player = (Player) constructor.newInstance(this, ev.getClientId(), ev.getAddress(), ev.getPort());
this.players.put(identifier, player);
this.identifiersACK.put(identifier, 0);
this.identifiers.put(player, identifier);
this.server.addPlayer(identifier, player);
} catch (NoSuchMethodException | InvocationTargetException | InstantiationException | IllegalAccessException e) {
e.printStackTrace();
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
public boolean getDataFlag(int propertyId, int id) {
return ((this.getDataPropertyByte(propertyId) == null ? 0 : this.getDataPropertyByte(propertyId).data & 0xff) & (1 << id)) > 0;
}
#location 2
#vulnerability type NULL_DEREFERENCE | #fixed code
public boolean getDataFlag(int propertyId, int id) {
return ((this.getDataPropertyByte(propertyId).data & 0xff) & (1 << id)) > 0;
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Test
public void testSpecialStyles() throws Exception {
File f = new File("src/test/resources/special_types.xlsx");
Map<Integer, List<Cell>> contents = new HashMap<>();
try(StreamingReader reader = StreamingReader.builder().read(f)) {
for(Row row : reader) {
contents.put(row.getRowNum(), new ArrayList<Cell>());
for(Cell c : row) {
if(c.getColumnIndex() > 0) {
contents.get(row.getRowNum()).add(c);
}
}
}
}
SimpleDateFormat df = new SimpleDateFormat("dd/MM/yyyy");
assertThat(contents.size(), equalTo(2));
assertThat(contents.get(0).size(), equalTo(4));
assertThat(contents.get(0).get(0).getStringCellValue(), equalTo("Thu\", \"Dec 25\", \"14"));
assertThat(contents.get(0).get(0).getDateCellValue(), equalTo(df.parse("25/12/2014")));
assertThat(contents.get(0).get(1).getStringCellValue(), equalTo("02/04/15"));
assertThat(contents.get(0).get(1).getDateCellValue(), equalTo(df.parse("04/02/2015")));
assertThat(contents.get(0).get(2).getStringCellValue(), equalTo("14\". \"Mar\". \"2015"));
assertThat(contents.get(0).get(2).getDateCellValue(), equalTo(df.parse("14/03/2015")));
assertThat(contents.get(0).get(3).getStringCellValue(), equalTo("2015-05-05"));
assertThat(contents.get(0).get(3).getDateCellValue(), equalTo(df.parse("05/05/2015")));
assertThat(contents.get(1).size(), equalTo(4));
assertThat(contents.get(1).get(0).getStringCellValue(), equalTo("3.12"));
assertThat(contents.get(1).get(0).getNumericCellValue(), equalTo(3.12312312312));
assertThat(contents.get(1).get(1).getStringCellValue(), equalTo("1,023,042"));
assertThat(contents.get(1).get(1).getNumericCellValue(), equalTo(1023042.0));
assertThat(contents.get(1).get(2).getStringCellValue(), equalTo("-312,231.12"));
assertThat(contents.get(1).get(2).getNumericCellValue(), equalTo(-312231.12123145));
assertThat(contents.get(1).get(3).getStringCellValue(), equalTo("(132)"));
assertThat(contents.get(1).get(3).getNumericCellValue(), equalTo(-132.0));
}
#location 22
#vulnerability type NULL_DEREFERENCE | #fixed code
@Test
public void testSpecialStyles() throws Exception {
File f = new File("src/test/resources/special_types.xlsx");
Map<Integer, List<Cell>> contents = new HashMap<>();
try(Workbook wb = StreamingReader.builder().open(f)) {
for(Row row : wb.getSheetAt(0)) {
contents.put(row.getRowNum(), new ArrayList<Cell>());
for(Cell c : row) {
if(c.getColumnIndex() > 0) {
contents.get(row.getRowNum()).add(c);
}
}
}
}
SimpleDateFormat df = new SimpleDateFormat("dd/MM/yyyy");
assertThat(contents.size(), equalTo(2));
assertThat(contents.get(0).size(), equalTo(4));
assertThat(contents.get(0).get(0).getStringCellValue(), equalTo("Thu\", \"Dec 25\", \"14"));
assertThat(contents.get(0).get(0).getDateCellValue(), equalTo(df.parse("25/12/2014")));
assertThat(contents.get(0).get(1).getStringCellValue(), equalTo("02/04/15"));
assertThat(contents.get(0).get(1).getDateCellValue(), equalTo(df.parse("04/02/2015")));
assertThat(contents.get(0).get(2).getStringCellValue(), equalTo("14\". \"Mar\". \"2015"));
assertThat(contents.get(0).get(2).getDateCellValue(), equalTo(df.parse("14/03/2015")));
assertThat(contents.get(0).get(3).getStringCellValue(), equalTo("2015-05-05"));
assertThat(contents.get(0).get(3).getDateCellValue(), equalTo(df.parse("05/05/2015")));
assertThat(contents.get(1).size(), equalTo(4));
assertThat(contents.get(1).get(0).getStringCellValue(), equalTo("3.12"));
assertThat(contents.get(1).get(0).getNumericCellValue(), equalTo(3.12312312312));
assertThat(contents.get(1).get(1).getStringCellValue(), equalTo("1,023,042"));
assertThat(contents.get(1).get(1).getNumericCellValue(), equalTo(1023042.0));
assertThat(contents.get(1).get(2).getStringCellValue(), equalTo("-312,231.12"));
assertThat(contents.get(1).get(2).getNumericCellValue(), equalTo(-312231.12123145));
assertThat(contents.get(1).get(3).getStringCellValue(), equalTo("(132)"));
assertThat(contents.get(1).get(3).getNumericCellValue(), equalTo(-132.0));
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Test
public void testSpecialStyles() throws Exception {
File f = new File("src/test/resources/special_types.xlsx");
Map<Integer, List<Cell>> contents = new HashMap<>();
try(StreamingReader reader = StreamingReader.builder().read(f)) {
for(Row row : reader) {
contents.put(row.getRowNum(), new ArrayList<Cell>());
for(Cell c : row) {
if(c.getColumnIndex() > 0) {
contents.get(row.getRowNum()).add(c);
}
}
}
}
SimpleDateFormat df = new SimpleDateFormat("dd/MM/yyyy");
assertThat(contents.size(), equalTo(2));
assertThat(contents.get(0).size(), equalTo(4));
assertThat(contents.get(0).get(0).getStringCellValue(), equalTo("Thu\", \"Dec 25\", \"14"));
assertThat(contents.get(0).get(0).getDateCellValue(), equalTo(df.parse("25/12/2014")));
assertThat(contents.get(0).get(1).getStringCellValue(), equalTo("02/04/15"));
assertThat(contents.get(0).get(1).getDateCellValue(), equalTo(df.parse("04/02/2015")));
assertThat(contents.get(0).get(2).getStringCellValue(), equalTo("14\". \"Mar\". \"2015"));
assertThat(contents.get(0).get(2).getDateCellValue(), equalTo(df.parse("14/03/2015")));
assertThat(contents.get(0).get(3).getStringCellValue(), equalTo("2015-05-05"));
assertThat(contents.get(0).get(3).getDateCellValue(), equalTo(df.parse("05/05/2015")));
assertThat(contents.get(1).size(), equalTo(4));
assertThat(contents.get(1).get(0).getStringCellValue(), equalTo("3.12"));
assertThat(contents.get(1).get(0).getNumericCellValue(), equalTo(3.12312312312));
assertThat(contents.get(1).get(1).getStringCellValue(), equalTo("1,023,042"));
assertThat(contents.get(1).get(1).getNumericCellValue(), equalTo(1023042.0));
assertThat(contents.get(1).get(2).getStringCellValue(), equalTo("-312,231.12"));
assertThat(contents.get(1).get(2).getNumericCellValue(), equalTo(-312231.12123145));
assertThat(contents.get(1).get(3).getStringCellValue(), equalTo("(132)"));
assertThat(contents.get(1).get(3).getNumericCellValue(), equalTo(-132.0));
}
#location 24
#vulnerability type NULL_DEREFERENCE | #fixed code
@Test
public void testSpecialStyles() throws Exception {
File f = new File("src/test/resources/special_types.xlsx");
Map<Integer, List<Cell>> contents = new HashMap<>();
try(Workbook wb = StreamingReader.builder().open(f)) {
for(Row row : wb.getSheetAt(0)) {
contents.put(row.getRowNum(), new ArrayList<Cell>());
for(Cell c : row) {
if(c.getColumnIndex() > 0) {
contents.get(row.getRowNum()).add(c);
}
}
}
}
SimpleDateFormat df = new SimpleDateFormat("dd/MM/yyyy");
assertThat(contents.size(), equalTo(2));
assertThat(contents.get(0).size(), equalTo(4));
assertThat(contents.get(0).get(0).getStringCellValue(), equalTo("Thu\", \"Dec 25\", \"14"));
assertThat(contents.get(0).get(0).getDateCellValue(), equalTo(df.parse("25/12/2014")));
assertThat(contents.get(0).get(1).getStringCellValue(), equalTo("02/04/15"));
assertThat(contents.get(0).get(1).getDateCellValue(), equalTo(df.parse("04/02/2015")));
assertThat(contents.get(0).get(2).getStringCellValue(), equalTo("14\". \"Mar\". \"2015"));
assertThat(contents.get(0).get(2).getDateCellValue(), equalTo(df.parse("14/03/2015")));
assertThat(contents.get(0).get(3).getStringCellValue(), equalTo("2015-05-05"));
assertThat(contents.get(0).get(3).getDateCellValue(), equalTo(df.parse("05/05/2015")));
assertThat(contents.get(1).size(), equalTo(4));
assertThat(contents.get(1).get(0).getStringCellValue(), equalTo("3.12"));
assertThat(contents.get(1).get(0).getNumericCellValue(), equalTo(3.12312312312));
assertThat(contents.get(1).get(1).getStringCellValue(), equalTo("1,023,042"));
assertThat(contents.get(1).get(1).getNumericCellValue(), equalTo(1023042.0));
assertThat(contents.get(1).get(2).getStringCellValue(), equalTo("-312,231.12"));
assertThat(contents.get(1).get(2).getNumericCellValue(), equalTo(-312231.12123145));
assertThat(contents.get(1).get(3).getStringCellValue(), equalTo("(132)"));
assertThat(contents.get(1).get(3).getNumericCellValue(), equalTo(-132.0));
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Test
public void testSpecialStyles() throws Exception {
File f = new File("src/test/resources/special_types.xlsx");
Map<Integer, List<Cell>> contents = new HashMap<>();
try(StreamingReader reader = StreamingReader.builder().read(f)) {
for(Row row : reader) {
contents.put(row.getRowNum(), new ArrayList<Cell>());
for(Cell c : row) {
if(c.getColumnIndex() > 0) {
contents.get(row.getRowNum()).add(c);
}
}
}
}
SimpleDateFormat df = new SimpleDateFormat("dd/MM/yyyy");
assertThat(contents.size(), equalTo(2));
assertThat(contents.get(0).size(), equalTo(4));
assertThat(contents.get(0).get(0).getStringCellValue(), equalTo("Thu\", \"Dec 25\", \"14"));
assertThat(contents.get(0).get(0).getDateCellValue(), equalTo(df.parse("25/12/2014")));
assertThat(contents.get(0).get(1).getStringCellValue(), equalTo("02/04/15"));
assertThat(contents.get(0).get(1).getDateCellValue(), equalTo(df.parse("04/02/2015")));
assertThat(contents.get(0).get(2).getStringCellValue(), equalTo("14\". \"Mar\". \"2015"));
assertThat(contents.get(0).get(2).getDateCellValue(), equalTo(df.parse("14/03/2015")));
assertThat(contents.get(0).get(3).getStringCellValue(), equalTo("2015-05-05"));
assertThat(contents.get(0).get(3).getDateCellValue(), equalTo(df.parse("05/05/2015")));
assertThat(contents.get(1).size(), equalTo(4));
assertThat(contents.get(1).get(0).getStringCellValue(), equalTo("3.12"));
assertThat(contents.get(1).get(0).getNumericCellValue(), equalTo(3.12312312312));
assertThat(contents.get(1).get(1).getStringCellValue(), equalTo("1,023,042"));
assertThat(contents.get(1).get(1).getNumericCellValue(), equalTo(1023042.0));
assertThat(contents.get(1).get(2).getStringCellValue(), equalTo("-312,231.12"));
assertThat(contents.get(1).get(2).getNumericCellValue(), equalTo(-312231.12123145));
assertThat(contents.get(1).get(3).getStringCellValue(), equalTo("(132)"));
assertThat(contents.get(1).get(3).getNumericCellValue(), equalTo(-132.0));
}
#location 20
#vulnerability type NULL_DEREFERENCE | #fixed code
@Test
public void testSpecialStyles() throws Exception {
File f = new File("src/test/resources/special_types.xlsx");
Map<Integer, List<Cell>> contents = new HashMap<>();
try(Workbook wb = StreamingReader.builder().open(f)) {
for(Row row : wb.getSheetAt(0)) {
contents.put(row.getRowNum(), new ArrayList<Cell>());
for(Cell c : row) {
if(c.getColumnIndex() > 0) {
contents.get(row.getRowNum()).add(c);
}
}
}
}
SimpleDateFormat df = new SimpleDateFormat("dd/MM/yyyy");
assertThat(contents.size(), equalTo(2));
assertThat(contents.get(0).size(), equalTo(4));
assertThat(contents.get(0).get(0).getStringCellValue(), equalTo("Thu\", \"Dec 25\", \"14"));
assertThat(contents.get(0).get(0).getDateCellValue(), equalTo(df.parse("25/12/2014")));
assertThat(contents.get(0).get(1).getStringCellValue(), equalTo("02/04/15"));
assertThat(contents.get(0).get(1).getDateCellValue(), equalTo(df.parse("04/02/2015")));
assertThat(contents.get(0).get(2).getStringCellValue(), equalTo("14\". \"Mar\". \"2015"));
assertThat(contents.get(0).get(2).getDateCellValue(), equalTo(df.parse("14/03/2015")));
assertThat(contents.get(0).get(3).getStringCellValue(), equalTo("2015-05-05"));
assertThat(contents.get(0).get(3).getDateCellValue(), equalTo(df.parse("05/05/2015")));
assertThat(contents.get(1).size(), equalTo(4));
assertThat(contents.get(1).get(0).getStringCellValue(), equalTo("3.12"));
assertThat(contents.get(1).get(0).getNumericCellValue(), equalTo(3.12312312312));
assertThat(contents.get(1).get(1).getStringCellValue(), equalTo("1,023,042"));
assertThat(contents.get(1).get(1).getNumericCellValue(), equalTo(1023042.0));
assertThat(contents.get(1).get(2).getStringCellValue(), equalTo("-312,231.12"));
assertThat(contents.get(1).get(2).getNumericCellValue(), equalTo(-312231.12123145));
assertThat(contents.get(1).get(3).getStringCellValue(), equalTo("(132)"));
assertThat(contents.get(1).get(3).getNumericCellValue(), equalTo(-132.0));
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Test
public void testSpecialStyles() throws Exception {
File f = new File("src/test/resources/special_types.xlsx");
Map<Integer, List<Cell>> contents = new HashMap<>();
try(StreamingReader reader = StreamingReader.builder().read(f)) {
for(Row row : reader) {
contents.put(row.getRowNum(), new ArrayList<Cell>());
for(Cell c : row) {
if(c.getColumnIndex() > 0) {
contents.get(row.getRowNum()).add(c);
}
}
}
}
SimpleDateFormat df = new SimpleDateFormat("dd/MM/yyyy");
assertThat(contents.size(), equalTo(2));
assertThat(contents.get(0).size(), equalTo(4));
assertThat(contents.get(0).get(0).getStringCellValue(), equalTo("Thu\", \"Dec 25\", \"14"));
assertThat(contents.get(0).get(0).getDateCellValue(), equalTo(df.parse("25/12/2014")));
assertThat(contents.get(0).get(1).getStringCellValue(), equalTo("02/04/15"));
assertThat(contents.get(0).get(1).getDateCellValue(), equalTo(df.parse("04/02/2015")));
assertThat(contents.get(0).get(2).getStringCellValue(), equalTo("14\". \"Mar\". \"2015"));
assertThat(contents.get(0).get(2).getDateCellValue(), equalTo(df.parse("14/03/2015")));
assertThat(contents.get(0).get(3).getStringCellValue(), equalTo("2015-05-05"));
assertThat(contents.get(0).get(3).getDateCellValue(), equalTo(df.parse("05/05/2015")));
assertThat(contents.get(1).size(), equalTo(4));
assertThat(contents.get(1).get(0).getStringCellValue(), equalTo("3.12"));
assertThat(contents.get(1).get(0).getNumericCellValue(), equalTo(3.12312312312));
assertThat(contents.get(1).get(1).getStringCellValue(), equalTo("1,023,042"));
assertThat(contents.get(1).get(1).getNumericCellValue(), equalTo(1023042.0));
assertThat(contents.get(1).get(2).getStringCellValue(), equalTo("-312,231.12"));
assertThat(contents.get(1).get(2).getNumericCellValue(), equalTo(-312231.12123145));
assertThat(contents.get(1).get(3).getStringCellValue(), equalTo("(132)"));
assertThat(contents.get(1).get(3).getNumericCellValue(), equalTo(-132.0));
}
#location 31
#vulnerability type NULL_DEREFERENCE | #fixed code
@Test
public void testSpecialStyles() throws Exception {
File f = new File("src/test/resources/special_types.xlsx");
Map<Integer, List<Cell>> contents = new HashMap<>();
try(Workbook wb = StreamingReader.builder().open(f)) {
for(Row row : wb.getSheetAt(0)) {
contents.put(row.getRowNum(), new ArrayList<Cell>());
for(Cell c : row) {
if(c.getColumnIndex() > 0) {
contents.get(row.getRowNum()).add(c);
}
}
}
}
SimpleDateFormat df = new SimpleDateFormat("dd/MM/yyyy");
assertThat(contents.size(), equalTo(2));
assertThat(contents.get(0).size(), equalTo(4));
assertThat(contents.get(0).get(0).getStringCellValue(), equalTo("Thu\", \"Dec 25\", \"14"));
assertThat(contents.get(0).get(0).getDateCellValue(), equalTo(df.parse("25/12/2014")));
assertThat(contents.get(0).get(1).getStringCellValue(), equalTo("02/04/15"));
assertThat(contents.get(0).get(1).getDateCellValue(), equalTo(df.parse("04/02/2015")));
assertThat(contents.get(0).get(2).getStringCellValue(), equalTo("14\". \"Mar\". \"2015"));
assertThat(contents.get(0).get(2).getDateCellValue(), equalTo(df.parse("14/03/2015")));
assertThat(contents.get(0).get(3).getStringCellValue(), equalTo("2015-05-05"));
assertThat(contents.get(0).get(3).getDateCellValue(), equalTo(df.parse("05/05/2015")));
assertThat(contents.get(1).size(), equalTo(4));
assertThat(contents.get(1).get(0).getStringCellValue(), equalTo("3.12"));
assertThat(contents.get(1).get(0).getNumericCellValue(), equalTo(3.12312312312));
assertThat(contents.get(1).get(1).getStringCellValue(), equalTo("1,023,042"));
assertThat(contents.get(1).get(1).getNumericCellValue(), equalTo(1023042.0));
assertThat(contents.get(1).get(2).getStringCellValue(), equalTo("-312,231.12"));
assertThat(contents.get(1).get(2).getNumericCellValue(), equalTo(-312231.12123145));
assertThat(contents.get(1).get(3).getStringCellValue(), equalTo("(132)"));
assertThat(contents.get(1).get(3).getNumericCellValue(), equalTo(-132.0));
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Test
public void testSpecialStyles() throws Exception {
File f = new File("src/test/resources/special_types.xlsx");
Map<Integer, List<Cell>> contents = new HashMap<>();
try(StreamingReader reader = StreamingReader.builder().read(f)) {
for(Row row : reader) {
contents.put(row.getRowNum(), new ArrayList<Cell>());
for(Cell c : row) {
if(c.getColumnIndex() > 0) {
contents.get(row.getRowNum()).add(c);
}
}
}
}
SimpleDateFormat df = new SimpleDateFormat("dd/MM/yyyy");
assertThat(contents.size(), equalTo(2));
assertThat(contents.get(0).size(), equalTo(4));
assertThat(contents.get(0).get(0).getStringCellValue(), equalTo("Thu\", \"Dec 25\", \"14"));
assertThat(contents.get(0).get(0).getDateCellValue(), equalTo(df.parse("25/12/2014")));
assertThat(contents.get(0).get(1).getStringCellValue(), equalTo("02/04/15"));
assertThat(contents.get(0).get(1).getDateCellValue(), equalTo(df.parse("04/02/2015")));
assertThat(contents.get(0).get(2).getStringCellValue(), equalTo("14\". \"Mar\". \"2015"));
assertThat(contents.get(0).get(2).getDateCellValue(), equalTo(df.parse("14/03/2015")));
assertThat(contents.get(0).get(3).getStringCellValue(), equalTo("2015-05-05"));
assertThat(contents.get(0).get(3).getDateCellValue(), equalTo(df.parse("05/05/2015")));
assertThat(contents.get(1).size(), equalTo(4));
assertThat(contents.get(1).get(0).getStringCellValue(), equalTo("3.12"));
assertThat(contents.get(1).get(0).getNumericCellValue(), equalTo(3.12312312312));
assertThat(contents.get(1).get(1).getStringCellValue(), equalTo("1,023,042"));
assertThat(contents.get(1).get(1).getNumericCellValue(), equalTo(1023042.0));
assertThat(contents.get(1).get(2).getStringCellValue(), equalTo("-312,231.12"));
assertThat(contents.get(1).get(2).getNumericCellValue(), equalTo(-312231.12123145));
assertThat(contents.get(1).get(3).getStringCellValue(), equalTo("(132)"));
assertThat(contents.get(1).get(3).getNumericCellValue(), equalTo(-132.0));
}
#location 23
#vulnerability type NULL_DEREFERENCE | #fixed code
@Test
public void testSpecialStyles() throws Exception {
File f = new File("src/test/resources/special_types.xlsx");
Map<Integer, List<Cell>> contents = new HashMap<>();
try(Workbook wb = StreamingReader.builder().open(f)) {
for(Row row : wb.getSheetAt(0)) {
contents.put(row.getRowNum(), new ArrayList<Cell>());
for(Cell c : row) {
if(c.getColumnIndex() > 0) {
contents.get(row.getRowNum()).add(c);
}
}
}
}
SimpleDateFormat df = new SimpleDateFormat("dd/MM/yyyy");
assertThat(contents.size(), equalTo(2));
assertThat(contents.get(0).size(), equalTo(4));
assertThat(contents.get(0).get(0).getStringCellValue(), equalTo("Thu\", \"Dec 25\", \"14"));
assertThat(contents.get(0).get(0).getDateCellValue(), equalTo(df.parse("25/12/2014")));
assertThat(contents.get(0).get(1).getStringCellValue(), equalTo("02/04/15"));
assertThat(contents.get(0).get(1).getDateCellValue(), equalTo(df.parse("04/02/2015")));
assertThat(contents.get(0).get(2).getStringCellValue(), equalTo("14\". \"Mar\". \"2015"));
assertThat(contents.get(0).get(2).getDateCellValue(), equalTo(df.parse("14/03/2015")));
assertThat(contents.get(0).get(3).getStringCellValue(), equalTo("2015-05-05"));
assertThat(contents.get(0).get(3).getDateCellValue(), equalTo(df.parse("05/05/2015")));
assertThat(contents.get(1).size(), equalTo(4));
assertThat(contents.get(1).get(0).getStringCellValue(), equalTo("3.12"));
assertThat(contents.get(1).get(0).getNumericCellValue(), equalTo(3.12312312312));
assertThat(contents.get(1).get(1).getStringCellValue(), equalTo("1,023,042"));
assertThat(contents.get(1).get(1).getNumericCellValue(), equalTo(1023042.0));
assertThat(contents.get(1).get(2).getStringCellValue(), equalTo("-312,231.12"));
assertThat(contents.get(1).get(2).getNumericCellValue(), equalTo(-312231.12123145));
assertThat(contents.get(1).get(3).getStringCellValue(), equalTo("(132)"));
assertThat(contents.get(1).get(3).getNumericCellValue(), equalTo(-132.0));
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Test
public void testSpecialStyles() throws Exception {
File f = new File("src/test/resources/special_types.xlsx");
Map<Integer, List<Cell>> contents = new HashMap<>();
try(StreamingReader reader = StreamingReader.builder().read(f)) {
for(Row row : reader) {
contents.put(row.getRowNum(), new ArrayList<Cell>());
for(Cell c : row) {
if(c.getColumnIndex() > 0) {
contents.get(row.getRowNum()).add(c);
}
}
}
}
SimpleDateFormat df = new SimpleDateFormat("dd/MM/yyyy");
assertThat(contents.size(), equalTo(2));
assertThat(contents.get(0).size(), equalTo(4));
assertThat(contents.get(0).get(0).getStringCellValue(), equalTo("Thu\", \"Dec 25\", \"14"));
assertThat(contents.get(0).get(0).getDateCellValue(), equalTo(df.parse("25/12/2014")));
assertThat(contents.get(0).get(1).getStringCellValue(), equalTo("02/04/15"));
assertThat(contents.get(0).get(1).getDateCellValue(), equalTo(df.parse("04/02/2015")));
assertThat(contents.get(0).get(2).getStringCellValue(), equalTo("14\". \"Mar\". \"2015"));
assertThat(contents.get(0).get(2).getDateCellValue(), equalTo(df.parse("14/03/2015")));
assertThat(contents.get(0).get(3).getStringCellValue(), equalTo("2015-05-05"));
assertThat(contents.get(0).get(3).getDateCellValue(), equalTo(df.parse("05/05/2015")));
assertThat(contents.get(1).size(), equalTo(4));
assertThat(contents.get(1).get(0).getStringCellValue(), equalTo("3.12"));
assertThat(contents.get(1).get(0).getNumericCellValue(), equalTo(3.12312312312));
assertThat(contents.get(1).get(1).getStringCellValue(), equalTo("1,023,042"));
assertThat(contents.get(1).get(1).getNumericCellValue(), equalTo(1023042.0));
assertThat(contents.get(1).get(2).getStringCellValue(), equalTo("-312,231.12"));
assertThat(contents.get(1).get(2).getNumericCellValue(), equalTo(-312231.12123145));
assertThat(contents.get(1).get(3).getStringCellValue(), equalTo("(132)"));
assertThat(contents.get(1).get(3).getNumericCellValue(), equalTo(-132.0));
}
#location 30
#vulnerability type NULL_DEREFERENCE | #fixed code
@Test
public void testSpecialStyles() throws Exception {
File f = new File("src/test/resources/special_types.xlsx");
Map<Integer, List<Cell>> contents = new HashMap<>();
try(Workbook wb = StreamingReader.builder().open(f)) {
for(Row row : wb.getSheetAt(0)) {
contents.put(row.getRowNum(), new ArrayList<Cell>());
for(Cell c : row) {
if(c.getColumnIndex() > 0) {
contents.get(row.getRowNum()).add(c);
}
}
}
}
SimpleDateFormat df = new SimpleDateFormat("dd/MM/yyyy");
assertThat(contents.size(), equalTo(2));
assertThat(contents.get(0).size(), equalTo(4));
assertThat(contents.get(0).get(0).getStringCellValue(), equalTo("Thu\", \"Dec 25\", \"14"));
assertThat(contents.get(0).get(0).getDateCellValue(), equalTo(df.parse("25/12/2014")));
assertThat(contents.get(0).get(1).getStringCellValue(), equalTo("02/04/15"));
assertThat(contents.get(0).get(1).getDateCellValue(), equalTo(df.parse("04/02/2015")));
assertThat(contents.get(0).get(2).getStringCellValue(), equalTo("14\". \"Mar\". \"2015"));
assertThat(contents.get(0).get(2).getDateCellValue(), equalTo(df.parse("14/03/2015")));
assertThat(contents.get(0).get(3).getStringCellValue(), equalTo("2015-05-05"));
assertThat(contents.get(0).get(3).getDateCellValue(), equalTo(df.parse("05/05/2015")));
assertThat(contents.get(1).size(), equalTo(4));
assertThat(contents.get(1).get(0).getStringCellValue(), equalTo("3.12"));
assertThat(contents.get(1).get(0).getNumericCellValue(), equalTo(3.12312312312));
assertThat(contents.get(1).get(1).getStringCellValue(), equalTo("1,023,042"));
assertThat(contents.get(1).get(1).getNumericCellValue(), equalTo(1023042.0));
assertThat(contents.get(1).get(2).getStringCellValue(), equalTo("-312,231.12"));
assertThat(contents.get(1).get(2).getNumericCellValue(), equalTo(-312231.12123145));
assertThat(contents.get(1).get(3).getStringCellValue(), equalTo("(132)"));
assertThat(contents.get(1).get(3).getNumericCellValue(), equalTo(-132.0));
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Test
public void testSpecialStyles() throws Exception {
File f = new File("src/test/resources/special_types.xlsx");
Map<Integer, List<Cell>> contents = new HashMap<>();
try(StreamingReader reader = StreamingReader.builder().read(f)) {
for(Row row : reader) {
contents.put(row.getRowNum(), new ArrayList<Cell>());
for(Cell c : row) {
if(c.getColumnIndex() > 0) {
contents.get(row.getRowNum()).add(c);
}
}
}
}
SimpleDateFormat df = new SimpleDateFormat("dd/MM/yyyy");
assertThat(contents.size(), equalTo(2));
assertThat(contents.get(0).size(), equalTo(4));
assertThat(contents.get(0).get(0).getStringCellValue(), equalTo("Thu\", \"Dec 25\", \"14"));
assertThat(contents.get(0).get(0).getDateCellValue(), equalTo(df.parse("25/12/2014")));
assertThat(contents.get(0).get(1).getStringCellValue(), equalTo("02/04/15"));
assertThat(contents.get(0).get(1).getDateCellValue(), equalTo(df.parse("04/02/2015")));
assertThat(contents.get(0).get(2).getStringCellValue(), equalTo("14\". \"Mar\". \"2015"));
assertThat(contents.get(0).get(2).getDateCellValue(), equalTo(df.parse("14/03/2015")));
assertThat(contents.get(0).get(3).getStringCellValue(), equalTo("2015-05-05"));
assertThat(contents.get(0).get(3).getDateCellValue(), equalTo(df.parse("05/05/2015")));
assertThat(contents.get(1).size(), equalTo(4));
assertThat(contents.get(1).get(0).getStringCellValue(), equalTo("3.12"));
assertThat(contents.get(1).get(0).getNumericCellValue(), equalTo(3.12312312312));
assertThat(contents.get(1).get(1).getStringCellValue(), equalTo("1,023,042"));
assertThat(contents.get(1).get(1).getNumericCellValue(), equalTo(1023042.0));
assertThat(contents.get(1).get(2).getStringCellValue(), equalTo("-312,231.12"));
assertThat(contents.get(1).get(2).getNumericCellValue(), equalTo(-312231.12123145));
assertThat(contents.get(1).get(3).getStringCellValue(), equalTo("(132)"));
assertThat(contents.get(1).get(3).getNumericCellValue(), equalTo(-132.0));
}
#location 26
#vulnerability type NULL_DEREFERENCE | #fixed code
@Test
public void testSpecialStyles() throws Exception {
File f = new File("src/test/resources/special_types.xlsx");
Map<Integer, List<Cell>> contents = new HashMap<>();
try(Workbook wb = StreamingReader.builder().open(f)) {
for(Row row : wb.getSheetAt(0)) {
contents.put(row.getRowNum(), new ArrayList<Cell>());
for(Cell c : row) {
if(c.getColumnIndex() > 0) {
contents.get(row.getRowNum()).add(c);
}
}
}
}
SimpleDateFormat df = new SimpleDateFormat("dd/MM/yyyy");
assertThat(contents.size(), equalTo(2));
assertThat(contents.get(0).size(), equalTo(4));
assertThat(contents.get(0).get(0).getStringCellValue(), equalTo("Thu\", \"Dec 25\", \"14"));
assertThat(contents.get(0).get(0).getDateCellValue(), equalTo(df.parse("25/12/2014")));
assertThat(contents.get(0).get(1).getStringCellValue(), equalTo("02/04/15"));
assertThat(contents.get(0).get(1).getDateCellValue(), equalTo(df.parse("04/02/2015")));
assertThat(contents.get(0).get(2).getStringCellValue(), equalTo("14\". \"Mar\". \"2015"));
assertThat(contents.get(0).get(2).getDateCellValue(), equalTo(df.parse("14/03/2015")));
assertThat(contents.get(0).get(3).getStringCellValue(), equalTo("2015-05-05"));
assertThat(contents.get(0).get(3).getDateCellValue(), equalTo(df.parse("05/05/2015")));
assertThat(contents.get(1).size(), equalTo(4));
assertThat(contents.get(1).get(0).getStringCellValue(), equalTo("3.12"));
assertThat(contents.get(1).get(0).getNumericCellValue(), equalTo(3.12312312312));
assertThat(contents.get(1).get(1).getStringCellValue(), equalTo("1,023,042"));
assertThat(contents.get(1).get(1).getNumericCellValue(), equalTo(1023042.0));
assertThat(contents.get(1).get(2).getStringCellValue(), equalTo("-312,231.12"));
assertThat(contents.get(1).get(2).getNumericCellValue(), equalTo(-312231.12123145));
assertThat(contents.get(1).get(3).getStringCellValue(), equalTo("(132)"));
assertThat(contents.get(1).get(3).getNumericCellValue(), equalTo(-132.0));
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Test
public void testSpecialStyles() throws Exception {
File f = new File("src/test/resources/special_types.xlsx");
Map<Integer, List<Cell>> contents = new HashMap<>();
try(StreamingReader reader = StreamingReader.builder().read(f)) {
for(Row row : reader) {
contents.put(row.getRowNum(), new ArrayList<Cell>());
for(Cell c : row) {
if(c.getColumnIndex() > 0) {
contents.get(row.getRowNum()).add(c);
}
}
}
}
SimpleDateFormat df = new SimpleDateFormat("dd/MM/yyyy");
assertThat(contents.size(), equalTo(2));
assertThat(contents.get(0).size(), equalTo(4));
assertThat(contents.get(0).get(0).getStringCellValue(), equalTo("Thu\", \"Dec 25\", \"14"));
assertThat(contents.get(0).get(0).getDateCellValue(), equalTo(df.parse("25/12/2014")));
assertThat(contents.get(0).get(1).getStringCellValue(), equalTo("02/04/15"));
assertThat(contents.get(0).get(1).getDateCellValue(), equalTo(df.parse("04/02/2015")));
assertThat(contents.get(0).get(2).getStringCellValue(), equalTo("14\". \"Mar\". \"2015"));
assertThat(contents.get(0).get(2).getDateCellValue(), equalTo(df.parse("14/03/2015")));
assertThat(contents.get(0).get(3).getStringCellValue(), equalTo("2015-05-05"));
assertThat(contents.get(0).get(3).getDateCellValue(), equalTo(df.parse("05/05/2015")));
assertThat(contents.get(1).size(), equalTo(4));
assertThat(contents.get(1).get(0).getStringCellValue(), equalTo("3.12"));
assertThat(contents.get(1).get(0).getNumericCellValue(), equalTo(3.12312312312));
assertThat(contents.get(1).get(1).getStringCellValue(), equalTo("1,023,042"));
assertThat(contents.get(1).get(1).getNumericCellValue(), equalTo(1023042.0));
assertThat(contents.get(1).get(2).getStringCellValue(), equalTo("-312,231.12"));
assertThat(contents.get(1).get(2).getNumericCellValue(), equalTo(-312231.12123145));
assertThat(contents.get(1).get(3).getStringCellValue(), equalTo("(132)"));
assertThat(contents.get(1).get(3).getNumericCellValue(), equalTo(-132.0));
}
#location 28
#vulnerability type NULL_DEREFERENCE | #fixed code
@Test
public void testSpecialStyles() throws Exception {
File f = new File("src/test/resources/special_types.xlsx");
Map<Integer, List<Cell>> contents = new HashMap<>();
try(Workbook wb = StreamingReader.builder().open(f)) {
for(Row row : wb.getSheetAt(0)) {
contents.put(row.getRowNum(), new ArrayList<Cell>());
for(Cell c : row) {
if(c.getColumnIndex() > 0) {
contents.get(row.getRowNum()).add(c);
}
}
}
}
SimpleDateFormat df = new SimpleDateFormat("dd/MM/yyyy");
assertThat(contents.size(), equalTo(2));
assertThat(contents.get(0).size(), equalTo(4));
assertThat(contents.get(0).get(0).getStringCellValue(), equalTo("Thu\", \"Dec 25\", \"14"));
assertThat(contents.get(0).get(0).getDateCellValue(), equalTo(df.parse("25/12/2014")));
assertThat(contents.get(0).get(1).getStringCellValue(), equalTo("02/04/15"));
assertThat(contents.get(0).get(1).getDateCellValue(), equalTo(df.parse("04/02/2015")));
assertThat(contents.get(0).get(2).getStringCellValue(), equalTo("14\". \"Mar\". \"2015"));
assertThat(contents.get(0).get(2).getDateCellValue(), equalTo(df.parse("14/03/2015")));
assertThat(contents.get(0).get(3).getStringCellValue(), equalTo("2015-05-05"));
assertThat(contents.get(0).get(3).getDateCellValue(), equalTo(df.parse("05/05/2015")));
assertThat(contents.get(1).size(), equalTo(4));
assertThat(contents.get(1).get(0).getStringCellValue(), equalTo("3.12"));
assertThat(contents.get(1).get(0).getNumericCellValue(), equalTo(3.12312312312));
assertThat(contents.get(1).get(1).getStringCellValue(), equalTo("1,023,042"));
assertThat(contents.get(1).get(1).getNumericCellValue(), equalTo(1023042.0));
assertThat(contents.get(1).get(2).getStringCellValue(), equalTo("-312,231.12"));
assertThat(contents.get(1).get(2).getNumericCellValue(), equalTo(-312231.12123145));
assertThat(contents.get(1).get(3).getStringCellValue(), equalTo("(132)"));
assertThat(contents.get(1).get(3).getNumericCellValue(), equalTo(-132.0));
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Test
public void testSpecialStyles() throws Exception {
File f = new File("src/test/resources/special_types.xlsx");
Map<Integer, List<Cell>> contents = new HashMap<>();
try(StreamingReader reader = StreamingReader.builder().read(f)) {
for(Row row : reader) {
contents.put(row.getRowNum(), new ArrayList<Cell>());
for(Cell c : row) {
if(c.getColumnIndex() > 0) {
contents.get(row.getRowNum()).add(c);
}
}
}
}
SimpleDateFormat df = new SimpleDateFormat("dd/MM/yyyy");
assertThat(contents.size(), equalTo(2));
assertThat(contents.get(0).size(), equalTo(4));
assertThat(contents.get(0).get(0).getStringCellValue(), equalTo("Thu\", \"Dec 25\", \"14"));
assertThat(contents.get(0).get(0).getDateCellValue(), equalTo(df.parse("25/12/2014")));
assertThat(contents.get(0).get(1).getStringCellValue(), equalTo("02/04/15"));
assertThat(contents.get(0).get(1).getDateCellValue(), equalTo(df.parse("04/02/2015")));
assertThat(contents.get(0).get(2).getStringCellValue(), equalTo("14\". \"Mar\". \"2015"));
assertThat(contents.get(0).get(2).getDateCellValue(), equalTo(df.parse("14/03/2015")));
assertThat(contents.get(0).get(3).getStringCellValue(), equalTo("2015-05-05"));
assertThat(contents.get(0).get(3).getDateCellValue(), equalTo(df.parse("05/05/2015")));
assertThat(contents.get(1).size(), equalTo(4));
assertThat(contents.get(1).get(0).getStringCellValue(), equalTo("3.12"));
assertThat(contents.get(1).get(0).getNumericCellValue(), equalTo(3.12312312312));
assertThat(contents.get(1).get(1).getStringCellValue(), equalTo("1,023,042"));
assertThat(contents.get(1).get(1).getNumericCellValue(), equalTo(1023042.0));
assertThat(contents.get(1).get(2).getStringCellValue(), equalTo("-312,231.12"));
assertThat(contents.get(1).get(2).getNumericCellValue(), equalTo(-312231.12123145));
assertThat(contents.get(1).get(3).getStringCellValue(), equalTo("(132)"));
assertThat(contents.get(1).get(3).getNumericCellValue(), equalTo(-132.0));
}
#location 25
#vulnerability type NULL_DEREFERENCE | #fixed code
@Test
public void testSpecialStyles() throws Exception {
File f = new File("src/test/resources/special_types.xlsx");
Map<Integer, List<Cell>> contents = new HashMap<>();
try(Workbook wb = StreamingReader.builder().open(f)) {
for(Row row : wb.getSheetAt(0)) {
contents.put(row.getRowNum(), new ArrayList<Cell>());
for(Cell c : row) {
if(c.getColumnIndex() > 0) {
contents.get(row.getRowNum()).add(c);
}
}
}
}
SimpleDateFormat df = new SimpleDateFormat("dd/MM/yyyy");
assertThat(contents.size(), equalTo(2));
assertThat(contents.get(0).size(), equalTo(4));
assertThat(contents.get(0).get(0).getStringCellValue(), equalTo("Thu\", \"Dec 25\", \"14"));
assertThat(contents.get(0).get(0).getDateCellValue(), equalTo(df.parse("25/12/2014")));
assertThat(contents.get(0).get(1).getStringCellValue(), equalTo("02/04/15"));
assertThat(contents.get(0).get(1).getDateCellValue(), equalTo(df.parse("04/02/2015")));
assertThat(contents.get(0).get(2).getStringCellValue(), equalTo("14\". \"Mar\". \"2015"));
assertThat(contents.get(0).get(2).getDateCellValue(), equalTo(df.parse("14/03/2015")));
assertThat(contents.get(0).get(3).getStringCellValue(), equalTo("2015-05-05"));
assertThat(contents.get(0).get(3).getDateCellValue(), equalTo(df.parse("05/05/2015")));
assertThat(contents.get(1).size(), equalTo(4));
assertThat(contents.get(1).get(0).getStringCellValue(), equalTo("3.12"));
assertThat(contents.get(1).get(0).getNumericCellValue(), equalTo(3.12312312312));
assertThat(contents.get(1).get(1).getStringCellValue(), equalTo("1,023,042"));
assertThat(contents.get(1).get(1).getNumericCellValue(), equalTo(1023042.0));
assertThat(contents.get(1).get(2).getStringCellValue(), equalTo("-312,231.12"));
assertThat(contents.get(1).get(2).getNumericCellValue(), equalTo(-312231.12123145));
assertThat(contents.get(1).get(3).getStringCellValue(), equalTo("(132)"));
assertThat(contents.get(1).get(3).getNumericCellValue(), equalTo(-132.0));
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Test
public void testSpecialStyles() throws Exception {
File f = new File("src/test/resources/special_types.xlsx");
Map<Integer, List<Cell>> contents = new HashMap<>();
try(StreamingReader reader = StreamingReader.builder().read(f)) {
for(Row row : reader) {
contents.put(row.getRowNum(), new ArrayList<Cell>());
for(Cell c : row) {
if(c.getColumnIndex() > 0) {
contents.get(row.getRowNum()).add(c);
}
}
}
}
SimpleDateFormat df = new SimpleDateFormat("dd/MM/yyyy");
assertThat(contents.size(), equalTo(2));
assertThat(contents.get(0).size(), equalTo(4));
assertThat(contents.get(0).get(0).getStringCellValue(), equalTo("Thu\", \"Dec 25\", \"14"));
assertThat(contents.get(0).get(0).getDateCellValue(), equalTo(df.parse("25/12/2014")));
assertThat(contents.get(0).get(1).getStringCellValue(), equalTo("02/04/15"));
assertThat(contents.get(0).get(1).getDateCellValue(), equalTo(df.parse("04/02/2015")));
assertThat(contents.get(0).get(2).getStringCellValue(), equalTo("14\". \"Mar\". \"2015"));
assertThat(contents.get(0).get(2).getDateCellValue(), equalTo(df.parse("14/03/2015")));
assertThat(contents.get(0).get(3).getStringCellValue(), equalTo("2015-05-05"));
assertThat(contents.get(0).get(3).getDateCellValue(), equalTo(df.parse("05/05/2015")));
assertThat(contents.get(1).size(), equalTo(4));
assertThat(contents.get(1).get(0).getStringCellValue(), equalTo("3.12"));
assertThat(contents.get(1).get(0).getNumericCellValue(), equalTo(3.12312312312));
assertThat(contents.get(1).get(1).getStringCellValue(), equalTo("1,023,042"));
assertThat(contents.get(1).get(1).getNumericCellValue(), equalTo(1023042.0));
assertThat(contents.get(1).get(2).getStringCellValue(), equalTo("-312,231.12"));
assertThat(contents.get(1).get(2).getNumericCellValue(), equalTo(-312231.12123145));
assertThat(contents.get(1).get(3).getStringCellValue(), equalTo("(132)"));
assertThat(contents.get(1).get(3).getNumericCellValue(), equalTo(-132.0));
}
#location 27
#vulnerability type NULL_DEREFERENCE | #fixed code
@Test
public void testSpecialStyles() throws Exception {
File f = new File("src/test/resources/special_types.xlsx");
Map<Integer, List<Cell>> contents = new HashMap<>();
try(Workbook wb = StreamingReader.builder().open(f)) {
for(Row row : wb.getSheetAt(0)) {
contents.put(row.getRowNum(), new ArrayList<Cell>());
for(Cell c : row) {
if(c.getColumnIndex() > 0) {
contents.get(row.getRowNum()).add(c);
}
}
}
}
SimpleDateFormat df = new SimpleDateFormat("dd/MM/yyyy");
assertThat(contents.size(), equalTo(2));
assertThat(contents.get(0).size(), equalTo(4));
assertThat(contents.get(0).get(0).getStringCellValue(), equalTo("Thu\", \"Dec 25\", \"14"));
assertThat(contents.get(0).get(0).getDateCellValue(), equalTo(df.parse("25/12/2014")));
assertThat(contents.get(0).get(1).getStringCellValue(), equalTo("02/04/15"));
assertThat(contents.get(0).get(1).getDateCellValue(), equalTo(df.parse("04/02/2015")));
assertThat(contents.get(0).get(2).getStringCellValue(), equalTo("14\". \"Mar\". \"2015"));
assertThat(contents.get(0).get(2).getDateCellValue(), equalTo(df.parse("14/03/2015")));
assertThat(contents.get(0).get(3).getStringCellValue(), equalTo("2015-05-05"));
assertThat(contents.get(0).get(3).getDateCellValue(), equalTo(df.parse("05/05/2015")));
assertThat(contents.get(1).size(), equalTo(4));
assertThat(contents.get(1).get(0).getStringCellValue(), equalTo("3.12"));
assertThat(contents.get(1).get(0).getNumericCellValue(), equalTo(3.12312312312));
assertThat(contents.get(1).get(1).getStringCellValue(), equalTo("1,023,042"));
assertThat(contents.get(1).get(1).getNumericCellValue(), equalTo(1023042.0));
assertThat(contents.get(1).get(2).getStringCellValue(), equalTo("-312,231.12"));
assertThat(contents.get(1).get(2).getNumericCellValue(), equalTo(-312231.12123145));
assertThat(contents.get(1).get(3).getStringCellValue(), equalTo("(132)"));
assertThat(contents.get(1).get(3).getNumericCellValue(), equalTo(-132.0));
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Test
public void testSpecialStyles() throws Exception {
File f = new File("src/test/resources/special_types.xlsx");
Map<Integer, List<Cell>> contents = new HashMap<>();
try(StreamingReader reader = StreamingReader.builder().read(f)) {
for(Row row : reader) {
contents.put(row.getRowNum(), new ArrayList<Cell>());
for(Cell c : row) {
if(c.getColumnIndex() > 0) {
contents.get(row.getRowNum()).add(c);
}
}
}
}
SimpleDateFormat df = new SimpleDateFormat("dd/MM/yyyy");
assertThat(contents.size(), equalTo(2));
assertThat(contents.get(0).size(), equalTo(4));
assertThat(contents.get(0).get(0).getStringCellValue(), equalTo("Thu\", \"Dec 25\", \"14"));
assertThat(contents.get(0).get(0).getDateCellValue(), equalTo(df.parse("25/12/2014")));
assertThat(contents.get(0).get(1).getStringCellValue(), equalTo("02/04/15"));
assertThat(contents.get(0).get(1).getDateCellValue(), equalTo(df.parse("04/02/2015")));
assertThat(contents.get(0).get(2).getStringCellValue(), equalTo("14\". \"Mar\". \"2015"));
assertThat(contents.get(0).get(2).getDateCellValue(), equalTo(df.parse("14/03/2015")));
assertThat(contents.get(0).get(3).getStringCellValue(), equalTo("2015-05-05"));
assertThat(contents.get(0).get(3).getDateCellValue(), equalTo(df.parse("05/05/2015")));
assertThat(contents.get(1).size(), equalTo(4));
assertThat(contents.get(1).get(0).getStringCellValue(), equalTo("3.12"));
assertThat(contents.get(1).get(0).getNumericCellValue(), equalTo(3.12312312312));
assertThat(contents.get(1).get(1).getStringCellValue(), equalTo("1,023,042"));
assertThat(contents.get(1).get(1).getNumericCellValue(), equalTo(1023042.0));
assertThat(contents.get(1).get(2).getStringCellValue(), equalTo("-312,231.12"));
assertThat(contents.get(1).get(2).getNumericCellValue(), equalTo(-312231.12123145));
assertThat(contents.get(1).get(3).getStringCellValue(), equalTo("(132)"));
assertThat(contents.get(1).get(3).getNumericCellValue(), equalTo(-132.0));
}
#location 21
#vulnerability type NULL_DEREFERENCE | #fixed code
@Test
public void testSpecialStyles() throws Exception {
File f = new File("src/test/resources/special_types.xlsx");
Map<Integer, List<Cell>> contents = new HashMap<>();
try(Workbook wb = StreamingReader.builder().open(f)) {
for(Row row : wb.getSheetAt(0)) {
contents.put(row.getRowNum(), new ArrayList<Cell>());
for(Cell c : row) {
if(c.getColumnIndex() > 0) {
contents.get(row.getRowNum()).add(c);
}
}
}
}
SimpleDateFormat df = new SimpleDateFormat("dd/MM/yyyy");
assertThat(contents.size(), equalTo(2));
assertThat(contents.get(0).size(), equalTo(4));
assertThat(contents.get(0).get(0).getStringCellValue(), equalTo("Thu\", \"Dec 25\", \"14"));
assertThat(contents.get(0).get(0).getDateCellValue(), equalTo(df.parse("25/12/2014")));
assertThat(contents.get(0).get(1).getStringCellValue(), equalTo("02/04/15"));
assertThat(contents.get(0).get(1).getDateCellValue(), equalTo(df.parse("04/02/2015")));
assertThat(contents.get(0).get(2).getStringCellValue(), equalTo("14\". \"Mar\". \"2015"));
assertThat(contents.get(0).get(2).getDateCellValue(), equalTo(df.parse("14/03/2015")));
assertThat(contents.get(0).get(3).getStringCellValue(), equalTo("2015-05-05"));
assertThat(contents.get(0).get(3).getDateCellValue(), equalTo(df.parse("05/05/2015")));
assertThat(contents.get(1).size(), equalTo(4));
assertThat(contents.get(1).get(0).getStringCellValue(), equalTo("3.12"));
assertThat(contents.get(1).get(0).getNumericCellValue(), equalTo(3.12312312312));
assertThat(contents.get(1).get(1).getStringCellValue(), equalTo("1,023,042"));
assertThat(contents.get(1).get(1).getNumericCellValue(), equalTo(1023042.0));
assertThat(contents.get(1).get(2).getStringCellValue(), equalTo("-312,231.12"));
assertThat(contents.get(1).get(2).getNumericCellValue(), equalTo(-312231.12123145));
assertThat(contents.get(1).get(3).getStringCellValue(), equalTo("(132)"));
assertThat(contents.get(1).get(3).getNumericCellValue(), equalTo(-132.0));
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
public void install() throws InstallationException {
if(nodeDownloadRoot == null || nodeDownloadRoot.isEmpty()){
nodeDownloadRoot = DEFAULT_NODEJS_DOWNLOAD_ROOT;
}
if(npmDownloadRoot == null || npmDownloadRoot.isEmpty()){
npmDownloadRoot = DEFAULT_NPM_DOWNLOAD_ROOT;
}
synchronized (lock) {
if (!nodeIsAlreadyInstalled()) {
logger.info("Installing node version {}", nodeVersion);
if (!nodeVersion.startsWith("v")) {
logger.warn("Node version does not start with naming convention 'v'.");
}
if (config.getPlatform().isWindows()) {
installNodeForWindows();
} else {
installNodeDefault();
}
}
if (!npmIsAlreadyInstalled()) {
installNpm();
}
}
}
#location 15
#vulnerability type THREAD_SAFETY_VIOLATION | #fixed code
public void install() throws InstallationException {
// use static lock object for a synchronized block
synchronized (LOCK) {
if(nodeDownloadRoot == null || nodeDownloadRoot.isEmpty()){
nodeDownloadRoot = DEFAULT_NODEJS_DOWNLOAD_ROOT;
}
if(npmDownloadRoot == null || npmDownloadRoot.isEmpty()){
npmDownloadRoot = DEFAULT_NPM_DOWNLOAD_ROOT;
}
if (!nodeIsAlreadyInstalled()) {
logger.info("Installing node version {}", nodeVersion);
if (!nodeVersion.startsWith("v")) {
logger.warn("Node version does not start with naming convention 'v'.");
}
if (config.getPlatform().isWindows()) {
installNodeForWindows();
} else {
installNodeDefault();
}
}
if (!npmIsAlreadyInstalled()) {
installNpm();
}
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
static List<String> buildArguments(ProxyConfig proxyConfig, String npmRegistryURL) {
List<String> arguments = new ArrayList<String>();
if(npmRegistryURL != null && !npmRegistryURL.isEmpty()){
arguments.add ("--registry=" + npmRegistryURL);
}
if(!proxyConfig.isEmpty()){
Proxy proxy = null;
if(npmRegistryURL != null && !npmRegistryURL.isEmpty()){
proxy = proxyConfig.getProxyForUrl(npmRegistryURL);
}
if(proxy == null){
proxy = proxyConfig.getSecureProxy();
}
if(proxy == null){
proxy = proxyConfig.getInsecureProxy();
}
arguments.add("--https-proxy=" + proxy.getUri().toString());
arguments.add("--proxy=" + proxy.getUri().toString());
final String nonProxyHosts = proxy.getNonProxyHosts();
if (nonProxyHosts != null && !nonProxyHosts.isEmpty()) {
arguments.add("--noproxy=" + nonProxyHosts.replace('|',','));
}
}
return arguments;
}
#location 22
#vulnerability type NULL_DEREFERENCE | #fixed code
static List<String> buildArguments(ProxyConfig proxyConfig, String npmRegistryURL) {
List<String> arguments = new ArrayList<String>();
if(npmRegistryURL != null && !npmRegistryURL.isEmpty()){
arguments.add ("--registry=" + npmRegistryURL);
}
if(!proxyConfig.isEmpty()){
Proxy proxy = null;
if(npmRegistryURL != null && !npmRegistryURL.isEmpty()){
proxy = proxyConfig.getProxyForUrl(npmRegistryURL);
}
if(proxy == null){
proxy = proxyConfig.getSecureProxy();
}
if(proxy == null){
proxy = proxyConfig.getInsecureProxy();
}
arguments.add("--https-proxy=" + proxy.getUri().toString());
arguments.add("--proxy=" + proxy.getUri().toString());
final String nonProxyHosts = proxy.getNonProxyHosts();
if (nonProxyHosts != null && !nonProxyHosts.isEmpty()) {
final String[] nonProxyHostList = nonProxyHosts.split("\\|");
for (String nonProxyHost: nonProxyHostList) {
arguments.add("--noproxy=" + nonProxyHost.replace("*", ""));
}
}
}
return arguments;
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
public void install() throws InstallationException {
if(nodeDownloadRoot == null || nodeDownloadRoot.isEmpty()){
nodeDownloadRoot = DEFAULT_NODEJS_DOWNLOAD_ROOT;
}
if(npmDownloadRoot == null || npmDownloadRoot.isEmpty()){
npmDownloadRoot = DEFAULT_NPM_DOWNLOAD_ROOT;
}
synchronized (lock) {
if (!nodeIsAlreadyInstalled()) {
logger.info("Installing node version {}", nodeVersion);
if (!nodeVersion.startsWith("v")) {
logger.warn("Node version does not start with naming convention 'v'.");
}
if (config.getPlatform().isWindows()) {
installNodeForWindows();
} else {
installNodeDefault();
}
}
if (!npmIsAlreadyInstalled()) {
installNpm();
}
}
}
#location 3
#vulnerability type THREAD_SAFETY_VIOLATION | #fixed code
public void install() throws InstallationException {
// use static lock object for a synchronized block
synchronized (LOCK) {
if(nodeDownloadRoot == null || nodeDownloadRoot.isEmpty()){
nodeDownloadRoot = DEFAULT_NODEJS_DOWNLOAD_ROOT;
}
if(npmDownloadRoot == null || npmDownloadRoot.isEmpty()){
npmDownloadRoot = DEFAULT_NPM_DOWNLOAD_ROOT;
}
if (!nodeIsAlreadyInstalled()) {
logger.info("Installing node version {}", nodeVersion);
if (!nodeVersion.startsWith("v")) {
logger.warn("Node version does not start with naming convention 'v'.");
}
if (config.getPlatform().isWindows()) {
installNodeForWindows();
} else {
installNodeDefault();
}
}
if (!npmIsAlreadyInstalled()) {
installNpm();
}
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
public void install() throws InstallationException {
if(nodeDownloadRoot == null || nodeDownloadRoot.isEmpty()){
nodeDownloadRoot = DEFAULT_NODEJS_DOWNLOAD_ROOT;
}
if(npmDownloadRoot == null || npmDownloadRoot.isEmpty()){
npmDownloadRoot = DEFAULT_NPM_DOWNLOAD_ROOT;
}
synchronized (lock) {
if (!nodeIsAlreadyInstalled()) {
logger.info("Installing node version {}", nodeVersion);
if (!nodeVersion.startsWith("v")) {
logger.warn("Node version does not start with naming convention 'v'.");
}
if (config.getPlatform().isWindows()) {
installNodeForWindows();
} else {
installNodeDefault();
}
}
if (!npmIsAlreadyInstalled()) {
installNpm();
}
}
}
#location 21
#vulnerability type THREAD_SAFETY_VIOLATION | #fixed code
public void install() throws InstallationException {
// use static lock object for a synchronized block
synchronized (LOCK) {
if(nodeDownloadRoot == null || nodeDownloadRoot.isEmpty()){
nodeDownloadRoot = DEFAULT_NODEJS_DOWNLOAD_ROOT;
}
if(npmDownloadRoot == null || npmDownloadRoot.isEmpty()){
npmDownloadRoot = DEFAULT_NPM_DOWNLOAD_ROOT;
}
if (!nodeIsAlreadyInstalled()) {
logger.info("Installing node version {}", nodeVersion);
if (!nodeVersion.startsWith("v")) {
logger.warn("Node version does not start with naming convention 'v'.");
}
if (config.getPlatform().isWindows()) {
installNodeForWindows();
} else {
installNodeDefault();
}
}
if (!npmIsAlreadyInstalled()) {
installNpm();
}
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
public void install() throws InstallationException {
if(nodeDownloadRoot == null || nodeDownloadRoot.isEmpty()){
nodeDownloadRoot = DEFAULT_NODEJS_DOWNLOAD_ROOT;
}
if(npmDownloadRoot == null || npmDownloadRoot.isEmpty()){
npmDownloadRoot = DEFAULT_NPM_DOWNLOAD_ROOT;
}
synchronized (lock) {
if (!nodeIsAlreadyInstalled()) {
logger.info("Installing node version {}", nodeVersion);
if (!nodeVersion.startsWith("v")) {
logger.warn("Node version does not start with naming convention 'v'.");
}
if (config.getPlatform().isWindows()) {
installNodeForWindows();
} else {
installNodeDefault();
}
}
if (!npmIsAlreadyInstalled()) {
installNpm();
}
}
}
#location 6
#vulnerability type THREAD_SAFETY_VIOLATION | #fixed code
public void install() throws InstallationException {
// use static lock object for a synchronized block
synchronized (LOCK) {
if(nodeDownloadRoot == null || nodeDownloadRoot.isEmpty()){
nodeDownloadRoot = DEFAULT_NODEJS_DOWNLOAD_ROOT;
}
if(npmDownloadRoot == null || npmDownloadRoot.isEmpty()){
npmDownloadRoot = DEFAULT_NPM_DOWNLOAD_ROOT;
}
if (!nodeIsAlreadyInstalled()) {
logger.info("Installing node version {}", nodeVersion);
if (!nodeVersion.startsWith("v")) {
logger.warn("Node version does not start with naming convention 'v'.");
}
if (config.getPlatform().isWindows()) {
installNodeForWindows();
} else {
installNodeDefault();
}
}
if (!npmIsAlreadyInstalled()) {
installNpm();
}
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
private void initialize(
final String methodName,
final AtomicReference<OperationArguments> operationArgumentsRef,
final AtomicReference<IAuthentication> authenticationRef
) throws IOException, URISyntaxException
{
// parse the operations arguments from stdin (this is how git sends commands)
// see: https://www.kernel.org/pub/software/scm/git/docs/technical/api-credentials.html
// see: https://www.kernel.org/pub/software/scm/git/docs/git-credential.html
final OperationArguments operationArguments;
final BufferedReader reader = new BufferedReader(new InputStreamReader(standardIn));
try
{
operationArguments = new OperationArguments(reader);
}
finally
{
IOUtils.closeQuietly(reader);
}
Debug.Assert(operationArguments.TargetUri != null, "The operationArguments.TargetUri is null");
final Configuration config = componentFactory.createConfiguration();
loadOperationArguments(operationArguments, config);
enableTraceLogging(operationArguments);
Trace.writeLine("Program::" + methodName);
Trace.writeLine(" targetUri = " + operationArguments.TargetUri);
final ISecureStore secureStore = componentFactory.createSecureStore();
final IAuthentication authentication = componentFactory.createAuthentication(operationArguments, secureStore);
operationArgumentsRef.set(operationArguments);
authenticationRef.set(authentication);
}
#location 18
#vulnerability type RESOURCE_LEAK | #fixed code
private void initialize(
final String methodName,
final AtomicReference<OperationArguments> operationArgumentsRef,
final AtomicReference<IAuthentication> authenticationRef
) throws IOException, URISyntaxException
{
// parse the operations arguments from stdin (this is how git sends commands)
// see: https://www.kernel.org/pub/software/scm/git/docs/technical/api-credentials.html
// see: https://www.kernel.org/pub/software/scm/git/docs/git-credential.html
final OperationArguments operationArguments;
final BufferedReader reader = new BufferedReader(new InputStreamReader(standardIn));
try
{
operationArguments = new OperationArguments(reader);
}
finally
{
IOHelper.closeQuietly(reader);
}
Debug.Assert(operationArguments.TargetUri != null, "The operationArguments.TargetUri is null");
final Configuration config = componentFactory.createConfiguration();
loadOperationArguments(operationArguments, config);
enableTraceLogging(operationArguments);
Trace.writeLine("Program::" + methodName);
Trace.writeLine(" targetUri = " + operationArguments.TargetUri);
final ISecureStore secureStore = componentFactory.createSecureStore();
final IAuthentication authentication = componentFactory.createAuthentication(operationArguments, secureStore);
operationArgumentsRef.set(operationArguments);
authenticationRef.set(authentication);
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
void save()
{
if (backingFile != null)
{
// TODO: consider creating a backup of the file, if it exists, before overwriting it
FileOutputStream fos = null;
try
{
fos = new FileOutputStream(backingFile);
final PrintStream printStream = new PrintStream(fos);
toXml(printStream);
}
catch (final FileNotFoundException e)
{
throw new Error("Error during save()", e);
}
finally
{
IOUtils.closeQuietly(fos);
}
}
}
#location 11
#vulnerability type RESOURCE_LEAK | #fixed code
void reload()
{
if (backingFile != null)
{
FileInputStream fis = null;
try
{
fis = new FileInputStream(backingFile);
final InsecureStore clone = fromXml(fis);
if (clone != null)
{
this.Tokens.clear();
this.Tokens.putAll(clone.Tokens);
this.Credentials.clear();
this.Credentials.putAll(clone.Credentials);
}
}
catch (FileNotFoundException e)
{
Trace.writeLine("backingFile '" + backingFile.getAbsolutePath() + "' did not exist.");
}
finally
{
IOUtils.closeQuietly(fis);
}
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
static InsecureStore clone(InsecureStore inputStore)
{
ByteArrayOutputStream baos = null;
ByteArrayInputStream bais = null;
try
{
baos = new ByteArrayOutputStream();
final PrintStream ps = new PrintStream(baos);
inputStore.toXml(ps);
ps.flush();
final String xmlString = baos.toString();
bais = new ByteArrayInputStream(xmlString.getBytes());
final InsecureStore result = InsecureStore.fromXml(bais);
return result;
}
finally
{
IOUtils.closeQuietly(baos);
IOUtils.closeQuietly(bais);
}
}
#location 11
#vulnerability type RESOURCE_LEAK | #fixed code
static InsecureStore clone(InsecureStore inputStore)
{
ByteArrayOutputStream baos = null;
ByteArrayInputStream bais = null;
try
{
baos = new ByteArrayOutputStream();
inputStore.toXml(baos);
final String xmlString = baos.toString();
bais = new ByteArrayInputStream(xmlString.getBytes());
final InsecureStore result = InsecureStore.fromXml(bais);
return result;
}
finally
{
IOUtils.closeQuietly(baos);
IOUtils.closeQuietly(bais);
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
private String doHttpGet(URL url) throws IOException, RestApiException {
System.out.println("GET " + url.toString());
HttpURLConnection connection = JdkHttpTransport.createConnection(config, url, headers, false);
connection.setInstanceFollowRedirects(true);
InputStream in;
System.out.println("HTTP " + connection.getResponseCode());
if(connection.getResponseCode() >= 400) {
in = connection.getErrorStream();
} else {
in = connection.getInputStream();
}
String encoding = connection.getHeaderField(CONTENT_HEADER);
StringBuilder responseBuilder = new StringBuilder();
if (encoding.startsWith(ContentType.JSON.toString())) {
BufferedInputStream bin = new BufferedInputStream(in);
//read the server response body
byte[] buffer = new byte[1024];
int bytesRead = 0;
while ((bytesRead = bin.read(buffer)) != -1) {
responseBuilder.append(new String(buffer, 0, bytesRead));
}
} else {
throw new IllegalStateException("Unknown content type on HTTP GET.");
}
in.close();
//send back the server response
return responseBuilder.toString();
}
#location 29
#vulnerability type RESOURCE_LEAK | #fixed code
private String doHttpGet(URL url) throws IOException, RestApiException {
System.out.println("GET " + url.toString());
HttpURLConnection connection = JdkHttpTransport.createConnection(config, url, headers, false);
connection.setInstanceFollowRedirects(true);
InputStream in;
System.out.println("HTTP " + connection.getResponseCode());
if(connection.getResponseCode() >= 400) {
in = connection.getErrorStream();
} else {
in = connection.getInputStream();
}
String encoding = connection.getHeaderField(CONTENT_HEADER);
StringBuilder responseBuilder = new StringBuilder();
if (encoding.startsWith(ContentType.JSON.toString())) {
BufferedInputStream bin = new BufferedInputStream(in);
//read the server response body
byte[] buffer = new byte[1024];
int bytesRead = 0;
while ((bytesRead = bin.read(buffer)) != -1) {
responseBuilder.append(new String(buffer, 0, bytesRead));
}
bin.close();
} else {
throw new IllegalStateException("Unknown content type on HTTP GET.");
}
in.close();
//send back the server response
return responseBuilder.toString();
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
private String doHttpGet(URL url) throws IOException, RestApiException {
System.out.println("GET " + url.toString());
HttpURLConnection connection = JdkHttpTransport.createConnection(config, url, headers, false);
connection.setInstanceFollowRedirects(true);
InputStream in;
System.out.println("HTTP " + connection.getResponseCode());
if(connection.getResponseCode() >= 400) {
in = connection.getErrorStream();
} else {
in = connection.getInputStream();
}
String encoding = connection.getHeaderField(CONTENT_HEADER);
StringBuilder responseBuilder = new StringBuilder();
if (encoding.startsWith(ContentType.JSON.toString())) {
BufferedInputStream bin = new BufferedInputStream(in);
//read the server response body
byte[] buffer = new byte[1024];
int bytesRead = 0;
while ((bytesRead = bin.read(buffer)) != -1) {
responseBuilder.append(new String(buffer, 0, bytesRead));
}
} else {
throw new IllegalStateException("Unknown content type on HTTP GET.");
}
in.close();
//send back the server response
return responseBuilder.toString();
}
#location 29
#vulnerability type RESOURCE_LEAK | #fixed code
private String doHttpGet(URL url) throws IOException, RestApiException {
System.out.println("GET " + url.toString());
HttpURLConnection connection = JdkHttpTransport.createConnection(config, url, headers, false);
connection.setInstanceFollowRedirects(true);
InputStream in;
System.out.println("HTTP " + connection.getResponseCode());
if(connection.getResponseCode() >= 400) {
in = connection.getErrorStream();
} else {
in = connection.getInputStream();
}
String encoding = connection.getHeaderField(CONTENT_HEADER);
StringBuilder responseBuilder = new StringBuilder();
if (encoding.startsWith(ContentType.JSON.toString())) {
BufferedInputStream bin = new BufferedInputStream(in);
//read the server response body
byte[] buffer = new byte[1024];
int bytesRead = 0;
while ((bytesRead = bin.read(buffer)) != -1) {
responseBuilder.append(new String(buffer, 0, bytesRead));
}
bin.close();
} else {
throw new IllegalStateException("Unknown content type on HTTP GET.");
}
in.close();
//send back the server response
return responseBuilder.toString();
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
private String doHttpPost(URL url, String body) throws IOException {
System.out.println("POST " + url.toString() + " " + body);
HttpURLConnection connection = JdkHttpTransport.createConnection(config, url, headers, false);
connection.setInstanceFollowRedirects(true);
connection.setDoOutput(true);
connection.setRequestMethod("POST");
OutputStream out = connection.getOutputStream();
InputStream in;
out.write(body.getBytes());
out.flush();
out.close();
System.out.print("HTTP " + connection.getResponseCode());
if(connection.getResponseCode() >= 400) {
in = connection.getErrorStream();
} else {
in = connection.getInputStream();
}
BufferedInputStream bin = new BufferedInputStream(in);
StringBuilder responseBuilder = new StringBuilder();
//read the server response body
byte[] buffer = new byte[1024];
int bytesRead = 0;
while ((bytesRead = bin.read(buffer)) != -1) {
responseBuilder.append(new String(buffer, 0, bytesRead));
}
String serverResponse = responseBuilder.toString();
System.out.print(serverResponse + "\r\n");
if(connection.getResponseCode() >= 400) {
throw new IllegalStateException(serverResponse);
} else {
return serverResponse;
}
}
#location 32
#vulnerability type RESOURCE_LEAK | #fixed code
private String doHttpPost(URL url, String body) throws IOException {
System.out.println("POST " + url.toString() + " " + body);
HttpURLConnection connection = JdkHttpTransport.createConnection(config, url, headers, false);
connection.setInstanceFollowRedirects(true);
connection.setDoOutput(true);
connection.setRequestMethod("POST");
OutputStream out = connection.getOutputStream();
InputStream in;
out.write(body.getBytes());
out.flush();
out.close();
System.out.print("HTTP " + connection.getResponseCode());
if(connection.getResponseCode() >= 400) {
in = connection.getErrorStream();
} else {
in = connection.getInputStream();
}
BufferedInputStream bin = new BufferedInputStream(in);
StringBuilder responseBuilder = new StringBuilder();
//read the server response body
byte[] buffer = new byte[1024];
int bytesRead = 0;
while ((bytesRead = bin.read(buffer)) != -1) {
responseBuilder.append(new String(buffer, 0, bytesRead));
}
bin.close();
String serverResponse = responseBuilder.toString();
System.out.print(serverResponse + "\r\n");
if(connection.getResponseCode() >= 400) {
throw new IllegalStateException(serverResponse);
} else {
return serverResponse;
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
private String doHttpPost(URL url, String body) throws IOException {
System.out.println("POST " + url.toString() + " " + body);
HttpURLConnection connection = JdkHttpTransport.createConnection(config, url, headers, false);
connection.setInstanceFollowRedirects(true);
connection.setDoOutput(true);
connection.setRequestMethod("POST");
OutputStream out = connection.getOutputStream();
InputStream in;
out.write(body.getBytes());
out.flush();
out.close();
System.out.print("HTTP " + connection.getResponseCode());
if(connection.getResponseCode() >= 400) {
in = connection.getErrorStream();
} else {
in = connection.getInputStream();
}
BufferedInputStream bin = new BufferedInputStream(in);
StringBuilder responseBuilder = new StringBuilder();
//read the server response body
byte[] buffer = new byte[1024];
int bytesRead = 0;
while ((bytesRead = bin.read(buffer)) != -1) {
responseBuilder.append(new String(buffer, 0, bytesRead));
}
String serverResponse = responseBuilder.toString();
System.out.print(serverResponse + "\r\n");
if(connection.getResponseCode() >= 400) {
throw new IllegalStateException(serverResponse);
} else {
return serverResponse;
}
}
#location 32
#vulnerability type RESOURCE_LEAK | #fixed code
private String doHttpPost(URL url, String body) throws IOException {
System.out.println("POST " + url.toString() + " " + body);
HttpURLConnection connection = JdkHttpTransport.createConnection(config, url, headers, false);
connection.setInstanceFollowRedirects(true);
connection.setDoOutput(true);
connection.setRequestMethod("POST");
OutputStream out = connection.getOutputStream();
InputStream in;
out.write(body.getBytes());
out.flush();
out.close();
System.out.print("HTTP " + connection.getResponseCode());
if(connection.getResponseCode() >= 400) {
in = connection.getErrorStream();
} else {
in = connection.getInputStream();
}
BufferedInputStream bin = new BufferedInputStream(in);
StringBuilder responseBuilder = new StringBuilder();
//read the server response body
byte[] buffer = new byte[1024];
int bytesRead = 0;
while ((bytesRead = bin.read(buffer)) != -1) {
responseBuilder.append(new String(buffer, 0, bytesRead));
}
bin.close();
String serverResponse = responseBuilder.toString();
System.out.print(serverResponse + "\r\n");
if(connection.getResponseCode() >= 400) {
throw new IllegalStateException(serverResponse);
} else {
return serverResponse;
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Override
public DataFrame<R, String> read(Consumer<DbSourceOptions<R>> configurator) throws DataFrameException {
final DbSourceOptions<R> options = initOptions(new DbSourceOptions<>(), configurator);
try (Connection conn = options.getConnection()) {
final SQL sql = SQL.of(options.getSql(), options.getParameters().orElse(new Object[0]));
return sql.executeQuery(conn, rs -> read(rs, options));
} catch (Exception ex) {
throw new DataFrameException("Failed to create DataFrame from database request: " + options, ex);
}
}
#location 6
#vulnerability type NULL_DEREFERENCE | #fixed code
@Override
public DataFrame<R, String> read(Consumer<DbSourceOptions<R>> configurator) throws DataFrameException {
final DbSourceOptions<R> options = initOptions(new DbSourceOptions<>(), configurator);
try (Connection conn = options.getConnection()) {
conn.setAutoCommit(options.isAutoCommit());
conn.setReadOnly(options.isReadOnly());
final int fetchSize = options.getFetchSize().orElse(1000);
final SQL sql = SQL.of(options.getSql(), options.getParameters().orElse(new Object[0]));
return sql.executeQuery(conn, fetchSize, rs -> read(rs, options));
} catch (Exception ex) {
throw new DataFrameException("Failed to create DataFrame from database request: " + options, ex);
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
public void testParse() throws ParseException, IOException, Exception {
// JSONObject parsed = iseParser.parse(getRawMessage().getBytes());
// assertNotNull(parsed);
URL log_url = getClass().getClassLoader().getResource("IseSample.log");
BufferedReader br = new BufferedReader(new FileReader(log_url.getFile()));
String line = "";
while ((line = br.readLine()) != null) {
System.out.println(line);
JSONObject parsed = iseParser.parse(line.getBytes());
System.out.println(parsed);
assertEquals(true, super.validateJsonData(super.getSchemaJsonString(), parsed.toString()));
}
br.close();
}
#location 16
#vulnerability type RESOURCE_LEAK | #fixed code
public void testParse() throws ParseException, IOException, Exception {
for (String inputString : getInputStrings()) {
JSONObject parsed = parser.parse(inputString.getBytes());
assertNotNull(parsed);
System.out.println(parsed);
JSONParser parser = new JSONParser();
Map<?, ?> json=null;
try {
json = (Map<?, ?>) parser.parse(parsed.toJSONString());
assertEquals(true, validateJsonData(super.getSchemaJsonString(), json.toString()));
} catch (ParseException e) {
e.printStackTrace();
}
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Override
public Map<String, JSONObject> alert(JSONObject raw_message) {
Map<String, JSONObject> alerts = new HashMap<String, JSONObject>();
JSONObject content = (JSONObject) raw_message.get("message");
JSONObject enrichment = null;
if (raw_message.containsKey("enrichment"))
enrichment = (JSONObject) raw_message.get("enrichment");
for (String keyword : keywordList) {
if (content.toString().contains(keyword)) {
JSONObject alert = new JSONObject();
String source = "unknown";
String dest = "unknown";
String host = "unknown";
if (content.containsKey("ip_src_addr"))
{
source = content.get("ip_src_addr").toString();
if(RangeChecker.checkRange(loaded_whitelist, source))
host = source;
}
if (content.containsKey("ip_dst_addr"))
{
dest = content.get("ip_dst_addr").toString();
if(RangeChecker.checkRange(loaded_whitelist, dest))
host = dest;
}
alert.put("designated_host", host);
alert.put("description", content.get("original_string").toString());
alert.put("priority", "MED");
String alert_id = generateAlertId(source, dest, 0);
alert.put("alert_id", alert_id);
alerts.put(alert_id, alert);
alert.put("enrichment", enrichment);
return alerts;
}
}
return null;
}
#location 36
#vulnerability type NULL_DEREFERENCE | #fixed code
@Override
public Map<String, JSONObject> alert(JSONObject raw_message) {
Map<String, JSONObject> alerts = new HashMap<String, JSONObject>();
JSONObject content = (JSONObject) raw_message.get("message");
JSONObject enrichment = null;
if (raw_message.containsKey("enrichment"))
enrichment = (JSONObject) raw_message.get("enrichment");
for (String keyword : keywordList) {
if (content.toString().contains(keyword)) {
//check it doesn't have an "exception" keyword in it
for (String exception : keywordExceptionList) {
if (content.toString().contains(exception)) {
return null;
}
}
JSONObject alert = new JSONObject();
String source = "unknown";
String dest = "unknown";
String host = "unknown";
if (content.containsKey("ip_src_addr"))
{
source = content.get("ip_src_addr").toString();
if(RangeChecker.checkRange(loaded_whitelist, source))
host = source;
}
if (content.containsKey("ip_dst_addr"))
{
dest = content.get("ip_dst_addr").toString();
if(RangeChecker.checkRange(loaded_whitelist, dest))
host = dest;
}
alert.put("designated_host", host);
alert.put("description", content.get("original_string").toString());
alert.put("priority", "MED");
String alert_id = generateAlertId(source, dest, 0);
alert.put("alert_id", alert_id);
alerts.put(alert_id, alert);
alert.put("enrichment", enrichment);
return alerts;
}
}
return null;
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Override
public boolean initializeAdapter() {
_LOG.info("Initializing MysqlAdapter....");
try {
boolean reachable = (java.lang.Runtime.getRuntime()
.exec("ping -n 1 " + _ip).waitFor() == 0);
if (!reachable)
throw new Exception("Unable to reach IP....");
Class.forName("com.mysql.jdbc.Driver");
connection = DriverManager.getConnection("jdbc:mysql://" + _ip
+ "/" + _tablename + "?user=" + _username + "&password="
+ _password);
connection.setReadOnly(true);
if (!connection.isValid(0))
throw new Exception("Invalid connection string....");
_LOG.info("Set JDBC connection....");
return true;
} catch (Exception e) {
e.printStackTrace();
_LOG.error("JDBC connection failed....");
return false;
}
}
#location 9
#vulnerability type RESOURCE_LEAK | #fixed code
@Override
public boolean initializeAdapter() {
_LOG.info("Initializing MysqlAdapter....");
try {
Class.forName("com.mysql.jdbc.Driver");
connection = DriverManager.getConnection("jdbc:mysql://" + _ip
+ "/" + _tablename + "?user=" + _username + "&password="
+ _password);
connection.setReadOnly(true);
if (!connection.isValid(0))
throw new Exception("Invalid connection string....");
_LOG.info("Set JDBC connection....");
return true;
} catch (Exception e) {
e.printStackTrace();
_LOG.error("JDBC connection failed....");
return false;
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
public void testParse() throws IOException, Exception {
URL log_url = getClass().getClassLoader().getResource("LancopeSample.log");
BufferedReader br;
try {
br = new BufferedReader(new FileReader(log_url.getFile()));
String line = "";
while ((line = br.readLine()) != null) {
System.out.println(line);
assertNotNull(line);
JSONObject parsed = lancopeParser.parse(line.getBytes());
System.out.println(parsed);
assertEquals(true, validateJsonData(super.getSchemaJsonString(), parsed.toString()));
}
br.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
#location 16
#vulnerability type RESOURCE_LEAK | #fixed code
public void testParse() throws IOException, Exception {
for (String inputString : getInputStrings()) {
JSONObject parsed = parser.parse(inputString.getBytes());
assertNotNull(parsed);
System.out.println(parsed);
JSONParser parser = new JSONParser();
Map<?, ?> json=null;
try {
json = (Map<?, ?>) parser.parse(parsed.toJSONString());
assertEquals(true, validateJsonData(super.getSchemaJsonString(), json.toString()));
} catch (ParseException e) {
e.printStackTrace();
}
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Override
public JSONObject parse(byte[] raw_message) {
String toParse = "";
JSONObject toReturn;
try {
toParse = new String(raw_message, "UTF-8");
//System.out.println("Received message: " + toParse);
OpenSOCMatch gm = grok.match(toParse);
gm.captures();
toReturn = new JSONObject();
toReturn.putAll(gm.toMap());
String id = toReturn.get("uid").toString();
// We are not parsing the fedata for multi part message as we cannot determine how we can split the message and how many multi part messages can there be.
// The message itself will be stored in the response.
String[] tokens = id.split("\\.");
if(tokens.length == 1 ) {
String syslog = toReturn.get("syslog").toString();
Multimap<String, String> multiMap = formatMain(syslog) ;
for(String key : multiMap.keySet()) {
String value =Joiner.on(",").join( multiMap.get(key));
toReturn.put(key, value);
}
}
String ip_src_addr = (String) toReturn.get("dvc");
String ip_src_port = (String) toReturn.get("src_port");
String ip_dst_addr = (String) toReturn.get("dst_ip");
String ip_dst_port = (String) toReturn.get("dst_port");
if(ip_src_addr != null)
toReturn.put("ip_src_addr", ip_src_addr);
if(ip_src_port != null)
toReturn.put("ip_src_port", ip_src_port);
if(ip_dst_addr != null)
toReturn.put("ip_dst_addr", ip_dst_addr);
if(ip_dst_port != null)
toReturn.put("ip_dst_port", ip_dst_port);
return toReturn;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
#location 19
#vulnerability type NULL_DEREFERENCE | #fixed code
@Override
public JSONObject parse(byte[] raw_message) {
String toParse = "";
JSONObject toReturn;
try {
toParse = new String(raw_message, "UTF-8");
//System.out.println("Received message: " + toParse);
//OpenSOCMatch gm = grok.match(toParse);
//gm.captures();
toReturn = new JSONObject();
String[] mTokens = toParse.split(" ");
//toReturn.putAll(gm.toMap());
String id = mTokens[0];
// We are not parsing the fedata for multi part message as we cannot determine how we can split the message and how many multi part messages can there be.
// The message itself will be stored in the response.
String[] tokens = id.split("\\.");
if(tokens.length == 2 ) {
String[] array = Arrays.copyOfRange(mTokens, 1, mTokens.length-1);
String syslog = Joiner.on(" ").join(array);
Multimap<String, String> multiMap = formatMain(syslog) ;
for(String key : multiMap.keySet()) {
String value =Joiner.on(",").join( multiMap.get(key));
toReturn.put(key, value);
}
}
String ip_src_addr = (String) toReturn.get("dvc");
String ip_src_port = (String) toReturn.get("src_port");
String ip_dst_addr = (String) toReturn.get("dst_ip");
String ip_dst_port = (String) toReturn.get("dst_port");
if(ip_src_addr != null)
toReturn.put("ip_src_addr", ip_src_addr);
if(ip_src_port != null)
toReturn.put("ip_src_port", ip_src_port);
if(ip_dst_addr != null)
toReturn.put("ip_dst_addr", ip_dst_addr);
if(ip_dst_port != null)
toReturn.put("ip_dst_port", ip_dst_port);
System.out.println(toReturn);
return toReturn;
} catch (Exception e) {
e.printStackTrace();
return null;
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Override
public JSONObject parse(byte[] raw_message) {
String toParse = "";
JSONObject toReturn;
try {
toParse = new String(raw_message, "UTF-8");
//System.out.println("Received message: " + toParse);
Match gm = grok.match(toParse);
gm.captures();
toReturn = new JSONObject();
toReturn.putAll(gm.toMap());
String id = toReturn.get("uid").toString();
// We are not parsing the fedata for multi part message as we cannot determine how we can split the message and how many multi part messages can there be.
// The message itself will be stored in the response.
String[] tokens = id.split("\\.");
if(tokens.length == 1 ) {
String syslog = toReturn.get("syslog").toString();
Multimap<String, String> multiMap = formatMain(syslog) ;
for(String key : multiMap.keySet()) {
toReturn.put(key, multiMap.get(key));
}
}
return toReturn;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
#location 28
#vulnerability type NULL_DEREFERENCE | #fixed code
@Override
public JSONObject parse(byte[] raw_message) {
String toParse = "";
JSONObject toReturn;
try {
toParse = new String(raw_message, "UTF-8");
//System.out.println("Received message: " + toParse);
Match gm = grok.match(toParse);
gm.captures();
toReturn = new JSONObject();
toReturn.putAll(gm.toMap());
String id = toReturn.get("uid").toString();
// We are not parsing the fedata for multi part message as we cannot determine how we can split the message and how many multi part messages can there be.
// The message itself will be stored in the response.
String[] tokens = id.split("\\.");
if(tokens.length == 1 ) {
String syslog = toReturn.get("syslog").toString();
Multimap<String, String> multiMap = formatMain(syslog) ;
for(String key : multiMap.keySet()) {
String value =Joiner.on(",").join( multiMap.get(key));
toReturn.put(key, value);
}
}
String ip_src_addr = (String) toReturn.get("dvc");
String ip_src_port = (String) toReturn.get("src_port");
String ip_dst_addr = (String) toReturn.get("dst_ip");
String ip_dst_port = (String) toReturn.get("dst_port");
if(ip_src_addr != null)
toReturn.put("ip_src_addr", ip_src_addr);
if(ip_src_port != null)
toReturn.put("ip_src_port", ip_src_port);
if(ip_dst_addr != null)
toReturn.put("ip_dst_addr", ip_dst_addr);
if(ip_dst_port != null)
toReturn.put("ip_dst_port", ip_dst_port);
return toReturn;
} catch (Exception e) {
e.printStackTrace();
return null;
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Override
protected Object createTest() throws Exception {
ensureHierarchicalFixturesAreValid();
return instances.getLast();
}
#location 4
#vulnerability type THREAD_SAFETY_VIOLATION | #fixed code
@Override
protected Object createTest() throws Exception {
instances = createHierarchicalFixtures();
return instances.getLast();
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Override
protected Statement withBefores(final FrameworkMethod method, final Object target, final Statement next) {
Statement statement = next;
for (int i = instances.size() - 1; i >= 0; i--) {
final Object instance = instances.get(i);
final TestClass tClass = new TestClass(instance.getClass());
final List<FrameworkMethod> befores = tClass.getAnnotatedMethods(Before.class);
statement = befores.isEmpty() ? statement : new RunBefores(statement, befores, instance);
}
return statement;
}
#location 5
#vulnerability type THREAD_SAFETY_VIOLATION | #fixed code
@Override
protected Statement withBefores(final FrameworkMethod method, final Object target, final Statement next) {
Statement statement = next;
for (int i = instances.size() - 1; i >= 0; i--) {
final Object instance = instances.get(i);
final TestClass tClass = TestClassPool.forClass(instance.getClass());
final List<FrameworkMethod> befores = tClass.getAnnotatedMethods(Before.class);
statement = befores.isEmpty() ? statement : new RunBefores(statement, befores, instance);
}
return statement;
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Override
protected Statement withAfters(final FrameworkMethod method, final Object target, final Statement next) {
Statement statement = next;
for (int i = instances.size() - 1; i >= 0; i--) {
final Object instance = instances.get(i);
final TestClass tClass = new TestClass(instance.getClass());
final List<FrameworkMethod> afters = tClass.getAnnotatedMethods(After.class);
statement = afters.isEmpty() ? statement : new RunAfters(statement, afters, instance);
}
return statement;
}
#location 5
#vulnerability type THREAD_SAFETY_VIOLATION | #fixed code
@Override
protected Statement withAfters(final FrameworkMethod method, final Object target, final Statement next) {
Statement statement = next;
for (int i = instances.size() - 1; i >= 0; i--) {
final Object instance = instances.get(i);
final TestClass tClass = TestClassPool.forClass(instance.getClass());
final List<FrameworkMethod> afters = tClass.getAnnotatedMethods(After.class);
statement = afters.isEmpty() ? statement : new RunAfters(statement, afters, instance);
}
return statement;
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
private void registerResources(final PluginAnnotation<T> pluginAnnotation, final ClassLoader classLoader) throws IOException {
final T annot = pluginAnnotation.getAnnotation();
WatchEventDTO watchEventDTO = WatchEventDTO.parse(annot);
String path = watchEventDTO.getPath();
// normalize
if (path.equals(".") || path.equals("/"))
path = "";
if (path.endsWith("/"))
path = path.substring(0, path.length() - 2);
// classpath resources (already should contain extraClasspath)
Enumeration<URL> en = classLoader.getResources(path);
while (en.hasMoreElements()) {
try {
URI uri = en.nextElement().toURI();
// check that this is a local accessible file (not vfs inside JAR etc.)
try {
new File(uri);
} catch (Exception e) {
LOGGER.trace("Skipping uri {}, not a local file.", uri);
continue;
}
LOGGER.debug("Registering resource listener on classpath URI {}", uri);
registerResourceListener(pluginAnnotation, watchEventDTO, classLoader, uri);
} catch (URISyntaxException e) {
LOGGER.error("Unable convert root resource path URL to URI", e);
}
}
// add extra directories for watchResources property
if (!watchEventDTO.isClassFileEvent()) {
for (URL url : pluginManager.getPluginConfiguration(classLoader).getWatchResources()) {
try {
Path watchResourcePath = Paths.get(url.toURI());
Path pathInWatchResource = watchResourcePath.resolve(path);
if (pathInWatchResource.toFile().exists()) {
LOGGER.debug("Registering resource listener on watchResources URI {}", pathInWatchResource.toUri());
registerResourceListener(pluginAnnotation, watchEventDTO, classLoader, pathInWatchResource.toUri());
}
} catch (URISyntaxException e) {
LOGGER.error("Unable convert watch resource path URL {} to URI", e, url);
}
}
}
}
#location 8
#vulnerability type NULL_DEREFERENCE | #fixed code
private void registerResources(final PluginAnnotation<T> pluginAnnotation, final ClassLoader classLoader) throws IOException {
final T annot = pluginAnnotation.getAnnotation();
WatchEventDTO watchEventDTO = WatchEventDTO.parse(annot);
String path = watchEventDTO.getPath();
// normalize
if (path == null || path.equals(".") || path.equals("/"))
path = "";
if (path.endsWith("/"))
path = path.substring(0, path.length() - 2);
// classpath resources (already should contain extraClasspath)
Enumeration<URL> en = classLoader.getResources(path);
while (en.hasMoreElements()) {
try {
URI uri = en.nextElement().toURI();
// check that this is a local accessible file (not vfs inside JAR etc.)
try {
new File(uri);
} catch (Exception e) {
LOGGER.trace("Skipping uri {}, not a local file.", uri);
continue;
}
LOGGER.debug("Registering resource listener on classpath URI {}", uri);
registerResourceListener(pluginAnnotation, watchEventDTO, classLoader, uri);
} catch (URISyntaxException e) {
LOGGER.error("Unable convert root resource path URL to URI", e);
}
}
// add extra directories for watchResources property
if (!watchEventDTO.isClassFileEvent()) {
for (URL url : pluginManager.getPluginConfiguration(classLoader).getWatchResources()) {
try {
Path watchResourcePath = Paths.get(url.toURI());
Path pathInWatchResource = watchResourcePath.resolve(path);
if (pathInWatchResource.toFile().exists()) {
LOGGER.debug("Registering resource listener on watchResources URI {}", pathInWatchResource.toUri());
registerResourceListener(pluginAnnotation, watchEventDTO, classLoader, pathInWatchResource.toUri());
}
} catch (URISyntaxException e) {
LOGGER.error("Unable convert watch resource path URL {} to URI", e, url);
}
}
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
public static void register(Object generatorStrategy, Object classGenerator, byte[] bytes) {
try {
ClassPool classPool = ProxyTransformationUtils.getClassPool(generatorStrategy.getClass().getClassLoader());
CtClass cc = classPool.makeClass(new ByteArrayInputStream(bytes), false);
generatorParams.put(cc.getName(), new GeneratorParams(generatorStrategy, classGenerator));
cc.detach();
} catch (IOException | RuntimeException e) {
LOGGER.error("Error saving parameters of a creation of a Cglib proxy", e);
}
}
#location 4
#vulnerability type RESOURCE_LEAK | #fixed code
public static void register(Object generatorStrategy, Object classGenerator, byte[] bytes) {
try {
generatorParams.put(getClassName(bytes), new GeneratorParams(generatorStrategy, classGenerator));
} catch (Exception e) {
LOGGER.error("Error saving parameters of a creation of a Cglib proxy", e);
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
public static Object callPluginMethod(Class pluginClass, ClassLoader appClassLoader, String method, Class[] paramTypes, Object[] params) {
Object pluginInstance = PluginManager.getInstance().getPlugin(pluginClass.getName(), appClassLoader);
try {
Method m = pluginInstance.getClass().getDeclaredMethod(method, paramTypes);
return m.invoke(pluginInstance, params);
} catch (Exception e) {
throw new Error(String.format("Exception calling method {} on plugin class {}", method, pluginClass), e);
}
}
#location 5
#vulnerability type NULL_DEREFERENCE | #fixed code
public static Object callPluginMethod(Class pluginClass, ClassLoader appClassLoader, String method, Class[] paramTypes, Object[] params) {
Object pluginInstance = PluginManager.getInstance().getPlugin(pluginClass.getName(), appClassLoader);
try {
Method m = pluginInstance.getClass().getDeclaredMethod(method, paramTypes);
return m.invoke(pluginInstance, params);
} catch (Exception e) {
throw new Error(String.format("Exception calling method %s on plugin class %s", method, pluginClass), e);
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@OnClassLoadEvent(classNameRegexp = ".*", events = LoadEvent.REDEFINE, skipSynthetic = false)
public static byte[] transformRedefinitions(final Class<?> classBeingRedefined, final byte[] classfileBuffer,
final ClassLoader loader) throws IllegalClassFormatException, IOException, RuntimeException {
// load the class in the pool for ClassfileSignatureComparer and JavassistProxyTransformer
ClassPool cp = ProxyTransformationUtils.getClassPool(loader);
CtClass cc = cp.makeClass(new ByteArrayInputStream(classfileBuffer), false);
byte[] result = classfileBuffer;
boolean useJavassistProxyTransformer = true;
if (useJavassistProxyTransformer) {
result = JavassistProxyTransformer.transform(classBeingRedefined, cc, cp, result);
} else {
result = JavaProxyTransformer.transform(classBeingRedefined, cc, cp, result);
}
return CglibProxyTransformer.transform(classBeingRedefined, cc, cp, result, loader);
}
#location 6
#vulnerability type RESOURCE_LEAK | #fixed code
@OnClassLoadEvent(classNameRegexp = ".*", events = LoadEvent.REDEFINE, skipSynthetic = false)
public static byte[] transformRedefinitions(final Class<?> classBeingRedefined, final byte[] classfileBuffer,
final ClassLoader loader) throws IllegalClassFormatException, IOException, RuntimeException {
if (NewClassLoaderJavaProxyTransformer.isProxy(classBeingRedefined.getName())) {
return NewClassLoaderJavaProxyTransformer.transform(classBeingRedefined, classfileBuffer, loader);
} else if (CglibProxyTransformer.isProxy(loader, classBeingRedefined.getName())) {
return CglibProxyTransformer.transform(classBeingRedefined, classfileBuffer, loader);
}
return classfileBuffer;
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
private void scanJar(String urlFile, ScannerVisitor visitor) throws IOException {
LOGGER.trace("Scanning JAR file '{}'", urlFile);
int separatorIndex = urlFile.indexOf(JAR_URL_SEPARATOR);
JarFile jarFile;
String rootEntryPath;
if (separatorIndex != -1) {
String jarFileUrl = urlFile.substring(0, separatorIndex);
rootEntryPath = urlFile.substring(separatorIndex + JAR_URL_SEPARATOR.length());
jarFile = getJarFile(jarFileUrl);
} else {
rootEntryPath = "";
jarFile = new JarFile(urlFile);
}
if (!"".equals(rootEntryPath) && !rootEntryPath.endsWith("/")) {
rootEntryPath = rootEntryPath + "/";
}
for (Enumeration<JarEntry> entries = jarFile.entries(); entries.hasMoreElements(); ) {
JarEntry entry = entries.nextElement();
String entryPath = entry.getName();
// class files inside entry
if (entryPath.startsWith(rootEntryPath) && entryPath.endsWith(".class")) {
LOGGER.trace("Visiting JAR entry {}", entryPath);
visitor.visit(jarFile.getInputStream(entry));
}
}
}
#location 15
#vulnerability type RESOURCE_LEAK | #fixed code
private void scanJar(String urlFile, ScannerVisitor visitor) throws IOException {
LOGGER.trace("Scanning JAR file '{}'", urlFile);
int separatorIndex = urlFile.indexOf(JAR_URL_SEPARATOR);
JarFile jarFile = null;
String rootEntryPath;
try {
if (separatorIndex != -1) {
String jarFileUrl = urlFile.substring(0, separatorIndex);
rootEntryPath = urlFile.substring(separatorIndex + JAR_URL_SEPARATOR.length());
jarFile = getJarFile(jarFileUrl);
} else {
rootEntryPath = "";
jarFile = new JarFile(urlFile);
}
if (!"".equals(rootEntryPath) && !rootEntryPath.endsWith("/")) {
rootEntryPath = rootEntryPath + "/";
}
for (Enumeration<JarEntry> entries = jarFile.entries(); entries.hasMoreElements(); ) {
JarEntry entry = entries.nextElement();
String entryPath = entry.getName();
// class files inside entry
if (entryPath.startsWith(rootEntryPath) && entryPath.endsWith(".class")) {
LOGGER.trace("Visiting JAR entry {}", entryPath);
visitor.visit(jarFile.getInputStream(entry));
}
}
} finally {
if (jarFile != null) {
jarFile.close();
}
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
public void defineBean(BeanDefinition candidate) {
synchronized (getClass()) { // TODO sychronize on DefaultListableFactory.beanDefinitionMap?
ScopeMetadata scopeMetadata = this.scopeMetadataResolver.resolveScopeMetadata(candidate);
candidate.setScope(scopeMetadata.getScopeName());
String beanName = this.beanNameGenerator.generateBeanName(candidate, registry);
if (candidate instanceof AbstractBeanDefinition) {
postProcessBeanDefinition((AbstractBeanDefinition) candidate, beanName);
}
if (candidate instanceof AnnotatedBeanDefinition) {
processCommonDefinitionAnnotations((AnnotatedBeanDefinition) candidate);
}
clearCahceIfExists(beanName);
DefaultListableBeanFactory bf = maybeRegistryToBeanFactory();
// use previous singleton bean, if modified class is not bean, a exception will be throw
Object bean;
try {
bean = bf.getBean(beanName);
} catch (NoSuchBeanDefinitionException e) {
LOGGER.warning("{} is not managed by spring", beanName);
return;
}
BeanWrapper bw = new BeanWrapperImpl(bf.getBean(beanName));
RootBeanDefinition rootBeanDefinition = (RootBeanDefinition)ReflectionHelper.invoke(bf, AbstractBeanFactory.class,
"getMergedLocalBeanDefinition", new Class[]{String.class},
beanName);
ReflectionHelper.invoke(bf, AbstractAutowireCapableBeanFactory.class,
"populateBean", new Class[]{String.class, RootBeanDefinition.class, BeanWrapper.class},
beanName,rootBeanDefinition , bw);
freezeConfiguration();
ProxyReplacer.clearAllProxies();
}
}
#location 20
#vulnerability type NULL_DEREFERENCE | #fixed code
public void defineBean(BeanDefinition candidate) {
synchronized (getClass()) { // TODO sychronize on DefaultListableFactory.beanDefinitionMap?
ScopeMetadata scopeMetadata = this.scopeMetadataResolver.resolveScopeMetadata(candidate);
candidate.setScope(scopeMetadata.getScopeName());
String beanName = this.beanNameGenerator.generateBeanName(candidate, registry);
if (candidate instanceof AbstractBeanDefinition) {
postProcessBeanDefinition((AbstractBeanDefinition) candidate, beanName);
}
if (candidate instanceof AnnotatedBeanDefinition) {
processCommonDefinitionAnnotations((AnnotatedBeanDefinition) candidate);
}
removeIfExists(beanName);
BeanDefinitionHolder definitionHolder = new BeanDefinitionHolder(candidate, beanName);
definitionHolder = applyScopedProxyMode(scopeMetadata, definitionHolder, registry);
LOGGER.reload("Registering Spring bean '{}'", beanName);
LOGGER.debug("Bean definition '{}'", beanName, candidate);
registerBeanDefinition(definitionHolder, registry);
freezeConfiguration();
}
ProxyReplacer.clearAllProxies();
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
public static void configureLog(Properties properties) {
for (String property : properties.stringPropertyNames()) {
if (property.startsWith(LOGGER_PREFIX)) {
String classPrefix = getClassPrefix(property);
AgentLogger.Level level = getLevel(property, properties.getProperty(property));
if (level != null) {
if (classPrefix == null)
AgentLogger.setLevel(level);
else
AgentLogger.setLevel(classPrefix, level);
}
} else if (property.equals(LOGFILE)) {
String logfile = properties.getProperty(LOGFILE);
try {
AgentLogger.getHandler().setPrintStream(new PrintStream(new File(logfile)));
} catch (FileNotFoundException e) {
LOGGER.error("Invalid configuration property {} value '{}'. Unable to create/open the file.",
e, LOGFILE, logfile);
}
}
}
}
#location 16
#vulnerability type RESOURCE_LEAK | #fixed code
public static void configureLog(Properties properties) {
for (String property : properties.stringPropertyNames()) {
if (property.startsWith(LOGGER_PREFIX)) {
String classPrefix = getClassPrefix(property);
AgentLogger.Level level = getLevel(property, properties.getProperty(property));
if (level != null) {
if (classPrefix == null)
AgentLogger.setLevel(level);
else
AgentLogger.setLevel(classPrefix, level);
}
} else if (property.equals(LOGFILE)) {
String logfile = properties.getProperty(LOGFILE);
boolean append = parseBoolean(properties.getProperty(LOGFILE_APPEND, "false"));
try {
PrintStream ps = new PrintStream(new FileOutputStream(new File(logfile), append));
AgentLogger.getHandler().setPrintStream(ps);
} catch (FileNotFoundException e) {
LOGGER.error("Invalid configuration property {} value '{}'. Unable to create/open the file.",
e, LOGFILE, logfile);
}
}
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
private void scanJar(String urlFile, ScannerVisitor visitor) throws IOException {
LOGGER.trace("Scanning JAR file '{}'", urlFile);
int separatorIndex = urlFile.indexOf(JAR_URL_SEPARATOR);
JarFile jarFile;
String rootEntryPath;
if (separatorIndex != -1) {
String jarFileUrl = urlFile.substring(0, separatorIndex);
rootEntryPath = urlFile.substring(separatorIndex + JAR_URL_SEPARATOR.length());
jarFile = getJarFile(jarFileUrl);
} else {
rootEntryPath = "";
jarFile = new JarFile(urlFile);
}
if (!"".equals(rootEntryPath) && !rootEntryPath.endsWith("/")) {
rootEntryPath = rootEntryPath + "/";
}
for (Enumeration<JarEntry> entries = jarFile.entries(); entries.hasMoreElements(); ) {
JarEntry entry = entries.nextElement();
String entryPath = entry.getName();
// class files inside entry
if (entryPath.startsWith(rootEntryPath) && entryPath.endsWith(".class")) {
LOGGER.trace("Visiting JAR entry {}", entryPath);
visitor.visit(jarFile.getInputStream(entry));
}
}
}
#location 15
#vulnerability type RESOURCE_LEAK | #fixed code
private void scanJar(String urlFile, ScannerVisitor visitor) throws IOException {
LOGGER.trace("Scanning JAR file '{}'", urlFile);
int separatorIndex = urlFile.indexOf(JAR_URL_SEPARATOR);
JarFile jarFile = null;
String rootEntryPath;
try {
if (separatorIndex != -1) {
String jarFileUrl = urlFile.substring(0, separatorIndex);
rootEntryPath = urlFile.substring(separatorIndex + JAR_URL_SEPARATOR.length());
jarFile = getJarFile(jarFileUrl);
} else {
rootEntryPath = "";
jarFile = new JarFile(urlFile);
}
if (!"".equals(rootEntryPath) && !rootEntryPath.endsWith("/")) {
rootEntryPath = rootEntryPath + "/";
}
for (Enumeration<JarEntry> entries = jarFile.entries(); entries.hasMoreElements(); ) {
JarEntry entry = entries.nextElement();
String entryPath = entry.getName();
// class files inside entry
if (entryPath.startsWith(rootEntryPath) && entryPath.endsWith(".class")) {
LOGGER.trace("Visiting JAR entry {}", entryPath);
visitor.visit(jarFile.getInputStream(entry));
}
}
} finally {
if (jarFile != null) {
jarFile.close();
}
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
public void refreshProxiedFactory() throws NoSuchMethodException, InvocationTargetException, IllegalAccessException, NoSuchFieldException {
// refresh registry
EntityManagerFactoryRegistry.INSTANCE.removeEntityManagerFactory(persistenceUnitName, currentInstance);
// from HibernatePersistence.createContainerEntityManagerFactory()
buildFreshEntityManagerFactory();
}
#location 6
#vulnerability type THREAD_SAFETY_VIOLATION | #fixed code
public void refreshProxiedFactory() throws NoSuchMethodException, InvocationTargetException, IllegalAccessException, NoSuchFieldException {
// refresh registry
try {
Class entityManagerFactoryRegistryClazz = loadClass("org.hibernate.ejb.internal.EntityManagerFactoryRegistry");
Object instance = ReflectionHelper.get(null, entityManagerFactoryRegistryClazz, "INSTANCE");
ReflectionHelper.invoke(instance, entityManagerFactoryRegistryClazz, "removeEntityManagerFactory",
new Class[] {String.class, EntityManagerFactory.class}, persistenceUnitName, currentInstance);
} catch (Exception e) {
LOGGER.error("Unable to clear previous instance of entity manager factory");
}
buildFreshEntityManagerFactory();
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
private void savePolicyFile(String text) {
try {
FileOutputStream fos = new FileOutputStream(filePath);
fos.write(text.getBytes());
fos.close();
} catch (IOException e) {
e.printStackTrace();
throw new Error("IO error occurred");
}
}
#location 6
#vulnerability type RESOURCE_LEAK | #fixed code
private void savePolicyFile(String text) {
try (FileOutputStream fos = new FileOutputStream(filePath)) {
IOUtils.write(text, fos, Charset.forName("UTF-8"));
} catch (IOException e) {
e.printStackTrace();
throw new Error("Policy save error");
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Test
public void testSpliter() throws IOException {
String testS = "test data only for ";
SharedBufferPool sharedPool = new SharedBufferPool(1024 * 1024 * 100, testS.length() + 4);
ReactorBufferPool reactBufferPool = new ReactorBufferPool(sharedPool, Thread.currentThread(), 1000);
ByteBufferArray bufArray = reactBufferPool.allocate();
bufArray.addNewBuffer();
int readBufferOffset = 0;
// @todo 构造符合MYSQL报文的数据包,进行测试
ByteArrayInputStream mysqlPackgsStream = createMysgqlPackages();
while (mysqlPackgsStream.available() > 0) {
ByteBuffer curBuf = bufArray.getLastByteBuffer();
if(!curBuf.hasRemaining())
{
curBuf=bufArray.addNewBuffer();
}
byte[] data = new byte[curBuf.remaining()];
int readed = mysqlPackgsStream.read(data);
curBuf.put(data, 0, readed);
readBufferOffset = CommonPackageUtil.parsePackages(bufArray, curBuf, readBufferOffset);
}
Assert.assertEquals(10, bufArray.getCurPacageIndex());
}
#location 12
#vulnerability type NULL_DEREFERENCE | #fixed code
@Test
public void testSpliter() throws IOException {
SharedBufferPool sharedPool = new SharedBufferPool(1024 * 1024 * 100, 10240);
ReactorBufferPool reactBufferPool = new ReactorBufferPool(sharedPool, Thread.currentThread(), 1000);
ByteBufferArray bufArray = reactBufferPool.allocate();
bufArray.addNewBuffer();
int readBufferOffset = 0;
// @todo 构造符合MYSQL报文的数据包,进行测试
ByteArrayInputStream mysqlPackgsStream = createMysgqlPackages();
while (mysqlPackgsStream.available() > 0) {
ByteBuffer curBuf = bufArray.getLastByteBuffer();
if (!curBuf.hasRemaining()) {
curBuf = bufArray.addNewBuffer();
}
byte[] data = new byte[curBuf.remaining()];
int readed = mysqlPackgsStream.read(data);
curBuf.put(data, 0, readed);
readBufferOffset = CommonPackageUtil.parsePackages(bufArray, curBuf, readBufferOffset);
}
Assert.assertEquals(PACKAGES_COUNT, bufArray.getCurPacageIndex());
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Test
public void testPostWithMultipartFormFieldsAndFile() throws IOException {
String fileName = "GrandCanyon.txt";
String fileContent = HttpPostRequestTest.VALUE;
String divider = UUID.randomUUID().toString();
String header = "POST " + HttpServerTest.URI + " HTTP/1.1\nContent-Type: " + "multipart/form-data; boundary=" + divider + "\n";
String content =
"--" + divider + "\r\n" + "Content-Disposition: form-data; name=\"" + HttpPostRequestTest.FIELD + "\"; filename=\"" + fileName + "\"\r\n"
+ "Content-Type: image/jpeg\r\n" + "\r\n" + fileContent + "\r\n" + "--" + divider + "\r\n" + "Content-Disposition: form-data; name=\""
+ HttpPostRequestTest.FIELD2 + "\"\r\n" + "\r\n" + HttpPostRequestTest.VALUE2 + "\r\n" + "--" + divider + "--\r\n";
int size = content.length() + header.length();
int contentLengthHeaderValueSize = String.valueOf(size).length();
int contentLength = size + contentLengthHeaderValueSize + HttpPostRequestTest.CONTENT_LENGTH.length();
String input = header + HttpPostRequestTest.CONTENT_LENGTH + (contentLength + 4) + "\r\n\r\n" + content;
invokeServer(input);
assertEquals("Parameter count did not match.", 2, this.testServer.parms.size());
assertEquals("Parameter value did not match", HttpPostRequestTest.VALUE2, this.testServer.parms.get(HttpPostRequestTest.FIELD2));
BufferedReader reader = new BufferedReader(new FileReader(this.testServer.files.get(HttpPostRequestTest.FIELD)));
List<String> lines = readLinesFromFile(reader);
assertLinesOfText(new String[]{
fileContent
}, lines);
}
#location 21
#vulnerability type RESOURCE_LEAK | #fixed code
@Test
public void testPostWithMultipartFormFieldsAndFile() throws IOException {
String fileName = "GrandCanyon.txt";
String fileContent = HttpPostRequestTest.VALUE;
String divider = UUID.randomUUID().toString();
String header = "POST " + HttpServerTest.URI + " HTTP/1.1\nContent-Type: " + "multipart/form-data; boundary=" + divider + "\n";
String content =
"--" + divider + "\r\n" + "Content-Disposition: form-data; name=\"" + HttpPostRequestTest.FIELD + "\"; filename=\"" + fileName + "\"\r\n"
+ "Content-Type: image/jpeg\r\n" + "\r\n" + fileContent + "\r\n" + "--" + divider + "\r\n" + "Content-Disposition: form-data; name=\""
+ HttpPostRequestTest.FIELD2 + "\"\r\n" + "\r\n" + HttpPostRequestTest.VALUE2 + "\r\n" + "--" + divider + "--\r\n";
int size = content.length() + header.length();
int contentLengthHeaderValueSize = String.valueOf(size).length();
int contentLength = size + contentLengthHeaderValueSize + HttpPostRequestTest.CONTENT_LENGTH.length();
String input = header + HttpPostRequestTest.CONTENT_LENGTH + (contentLength + 4) + "\r\n\r\n" + content;
invokeServer(input);
assertEquals("Parms count did not match.", 2, this.testServer.parms.size());
assertEquals("Parameters count did not match.", 2, this.testServer.parameters.size());
assertEquals("Param value did not match", HttpPostRequestTest.VALUE2, this.testServer.parms.get(HttpPostRequestTest.FIELD2));
assertEquals("Parameter value did not match", HttpPostRequestTest.VALUE2, this.testServer.parameters.get(HttpPostRequestTest.FIELD2).get(0));
BufferedReader reader = new BufferedReader(new FileReader(this.testServer.files.get(HttpPostRequestTest.FIELD)));
List<String> lines = readLinesFromFile(reader);
assertLinesOfText(new String[]{
fileContent
}, lines);
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
private void sendBodyWithCorrectTransferAndEncoding(OutputStream outputStream, long pending) throws IOException {
if (this.requestMethod != Method.HEAD && this.chunkedTransfer) {
ChunkedOutputStream chunkedOutputStream = new ChunkedOutputStream(outputStream);
sendBodyWithCorrectEncoding(chunkedOutputStream, -1);
chunkedOutputStream.finish();
} else {
sendBodyWithCorrectEncoding(outputStream, pending);
}
}
#location 5
#vulnerability type RESOURCE_LEAK | #fixed code
private void sendBodyWithCorrectTransferAndEncoding(OutputStream outputStream, long pending) throws IOException {
if (this.requestMethod != Method.HEAD && this.chunkedTransfer) {
ChunkedOutputStream chunkedOutputStream = new ChunkedOutputStream(outputStream);
sendBodyWithCorrectEncoding(chunkedOutputStream, -1);
try {
chunkedOutputStream.finish();
} catch (Exception e) {
if(this.data != null) {
this.data.close();
}
}
} else {
sendBodyWithCorrectEncoding(outputStream, pending);
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Test
public void shutdown() throws Exception {
Client client = TestGraphUtil.instance.createClient();
client.delegate().shutdown();
}
#location 4
#vulnerability type NULL_DEREFERENCE | #fixed code
@Test
public void shutdown() throws Exception {
Client client = TestGraphUtil.instance.createClient();
client.getDelegate().shutdown();
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
public static void load(final JanusGraph graph, final int rowsToLoad, final boolean report)
throws IOException, InterruptedException {
final JanusGraphManagement mgmt = graph.openManagement();
if (mgmt.getGraphIndex(CHARACTER) == null) {
final PropertyKey characterKey = mgmt.makePropertyKey(CHARACTER).dataType(String.class).make();
mgmt.buildIndex(CHARACTER, Vertex.class).addKey(characterKey).unique().buildCompositeIndex();
}
if (mgmt.getGraphIndex(COMIC_BOOK) == null) {
final PropertyKey comicBookKey = mgmt.makePropertyKey(COMIC_BOOK).dataType(String.class).make();
mgmt.buildIndex(COMIC_BOOK, Vertex.class).addKey(comicBookKey).unique().buildCompositeIndex();
mgmt.makePropertyKey(WEAPON).dataType(String.class).make();
mgmt.makeEdgeLabel(APPEARED).multiplicity(Multiplicity.MULTI).make();
}
mgmt.commit();
final ClassLoader classLoader = MarvelGraphFactory.class.getClassLoader();
final URL resource = classLoader.getResource("META-INF/marvel.csv");
Preconditions.checkNotNull(resource);
final Map<String, Set<String>> comicToCharacter = new HashMap<>();
final Map<String, Set<String>> characterToComic = new HashMap<>();
final Set<String> characters = new HashSet<>();
final BlockingQueue<Runnable> creationQueue = new LinkedBlockingQueue<>();
try (CSVReader reader = new CSVReader(new InputStreamReader(resource.openStream()))) {
reader.readAll().subList(0, rowsToLoad).forEach(nextLine -> {
final String comicBook = nextLine[1];
final String[] characterNames = nextLine[0].split("/");
if (!comicToCharacter.containsKey(comicBook)) {
comicToCharacter.put(comicBook, new HashSet<>());
}
final List<String> comicCharacters = Arrays.asList(characterNames);
comicToCharacter.get(comicBook).addAll(comicCharacters);
characters.addAll(comicCharacters);
});
}
creationQueue.addAll(characters.stream().map(character -> new CharacterCreationCommand(character, graph))
.collect(Collectors.toList()));
final BlockingQueue<Runnable> appearedQueue = new LinkedBlockingQueue<>();
for (String comicBook : comicToCharacter.keySet()) {
creationQueue.add(new ComicBookCreationCommand(comicBook, graph));
final Set<String> comicCharacters = comicToCharacter.get(comicBook);
for (String character : comicCharacters) {
final AppearedCommand lineCommand = new AppearedCommand(graph, new Appeared(character, comicBook));
appearedQueue.add(lineCommand);
if (!characterToComic.containsKey(character)) {
characterToComic.put(character, new HashSet<String>());
}
characterToComic.get(character).add(comicBook);
}
REGISTRY.histogram("histogram.comic-to-character").update(comicCharacters.size());
}
int maxAppearances = 0;
String maxCharacter = "";
for (String character : characterToComic.keySet()) {
final Set<String> comicBookSet = characterToComic.get(character);
final int numberOfAppearances = comicBookSet.size();
REGISTRY.histogram("histogram.character-to-comic").update(numberOfAppearances);
if (numberOfAppearances > maxAppearances) {
maxCharacter = character;
maxAppearances = numberOfAppearances;
}
}
log.info("Character {} has most appearances at {}", maxCharacter, maxAppearances);
ExecutorService executor = Executors.newFixedThreadPool(POOL_SIZE);
for (int i = 0; i < POOL_SIZE; i++) {
executor.execute(new BatchCommand(graph, creationQueue));
}
executor.shutdown();
while (!executor.awaitTermination(TIMEOUT_SIXTY_SECONDS, TimeUnit.SECONDS)) {
log.info("Awaiting:" + creationQueue.size());
if (report) {
REPORTER.report();
}
}
executor = Executors.newSingleThreadExecutor();
executor.execute(new BatchCommand(graph, appearedQueue));
executor.shutdown();
while (!executor.awaitTermination(TIMEOUT_SIXTY_SECONDS, TimeUnit.SECONDS)) {
log.info("Awaiting:" + appearedQueue.size());
if (report) {
REPORTER.report();
}
}
log.info("MarvelGraph.load complete");
}
#location 43
#vulnerability type NULL_DEREFERENCE | #fixed code
public static void load(final JanusGraph graph, final int rowsToLoad, final boolean report)
throws IOException, InterruptedException {
final JanusGraphManagement mgmt = graph.openManagement();
if (mgmt.getGraphIndex(CHARACTER) == null) {
final PropertyKey characterKey = mgmt.makePropertyKey(CHARACTER).dataType(String.class).make();
mgmt.buildIndex(CHARACTER, Vertex.class).addKey(characterKey).unique().buildCompositeIndex();
}
if (mgmt.getGraphIndex(COMIC_BOOK) == null) {
final PropertyKey comicBookKey = mgmt.makePropertyKey(COMIC_BOOK).dataType(String.class).make();
mgmt.buildIndex(COMIC_BOOK, Vertex.class).addKey(comicBookKey).unique().buildCompositeIndex();
mgmt.makePropertyKey(WEAPON).dataType(String.class).make();
mgmt.makeEdgeLabel(APPEARED).multiplicity(Multiplicity.MULTI).make();
}
mgmt.commit();
final ClassLoader classLoader = MarvelGraphFactory.class.getClassLoader();
final URL resource = classLoader.getResource("META-INF/marvel.csv");
Preconditions.checkNotNull(resource);
final Map<String, Set<String>> comicToCharacter = new HashMap<>();
final Map<String, Set<String>> characterToComic = new HashMap<>();
final Set<String> characters = new HashSet<>();
final BlockingQueue<Runnable> creationQueue = new LinkedBlockingQueue<>();
try (CSVReader reader = new CSVReader(new InputStreamReader(resource.openStream(), Charset.forName("UTF-8")))) {
reader.readAll().subList(0, rowsToLoad).forEach(nextLine -> {
final String comicBook = nextLine[1];
final String[] characterNames = nextLine[0].split("/");
if (!comicToCharacter.containsKey(comicBook)) {
comicToCharacter.put(comicBook, new HashSet<>());
}
final List<String> comicCharacters = Arrays.asList(characterNames);
comicToCharacter.get(comicBook).addAll(comicCharacters);
characters.addAll(comicCharacters);
});
}
creationQueue.addAll(characters.stream().map(character -> new CharacterCreationCommand(character, graph))
.collect(Collectors.toList()));
final BlockingQueue<Runnable> appearedQueue = new LinkedBlockingQueue<>();
for (Map.Entry<String, Set<String>> entry : comicToCharacter.entrySet()) {
final String comicBook = entry.getKey();
final Set<String> comicCharacters = entry.getValue();
creationQueue.add(new ComicBookCreationCommand(comicBook, graph));
for (String character : comicCharacters) {
final AppearedCommand lineCommand = new AppearedCommand(graph, new Appeared(character, comicBook));
appearedQueue.add(lineCommand);
if (!characterToComic.containsKey(character)) {
characterToComic.put(character, new HashSet<String>());
}
characterToComic.get(character).add(comicBook);
}
REGISTRY.histogram("histogram.comic-to-character").update(comicCharacters.size());
}
int maxAppearances = 0;
String maxCharacter = "";
for (Map.Entry<String, Set<String>> entry : characterToComic.entrySet()) {
final String character = entry.getKey();
final Set<String> comicBookSet = entry.getValue();
final int numberOfAppearances = comicBookSet.size();
REGISTRY.histogram("histogram.character-to-comic").update(numberOfAppearances);
if (numberOfAppearances > maxAppearances) {
maxCharacter = character;
maxAppearances = numberOfAppearances;
}
}
log.info("Character {} has most appearances at {}", maxCharacter, maxAppearances);
ExecutorService executor = Executors.newFixedThreadPool(POOL_SIZE);
for (int i = 0; i < POOL_SIZE; i++) {
executor.execute(new BatchCommand(graph, creationQueue));
}
executor.shutdown();
while (!executor.awaitTermination(TIMEOUT_SIXTY_SECONDS, TimeUnit.SECONDS)) {
log.info("Awaiting:" + creationQueue.size());
if (report) {
REPORTER.report();
}
}
executor = Executors.newSingleThreadExecutor();
executor.execute(new BatchCommand(graph, appearedQueue));
executor.shutdown();
while (!executor.awaitTermination(TIMEOUT_SIXTY_SECONDS, TimeUnit.SECONDS)) {
log.info("Awaiting:" + appearedQueue.size());
if (report) {
REPORTER.report();
}
}
log.info("MarvelGraph.load complete");
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
public List<Category> getFriendList() {
LOGGER.info("开始获取好友列表");
HttpPost post = defaultHttpPost(
"http://s.web2.qq.com/api/get_user_friends2",
"http://s.web2.qq.com/proxy.html?v=20130916001&callback=1&id=1");
JSONObject r = new JSONObject();
r.put("vfwebqq", vfwebqq);
r.put("hash", hash());
try {
post.setEntity(new UrlEncodedFormEntity(Arrays.asList(new BasicNameValuePair("r", r.toJSONString()))));
try (CloseableHttpResponse response = client.execute(post, context)) {
JSONObject responseJson = JSON.parseObject(getResponseText(response));
if (0 == responseJson.getIntValue("retcode")) {
JSONObject result = responseJson.getJSONObject("result");
//获得分组
JSONArray categories = result.getJSONArray("categories");
Map<Integer, Category> categoryMap = new HashMap<>();
categoryMap.put(0, Category.defaultCategory());
for (int i = 0; categories != null && i < categories.size(); i++) {
Category category = categories.getObject(i, Category.class);
categoryMap.put(category.getIndex(), category);
}
//获得好友信息
Map<Long, Friend> friendMap = new HashMap<>();
JSONArray friends = result.getJSONArray("friends");
for (int i = 0; friends != null && i < friends.size(); i++) {
JSONObject item = friends.getJSONObject(i);
Friend friend = new Friend();
friend.setUserId(item.getLongValue("uin"));
friendMap.put(friend.getUserId(), friend);
categoryMap.get(item.getIntValue("categories")).addFriend(friend);
}
JSONArray marknames = result.getJSONArray("marknames");
for (int i = 0; marknames != null && i < marknames.size(); i++) {
JSONObject item = marknames.getJSONObject(i);
friendMap.get(item.getLongValue("uin")).setMarkname(item.getString("markname"));
}
JSONArray info = result.getJSONArray("info");
for (int i = 0; info != null && i < info.size(); i++) {
JSONObject item = info.getJSONObject(i);
friendMap.get(item.getLongValue("uin")).setNickname(item.getString("nick"));
}
JSONArray vipinfo = result.getJSONArray("vipinfo");
for (int i = 0; vipinfo != null && i < vipinfo.size(); i++) {
JSONObject item = vipinfo.getJSONObject(i);
Friend friend = friendMap.get(item.getLongValue("u"));
friend.setVip(item.getIntValue("is_vip") == 1);
friend.setVipLevel(item.getIntValue("vip_level"));
}
return new ArrayList<>(categoryMap.values());
} else {
LOGGER.error("获取好友列表失败");
}
} catch (IOException e) {
LOGGER.error("获取好友列表失败");
}
} catch (UnsupportedEncodingException e) {
LOGGER.error("获取好友列表失败");
}
return Collections.EMPTY_LIST;
}
#location 31
#vulnerability type NULL_DEREFERENCE | #fixed code
public List<Category> getFriendList() {
LOGGER.info("开始获取好友列表");
JSONObject r = new JSONObject();
r.put("vfwebqq", vfwebqq);
r.put("hash", hash());
try {
HttpPost post = defaultHttpPost(ApiUrl.GET_FRIEND_LIST, new BasicNameValuePair("r", r.toJSONString()));
try (CloseableHttpClient client = HttpClients.createDefault();
CloseableHttpResponse response = client.execute(post, context)) {
JSONObject responseJson = JSON.parseObject(getResponseText(response));
if (0 == responseJson.getIntValue("retcode")) {
JSONObject result = responseJson.getJSONObject("result");
//获得分组
JSONArray categories = result.getJSONArray("categories");
Map<Integer, Category> categoryMap = new HashMap<>();
categoryMap.put(0, Category.defaultCategory());
for (int i = 0; categories != null && i < categories.size(); i++) {
Category category = categories.getObject(i, Category.class);
categoryMap.put(category.getIndex(), category);
}
//获得好友信息
Map<Long, Friend> friendMap = new HashMap<>();
JSONArray friends = result.getJSONArray("friends");
for (int i = 0; friends != null && i < friends.size(); i++) {
JSONObject item = friends.getJSONObject(i);
Friend friend = new Friend();
friend.setUserId(item.getLongValue("uin"));
friendMap.put(friend.getUserId(), friend);
categoryMap.get(item.getIntValue("categories")).addFriend(friend);
}
JSONArray marknames = result.getJSONArray("marknames");
for (int i = 0; marknames != null && i < marknames.size(); i++) {
JSONObject item = marknames.getJSONObject(i);
friendMap.get(item.getLongValue("uin")).setMarkname(item.getString("markname"));
}
JSONArray info = result.getJSONArray("info");
for (int i = 0; info != null && i < info.size(); i++) {
JSONObject item = info.getJSONObject(i);
friendMap.get(item.getLongValue("uin")).setNickname(item.getString("nick"));
}
JSONArray vipinfo = result.getJSONArray("vipinfo");
for (int i = 0; vipinfo != null && i < vipinfo.size(); i++) {
JSONObject item = vipinfo.getJSONObject(i);
Friend friend = friendMap.get(item.getLongValue("u"));
friend.setVip(item.getIntValue("is_vip") == 1);
friend.setVipLevel(item.getIntValue("vip_level"));
}
return new ArrayList<>(categoryMap.values());
} else {
LOGGER.error("获取好友列表失败");
}
} catch (IOException e) {
LOGGER.error("获取好友列表失败");
}
} catch (UnsupportedEncodingException e) {
LOGGER.error("获取好友列表失败");
}
return Collections.EMPTY_LIST;
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Test
public void shouldCreateConversationThenJoinAndSendOfferRequest() throws Exception {
// given
MessageMatcher s1Matcher = new MessageMatcher();
MessageMatcher s2Matcher = new MessageMatcher();
Session s1 = mockSession("s1", s1Matcher);
Session s2 = mockSession("s2", s2Matcher);
server.register(s1);
server.register(s2);
// when
server.handle(Message.create()//
.signal("create")//
.build(), s1);
String conversationKey = s1Matcher.getMessage().getContent();
s1Matcher.reset();
server.handle(Message.create()//
.signal("join")//
.content(conversationKey)//
.build(), s2);
// then
assertThat(s1Matcher.getMessages().size(), is(2));
assertThat(s1Matcher.getMessage().getFrom(), is("s2"));
assertThat(s1Matcher.getMessage().getTo(), is("s1"));
assertThat(s1Matcher.getMessage().getSignal(), is("joined"));
assertThat(s1Matcher.getMessage(1).getFrom(), is("s2"));
assertThat(s1Matcher.getMessage(1).getTo(), is("s1"));
assertThat(s1Matcher.getMessage(1).getSignal(), is("offerRequest"));
assertThat(s2Matcher.getMessages().size(), is(1));
assertThat(s2Matcher.getMessage().getSignal(), is("joined"));
assertThat(s2Matcher.getMessage().getContent(), is(conversationKey));
}
#location 29
#vulnerability type NULL_DEREFERENCE | #fixed code
@Test
public void shouldCreateConversationThenJoinAndSendOfferRequest() throws Exception {
// given
MessageMatcher s1Matcher = new MessageMatcher();
MessageMatcher s2Matcher = new MessageMatcher();
Session s1 = mockSession("s1", s1Matcher);
Session s2 = mockSession("s2", s2Matcher);
server.register(s1);
server.register(s2);
// when
server.handle(Message.create()//
.signal("create")//
.build(), s1);
String conversationKey = s1Matcher.getMessage().getContent();
s1Matcher.reset();
server.handle(Message.create()//
.signal("join")//
.content(conversationKey)//
.build(), s2);
// then
assertThat(s1Matcher.getMessages().size(), is(2));
assertMatch(s1Matcher, 0, "s2", "s1", "joined", EMPTY);
assertMatch(s1Matcher, 1, "s2", "s1", "offerRequest", EMPTY);
assertThat(s2Matcher.getMessages().size(), is(1));
assertMatch(s2Matcher, 0, EMPTY, "s2", "joined", conversationKey);
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
public void handleError(Session s, Throwable exception) {
doSaveExecution(new SessionWrapper(s), session -> {
members.unregister(session.getId());
eventBus.post(UNEXPECTED_SITUATION.occurFor(session, exception.getMessage()));
}
);
}
#location 2
#vulnerability type RESOURCE_LEAK | #fixed code
public void handleError(Session s, Throwable exception) {
doSaveExecution(s, session -> {
members.unregister(session.getId());
eventBus.post(UNEXPECTED_SITUATION.occurFor(session, exception.getMessage()));
}
);
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Test
public void shouldCreateConversation() throws Exception {
// given
MessageMatcher matcher = new MessageMatcher();
InternalMessage message = InternalMessage.create()//
.from(Member.builder()//
.session(mockSession("sessionId", matcher))//
.build())//
.signal(create)//
.content("c1")//
.build();
// when
create.executeMessage(message);
// then
Optional<Conversation> conv = conversations.findBy("c1");
assertTrue(conv.isPresent());
Message send = matcher.getMessage();
assertNotNull(send);
assertThat(send.getFrom(), is(EMPTY));
assertThat(send.getTo(), is("sessionId"));
assertThat(send.getSignal(), is("created"));
assertThat(send.getContent(), is("c1"));
assertThat(send.getParameters(), notNullValue());
}
#location 21
#vulnerability type NULL_DEREFERENCE | #fixed code
@Test
public void shouldCreateConversation() throws Exception {
// given
MessageMatcher matcher = new MessageMatcher();
InternalMessage message = InternalMessage.create()//
.from(Member.create()//
.session(mockSession("sessionId", matcher))//
.build())//
.signal(create)//
.content("c1")//
.build();
// when
create.executeMessage(message);
// then
Optional<Conversation> conv = conversations.findBy("c1");
assertTrue(conv.isPresent());
Message send = matcher.getMessage();
assertNotNull(send);
assertThat(send.getFrom(), is(EMPTY));
assertThat(send.getTo(), is("sessionId"));
assertThat(send.getSignal(), is("created"));
assertThat(send.getContent(), is("c1"));
assertThat(send.getParameters(), notNullValue());
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Test
public void shouldCreateConversationThenJoinAndSendOfferRequest() throws Exception {
// given
MessageMatcher s1Matcher = new MessageMatcher();
MessageMatcher s2Matcher = new MessageMatcher();
Session s1 = mockSession("s1", s1Matcher);
Session s2 = mockSession("s2", s2Matcher);
server.register(s1);
server.register(s2);
// when
server.handle(Message.create()//
.signal("create")//
.build(), s1);
String conversationKey = s1Matcher.getMessage().getContent();
s1Matcher.reset();
server.handle(Message.create()//
.signal("join")//
.content(conversationKey)//
.build(), s2);
// then
assertThat(s1Matcher.getMessages().size(), is(2));
assertThat(s1Matcher.getMessage().getFrom(), is("s2"));
assertThat(s1Matcher.getMessage().getTo(), is("s1"));
assertThat(s1Matcher.getMessage().getSignal(), is("joined"));
assertThat(s1Matcher.getMessage(1).getFrom(), is("s2"));
assertThat(s1Matcher.getMessage(1).getTo(), is("s1"));
assertThat(s1Matcher.getMessage(1).getSignal(), is("offerRequest"));
assertThat(s2Matcher.getMessages().size(), is(1));
assertThat(s2Matcher.getMessage().getSignal(), is("joined"));
assertThat(s2Matcher.getMessage().getContent(), is(conversationKey));
}
#location 30
#vulnerability type NULL_DEREFERENCE | #fixed code
@Test
public void shouldCreateConversationThenJoinAndSendOfferRequest() throws Exception {
// given
MessageMatcher s1Matcher = new MessageMatcher();
MessageMatcher s2Matcher = new MessageMatcher();
Session s1 = mockSession("s1", s1Matcher);
Session s2 = mockSession("s2", s2Matcher);
server.register(s1);
server.register(s2);
// when
server.handle(Message.create()//
.signal("create")//
.build(), s1);
String conversationKey = s1Matcher.getMessage().getContent();
s1Matcher.reset();
server.handle(Message.create()//
.signal("join")//
.content(conversationKey)//
.build(), s2);
// then
assertThat(s1Matcher.getMessages().size(), is(2));
assertMatch(s1Matcher, 0, "s2", "s1", "joined", EMPTY);
assertMatch(s1Matcher, 1, "s2", "s1", "offerRequest", EMPTY);
assertThat(s2Matcher.getMessages().size(), is(1));
assertMatch(s2Matcher, 0, EMPTY, "s2", "joined", conversationKey);
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
private void send(InternalMessage message, int retry) {
Message messageToSend = message.transformToExternalMessage();
if (message.getSignal() != Signal.PING) {
log.info("Outgoing: " + toString());
}
Session destSession = message.getTo().getSession();
if (!destSession.isOpen()) {
log.warn("Session is closed! Message will not be send: ");
return;
}
try {
RemoteEndpoint.Basic basic = destSession.getBasicRemote();
synchronized (basic) {
basic.sendObject(messageToSend);
}
} catch (Exception e) {
if (retry >= 0) {
log.info("Retrying... " + messageToSend);
send(message, --retry);
}
log.error("Unable to send message: " + messageToSend + " error during sending!");
throw new RuntimeException("Unable to send message: " + messageToSend, e);
}
}
#location 6
#vulnerability type NULL_DEREFERENCE | #fixed code
private void send(InternalMessage message, int retry) {
if (message.getSignal() != Signal.PING) {
log.debug("Outgoing: " + message.transformToExternalMessage());
}
if (message.getSignal() == Signal.ERROR) {
tryToSendErrorMessage(message);
return;
}
Member destination = message.getTo();
if (destination == null || !destination.getSession().isOpen()) {
log.warn("Destination member is not set or session is closed! Message will not be send: " + message.transformToExternalMessage());
return;
}
members.findBy(destination.getId()).ifPresent(member ->
lockAndRun(message, member, retry)
);
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Test
public void shouldCreateConversationThenJoinAndSendOfferRequest() throws Exception {
// given
MessageMatcher s1Matcher = new MessageMatcher();
MessageMatcher s2Matcher = new MessageMatcher();
Session s1 = mockSession("s1", s1Matcher);
Session s2 = mockSession("s2", s2Matcher);
server.register(s1);
server.register(s2);
// when
server.handle(Message.create()//
.signal("create")//
.build(), s1);
String conversationKey = s1Matcher.getMessage().getContent();
s1Matcher.reset();
server.handle(Message.create()//
.signal("join")//
.content(conversationKey)//
.build(), s2);
// then
assertThat(s1Matcher.getMessages().size(), is(2));
assertThat(s1Matcher.getMessage().getFrom(), is("s2"));
assertThat(s1Matcher.getMessage().getTo(), is("s1"));
assertThat(s1Matcher.getMessage().getSignal(), is("joined"));
assertThat(s1Matcher.getMessage(1).getFrom(), is("s2"));
assertThat(s1Matcher.getMessage(1).getTo(), is("s1"));
assertThat(s1Matcher.getMessage(1).getSignal(), is("offerRequest"));
assertThat(s2Matcher.getMessages().size(), is(1));
assertThat(s2Matcher.getMessage().getSignal(), is("joined"));
assertThat(s2Matcher.getMessage().getContent(), is(conversationKey));
}
#location 28
#vulnerability type NULL_DEREFERENCE | #fixed code
@Test
public void shouldCreateConversationThenJoinAndSendOfferRequest() throws Exception {
// given
MessageMatcher s1Matcher = new MessageMatcher();
MessageMatcher s2Matcher = new MessageMatcher();
Session s1 = mockSession("s1", s1Matcher);
Session s2 = mockSession("s2", s2Matcher);
server.register(s1);
server.register(s2);
// when
server.handle(Message.create()//
.signal("create")//
.build(), s1);
String conversationKey = s1Matcher.getMessage().getContent();
s1Matcher.reset();
server.handle(Message.create()//
.signal("join")//
.content(conversationKey)//
.build(), s2);
// then
assertThat(s1Matcher.getMessages().size(), is(2));
assertMatch(s1Matcher, 0, "s2", "s1", "joined", EMPTY);
assertMatch(s1Matcher, 1, "s2", "s1", "offerRequest", EMPTY);
assertThat(s2Matcher.getMessages().size(), is(1));
assertMatch(s2Matcher, 0, EMPTY, "s2", "joined", conversationKey);
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@SuppressWarnings("unchecked")
private Object getListArg(ManagedList<XmlManagedNode> values, Class<?> setterParamType) {
Collection<Object> collection = null;
if (VerifyUtils.isNotEmpty(values.getTypeName())) {
try {
collection = (Collection<Object>) XmlApplicationContext.class
.getClassLoader().loadClass(values.getTypeName())
.newInstance();
} catch (Throwable t) {
log.error("list inject error", t);
}
} else {
collection = (setterParamType == null ? new ArrayList<Object>()
: ConvertUtils.getCollectionObj(setterParamType));
}
for (XmlManagedNode item : values) {
Object listValue = getInjectArg(item, null);
collection.add(listValue);
}
return collection;
}
#location 20
#vulnerability type NULL_DEREFERENCE | #fixed code
@SuppressWarnings("unchecked")
private Object getListArg(ManagedList<XmlManagedNode> values, Class<?> setterParamType) {
Collection<Object> collection = null;
if (VerifyUtils.isNotEmpty(values.getTypeName())) {
try {
collection = (Collection<Object>) XmlApplicationContext.class
.getClassLoader()
.loadClass(values.getTypeName())
.newInstance();
} catch (Throwable t) {
log.error("list inject error", t);
}
} else {
collection = (setterParamType == null ? new ArrayList<>()
: ConvertUtils.getCollectionObj(setterParamType));
}
if (collection != null) {
for (XmlManagedNode item : values) {
Object listValue = getInjectArg(item, null);
collection.add(listValue);
}
}
return collection;
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
private void parseProperties(Properties properties) {
for (Entry<Object, Object> entry : properties.entrySet()) {
String name = (String) entry.getKey();
String value = (String) entry.getValue();
// System.out.println(name + "|" + value);
String[] strs = StringUtils.split(value, ',');
if (strs.length < 2) {
System.err.println("the log configuration file format is illegal");
continue;
}
String path = strs[1];
FileLog fileLog = new FileLog();
fileLog.setName(name);
fileLog.setLevel(LogLevel.fromName(strs[0]));
if ("console".equalsIgnoreCase(path)) {
fileLog.setFileOutput(false);
fileLog.setConsoleOutput(true);
} else {
File file = new File(path);
if(file.exists() && file.isDirectory()) {
fileLog.setPath(path);
fileLog.setFileOutput(true);
} else {
boolean success = file.mkdirs();
if(success) {
fileLog.setPath(path);
fileLog.setFileOutput(true);
} else {
System.err.println("create directory " + path + " failure");
continue;
}
}
if (strs.length > 2)
fileLog.setConsoleOutput("console".equalsIgnoreCase(strs[2]));
}
logMap.put(name, fileLog);
System.out.println("initialize log " + fileLog.toString() + " success");
}
}
#location 32
#vulnerability type RESOURCE_LEAK | #fixed code
private void parseProperties(Properties properties) {
for (Entry<Object, Object> entry : properties.entrySet()) {
String name = (String) entry.getKey();
String value = (String) entry.getValue();
String[] strs = StringUtils.split(value, ',');
switch (strs.length) {
case 1:
createLog(name, strs[0], null, false);
break;
case 2:
if("console".equalsIgnoreCase(strs[1])) {
createLog(name, strs[0], null, true);
} else {
createLog(name, strs[0], strs[1], false);
}
break;
case 3:
createLog(name, strs[0], strs[1], "console".equalsIgnoreCase(strs[2]));
break;
default:
System.err.println("The log " + name + " configuration format is illegal. It will use default log configuration");
createLog(name, DEFAULT_LOG_LEVEL, null, false);
break;
}
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
public static void main(String[] args) {
String json = "{ \"key1\":333, \"arrayKey\":[444, \"array\"], \"key2\" : {\"key3\" : \"hello\", \"key4\":\"world\" }, \"booleanKey\" : true } ";
JsonObject jsonObject = Json.toJsonObject(json);
System.out.println(jsonObject.getJsonArray("arrayKey"));
System.out.println(jsonObject.getJsonObject("key2").getString("key4"));
}
#location 5
#vulnerability type NULL_DEREFERENCE | #fixed code
public static void main(String[] args) {
Calendar cal = Calendar.getInstance();
cal.set(2015, Calendar.JANUARY, 25, 14, 53, 12);
System.out.println(cal.get(Calendar.HOUR_OF_DAY));
DateFormatObject obj = new DateFormatObject();
System.out.println(obj);
obj.init(cal);
String json = Json.toJson(obj);
System.out.println(json);
DateFormatObject obj2 = Json.toObject(json, DateFormatObject.class);
System.out.println(obj2);
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
public static long copy(File src, File dest, long position, long count) throws IOException {
FileInputStream in = new FileInputStream(src);
FileOutputStream out = new FileOutputStream(dest);
FileChannel inChannel = in.getChannel();
FileChannel outChannel = out.getChannel();
try {
return inChannel.transferTo(position, count, outChannel);
} finally {
if (inChannel != null)
inChannel.close();
if (outChannel != null)
outChannel.close();
if (in != null)
in.close();
if (out != null)
out.close();
}
}
#location 17
#vulnerability type RESOURCE_LEAK | #fixed code
public static long copy(File src, File dest, long position, long count) throws IOException {
try(FileInputStream in = new FileInputStream(src);
FileOutputStream out = new FileOutputStream(dest);
FileChannel inChannel = in.getChannel();
FileChannel outChannel = out.getChannel();) {
return inChannel.transferTo(position, count, outChannel);
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
public void flush() {
if (fileOutput && buffer.size() > 0) {
BufferedWriter bufferedWriter = null;
try {
String date = LogFactory.dayDateFormat.format(new Date());
bufferedWriter = getBufferedWriter(date);
for (LogItem logItem = null; (logItem = buffer.poll()) != null;) {
Date d = new Date();
String newDate = LogFactory.dayDateFormat.format(d);
if(!newDate.equals(date)) {
if (bufferedWriter != null)
try {
bufferedWriter.close();
} catch (IOException e) {
e.printStackTrace();
}
date = newDate;
bufferedWriter = getBufferedWriter(date);
}
logItem.setDate(SafeSimpleDateFormat.defaultDateFormat.format(d));
bufferedWriter.append(logItem.toString() + CL);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (bufferedWriter != null)
try {
bufferedWriter.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
#location 23
#vulnerability type NULL_DEREFERENCE | #fixed code
public void flush() {
if (fileOutput && buffer.size() > 0) {
try {
for (LogItem logItem = null; (logItem = buffer.poll()) != null;) {
Date d = new Date();
bufferedWriter = getBufferedWriter(LogFactory.dayDateFormat.format(d));
logItem.setDate(SafeSimpleDateFormat.defaultDateFormat.format(d));
bufferedWriter.append(logItem.toString() + CL);
}
bufferedWriter.flush();
} catch (IOException e) {
e.printStackTrace();
}
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Test
public void testHeaders() throws Throwable {
final HTTP2ServerDecoder decoder = new HTTP2ServerDecoder();
final HTTP2MockSession session = new HTTP2MockSession();
final HTTP2Configuration http2Configuration = new HTTP2Configuration();
final HTTP2ServerConnection http2ServerConnection = new HTTP2ServerConnection(http2Configuration, session, null,
new ServerSessionListener(){
@Override
public Map<Integer, Integer> onPreface(Session session) {
System.out.println("on preface: " + session.isClosed());
Assert.assertThat(session.isClosed(), is(false));
return null;
}
@Override
public Listener onNewStream(Stream stream, HeadersFrame frame) {
System.out.println("on new stream: " + stream.getId());
System.out.println("on new stread headers: " + frame.getMetaData().toString());
Assert.assertThat(stream.getId(), is(5));
Assert.assertThat(frame.getMetaData().getVersion(), is(HttpVersion.HTTP_2));
Assert.assertThat(frame.getMetaData().getFields().get("User-Agent"), is("Firefly Client 1.0"));
MetaData.Request request = (MetaData.Request) frame.getMetaData();
Assert.assertThat(request.getMethod(), is("GET"));
Assert.assertThat(request.getURI().getPath(), is("/index"));
Assert.assertThat(request.getURI().getPort(), is(8080));
Assert.assertThat(request.getURI().getHost(), is("localhost"));
return new Listener(){
@Override
public void onHeaders(Stream stream, HeadersFrame frame) {
System.out.println("on headers: " + frame.getMetaData());
}
@Override
public Listener onPush(Stream stream, PushPromiseFrame frame) {
return null;
}
@Override
public void onData(Stream stream, DataFrame frame, Callback callback) {
}
@Override
public void onReset(Stream stream, ResetFrame frame) {
}
@Override
public void onTimeout(Stream stream, Throwable x) {
}};
}
@Override
public void onSettings(Session session, SettingsFrame frame) {
System.out.println("on settings: " + frame.toString());
Assert.assertThat(frame.getSettings().get(SettingsFrame.INITIAL_WINDOW_SIZE), is(http2Configuration.getInitialStreamSendWindow()));
}
@Override
public void onPing(Session session, PingFrame frame) {
}
@Override
public void onReset(Session session, ResetFrame frame) {
}
@Override
public void onClose(Session session, GoAwayFrame frame) {
}
@Override
public void onFailure(Session session, Throwable failure) {
}
@Override
public void onAccept(Session session) {
}});
int streamId = 5;
HttpFields fields = new HttpFields();
fields.put("Accept", "text/html");
fields.put("User-Agent", "Firefly Client 1.0");
MetaData.Request metaData = new MetaData.Request("GET", HttpScheme.HTTP,
new HostPortHttpField("localhost:8080"), "/index", HttpVersion.HTTP_2, fields);
Map<Integer, Integer> settings = new HashMap<>();
settings.put(SettingsFrame.HEADER_TABLE_SIZE, http2Configuration.getMaxDynamicTableSize());
settings.put(SettingsFrame.INITIAL_WINDOW_SIZE, http2Configuration.getInitialStreamSendWindow());
HeadersGenerator headersGenerator = http2ServerConnection.getGenerator().getControlGenerator(FrameType.HEADERS);
SettingsGenerator settingsGenerator = http2ServerConnection.getGenerator().getControlGenerator(FrameType.SETTINGS);
List<ByteBuffer> list = new LinkedList<>();
list.add(ByteBuffer.wrap(PrefaceFrame.PREFACE_BYTES));
list.add(settingsGenerator.generateSettings(settings, false));
list.addAll(headersGenerator.generateHeaders(streamId, metaData, null, true));
for(ByteBuffer buffer : list) {
decoder.decode(buffer, session);
}
Assert.assertThat(session.outboundData.size(), greaterThan(0));
System.out.println("out data: " + session.outboundData.size());
Assert.assertThat(session.outboundData.size(), greaterThan(1));
http2ServerConnection.close();
}
#location 14
#vulnerability type RESOURCE_LEAK | #fixed code
@Test
public void testHeaders() throws Throwable {
final HTTP2ServerDecoder decoder = new HTTP2ServerDecoder();
final HTTP2MockSession session = new HTTP2MockSession();
final HTTP2Configuration http2Configuration = new HTTP2Configuration();
final HTTP2ServerConnection http2ServerConnection = new HTTP2ServerConnection(http2Configuration, session, null,
new ServerSessionListener(){
@Override
public Map<Integer, Integer> onPreface(Session session) {
System.out.println("on preface: " + session.isClosed());
Assert.assertThat(session.isClosed(), is(false));
return null;
}
@Override
public Listener onNewStream(Stream stream, HeadersFrame frame) {
System.out.println("on new stream: " + stream.getId());
System.out.println("on new stread headers: " + frame.getMetaData().toString());
Assert.assertThat(stream.getId(), is(5));
Assert.assertThat(frame.getMetaData().getVersion(), is(HttpVersion.HTTP_2));
Assert.assertThat(frame.getMetaData().getFields().get("User-Agent"), is("Firefly Client 1.0"));
MetaData.Request request = (MetaData.Request) frame.getMetaData();
Assert.assertThat(request.getMethod(), is("GET"));
Assert.assertThat(request.getURI().getPath(), is("/index"));
Assert.assertThat(request.getURI().getPort(), is(8080));
Assert.assertThat(request.getURI().getHost(), is("localhost"));
return new Listener(){
@Override
public void onHeaders(Stream stream, HeadersFrame frame) {
System.out.println("on headers: " + frame.getMetaData());
}
@Override
public Listener onPush(Stream stream, PushPromiseFrame frame) {
return null;
}
@Override
public void onData(Stream stream, DataFrame frame, Callback callback) {
}
@Override
public void onReset(Stream stream, ResetFrame frame) {
}
@Override
public void onTimeout(Stream stream, Throwable x) {
}};
}
@Override
public void onSettings(Session session, SettingsFrame frame) {
System.out.println("on settings: " + frame.toString());
Assert.assertThat(frame.getSettings().get(SettingsFrame.INITIAL_WINDOW_SIZE), is(http2Configuration.getInitialStreamSendWindow()));
}
@Override
public void onPing(Session session, PingFrame frame) {
}
@Override
public void onReset(Session session, ResetFrame frame) {
}
@Override
public void onClose(Session session, GoAwayFrame frame) {
}
@Override
public void onFailure(Session session, Throwable failure) {
}
@Override
public void onAccept(Session session) {
}});
int streamId = 5;
HttpFields fields = new HttpFields();
fields.put("Accept", "text/html");
fields.put("User-Agent", "Firefly Client 1.0");
MetaData.Request metaData = new MetaData.Request("GET", HttpScheme.HTTP,
new HostPortHttpField("localhost:8080"), "/index", HttpVersion.HTTP_2, fields);
Map<Integer, Integer> settings = new HashMap<>();
settings.put(SettingsFrame.HEADER_TABLE_SIZE, http2Configuration.getMaxDynamicTableSize());
settings.put(SettingsFrame.INITIAL_WINDOW_SIZE, http2Configuration.getInitialStreamSendWindow());
Generator generator = new Generator(http2Configuration.getMaxDynamicTableSize(), http2Configuration.getMaxHeaderBlockFragment());
HeadersGenerator headersGenerator = generator.getControlGenerator(FrameType.HEADERS);
SettingsGenerator settingsGenerator = generator.getControlGenerator(FrameType.SETTINGS);
List<ByteBuffer> list = new LinkedList<>();
list.add(ByteBuffer.wrap(PrefaceFrame.PREFACE_BYTES));
list.add(settingsGenerator.generateSettings(settings, false));
list.addAll(headersGenerator.generateHeaders(streamId, metaData, null, true));
for(ByteBuffer buffer : list) {
decoder.decode(buffer, session);
}
Assert.assertThat(session.outboundData.size(), greaterThan(0));
System.out.println("out data: " + session.outboundData.size());
Assert.assertThat(session.outboundData.size(), greaterThan(1));
http2ServerConnection.close();
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
public void render(RoutingContext ctx, int status, Throwable t) {
HttpStatus.Code code = HttpStatus.getCode(status);
String title = status + " " + (code != null ? code.getMessage() : "error");
String content;
switch (code) {
case NOT_FOUND: {
content = "The resource " + ctx.getURI().getPath() + " is not found";
}
break;
case INTERNAL_SERVER_ERROR: {
content = "The server internal error. <br/>" + (t != null ? t.getMessage() : "");
}
break;
default: {
content = title + "<br/>" + (t != null ? t.getMessage() : "");
}
break;
}
ctx.setStatus(status).put(HttpHeader.CONTENT_TYPE, "text/html")
.write("<!DOCTYPE html>")
.write("<html>")
.write("<head>")
.write("<title>")
.write(title)
.write("</title>")
.write("</head>")
.write("<body>")
.write("<h1> " + title + " </h1>")
.write("<p>" + content + "</p>")
.write("<hr/>")
.write("<footer><em>powered by Firefly " + Version.value + "</em></footer>")
.write("</body>")
.end("</html>");
}
#location 5
#vulnerability type NULL_DEREFERENCE | #fixed code
public void render(RoutingContext ctx, int status, Throwable t) {
HttpStatus.Code code = Optional.ofNullable(HttpStatus.getCode(status)).orElse(HttpStatus.Code.INTERNAL_SERVER_ERROR);
String title = status + " " + code.getMessage();
String content;
switch (code) {
case NOT_FOUND: {
content = "The resource " + ctx.getURI().getPath() + " is not found";
}
break;
case INTERNAL_SERVER_ERROR: {
content = "The server internal error. <br/>" + (t != null ? t.getMessage() : "");
}
break;
default: {
content = title + "<br/>" + (t != null ? t.getMessage() : "");
}
break;
}
ctx.setStatus(status).put(HttpHeader.CONTENT_TYPE, "text/html")
.write("<!DOCTYPE html>")
.write("<html>")
.write("<head>")
.write("<title>")
.write(title)
.write("</title>")
.write("</head>")
.write("<body>")
.write("<h1> " + title + " </h1>")
.write("<p>" + content + "</p>")
.write("<hr/>")
.write("<footer><em>powered by Firefly " + Version.value + "</em></footer>")
.write("</body>")
.end("</html>");
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Test
public void testMethodType() {
Map<String, MethodGenericTypeBind> getterMap = ReflectUtils.getGenericBeanGetterMethods(
new GenericTypeReference<Request<Map<String, Foo>, String, Map<String, List<Foo>>>>() {
}, null);
MethodGenericTypeBind extInfo = getterMap.get("extInfo");
ParameterizedType parameterizedType = (ParameterizedType) extInfo.getType();
System.out.println(parameterizedType.getTypeName());
Assert.assertThat(parameterizedType.getTypeName(), is("java.util.Map<java.lang.String, java.util.Map<java.lang.String, java.util.List<test.utils.lang.TestGenericTypeReference$Foo>>>"));
Assert.assertThat(extInfo.getMethodType(), is(MethodType.GETTER));
Map<String, MethodGenericTypeBind> setterMap = ReflectUtils.getGenericBeanSetterMethods(
new GenericTypeReference<Request<Map<String, Foo>, String, Map<String, List<Foo>>>>() {
}, null);
extInfo = setterMap.get("extInfo");
parameterizedType = (ParameterizedType) extInfo.getType();
System.out.println(parameterizedType.getTypeName());
Assert.assertThat(parameterizedType.getTypeName(), is("java.util.Map<java.lang.String, java.util.Map<java.lang.String, java.util.List<test.utils.lang.TestGenericTypeReference$Foo>>>"));
Assert.assertThat(extInfo.getMethodType(), is(MethodType.SETTER));
}
#location 16
#vulnerability type NULL_DEREFERENCE | #fixed code
@Test
public void testMethodType() {
Map<String, MethodGenericTypeBind> getterMap = ReflectUtils.getGenericBeanGetterMethods(reqRef);
MethodGenericTypeBind extInfo = getterMap.get("extInfo");
ParameterizedType parameterizedType = (ParameterizedType) extInfo.getType();
System.out.println(parameterizedType.getTypeName());
Assert.assertThat(parameterizedType.getTypeName(), is("java.util.Map<java.lang.String, java.util.Map<java.lang.String, java.util.List<test.utils.lang.TestGenericTypeReference$Foo>>>"));
Assert.assertThat(extInfo.getMethodType(), is(MethodType.GETTER));
Map<String, MethodGenericTypeBind> setterMap = ReflectUtils.getGenericBeanSetterMethods(reqRef);
extInfo = setterMap.get("extInfo");
parameterizedType = (ParameterizedType) extInfo.getType();
System.out.println(parameterizedType.getTypeName());
Assert.assertThat(parameterizedType.getTypeName(), is("java.util.Map<java.lang.String, java.util.Map<java.lang.String, java.util.List<test.utils.lang.TestGenericTypeReference$Foo>>>"));
Assert.assertThat(extInfo.getMethodType(), is(MethodType.SETTER));
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
public static long copy(File src, File dest, long position, long count) throws IOException {
FileInputStream in = new FileInputStream(src);
FileOutputStream out = new FileOutputStream(dest);
FileChannel inChannel = in.getChannel();
FileChannel outChannel = out.getChannel();
try {
return inChannel.transferTo(position, count, outChannel);
} finally {
if (inChannel != null)
inChannel.close();
if (outChannel != null)
outChannel.close();
if (in != null)
in.close();
if (out != null)
out.close();
}
}
#location 17
#vulnerability type RESOURCE_LEAK | #fixed code
public static long copy(File src, File dest, long position, long count) throws IOException {
try(FileInputStream in = new FileInputStream(src);
FileOutputStream out = new FileOutputStream(dest);
FileChannel inChannel = in.getChannel();
FileChannel outChannel = out.getChannel();) {
return inChannel.transferTo(position, count, outChannel);
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Test
public void testHeaders() throws Throwable {
final HTTP2Decoder decoder = new HTTP2Decoder();
final HTTP2MockSession session = new HTTP2MockSession();
final HTTP2Configuration http2Configuration = new HTTP2Configuration();
final HTTP2SessionAttachment attachment = new HTTP2SessionAttachment(http2Configuration, session,
new ServerSessionListener(){
@Override
public Map<Integer, Integer> onPreface(Session session) {
System.out.println("on preface: " + session.isClosed());
Assert.assertThat(session.isClosed(), is(false));
return null;
}
@Override
public Listener onNewStream(Stream stream, HeadersFrame frame) {
System.out.println("on new stream: " + stream.getId());
System.out.println("on new stread headers: " + frame.getMetaData().toString());
Assert.assertThat(stream.getId(), is(5));
Assert.assertThat(frame.getMetaData().getVersion(), is(HttpVersion.HTTP_2));
Assert.assertThat(frame.getMetaData().getFields().get("User-Agent"), is("Firefly Client 1.0"));
MetaData.Request request = (MetaData.Request) frame.getMetaData();
Assert.assertThat(request.getMethod(), is("GET"));
Assert.assertThat(request.getURI().getPath(), is("/index"));
Assert.assertThat(request.getURI().getPort(), is(8080));
Assert.assertThat(request.getURI().getHost(), is("localhost"));
return new Listener(){
@Override
public void onHeaders(Stream stream, HeadersFrame frame) {
System.out.println("on headers: " + frame.getMetaData());
}
@Override
public Listener onPush(Stream stream, PushPromiseFrame frame) {
return null;
}
@Override
public void onData(Stream stream, DataFrame frame, Callback callback) {
}
@Override
public void onReset(Stream stream, ResetFrame frame) {
}
@Override
public void onTimeout(Stream stream, Throwable x) {
}};
}
@Override
public void onSettings(Session session, SettingsFrame frame) {
System.out.println("on settings: " + frame.toString());
Assert.assertThat(frame.getSettings().get(SettingsFrame.INITIAL_WINDOW_SIZE), is(http2Configuration.getInitialStreamSendWindow()));
}
@Override
public void onPing(Session session, PingFrame frame) {
}
@Override
public void onReset(Session session, ResetFrame frame) {
}
@Override
public void onClose(Session session, GoAwayFrame frame) {
}
@Override
public void onFailure(Session session, Throwable failure) {
}
@Override
public void onAccept(Session session) {
}});
int streamId = 5;
HttpFields fields = new HttpFields();
fields.put("Accept", "text/html");
fields.put("User-Agent", "Firefly Client 1.0");
MetaData.Request metaData = new MetaData.Request("GET", HttpScheme.HTTP,
new HostPortHttpField("localhost:8080"), "/index", HttpVersion.HTTP_2, fields);
Map<Integer, Integer> settings = new HashMap<>();
settings.put(SettingsFrame.HEADER_TABLE_SIZE, http2Configuration.getMaxDynamicTableSize());
settings.put(SettingsFrame.INITIAL_WINDOW_SIZE, http2Configuration.getInitialStreamSendWindow());
HeadersGenerator headersGenerator = attachment.getGenerator().getControlGenerator(FrameType.HEADERS);
SettingsGenerator settingsGenerator = attachment.getGenerator().getControlGenerator(FrameType.SETTINGS);
List<ByteBuffer> list = new LinkedList<>();
list.add(ByteBuffer.wrap(PrefaceFrame.PREFACE_BYTES));
list.add(settingsGenerator.generateSettings(settings, false));
list.addAll(headersGenerator.generateHeaders(streamId, metaData, null, true));
for(ByteBuffer buffer : list) {
decoder.decode(buffer, session);
}
Assert.assertThat(session.outboundData.size(), greaterThan(0));
System.out.println("out data: " + session.outboundData.size());
}
#location 93
#vulnerability type NULL_DEREFERENCE | #fixed code
@Test
public void testHeaders() throws Throwable {
final HTTP2Decoder decoder = new HTTP2Decoder();
final HTTP2MockSession session = new HTTP2MockSession();
final HTTP2Configuration http2Configuration = new HTTP2Configuration();
final HTTP2SessionAttachment attachment = new HTTP2SessionAttachment(http2Configuration, session,
new ServerSessionListener(){
@Override
public Map<Integer, Integer> onPreface(Session session) {
System.out.println("on preface: " + session.isClosed());
Assert.assertThat(session.isClosed(), is(false));
return null;
}
@Override
public Listener onNewStream(Stream stream, HeadersFrame frame) {
System.out.println("on new stream: " + stream.getId());
System.out.println("on new stread headers: " + frame.getMetaData().toString());
Assert.assertThat(stream.getId(), is(5));
Assert.assertThat(frame.getMetaData().getVersion(), is(HttpVersion.HTTP_2));
Assert.assertThat(frame.getMetaData().getFields().get("User-Agent"), is("Firefly Client 1.0"));
MetaData.Request request = (MetaData.Request) frame.getMetaData();
Assert.assertThat(request.getMethod(), is("GET"));
Assert.assertThat(request.getURI().getPath(), is("/index"));
Assert.assertThat(request.getURI().getPort(), is(8080));
Assert.assertThat(request.getURI().getHost(), is("localhost"));
return new Listener(){
@Override
public void onHeaders(Stream stream, HeadersFrame frame) {
System.out.println("on headers: " + frame.getMetaData());
}
@Override
public Listener onPush(Stream stream, PushPromiseFrame frame) {
return null;
}
@Override
public void onData(Stream stream, DataFrame frame, Callback callback) {
}
@Override
public void onReset(Stream stream, ResetFrame frame) {
}
@Override
public void onTimeout(Stream stream, Throwable x) {
}};
}
@Override
public void onSettings(Session session, SettingsFrame frame) {
System.out.println("on settings: " + frame.toString());
Assert.assertThat(frame.getSettings().get(SettingsFrame.INITIAL_WINDOW_SIZE), is(http2Configuration.getInitialStreamSendWindow()));
}
@Override
public void onPing(Session session, PingFrame frame) {
}
@Override
public void onReset(Session session, ResetFrame frame) {
}
@Override
public void onClose(Session session, GoAwayFrame frame) {
}
@Override
public void onFailure(Session session, Throwable failure) {
}
@Override
public void onAccept(Session session) {
}});
int streamId = 5;
HttpFields fields = new HttpFields();
fields.put("Accept", "text/html");
fields.put("User-Agent", "Firefly Client 1.0");
MetaData.Request metaData = new MetaData.Request("GET", HttpScheme.HTTP,
new HostPortHttpField("localhost:8080"), "/index", HttpVersion.HTTP_2, fields);
Map<Integer, Integer> settings = new HashMap<>();
settings.put(SettingsFrame.HEADER_TABLE_SIZE, http2Configuration.getMaxDynamicTableSize());
settings.put(SettingsFrame.INITIAL_WINDOW_SIZE, http2Configuration.getInitialStreamSendWindow());
HeadersGenerator headersGenerator = attachment.getGenerator().getControlGenerator(FrameType.HEADERS);
SettingsGenerator settingsGenerator = attachment.getGenerator().getControlGenerator(FrameType.SETTINGS);
List<ByteBuffer> list = new LinkedList<>();
list.add(ByteBuffer.wrap(PrefaceFrame.PREFACE_BYTES));
list.add(settingsGenerator.generateSettings(settings, false));
list.addAll(headersGenerator.generateHeaders(streamId, metaData, null, true));
for(ByteBuffer buffer : list) {
decoder.decode(buffer, session);
}
Assert.assertThat(session.outboundData.size(), greaterThan(0));
System.out.println("out data: " + session.outboundData.size());
attachment.close();
} | Below is the vulnerable code, please generate the patch based on the following information. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.