output
stringlengths 64
73.2k
| input
stringlengths 208
73.3k
| instruction
stringclasses 1
value |
|---|---|---|
#fixed code
public void shutdown() throws InterruptedException {
//remove all webServices
WebService[] services;
synchronized (this){
services = new WebService[registeredServices.values().size()];
registeredServices.values().toArray(services);
}
for(WebService service : services){
removeService(service.getPath());
}
//some time to send possible update notifications (404_NOT_FOUND) to observers
Thread.sleep(1000);
//Close the datagram datagramChannel (includes unbind)
ChannelFuture future = channel.close();
//Await the closure and let the factory release its external resource to finalize the shutdown
future.addListener(new ChannelFutureListener() {
@Override
public void operationComplete(ChannelFuture future) throws Exception {
DatagramChannel closedChannel = (DatagramChannel) future.getChannel();
log.info("Server channel closed (port {}).", closedChannel.getLocalAddress().getPort());
channel.getFactory().releaseExternalResources();
log.info("External resources released, shutdown completed (port {}).",
closedChannel.getLocalAddress().getPort());
}
});
future.awaitUninterruptibly();
}
|
#vulnerable code
public void shutdown(){
//remove all webServices
WebService[] services;
synchronized (this){
services = new WebService[registeredServices.values().size()];
registeredServices.values().toArray(services);
}
for(WebService service : services){
removeService(service.getPath());
}
//Close the datagram datagramChannel (includes unbind)
ChannelFuture future = channel.close();
//Await the closure and let the factory release its external resource to finalize the shutdown
future.addListener(new ChannelFutureListener() {
@Override
public void operationComplete(ChannelFuture future) throws Exception {
DatagramChannel closedChannel = (DatagramChannel) future.getChannel();
log.info("Server channel closed (port {}).", closedChannel.getLocalAddress().getPort());
channel.getFactory().releaseExternalResources();
log.info("External resources released, shutdown completed (port {}).",
closedChannel.getLocalAddress().getPort());
}
});
future.awaitUninterruptibly();
executorService.shutdownNow();
}
#location 32
#vulnerability type THREAD_SAFETY_VIOLATION
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
@Override
public void messageReceived(ChannelHandlerContext ctx, MessageEvent me) throws Exception {
super.messageReceived(ctx, me);
}
|
#vulnerable code
@Override
public void messageReceived(ChannelHandlerContext ctx, MessageEvent me){
if(!(me.getMessage() instanceof CoapMessage)){
ctx.sendUpstream(me);
return;
}
CoapMessage coapMessage = (CoapMessage) me.getMessage();
if(coapMessage.getCode().isError() || coapMessage.getMessageType().equals(MsgType.RST)){
errorMessageReceived(ctx, me);
return;
}
if(me.getMessage() instanceof CoapResponse){
CoapResponse response = (CoapResponse) me.getMessage();
final byte[] token = response.getToken();
BlockwiseTransfer transfer;
//Add latest received payload to already received payload
synchronized (incompleteResponseMonitor){
transfer = incompleteResponsePayload.get(new ByteArrayWrapper(token));
if(transfer != null){
try {
if(response.getBlockNumber(BLOCK_2) == transfer.getNextBlockNumber()){
log.debug("Received response (Token: " + (new ByteArrayWrapper(token).toHexString()) +
" , Block: " + response.getBlockNumber(BLOCK_2) + "), ");
if (log.isDebugEnabled()){
//Copy Payload
ChannelBuffer payloadCopy = ChannelBuffers.copiedBuffer(response.getPayload());
byte[] bytes = new byte[payloadCopy.readableBytes()];
payloadCopy.getBytes(0, bytes);
log.debug("Payload Hex: " + new ByteArrayWrapper(bytes).toHexString());
}
transfer.getPartialPayload()
.writeBytes(response.getPayload(), 0, response.getPayload().readableBytes());
transfer.setNextBlockNumber(transfer.getNextBlockNumber() + 1);
}
else{
log.debug("Received unexpected response (Token: " + (new ByteArrayWrapper(token).toHexString()) +
" , Block: " + response.getBlockNumber(BLOCK_2) + "). IGNORE!");
me.getFuture().setSuccess();
return;
}
}
catch (InvalidOptionException e) {
log.error("This should never happen!", e);
}
}
}
//Check whether payload of the response is complete
if(transfer != null){
try {
if(response.isLastBlock(BLOCK_2)){
//Send response with complete payload to application
log.debug("Block " + response.getBlockNumber(BLOCK_2) + " for response with token " +
new ByteArrayWrapper(token).toHexString() +
" received. Payload complete. Forward to client application.");
response.getOptionList().removeAllOptions(BLOCK_2);
response.setPayload(transfer.getPartialPayload());
MessageEvent event = new UpstreamMessageEvent(me.getChannel(), response, me.getRemoteAddress());
ctx.sendUpstream(event);
synchronized (incompleteResponseMonitor){
if(incompleteResponsePayload.remove(new ByteArrayWrapper(token)) == null){
log.error("This should never happen! No incomplete payload found for token " +
new ByteArrayWrapper(token).toHexString());
}
else{
log.debug("Deleted not anymore incomplete payload for token " +
new ByteArrayWrapper(token).toHexString() + " from list");
}
}
return;
}
else{
final long receivedBlockNumber = response.getBlockNumber(BLOCK_2);
log.debug("Block " + receivedBlockNumber + " for response with token " +
new ByteArrayWrapper(token).toHexString() +
" received. Payload (still) incomplete.");
CoapRequest nextCoapRequest = (CoapRequest) transfer.getCoapMessage();
nextCoapRequest.setMessageID(-1);
nextCoapRequest.setBlockOption(BLOCK_2, receivedBlockNumber + 1,
false, response.getMaxBlocksizeForResponse());
ChannelFuture future = Channels.future(me.getChannel());
future.addListener(new ChannelFutureListener() {
@Override
public void operationComplete(ChannelFuture future) throws Exception {
log.debug("Request for block " + (receivedBlockNumber + 1) + " for token " +
new ByteArrayWrapper(token).toHexString() + " sent succesfully.");
}
});
MessageEvent event = new DownstreamMessageEvent(me.getChannel(),
future, nextCoapRequest, me.getRemoteAddress());
log.debug("Send request for block " + (receivedBlockNumber + 1) + " for token " +
new ByteArrayWrapper(token).toHexString() + ".");
ctx.sendDownstream(event);
return;
}
}
catch (InvalidOptionException e) {
log.error("This should never happen!", e);
}
catch (MessageDoesNotAllowPayloadException e) {
log.error("This should never happen!", e);
}
catch (ToManyOptionsException e){
log.error("This should never happen!", e);
}
catch (InvalidHeaderException e) {
log.error("This should never happen!", e);
}
}
}
ctx.sendUpstream(me);
}
#location 66
#vulnerability type THREAD_SAFETY_VIOLATION
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
@Override
public void receiveResponse(CoapResponse coapResponse) {
receivedResponses.put(System.currentTimeMillis(), coapResponse);
}
|
#vulnerable code
@Override
public void receiveResponse(CoapResponse coapResponse) {
if (receiveEnabled) {
receivedResponses.put(System.currentTimeMillis(), coapResponse);
}
}
#location 3
#vulnerability type THREAD_SAFETY_VIOLATION
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
@Override
public void messageReceived(ChannelHandlerContext ctx, MessageEvent me) throws Exception {
super.messageReceived(ctx, me);
}
|
#vulnerable code
@Override
public void messageReceived(ChannelHandlerContext ctx, MessageEvent me){
if(!(me.getMessage() instanceof CoapMessage)){
ctx.sendUpstream(me);
return;
}
CoapMessage coapMessage = (CoapMessage) me.getMessage();
if(coapMessage.getCode().isError() || coapMessage.getMessageType().equals(MsgType.RST)){
errorMessageReceived(ctx, me);
return;
}
if(me.getMessage() instanceof CoapResponse){
CoapResponse response = (CoapResponse) me.getMessage();
final byte[] token = response.getToken();
BlockwiseTransfer transfer;
//Add latest received payload to already received payload
synchronized (incompleteResponseMonitor){
transfer = incompleteResponsePayload.get(new ByteArrayWrapper(token));
if(transfer != null){
try {
if(response.getBlockNumber(BLOCK_2) == transfer.getNextBlockNumber()){
log.debug("Received response (Token: " + (new ByteArrayWrapper(token).toHexString()) +
" , Block: " + response.getBlockNumber(BLOCK_2) + "), ");
if (log.isDebugEnabled()){
//Copy Payload
ChannelBuffer payloadCopy = ChannelBuffers.copiedBuffer(response.getPayload());
byte[] bytes = new byte[payloadCopy.readableBytes()];
payloadCopy.getBytes(0, bytes);
log.debug("Payload Hex: " + new ByteArrayWrapper(bytes).toHexString());
}
transfer.getPartialPayload()
.writeBytes(response.getPayload(), 0, response.getPayload().readableBytes());
transfer.setNextBlockNumber(transfer.getNextBlockNumber() + 1);
}
else{
log.debug("Received unexpected response (Token: " + (new ByteArrayWrapper(token).toHexString()) +
" , Block: " + response.getBlockNumber(BLOCK_2) + "). IGNORE!");
me.getFuture().setSuccess();
return;
}
}
catch (InvalidOptionException e) {
log.error("This should never happen!", e);
}
}
}
//Check whether payload of the response is complete
if(transfer != null){
try {
if(response.isLastBlock(BLOCK_2)){
//Send response with complete payload to application
log.debug("Block " + response.getBlockNumber(BLOCK_2) + " for response with token " +
new ByteArrayWrapper(token).toHexString() +
" received. Payload complete. Forward to client application.");
response.getOptionList().removeAllOptions(BLOCK_2);
response.setPayload(transfer.getPartialPayload());
MessageEvent event = new UpstreamMessageEvent(me.getChannel(), response, me.getRemoteAddress());
ctx.sendUpstream(event);
synchronized (incompleteResponseMonitor){
if(incompleteResponsePayload.remove(new ByteArrayWrapper(token)) == null){
log.error("This should never happen! No incomplete payload found for token " +
new ByteArrayWrapper(token).toHexString());
}
else{
log.debug("Deleted not anymore incomplete payload for token " +
new ByteArrayWrapper(token).toHexString() + " from list");
}
}
return;
}
else{
final long receivedBlockNumber = response.getBlockNumber(BLOCK_2);
log.debug("Block " + receivedBlockNumber + " for response with token " +
new ByteArrayWrapper(token).toHexString() +
" received. Payload (still) incomplete.");
CoapRequest nextCoapRequest = (CoapRequest) transfer.getCoapMessage();
nextCoapRequest.setMessageID(-1);
nextCoapRequest.setBlockOption(BLOCK_2, receivedBlockNumber + 1,
false, response.getMaxBlocksizeForResponse());
ChannelFuture future = Channels.future(me.getChannel());
future.addListener(new ChannelFutureListener() {
@Override
public void operationComplete(ChannelFuture future) throws Exception {
log.debug("Request for block " + (receivedBlockNumber + 1) + " for token " +
new ByteArrayWrapper(token).toHexString() + " sent succesfully.");
}
});
MessageEvent event = new DownstreamMessageEvent(me.getChannel(),
future, nextCoapRequest, me.getRemoteAddress());
log.debug("Send request for block " + (receivedBlockNumber + 1) + " for token " +
new ByteArrayWrapper(token).toHexString() + ".");
ctx.sendDownstream(event);
return;
}
}
catch (InvalidOptionException e) {
log.error("This should never happen!", e);
}
catch (MessageDoesNotAllowPayloadException e) {
log.error("This should never happen!", e);
}
catch (ToManyOptionsException e){
log.error("This should never happen!", e);
}
catch (InvalidHeaderException e) {
log.error("This should never happen!", e);
}
}
}
ctx.sendUpstream(me);
}
#location 38
#vulnerability type THREAD_SAFETY_VIOLATION
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
@Override
public void messageReceived(ChannelHandlerContext ctx, MessageEvent me) throws Exception {
super.messageReceived(ctx, me);
}
|
#vulnerable code
@Override
public void messageReceived(ChannelHandlerContext ctx, MessageEvent me){
if(!(me.getMessage() instanceof CoapMessage)){
ctx.sendUpstream(me);
return;
}
CoapMessage coapMessage = (CoapMessage) me.getMessage();
if(coapMessage.getCode().isError() || coapMessage.getMessageType().equals(MsgType.RST)){
errorMessageReceived(ctx, me);
return;
}
if(me.getMessage() instanceof CoapResponse){
CoapResponse response = (CoapResponse) me.getMessage();
final byte[] token = response.getToken();
BlockwiseTransfer transfer;
//Add latest received payload to already received payload
synchronized (incompleteResponseMonitor){
transfer = incompleteResponsePayload.get(new ByteArrayWrapper(token));
if(transfer != null){
try {
if(response.getBlockNumber(BLOCK_2) == transfer.getNextBlockNumber()){
log.debug("Received response (Token: " + (new ByteArrayWrapper(token).toHexString()) +
" , Block: " + response.getBlockNumber(BLOCK_2) + "), ");
if (log.isDebugEnabled()){
//Copy Payload
ChannelBuffer payloadCopy = ChannelBuffers.copiedBuffer(response.getPayload());
byte[] bytes = new byte[payloadCopy.readableBytes()];
payloadCopy.getBytes(0, bytes);
log.debug("Payload Hex: " + new ByteArrayWrapper(bytes).toHexString());
}
transfer.getPartialPayload()
.writeBytes(response.getPayload(), 0, response.getPayload().readableBytes());
transfer.setNextBlockNumber(transfer.getNextBlockNumber() + 1);
}
else{
log.debug("Received unexpected response (Token: " + (new ByteArrayWrapper(token).toHexString()) +
" , Block: " + response.getBlockNumber(BLOCK_2) + "). IGNORE!");
me.getFuture().setSuccess();
return;
}
}
catch (InvalidOptionException e) {
log.error("This should never happen!", e);
}
}
}
//Check whether payload of the response is complete
if(transfer != null){
try {
if(response.isLastBlock(BLOCK_2)){
//Send response with complete payload to application
log.debug("Block " + response.getBlockNumber(BLOCK_2) + " for response with token " +
new ByteArrayWrapper(token).toHexString() +
" received. Payload complete. Forward to client application.");
response.getOptionList().removeAllOptions(BLOCK_2);
response.setPayload(transfer.getPartialPayload());
MessageEvent event = new UpstreamMessageEvent(me.getChannel(), response, me.getRemoteAddress());
ctx.sendUpstream(event);
synchronized (incompleteResponseMonitor){
if(incompleteResponsePayload.remove(new ByteArrayWrapper(token)) == null){
log.error("This should never happen! No incomplete payload found for token " +
new ByteArrayWrapper(token).toHexString());
}
else{
log.debug("Deleted not anymore incomplete payload for token " +
new ByteArrayWrapper(token).toHexString() + " from list");
}
}
return;
}
else{
final long receivedBlockNumber = response.getBlockNumber(BLOCK_2);
log.debug("Block " + receivedBlockNumber + " for response with token " +
new ByteArrayWrapper(token).toHexString() +
" received. Payload (still) incomplete.");
CoapRequest nextCoapRequest = (CoapRequest) transfer.getCoapMessage();
nextCoapRequest.setMessageID(-1);
nextCoapRequest.setBlockOption(BLOCK_2, receivedBlockNumber + 1,
false, response.getMaxBlocksizeForResponse());
ChannelFuture future = Channels.future(me.getChannel());
future.addListener(new ChannelFutureListener() {
@Override
public void operationComplete(ChannelFuture future) throws Exception {
log.debug("Request for block " + (receivedBlockNumber + 1) + " for token " +
new ByteArrayWrapper(token).toHexString() + " sent succesfully.");
}
});
MessageEvent event = new DownstreamMessageEvent(me.getChannel(),
future, nextCoapRequest, me.getRemoteAddress());
log.debug("Send request for block " + (receivedBlockNumber + 1) + " for token " +
new ByteArrayWrapper(token).toHexString() + ".");
ctx.sendDownstream(event);
return;
}
}
catch (InvalidOptionException e) {
log.error("This should never happen!", e);
}
catch (MessageDoesNotAllowPayloadException e) {
log.error("This should never happen!", e);
}
catch (ToManyOptionsException e){
log.error("This should never happen!", e);
}
catch (InvalidHeaderException e) {
log.error("This should never happen!", e);
}
}
}
ctx.sendUpstream(me);
}
#location 91
#vulnerability type THREAD_SAFETY_VIOLATION
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
@Override
public void writeRequested(ChannelHandlerContext ctx, MessageEvent me) throws Exception{
if(!(me.getMessage() instanceof CoapMessage)){
ctx.sendDownstream(me);
return;
}
CoapMessage coapMessage = (CoapMessage) me.getMessage();
log.debug("Outgoing " + coapMessage.getMessageType() + " (MsgID " + coapMessage.getMessageID() +
", MsgHash " + Integer.toHexString(coapMessage.hashCode()) + ", Rcpt " + me.getRemoteAddress() +
", Block " + coapMessage.getBlockNumber(OptionRegistry.OptionName.BLOCK_2) + ").");
if(coapMessage.getMessageID() == -1){
coapMessage.setMessageID(messageIDFactory.nextMessageID());
log.debug("Set message ID " + coapMessage.getMessageID());
if(coapMessage.getMessageType() == MsgType.CON){
if(!waitingForACK.contains(me.getRemoteAddress(), coapMessage.getMessageID())){
MessageRetransmissionScheduler scheduler =
new MessageRetransmissionScheduler((InetSocketAddress) me.getRemoteAddress(), coapMessage);
executorService.schedule(scheduler, 0, TimeUnit.MILLISECONDS);
}
}
}
ctx.sendDownstream(me);
}
|
#vulnerable code
@Override
public void writeRequested(ChannelHandlerContext ctx, MessageEvent me) throws Exception{
if(!(me.getMessage() instanceof CoapMessage)){
ctx.sendDownstream(me);
return;
}
CoapMessage coapMessage = (CoapMessage) me.getMessage();
log.debug("Handle downstream event for message with ID " +
coapMessage.getMessageID() + " for " + me.getRemoteAddress() );
if(coapMessage.getMessageID() == -1){
coapMessage.setMessageID(messageIDFactory.nextMessageID());
log.debug("Set message ID " + coapMessage.getMessageID());
if(coapMessage.getMessageType() == MsgType.CON){
if(!openOutgoingConMsg.contains(me.getRemoteAddress(), coapMessage.getMessageID())){
synchronized (getClass()){
openOutgoingConMsg.put((InetSocketAddress) me.getRemoteAddress(),
coapMessage.getMessageID(),
coapMessage.getToken());
//Schedule first retransmission
MessageRetransmitter messageRetransmitter
= new MessageRetransmitter((InetSocketAddress) me.getRemoteAddress(), coapMessage);
int delay = (int) (TIMEOUT_MILLIS * messageRetransmitter.randomFactor);
executorService.schedule(messageRetransmitter, delay, TimeUnit.MILLISECONDS);
log.debug("First retransmit for " +
coapMessage.getMessageType() + " message with ID " + coapMessage.getMessageID() +
" to be confirmed by " + me.getRemoteAddress() + " scheduled with a delay of " +
delay + " millis.");
}
}
}
}
ctx.sendDownstream(me);
}
#location 16
#vulnerability type THREAD_SAFETY_VIOLATION
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
@Test
public void getChannelNameFromMessageTest() throws IOException, InvocationTargetException, IllegalAccessException {
Method method = MethodUtils.getMatchingMethod(HitbtcStreamingService.class, "getChannelNameFromMessage", JsonNode.class);
method.setAccessible(true);
String json = "{\"method\":\"aaa\"}";
Assert.assertEquals("aaa", method.invoke(streamingService, objectMapper.readTree(json)));
json = "{ \"method\": \"updateOrderbook\", \"params\": { \"symbol\": \"ETHBTC\" } }";
Assert.assertEquals("orderbook-ETHBTC", method.invoke(streamingService, objectMapper.readTree(json)));
json = "{ \"method\": \"snapshotOrderbook\", \"params\": { \"symbol\": \"ETHBTC\" } }";
Assert.assertEquals("orderbook-ETHBTC", method.invoke(streamingService, objectMapper.readTree(json)));
json = "{ \"method\": \"test\", \"params\": { \"symbol\": \"ETHBTC\" } }";
Assert.assertEquals("test-ETHBTC", method.invoke(streamingService, objectMapper.readTree(json)));
json = "{ \"noMethod\": \"updateOrderbook\" } }";
thrown.expect(InvocationTargetException.class);
method.invoke(streamingService, objectMapper.readTree(json));
}
|
#vulnerable code
@Test
public void getChannelNameFromMessageTest() throws IOException, InvocationTargetException, IllegalAccessException {
Method method = MethodUtils.getMatchingMethod(HitbtcStreamingService.class, "getChannelNameFromMessage", JsonNode.class);
method.setAccessible(true);
String json = "{\"method\":\"aaa\"}";
Assert.assertEquals("aaa", method.invoke(streamingService, objectMapper.readTree(json)));
json = "{ \"method\": \"updateOrderbook\", \"params\": { \"symbol\": \"ETHBTC\" } }";
Assert.assertEquals("orderbook-ETHBTC", method.invoke(streamingService, objectMapper.readTree(json)));
json = "{ \"method\": \"snapshotOrderbook\", \"params\": { \"symbol\": \"ETHBTC\" } }";
Assert.assertEquals("orderbook-ETHBTC", method.invoke(streamingService, objectMapper.readTree(json)));
json = "{ \"method\": \"test\", \"params\": { \"symbol\": \"ETHBTC\" } }";
Assert.assertEquals("test-ETHBTC", method.invoke(streamingService, objectMapper.readTree(json)));
json = "{ \"noMethod\": \"updateOrderbook\" } }";
Throwable exception = null;
try {
method.invoke(streamingService, objectMapper.readTree(json));
} catch (InvocationTargetException e) {
exception = e.getTargetException();
}
Assert.assertNotNull("Expected IOException because no method", exception);
Assert.assertEquals(IOException.class, exception.getClass());
}
#location 28
#vulnerability type NULL_DEREFERENCE
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
@Test
public void dup2Test() throws Throwable {
File tmp = File.createTempFile("dupTest", "tmp");
int oldFd = posix.open(tmp.getAbsolutePath(), OpenFlags.O_RDWR.intValue(), 0666);
int newFd = 1000;
byte[] outContent = "foo".getBytes();
// NB: Windows differs a bit from POSIX's return value. Both will return -1 on failure, but Windows will return
// 0 upon success, while POSIX will return the new FD. Since we already know what the FD will be if the call
// is successful, it's easy to make code that works with both forms. But it is something to watch out for.
assertNotEquals(-1, posix.dup2(oldFd, newFd));
FileDescriptor newFileDescriptor = toDescriptor(newFd);
new FileOutputStream(toDescriptor(oldFd)).write(outContent);
posix.lseek(newFd, SEEK_SET, 0);
byte[] inContent = new byte[outContent.length];
new FileInputStream(newFileDescriptor).read(inContent, 0, 3);
assertArrayEquals(inContent, outContent);
}
|
#vulnerable code
@Test
public void dup2Test() throws Throwable {
File tmp = File.createTempFile("dupTest", "tmp");
RandomAccessFile raf = new RandomAccessFile(tmp, "rw");
int oldFd = getFdFromDescriptor(JavaLibCHelper.getDescriptorFromChannel(new RandomAccessFile(tmp, "rw").getChannel()));
int newFd = getFdFromDescriptor(JavaLibCHelper.getDescriptorFromChannel(raf.getChannel()));
byte[] outContent = "foo".getBytes();
// NB: Windows differs a bit from POSIX's return value. Both will return -1 on failure, but Windows will return
// 0 upon success, while POSIX will return the new FD. Since we already know what the FD will be if the call
// is successful, it's easy to make code that works with both forms. But it is something to watch out for.
assertNotEquals(-1, posix.dup2(oldFd, newFd));
FileDescriptor newFileDescriptor = toDescriptor(newFd);
new FileOutputStream(toDescriptor(oldFd)).write(outContent);
raf.seek(0);
byte[] inContent = new byte[outContent.length];
new FileInputStream(newFileDescriptor).read(inContent, 0, 3);
assertArrayEquals(inContent, outContent);
}
#location 5
#vulnerability type RESOURCE_LEAK
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
@Test
public void fcntlDupfdWithArgTest() throws Throwable {
File tmp = File.createTempFile("dupTest", "tmp");
int oldFd = JavaLibCHelper.getfdFromDescriptor(JavaLibCHelper.getDescriptorFromChannel(
new RandomAccessFile(tmp, "rw").getChannel()));
int newFd = JavaLibCHelper.getfdFromDescriptor(JavaLibCHelper.getDescriptorFromChannel(
new RandomAccessFile(tmp, "rw").getChannel()));
byte[] outContent = "foo".getBytes();
int dupFd = posix.fcntl(oldFd, Fcntl.F_DUPFD, newFd);
new FileOutputStream(JavaLibCHelper.toFileDescriptor(newFd)).write(outContent);
byte[] inContent = new byte[outContent.length];
new FileInputStream(JavaLibCHelper.toFileDescriptor(dupFd)).read(inContent, 0, 3);
assertTrue(dupFd > newFd);
assertArrayEquals(inContent, outContent);
}
|
#vulnerable code
@Test
public void fcntlDupfdWithArgTest() throws Throwable {
File tmp = File.createTempFile("dupTest", "tmp");
RandomAccessFile raf = new RandomAccessFile(tmp, "rw");
int oldFd = JavaLibCHelper.getfdFromDescriptor(JavaLibCHelper.getDescriptorFromChannel(new RandomAccessFile(tmp, "rw").getChannel()));
int newFd = JavaLibCHelper.getfdFromDescriptor(JavaLibCHelper.getDescriptorFromChannel(raf.getChannel()));
byte[] outContent = "foo".getBytes();
FileDescriptor newFileDescriptor = JavaLibCHelper.toFileDescriptor(posix.fcntl(oldFd, Fcntl.F_DUPFD, newFd));
new FileOutputStream(JavaLibCHelper.toFileDescriptor(newFd)).write(outContent);
raf.seek(0);
byte[] inContent = new byte[outContent.length];
new FileInputStream(newFileDescriptor).read(inContent, 0, 3);
assertArrayEquals(inContent, outContent);
}
#location 13
#vulnerability type RESOURCE_LEAK
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
@Test
public void getgroups() throws Throwable {
if (jnr.ffi.Platform.getNativePlatform().isUnix()) {
String[] groupIdsAsStrings = exec("id -G").split(" ");
long[] expectedGroupIds = new long[groupIdsAsStrings.length];
for (int i = 0; i < groupIdsAsStrings.length; i++) {
expectedGroupIds[i] = Long.parseLong(groupIdsAsStrings[i]);
}
long[] actualGroupIds = posix.getgroups();
// getgroups does not specify whether the effective group ID is included along with the supplementary
// group IDs. However, `id -G` always includes all group IDs. So, we must do something of a fuzzy match.
// If the actual list is shorter than the expected list by 1, alter the expected list by removing the
// effective group ID before comparing the two arrays.
if (actualGroupIds.length == expectedGroupIds.length - 1) {
long effectiveGroupId = Long.parseLong(exec("id -g"));
expectedGroupIds = removeElement(expectedGroupIds, effectiveGroupId);
}
Arrays.sort(expectedGroupIds);
Arrays.sort(actualGroupIds);
assertArrayEquals(expectedGroupIds, actualGroupIds);
}
}
|
#vulnerable code
@Test
public void getgroups() throws Throwable {
if (jnr.ffi.Platform.getNativePlatform().isUnix()) {
InputStreamReader isr = null;
BufferedReader reader = null;
try {
isr = new InputStreamReader(Runtime.getRuntime().exec("id -G").getInputStream());
reader = new BufferedReader(isr);
String[] groupIdsAsStrings = reader.readLine().split(" ");
long[] expectedGroupIds = new long[groupIdsAsStrings.length];
for (int i = 0; i < groupIdsAsStrings.length; i++) {
expectedGroupIds[i] = Long.parseLong(groupIdsAsStrings[i]);
}
long[] actualGroupIds = posix.getgroups();
Arrays.sort(expectedGroupIds);
Arrays.sort(actualGroupIds);
assertArrayEquals(expectedGroupIds, actualGroupIds);
} finally {
if (reader != null) {
reader.close();
}
if (isr != null) {
isr.close();
}
}
}
}
#location 8
#vulnerability type RESOURCE_LEAK
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
public int fpathconf(int fd, Pathconf name) {
return posix().fpathconf(fd, name);
}
|
#vulnerable code
public int fpathconf(int fd, Pathconf name) {
return libc().fpathconf(fd, name);
}
#location 2
#vulnerability type NULL_DEREFERENCE
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
@Test
public void fcntlDupfdTest() throws Throwable {
if (!Platform.IS_WINDOWS) {
File tmp = File.createTempFile("fcntlTest", "tmp");
int fd = posix.open(tmp.getPath(), OpenFlags.O_RDWR.intValue(), 0444);
byte[] outContent = "foo".getBytes();
int newFd = posix.fcntl(fd, Fcntl.F_DUPFD);
new FileOutputStream(JavaLibCHelper.toFileDescriptor(fd)).write(outContent);
posix.lseek(fd, SEEK_SET, 0);
byte[] inContent = new byte[outContent.length];
new FileInputStream(JavaLibCHelper.toFileDescriptor(newFd)).read(inContent, 0, 3);
assertArrayEquals(inContent, outContent);
}
}
|
#vulnerable code
@Test
public void fcntlDupfdTest() throws Throwable {
if (!Platform.IS_WINDOWS) {
File tmp = File.createTempFile("fcntlTest", "tmp");
RandomAccessFile raf = new RandomAccessFile(tmp, "rw");
int fd = JavaLibCHelper.getfdFromDescriptor(JavaLibCHelper.getDescriptorFromChannel(raf.getChannel()));
byte[] outContent = "foo".getBytes();
int newFd = posix.fcntl(fd, Fcntl.F_DUPFD);
new FileOutputStream(JavaLibCHelper.toFileDescriptor(fd)).write(outContent);
raf.seek(0);
byte[] inContent = new byte[outContent.length];
new FileInputStream(JavaLibCHelper.toFileDescriptor(newFd)).read(inContent, 0, 3);
assertArrayEquals(inContent, outContent);
}
}
#location 19
#vulnerability type RESOURCE_LEAK
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
public int confstr(Confstr name, ByteBuffer buf, int len) {
return posix().confstr(name, buf, len);
}
|
#vulnerable code
public int confstr(Confstr name, ByteBuffer buf, int len) {
return libc().confstr(name, buf, len);
}
#location 2
#vulnerability type NULL_DEREFERENCE
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
@Test
public void fcntlDupfdTest() throws Throwable {
if (!Platform.IS_WINDOWS) {
File tmp = File.createTempFile("fcntlTest", "tmp");
int fd = posix.open(tmp.getPath(), OpenFlags.O_RDWR.intValue(), 0444);
byte[] outContent = "foo".getBytes();
int newFd = posix.fcntl(fd, Fcntl.F_DUPFD);
new FileOutputStream(JavaLibCHelper.toFileDescriptor(fd)).write(outContent);
posix.lseek(fd, SEEK_SET, 0);
byte[] inContent = new byte[outContent.length];
new FileInputStream(JavaLibCHelper.toFileDescriptor(newFd)).read(inContent, 0, 3);
assertArrayEquals(inContent, outContent);
}
}
|
#vulnerable code
@Test
public void fcntlDupfdTest() throws Throwable {
if (!Platform.IS_WINDOWS) {
File tmp = File.createTempFile("fcntlTest", "tmp");
RandomAccessFile raf = new RandomAccessFile(tmp, "rw");
int fd = JavaLibCHelper.getfdFromDescriptor(JavaLibCHelper.getDescriptorFromChannel(raf.getChannel()));
byte[] outContent = "foo".getBytes();
int newFd = posix.fcntl(fd, Fcntl.F_DUPFD);
new FileOutputStream(JavaLibCHelper.toFileDescriptor(fd)).write(outContent);
raf.seek(0);
byte[] inContent = new byte[outContent.length];
new FileInputStream(JavaLibCHelper.toFileDescriptor(newFd)).read(inContent, 0, 3);
assertArrayEquals(inContent, outContent);
}
}
#location 13
#vulnerability type RESOURCE_LEAK
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
public FileStat allocateStat() {
if (freebsdVersion >= 12) {
return new FreeBSDFileStat12(this);
} else {
return new FreeBSDFileStat(this);
}
}
|
#vulnerable code
public FileStat allocateStat() {
if (System.getProperty("os.version").compareTo("12.0") > 0) {
return new FreeBSDFileStat12(this);
} else {
return new FreeBSDFileStat(this);
}
}
#location 2
#vulnerability type NULL_DEREFERENCE
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
@Test
public void fcntlDupfdWithArgTest() throws Throwable {
File tmp = File.createTempFile("dupTest", "tmp");
int oldFd = JavaLibCHelper.getfdFromDescriptor(JavaLibCHelper.getDescriptorFromChannel(
new RandomAccessFile(tmp, "rw").getChannel()));
int newFd = JavaLibCHelper.getfdFromDescriptor(JavaLibCHelper.getDescriptorFromChannel(
new RandomAccessFile(tmp, "rw").getChannel()));
byte[] outContent = "foo".getBytes();
int dupFd = posix.fcntl(oldFd, Fcntl.F_DUPFD, newFd);
new FileOutputStream(JavaLibCHelper.toFileDescriptor(newFd)).write(outContent);
byte[] inContent = new byte[outContent.length];
new FileInputStream(JavaLibCHelper.toFileDescriptor(dupFd)).read(inContent, 0, 3);
assertTrue(dupFd > newFd);
assertArrayEquals(inContent, outContent);
}
|
#vulnerable code
@Test
public void fcntlDupfdWithArgTest() throws Throwable {
File tmp = File.createTempFile("dupTest", "tmp");
RandomAccessFile raf = new RandomAccessFile(tmp, "rw");
int oldFd = JavaLibCHelper.getfdFromDescriptor(JavaLibCHelper.getDescriptorFromChannel(new RandomAccessFile(tmp, "rw").getChannel()));
int newFd = JavaLibCHelper.getfdFromDescriptor(JavaLibCHelper.getDescriptorFromChannel(raf.getChannel()));
byte[] outContent = "foo".getBytes();
FileDescriptor newFileDescriptor = JavaLibCHelper.toFileDescriptor(posix.fcntl(oldFd, Fcntl.F_DUPFD, newFd));
new FileOutputStream(JavaLibCHelper.toFileDescriptor(newFd)).write(outContent);
raf.seek(0);
byte[] inContent = new byte[outContent.length];
new FileInputStream(newFileDescriptor).read(inContent, 0, 3);
assertArrayEquals(inContent, outContent);
}
#location 19
#vulnerability type RESOURCE_LEAK
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
public void stopRecording() throws IOException {
Integer processId = androidScreenRecordProcess.get(Thread.currentThread().getId());
if (processId != -1) {
String process =
"pgrep -P " + processId;
System.out.println(process);
Process p2 = Runtime.getRuntime().exec(process);
BufferedReader r = new BufferedReader(new InputStreamReader(p2.getInputStream()));
String command =
"kill -s SIGINT " + processId;
System.out.println("Stopping Video Recording");
System.out.println("******************" + command);
Process killProcess = Runtime.getRuntime().exec(command);
try {
killProcess.waitFor();
Thread.sleep(5000);
System.out.println("Killed video recording with exit code :"+ killProcess.exitValue());
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
|
#vulnerable code
public void stopRecording() throws IOException {
if (androidScreenRecordProcess.get(Thread.currentThread().getId()) != -1) {
String process =
"pgrep -P " + androidScreenRecordProcess.get(Thread.currentThread().getId());
System.out.println(process);
Process p2 = Runtime.getRuntime().exec(process);
BufferedReader r = new BufferedReader(new InputStreamReader(p2.getInputStream()));
String command =
"kill -s SIGINT " + androidScreenRecordProcess.get(Thread.currentThread().getId());
System.out.println("Stopping Video Recording");
System.out.println("******************" + command);
Runtime.getRuntime().exec(command);
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
#location 12
#vulnerability type RESOURCE_LEAK
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
public void triggerTest(String pack, List<String> tests) throws Exception {
parallelExecution(pack, tests);
}
|
#vulnerable code
public void triggerTest(String pack, List<String> tests) throws Exception {
String operSys = System.getProperty("os.name").toLowerCase();
File f = new File(System.getProperty("user.dir") + "/target/appiumlogs/");
if (!f.exists()) {
System.out.println("creating directory: " + "Logs");
boolean result = false;
try {
f.mkdir();
result = true;
} catch (SecurityException se) {
se.printStackTrace();
}
}
input = new FileInputStream("config.properties");
prop.load(input);
if (deviceConf.getDevices() != null) {
devices = deviceConf.getDevices();
deviceCount = devices.size() / 3;
File adb_logs = new File(System.getProperty("user.dir") + "/target/adblogs/");
if (!adb_logs.exists()) {
System.out.println("creating directory: " + "ADBLogs");
boolean result = false;
try {
adb_logs.mkdir();
result = true;
} catch (SecurityException se) {
se.printStackTrace();
}
}
createSnapshotFolderAndroid(deviceCount, "android");
}
if (operSys.contains("mac")) {
if (iosDevice.getIOSUDID() != null) {
iosDevice.checkExecutePermissionForIOSDebugProxyLauncher();
iOSdevices = iosDevice.getIOSUDIDHash();
deviceCount += iOSdevices.size();
createSnapshotFolderiOS(deviceCount, "iPhone");
}
}
if (deviceCount == 0) {
System.exit(0);
}
System.out.println("Total Number of devices detected::" + deviceCount);
System.out.println("starting running tests in threads");
testcases = new ArrayList<Class>();
if (prop.getProperty("FRAMEWORK").equalsIgnoreCase("testng")) {
// final String pack = "com.paralle.tests"; // Or any other package
PackageUtil.getClasses(pack).stream().forEach(s -> {
if (s.toString().contains("Test")) {
System.out.println("forEach: " + testcases.add((Class) s));
}
});
if (prop.getProperty("RUNNER").equalsIgnoreCase("distribute")) {
myTestExecutor.runMethodParallelAppium(tests, pack, deviceCount, "distribute");
}
if (prop.getProperty("RUNNER").equalsIgnoreCase("parallel")) {
myTestExecutor.runMethodParallelAppium(tests, pack, deviceCount, "parallel");
}
}
if (prop.getProperty("FRAMEWORK").equalsIgnoreCase("cucumber")) {
//addPluginToCucumberRunner();
if (prop.getProperty("RUNNER").equalsIgnoreCase("distribute")) {
myTestExecutor.distributeTests(deviceCount);
} else if (prop.getProperty("RUNNER").equalsIgnoreCase("parallel")) {
//addPluginToCucumberRunner();
myTestExecutor.parallelTests(deviceCount);
}
}
}
#location 3
#vulnerability type NULL_DEREFERENCE
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
@Override
public void startAppiumServer(String host) throws Exception {
System.out.println(
"**************************************************************************\n");
System.out.println("Starting Appium Server on host " + host);
System.out.println(
"**************************************************************************\n");
String serverPath = CapabilityManager.getInstance().getAppiumServerPath(host);
String serverPort = CapabilityManager.getInstance().getAppiumServerPort(host);
if (serverPath == null
&& serverPort == null) {
System.out.println("Picking Default Path for AppiumServiceBuilder");
new Api().getResponse("http://" + host + ":"
+ getRemoteAppiumManagerPort(host)
+ "/appium/start").body().string();
} else if (serverPath != null && serverPort != null) {
System.out.println("Picking UserSpecified Path & Port for AppiumServiceBuilder");
new Api().getResponse("http://" + host + ":"
+ getRemoteAppiumManagerPort(host)
+ "/appium/start?URL=" + serverPath
+ "&PORT=" + serverPort).body().string();
} else if (serverPath != null) {
System.out.println("Picking UserSpecified Path "
+ "& Using default Port for AppiumServiceBuilder");
new Api().getResponse("http://" + host + ":"
+ getRemoteAppiumManagerPort(host)
+ "/appium/start?URL=" + serverPath).body().string();
} else if (serverPort != null) {
System.out.println("Picking Default Path & User Port for AppiumServiceBuilder");
new Api().getResponse("http://" + host + ":"
+ getRemoteAppiumManagerPort(host)
+ "/appium/start?PORT=" + serverPort).body().string();
}
boolean status = Boolean.getBoolean(new JSONObject(new Api()
.getResponse("http://" + host + ":"
+ getRemoteAppiumManagerPort(host)
+ "/appium/isRunning").body().string()).get("status").toString());
if (status) {
System.out.println(
"***************************************************************\n");
System.out.println("Appium Server started successfully on " + host);
System.out.println(
"****************************************************************\n");
}
}
|
#vulnerable code
@Override
public void startAppiumServer(String host) throws Exception {
System.out.println(
"**************************************************************************\n");
System.out.println("Starting Appium Server on host " + host);
System.out.println(
"**************************************************************************\n");
String serverPath = CapabilityManager.getInstance().getAppiumServerPath(host);
String serverPort = CapabilityManager.getInstance().getAppiumServerPort(host);
if (serverPath == null
&& serverPort == null) {
System.out.println("Picking Default Path for AppiumServiceBuilder");
new Api().getResponse("http://" + host + ":4567"
+ "/appium/start").body().string();
} else if (serverPath != null && serverPort != null) {
System.out.println("Picking UserSpecified Path & Port for AppiumServiceBuilder");
new Api().getResponse("http://" + host + ":4567"
+ "/appium/start?URL=" + serverPath
+ "&PORT=" + serverPort).body().string();
} else if (serverPath != null) {
System.out.println("Picking UserSpecified Path "
+ "& Using default Port for AppiumServiceBuilder");
new Api().getResponse("http://" + host + ":4567"
+ "/appium/start?URL=" + serverPath).body().string();
} else if (serverPort != null) {
System.out.println("Picking Default Path & User Port for AppiumServiceBuilder");
new Api().getResponse("http://" + host + ":4567"
+ "/appium/start?PORT=" + serverPort).body().string();
}
boolean status = Boolean.getBoolean(new JSONObject(new Api().getResponse("http://" + host + ":4567"
+ "/appium/isRunning").body().string()).get("status").toString());
if (status) {
System.out.println(
"***************************************************************\n");
System.out.println("Appium Server started successfully on " + host);
System.out.println(
"****************************************************************\n");
}
}
#location 24
#vulnerability type NULL_DEREFERENCE
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
public DesiredCapabilities buildDesiredCapability(String platform,
String jsonPath) throws Exception {
final boolean[] flag = {false};
System.out.println("DeviceMappy-----" + DeviceAllocationManager.getInstance().deviceMapping);
Object port = ((HashMap) DeviceAllocationManager.getInstance().deviceMapping.get(DeviceManager
.getDeviceUDID())).get("port");
DesiredCapabilities desiredCapabilities = new DesiredCapabilities();
JSONArray jsonParsedObject = new JsonParser(jsonPath).getJsonParsedObject();
Object getPlatformObject = jsonParsedObject.stream().filter(o -> ((JSONObject) o)
.get(platform) != null)
.findFirst();
Object platFormCapabilities = ((JSONObject) ((Optional) getPlatformObject)
.get()).get(platform);
((JSONObject) platFormCapabilities)
.forEach((caps, values) -> {
if ("browserName".equals(caps) && "chrome".equals(values.toString())) {
flag[0] = true;
try {
desiredCapabilities.setCapability("chromeDriverPort",
availablePorts.getPort());
} catch (Exception e) {
e.printStackTrace();
}
}
if ("app".equals(caps)) {
if (values instanceof JSONObject) {
if (DeviceManager.getDeviceUDID().length()
== IOSDeviceConfiguration.SIM_UDID_LENGTH) {
values = ((JSONObject) values).get("simulator");
} else if (DeviceManager.getDeviceUDID().length()
== IOSDeviceConfiguration.IOS_UDID_LENGTH) {
values = ((JSONObject) values).get("device");
}
}
Path path = FileSystems.getDefault().getPath(values.toString());
if (!path.getParent().isAbsolute()) {
desiredCapabilities.setCapability(caps.toString(), path.normalize()
.toAbsolutePath().toString());
} else {
desiredCapabilities.setCapability(caps.toString(), path
.toString());
}
} else {
desiredCapabilities.setCapability(caps.toString(), values.toString());
}
});
if (DeviceManager.getMobilePlatform().equals(MobilePlatform.ANDROID) && !flag[0]) {
if (desiredCapabilities.getCapability("automationName") == null
|| desiredCapabilities.getCapability("automationName")
.toString() != "UIAutomator2") {
desiredCapabilities.setCapability(MobileCapabilityType.AUTOMATION_NAME,
AutomationName.ANDROID_UIAUTOMATOR2);
desiredCapabilities.setCapability(AndroidMobileCapabilityType.SYSTEM_PORT,
Integer.parseInt(port.toString()));
}
appPackage(desiredCapabilities);
} else if (DeviceManager.getMobilePlatform().equals(MobilePlatform.IOS)) {
String version = iosDevice.getIOSDeviceProductVersion();
appPackageBundle(desiredCapabilities);
//Check if simulator.json exists and add the deviceName and OS
if (DeviceManager.getDeviceUDID().length() == IOSDeviceConfiguration.SIM_UDID_LENGTH) {
desiredCapabilities.setCapability(MobileCapabilityType.DEVICE_NAME,
simulatorManager.getSimulatorDetailsFromUDID(
DeviceManager.getDeviceUDID()).getName());
desiredCapabilities.setCapability(MobileCapabilityType.PLATFORM_VERSION,
simulatorManager.getSimulatorDetailsFromUDID(DeviceManager.getDeviceUDID())
.getOsVersion());
} else {
desiredCapabilities.setCapability("webkitDebugProxyPort",
new IOSDeviceConfiguration().startIOSWebKit());
}
if (Float.valueOf(version.substring(0, version.length() - 2)) >= 10.0) {
desiredCapabilities.setCapability(MobileCapabilityType.AUTOMATION_NAME,
AutomationName.IOS_XCUI_TEST);
desiredCapabilities.setCapability(IOSMobileCapabilityType
.WDA_LOCAL_PORT, Integer.parseInt(port.toString()));
}
desiredCapabilities.setCapability(MobileCapabilityType.UDID,
DeviceManager.getDeviceUDID());
}
desiredCapabilities.setCapability(MobileCapabilityType.UDID,
DeviceManager.getDeviceUDID());
desiredCapabilitiesThreadLocal.set(desiredCapabilities);
return desiredCapabilities;
}
|
#vulnerable code
public DesiredCapabilities buildDesiredCapability(String platform,
String jsonPath) throws Exception {
final boolean[] flag = {false};
DesiredCapabilities desiredCapabilities = new DesiredCapabilities();
JSONArray jsonParsedObject = new JsonParser(jsonPath).getJsonParsedObject();
Object getPlatformObject = jsonParsedObject.stream().filter(o -> ((JSONObject) o)
.get(platform) != null)
.findFirst();
Object platFormCapabilities = ((JSONObject) ((Optional) getPlatformObject)
.get()).get(platform);
((JSONObject) platFormCapabilities)
.forEach((caps, values) -> {
if ("browserName".equals(caps) && "chrome".equals(values.toString())) {
flag[0] = true;
try {
desiredCapabilities.setCapability("chromeDriverPort",
availablePorts.getPort());
} catch (Exception e) {
e.printStackTrace();
}
}
if ("app".equals(caps)) {
if (values instanceof JSONObject) {
if (DeviceManager.getDeviceUDID().length()
== IOSDeviceConfiguration.SIM_UDID_LENGTH) {
values = ((JSONObject) values).get("simulator");
} else if (DeviceManager.getDeviceUDID().length()
== IOSDeviceConfiguration.IOS_UDID_LENGTH) {
values = ((JSONObject) values).get("device");
}
}
Path path = FileSystems.getDefault().getPath(values.toString());
if (!path.getParent().isAbsolute()) {
desiredCapabilities.setCapability(caps.toString(), path.normalize()
.toAbsolutePath().toString());
} else {
desiredCapabilities.setCapability(caps.toString(), path
.toString());
}
} else {
desiredCapabilities.setCapability(caps.toString(), values.toString());
}
});
if (DeviceManager.getMobilePlatform().equals(MobilePlatform.ANDROID) && !flag[0]) {
if (desiredCapabilities.getCapability("automationName") == null
|| desiredCapabilities.getCapability("automationName")
.toString() != "UIAutomator2") {
desiredCapabilities.setCapability(MobileCapabilityType.AUTOMATION_NAME,
AutomationName.ANDROID_UIAUTOMATOR2);
desiredCapabilities.setCapability(AndroidMobileCapabilityType.SYSTEM_PORT,
availablePorts.getPort());
}
appPackage(desiredCapabilities);
} else if (DeviceManager.getMobilePlatform().equals(MobilePlatform.IOS)) {
String version = iosDevice.getIOSDeviceProductVersion();
appPackageBundle(desiredCapabilities);
//Check if simulator.json exists and add the deviceName and OS
if (DeviceManager.getDeviceUDID().length() == IOSDeviceConfiguration.SIM_UDID_LENGTH) {
desiredCapabilities.setCapability(MobileCapabilityType.DEVICE_NAME,
simulatorManager.getSimulatorDetailsFromUDID(
DeviceManager.getDeviceUDID()).getName());
desiredCapabilities.setCapability(MobileCapabilityType.PLATFORM_VERSION,
simulatorManager.getSimulatorDetailsFromUDID(DeviceManager.getDeviceUDID())
.getOsVersion());
} else {
desiredCapabilities.setCapability("webkitDebugProxyPort",
new IOSDeviceConfiguration().startIOSWebKit());
}
if (Float.valueOf(version.substring(0, version.length() - 2)) >= 10.0) {
desiredCapabilities.setCapability(MobileCapabilityType.AUTOMATION_NAME,
AutomationName.IOS_XCUI_TEST);
desiredCapabilities.setCapability(IOSMobileCapabilityType
.WDA_LOCAL_PORT, availablePorts.getPort());
}
desiredCapabilities.setCapability(MobileCapabilityType.UDID,
DeviceManager.getDeviceUDID());
}
desiredCapabilities.setCapability(MobileCapabilityType.UDID,
DeviceManager.getDeviceUDID());
desiredCapabilitiesThreadLocal.set(desiredCapabilities);
return desiredCapabilities;
}
#location 12
#vulnerability type NULL_DEREFERENCE
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
@SuppressWarnings({ "rawtypes" })
public void runner(String pack) throws Exception {
File f = new File(System.getProperty("user.dir") + "/target/appiumlogs/");
if (!f.exists()) {
System.out.println("creating directory: " + "Logs");
boolean result = false;
try {
f.mkdir();
result = true;
} catch (SecurityException se) {
// handle it
}
if (result) {
System.out.println("DIR created");
}
}
File adb_logs = new File(System.getProperty("user.dir") + "/target/adblogs/");
if (!adb_logs.exists()) {
System.out.println("creating directory: " + "ADBLogs");
boolean result = false;
try {
adb_logs.mkdir();
result = true;
} catch (SecurityException se) {
// handle it
}
if (result) {
System.out.println("DIR created");
}
}
input = new FileInputStream("config.properties");
prop.load(input);
if(deviceConf.getDevices() != null){
devices = deviceConf.getDevices();
deviceCount = devices.size() / 3;
}
if(iosDevice.getIOSUDID() != null){
deviceCount += iosDevice.getIOSUDID().size();
}
createSnapshotFolder(deviceCount);
System.out.println("Total Number of devices detected::" + deviceCount);
System.out.println("starting running tests in threads");
testcases = new ArrayList<Class>();
// final String pack = "com.paralle.tests"; // Or any other package
PackageUtil.getClasses(pack).stream().forEach(s -> {
if (s.toString().contains("Test")) {
System.out.println("forEach: " + testcases.add((Class) s));
}
});
//TODO: Add another check for OS on distribution and parallel
if (prop.getProperty("RUNNER").equalsIgnoreCase("distribute")) {
//myTestExecutor.distributeTests(deviceCount, testcases);
myTestExecutor.runMethodParallelAppium(pack, deviceCount,"distribute");
}//TODO: Add another check for OS on distribution and parallel
else if (prop.getProperty("RUNNER").equalsIgnoreCase("parallel")) {
myTestExecutor.runMethodParallelAppium(pack, deviceCount,"parallel");
}
}
|
#vulnerable code
@SuppressWarnings({ "rawtypes" })
public void runner(String pack) throws Exception {
File f = new File(System.getProperty("user.dir") + "/target/appiumlogs/");
if (!f.exists()) {
System.out.println("creating directory: " + "Logs");
boolean result = false;
try {
f.mkdir();
result = true;
} catch (SecurityException se) {
// handle it
}
if (result) {
System.out.println("DIR created");
}
}
File adb_logs = new File(System.getProperty("user.dir") + "/target/adblogs/");
if (!adb_logs.exists()) {
System.out.println("creating directory: " + "ADBLogs");
boolean result = false;
try {
adb_logs.mkdir();
result = true;
} catch (SecurityException se) {
// handle it
}
if (result) {
System.out.println("DIR created");
}
}
input = new FileInputStream("config.properties");
prop.load(input);
if(deviceConf.getDevices() != null){
devices = deviceConf.getDevices();
deviceCount = devices.size() / 3;
} else if (prop.getProperty("PLATFORM").equalsIgnoreCase("ios")) {
deviceCount=iosDevice.getIOSUDID().size();
}
if(iosDevice.getIOSUDID() != null){
deviceCount += iosDevice.getIOSUDID().size();
}
createSnapshotFolder(deviceCount);
System.out.println("Total Number of devices detected::" + deviceCount);
System.out.println("starting running tests in threads");
testcases = new ArrayList<Class>();
// final String pack = "com.paralle.tests"; // Or any other package
PackageUtil.getClasses(pack).stream().forEach(s -> {
if (s.toString().contains("Test")) {
System.out.println("forEach: " + testcases.add((Class) s));
}
});
//TODO: Add another check for OS on distribution and parallel
if (prop.getProperty("RUNNER").equalsIgnoreCase("distribute")) {
//myTestExecutor.distributeTests(deviceCount, testcases);
myTestExecutor.runMethodParallelAppium(pack, deviceCount,"distribute");
}//TODO: Add another check for OS on distribution and parallel
else if (prop.getProperty("RUNNER").equalsIgnoreCase("parallel")) {
myTestExecutor.runMethodParallelAppium(pack, deviceCount,"parallel");
}
}
#location 39
#vulnerability type NULL_DEREFERENCE
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
public void captureScreenShot(String screenShotName) throws IOException, InterruptedException {
File framePath = new File(System.getProperty("user.dir")+"/src/main/resources/");
File scrFile = ((TakesScreenshot) driver).getScreenshotAs(OutputType.FILE);
if(driver.toString().split(":")[0].trim().equals("AndroidDriver")){
String androidModel = androidDevice.deviceModel(device_udid);
try {
FileUtils.copyFile(scrFile, new File(System.getProperty("user.dir") + "/target/screenshot/android/" + device_udid.replaceAll("\\W", "_") + "/"
+ androidModel + "/" + screenShotName + ".png"));
File [] files1 = framePath.listFiles();
for (int i = 0; i < files1.length; i++){
if (files1[i].isFile()){ //this line weeds out other directories/folders
System.out.println(files1[i]);
Path p = Paths.get(files1[i].toString());
String fileName=p.getFileName().toString().toLowerCase();
if(androidModel.toString().toLowerCase().contains(fileName.split(".png")[0].toLowerCase())){
try {
imageUtils.wrapDeviceFrames(files1[i].toString(),System.getProperty("user.dir") + "/target/screenshot/android/" + device_udid.replaceAll("\\W", "_") + "/"
+ androidModel + "/" + screenShotName + ".png",System.getProperty("user.dir") + "/target/screenshot/android/" + device_udid.replaceAll("\\W", "_") + "/"
+ androidModel + "/" + screenShotName + "_framed.png");
ExtentTestManager.logOutPut(System.getProperty("user.dir") + "/target/screenshot/android/" + device_udid.replaceAll("\\W", "_") + "/"
+ androidModel + "/" + screenShotName + "_framed.png",screenShotName.toUpperCase());
break;
} catch (InterruptedException e) {
e.printStackTrace();
} catch (IM4JavaException e) {
e.printStackTrace();
}
}
}
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}else if(driver.toString().split(":")[0].trim().equals("IOSDriver"))
{
String iosModel=iosDevice.getIOSDeviceProductTypeAndVersion(device_udid);
try {
FileUtils.copyFile(scrFile, new File(System.getProperty("user.dir") + "/target/screenshot/iPhone/" + device_udid.replaceAll("\\W", "_") + "/"
+ iosModel + "/" + screenShotName + ".png"));
File [] files1 = framePath.listFiles();
for (int i = 0; i < files1.length; i++){
if (files1[i].isFile()){ //this line weeds out other directories/folders
System.out.println(files1[i]);
Path p = Paths.get(files1[i].toString());
String fileName=p.getFileName().toString().toLowerCase();
if(iosModel.toString().toLowerCase().contains(fileName.split(".png")[0].toLowerCase())){
try {
imageUtils.wrapDeviceFrames(files1[i].toString(),System.getProperty("user.dir") + "/target/screenshot/iPhone/" + device_udid.replaceAll("\\W", "_") + "/"
+ iosModel + "/" + screenShotName + ".png",System.getProperty("user.dir") + "/target/screenshot/iPhone/" + device_udid.replaceAll("\\W", "_") + "/"
+ iosModel + "/" + screenShotName + "_framed.png");
ExtentTestManager.logOutPut(System.getProperty("user.dir") + "/target/screenshot/iPhone/" + device_udid.replaceAll("\\W", "_") + "/"
+ iosModel + "/" + screenShotName + "_framed.png",screenShotName.toUpperCase());
break;
} catch (InterruptedException e) {
e.printStackTrace();
} catch (IM4JavaException e) {
e.printStackTrace();
}
}
}
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
|
#vulnerable code
public void captureScreenShot(String screenShotName) throws IOException, InterruptedException {
File framePath = new File(System.getProperty("user.dir")+"/src/main/resources/");
File scrFile = ((TakesScreenshot) driver).getScreenshotAs(OutputType.FILE);
if(driver.toString().split(":")[0].trim().equals("AndroidDriver")){
String androidModel = androidDevice.deviceModel(device_udid);
try {
FileUtils.copyFile(scrFile, new File(System.getProperty("user.dir") + "/target/screenshot/android/" + device_udid.replaceAll("\\W", "_") + "/"
+ androidModel + "/" + screenShotName + ".png"));
File [] files1 = framePath.listFiles();
for (int i = 0; i < files1.length; i++){
if (files1[i].isFile()){ //this line weeds out other directories/folders
System.out.println(files1[i]);
Path p = Paths.get(files1[i].toString());
String fileName=p.getFileName().toString().toLowerCase();
if(androidModel.toString().toLowerCase().contains(fileName.split(".png")[0].toLowerCase())){
try {
imageUtils.wrapDeviceFrames(files1[i].toString(),System.getProperty("user.dir") + "/target/screenshot/android/" + device_udid.replaceAll("\\W", "_") + "/"
+ androidModel + "/" + screenShotName + ".png",System.getProperty("user.dir") + "/target/screenshot/android/" + device_udid.replaceAll("\\W", "_") + "/"
+ androidModel + "/" + screenShotName + "_framed.png");
ExtentTestManager.logOutPut(System.getProperty("user.dir") + "/target/screenshot/android/" + device_udid.replaceAll("\\W", "_") + "/"
+ androidModel + "/" + screenShotName + "_framed.png",screenShotName.toUpperCase());
break;
} catch (InterruptedException e) {
e.printStackTrace();
} catch (IM4JavaException e) {
e.printStackTrace();
}
}
}
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}else if(driver.toString().split(":")[0].trim().equals("IOSDriver"))
{
String iosModel=iosDevice.getDeviceName(device_udid);
try {
FileUtils.copyFile(scrFile, new File(System.getProperty("user.dir") + "/target/screenshot/iPhone/" + device_udid.replaceAll("\\W", "_") + "/"
+ iosModel + "/" + screenShotName + ".png"));
File [] files1 = framePath.listFiles();
for (int i = 0; i < files1.length; i++){
if (files1[i].isFile()){ //this line weeds out other directories/folders
System.out.println(files1[i]);
Path p = Paths.get(files1[i].toString());
String fileName=p.getFileName().toString().toLowerCase();
if(iosModel.toString().toLowerCase().contains(fileName.split(".png")[0].toLowerCase())){
try {
imageUtils.wrapDeviceFrames(files1[i].toString(),System.getProperty("user.dir") + "/target/screenshot/iPhone/" + device_udid.replaceAll("\\W", "_") + "/"
+ iosModel + "/" + screenShotName + ".png",System.getProperty("user.dir") + "/target/screenshot/iPhone/" + device_udid.replaceAll("\\W", "_") + "/"
+ iosModel + "/" + screenShotName + "_framed.png");
ExtentTestManager.logOutPut(System.getProperty("user.dir") + "/target/screenshot/iPhone/" + device_udid.replaceAll("\\W", "_") + "/"
+ iosModel + "/" + screenShotName + "_framed.png",screenShotName.toUpperCase());
break;
} catch (InterruptedException e) {
e.printStackTrace();
} catch (IM4JavaException e) {
e.printStackTrace();
}
}
}
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
#location 5
#vulnerability type THREAD_SAFETY_VIOLATION
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
@Override
public List<Device> getDevices(String machineIP, String platform) throws Exception {
ObjectMapper mapper = new ObjectMapper()
.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
List<Device> devices = new ArrayList<>();
if (platform.equalsIgnoreCase(OSType.ANDROID.name()) ||
platform.equalsIgnoreCase(OSType.BOTH.name())) {
List<Device> androidDevices = Arrays.asList(mapper.readValue(new URL(
"http://" + machineIP + ":4567/devices/android"),
Device[].class));
Optional.ofNullable(androidDevices).ifPresent(devices::addAll);
}
if (platform.equalsIgnoreCase(OSType.iOS.name()) ||
platform.equalsIgnoreCase(OSType.BOTH.name())) {
if (CapabilityManager.getInstance().isApp()) {
if (CapabilityManager.getInstance().isSimulatorAppPresentInCapsJson()) {
List<Device> bootedSims = Arrays.asList(mapper.readValue(new URL(
"http://" + machineIP + ":4567/devices/ios/bootedSims"),
Device[].class));
Optional.ofNullable(bootedSims).ifPresent(devices::addAll);
}
if (CapabilityManager.getInstance().isRealDeviceAppPresentInCapsJson()) {
List<Device> iOSRealDevices = Arrays.asList(mapper.readValue(new URL(
"http://" + machineIP + ":4567/devices/ios/realDevices"),
Device[].class));
Optional.ofNullable(iOSRealDevices).ifPresent(devices::addAll);
}
} else {
List<Device> iOSDevices = Arrays.asList(mapper.readValue(new URL(
"http://" + machineIP + ":4567/devices/ios/realDevices"),
Device[].class));
Optional.ofNullable(iOSDevices).ifPresent(devices::addAll);
}
}
return devices;
}
|
#vulnerable code
@Override
public List<Device> getDevices(String machineIP, String platform) throws Exception {
ObjectMapper mapper = new ObjectMapper()
.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
List<Device> devices = null;
if (platform.equalsIgnoreCase(OSType.ANDROID.name()) ||
platform.equalsIgnoreCase(OSType.BOTH.name())) {
devices.addAll(Arrays.asList(mapper.readValue(new URL(
"http://" + machineIP + ":4567/devices/android"),
Device[].class)));
}
if (platform.equalsIgnoreCase(OSType.iOS.name()) ||
platform.equalsIgnoreCase(OSType.BOTH.name())) {
if (CapabilityManager.getInstance().isApp()) {
if (CapabilityManager.getInstance().isSimulatorAppPresentInCapsJson()) {
devices.addAll(Arrays.asList(mapper.readValue(new URL(
"http://" + machineIP + ":4567/devices/ios/bootedSims"),
Device[].class)));
}
if (CapabilityManager.getInstance().isRealDeviceAppPresentInCapsJson()) {
devices.addAll(Arrays.asList(mapper.readValue(new URL(
"http://" + machineIP + ":4567/devices/ios/realDevices"),
Device[].class)));
}
} else {
devices.addAll(Arrays.asList(mapper.readValue(new URL(
"http://" + machineIP + ":4567/devices/ios"),
Device[].class)));
}
}
assert devices != null;
return devices;
}
#location 9
#vulnerability type NULL_DEREFERENCE
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
@SuppressWarnings("unused")
public void convertXmlToJSon() throws IOException{
String fileName = "report.json";
BufferedWriter bufferedWriter = null;
try {
int i = 1;
FileWriter fileWriter;
int dir_1 = new File(System.getProperty("user.dir") + "/test-output/junitreports").listFiles().length;
List textFiles = new ArrayList();
File dir = new File(System.getProperty("user.dir") + "/test-output/junitreports");
for (File file : dir.listFiles()) {
if (file.getName().contains(("Test"))) {
System.out.println(file);
fileWriter = new FileWriter(fileName, true);
InputStream inputStream = new FileInputStream(file);
StringBuilder builder = new StringBuilder();
int ptr = 0;
while ((ptr = inputStream.read()) != -1) {
builder.append((char) ptr);
}
String xml = builder.toString();
JSONObject jsonObj = XML.toJSONObject(xml);
// Always wrap FileWriter in BufferedWriter.
bufferedWriter = new BufferedWriter(fileWriter);
// Always close files.
String jsonPrettyPrintString = jsonObj.toString(4);
// bufferedWriter.write(jsonPrettyPrintString);
if (i == 1) {
bufferedWriter.append("[");
}
bufferedWriter.append(jsonPrettyPrintString);
if (i != dir_1) {
bufferedWriter.append(",");
}
if (i == dir_1) {
bufferedWriter.append("]");
}
bufferedWriter.newLine();
bufferedWriter.close();
i++;
}
}
} catch (IOException ex) {
System.out.println("Error writing to file '" + fileName + "'");
} catch (Exception e) {
e.printStackTrace();
}
}
|
#vulnerable code
@SuppressWarnings("unused")
public void convertXmlToJSon() throws IOException{
String fileName = "report.json";
BufferedWriter bufferedWriter = null;
try {
FileWriter fileWriter;
List textFiles = new ArrayList();
File dir = new File(System.getProperty("user.dir") + "/test-output/junitreports");
for (File file : dir.listFiles()) {
if (file.getName().contains(("Test"))) {
System.out.println(file);
fileWriter = new FileWriter(fileName,true);
InputStream inputStream = new FileInputStream(file);
StringBuilder builder = new StringBuilder();
int ptr = 0;
while ((ptr = inputStream.read()) != -1) {
builder.append((char) ptr);
}
String xml = builder.toString();
JSONObject jsonObj = XML.toJSONObject(xml);
// Always wrap FileWriter in BufferedWriter.
bufferedWriter = new BufferedWriter(fileWriter);
// Always close files.
String jsonPrettyPrintString = jsonObj.toString(4);
//bufferedWriter.write(jsonPrettyPrintString);
bufferedWriter.append(jsonPrettyPrintString);
bufferedWriter.newLine();
bufferedWriter.close();
}
}
} catch (IOException ex) {
System.out.println("Error writing to file '" + fileName + "'");
} catch (Exception e) {
e.printStackTrace();
}
}
#location 11
#vulnerability type NULL_DEREFERENCE
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
public XmlSuite constructXmlSuiteForDistribution(String pack, List<String> tests,
Map<String, List<Method>> methods, int deviceCount) {
ArrayList<String> listeners = new ArrayList<>();
try {
prop.load(new FileInputStream("config.properties"));
} catch (IOException e) {
e.printStackTrace();
}
if (prop.getProperty("LISTENERS") != null) {
Collections.addAll(listeners, prop.getProperty("LISTENERS").split("\\s*,\\s*"));
}
XmlSuite suite = new XmlSuite();
suite.setName("TestNG Forum");
suite.setThreadCount(deviceCount);
suite.setParallel(ParallelMode.CLASSES);
suite.setVerbose(2);
listeners.add("com.appium.manager.AppiumParallelTest");
listeners.add("com.appium.utils.RetryListener");
suite.setListeners(listeners);
if (prop.getProperty("LISTENERS") != null) {
suite.setListeners(listeners);
}
XmlTest test = new XmlTest(suite);
test.setName("TestNG Test");
List<XmlClass> xmlClasses = new ArrayList<>();
for (String className : methods.keySet()) {
if (className.contains("Test")) {
if (tests.size() == 0) {
xmlClasses.add(createClass(className, methods.get(className)));
} else {
for (String s : tests) {
for (int i = 0; i < items.size(); i++) {
String testName = items.get(i).concat("." + s).toString();
if (testName.equals(className)) {
xmlClasses.add(createClass(className, methods.get(className)));
}
}
}
}
}
}
test.setXmlClasses(xmlClasses);
return suite;
}
|
#vulnerable code
public XmlSuite constructXmlSuiteForDistribution(String pack, List<String> tests,
Map<String, List<Method>> methods, int deviceCount) {
ArrayList<String> items = new ArrayList<>();
try {
prop.load(new FileInputStream("config.properties"));
} catch (IOException e) {
e.printStackTrace();
}
if (prop.getProperty("LISTENERS") != null) {
Collections.addAll(items, prop.getProperty("LISTENERS").split("\\s*,\\s*"));
}
XmlSuite suite = new XmlSuite();
suite.setName("TestNG Forum");
suite.setThreadCount(deviceCount);
suite.setParallel(ParallelMode.CLASSES);
suite.setVerbose(2);
items.add("com.appium.manager.AppiumParallelTest");
items.add("com.appium.utils.RetryListener");
suite.setListeners(items);
if (prop.getProperty("LISTENERS") != null) {
suite.setListeners(items);
}
XmlTest test = new XmlTest(suite);
test.setName("TestNG Test");
List<XmlClass> xmlClasses = new ArrayList<>();
for (String className : methods.keySet()) {
if (className.contains("Test")) {
if (tests.size() == 0) {
xmlClasses.add(createClass(className, methods.get(className)));
} else {
for (String s : tests) {
if (pack.concat("." + s).equals(className)) {
xmlClasses.add(createClass(className, methods.get(className)));
}
}
}
}
}
test.setXmlClasses(xmlClasses);
return suite;
}
#location 5
#vulnerability type RESOURCE_LEAK
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
public XmlSuite constructXmlSuiteDistributeCucumber(
int deviceCount, ArrayList<String> deviceSerail) {
XmlSuite suite = new XmlSuite();
suite.setName("TestNG Forum");
suite.setThreadCount(deviceCount);
suite.setParallel(ParallelMode.CLASSES);
suite.setVerbose(2);
XmlTest test = new XmlTest(suite);
test.setName("TestNG Test");
test.addParameter("device", "");
test.setPackages(getPackages());
File file = new File(System.getProperty("user.dir") + "/target/parallelCucumber.xml");
FileWriter fw = null;
try {
fw = new FileWriter(file.getAbsoluteFile());
} catch (IOException e) {
e.printStackTrace();
}
BufferedWriter bw = new BufferedWriter(fw);
try {
bw.write(suite.toXml());
} catch (IOException e) {
e.printStackTrace();
}
try {
bw.close();
} catch (IOException e) {
e.printStackTrace();
}
return suite;
}
|
#vulnerable code
public XmlSuite constructXmlSuiteDistributeCucumber(
int deviceCount, ArrayList<String> deviceSerail) {
try {
prop.load(new FileInputStream("config.properties"));
} catch (IOException e) {
e.printStackTrace();
}
XmlSuite suite = new XmlSuite();
suite.setName("TestNG Forum");
suite.setThreadCount(deviceCount);
suite.setParallel(ParallelMode.CLASSES);
suite.setVerbose(2);
XmlTest test = new XmlTest(suite);
test.setName("TestNG Test");
test.addParameter("device", "");
test.setPackages(getPackages());
File file = new File(System.getProperty("user.dir") + "/target/parallelCucumber.xml");
FileWriter fw = null;
try {
fw = new FileWriter(file.getAbsoluteFile());
} catch (IOException e) {
e.printStackTrace();
}
BufferedWriter bw = new BufferedWriter(fw);
try {
bw.write(suite.toXml());
} catch (IOException e) {
e.printStackTrace();
}
try {
bw.close();
} catch (IOException e) {
e.printStackTrace();
}
return suite;
}
#location 4
#vulnerability type RESOURCE_LEAK
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
private boolean parallelExecution(String pack, List<String> tests) throws Exception {
String os = System.getProperty("os.name").toLowerCase();
String platform = System.getenv("Platform");
HostMachineDeviceManager hostMachineDeviceManager = HostMachineDeviceManager.getInstance();
int deviceCount = hostMachineDeviceManager.getDevicesByHost().getAllDevices().size();
if (deviceCount == 0) {
figlet("No Devices Connected");
System.exit(0);
}
System.out.println("***************************************************\n");
System.out.println("Total Number of devices detected::" + deviceCount + "\n");
System.out.println("***************************************************\n");
System.out.println("starting running tests in threads");
createAppiumLogsFolder();
if (deviceAllocationManager.getDevices() != null && platform
.equalsIgnoreCase(ANDROID)
|| platform.equalsIgnoreCase(BOTH)) {
generateDirectoryForAdbLogs();
createSnapshotFolderAndroid("android");
}
if (os.contains("mac") && platform.equalsIgnoreCase(IOS)
|| platform.equalsIgnoreCase(BOTH)) {
//iosDevice.checkExecutePermissionForIOSDebugProxyLauncher();
createSnapshotFolderiOS("iPhone");
}
List<Class> testcases = new ArrayList<>();
boolean hasFailures = false;
String runner = configFileManager.getProperty("RUNNER");
String framework = configFileManager.getProperty("FRAMEWORK");
if (framework.equalsIgnoreCase("testng")) {
// final String pack = "com.paralle.tests"; // Or any other package
PackageUtil.getClasses(pack).stream().forEach(s -> {
if (s.toString().contains("Test")) {
testcases.add((Class) s);
}
});
String executionType = runner.equalsIgnoreCase("distribute")
? "distribute" : "parallel";
hasFailures = myTestExecutor
.runMethodParallelAppium(tests, pack, deviceCount,
executionType);
}
if (framework.equalsIgnoreCase("cucumber")) {
//addPluginToCucumberRunner();
if (runner.equalsIgnoreCase("distribute")) {
myTestExecutor
.constructXmlSuiteDistributeCucumber(deviceCount);
hasFailures = myTestExecutor.runMethodParallel();
} else if (runner.equalsIgnoreCase("parallel")) {
//addPluginToCucumberRunner();
myTestExecutor
.constructXmlSuiteForParallelCucumber(deviceCount,
hostMachineDeviceManager.getDevicesByHost().getAllDevices());
hasFailures = myTestExecutor.runMethodParallel();
htmlReporter.generateReports();
}
}
return hasFailures;
}
|
#vulnerable code
private boolean parallelExecution(String pack, List<String> tests) throws Exception {
String os = System.getProperty("os.name").toLowerCase();
String platform = System.getProperty("Platform");
HostMachineDeviceManager hostMachineDeviceManager = HostMachineDeviceManager.getInstance();
int deviceCount = hostMachineDeviceManager.getDevicesByHost().getAllDevices().size();
if (deviceCount == 0) {
figlet("No Devices Connected");
System.exit(0);
}
System.out.println("***************************************************\n");
System.out.println("Total Number of devices detected::" + deviceCount + "\n");
System.out.println("***************************************************\n");
System.out.println("starting running tests in threads");
createAppiumLogsFolder();
if (deviceAllocationManager.getDevices() != null && platform
.equalsIgnoreCase(ANDROID)
|| platform.equalsIgnoreCase(BOTH)) {
generateDirectoryForAdbLogs();
createSnapshotFolderAndroid("android");
}
if (os.contains("mac") && platform.equalsIgnoreCase(IOS)
|| platform.equalsIgnoreCase(BOTH)) {
createSnapshotFolderiOS("iPhone");
}
List<Class> testcases = new ArrayList<>();
boolean hasFailures = false;
String runner = configFileManager.getProperty("RUNNER");
String framework = configFileManager.getProperty("FRAMEWORK");
if (framework.equalsIgnoreCase("testng")) {
// final String pack = "com.paralle.tests"; // Or any other package
PackageUtil.getClasses(pack).stream().forEach(s -> {
if (s.toString().contains("Test")) {
testcases.add((Class) s);
}
});
String executionType = runner.equalsIgnoreCase("distribute")
? "distribute" : "parallel";
hasFailures = myTestExecutor
.runMethodParallelAppium(tests, pack, deviceCount,
executionType);
}
if (framework.equalsIgnoreCase("cucumber")) {
//addPluginToCucumberRunner();
if (runner.equalsIgnoreCase("distribute")) {
myTestExecutor
.constructXmlSuiteDistributeCucumber(deviceCount);
hasFailures = myTestExecutor.runMethodParallel();
} else if (runner.equalsIgnoreCase("parallel")) {
//addPluginToCucumberRunner();
myTestExecutor
.constructXmlSuiteForParallelCucumber(deviceCount,
hostMachineDeviceManager.getDevicesByHost().getAllDevices());
hasFailures = myTestExecutor.runMethodParallel();
htmlReporter.generateReports();
}
}
return hasFailures;
}
#location 20
#vulnerability type NULL_DEREFERENCE
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
public XmlSuite constructXmlSuiteForParallelCucumber(
int deviceCount, ArrayList<String> deviceSerail) {
XmlSuite suite = new XmlSuite();
suite.setName("TestNG Forum");
suite.setThreadCount(deviceCount);
suite.setParallel(ParallelMode.TESTS);
suite.setVerbose(2);
for (int i = 0; i < deviceCount; i++) {
XmlTest test = new XmlTest(suite);
test.setName("TestNG Test" + i);
test.setPreserveOrder("false");
test.addParameter("device", deviceSerail.get(i));
test.setPackages(getPackages());
}
File file = new File(System.getProperty("user.dir") + "/target/parallelCucumber.xml");
FileWriter fw = null;
try {
fw = new FileWriter(file.getAbsoluteFile());
} catch (IOException e) {
e.printStackTrace();
}
BufferedWriter bw = new BufferedWriter(fw);
try {
bw.write(suite.toXml());
} catch (IOException e) {
e.printStackTrace();
}
try {
bw.close();
} catch (IOException e) {
e.printStackTrace();
}
return suite;
}
|
#vulnerable code
public XmlSuite constructXmlSuiteForParallelCucumber(
int deviceCount, ArrayList<String> deviceSerail) {
try {
prop.load(new FileInputStream("config.properties"));
} catch (IOException e) {
e.printStackTrace();
}
XmlSuite suite = new XmlSuite();
suite.setName("TestNG Forum");
suite.setThreadCount(deviceCount);
suite.setParallel(ParallelMode.TESTS);
suite.setVerbose(2);
for (int i = 0; i < deviceCount; i++) {
XmlTest test = new XmlTest(suite);
test.setName("TestNG Test" + i);
test.setPreserveOrder("false");
test.addParameter("device", deviceSerail.get(i));
test.setPackages(getPackages());
}
File file = new File(System.getProperty("user.dir") + "/target/parallelCucumber.xml");
FileWriter fw = null;
try {
fw = new FileWriter(file.getAbsoluteFile());
} catch (IOException e) {
e.printStackTrace();
}
BufferedWriter bw = new BufferedWriter(fw);
try {
bw.write(suite.toXml());
} catch (IOException e) {
e.printStackTrace();
}
try {
bw.close();
} catch (IOException e) {
e.printStackTrace();
}
return suite;
}
#location 4
#vulnerability type RESOURCE_LEAK
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
public ArrayList<String> getDeviceSerial() throws Exception {
startADB(); // start adb service
String output = cmd.runCommand("adb devices");
String[] lines = output.split("\n");
if (lines.length <= 1) {
System.out.println("No Android Device Connected");
return null;
} else {
for (int i = 1; i < lines.length; i++) {
lines[i] = lines[i].replaceAll("\\s+", "");
if (lines[i].contains("device")) {
lines[i] = lines[i].replaceAll("device", "");
String deviceID = lines[i];
if (validDeviceIds == null
|| (validDeviceIds != null && validDeviceIds.contains(deviceID))) {
if (validDeviceIds == null) {
System.out.println("validDeviceIds is null!!!");
}
System.out.println("Adding device: " + deviceID);
deviceSerial.add(deviceID);
}
} else if (lines[i].contains("unauthorized")) {
lines[i] = lines[i].replaceAll("unauthorized", "");
String deviceID = lines[i];
} else if (lines[i].contains("offline")) {
lines[i] = lines[i].replaceAll("offline", "");
String deviceID = lines[i];
}
}
return deviceSerial;
}
}
|
#vulnerable code
public ArrayList<String> getDeviceSerial() throws Exception {
startADB(); // start adb service
String output = cmd.runCommand("adb devices");
String[] lines = output.split("\n");
if (lines.length <= 1) {
System.out.println("No Device Connected");
return null;
} else {
for (int i = 1; i < lines.length; i++) {
lines[i] = lines[i].replaceAll("\\s+", "");
if (lines[i].contains("device")) {
lines[i] = lines[i].replaceAll("device", "");
String deviceID = lines[i];
deviceSerail.add(deviceID);
} else if (lines[i].contains("unauthorized")) {
lines[i] = lines[i].replaceAll("unauthorized", "");
String deviceID = lines[i];
} else if (lines[i].contains("offline")) {
lines[i] = lines[i].replaceAll("offline", "");
String deviceID = lines[i];
}
}
return deviceSerail;
}
}
#location 4
#vulnerability type RESOURCE_LEAK
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
public AppiumServiceBuilder getAppiumServiceBuilder(String methodName) throws Exception {
String webKitPort = iosDevice.startIOSWebKit(device_udid);
return appiumMan.appiumServerForIOS(device_udid, methodName, webKitPort);
}
|
#vulnerable code
public AppiumServiceBuilder getAppiumServiceBuilder(String methodName) throws Exception {
if (iosDevice.checkiOSDevice(device_udid)) {
String webKitPort = iosDevice.startIOSWebKit(device_udid);
return appiumMan.appiumServerForIOS(device_udid, methodName, webKitPort);
} else if (!iosDevice.checkiOSDevice(device_udid)) {
return appiumMan.appiumServerForAndroid(device_udid, methodName);
}
return null;
}
#location 5
#vulnerability type RESOURCE_LEAK
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
public synchronized static ExtentReports getExtent() {
if (extent == null) {
try {
configFileManager = ConfigFileManager.getInstance();
extent = new ExtentReports();
extent.attachReporter(getHtmlReporter());
if (System.getenv("ExtentX") != null && System.getenv("ExtentX")
.equalsIgnoreCase("true")) {
extent.attachReporter(klovReporter());
}
extent.setSystemInfo("Selenium Java Version", "3.3.1");
String appiumVersion = null;
try {
String command = "node "
+ configFileManager.getProperty("APPIUM_JS_PATH") + " -v";
appiumVersion = commandPrompt.runCommand(command);
} catch (InterruptedException e) {
e.printStackTrace();
}
extent.setSystemInfo("AppiumClient", "5.0.0-BETA6");
extent.setSystemInfo("AppiumServer", appiumVersion.replace("\n", ""));
extent.setSystemInfo("Runner", configFileManager.getProperty("RUNNER"));
extent.setSystemInfo("AppiumServerLogs","<a target=\"_parent\" href=" + "/appiumlogs/appiumlogs/"
+ ".txt" + ">AppiumServerLogs</a>");
return extent;
} catch (IOException e) {
e.printStackTrace();
}
}
return extent;
}
|
#vulnerable code
public synchronized static ExtentReports getExtent() {
if (extent == null) {
try {
configFileManager = ConfigFileManager.getInstance();
extent = new ExtentReports();
extent.attachReporter(getHtmlReporter());
if (System.getProperty("ExtentX") != null && System.getProperty("ExtentX")
.equalsIgnoreCase("true")) {
extent.attachReporter(klovReporter());
}
extent.setSystemInfo("Selenium Java Version", "3.3.1");
String appiumVersion = null;
try {
String command = "node "
+ configFileManager.getProperty("APPIUM_JS_PATH") + " -v";
appiumVersion = commandPrompt.runCommand(command);
} catch (InterruptedException e) {
e.printStackTrace();
}
extent.setSystemInfo("AppiumClient", "5.0.0-BETA6");
extent.setSystemInfo("AppiumServer", appiumVersion.replace("\n", ""));
extent.setSystemInfo("Runner", configFileManager.getProperty("RUNNER"));
extent.setSystemInfo("AppiumServerLogs","<a target=\"_parent\" href=" + "/appiumlogs/appiumlogs/"
+ ".txt" + ">AppiumServerLogs</a>");
return extent;
} catch (IOException e) {
e.printStackTrace();
}
}
return extent;
}
#location 8
#vulnerability type NULL_DEREFERENCE
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
public String getIOSDeviceProductTypeAndVersion(String udid) throws InterruptedException, IOException {
return commandPrompt.runCommandThruProcessBuilder("ideviceinfo --udid "+udid+" | grep ProductType");
}
|
#vulnerable code
public String getIOSDeviceProductTypeAndVersion(String udid) throws InterruptedException, IOException {
System.out.println("ideviceinfo --udid " + udid + " | grep ProductType");
System.out.println("ideviceinfo --udid " + udid + " | grep ProductVersion");
String productType = commandPrompt.runCommand("ideviceinfo --udid " + udid);
System.out.println(productType);
String version = commandPrompt.runCommand("ideviceinfo --udid " + udid);
System.out.println(version);
System.out.println(productType.concat(version));
return productType.concat(version);
}
#location 6
#vulnerability type RESOURCE_LEAK
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
public void stopRecording() throws IOException {
Integer processId = androidScreenRecordProcess.get(Thread.currentThread().getId());
stopRunningProcess(processId);
}
|
#vulnerable code
public void stopRecording() throws IOException {
Integer processId = androidScreenRecordProcess.get(Thread.currentThread().getId());
if (processId != -1) {
String process = "pgrep -P " + processId;
System.out.println(process);
Process p2 = Runtime.getRuntime().exec(process);
BufferedReader r = new BufferedReader(new InputStreamReader(p2.getInputStream()));
String command = "kill " + processId;
System.out.println("Stopping Video Recording");
System.out.println("******************" + command);
try {
runCommandThruProcess(command);
Thread.sleep(10000);
System.out.println("Killed video recording with exit code :" + command);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
#location 7
#vulnerability type RESOURCE_LEAK
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
public synchronized AppiumServiceBuilder startAppiumServer(String methodName) throws Exception {
device_udid = getNextAvailableDeviceId();
if (device_udid == null) {
System.out.println("No devices are free to run test or Failed to run test");
return null;
}
if (System.getProperty("os.name").toLowerCase().contains("mac")) {
if (iosDevice.checkiOSDevice(device_udid)) {
iosDevice.setIOSWebKitProxyPorts(device_udid);
category = iosDevice.getDeviceName(device_udid).replace(" ", "_");
} else if (!iosDevice.checkiOSDevice(device_udid)) {
category = androidDevice.getDeviceModel(device_udid);
System.out.println(category);
}
} else {
category = androidDevice.getDeviceModel(device_udid);
}
if (prop.getProperty("FRAMEWORK").equalsIgnoreCase("testng")) {
if (getClass().getAnnotation(Description.class) != null) {
testDescription = getClass().getAnnotation(Description.class).value();
}
parent = ExtentTestManager.startTest(methodName, testDescription,
category + "_" + device_udid.replaceAll("\\W", "_"));
parentContext.put(Thread.currentThread().getId(), parent);
ExtentTestManager.getTest().log(LogStatus.INFO, "AppiumServerLogs",
"<a href=" + System.getProperty("user.dir") + "/target/appiumlogs/" + device_udid
.replaceAll("\\W", "_") + "__" + methodName + ".txt" + ">Logs</a>");
}
if (System.getProperty("os.name").toLowerCase().contains("mac")) {
if (iosDevice.checkiOSDevice(device_udid)) {
String webKitPort = iosDevice.startIOSWebKit(device_udid);
return appiumMan.appiumServerForIOS(device_udid, methodName, webKitPort);
} else if (!iosDevice.checkiOSDevice(device_udid)) {
return appiumMan.appiumServerForAndroid(device_udid, methodName);
}
} else {
return appiumMan.appiumServerForAndroid(device_udid, methodName);
}
return null;
}
|
#vulnerable code
public synchronized AppiumServiceBuilder startAppiumServer(String methodName) throws Exception {
device_udid = getNextAvailableDeviceId();
if (device_udid == null) {
System.out.println("No devices are free to run test or Failed to run test");
return null;
}
if (System.getProperty("os.name").toLowerCase().contains("mac")) {
if (iosDevice.checkiOSDevice(device_udid)) {
iosDevice.setIOSWebKitProxyPorts(device_udid);
category = iosDevice.getDeviceName(device_udid).replace(" ", "_");
} else if (!iosDevice.checkiOSDevice(device_udid)) {
category = androidDevice.getDeviceModel(device_udid);
System.out.println(category);
}
} else {
category = androidDevice.getDeviceModel(device_udid);
}
if (prop.getProperty("FRAMEWORK").equalsIgnoreCase("testng")) {
parent = ExtentTestManager.startTest(methodName, "Mobile Appium Test",
category + "_" + device_udid.replaceAll("\\W", "_"));
parentContext.put(Thread.currentThread().getId(), parent);
ExtentTestManager.getTest().log(LogStatus.INFO, "AppiumServerLogs",
"<a href=" + System.getProperty("user.dir") + "/target/appiumlogs/" + device_udid
.replaceAll("\\W", "_") + "__" + methodName + ".txt" + ">Logs</a>");
}
if (System.getProperty("os.name").toLowerCase().contains("mac")) {
if (iosDevice.checkiOSDevice(device_udid)) {
String webKitPort = iosDevice.startIOSWebKit(device_udid);
return appiumMan.appiumServerForIOS(device_udid, methodName, webKitPort);
} else if (!iosDevice.checkiOSDevice(device_udid)) {
return appiumMan.appiumServerForAndroid(device_udid, methodName);
}
} else {
return appiumMan.appiumServerForAndroid(device_udid, methodName);
}
return null;
}
#location 8
#vulnerability type RESOURCE_LEAK
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
public boolean parallelExecution(String pack, List<String> tests) throws Exception {
String operSys = System.getProperty("os.name").toLowerCase();
File f = new File(System.getProperty("user.dir") + "/target/appiumlogs/");
if (!f.exists()) {
System.out.println("creating directory: " + "Logs");
boolean result = false;
try {
f.mkdir();
result = true;
} catch (SecurityException se) {
se.printStackTrace();
}
}
if (configurationManager.getProperty("ANDROID_APP_PATH") != null && deviceConf.getDevices() != null) {
devices = deviceConf.getDevices();
deviceCount = devices.size() / 4;
File adb_logs = new File(System.getProperty("user.dir") + "/target/adblogs/");
if (!adb_logs.exists()) {
System.out.println("creating directory: " + "ADBLogs");
boolean result = false;
try {
adb_logs.mkdir();
result = true;
} catch (SecurityException se) {
se.printStackTrace();
}
}
createSnapshotFolderAndroid(deviceCount, "android");
}
if (operSys.contains("mac")) {
if (configurationManager.getProperty("IOS_APP_PATH") != null ) {
if (iosDevice.getIOSUDID() != null) {
iosDevice.checkExecutePermissionForIOSDebugProxyLauncher();
iOSdevices = iosDevice.getIOSUDIDHash();
deviceCount += iOSdevices.size();
createSnapshotFolderiOS(deviceCount, "iPhone");
}
}
}
if (deviceCount == 0) {
figlet("No Devices Connected");
System.exit(0);
}
System.out.println("***************************************************\n");
System.out.println("Total Number of devices detected::" + deviceCount + "\n");
System.out.println("***************************************************\n");
System.out.println("starting running tests in threads");
testcases = new ArrayList<Class>();
boolean hasFailures = false;
if (configurationManager.getProperty("FRAMEWORK").equalsIgnoreCase("testng")) {
// final String pack = "com.paralle.tests"; // Or any other package
PackageUtil.getClasses(pack).stream().forEach(s -> {
if (s.toString().contains("Test")) {
testcases.add((Class) s);
}
});
if (configurationManager.getProperty("RUNNER").equalsIgnoreCase("distribute")) {
hasFailures = myTestExecutor
.runMethodParallelAppium(tests, pack, deviceCount,
"distribute");
}
if (configurationManager.getProperty("RUNNER").equalsIgnoreCase("parallel")) {
hasFailures = myTestExecutor
.runMethodParallelAppium(tests, pack, deviceCount,
"parallel");
}
}
if (configurationManager.getProperty("FRAMEWORK").equalsIgnoreCase("cucumber")) {
//addPluginToCucumberRunner();
if (configurationManager.getProperty("RUNNER").equalsIgnoreCase("distribute")) {
hasFailures = myTestExecutor.runMethodParallel(myTestExecutor
.constructXmlSuiteDistributeCucumber(deviceCount,
AppiumParallelTest.devices));
} else if (configurationManager.getProperty("RUNNER").equalsIgnoreCase("parallel")) {
//addPluginToCucumberRunner();
hasFailures = myTestExecutor.runMethodParallel(myTestExecutor
.constructXmlSuiteForParallelCucumber(deviceCount,
AppiumParallelTest.devices));
htmlReporter.generateReports();
}
}
return hasFailures;
}
|
#vulnerable code
public boolean parallelExecution(String pack, List<String> tests) throws Exception {
String operSys = System.getProperty("os.name").toLowerCase();
File f = new File(System.getProperty("user.dir") + "/target/appiumlogs/");
if (!f.exists()) {
System.out.println("creating directory: " + "Logs");
boolean result = false;
try {
f.mkdir();
result = true;
} catch (SecurityException se) {
se.printStackTrace();
}
}
if (prop.getProperty("ANDROID_APP_PATH") != null && deviceConf.getDevices() != null) {
devices = deviceConf.getDevices();
deviceCount = devices.size() / 4;
File adb_logs = new File(System.getProperty("user.dir") + "/target/adblogs/");
if (!adb_logs.exists()) {
System.out.println("creating directory: " + "ADBLogs");
boolean result = false;
try {
adb_logs.mkdir();
result = true;
} catch (SecurityException se) {
se.printStackTrace();
}
}
createSnapshotFolderAndroid(deviceCount, "android");
}
if (operSys.contains("mac")) {
if (prop.getProperty("IOS_APP_PATH") != null ) {
if (iosDevice.getIOSUDID() != null) {
iosDevice.checkExecutePermissionForIOSDebugProxyLauncher();
iOSdevices = iosDevice.getIOSUDIDHash();
deviceCount += iOSdevices.size();
createSnapshotFolderiOS(deviceCount, "iPhone");
}
}
}
if (deviceCount == 0) {
figlet("No Devices Connected");
System.exit(0);
}
System.out.println("***************************************************\n");
System.out.println("Total Number of devices detected::" + deviceCount + "\n");
System.out.println("***************************************************\n");
System.out.println("starting running tests in threads");
testcases = new ArrayList<Class>();
boolean hasFailures = false;
if (prop.getProperty("FRAMEWORK").equalsIgnoreCase("testng")) {
// final String pack = "com.paralle.tests"; // Or any other package
PackageUtil.getClasses(pack).stream().forEach(s -> {
if (s.toString().contains("Test")) {
testcases.add((Class) s);
}
});
if (prop.getProperty("RUNNER").equalsIgnoreCase("distribute")) {
hasFailures = myTestExecutor
.runMethodParallelAppium(tests, pack, deviceCount,
"distribute");
}
if (prop.getProperty("RUNNER").equalsIgnoreCase("parallel")) {
hasFailures = myTestExecutor
.runMethodParallelAppium(tests, pack, deviceCount,
"parallel");
}
}
if (prop.getProperty("FRAMEWORK").equalsIgnoreCase("cucumber")) {
//addPluginToCucumberRunner();
if (prop.getProperty("RUNNER").equalsIgnoreCase("distribute")) {
hasFailures = myTestExecutor.runMethodParallel(myTestExecutor
.constructXmlSuiteDistributeCucumber(deviceCount,
AppiumParallelTest.devices));
} else if (prop.getProperty("RUNNER").equalsIgnoreCase("parallel")) {
//addPluginToCucumberRunner();
hasFailures = myTestExecutor.runMethodParallel(myTestExecutor
.constructXmlSuiteForParallelCucumber(deviceCount,
AppiumParallelTest.devices));
htmlReporter.generateReports();
}
}
return hasFailures;
}
#location 56
#vulnerability type NULL_DEREFERENCE
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
public synchronized AppiumDriver<MobileElement> startAppiumServerInParallel(String methodName)
throws Exception {
ExtentTestManager.loadConfig();
if (prop.getProperty("FRAMEWORK").equalsIgnoreCase("testng")) {
child = ExtentTestManager.startTest(methodName.toString())
.assignCategory(category + "_" + device_udid.replaceAll("\\W", "_"));
}
Thread.sleep(3000);
startingServerInstance();
return driver;
}
|
#vulnerable code
public synchronized AppiumDriver<MobileElement> startAppiumServerInParallel(String methodName)
throws Exception {
ExtentTestManager.loadConfig();
if (prop.getProperty("FRAMEWORK").equalsIgnoreCase("testng")) {
child = ExtentTestManager.startTest(methodName)
.assignCategory(category + "_" + device_udid.replaceAll("\\W", "_"));
}
Thread.sleep(3000);
if (prop.getProperty("APP_TYPE").equalsIgnoreCase("web")) {
driver = new AndroidDriver<>(appiumMan.getAppiumUrl(), androidWeb());
} else {
if (System.getProperty("os.name").toLowerCase().contains("mac")) {
if (iosDevice.checkiOSDevice(device_udid)) {
driver = new IOSDriver<>(appiumMan.getAppiumUrl(), iosNative());
} else if (!iosDevice.checkiOSDevice(device_udid)) {
driver = new AndroidDriver<>(appiumMan.getAppiumUrl(), androidNative());
}
} else {
driver = new AndroidDriver<>(appiumMan.getAppiumUrl(), androidNative());
}
}
return driver;
}
#location 12
#vulnerability type NULL_DEREFERENCE
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
public AppiumServiceBuilder getAppiumServiceBuilder(String methodName) throws Exception {
String webKitPort = iosDevice.startIOSWebKit(device_udid);
return appiumMan.appiumServerForIOS(device_udid, methodName, webKitPort);
}
|
#vulnerable code
public AppiumServiceBuilder getAppiumServiceBuilder(String methodName) throws Exception {
if (iosDevice.checkiOSDevice(device_udid)) {
String webKitPort = iosDevice.startIOSWebKit(device_udid);
return appiumMan.appiumServerForIOS(device_udid, methodName, webKitPort);
} else if (!iosDevice.checkiOSDevice(device_udid)) {
return appiumMan.appiumServerForAndroid(device_udid, methodName);
}
return null;
}
#location 5
#vulnerability type THREAD_SAFETY_VIOLATION
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
public void startingServerInstance() throws Exception {
startingServerInstance(null, null);
}
|
#vulnerable code
public void startingServerInstance() throws Exception {
if (prop.getProperty("APP_TYPE").equalsIgnoreCase("web")) {
driver = new AndroidDriver<>(appiumMan.getAppiumUrl(), androidWeb());
} else {
if (System.getProperty("os.name").toLowerCase().contains("mac")) {
if (iosDevice.checkiOSDevice(device_udid)) {
driver = new IOSDriver<>(appiumMan.getAppiumUrl(), iosNative());
} else if (!iosDevice.checkiOSDevice(device_udid)) {
driver = new AndroidDriver<>(appiumMan.getAppiumUrl(), androidNative());
}
} else {
driver = new AndroidDriver<>(appiumMan.getAppiumUrl(), androidNative());
}
}
}
#location 6
#vulnerability type THREAD_SAFETY_VIOLATION
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
public void stopRecording() throws IOException {
Integer processId = androidScreenRecordProcess.get(Thread.currentThread().getId());
if (processId != -1) {
String process = "pgrep -P " + processId;
System.out.println(process);
Process p2 = Runtime.getRuntime().exec(process);
BufferedReader r = new BufferedReader(new InputStreamReader(p2.getInputStream()));
String command = "kill " + processId;
System.out.println("Stopping Video Recording");
System.out.println("******************" + command);
try {
runCommandThruProcess(command);
Thread.sleep(10000);
System.out.println("Killed video recording with exit code :" + command);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
|
#vulnerable code
public void stopRecording() throws IOException {
Integer processId = androidScreenRecordProcess.get(Thread.currentThread().getId());
if (processId != -1) {
String process = "pgrep -P " + processId;
System.out.println(process);
Process p2 = Runtime.getRuntime().exec(process);
BufferedReader r = new BufferedReader(new InputStreamReader(p2.getInputStream()));
String command = "kill -s SIGTSTP " + processId;
System.out.println("Stopping Video Recording");
System.out.println("******************" + command);
Process killProcess = Runtime.getRuntime().exec(command);
try {
killProcess.waitFor();
Thread.sleep(5000);
System.out.println(
"Killed video recording with exit code :" + killProcess.exitValue()
+ processId);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
#location 16
#vulnerability type RESOURCE_LEAK
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
public String runCommandThruProcessBuilder(String command)
throws InterruptedException, IOException {
BufferedReader br = getBufferedReader(command);
String line;
String allLine = "";
while ((line = br.readLine()) != null) {
allLine = allLine + "" + line + "\n";
System.out.println(allLine);
}
return allLine.split(":")[1].replace("\n", "").trim();
}
|
#vulnerable code
public String runCommandThruProcessBuilder(String command)
throws InterruptedException, IOException {
List<String> commands = new ArrayList<String>();
commands.add("/bin/sh");
commands.add("-c");
commands.add(command);
ProcessBuilder builder = new ProcessBuilder(commands);
Map<String, String> environ = builder.environment();
final Process process = builder.start();
InputStream is = process.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
String line;
String allLine = "";
while ((line = br.readLine()) != null) {
allLine = allLine + "" + line + "\n";
System.out.println(allLine);
}
return allLine.split(":")[1].replace("\n", "").trim();
}
#location 20
#vulnerability type RESOURCE_LEAK
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
@SuppressWarnings({ "rawtypes" })
public void runner(String pack) throws Exception {
File f = new File(System.getProperty("user.dir") + "/target/appiumlogs/");
if (!f.exists()) {
System.out.println("creating directory: " + "Logs");
boolean result = false;
try {
f.mkdir();
result = true;
} catch (SecurityException se) {
// handle it
}
if (result) {
System.out.println("DIR created");
}
}
File adb_logs = new File(System.getProperty("user.dir") + "/target/adblogs/");
if (!adb_logs.exists()) {
System.out.println("creating directory: " + "ADBLogs");
boolean result = false;
try {
adb_logs.mkdir();
result = true;
} catch (SecurityException se) {
// handle it
}
if (result) {
System.out.println("DIR created");
}
}
input = new FileInputStream("config.properties");
prop.load(input);
if(deviceConf.getDevices() != null){
devices = deviceConf.getDevices();
deviceCount = devices.size() / 3;
createSnapshotFolderAndroid(deviceCount,"android");
}
if(iosDevice.getIOSUDID() != null){
iOSdevices = iosDevice.getIOSUDIDHash();
deviceCount += iOSdevices.size();
System.out.println("iOSdevices.size():"+iOSdevices.size());
System.out.println(deviceCount);
createSnapshotFolderiOS(deviceCount,"iPhone");
}
if(deviceCount == 0){
System.exit(0);
}
System.out.println("Total Number of devices detected::" + deviceCount);
System.out.println("starting running tests in threads");
testcases = new ArrayList<Class>();
// final String pack = "com.paralle.tests"; // Or any other package
PackageUtil.getClasses(pack).stream().forEach(s -> {
if (s.toString().contains("Test")) {
System.out.println("forEach: " + testcases.add((Class) s));
}
});
if (prop.getProperty("RUNNER").equalsIgnoreCase("distribute")) {
//myTestExecutor.distributeTests(deviceCount, testcases);
myTestExecutor.runMethodParallelAppium(pack, deviceCount,"distribute");
}
else if (prop.getProperty("RUNNER").equalsIgnoreCase("parallel")) {
myTestExecutor.runMethodParallelAppium(pack, deviceCount,"parallel");
}
}
|
#vulnerable code
@SuppressWarnings({ "rawtypes" })
public void runner(String pack) throws Exception {
File f = new File(System.getProperty("user.dir") + "/target/appiumlogs/");
if (!f.exists()) {
System.out.println("creating directory: " + "Logs");
boolean result = false;
try {
f.mkdir();
result = true;
} catch (SecurityException se) {
// handle it
}
if (result) {
System.out.println("DIR created");
}
}
File adb_logs = new File(System.getProperty("user.dir") + "/target/adblogs/");
if (!adb_logs.exists()) {
System.out.println("creating directory: " + "ADBLogs");
boolean result = false;
try {
adb_logs.mkdir();
result = true;
} catch (SecurityException se) {
// handle it
}
if (result) {
System.out.println("DIR created");
}
}
input = new FileInputStream("config.properties");
prop.load(input);
if(deviceConf.getDevices() != null){
devices = deviceConf.getDevices();
deviceCount = devices.size() / 3;
createSnapshotFolderAndroid(deviceCount,"android");
}
if(iosDevice.getIOSUDID() != null){
iOSdevices = iosDevice.getIOSUDIDHash();
deviceCount += iosDevice.getIOSUDID().size();
createSnapshotFolderiOS(deviceCount,"iPhone");
}
if(deviceCount == 0){
System.exit(0);
}
System.out.println("Total Number of devices detected::" + deviceCount);
System.out.println("starting running tests in threads");
testcases = new ArrayList<Class>();
// final String pack = "com.paralle.tests"; // Or any other package
PackageUtil.getClasses(pack).stream().forEach(s -> {
if (s.toString().contains("Test")) {
System.out.println("forEach: " + testcases.add((Class) s));
}
});
if (prop.getProperty("RUNNER").equalsIgnoreCase("distribute")) {
//myTestExecutor.distributeTests(deviceCount, testcases);
myTestExecutor.runMethodParallelAppium(pack, deviceCount,"distribute");
}
else if (prop.getProperty("RUNNER").equalsIgnoreCase("parallel")) {
myTestExecutor.runMethodParallelAppium(pack, deviceCount,"parallel");
}
}
#location 42
#vulnerability type RESOURCE_LEAK
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
public void startingServerInstance() throws Exception {
startingServerInstance(null, null);
}
|
#vulnerable code
public void startingServerInstance() throws Exception {
if (prop.getProperty("APP_TYPE").equalsIgnoreCase("web")) {
driver = new AndroidDriver<>(appiumMan.getAppiumUrl(), androidWeb());
} else {
if (System.getProperty("os.name").toLowerCase().contains("mac")) {
if (iosDevice.checkiOSDevice(device_udid)) {
driver = new IOSDriver<>(appiumMan.getAppiumUrl(), iosNative());
} else if (!iosDevice.checkiOSDevice(device_udid)) {
driver = new AndroidDriver<>(appiumMan.getAppiumUrl(), androidNative());
}
} else {
driver = new AndroidDriver<>(appiumMan.getAppiumUrl(), androidNative());
}
}
}
#location 8
#vulnerability type THREAD_SAFETY_VIOLATION
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
public String getAppiumServerPath(String host) throws Exception {
return appiumServerProp(host, "appiumServerPath");
}
|
#vulnerable code
public String getAppiumServerPath(String host) throws Exception {
JSONArray hostMachineObject = CapabilityManager.getInstance().getHostMachineObject();
List<Object> objects = hostMachineObject.toList();
Object o = objects.stream().filter(object -> ((HashMap) object).get("machineIP")
.toString().equalsIgnoreCase(host)
&& ((HashMap) object).get("appiumServerPath") != null)
.findFirst().orElse(null);
if (o != null) {
return ((HashMap) o).get("appiumServerPath").toString();
}
return null;
}
#location 9
#vulnerability type NULL_DEREFERENCE
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
public Map<String, String> getDevices() throws Exception {
startADB(); // start adb service
String output = cmd.runCommand("adb devices");
String[] lines = output.split("\n");
if (lines.length <= 1) {
System.out.println("No Android Device Connected");
stopADB();
return null;
} else {
for (int i = 1; i < lines.length; i++) {
lines[i] = lines[i].replaceAll("\\s+", "");
if (lines[i].contains("device")) {
lines[i] = lines[i].replaceAll("device", "");
String deviceID = lines[i];
if (validDeviceIds == null
|| (validDeviceIds != null && validDeviceIds.contains(deviceID))) {
String model =
cmd.runCommand("adb -s " + deviceID
+ " shell getprop ro.product.model")
.replaceAll("\\s+", "");
String brand =
cmd.runCommand("adb -s " + deviceID
+ " shell getprop ro.product.brand")
.replaceAll("\\s+", "");
String osVersion = cmd.runCommand(
"adb -s " + deviceID + " shell getprop ro.build.version.release")
.replaceAll("\\s+", "");
String deviceName = brand + " " + model;
String apiLevel =
cmd.runCommand("adb -s " + deviceID
+ " shell getprop ro.build.version.sdk")
.replaceAll("\n", "");
devices.put("deviceID" + i, deviceID);
devices.put("deviceName" + i, deviceName);
devices.put("osVersion" + i, osVersion);
devices.put(deviceID, apiLevel);
deviceSerial.add(deviceID);
}
} else if (lines[i].contains("unauthorized")) {
lines[i] = lines[i].replaceAll("unauthorized", "");
String deviceID = lines[i];
} else if (lines[i].contains("offline")) {
lines[i] = lines[i].replaceAll("offline", "");
String deviceID = lines[i];
}
}
return devices;
}
}
|
#vulnerable code
public Map<String, String> getDevices() throws Exception {
startADB(); // start adb service
String output = cmd.runCommand("adb devices");
String[] lines = output.split("\n");
if (lines.length <= 1) {
System.out.println("No Device Connected");
stopADB();
return null;
} else {
for (int i = 1; i < lines.length; i++) {
lines[i] = lines[i].replaceAll("\\s+", "");
if (lines[i].contains("device")) {
lines[i] = lines[i].replaceAll("device", "");
String deviceID = lines[i];
String model =
cmd.runCommand("adb -s " + deviceID + " shell getprop ro.product.model")
.replaceAll("\\s+", "");
String brand =
cmd.runCommand("adb -s " + deviceID + " shell getprop ro.product.brand")
.replaceAll("\\s+", "");
String osVersion = cmd.runCommand(
"adb -s " + deviceID + " shell getprop ro.build.version.release")
.replaceAll("\\s+", "");
String deviceName = brand + " " + model;
String apiLevel =
cmd.runCommand("adb -s " + deviceID + " shell getprop ro.build.version.sdk")
.replaceAll("\n", "");
devices.put("deviceID" + i, deviceID);
devices.put("deviceName" + i, deviceName);
devices.put("osVersion" + i, osVersion);
devices.put(deviceID, apiLevel);
} else if (lines[i].contains("unauthorized")) {
lines[i] = lines[i].replaceAll("unauthorized", "");
String deviceID = lines[i];
} else if (lines[i].contains("offline")) {
lines[i] = lines[i].replaceAll("offline", "");
String deviceID = lines[i];
}
}
return devices;
}
}
#location 19
#vulnerability type RESOURCE_LEAK
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
private void startAppiumDriverInstance(Optional<DesiredCapabilities> iosCaps,
Optional<DesiredCapabilities> androidCaps)
throws Exception {
AppiumDriver<MobileElement> currentDriverSession;
if (System.getProperty("os.name").toLowerCase().contains("mac")
&& System.getenv("Platform").equalsIgnoreCase("iOS")
|| System.getenv("Platform").equalsIgnoreCase("Both")) {
if (AppiumDeviceManager.getMobilePlatform().equals(MobilePlatform.IOS)) {
currentDriverSession = getMobileiOSElementAppiumDriver(iosCaps);
AppiumDriverManager.setDriver(currentDriverSession);
} else if (AppiumDeviceManager.getMobilePlatform().equals(MobilePlatform.ANDROID)) {
currentDriverSession = getMobileAndroidElementAppiumDriver(androidCaps);
AppiumDriverManager.setDriver(currentDriverSession);
}
} else {
currentDriverSession = getMobileAndroidElementAppiumDriver(androidCaps);
AppiumDriverManager.setDriver(currentDriverSession);
}
}
|
#vulnerable code
private void startAppiumDriverInstance(Optional<DesiredCapabilities> iosCaps,
Optional<DesiredCapabilities> androidCaps)
throws Exception {
AppiumDriver<MobileElement> currentDriverSession;
if (System.getProperty("os.name").toLowerCase().contains("mac")
&& System.getProperty("Platform").equalsIgnoreCase("iOS")
|| System.getProperty("Platform").equalsIgnoreCase("Both")) {
if (AppiumDeviceManager.getMobilePlatform().equals(MobilePlatform.IOS)) {
currentDriverSession = getMobileiOSElementAppiumDriver(iosCaps);
AppiumDriverManager.setDriver(currentDriverSession);
} else if (AppiumDeviceManager.getMobilePlatform().equals(MobilePlatform.ANDROID)) {
currentDriverSession = getMobileAndroidElementAppiumDriver(androidCaps);
AppiumDriverManager.setDriver(currentDriverSession);
}
} else {
currentDriverSession = getMobileAndroidElementAppiumDriver(androidCaps);
AppiumDriverManager.setDriver(currentDriverSession);
}
}
#location 7
#vulnerability type NULL_DEREFERENCE
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
@Override
public String getRemoteWDHubIP(String host) throws Exception {
String hostIP = "http://" + host;
String appiumRunningPort = new JSONObject(new Api().getResponse(hostIP
+ ":" + getRemoteAppiumManagerPort(host)
+ "/appium/isRunning").body().string()).get("port").toString();
return hostIP + ":" + appiumRunningPort + "/wd/hub";
}
|
#vulnerable code
@Override
public String getRemoteWDHubIP(String host) throws IOException {
String hostIP = "http://" + host;
String appiumRunningPort = new JSONObject(new Api().getResponse(hostIP + ":4567"
+ "/appium/isRunning").body().string()).get("port").toString();
return hostIP + ":" + appiumRunningPort + "/wd/hub";
}
#location 5
#vulnerability type NULL_DEREFERENCE
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
public synchronized AppiumDriver<MobileElement> startAppiumServerInParallel(String methodName)
throws Exception {
ExtentTestManager.loadConfig();
if (prop.getProperty("FRAMEWORK").equalsIgnoreCase("testng")) {
child = ExtentTestManager.startTest(methodName.toString())
.assignCategory(category + "_" + device_udid.replaceAll("\\W", "_"));
}
Thread.sleep(3000);
startingServerInstance();
return driver;
}
|
#vulnerable code
public synchronized AppiumDriver<MobileElement> startAppiumServerInParallel(String methodName)
throws Exception {
ExtentTestManager.loadConfig();
if (prop.getProperty("FRAMEWORK").equalsIgnoreCase("testng")) {
child = ExtentTestManager.startTest(methodName)
.assignCategory(category + "_" + device_udid.replaceAll("\\W", "_"));
}
Thread.sleep(3000);
if (prop.getProperty("APP_TYPE").equalsIgnoreCase("web")) {
driver = new AndroidDriver<>(appiumMan.getAppiumUrl(), androidWeb());
} else {
if (System.getProperty("os.name").toLowerCase().contains("mac")) {
if (iosDevice.checkiOSDevice(device_udid)) {
driver = new IOSDriver<>(appiumMan.getAppiumUrl(), iosNative());
} else if (!iosDevice.checkiOSDevice(device_udid)) {
driver = new AndroidDriver<>(appiumMan.getAppiumUrl(), androidNative());
}
} else {
driver = new AndroidDriver<>(appiumMan.getAppiumUrl(), androidNative());
}
}
return driver;
}
#location 15
#vulnerability type RESOURCE_LEAK
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
public void startingServerInstance() throws Exception {
startingServerInstance(null, null);
}
|
#vulnerable code
public void startingServerInstance() throws Exception {
if (prop.getProperty("APP_TYPE").equalsIgnoreCase("web")) {
driver = new AndroidDriver<>(appiumMan.getAppiumUrl(), androidWeb());
} else {
if (System.getProperty("os.name").toLowerCase().contains("mac")) {
if (iosDevice.checkiOSDevice(device_udid)) {
driver = new IOSDriver<>(appiumMan.getAppiumUrl(), iosNative());
} else if (!iosDevice.checkiOSDevice(device_udid)) {
driver = new AndroidDriver<>(appiumMan.getAppiumUrl(), androidNative());
}
} else {
driver = new AndroidDriver<>(appiumMan.getAppiumUrl(), androidNative());
}
}
}
#location 9
#vulnerability type THREAD_SAFETY_VIOLATION
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
public AppiumServiceBuilder getAppiumServiceBuilder(String methodName) throws Exception {
String webKitPort = iosDevice.startIOSWebKit(device_udid);
return appiumMan.appiumServerForIOS(device_udid, methodName, webKitPort);
}
|
#vulnerable code
public AppiumServiceBuilder getAppiumServiceBuilder(String methodName) throws Exception {
if (iosDevice.checkiOSDevice(device_udid)) {
String webKitPort = iosDevice.startIOSWebKit(device_udid);
return appiumMan.appiumServerForIOS(device_udid, methodName, webKitPort);
} else if (!iosDevice.checkiOSDevice(device_udid)) {
return appiumMan.appiumServerForAndroid(device_udid, methodName);
}
return null;
}
#location 6
#vulnerability type THREAD_SAFETY_VIOLATION
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
private HashMap<String, String> getArtifactForHost(String hostMachine) throws IOException {
String platform = System.getenv("Platform");
String app = "app";
HashMap<String, String> artifactPaths = new HashMap<>();
JSONObject android = capabilityManager
.getCapabilityObjectFromKey("android");
JSONObject iOSAppPath = capabilityManager
.getCapabilityObjectFromKey("iOS");
if (android != null && android.has(app)
&& platform.equalsIgnoreCase("android")
|| platform.equalsIgnoreCase("both")) {
artifactPaths.put("APK", getArtifactPath(hostMachine, android.getString("app")));
}
if (iOSAppPath != null && iOSAppPath.has("app")
&& platform.equalsIgnoreCase("ios")
|| platform.equalsIgnoreCase("both")) {
if (iOSAppPath.get("app") instanceof JSONObject) {
JSONObject iOSApp = iOSAppPath.getJSONObject("app");
if (iOSApp.has("simulator")) {
String simulatorApp = iOSApp.getString("simulator");
artifactPaths.put("APP", getArtifactPath(hostMachine, simulatorApp));
}
if (iOSApp.has("device")) {
String deviceIPA = iOSApp.getString("device");
artifactPaths.put("IPA", getArtifactPath(hostMachine, deviceIPA));
}
}
}
return artifactPaths;
}
|
#vulnerable code
private HashMap<String, String> getArtifactForHost(String hostMachine) throws IOException {
String platform = System.getProperty("Platform");
String app = "app";
HashMap<String, String> artifactPaths = new HashMap<>();
JSONObject android = capabilityManager
.getCapabilityObjectFromKey("android");
JSONObject iOSAppPath = capabilityManager
.getCapabilityObjectFromKey("iOS");
if (android != null && android.has(app)
&& platform.equalsIgnoreCase("android")
|| platform.equalsIgnoreCase("both")) {
artifactPaths.put("APK", getArtifactPath(hostMachine, android.getString("app")));
}
if (iOSAppPath != null && iOSAppPath.has("app")
&& platform.equalsIgnoreCase("ios")
|| platform.equalsIgnoreCase("both")) {
if (iOSAppPath.get("app") instanceof JSONObject) {
JSONObject iOSApp = iOSAppPath.getJSONObject("app");
if (iOSApp.has("simulator")) {
String simulatorApp = iOSApp.getString("simulator");
artifactPaths.put("APP", getArtifactPath(hostMachine, simulatorApp));
}
if (iOSApp.has("device")) {
String deviceIPA = iOSApp.getString("device");
artifactPaths.put("IPA", getArtifactPath(hostMachine, deviceIPA));
}
}
}
return artifactPaths;
}
#location 10
#vulnerability type NULL_DEREFERENCE
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
@Override
public void startAppiumServer(String host) throws Exception {
System.out.println(
"**************************************************************************\n");
System.out.println("Starting Appium Server on host " + host);
System.out.println(
"**************************************************************************\n");
String serverPath = CapabilityManager.getInstance().getAppiumServerPath(host);
String serverPort = CapabilityManager.getInstance().getAppiumServerPort(host);
if (serverPath == null
&& serverPort == null) {
System.out.println("Picking Default Path for AppiumServiceBuilder");
new Api().getResponse("http://" + host + ":4567"
+ "/appium/start").body().string();
} else if (serverPath != null && serverPort != null ) {
System.out.println("Picking UserSpecified Path & Port for AppiumServiceBuilder");
new Api().getResponse("http://" + host + ":4567"
+ "/appium/start?URL=" + serverPath
+ "&PORT=" + serverPort).body().string();
} else if (serverPath != null) {
System.out.println("Picking UserSpecified Path & Using default Port for AppiumServiceBuilder");
new Api().getResponse("http://" + host + ":4567"
+ "/appium/start?URL=" + serverPath).body().string();
} else if (serverPort != null) {
System.out.println("Picking Default Path & User Port for AppiumServiceBuilder");
new Api().getResponse("http://" + host + ":4567"
+ "/appium/start?PORT=" + serverPort).body().string();
}
boolean status = Boolean.getBoolean(new JSONObject(new Api().getResponse("http://" + host + ":4567"
+ "/appium/isRunning").body().string()).get("status").toString());
if (status) {
System.out.println(
"***************************************************************\n");
System.out.println("Appium Server started successfully on " + host);
System.out.println(
"****************************************************************\n");
}
}
|
#vulnerable code
@Override
public void startAppiumServer(String host) throws Exception {
System.out.println(
"**************************************************************************\n");
System.out.println("Starting Appium Server on host " + host);
System.out.println(
"**************************************************************************\n");
if (CapabilityManager.getInstance().getAppiumServerPath(host) == null) {
System.out.println("Picking Default Path for AppiumServiceBuilder");
new Api().getResponse("http://" + host + ":4567"
+ "/appium/start").body().string();
} else {
System.out.println("Picking UserSpecified Path for AppiumServiceBuilder");
String appiumServerPath = CapabilityManager.getInstance().getAppiumServerPath(host);
new Api().getResponse("http://" + host + ":4567"
+ "/appium/start?URL=" + appiumServerPath).body().string();
}
boolean status = Boolean.getBoolean(new JSONObject(new Api().getResponse("http://" + host + ":4567"
+ "/appium/isRunning").body().string()).get("status").toString());
if (status) {
System.out.println(
"***************************************************************\n");
System.out.println("Appium Server started successfully on " + host);
System.out.println(
"****************************************************************\n");
}
}
#location 11
#vulnerability type NULL_DEREFERENCE
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
public synchronized AppiumServiceBuilder startAppiumServer(String methodName) throws Exception {
device_udid = getNextAvailableDeviceId();
if (device_udid == null) {
System.out.println("No devices are free to run test or Failed to run test");
return null;
}
if (System.getProperty("os.name").toLowerCase().contains("mac")) {
if (iosDevice.checkiOSDevice(device_udid)) {
iosDevice.setIOSWebKitProxyPorts(device_udid);
category = iosDevice.getDeviceName(device_udid).replace(" ", "_");
} else if (!iosDevice.checkiOSDevice(device_udid)) {
category = androidDevice.getDeviceModel(device_udid);
System.out.println(category);
}
} else {
category = androidDevice.getDeviceModel(device_udid);
}
if (prop.getProperty("FRAMEWORK").equalsIgnoreCase("testng")) {
if (getClass().getAnnotation(Description.class) != null) {
testDescription = getClass().getAnnotation(Description.class).value();
}
parent = ExtentTestManager.startTest(methodName, testDescription,
category + "_" + device_udid.replaceAll("\\W", "_"));
parentContext.put(Thread.currentThread().getId(), parent);
ExtentTestManager.getTest().log(LogStatus.INFO, "AppiumServerLogs",
"<a href=" + System.getProperty("user.dir") + "/target/appiumlogs/" + device_udid
.replaceAll("\\W", "_") + "__" + methodName + ".txt" + ">Logs</a>");
}
if (System.getProperty("os.name").toLowerCase().contains("mac")) {
if (iosDevice.checkiOSDevice(device_udid)) {
String webKitPort = iosDevice.startIOSWebKit(device_udid);
return appiumMan.appiumServerForIOS(device_udid, methodName, webKitPort);
} else if (!iosDevice.checkiOSDevice(device_udid)) {
return appiumMan.appiumServerForAndroid(device_udid, methodName);
}
} else {
return appiumMan.appiumServerForAndroid(device_udid, methodName);
}
return null;
}
|
#vulnerable code
public synchronized AppiumServiceBuilder startAppiumServer(String methodName) throws Exception {
device_udid = getNextAvailableDeviceId();
if (device_udid == null) {
System.out.println("No devices are free to run test or Failed to run test");
return null;
}
if (System.getProperty("os.name").toLowerCase().contains("mac")) {
if (iosDevice.checkiOSDevice(device_udid)) {
iosDevice.setIOSWebKitProxyPorts(device_udid);
category = iosDevice.getDeviceName(device_udid).replace(" ", "_");
} else if (!iosDevice.checkiOSDevice(device_udid)) {
category = androidDevice.getDeviceModel(device_udid);
System.out.println(category);
}
} else {
category = androidDevice.getDeviceModel(device_udid);
}
if (prop.getProperty("FRAMEWORK").equalsIgnoreCase("testng")) {
parent = ExtentTestManager.startTest(methodName, "Mobile Appium Test",
category + "_" + device_udid.replaceAll("\\W", "_"));
parentContext.put(Thread.currentThread().getId(), parent);
ExtentTestManager.getTest().log(LogStatus.INFO, "AppiumServerLogs",
"<a href=" + System.getProperty("user.dir") + "/target/appiumlogs/" + device_udid
.replaceAll("\\W", "_") + "__" + methodName + ".txt" + ">Logs</a>");
}
if (System.getProperty("os.name").toLowerCase().contains("mac")) {
if (iosDevice.checkiOSDevice(device_udid)) {
String webKitPort = iosDevice.startIOSWebKit(device_udid);
return appiumMan.appiumServerForIOS(device_udid, methodName, webKitPort);
} else if (!iosDevice.checkiOSDevice(device_udid)) {
return appiumMan.appiumServerForAndroid(device_udid, methodName);
}
} else {
return appiumMan.appiumServerForAndroid(device_udid, methodName);
}
return null;
}
#location 11
#vulnerability type RESOURCE_LEAK
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
public synchronized AppiumDriver<MobileElement> startAppiumServerInParallel(String methodName) throws Exception {
child = ExtentTestManager
.startTest(methodName).assignCategory(category + device_udid.replaceAll("\\W", "_"));
if (prop.getProperty("APP_TYPE").equalsIgnoreCase("web")) {
androidWeb();
} else {
System.out.println(iosDevice.checkiOSDevice(device_udid));
if (iosDevice.checkiOSDevice(device_udid)) {
iosNative();
} else if(!iosDevice.checkiOSDevice(device_udid)){
androidNative();
}
}
Thread.sleep(5000);
if (prop.getProperty("APP_TYPE").equalsIgnoreCase("web")) {
driver = new AndroidDriver<>(appiumMan.getAppiumUrl(), capabilities);
} else{
if (iosDevice.checkiOSDevice(device_udid)) {
driver = new IOSDriver<>(appiumMan.getAppiumUrl(), capabilities);
} else if (!iosDevice.checkiOSDevice(device_udid)){
driver = new AndroidDriver<>(appiumMan.getAppiumUrl(), capabilities);
}
}
return driver;
}
|
#vulnerable code
public synchronized AppiumDriver<MobileElement> startAppiumServerInParallel(String methodName) throws Exception {
child = ExtentTestManager
.startTest(methodName).assignCategory(category + device_udid.replaceAll("\\W", "_"));
if (prop.getProperty("APP_TYPE").equalsIgnoreCase("web")) {
androidWeb();
} else {
System.out.println(iosDevice.checkiOSDevice(device_udid));
if (iosDevice.checkiOSDevice(device_udid)) {
iosNative();
} else {
androidNative();
}
}
Thread.sleep(5000);
if (prop.getProperty("APP_TYPE").equalsIgnoreCase("web")) {
driver = new AndroidDriver<>(appiumMan.getAppiumUrl(), capabilities);
} else{
if (iosDevice.checkiOSDevice(device_udid)) {
driver = new IOSDriver<>(appiumMan.getAppiumUrl(), capabilities);
} else if (!iosDevice.checkiOSDevice(device_udid)){
driver = new AndroidDriver<>(appiumMan.getAppiumUrl(), capabilities);
}
}
return driver;
}
#location 8
#vulnerability type RESOURCE_LEAK
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
public XmlSuite constructXmlSuiteForDistribution(String pack, List<String> tests,
Map<String, List<Method>> methods, int deviceCount) {
include(listeners, "LISTENERS");
include(groupsInclude, "INCLUDE_GROUPS");
XmlSuite suite = new XmlSuite();
suite.setName("TestNG Forum");
suite.setThreadCount(deviceCount);
suite.setParallel(ParallelMode.CLASSES);
suite.setVerbose(2);
listeners.add("com.appium.manager.AppiumParallelTest");
listeners.add("com.appium.utils.RetryListener");
suite.setListeners(listeners);
if (prop.getProperty("LISTENERS") != null) {
suite.setListeners(listeners);
}
XmlTest test = new XmlTest(suite);
test.setName("TestNG Test");
test.addParameter("device", "");
include(groupsExclude, "EXCLUDE_GROUPS");
test.setIncludedGroups(groupsInclude);
test.setExcludedGroups(groupsExclude);
List<XmlClass> xmlClasses = new ArrayList<>();
writeXmlClass(tests, methods, xmlClasses);
test.setXmlClasses(xmlClasses);
return suite;
}
|
#vulnerable code
public XmlSuite constructXmlSuiteForDistribution(String pack, List<String> tests,
Map<String, List<Method>> methods, int deviceCount) {
try {
prop.load(new FileInputStream("config.properties"));
} catch (IOException e) {
e.printStackTrace();
}
include(listeners, "LISTENERS");
include(groupsInclude, "INCLUDE_GROUPS");
XmlSuite suite = new XmlSuite();
suite.setName("TestNG Forum");
suite.setThreadCount(deviceCount);
suite.setParallel(ParallelMode.CLASSES);
suite.setVerbose(2);
listeners.add("com.appium.manager.AppiumParallelTest");
listeners.add("com.appium.utils.RetryListener");
suite.setListeners(listeners);
if (prop.getProperty("LISTENERS") != null) {
suite.setListeners(listeners);
}
XmlTest test = new XmlTest(suite);
test.setName("TestNG Test");
test.addParameter("device", "");
include(groupsExclude, "EXCLUDE_GROUPS");
test.setIncludedGroups(groupsInclude);
test.setExcludedGroups(groupsExclude);
List<XmlClass> xmlClasses = new ArrayList<>();
writeXmlClass(tests, methods, xmlClasses);
test.setXmlClasses(xmlClasses);
return suite;
}
#location 4
#vulnerability type RESOURCE_LEAK
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
public void startingServerInstance() throws Exception {
startingServerInstance(null, null);
}
|
#vulnerable code
public void startingServerInstance() throws Exception {
if (prop.getProperty("APP_TYPE").equalsIgnoreCase("web")) {
driver = new AndroidDriver<>(appiumMan.getAppiumUrl(), androidWeb());
} else {
if (System.getProperty("os.name").toLowerCase().contains("mac")) {
if (iosDevice.checkiOSDevice(device_udid)) {
driver = new IOSDriver<>(appiumMan.getAppiumUrl(), iosNative());
} else if (!iosDevice.checkiOSDevice(device_udid)) {
driver = new AndroidDriver<>(appiumMan.getAppiumUrl(), androidNative());
}
} else {
driver = new AndroidDriver<>(appiumMan.getAppiumUrl(), androidNative());
}
}
}
#location 8
#vulnerability type RESOURCE_LEAK
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
public AppiumServiceBuilder getAppiumServiceBuilder(String methodName) throws Exception {
String webKitPort = iosDevice.startIOSWebKit(device_udid);
return appiumMan.appiumServerForIOS(device_udid, methodName, webKitPort);
}
|
#vulnerable code
public AppiumServiceBuilder getAppiumServiceBuilder(String methodName) throws Exception {
if (iosDevice.checkiOSDevice(device_udid)) {
String webKitPort = iosDevice.startIOSWebKit(device_udid);
return appiumMan.appiumServerForIOS(device_udid, methodName, webKitPort);
} else if (!iosDevice.checkiOSDevice(device_udid)) {
return appiumMan.appiumServerForAndroid(device_udid, methodName);
}
return null;
}
#location 2
#vulnerability type THREAD_SAFETY_VIOLATION
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
public void captureScreenShot(String screenShotName) throws IOException, InterruptedException {
File framePath = new File(System.getProperty("user.dir")+"/src/main/resources/");
File scrFile = ((TakesScreenshot) driver).getScreenshotAs(OutputType.FILE);
if(driver.toString().split(":")[0].trim().equals("AndroidDriver")){
String androidModel = androidDevice.deviceModel(device_udid);
try {
FileUtils.copyFile(scrFile, new File(System.getProperty("user.dir") + "/target/screenshot/android/" + device_udid.replaceAll("\\W", "_") + "/"
+ androidModel + "/" + screenShotName + ".png"));
File [] files1 = framePath.listFiles();
for (int i = 0; i < files1.length; i++){
if (files1[i].isFile()){ //this line weeds out other directories/folders
System.out.println(files1[i]);
Path p = Paths.get(files1[i].toString());
String fileName=p.getFileName().toString().toLowerCase();
if(androidModel.toString().toLowerCase().contains(fileName.split(".png")[0].toLowerCase())){
try {
imageUtils.wrapDeviceFrames(files1[i].toString(),System.getProperty("user.dir") + "/target/screenshot/android/" + device_udid.replaceAll("\\W", "_") + "/"
+ androidModel + "/" + screenShotName + ".png",System.getProperty("user.dir") + "/target/screenshot/android/" + device_udid.replaceAll("\\W", "_") + "/"
+ androidModel + "/" + screenShotName + "_framed.png");
ExtentTestManager.logOutPut(System.getProperty("user.dir") + "/target/screenshot/android/" + device_udid.replaceAll("\\W", "_") + "/"
+ androidModel + "/" + screenShotName + "_framed.png",screenShotName.toUpperCase());
break;
} catch (InterruptedException e) {
e.printStackTrace();
} catch (IM4JavaException e) {
e.printStackTrace();
}
}
}
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}else if(driver.toString().split(":")[0].trim().equals("IOSDriver"))
{
String iosModel=iosDevice.getIOSDeviceProductTypeAndVersion(device_udid);
try {
FileUtils.copyFile(scrFile, new File(System.getProperty("user.dir") + "/target/screenshot/iPhone/" + device_udid.replaceAll("\\W", "_") + "/"
+ iosModel + "/" + screenShotName + ".png"));
File [] files1 = framePath.listFiles();
for (int i = 0; i < files1.length; i++){
if (files1[i].isFile()){ //this line weeds out other directories/folders
System.out.println(files1[i]);
Path p = Paths.get(files1[i].toString());
String fileName=p.getFileName().toString().toLowerCase();
if(iosModel.toString().toLowerCase().contains(fileName.split(".png")[0].toLowerCase())){
try {
imageUtils.wrapDeviceFrames(files1[i].toString(),System.getProperty("user.dir") + "/target/screenshot/iPhone/" + device_udid.replaceAll("\\W", "_") + "/"
+ iosModel + "/" + screenShotName + ".png",System.getProperty("user.dir") + "/target/screenshot/iPhone/" + device_udid.replaceAll("\\W", "_") + "/"
+ iosModel + "/" + screenShotName + "_framed.png");
ExtentTestManager.logOutPut(System.getProperty("user.dir") + "/target/screenshot/iPhone/" + device_udid.replaceAll("\\W", "_") + "/"
+ iosModel + "/" + screenShotName + "_framed.png",screenShotName.toUpperCase());
break;
} catch (InterruptedException e) {
e.printStackTrace();
} catch (IM4JavaException e) {
e.printStackTrace();
}
}
}
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
|
#vulnerable code
public void captureScreenShot(String screenShotName) throws IOException, InterruptedException {
File framePath = new File(System.getProperty("user.dir")+"/src/main/resources/");
File scrFile = ((TakesScreenshot) driver).getScreenshotAs(OutputType.FILE);
if(driver.toString().split(":")[0].trim().equals("AndroidDriver")){
String androidModel = androidDevice.deviceModel(device_udid);
try {
FileUtils.copyFile(scrFile, new File(System.getProperty("user.dir") + "/target/screenshot/android/" + device_udid.replaceAll("\\W", "_") + "/"
+ androidModel + "/" + screenShotName + ".png"));
File [] files1 = framePath.listFiles();
for (int i = 0; i < files1.length; i++){
if (files1[i].isFile()){ //this line weeds out other directories/folders
System.out.println(files1[i]);
Path p = Paths.get(files1[i].toString());
String fileName=p.getFileName().toString().toLowerCase();
if(androidModel.toString().toLowerCase().contains(fileName.split(".png")[0].toLowerCase())){
try {
imageUtils.wrapDeviceFrames(files1[i].toString(),System.getProperty("user.dir") + "/target/screenshot/android/" + device_udid.replaceAll("\\W", "_") + "/"
+ androidModel + "/" + screenShotName + ".png",System.getProperty("user.dir") + "/target/screenshot/android/" + device_udid.replaceAll("\\W", "_") + "/"
+ androidModel + "/" + screenShotName + "_framed.png");
ExtentTestManager.logOutPut(System.getProperty("user.dir") + "/target/screenshot/android/" + device_udid.replaceAll("\\W", "_") + "/"
+ androidModel + "/" + screenShotName + "_framed.png",screenShotName.toUpperCase());
break;
} catch (InterruptedException e) {
e.printStackTrace();
} catch (IM4JavaException e) {
e.printStackTrace();
}
}
}
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}else if(driver.toString().split(":")[0].trim().equals("IOSDriver"))
{
String iosModel=iosDevice.getDeviceName(device_udid);
try {
FileUtils.copyFile(scrFile, new File(System.getProperty("user.dir") + "/target/screenshot/iPhone/" + device_udid.replaceAll("\\W", "_") + "/"
+ iosModel + "/" + screenShotName + ".png"));
File [] files1 = framePath.listFiles();
for (int i = 0; i < files1.length; i++){
if (files1[i].isFile()){ //this line weeds out other directories/folders
System.out.println(files1[i]);
Path p = Paths.get(files1[i].toString());
String fileName=p.getFileName().toString().toLowerCase();
if(iosModel.toString().toLowerCase().contains(fileName.split(".png")[0].toLowerCase())){
try {
imageUtils.wrapDeviceFrames(files1[i].toString(),System.getProperty("user.dir") + "/target/screenshot/iPhone/" + device_udid.replaceAll("\\W", "_") + "/"
+ iosModel + "/" + screenShotName + ".png",System.getProperty("user.dir") + "/target/screenshot/iPhone/" + device_udid.replaceAll("\\W", "_") + "/"
+ iosModel + "/" + screenShotName + "_framed.png");
ExtentTestManager.logOutPut(System.getProperty("user.dir") + "/target/screenshot/iPhone/" + device_udid.replaceAll("\\W", "_") + "/"
+ iosModel + "/" + screenShotName + "_framed.png",screenShotName.toUpperCase());
break;
} catch (InterruptedException e) {
e.printStackTrace();
} catch (IM4JavaException e) {
e.printStackTrace();
}
}
}
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
#location 10
#vulnerability type NULL_DEREFERENCE
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
public void endLogTestResults(ITestResult result) throws IOException, InterruptedException {
final String classNameCur = result.getName().split(" ")[2].substring(1);
final Package[] packages = Package.getPackages();
String className = null;
for (final Package p : packages) {
final String pack = p.getName();
final String tentative = pack + "." + classNameCur;
try {
Class.forName(tentative);
} catch (final ClassNotFoundException e) {
continue;
}
className = tentative;
break;
}
if (result.isSuccess()) {
ExtentTestManager.getTest()
.log(LogStatus.PASS, result.getMethod().getMethodName(), "Pass");
if (driver.toString().split("\\(")[0].trim().equals("AndroidDriver: on LINUX")) {
log_file_writer.println(logEntries);
log_file_writer.flush();
ExtentTestManager.getTest().log(LogStatus.INFO, result.getMethod().getMethodName(),
"ADBLogs:: <a href=" + "adblogs/" + device_udid
.replaceAll("\\W", "_") + "__" + result.getMethod().getMethodName() + ".txt"
+ ">AdbLogs</a>");
System.out.println(driver.getSessionId() + ": Saving device log - Done.");
}
}
if (result.getStatus() == ITestResult.FAILURE) {
writeFailureToTxt();
ExtentTestManager.getTest()
.log(LogStatus.FAIL, result.getMethod().getMethodName(), result.getThrowable());
if (driver.toString().split(":")[0].trim().equals("AndroidDriver")) {
System.out.println("im in");
deviceModel = androidDevice.getDeviceModel(device_udid);
//captureScreenshot(result.getMethod().getMethodName(), "android", className);
captureScreenShot(result.getMethod().getMethodName(), result.getStatus(),
result.getTestClass().getName());
} else if (driver.toString().split(":")[0].trim().equals("IOSDriver")) {
deviceModel = iosDevice.getIOSDeviceProductTypeAndVersion(device_udid);
captureScreenShot(result.getMethod().getMethodName(), result.getStatus(),
result.getTestClass().getName());
}
if (driver.toString().split(":")[0].trim().equals("AndroidDriver")) {
File framedImageAndroid = new File(
"screenshot/android/" + device_udid
.replaceAll("\\W", "_") + "/" + className + "/" + result.getMethod()
.getMethodName() + "/" + screenShotNameWithTimeStamp + deviceModel
+ "_failed_" + result.getMethod().getMethodName() + "_framed.png");
if (framedImageAndroid.exists()) {
ExtentTestManager.getTest()
.log(LogStatus.INFO, result.getMethod().getMethodName(),
"Snapshot below: " + ExtentTestManager.getTest().addScreenCapture(
"screenshot/android/" + device_udid
.replaceAll("\\W", "_") + "/" + className + "/" + result
.getMethod().getMethodName() + "/" + screenShotNameWithTimeStamp
+ deviceModel + "_failed_" + result.getMethod().getMethodName()
+ "_framed.png"));
} else {
ExtentTestManager.getTest()
.log(LogStatus.INFO, result.getMethod().getMethodName(),
"Snapshot below: " + ExtentTestManager.getTest().addScreenCapture(
"screenshot/android/" + device_udid
.replaceAll("\\W", "_") + "/" + className + "/" + result
.getMethod().getMethodName() + "/" + screenShotNameWithTimeStamp
+ deviceModel + "_" + result.getMethod().getMethodName()
+ "_failed.png"));
}
}
if (driver.toString().split(":")[0].trim().equals("IOSDriver")) {
File framedImageIOS = new File(
"screenshot/iOS/" + device_udid
.replaceAll("\\W", "_") + "/" + className + "/" + result.getMethod()
.getMethodName() + "/" + screenShotNameWithTimeStamp + deviceModel
+ "_failed_" + result.getMethod().getMethodName() + "_framed.png");
if (framedImageIOS.exists()) {
ExtentTestManager.getTest()
.log(LogStatus.INFO, result.getMethod().getMethodName(),
"Snapshot below: " + ExtentTestManager.getTest().addScreenCapture(
"/screenshot/iOS/" + device_udid
.replaceAll("\\W", "_") + "/" + className + "/" + result
.getMethod().getMethodName() + "/" + screenShotNameWithTimeStamp
+ deviceModel + "_failed_" + result.getMethod().getMethodName()
+ "_framed.png"));
} else {
ExtentTestManager.getTest()
.log(LogStatus.INFO, result.getMethod().getMethodName(),
"Snapshot below: " + ExtentTestManager.getTest().addScreenCapture(
"screenshot/iOS/" + device_udid
.replaceAll("\\W", "_") + "/" + className + "/" + result
.getMethod().getMethodName() + "/" + screenShotNameWithTimeStamp
+ deviceModel + "_" + result.getMethod().getMethodName()
+ "_failed.png"));
}
}
if (driver.toString().split("\\(")[0].trim().equals("AndroidDriver: on LINUX")) {
log_file_writer.println(logEntries);
log_file_writer.flush();
ExtentTestManager.getTest().log(LogStatus.INFO, result.getMethod().getMethodName(),
"ADBLogs:: <a href=" + "adblogs/" + device_udid
.replaceAll("\\W", "_") + "__" + result.getMethod().getMethodName() + ".txt"
+ ">AdbLogs</a>");
System.out.println(driver.getSessionId() + ": Saving device log - Done.");
}
}
if (result.getStatus() == ITestResult.SKIP) {
ExtentTestManager.getTest().log(LogStatus.SKIP, "Test skipped");
}
parentContext.get(Thread.currentThread().getId()).appendChild(child);
ExtentManager.getInstance().flush();
}
|
#vulnerable code
public void endLogTestResults(ITestResult result) throws IOException, InterruptedException {
final String classNameCur = result.getName().split(" ")[2].substring(1);
final Package[] packages = Package.getPackages();
String className = null;
for (final Package p : packages) {
final String pack = p.getName();
final String tentative = pack + "." + classNameCur;
try {
Class.forName(tentative);
} catch (final ClassNotFoundException e) {
continue;
}
className = tentative;
break;
}
if (result.isSuccess()) {
ExtentTestManager.getTest()
.log(LogStatus.PASS, result.getMethod().getMethodName(), "Pass");
if (driver.toString().split("\\(")[0].trim().equals("AndroidDriver: on LINUX")) {
log_file_writer.println(logEntries);
log_file_writer.flush();
ExtentTestManager.getTest().log(LogStatus.INFO, result.getMethod().getMethodName(),
"ADBLogs:: <a href=" + CI_BASE_URI + "/target/adblogs/" + device_udid
.replaceAll("\\W", "_") + "__" + result.getMethod().getMethodName() + ".txt"
+ ">AdbLogs</a>");
System.out.println(driver.getSessionId() + ": Saving device log - Done.");
}
}
if (result.getStatus() == ITestResult.FAILURE) {
writeFailureToTxt();
ExtentTestManager.getTest()
.log(LogStatus.FAIL, result.getMethod().getMethodName(), result.getThrowable());
if (driver.toString().split(":")[0].trim().equals("AndroidDriver")) {
System.out.println("im in");
deviceModel = androidDevice.getDeviceModel(device_udid);
//captureScreenshot(result.getMethod().getMethodName(), "android", className);
captureScreenShot(result.getMethod().getMethodName(), result.getStatus(),
result.getTestClass().getName());
} else if (driver.toString().split(":")[0].trim().equals("IOSDriver")) {
deviceModel = iosDevice.getIOSDeviceProductTypeAndVersion(device_udid);
captureScreenShot(result.getMethod().getMethodName(), result.getStatus(),
result.getTestClass().getName());
}
if (driver.toString().split(":")[0].trim().equals("AndroidDriver")) {
File framedImageAndroid = new File(
System.getProperty("user.dir") + "/target/screenshot/android/" + device_udid
.replaceAll("\\W", "_") + "/" + className + "/" + result.getMethod()
.getMethodName() + "/" + screenShotNameWithTimeStamp + deviceModel
+ "_failed_" + result.getMethod().getMethodName() + "_framed.png");
if (framedImageAndroid.exists()) {
ExtentTestManager.getTest()
.log(LogStatus.INFO, result.getMethod().getMethodName(),
"Snapshot below: " + ExtentTestManager.getTest().addScreenCapture(
CI_BASE_URI + "/target/screenshot/android/" + device_udid
.replaceAll("\\W", "_") + "/" + className + "/" + result
.getMethod().getMethodName() + "/" + screenShotNameWithTimeStamp
+ deviceModel + "_failed_" + result.getMethod().getMethodName()
+ "_framed.png"));
} else {
ExtentTestManager.getTest()
.log(LogStatus.INFO, result.getMethod().getMethodName(),
"Snapshot below: " + ExtentTestManager.getTest().addScreenCapture(
CI_BASE_URI + "/target/screenshot/android/" + device_udid
.replaceAll("\\W", "_") + "/" + className + "/" + result
.getMethod().getMethodName() + "/" + screenShotNameWithTimeStamp
+ deviceModel + "_" + result.getMethod().getMethodName()
+ "_failed.png"));
}
}
if (driver.toString().split(":")[0].trim().equals("IOSDriver")) {
File framedImageIOS = new File(
System.getProperty("user.dir") + "/target/screenshot/iOS/" + device_udid
.replaceAll("\\W", "_") + "/" + className + "/" + result.getMethod()
.getMethodName() + "/" + screenShotNameWithTimeStamp + deviceModel
+ "_failed_" + result.getMethod().getMethodName() + "_framed.png");
if (framedImageIOS.exists()) {
ExtentTestManager.getTest()
.log(LogStatus.INFO, result.getMethod().getMethodName(),
"Snapshot below: " + ExtentTestManager.getTest().addScreenCapture(
CI_BASE_URI + "/target/screenshot/iOS/" + device_udid
.replaceAll("\\W", "_") + "/" + className + "/" + result
.getMethod().getMethodName() + "/" + screenShotNameWithTimeStamp
+ deviceModel + "_failed_" + result.getMethod().getMethodName()
+ "_framed.png"));
} else {
ExtentTestManager.getTest()
.log(LogStatus.INFO, result.getMethod().getMethodName(),
"Snapshot below: " + ExtentTestManager.getTest().addScreenCapture(
CI_BASE_URI + "/target/screenshot/iOS/" + device_udid
.replaceAll("\\W", "_") + "/" + className + "/" + result
.getMethod().getMethodName() + "/" + screenShotNameWithTimeStamp
+ deviceModel + "_" + result.getMethod().getMethodName()
+ "_failed.png"));
}
}
if (driver.toString().split("\\(")[0].trim().equals("AndroidDriver: on LINUX")) {
log_file_writer.println(logEntries);
log_file_writer.flush();
ExtentTestManager.getTest().log(LogStatus.INFO, result.getMethod().getMethodName(),
"ADBLogs:: <a href=" + CI_BASE_URI + "/target/adblogs/" + device_udid
.replaceAll("\\W", "_") + "__" + result.getMethod().getMethodName() + ".txt"
+ ">AdbLogs</a>");
System.out.println(driver.getSessionId() + ": Saving device log - Done.");
}
}
if (result.getStatus() == ITestResult.SKIP) {
ExtentTestManager.getTest().log(LogStatus.SKIP, "Test skipped");
}
parentContext.get(Thread.currentThread().getId()).appendChild(child);
ExtentManager.getInstance().flush();
}
#location 25
#vulnerability type THREAD_SAFETY_VIOLATION
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
public synchronized AppiumDriver<MobileElement> startAppiumServerInParallel(String methodName)
throws Exception {
ExtentTestManager.loadConfig();
if (prop.getProperty("FRAMEWORK").equalsIgnoreCase("testng")) {
child = ExtentTestManager.startTest(methodName.toString())
.assignCategory(category + "_" + device_udid.replaceAll("\\W", "_"));
}
Thread.sleep(3000);
startingServerInstance();
return driver;
}
|
#vulnerable code
public synchronized AppiumDriver<MobileElement> startAppiumServerInParallel(String methodName)
throws Exception {
ExtentTestManager.loadConfig();
if (prop.getProperty("FRAMEWORK").equalsIgnoreCase("testng")) {
child = ExtentTestManager.startTest(methodName)
.assignCategory(category + "_" + device_udid.replaceAll("\\W", "_"));
}
Thread.sleep(3000);
if (prop.getProperty("APP_TYPE").equalsIgnoreCase("web")) {
driver = new AndroidDriver<>(appiumMan.getAppiumUrl(), androidWeb());
} else {
if (System.getProperty("os.name").toLowerCase().contains("mac")) {
if (iosDevice.checkiOSDevice(device_udid)) {
driver = new IOSDriver<>(appiumMan.getAppiumUrl(), iosNative());
} else if (!iosDevice.checkiOSDevice(device_udid)) {
driver = new AndroidDriver<>(appiumMan.getAppiumUrl(), androidNative());
}
} else {
driver = new AndroidDriver<>(appiumMan.getAppiumUrl(), androidNative());
}
}
return driver;
}
#location 16
#vulnerability type RESOURCE_LEAK
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
public synchronized AppiumServiceBuilder startAppiumServer(String methodName) throws Exception {
device_udid = getNextAvailableDeviceId();
if (device_udid == null) {
System.out.println("No devices are free to run test or Failed to run test");
return null;
}
if (iosDevice.checkiOSDevice(device_udid)) {
iosDevice.setIOSWebKitProxyPorts(device_udid);
category = iosDevice.getDeviceName(device_udid).replace("\n", " ");
} else {
category = androidDevice.getDeviceModel(device_udid);
}
parent = ExtentTestManager.startTest(methodName, "Mobile Appium Test",
category + device_udid.replaceAll("\\W", "_"));
parentContext.put(Thread.currentThread().getId(), parent);
ExtentTestManager.getTest().log(LogStatus.INFO, "AppiumServerLogs", "<a href=" + System.getProperty("user.dir")
+ "/target/appiumlogs/" + device_udid.replaceAll("\\W", "_") + "__" + methodName + ".txt" + ">Logs</a>");
if (iosDevice.checkiOSDevice(device_udid)) {
String webKitPort = iosDevice.startIOSWebKit(device_udid);
return appiumMan.appiumServerForIOS(device_udid, methodName, webKitPort);
} else {
return appiumMan.appiumServerForAndroid(device_udid, methodName);
}
}
|
#vulnerable code
public synchronized AppiumServiceBuilder startAppiumServer(String methodName) throws Exception {
device_udid = getNextAvailableDeviceId();
if (device_udid == null) {
System.out.println("No devices are free to run test or Failed to run test");
return null;
}
if (iosDevice.checkiOSDevice(device_udid)) {
iosDevice.setIOSWebKitProxyPorts(device_udid);
category = iosDevice.getDeviceName(device_udid).replace("\n", " ");
} else {
category = androidDevice.deviceModel(device_udid);
}
System.out.println(category + device_udid.replaceAll("\\W", "_"));
parent = ExtentTestManager.startTest(methodName, "Mobile Appium Test",
category + device_udid.replaceAll("\\W", "_"));
parentContext.put(Thread.currentThread().getId(), parent);
ExtentTestManager.getTest().log(LogStatus.INFO, "AppiumServerLogs", "<a href=" + System.getProperty("user.dir")
+ "/target/appiumlogs/" + device_udid.replaceAll("\\W", "_") + "__" + methodName + ".txt" + ">Logs</a>");
if (iosDevice.checkiOSDevice(device_udid)) {
String webKitPort = iosDevice.startIOSWebKit(device_udid);
return appiumMan.appiumServerIOS(device_udid, methodName, webKitPort);
} else {
return appiumMan.appiumServer(device_udid, methodName);
}
}
#location 8
#vulnerability type RESOURCE_LEAK
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
public Map<String, String> getDevices() throws Exception {
startADB(); // start adb service
String output = cmd.runCommand("adb devices");
String[] lines = output.split("\n");
if (lines.length <= 1) {
System.out.println("No Android Device Connected");
stopADB();
return null;
} else {
for (int i = 1; i < lines.length; i++) {
lines[i] = lines[i].replaceAll("\\s+", "");
if (lines[i].contains("device")) {
lines[i] = lines[i].replaceAll("device", "");
String deviceID = lines[i];
if (validDeviceIds == null
|| (validDeviceIds != null && validDeviceIds.contains(deviceID))) {
String model =
cmd.runCommand("adb -s " + deviceID
+ " shell getprop ro.product.model")
.replaceAll("\\s+", "");
String brand =
cmd.runCommand("adb -s " + deviceID
+ " shell getprop ro.product.brand")
.replaceAll("\\s+", "");
String osVersion = cmd.runCommand(
"adb -s " + deviceID + " shell getprop ro.build.version.release")
.replaceAll("\\s+", "");
String deviceName = brand + " " + model;
String apiLevel =
cmd.runCommand("adb -s " + deviceID
+ " shell getprop ro.build.version.sdk")
.replaceAll("\n", "");
devices.put("deviceID" + i, deviceID);
devices.put("deviceName" + i, deviceName);
devices.put("osVersion" + i, osVersion);
devices.put(deviceID, apiLevel);
deviceSerial.add(deviceID);
}
} else if (lines[i].contains("unauthorized")) {
lines[i] = lines[i].replaceAll("unauthorized", "");
String deviceID = lines[i];
} else if (lines[i].contains("offline")) {
lines[i] = lines[i].replaceAll("offline", "");
String deviceID = lines[i];
}
}
return devices;
}
}
|
#vulnerable code
public Map<String, String> getDevices() throws Exception {
startADB(); // start adb service
String output = cmd.runCommand("adb devices");
String[] lines = output.split("\n");
if (lines.length <= 1) {
System.out.println("No Device Connected");
stopADB();
return null;
} else {
for (int i = 1; i < lines.length; i++) {
lines[i] = lines[i].replaceAll("\\s+", "");
if (lines[i].contains("device")) {
lines[i] = lines[i].replaceAll("device", "");
String deviceID = lines[i];
String model =
cmd.runCommand("adb -s " + deviceID + " shell getprop ro.product.model")
.replaceAll("\\s+", "");
String brand =
cmd.runCommand("adb -s " + deviceID + " shell getprop ro.product.brand")
.replaceAll("\\s+", "");
String osVersion = cmd.runCommand(
"adb -s " + deviceID + " shell getprop ro.build.version.release")
.replaceAll("\\s+", "");
String deviceName = brand + " " + model;
String apiLevel =
cmd.runCommand("adb -s " + deviceID + " shell getprop ro.build.version.sdk")
.replaceAll("\n", "");
devices.put("deviceID" + i, deviceID);
devices.put("deviceName" + i, deviceName);
devices.put("osVersion" + i, osVersion);
devices.put(deviceID, apiLevel);
} else if (lines[i].contains("unauthorized")) {
lines[i] = lines[i].replaceAll("unauthorized", "");
String deviceID = lines[i];
} else if (lines[i].contains("offline")) {
lines[i] = lines[i].replaceAll("offline", "");
String deviceID = lines[i];
}
}
return devices;
}
}
#location 22
#vulnerability type RESOURCE_LEAK
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
private Map<String, List<AppiumDevice>> filterByDevicePlatform(Map<String, List<AppiumDevice>> devicesByHost) {
String platform = System.getenv(PLATFORM);
if (platform.equalsIgnoreCase(OSType.BOTH.name())) {
return devicesByHost;
} else {
HashMap<String, List<AppiumDevice>> filteredDevicesHostName = new HashMap<>();
devicesByHost.forEach((hostName, appiumDevices) -> {
List<AppiumDevice> filteredDevices = appiumDevices.stream().filter(appiumDevice ->
appiumDevice.getDevice().getOs().equalsIgnoreCase(platform)).collect(Collectors.toList());
if (!filteredDevices.isEmpty())
filteredDevicesHostName.put(hostName, filteredDevices);
});
return filteredDevicesHostName;
}
}
|
#vulnerable code
private Map<String, List<AppiumDevice>> filterByDevicePlatform(Map<String, List<AppiumDevice>> devicesByHost) {
String platform = System.getProperty(PLATFORM);
if (platform.equalsIgnoreCase(OSType.BOTH.name())) {
return devicesByHost;
} else {
HashMap<String, List<AppiumDevice>> filteredDevicesHostName = new HashMap<>();
devicesByHost.forEach((hostName, appiumDevices) -> {
List<AppiumDevice> filteredDevices = appiumDevices.stream().filter(appiumDevice ->
appiumDevice.getDevice().getOs().equalsIgnoreCase(platform)).collect(Collectors.toList());
if (!filteredDevices.isEmpty())
filteredDevicesHostName.put(hostName, filteredDevices);
});
return filteredDevicesHostName;
}
}
#location 3
#vulnerability type NULL_DEREFERENCE
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
@Override
public void startAppiumServer(String host) throws Exception {
System.out.println(
"**************************************************************************\n");
System.out.println("Starting Appium Server on host " + host);
System.out.println(
"**************************************************************************\n");
String serverPath = CapabilityManager.getInstance().getAppiumServerPath(host);
String serverPort = CapabilityManager.getInstance().getAppiumServerPort(host);
if (serverPath == null
&& serverPort == null) {
System.out.println("Picking Default Path for AppiumServiceBuilder");
new Api().getResponse("http://" + host + ":"
+ getRemoteAppiumManagerPort(host)
+ "/appium/start").body().string();
} else if (serverPath != null && serverPort != null) {
System.out.println("Picking UserSpecified Path & Port for AppiumServiceBuilder");
new Api().getResponse("http://" + host + ":"
+ getRemoteAppiumManagerPort(host)
+ "/appium/start?URL=" + serverPath
+ "&PORT=" + serverPort).body().string();
} else if (serverPath != null) {
System.out.println("Picking UserSpecified Path "
+ "& Using default Port for AppiumServiceBuilder");
new Api().getResponse("http://" + host + ":"
+ getRemoteAppiumManagerPort(host)
+ "/appium/start?URL=" + serverPath).body().string();
} else if (serverPort != null) {
System.out.println("Picking Default Path & User Port for AppiumServiceBuilder");
new Api().getResponse("http://" + host + ":"
+ getRemoteAppiumManagerPort(host)
+ "/appium/start?PORT=" + serverPort).body().string();
}
boolean status = Boolean.getBoolean(new JSONObject(new Api()
.getResponse("http://" + host + ":"
+ getRemoteAppiumManagerPort(host)
+ "/appium/isRunning").body().string()).get("status").toString());
if (status) {
System.out.println(
"***************************************************************\n");
System.out.println("Appium Server started successfully on " + host);
System.out.println(
"****************************************************************\n");
}
}
|
#vulnerable code
@Override
public void startAppiumServer(String host) throws Exception {
System.out.println(
"**************************************************************************\n");
System.out.println("Starting Appium Server on host " + host);
System.out.println(
"**************************************************************************\n");
String serverPath = CapabilityManager.getInstance().getAppiumServerPath(host);
String serverPort = CapabilityManager.getInstance().getAppiumServerPort(host);
if (serverPath == null
&& serverPort == null) {
System.out.println("Picking Default Path for AppiumServiceBuilder");
new Api().getResponse("http://" + host + ":4567"
+ "/appium/start").body().string();
} else if (serverPath != null && serverPort != null) {
System.out.println("Picking UserSpecified Path & Port for AppiumServiceBuilder");
new Api().getResponse("http://" + host + ":4567"
+ "/appium/start?URL=" + serverPath
+ "&PORT=" + serverPort).body().string();
} else if (serverPath != null) {
System.out.println("Picking UserSpecified Path "
+ "& Using default Port for AppiumServiceBuilder");
new Api().getResponse("http://" + host + ":4567"
+ "/appium/start?URL=" + serverPath).body().string();
} else if (serverPort != null) {
System.out.println("Picking Default Path & User Port for AppiumServiceBuilder");
new Api().getResponse("http://" + host + ":4567"
+ "/appium/start?PORT=" + serverPort).body().string();
}
boolean status = Boolean.getBoolean(new JSONObject(new Api().getResponse("http://" + host + ":4567"
+ "/appium/isRunning").body().string()).get("status").toString());
if (status) {
System.out.println(
"***************************************************************\n");
System.out.println("Appium Server started successfully on " + host);
System.out.println(
"****************************************************************\n");
}
}
#location 19
#vulnerability type NULL_DEREFERENCE
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
private HashMap<String, String> getArtifactForHost(String hostMachine) throws IOException {
String platform = System.getenv("Platform");
String app = "app";
HashMap<String, String> artifactPaths = new HashMap<>();
JSONObject android = capabilityManager
.getCapabilityObjectFromKey("android");
JSONObject iOSAppPath = capabilityManager
.getCapabilityObjectFromKey("iOS");
if (android != null && android.has(app)
&& platform.equalsIgnoreCase("android")
|| platform.equalsIgnoreCase("both")) {
artifactPaths.put("APK", getArtifactPath(hostMachine, android.getString("app")));
}
if (iOSAppPath != null && iOSAppPath.has("app")
&& platform.equalsIgnoreCase("ios")
|| platform.equalsIgnoreCase("both")) {
if (iOSAppPath.get("app") instanceof JSONObject) {
JSONObject iOSApp = iOSAppPath.getJSONObject("app");
if (iOSApp.has("simulator")) {
String simulatorApp = iOSApp.getString("simulator");
artifactPaths.put("APP", getArtifactPath(hostMachine, simulatorApp));
}
if (iOSApp.has("device")) {
String deviceIPA = iOSApp.getString("device");
artifactPaths.put("IPA", getArtifactPath(hostMachine, deviceIPA));
}
}
}
return artifactPaths;
}
|
#vulnerable code
private HashMap<String, String> getArtifactForHost(String hostMachine) throws IOException {
String platform = System.getProperty("Platform");
String app = "app";
HashMap<String, String> artifactPaths = new HashMap<>();
JSONObject android = capabilityManager
.getCapabilityObjectFromKey("android");
JSONObject iOSAppPath = capabilityManager
.getCapabilityObjectFromKey("iOS");
if (android != null && android.has(app)
&& platform.equalsIgnoreCase("android")
|| platform.equalsIgnoreCase("both")) {
artifactPaths.put("APK", getArtifactPath(hostMachine, android.getString("app")));
}
if (iOSAppPath != null && iOSAppPath.has("app")
&& platform.equalsIgnoreCase("ios")
|| platform.equalsIgnoreCase("both")) {
if (iOSAppPath.get("app") instanceof JSONObject) {
JSONObject iOSApp = iOSAppPath.getJSONObject("app");
if (iOSApp.has("simulator")) {
String simulatorApp = iOSApp.getString("simulator");
artifactPaths.put("APP", getArtifactPath(hostMachine, simulatorApp));
}
if (iOSApp.has("device")) {
String deviceIPA = iOSApp.getString("device");
artifactPaths.put("IPA", getArtifactPath(hostMachine, deviceIPA));
}
}
}
return artifactPaths;
}
#location 11
#vulnerability type NULL_DEREFERENCE
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
public Map<String, String> getDevices() throws Exception {
startADB(); // start adb service
String output = cmd.runCommand("adb devices");
String[] lines = output.split("\n");
if (lines.length <= 1) {
System.out.println("No Android Device Connected");
stopADB();
return null;
} else {
for (int i = 1; i < lines.length; i++) {
lines[i] = lines[i].replaceAll("\\s+", "");
if (lines[i].contains("device")) {
lines[i] = lines[i].replaceAll("device", "");
String deviceID = lines[i];
if (validDeviceIds == null
|| (validDeviceIds != null && validDeviceIds.contains(deviceID))) {
String model =
cmd.runCommand("adb -s " + deviceID
+ " shell getprop ro.product.model")
.replaceAll("\\s+", "");
String brand =
cmd.runCommand("adb -s " + deviceID
+ " shell getprop ro.product.brand")
.replaceAll("\\s+", "");
String osVersion = cmd.runCommand(
"adb -s " + deviceID + " shell getprop ro.build.version.release")
.replaceAll("\\s+", "");
String deviceName = brand + " " + model;
String apiLevel =
cmd.runCommand("adb -s " + deviceID
+ " shell getprop ro.build.version.sdk")
.replaceAll("\n", "");
devices.put("deviceID" + i, deviceID);
devices.put("deviceName" + i, deviceName);
devices.put("osVersion" + i, osVersion);
devices.put(deviceID, apiLevel);
deviceSerial.add(deviceID);
}
} else if (lines[i].contains("unauthorized")) {
lines[i] = lines[i].replaceAll("unauthorized", "");
String deviceID = lines[i];
} else if (lines[i].contains("offline")) {
lines[i] = lines[i].replaceAll("offline", "");
String deviceID = lines[i];
}
}
return devices;
}
}
|
#vulnerable code
public Map<String, String> getDevices() throws Exception {
startADB(); // start adb service
String output = cmd.runCommand("adb devices");
String[] lines = output.split("\n");
if (lines.length <= 1) {
System.out.println("No Device Connected");
stopADB();
return null;
} else {
for (int i = 1; i < lines.length; i++) {
lines[i] = lines[i].replaceAll("\\s+", "");
if (lines[i].contains("device")) {
lines[i] = lines[i].replaceAll("device", "");
String deviceID = lines[i];
String model =
cmd.runCommand("adb -s " + deviceID + " shell getprop ro.product.model")
.replaceAll("\\s+", "");
String brand =
cmd.runCommand("adb -s " + deviceID + " shell getprop ro.product.brand")
.replaceAll("\\s+", "");
String osVersion = cmd.runCommand(
"adb -s " + deviceID + " shell getprop ro.build.version.release")
.replaceAll("\\s+", "");
String deviceName = brand + " " + model;
String apiLevel =
cmd.runCommand("adb -s " + deviceID + " shell getprop ro.build.version.sdk")
.replaceAll("\n", "");
devices.put("deviceID" + i, deviceID);
devices.put("deviceName" + i, deviceName);
devices.put("osVersion" + i, osVersion);
devices.put(deviceID, apiLevel);
} else if (lines[i].contains("unauthorized")) {
lines[i] = lines[i].replaceAll("unauthorized", "");
String deviceID = lines[i];
} else if (lines[i].contains("offline")) {
lines[i] = lines[i].replaceAll("offline", "");
String deviceID = lines[i];
}
}
return devices;
}
}
#location 29
#vulnerability type RESOURCE_LEAK
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
@Test
public static void testApp() throws Exception {
ParallelThread parallelThread = new ParallelThread();
List<String> tests = new ArrayList<>();
tests.add("HomePageTest3");
tests.add("HomePageTest2");
boolean hasFailures = parallelThread.runner("com.test.site",tests);
Assert.assertFalse(hasFailures, "Testcases have failed in parallel execution");
}
|
#vulnerable code
@Test
public static void testApp() throws Exception {
ParallelThread parallelThread = new ParallelThread();
List<String> tests = new ArrayList<>();
//tests.add("HomePageTest1");
//tests.add("HomePageTest2");
boolean hasFailures = parallelThread.runner("com.test.site");
Assert.assertFalse(hasFailures, "Testcases have failed in parallel execution");
}
#location 4
#vulnerability type RESOURCE_LEAK
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
public Map<String, String> getDevices() throws Exception {
startADB(); // start adb service
String output = cmd.runCommand("adb devices");
String[] lines = output.split("\n");
if (lines.length <= 1) {
System.out.println("No Android Device Connected");
stopADB();
return null;
} else {
for (int i = 1; i < lines.length; i++) {
lines[i] = lines[i].replaceAll("\\s+", "");
if (lines[i].contains("device")) {
lines[i] = lines[i].replaceAll("device", "");
String deviceID = lines[i];
if (validDeviceIds == null
|| (validDeviceIds != null && validDeviceIds.contains(deviceID))) {
String model =
cmd.runCommand("adb -s " + deviceID
+ " shell getprop ro.product.model")
.replaceAll("\\s+", "");
String brand =
cmd.runCommand("adb -s " + deviceID
+ " shell getprop ro.product.brand")
.replaceAll("\\s+", "");
String osVersion = cmd.runCommand(
"adb -s " + deviceID + " shell getprop ro.build.version.release")
.replaceAll("\\s+", "");
String deviceName = brand + " " + model;
String apiLevel =
cmd.runCommand("adb -s " + deviceID
+ " shell getprop ro.build.version.sdk")
.replaceAll("\n", "");
devices.put("deviceID" + i, deviceID);
devices.put("deviceName" + i, deviceName);
devices.put("osVersion" + i, osVersion);
devices.put(deviceID, apiLevel);
deviceSerial.add(deviceID);
}
} else if (lines[i].contains("unauthorized")) {
lines[i] = lines[i].replaceAll("unauthorized", "");
String deviceID = lines[i];
} else if (lines[i].contains("offline")) {
lines[i] = lines[i].replaceAll("offline", "");
String deviceID = lines[i];
}
}
return devices;
}
}
|
#vulnerable code
public Map<String, String> getDevices() throws Exception {
startADB(); // start adb service
String output = cmd.runCommand("adb devices");
String[] lines = output.split("\n");
if (lines.length <= 1) {
System.out.println("No Device Connected");
stopADB();
return null;
} else {
for (int i = 1; i < lines.length; i++) {
lines[i] = lines[i].replaceAll("\\s+", "");
if (lines[i].contains("device")) {
lines[i] = lines[i].replaceAll("device", "");
String deviceID = lines[i];
String model =
cmd.runCommand("adb -s " + deviceID + " shell getprop ro.product.model")
.replaceAll("\\s+", "");
String brand =
cmd.runCommand("adb -s " + deviceID + " shell getprop ro.product.brand")
.replaceAll("\\s+", "");
String osVersion = cmd.runCommand(
"adb -s " + deviceID + " shell getprop ro.build.version.release")
.replaceAll("\\s+", "");
String deviceName = brand + " " + model;
String apiLevel =
cmd.runCommand("adb -s " + deviceID + " shell getprop ro.build.version.sdk")
.replaceAll("\n", "");
devices.put("deviceID" + i, deviceID);
devices.put("deviceName" + i, deviceName);
devices.put("osVersion" + i, osVersion);
devices.put(deviceID, apiLevel);
} else if (lines[i].contains("unauthorized")) {
lines[i] = lines[i].replaceAll("unauthorized", "");
String deviceID = lines[i];
} else if (lines[i].contains("offline")) {
lines[i] = lines[i].replaceAll("offline", "");
String deviceID = lines[i];
}
}
return devices;
}
}
#location 4
#vulnerability type RESOURCE_LEAK
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
@Override
public void destroyAppiumNode(String host) throws Exception {
new Api().getResponse("http://" + host + ":" + getRemoteAppiumManagerPort(host)
+ "/appium/stop").body().string();
}
|
#vulnerable code
@Override
public void destroyAppiumNode(String host) throws IOException {
new Api().getResponse("http://" + host + ":4567"
+ "/appium/stop").body().string();
}
#location 4
#vulnerability type NULL_DEREFERENCE
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
public synchronized AppiumServiceBuilder startAppiumServer(String methodName) throws Exception {
device_udid = getNextAvailableDeviceId();
if (device_udid == null) {
System.out.println("No devices are free to run test or Failed to run test");
return null;
}
if (System.getProperty("os.name").toLowerCase().contains("mac")) {
if (iosDevice.checkiOSDevice(device_udid)) {
iosDevice.setIOSWebKitProxyPorts(device_udid);
category = iosDevice.getDeviceName(device_udid).replace(" ", "_");
} else if (!iosDevice.checkiOSDevice(device_udid)) {
category = androidDevice.getDeviceModel(device_udid);
System.out.println(category);
}
} else {
category = androidDevice.getDeviceModel(device_udid);
}
if (prop.getProperty("FRAMEWORK").equalsIgnoreCase("testng")) {
if (getClass().getAnnotation(Description.class) != null) {
testDescription = getClass().getAnnotation(Description.class).value();
}
parent = ExtentTestManager.startTest(methodName, testDescription,
category + "_" + device_udid.replaceAll("\\W", "_"));
parentContext.put(Thread.currentThread().getId(), parent);
ExtentTestManager.getTest().log(LogStatus.INFO, "AppiumServerLogs",
"<a href=" + System.getProperty("user.dir") + "/target/appiumlogs/" + device_udid
.replaceAll("\\W", "_") + "__" + methodName + ".txt" + ">Logs</a>");
}
if (System.getProperty("os.name").toLowerCase().contains("mac")) {
if (iosDevice.checkiOSDevice(device_udid)) {
String webKitPort = iosDevice.startIOSWebKit(device_udid);
return appiumMan.appiumServerForIOS(device_udid, methodName, webKitPort);
} else if (!iosDevice.checkiOSDevice(device_udid)) {
return appiumMan.appiumServerForAndroid(device_udid, methodName);
}
} else {
return appiumMan.appiumServerForAndroid(device_udid, methodName);
}
return null;
}
|
#vulnerable code
public synchronized AppiumServiceBuilder startAppiumServer(String methodName) throws Exception {
device_udid = getNextAvailableDeviceId();
if (device_udid == null) {
System.out.println("No devices are free to run test or Failed to run test");
return null;
}
if (System.getProperty("os.name").toLowerCase().contains("mac")) {
if (iosDevice.checkiOSDevice(device_udid)) {
iosDevice.setIOSWebKitProxyPorts(device_udid);
category = iosDevice.getDeviceName(device_udid).replace(" ", "_");
} else if (!iosDevice.checkiOSDevice(device_udid)) {
category = androidDevice.getDeviceModel(device_udid);
System.out.println(category);
}
} else {
category = androidDevice.getDeviceModel(device_udid);
}
if (prop.getProperty("FRAMEWORK").equalsIgnoreCase("testng")) {
parent = ExtentTestManager.startTest(methodName, "Mobile Appium Test",
category + "_" + device_udid.replaceAll("\\W", "_"));
parentContext.put(Thread.currentThread().getId(), parent);
ExtentTestManager.getTest().log(LogStatus.INFO, "AppiumServerLogs",
"<a href=" + System.getProperty("user.dir") + "/target/appiumlogs/" + device_udid
.replaceAll("\\W", "_") + "__" + methodName + ".txt" + ">Logs</a>");
}
if (System.getProperty("os.name").toLowerCase().contains("mac")) {
if (iosDevice.checkiOSDevice(device_udid)) {
String webKitPort = iosDevice.startIOSWebKit(device_udid);
return appiumMan.appiumServerForIOS(device_udid, methodName, webKitPort);
} else if (!iosDevice.checkiOSDevice(device_udid)) {
return appiumMan.appiumServerForAndroid(device_udid, methodName);
}
} else {
return appiumMan.appiumServerForAndroid(device_udid, methodName);
}
return null;
}
#location 11
#vulnerability type RESOURCE_LEAK
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
public void startingServerInstance() throws Exception {
startingServerInstance(null, null);
}
|
#vulnerable code
public void startingServerInstance() throws Exception {
if (prop.getProperty("APP_TYPE").equalsIgnoreCase("web")) {
driver = new AndroidDriver<>(appiumMan.getAppiumUrl(), androidWeb());
} else {
if (System.getProperty("os.name").toLowerCase().contains("mac")) {
if (iosDevice.checkiOSDevice(device_udid)) {
driver = new IOSDriver<>(appiumMan.getAppiumUrl(), iosNative());
} else if (!iosDevice.checkiOSDevice(device_udid)) {
driver = new AndroidDriver<>(appiumMan.getAppiumUrl(), androidNative());
}
} else {
driver = new AndroidDriver<>(appiumMan.getAppiumUrl(), androidNative());
}
}
}
#location 5
#vulnerability type NULL_DEREFERENCE
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
public static void main(String[] args) throws IOException {
String logo = "http://sauceio.com/wp-content/uploads/2014/04/appium_logo_final.png";
StringBuilder sb = new StringBuilder();
String a = "testcasepassed";
sb.append("<html>");
sb.append("<head>");
sb.append("<title>Automation Results");
sb.append("</title>");
sb.append("</head>");
sb.append("<body BGCOLOR='white'> <center><img src=" + logo + " ALIGN='center'></center>");
sb.append("</body>");
sb.append("<div style=float:left>");
sb.append("<table BORDER='1' ALIGN='center' width='320'>");
sb.append("<tr><th>TestClassName</th></tr>");
sb.append("<tr><TH><a href=#><center><font color='green'>" + a + "</font></center></a></TH>");
sb.append("</tr>");
sb.append("</table>");
sb.append("</div>");
sb.append("<div style=float:left>");
sb.append("<table BORDER='1' ALIGN='center' width='320'>");
sb.append("<tr><th>TestClassMethod</th></tr>");
sb.append("<tr><TH><a href=#><center><font color='red'>" + a + "</font></center></a></TH>");
sb.append("</tr>");
sb.append("</table>");
sb.append("</div>");
sb.append("</html>");
System.out.println(sb.toString());
FileWriter fstream = new FileWriter("MyHtml.html");
BufferedWriter out = new BufferedWriter(fstream);
out.write(sb.toString());
out.close();
}
|
#vulnerable code
public static void main(String[] args) {
// TODO Auto-generated method stub
// List<Class> testCases = new ArrayList<Class>();
// testCases.add(HomePageTest1.class);
// testCases.add(HomePageTest2.class);
// testCases.add(HomePageTest3.class);
// testCases.add(HomePageTest4.class);
// testCases.add(HomePageTest5.class);
List textFiles = new ArrayList();
File dir = new File(System.getProperty("user.dir") + "/src/test/java/com/test/site");
for (File file : dir.listFiles()) {
if (file.getName().contains(("Test"))) {
textFiles.add(file.getClass().getClassLoader());
}
}
}
#location 13
#vulnerability type NULL_DEREFERENCE
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
public void startingServerInstance() throws Exception {
startingServerInstance(null, null);
}
|
#vulnerable code
public void startingServerInstance() throws Exception {
if (prop.getProperty("APP_TYPE").equalsIgnoreCase("web")) {
driver = new AndroidDriver<>(appiumMan.getAppiumUrl(), androidWeb());
} else {
if (System.getProperty("os.name").toLowerCase().contains("mac")) {
if (iosDevice.checkiOSDevice(device_udid)) {
driver = new IOSDriver<>(appiumMan.getAppiumUrl(), iosNative());
} else if (!iosDevice.checkiOSDevice(device_udid)) {
driver = new AndroidDriver<>(appiumMan.getAppiumUrl(), androidNative());
}
} else {
driver = new AndroidDriver<>(appiumMan.getAppiumUrl(), androidNative());
}
}
}
#location 9
#vulnerability type THREAD_SAFETY_VIOLATION
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
@Test
public static void testApp() throws Exception {
ParallelThread parallelThread = new ParallelThread();
List<String> tests = new ArrayList<>();
tests.add("HomePageTest3");
tests.add("HomePageTest2");
boolean hasFailures = parallelThread.runner("com.test.site",tests);
Assert.assertFalse(hasFailures, "Testcases have failed in parallel execution");
}
|
#vulnerable code
@Test
public static void testApp() throws Exception {
ParallelThread parallelThread = new ParallelThread();
List<String> tests = new ArrayList<>();
//tests.add("HomePageTest1");
//tests.add("HomePageTest2");
boolean hasFailures = parallelThread.runner("com.test.site");
Assert.assertFalse(hasFailures, "Testcases have failed in parallel execution");
}
#location 8
#vulnerability type RESOURCE_LEAK
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
protected void processIsInJarAndlastModified() {
if ("file".equalsIgnoreCase(url.getProtocol())) {
isInJar = false;
lastModified = new File(url.getFile()).lastModified();
} else {
isInJar = true;
lastModified = -1;
}
}
|
#vulnerable code
protected void processIsInJarAndlastModified() {
try {
URLConnection conn = url.openConnection();
if ("jar".equals(url.getProtocol()) || conn instanceof JarURLConnection) {
isInJar = true;
lastModified = -1;
} else {
isInJar = false;
lastModified = conn.getLastModified();
}
} catch (IOException e) {
throw new RuntimeException(e);
}
}
#location 9
#vulnerability type RESOURCE_LEAK
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
protected long getLastModified() {
return new File(url.getFile()).lastModified();
}
|
#vulnerable code
protected long getLastModified() {
try {
URLConnection conn = url.openConnection();
return conn.getLastModified();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
#location 4
#vulnerability type RESOURCE_LEAK
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
protected long getLastModified() {
return new File(url.getFile()).lastModified();
}
|
#vulnerable code
protected long getLastModified() {
try {
URLConnection conn = url.openConnection();
return conn.getLastModified();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
#location 4
#vulnerability type RESOURCE_LEAK
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
private boolean hookExist() throws IOException {
GHRepository ghRepository = getGitHubRepo();
if (ghRepository == null) {
throw new IOException("Unable to get repo [ " + reponame + " ]");
}
for (GHHook h : ghRepository.getHooks()) {
if (!"web".equals(h.getName())) {
continue;
}
if (!getHookUrl().equals(h.getConfig().get("url"))) {
continue;
}
return true;
}
return false;
}
|
#vulnerable code
private boolean hookExist() throws IOException {
GHRepository ghRepository = getGitHubRepo();
for (GHHook h : ghRepository.getHooks()) {
if (!"web".equals(h.getName())) {
continue;
}
if (!getHookUrl().equals(h.getConfig().get("url"))) {
continue;
}
return true;
}
return false;
}
#location 3
#vulnerability type NULL_DEREFERENCE
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
@Override
public Environment setUpEnvironment(@SuppressWarnings("rawtypes") AbstractBuild build, Launcher launcher, BuildListener listener) throws IOException, InterruptedException, Run.RunnerAbortedException {
GhprbTrigger trigger = Ghprb.extractTrigger(build);
if (trigger != null && trigger.getBuilds() != null) {
trigger.getBuilds().onEnvironmentSetup(build, launcher, listener);
}
return new hudson.model.Environment(){};
}
|
#vulnerable code
@Override
public Environment setUpEnvironment(@SuppressWarnings("rawtypes") AbstractBuild build, Launcher launcher, BuildListener listener) throws IOException, InterruptedException, Run.RunnerAbortedException {
GhprbTrigger trigger = Ghprb.extractTrigger(build);
if (trigger != null) {
trigger.getBuilds().onEnvironmentSetup(build, launcher, listener);
}
return new hudson.model.Environment(){};
}
#location 5
#vulnerability type NULL_DEREFERENCE
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
public void check(Map<Integer,GhprbPullRequest> pulls){
if(repo == null) try {
repo = gh.getRepository(reponame);
if(repo == null){
Logger.getLogger(GhprbRepo.class.getName()).log(Level.SEVERE, "Could not retrieve repo named {0} (Do you have properly set 'GitHub project' field in job configuration?)", reponame);
}
} catch (IOException ex) {
Logger.getLogger(GhprbRepo.class.getName()).log(Level.SEVERE, "Could not retrieve repo named " + reponame + " (Do you have properly set 'GitHub project' field in job configuration?)", ex);
}
List<GHPullRequest> prs;
try {
prs = repo.getPullRequests(GHIssueState.OPEN);
} catch (IOException ex) {
Logger.getLogger(GhprbRepo.class.getName()).log(Level.SEVERE, "Could not retrieve pull requests.", ex);
return;
}
Set<Integer> closedPulls = new HashSet<Integer>(pulls.keySet());
for(GHPullRequest pr : prs){
Integer id = pr.getNumber();
GhprbPullRequest pull;
if(pulls.containsKey(id)){
pull = pulls.get(id);
}else{
pull = new GhprbPullRequest(pr, this);
pulls.put(id, pull);
}
pull.check(pr,this);
closedPulls.remove(id);
}
removeClosed(closedPulls, pulls);
checkBuilds();
}
|
#vulnerable code
public void check(Map<Integer,GhprbPullRequest> pulls){
if(repo == null) try {
repo = gh.getRepository(reponame);
if(repo == null){
Logger.getLogger(GhprbRepo.class.getName()).log(Level.SEVERE, "Could not retrieve repo named {0} (Do you have properly set 'GitHub project' field in job configuration?)", reponame);
}
} catch (IOException ex) {
Logger.getLogger(GhprbRepo.class.getName()).log(Level.SEVERE, "Could not retrieve repo named " + reponame + " (Do you have properly set 'GitHub project' field in job configuration?)", ex);
}
List<GHPullRequest> prs;
try {
prs = repo.getPullRequests(GHIssueState.OPEN);
} catch (IOException ex) {
Logger.getLogger(GhprbRepo.class.getName()).log(Level.SEVERE, "Could not retrieve pull requests.", ex);
return;
}
Set<Integer> closedPulls = new HashSet<Integer>(pulls.keySet());
for(GHPullRequest pr : prs){
Integer id = pr.getNumber();
GhprbPullRequest pull;
if(pulls.containsKey(id)){
pull = pulls.get(id);
}else{
pull = new GhprbPullRequest(pr, this);
pulls.put(id, pull);
}
try {
pull.check(pr,this);
} catch (IOException ex) {
Logger.getLogger(GhprbRepo.class.getName()).log(Level.SEVERE, "Couldn't check pull request #" + id, ex);
}
closedPulls.remove(id);
}
removeClosed(closedPulls, pulls);
checkBuilds();
}
#location 12
#vulnerability type NULL_DEREFERENCE
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
@Override
public boolean perform(AbstractBuild<?, ?> build, Launcher launcher, final BuildListener listener) throws InterruptedException, IOException {
AbstractProject<?, ?> project = build.getProject();
if (build.getResult().isWorseThan(Result.SUCCESS)) {
logger.log(Level.INFO, "Build did not succeed, merge will not be run");
return true;
}
trigger = GhprbTrigger.extractTrigger(project);
if (trigger == null) return false;
cause = getCause(build);
if (cause == null) {
return true;
}
ConcurrentMap<Integer, GhprbPullRequest> pulls = trigger.getDescriptor().getPullRequests(project.getName());
pr = pulls.get(cause.getPullID()).getPullRequest();
if (pr == null) {
logger.log(Level.INFO, "Pull request is null for ID: " + cause.getPullID());
return false;
}
Boolean isMergeable = cause.isMerged();
helper = new Ghprb(project, trigger, pulls);
helper.init();
if (isMergeable == null || !isMergeable) {
logger.log(Level.INFO, "Pull request cannot be automerged, moving on.");
commentOnRequest("Pull request is not mergeable.");
return true;
}
GHUser triggerSender = cause.getTriggerSender();
boolean merge = true;
if (isOnlyAdminsMerge() && !helper.isAdmin(triggerSender.getLogin())){
merge = false;
logger.log(Level.INFO, "Only admins can merge this pull request, {0} is not an admin.",
new Object[]{triggerSender.getLogin()});
commentOnRequest(
String.format("Code not merged because %s is not in the Admin list.",
triggerSender.getName()));
}
if (isOnlyTriggerPhrase() && !helper.isTriggerPhrase(cause.getCommentBody())) {
merge = false;
logger.log(Level.INFO, "The comment does not contain the required trigger phrase.");
commentOnRequest(
String.format("Please comment with '%s' to automerge this request",
trigger.getTriggerPhrase()));
}
if (isDisallowOwnCode() && isOwnCode(pr, triggerSender)) {
merge = false;
logger.log(Level.INFO, "The commentor is also one of the contributors.");
commentOnRequest(
String.format("Code not merged because %s has committed code in the request.",
triggerSender.getName()));
}
if (merge) {
logger.log(Level.INFO, "Merging the pull request");
pr.merge(getMergeComment());
logger.log(Level.INFO, "Pull request successfully merged");
// deleteBranch(); //TODO: Update so it also deletes the branch being pulled from. probably make it an option.
}
return merge;
}
|
#vulnerable code
@Override
public boolean perform(AbstractBuild<?, ?> build, Launcher launcher, final BuildListener listener) throws InterruptedException, IOException {
AbstractProject<?, ?> project = build.getProject();
if (build.getResult().isWorseThan(Result.SUCCESS)) {
logger.log(Level.INFO, "Build did not succeed, merge will not be run");
return true;
}
trigger = GhprbTrigger.extractTrigger(project);
if (trigger == null) return false;
ConcurrentMap<Integer, GhprbPullRequest> pulls = trigger.getDescriptor().getPullRequests(project.getName());
helper = new Ghprb(project, trigger, pulls);
helper.getRepository().init();
cause = getCause(build);
if (cause == null) {
return true;
}
pr = helper.getRepository().getPullRequest(cause.getPullID());
if (pr == null) {
logger.log(Level.INFO, "Pull request is null for ID: " + cause.getPullID());
return false;
}
Boolean isMergeable = pr.getMergeable();
int counter = 0;
while (counter++ < 15) {
if (isMergeable != null) {
break;
}
try {
logger.log(Level.INFO, "Waiting for github to settle so we can check if the PR is mergeable.");
Thread.sleep(1000);
} catch (Exception e) {
}
isMergeable = pr.getMergeable();
}
if (isMergeable == null || isMergeable) {
logger.log(Level.INFO, "Pull request cannot be automerged, moving on.");
commentOnRequest("Pull request is not mergeable.");
return true;
}
GHUser commentor = cause.getTriggerSender();
boolean merge = true;
if (isOnlyAdminsMerge() && !helper.isAdmin(commentor.getLogin())){
merge = false;
logger.log(Level.INFO, "Only admins can merge this pull request, {0} is not an admin.",
new Object[]{commentor.getLogin()});
commentOnRequest(
String.format("Code not merged because %s is not in the Admin list.",
commentor.getName()));
}
if (isOnlyTriggerPhrase() && !helper.isTriggerPhrase(cause.getCommentBody())) {
merge = false;
logger.log(Level.INFO, "The comment does not contain the required trigger phrase.");
commentOnRequest(
String.format("Please comment with '%s' to automerge this request",
trigger.getTriggerPhrase()));
return true;
}
if (isDisallowOwnCode() && isOwnCode(pr, commentor)) {
merge = false;
logger.log(Level.INFO, "The commentor is also one of the contributors.");
commentOnRequest(
String.format("Code not merged because %s has committed code in the request.",
commentor.getName()));
}
if (merge) {
logger.log(Level.INFO, "Merging the pull request");
pr.merge(getMergeComment());
// deleteBranch(); //TODO: Update so it also deletes the branch being pulled from. probably make it an option.
}
return merge;
}
#location 15
#vulnerability type NULL_DEREFERENCE
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
public boolean cancelBuild(int id) {
Iterator<GhprbBuild> it = builds.iterator();
while(it.hasNext()){
GhprbBuild build = it.next();
if (build.getPullID() == id) {
if (build.cancel()) {
it.remove();
return true;
}
}
}
return false;
}
|
#vulnerable code
public boolean cancelBuild(int id) {
if(queuedBuilds.containsKey(id)){
try {
Run<?,?> build = (Run) queuedBuilds.get(id).waitForStart();
if(build.getExecutor() == null) return false;
build.getExecutor().interrupt();
queuedBuilds.remove(id);
return true;
} catch (Exception ex) {
Logger.getLogger(GhprbRepo.class.getName()).log(Level.WARNING, null, ex);
return false;
}
}else if(runningBuilds.containsKey(id)){
try {
Run<?,?> build = (Run) runningBuilds.get(id).waitForStart();
if(build.getExecutor() == null) return false;
build.getExecutor().interrupt();
runningBuilds.remove(id);
return true;
} catch (Exception ex) {
Logger.getLogger(GhprbRepo.class.getName()).log(Level.WARNING, null, ex);
return false;
}
}else{
return false;
}
}
#location 4
#vulnerability type NULL_DEREFERENCE
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
@Override
public void onCompleted(AbstractBuild<?, ?> build, TaskListener listener) {
GhprbTrigger trigger = Ghprb.extractTrigger(build);
if (trigger != null && trigger.getBuilds() != null) {
trigger.getBuilds().onCompleted(build, listener);
}
}
|
#vulnerable code
@Override
public void onCompleted(AbstractBuild<?, ?> build, TaskListener listener) {
GhprbTrigger trigger = Ghprb.extractTrigger(build);
if (trigger != null) {
trigger.getBuilds().onCompleted(build, listener);
}
}
#location 5
#vulnerability type NULL_DEREFERENCE
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
@Override
public void onStarted(AbstractBuild<?, ?> build, TaskListener listener) {
GhprbTrigger trigger = Ghprb.extractTrigger(build);
if (trigger != null && trigger.getBuilds() != null) {
trigger.getBuilds().onStarted(build, listener);
}
}
|
#vulnerable code
@Override
public void onStarted(AbstractBuild<?, ?> build, TaskListener listener) {
GhprbTrigger trigger = Ghprb.extractTrigger(build);
if (trigger != null) {
trigger.getBuilds().onStarted(build, listener);
}
}
#location 5
#vulnerability type NULL_DEREFERENCE
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
public void check(GHIssueComment comment) {
if (helper.isProjectDisabled()) {
logger.log(Level.FINE, "Project is disabled, ignoring comment");
return;
}
synchronized (this) {
try {
checkComment(comment);
} catch (IOException ex) {
logger.log(Level.SEVERE, "Couldn't check comment #" + comment.getId(), ex);
return;
}
try {
GHUser user = null;
try {
user = comment.getUser();
} catch (IOException e) {
logger.log(Level.SEVERE, "Couldn't get the user that made the comment", e);
}
updatePR(getPullRequest(true), user);
} catch (IOException ex) {
logger.log(Level.SEVERE, "Unable to get a new copy of the pull request!");
}
tryBuild();
}
}
|
#vulnerable code
public void check(GHIssueComment comment) {
if (helper.isProjectDisabled()) {
logger.log(Level.FINE, "Project is disabled, ignoring comment");
return;
}
synchronized (this) {
try {
checkComment(comment);
} catch (IOException ex) {
logger.log(Level.SEVERE, "Couldn't check comment #" + comment.getId(), ex);
return;
}
try {
GHUser user = null;
try {
user = comment.getUser();
} catch (IOException e) {
logger.log(Level.SEVERE, "Couldn't get the user that made the comment", e);
}
updatePR(getPullRequest(true), user);
} catch (IOException ex) {
logger.log(Level.SEVERE, "Unable to get a new copy of the pull request!");
}
checkSkipBuild(comment.getParent());
tryBuild();
}
}
#location 2
#vulnerability type THREAD_SAFETY_VIOLATION
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
public void check(GHPullRequest ghpr) {
setPullRequest(ghpr);
if (helper.isProjectDisabled()) {
logger.log(Level.FINE, "Project is disabled, ignoring pull request");
return;
}
try {
getPullRequest(false);
} catch (IOException e) {
logger.log(Level.SEVERE, "Unable to get the latest copy of the PR from github", e);
return;
}
updatePR(pr, pr.getUser());
tryBuild();
}
|
#vulnerable code
public void check(GHPullRequest ghpr) {
setPullRequest(ghpr);
if (helper.isProjectDisabled()) {
logger.log(Level.FINE, "Project is disabled, ignoring pull request");
return;
}
try {
getPullRequest(false);
} catch (IOException e) {
logger.log(Level.SEVERE, "Unable to get the latest copy of the PR from github", e);
return;
}
updatePR(pr, pr.getUser());
checkSkipBuild(pr);
tryBuild();
}
#location 3
#vulnerability type THREAD_SAFETY_VIOLATION
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
public void check(GHPullRequest ghpr) {
setPullRequest(ghpr);
if (helper.isProjectDisabled()) {
logger.log(Level.FINE, "Project is disabled, ignoring pull request");
return;
}
try {
getPullRequest(false);
} catch (IOException e) {
logger.log(Level.SEVERE, "Unable to get the latest copy of the PR from github", e);
return;
}
updatePR(pr, pr.getUser());
tryBuild();
}
|
#vulnerable code
public void check(GHPullRequest ghpr) {
setPullRequest(ghpr);
if (helper.isProjectDisabled()) {
logger.log(Level.FINE, "Project is disabled, ignoring pull request");
return;
}
try {
getPullRequest(false);
} catch (IOException e) {
logger.log(Level.SEVERE, "Unable to get the latest copy of the PR from github", e);
return;
}
updatePR(pr, pr.getUser());
checkSkipBuild(pr);
tryBuild();
}
#location 17
#vulnerability type THREAD_SAFETY_VIOLATION
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
private boolean initGhRepository() {
GitHub gitHub = null;
try {
GhprbGitHub repo = helper.getGitHub();
if (repo == null) {
return false;
}
gitHub = repo.get();
if (gitHub == null) {
logger.log(Level.SEVERE, "No connection returned to GitHub server!");
return false;
}
if (gitHub.getRateLimit().remaining == 0) {
return false;
}
} catch (FileNotFoundException ex) {
logger.log(Level.INFO, "Rate limit API not found.");
} catch (IOException ex) {
logger.log(Level.SEVERE, "Error while accessing rate limit API", ex);
return false;
}
if (ghRepository == null) {
try {
ghRepository = gitHub.getRepository(reponame);
} catch (IOException ex) {
logger.log(Level.SEVERE, "Could not retrieve GitHub repository named " + reponame + " (Do you have properly set 'GitHub project' field in job configuration?)", ex);
return false;
}
}
return true;
}
|
#vulnerable code
private boolean initGhRepository() {
GitHub gitHub = null;
try {
GhprbGitHub repo = helper.getGitHub();
if (repo == null) {
return false;
}
gitHub = repo.get();
if (gitHub.getRateLimit().remaining == 0) {
return false;
}
} catch (FileNotFoundException ex) {
logger.log(Level.INFO, "Rate limit API not found.");
} catch (IOException ex) {
logger.log(Level.SEVERE, "Error while accessing rate limit API", ex);
return false;
}
if (ghRepository == null) {
try {
ghRepository = gitHub.getRepository(reponame);
} catch (IOException ex) {
logger.log(Level.SEVERE, "Could not retrieve GitHub repository named " + reponame + " (Do you have properly set 'GitHub project' field in job configuration?)", ex);
return false;
}
}
return true;
}
#location 9
#vulnerability type NULL_DEREFERENCE
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
public QueueTaskFuture<?> startJob(GhprbCause cause, GhprbRepository repo) {
for (GhprbExtension ext : Ghprb.getJobExtensions(this, GhprbBuildStep.class)) {
if (ext instanceof GhprbBuildStep) {
((GhprbBuildStep)ext).onStartBuild(super.job, cause);
}
}
ArrayList<ParameterValue> values = getDefaultParameters();
final String commitSha = cause.isMerged() ? "origin/pr/" + cause.getPullID() + "/merge" : cause.getCommit();
values.add(new StringParameterValue("sha1", commitSha));
values.add(new StringParameterValue("ghprbActualCommit", cause.getCommit()));
String triggerAuthor = "";
String triggerAuthorEmail = "";
String triggerAuthorLogin = "";
GhprbPullRequest pr = getRepository().getPullRequest(cause.getPullID());
String lastBuildId = pr.getLastBuildId();
BuildData buildData = null;
if (!(job instanceof MatrixProject) && !StringUtils.isEmpty(lastBuildId)) {
AbstractBuild<?, ?> lastBuild = job.getBuild(lastBuildId);
buildData = lastBuild.getAction(BuildData.class);
}
try {
triggerAuthor = getString(cause.getTriggerSender().getName(), "");
} catch (Exception e) {}
try {
triggerAuthorEmail = getString(cause.getTriggerSender().getEmail(), "");
} catch (Exception e) {}
try {
triggerAuthorLogin = getString(cause.getTriggerSender().getLogin(), "");
} catch (Exception e) {}
setCommitAuthor(cause, values);
values.add(new StringParameterValue("ghprbAuthorRepoGitUrl", getString(cause.getAuthorRepoGitUrl(), "")));
values.add(new StringParameterValue("ghprbTriggerAuthor", triggerAuthor));
values.add(new StringParameterValue("ghprbTriggerAuthorEmail", triggerAuthorEmail));
values.add(new StringParameterValue("ghprbTriggerAuthorLogin", triggerAuthorLogin));
values.add(new StringParameterValue("ghprbTriggerAuthorLoginMention", !triggerAuthorLogin.isEmpty() ? "@"
+ triggerAuthorLogin : ""));
final StringParameterValue pullIdPv = new StringParameterValue("ghprbPullId", String.valueOf(cause.getPullID()));
values.add(pullIdPv);
values.add(new StringParameterValue("ghprbTargetBranch", String.valueOf(cause.getTargetBranch())));
values.add(new StringParameterValue("ghprbSourceBranch", String.valueOf(cause.getSourceBranch())));
values.add(new StringParameterValue("GIT_BRANCH", String.valueOf(cause.getSourceBranch())));
// it's possible the GHUser doesn't have an associated email address
values.add(new StringParameterValue("ghprbPullAuthorEmail", getString(cause.getAuthorEmail(), "")));
values.add(new StringParameterValue("ghprbPullAuthorLogin", String.valueOf(cause.getPullRequestAuthor().getLogin())));
values.add(new StringParameterValue("ghprbPullAuthorLoginMention", "@" + cause.getPullRequestAuthor().getLogin()));
values.add(new StringParameterValue("ghprbPullDescription", escapeText(String.valueOf(cause.getShortDescription()))));
values.add(new StringParameterValue("ghprbPullTitle", String.valueOf(cause.getTitle())));
values.add(new StringParameterValue("ghprbPullLink", String.valueOf(cause.getUrl())));
values.add(new StringParameterValue("ghprbPullLongDescription", escapeText(String.valueOf(cause.getDescription()))));
values.add(new StringParameterValue("ghprbCommentBody", escapeText(String.valueOf(cause.getCommentBody()))));
values.add(new StringParameterValue("ghprbGhRepository", repo.getName()));
values.add(new StringParameterValue("ghprbCredentialsId", getString(getGitHubApiAuth().getCredentialsId(), "")));
// add the previous pr BuildData as an action so that the correct change log is generated by the GitSCM plugin
// note that this will be removed from the Actions list after the job is completed so that the old (and incorrect)
// one isn't there
return this.job.scheduleBuild2(job.getQuietPeriod(), cause, new ParametersAction(values), buildData);
}
|
#vulnerable code
public QueueTaskFuture<?> startJob(GhprbCause cause, GhprbRepository repo) {
ArrayList<ParameterValue> values = getDefaultParameters();
final String commitSha = cause.isMerged() ? "origin/pr/" + cause.getPullID() + "/merge" : cause.getCommit();
values.add(new StringParameterValue("sha1", commitSha));
values.add(new StringParameterValue("ghprbActualCommit", cause.getCommit()));
String triggerAuthor = "";
String triggerAuthorEmail = "";
String triggerAuthorLogin = "";
GhprbPullRequest pr = getRepository().getPullRequest(cause.getPullID());
String lastBuildId = pr.getLastBuildId();
BuildData buildData = null;
if (!(job instanceof MatrixProject) && !StringUtils.isEmpty(lastBuildId)) {
AbstractBuild<?, ?> lastBuild = job.getBuild(lastBuildId);
buildData = lastBuild.getAction(BuildData.class);
}
try {
triggerAuthor = getString(cause.getTriggerSender().getName(), "");
} catch (Exception e) {}
try {
triggerAuthorEmail = getString(cause.getTriggerSender().getEmail(), "");
} catch (Exception e) {}
try {
triggerAuthorLogin = getString(cause.getTriggerSender().getLogin(), "");
} catch (Exception e) {}
setCommitAuthor(cause, values);
values.add(new StringParameterValue("ghprbAuthorRepoGitUrl", getString(cause.getAuthorRepoGitUrl(), "")));
values.add(new StringParameterValue("ghprbTriggerAuthor", triggerAuthor));
values.add(new StringParameterValue("ghprbTriggerAuthorEmail", triggerAuthorEmail));
values.add(new StringParameterValue("ghprbTriggerAuthorLogin", triggerAuthorLogin));
values.add(new StringParameterValue("ghprbTriggerAuthorLoginMention", !triggerAuthorLogin.isEmpty() ? "@"
+ triggerAuthorLogin : ""));
final StringParameterValue pullIdPv = new StringParameterValue("ghprbPullId", String.valueOf(cause.getPullID()));
values.add(pullIdPv);
values.add(new StringParameterValue("ghprbTargetBranch", String.valueOf(cause.getTargetBranch())));
values.add(new StringParameterValue("ghprbSourceBranch", String.valueOf(cause.getSourceBranch())));
values.add(new StringParameterValue("GIT_BRANCH", String.valueOf(cause.getSourceBranch())));
// it's possible the GHUser doesn't have an associated email address
values.add(new StringParameterValue("ghprbPullAuthorEmail", getString(cause.getAuthorEmail(), "")));
values.add(new StringParameterValue("ghprbPullAuthorLogin", String.valueOf(cause.getPullRequestAuthor().getLogin())));
values.add(new StringParameterValue("ghprbPullAuthorLoginMention", "@" + cause.getPullRequestAuthor().getLogin()));
values.add(new StringParameterValue("ghprbPullDescription", escapeText(String.valueOf(cause.getShortDescription()))));
values.add(new StringParameterValue("ghprbPullTitle", String.valueOf(cause.getTitle())));
values.add(new StringParameterValue("ghprbPullLink", String.valueOf(cause.getUrl())));
values.add(new StringParameterValue("ghprbPullLongDescription", escapeText(String.valueOf(cause.getDescription()))));
values.add(new StringParameterValue("ghprbCommentBody", escapeText(String.valueOf(cause.getCommentBody()))));
values.add(new StringParameterValue("ghprbGhRepository", repo.getName()));
values.add(new StringParameterValue("ghprbCredentialsId", getString(getGitHubApiAuth().getCredentialsId(), "")));
// add the previous pr BuildData as an action so that the correct change log is generated by the GitSCM plugin
// note that this will be removed from the Actions list after the job is completed so that the old (and incorrect)
// one isn't there
return this.job.scheduleBuild2(job.getQuietPeriod(), cause, new ParametersAction(values), buildData);
}
#location 10
#vulnerability type NULL_DEREFERENCE
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
public void check(GHPullRequest ghpr) {
setPullRequest(ghpr);
if (helper.isProjectDisabled()) {
logger.log(Level.FINE, "Project is disabled, ignoring pull request");
return;
}
try {
getPullRequest(false);
} catch (IOException e) {
logger.log(Level.SEVERE, "Unable to get the latest copy of the PR from github", e);
return;
}
updatePR(pr, pr.getUser());
tryBuild();
}
|
#vulnerable code
public void check(GHPullRequest ghpr) {
setPullRequest(ghpr);
if (helper.isProjectDisabled()) {
logger.log(Level.FINE, "Project is disabled, ignoring pull request");
return;
}
try {
getPullRequest(false);
} catch (IOException e) {
logger.log(Level.SEVERE, "Unable to get the latest copy of the PR from github", e);
return;
}
updatePR(pr, pr.getUser());
checkSkipBuild(pr);
tryBuild();
}
#location 18
#vulnerability type THREAD_SAFETY_VIOLATION
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
@Override
public void makeBuildVariables(@SuppressWarnings("rawtypes") AbstractBuild build, Map<String,String> variables){
variables.put("ghprbUpstreamStatus", "true");
variables.put("ghprbCommitStatusContext", commitStatusContext);
variables.put("ghprbTriggeredStatus", triggeredStatus);
variables.put("ghprbStartedStatus", startedStatus);
variables.put("ghprbStatusUrl", statusUrl);
Map<GHCommitState, StringBuilder> statusMessages = new HashMap<GHCommitState, StringBuilder>(5);
for (GhprbBuildResultMessage message : completedStatus) {
GHCommitState state = message.getResult();
StringBuilder sb;
if (!statusMessages.containsKey(state)) {
sb = new StringBuilder();
statusMessages.put(state, sb);
} else {
sb = statusMessages.get(state);
sb.append("\n");
}
sb.append(message.getMessage());
}
for (Entry<GHCommitState, StringBuilder> next : statusMessages.entrySet()) {
String key = String.format("ghprb%sMessage", next.getKey().name());
variables.put(key, next.getValue().toString());
}
}
|
#vulnerable code
@Override
public void makeBuildVariables(@SuppressWarnings("rawtypes") AbstractBuild build, Map<String,String> variables){
variables.put("ghprbUpstreamStatus", "true");
variables.put("ghprbCommitStatusContext", commitStatusContext);
variables.put("ghprbTriggeredStatus", triggeredStatus);
variables.put("ghprbStartedStatus", startedStatus);
variables.put("ghprbStatusUrl", statusUrl);
Map<GHCommitState, StringBuilder> statusMessages = new HashMap<GHCommitState, StringBuilder>(5);
for (GhprbBuildResultMessage message : completedStatus) {
GHCommitState state = message.getResult();
StringBuilder sb;
if (statusMessages.containsKey(state)){
sb = new StringBuilder();
statusMessages.put(state, sb);
} else {
sb = statusMessages.get(state);
sb.append("\n");
}
sb.append(message.getMessage());
}
for (Entry<GHCommitState, StringBuilder> next : statusMessages.entrySet()) {
String key = String.format("ghprb%sMessage", next.getKey().name());
variables.put(key, next.getValue().toString());
}
}
#location 19
#vulnerability type NULL_DEREFERENCE
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
public void onStarted(AbstractBuild<?, ?> build, TaskListener listener) {
PrintStream logger = listener.getLogger();
GhprbCause c = Ghprb.getCause(build);
if (c == null) {
return;
}
GhprbTrigger trigger = Ghprb.extractTrigger(build);
ConcurrentMap<Integer, GhprbPullRequest> pulls = trigger.getDescriptor().getPullRequests(build.getProject().getFullName());
GHPullRequest pr = pulls.get(c.getPullID()).getPullRequest();
try {
int counter = 0;
// If the PR is being resolved by GitHub then getMergeable will return null
Boolean isMergeable = pr.getMergeable();
Boolean isMerged = pr.isMerged();
// Not sure if isMerged can return null, but adding if just in case
if (isMerged == null) {
isMerged = false;
}
while (isMergeable == null && !isMerged && counter++ < 60) {
Thread.sleep(1000);
isMergeable = pr.getMergeable();
isMerged = pr.isMerged();
if (isMerged == null) {
isMerged = false;
}
}
if (isMerged) {
logger.println("PR has already been merged, builds using the merged sha1 will fail!!!");
} else if (isMergeable == null) {
logger.println("PR merge status couldn't be retrieved, maybe GitHub hasn't settled yet");
} else if (isMergeable != c.isMerged()) {
logger.println("!!! PR mergeability status has changed !!! ");
if (isMergeable) {
logger.println("PR now has NO merge conflicts");
} else if (!isMergeable) {
logger.println("PR now has merge conflicts!");
}
}
} catch (Exception e) {
logger.print("Unable to query GitHub for status of PullRequest");
e.printStackTrace(logger);
}
for (GhprbExtension ext : Ghprb.getJobExtensions(trigger, GhprbCommitStatus.class)) {
if (ext instanceof GhprbCommitStatus) {
try {
((GhprbCommitStatus) ext).onBuildStart(build, listener, repo.getGitHubRepo());
} catch (GhprbCommitStatusException e) {
repo.commentOnFailure(build, listener, e);
}
}
}
try {
build.setDescription("<a title=\"" + c.getTitle() + "\" href=\"" + c.getUrl() + "\">PR #" + c.getPullID() + "</a>: " + c.getAbbreviatedTitle());
} catch (IOException ex) {
logger.println("Can't update build description");
ex.printStackTrace(logger);
}
}
|
#vulnerable code
public void onStarted(AbstractBuild<?, ?> build, TaskListener listener) {
PrintStream logger = listener.getLogger();
GhprbCause c = Ghprb.getCause(build);
if (c == null) {
return;
}
GhprbTrigger trigger = Ghprb.extractTrigger(build);
ConcurrentMap<Integer, GhprbPullRequest> pulls = trigger.getDescriptor().getPullRequests(build.getProject().getFullName());
GHPullRequest pr = pulls.get(c.getPullID()).getPullRequest();
try {
int counter = 0;
Boolean isMergeable = pr.getMergeable();
Boolean isMerged = pr.isMerged();
while (isMergeable == null && !isMerged && counter++ < 60) {
Thread.sleep(1000);
isMergeable = pr.getMergeable();
isMerged = pr.isMerged();
}
if (isMergeable != c.isMerged() || isMerged == true) {
logger.println("!!! PR status has changed !!! ");
if (isMergeable == null) {
if (isMerged) {
logger.println("PR has already been merged");
} else {
logger.println("PR merge status couldn't be retrieved, GitHub maybe hasn't settled yet");
}
} else if (isMergeable) {
logger.println("PR has NO merge conflicts");
} else if (!isMergeable) {
logger.println("PR has merge conflicts!");
}
}
} catch (Exception e) {
logger.print("Unable to query GitHub for status of PullRequest");
e.printStackTrace(logger);
}
for (GhprbExtension ext : Ghprb.getJobExtensions(trigger, GhprbCommitStatus.class)) {
if (ext instanceof GhprbCommitStatus) {
try {
((GhprbCommitStatus) ext).onBuildStart(build, listener, repo.getGitHubRepo());
} catch (GhprbCommitStatusException e) {
repo.commentOnFailure(build, listener, e);
}
}
}
try {
build.setDescription("<a title=\"" + c.getTitle() + "\" href=\"" + c.getUrl() + "\">PR #" + c.getPullID() + "</a>: " + c.getAbbreviatedTitle());
} catch (IOException ex) {
logger.println("Can't update build description");
ex.printStackTrace(logger);
}
}
#location 24
#vulnerability type NULL_DEREFERENCE
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
public void check(GHIssueComment comment) {
if (helper.isProjectDisabled()) {
logger.log(Level.FINE, "Project is disabled, ignoring comment");
return;
}
synchronized (this) {
try {
checkComment(comment);
} catch (IOException ex) {
logger.log(Level.SEVERE, "Couldn't check comment #" + comment.getId(), ex);
return;
}
try {
GHUser user = null;
try {
user = comment.getUser();
} catch (IOException e) {
logger.log(Level.SEVERE, "Couldn't get the user that made the comment", e);
}
updatePR(getPullRequest(true), user);
} catch (IOException ex) {
logger.log(Level.SEVERE, "Unable to get a new copy of the pull request!");
}
tryBuild();
}
}
|
#vulnerable code
public void check(GHIssueComment comment) {
if (helper.isProjectDisabled()) {
logger.log(Level.FINE, "Project is disabled, ignoring comment");
return;
}
synchronized (this) {
try {
checkComment(comment);
} catch (IOException ex) {
logger.log(Level.SEVERE, "Couldn't check comment #" + comment.getId(), ex);
return;
}
try {
GHUser user = null;
try {
user = comment.getUser();
} catch (IOException e) {
logger.log(Level.SEVERE, "Couldn't get the user that made the comment", e);
}
updatePR(getPullRequest(true), user);
} catch (IOException ex) {
logger.log(Level.SEVERE, "Unable to get a new copy of the pull request!");
}
checkSkipBuild(comment.getParent());
tryBuild();
}
}
#location 28
#vulnerability type THREAD_SAFETY_VIOLATION
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
public void check(GHPullRequest ghpr) {
setPullRequest(ghpr);
if (helper.isProjectDisabled()) {
logger.log(Level.FINE, "Project is disabled, ignoring pull request");
return;
}
try {
getPullRequest(false);
} catch (IOException e) {
logger.log(Level.SEVERE, "Unable to get the latest copy of the PR from github", e);
return;
}
updatePR(pr, pr.getUser());
tryBuild();
}
|
#vulnerable code
public void check(GHPullRequest ghpr) {
setPullRequest(ghpr);
if (helper.isProjectDisabled()) {
logger.log(Level.FINE, "Project is disabled, ignoring pull request");
return;
}
try {
getPullRequest(false);
} catch (IOException e) {
logger.log(Level.SEVERE, "Unable to get the latest copy of the PR from github", e);
return;
}
updatePR(pr, pr.getUser());
checkSkipBuild(pr);
tryBuild();
}
#location 15
#vulnerability type THREAD_SAFETY_VIOLATION
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
public void handleWebHook(String event, String payload, String body, String signature) {
GhprbRepository repo = trigger.getRepository();
String repoName = repo.getName();
logger.log(Level.INFO, "Got payload event: {0}", event);
try {
GitHub gh = trigger.getGitHub();
if ("issue_comment".equals(event)) {
GHEventPayload.IssueComment issueComment = gh.parseEventPayload(
new StringReader(payload),
GHEventPayload.IssueComment.class);
GHIssueState state = issueComment.getIssue().getState();
if (state == GHIssueState.CLOSED) {
logger.log(Level.INFO, "Skip comment on closed PR");
return;
}
if (matchRepo(repo, issueComment.getRepository())) {
if (!checkSignature(body, signature, trigger.getGitHubApiAuth().getSecret())){
return;
}
logger.log(Level.INFO, "Checking issue comment ''{0}'' for repo {1}",
new Object[] { issueComment.getComment(), repoName }
);
repo.onIssueCommentHook(issueComment);
}
} else if ("pull_request".equals(event)) {
GHEventPayload.PullRequest pr = gh.parseEventPayload(
new StringReader(payload),
GHEventPayload.PullRequest.class);
if (matchRepo(repo, pr.getPullRequest().getRepository())) {
if (!checkSignature(body, signature, trigger.getGitHubApiAuth().getSecret())){
return;
}
logger.log(Level.INFO, "Checking PR #{1} for {0}", new Object[] { repoName, pr.getNumber() });
repo.onPullRequestHook(pr);
}
} else {
logger.log(Level.WARNING, "Request not known");
}
} catch (IOException ex) {
logger.log(Level.SEVERE, "Failed to parse github hook payload for " + trigger.getProject(), ex);
}
}
|
#vulnerable code
public void handleWebHook(String event, String payload, String body, String signature) {
if (!checkSignature(body, signature, trigger.getGitHubApiAuth().getSecret())){
return;
}
GhprbRepository repo = trigger.getRepository();
String repoName = repo.getName();
logger.log(Level.INFO, "Got payload event: {0}", event);
try {
GitHub gh = trigger.getGitHub();
if ("issue_comment".equals(event)) {
GHEventPayload.IssueComment issueComment = gh.parseEventPayload(
new StringReader(payload),
GHEventPayload.IssueComment.class);
GHIssueState state = issueComment.getIssue().getState();
if (state == GHIssueState.CLOSED) {
logger.log(Level.INFO, "Skip comment on closed PR");
return;
}
if (matchRepo(repo, issueComment.getRepository())) {
logger.log(Level.INFO, "Checking issue comment ''{0}'' for repo {1}",
new Object[] { issueComment.getComment(), repoName }
);
repo.onIssueCommentHook(issueComment);
}
} else if ("pull_request".equals(event)) {
GHEventPayload.PullRequest pr = gh.parseEventPayload(
new StringReader(payload),
GHEventPayload.PullRequest.class);
if (matchRepo(repo, pr.getPullRequest().getRepository())) {
logger.log(Level.INFO, "Checking PR #{1} for {0}", new Object[] { repoName, pr.getNumber() });
repo.onPullRequestHook(pr);
}
} else {
logger.log(Level.WARNING, "Request not known");
}
} catch (IOException ex) {
logger.log(Level.SEVERE, "Failed to parse github hook payload for " + trigger.getProject(), ex);
}
}
#location 2
#vulnerability type NULL_DEREFERENCE
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
public void check(GHIssueComment comment) {
if (helper.isProjectDisabled()) {
logger.log(Level.FINE, "Project is disabled, ignoring comment");
return;
}
synchronized (this) {
try {
checkComment(comment);
} catch (IOException ex) {
logger.log(Level.SEVERE, "Couldn't check comment #" + comment.getId(), ex);
return;
}
try {
GHUser user = null;
try {
user = comment.getUser();
} catch (IOException e) {
logger.log(Level.SEVERE, "Couldn't get the user that made the comment", e);
}
updatePR(getPullRequest(true), user);
} catch (IOException ex) {
logger.log(Level.SEVERE, "Unable to get a new copy of the pull request!");
}
tryBuild();
}
}
|
#vulnerable code
public void check(GHIssueComment comment) {
if (helper.isProjectDisabled()) {
logger.log(Level.FINE, "Project is disabled, ignoring comment");
return;
}
synchronized (this) {
try {
checkComment(comment);
} catch (IOException ex) {
logger.log(Level.SEVERE, "Couldn't check comment #" + comment.getId(), ex);
return;
}
try {
GHUser user = null;
try {
user = comment.getUser();
} catch (IOException e) {
logger.log(Level.SEVERE, "Couldn't get the user that made the comment", e);
}
updatePR(getPullRequest(true), user);
} catch (IOException ex) {
logger.log(Level.SEVERE, "Unable to get a new copy of the pull request!");
}
checkSkipBuild(comment.getParent());
tryBuild();
}
}
#location 22
#vulnerability type THREAD_SAFETY_VIOLATION
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
@Test
public void findAllByIdReferenceConsistencyTest() {
when(this.objectToKeyFactory.getKeyFromObject(eq(this.childEntity1), any())).thenReturn(this.childEntity1.id);
when(this.datastore.fetch(eq(this.key1)))
.thenReturn(Arrays.asList(this.e1));
verifyBeforeAndAfterEvents(null,
new AfterFindByKeyEvent(Collections.singletonList(this.ob1), Collections.singleton(this.key1)),
() -> {
TestEntity parentEntity1 = this.datastoreTemplate.findById(this.key1, TestEntity.class);
assertThat(parentEntity1).isSameAs(this.ob1);
ChildEntity singularReference1 = parentEntity1.singularReference;
ChildEntity childEntity1 = parentEntity1.childEntities.get(0);
assertThat(singularReference1).isSameAs(childEntity1);
TestEntity parentEntity2 = this.datastoreTemplate.findById(this.key1, TestEntity.class);
assertThat(parentEntity2).isSameAs(this.ob1);
ChildEntity singularReference2 = parentEntity2.singularReference;
ChildEntity childEntity2 = parentEntity2.childEntities.get(0);
assertThat(singularReference2).isSameAs(childEntity2);
assertThat(childEntity1).isNotSameAs(childEntity2);
}, x -> {
});
}
|
#vulnerable code
@Test
public void findAllByIdReferenceConsistencyTest() {
when(this.objectToKeyFactory.getKeyFromObject(eq(this.childEntity1), any())).thenReturn(this.childEntity1.id);
when(this.datastore.fetch(eq(this.key1)))
.thenReturn(Arrays.asList(this.e1));
TestEntity parentEntity1 = this.datastoreTemplate.findById(this.key1, TestEntity.class);
assertThat(parentEntity1).isSameAs(this.ob1);
ChildEntity singularReference1 = parentEntity1.singularReference;
ChildEntity childEntity1 = parentEntity1.childEntities.get(0);
assertThat(singularReference1).isSameAs(childEntity1);
TestEntity parentEntity2 = this.datastoreTemplate.findById(this.key1, TestEntity.class);
assertThat(parentEntity2).isSameAs(this.ob1);
ChildEntity singularReference2 = parentEntity2.singularReference;
ChildEntity childEntity2 = parentEntity2.childEntities.get(0);
assertThat(singularReference2).isSameAs(childEntity2);
assertThat(childEntity1).isNotSameAs(childEntity2);
}
#location 16
#vulnerability type NULL_DEREFERENCE
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
@SuppressWarnings("unchecked")
private static Map<Class<?>, BiConsumer<ValueBinder<?>, Iterable>> createIterableTypeMapping() {
Map<Class<?>, BiConsumer<ValueBinder<?>, Iterable>> map = new LinkedHashMap<>();
map.put(com.google.cloud.Date.class, ValueBinder::toDateArray);
map.put(Boolean.class, ValueBinder::toBoolArray);
map.put(Long.class, ValueBinder::toInt64Array);
map.put(String.class, ValueBinder::toStringArray);
map.put(Double.class, ValueBinder::toFloat64Array);
map.put(Timestamp.class, ValueBinder::toTimestampArray);
map.put(ByteArray.class, ValueBinder::toBytesArray);
return Collections.unmodifiableMap(map);
}
|
#vulnerable code
@SuppressWarnings("unchecked")
private static Map<Class<?>, BiConsumer<ValueBinder<?>, Iterable>> createIterableTypeMapping() {
// Java 8 has compile errors when using the builder extension methods
// @formatter:off
ImmutableMap.Builder<Class<?>, BiConsumer<ValueBinder<?>, Iterable>> builder =
new ImmutableMap.Builder<>();
// @formatter:on
builder.put(com.google.cloud.Date.class, ValueBinder::toDateArray);
builder.put(Boolean.class, ValueBinder::toBoolArray);
builder.put(Long.class, ValueBinder::toInt64Array);
builder.put(String.class, ValueBinder::toStringArray);
builder.put(Double.class, ValueBinder::toFloat64Array);
builder.put(Timestamp.class, ValueBinder::toTimestampArray);
builder.put(ByteArray.class, ValueBinder::toBytesArray);
return builder.build();
}
#location 2
#vulnerability type CHECKERS_IMMUTABLE_CAST
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
@Test
public void findAllByIdReferenceConsistencyTest() {
when(this.objectToKeyFactory.getKeyFromObject(eq(this.childEntity1), any())).thenReturn(this.childEntity1.id);
when(this.datastore.fetch(eq(this.key1)))
.thenReturn(Arrays.asList(this.e1));
verifyBeforeAndAfterEvents(null,
new AfterFindByKeyEvent(Collections.singletonList(this.ob1), Collections.singleton(this.key1)),
() -> {
TestEntity parentEntity1 = this.datastoreTemplate.findById(this.key1, TestEntity.class);
assertThat(parentEntity1).isSameAs(this.ob1);
ChildEntity singularReference1 = parentEntity1.singularReference;
ChildEntity childEntity1 = parentEntity1.childEntities.get(0);
assertThat(singularReference1).isSameAs(childEntity1);
TestEntity parentEntity2 = this.datastoreTemplate.findById(this.key1, TestEntity.class);
assertThat(parentEntity2).isSameAs(this.ob1);
ChildEntity singularReference2 = parentEntity2.singularReference;
ChildEntity childEntity2 = parentEntity2.childEntities.get(0);
assertThat(singularReference2).isSameAs(childEntity2);
assertThat(childEntity1).isNotSameAs(childEntity2);
}, x -> {
});
}
|
#vulnerable code
@Test
public void findAllByIdReferenceConsistencyTest() {
when(this.objectToKeyFactory.getKeyFromObject(eq(this.childEntity1), any())).thenReturn(this.childEntity1.id);
when(this.datastore.fetch(eq(this.key1)))
.thenReturn(Arrays.asList(this.e1));
TestEntity parentEntity1 = this.datastoreTemplate.findById(this.key1, TestEntity.class);
assertThat(parentEntity1).isSameAs(this.ob1);
ChildEntity singularReference1 = parentEntity1.singularReference;
ChildEntity childEntity1 = parentEntity1.childEntities.get(0);
assertThat(singularReference1).isSameAs(childEntity1);
TestEntity parentEntity2 = this.datastoreTemplate.findById(this.key1, TestEntity.class);
assertThat(parentEntity2).isSameAs(this.ob1);
ChildEntity singularReference2 = parentEntity2.singularReference;
ChildEntity childEntity2 = parentEntity2.childEntities.get(0);
assertThat(singularReference2).isSameAs(childEntity2);
assertThat(childEntity1).isNotSameAs(childEntity2);
}
#location 10
#vulnerability type NULL_DEREFERENCE
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
private <T> String buildResourceName(T entity) {
FirestorePersistentEntity<?> persistentEntity =
this.mappingContext.getPersistentEntity(entity.getClass());
FirestorePersistentProperty idProperty = persistentEntity.getIdPropertyOrFail();
Object idVal = persistentEntity.getPropertyAccessor(entity).getProperty(idProperty);
if (idVal == null) {
if (idProperty.getType() != String.class) {
throw new FirestoreDataException(
"ID property was null; automatic ID generation is only supported for String type");
}
//TODO: replace with com.google.cloud.firestore.Internal.autoId() when it is available
idVal = AutoId.autoId();
persistentEntity.getPropertyAccessor(entity).setProperty(idProperty, idVal);
}
return buildResourceName(persistentEntity, idVal.toString());
}
|
#vulnerable code
private <T> String buildResourceName(T entity) {
FirestorePersistentEntity<?> persistentEntity =
this.mappingContext.getPersistentEntity(entity.getClass());
FirestorePersistentProperty idProperty = persistentEntity.getIdPropertyOrFail();
Object idVal = persistentEntity.getPropertyAccessor(entity).getProperty(idProperty);
return buildResourceName(persistentEntity, idVal.toString());
}
#location 7
#vulnerability type NULL_DEREFERENCE
|
Below is the vulnerable code, please generate the patch based on the following information.
|
#fixed code
private boolean isDiscriminationFieldMatch(DatastorePersistentEntity entity,
EntityPropertyValueProvider propertyValueProvider) {
return ((String[]) propertyValueProvider.getPropertyValue(entity.getDiscriminationFieldName(),
EmbeddedType.NOT_EMBEDDED,
ClassTypeInformation.from(String[].class)))[0].equals(entity.getDiscriminationValue());
}
|
#vulnerable code
private boolean isDiscriminationFieldMatch(DatastorePersistentEntity entity,
EntityPropertyValueProvider propertyValueProvider) {
return propertyValueProvider.getPropertyValue(entity.getDiscriminationFieldName(), EmbeddedType.NOT_EMBEDDED,
ClassTypeInformation.from(String.class)).equals(entity.getDiscriminationValue());
}
#location 4
#vulnerability type NULL_DEREFERENCE
|
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.