input
stringlengths 205
73.3k
| output
stringlengths 64
73.2k
| instruction
stringclasses 1
value |
---|---|---|
#vulnerable code
@Override
public RulesProfile createProfile(final ValidationMessages messages) {
LOGGER.info("Creating Swift Profile");
Reader config = null;
final RulesProfile profile = RulesProfile.create("Swift", Swift.KEY);
profile.setDefaultProfile(true);
try {
// add swift lint rules
config = new InputStreamReader(getClass().getResourceAsStream(SwiftLintProfile.PROFILE_PATH));
RulesProfile ocLintRulesProfile = this.swiftLintProfileImporter.importProfile(config, messages);
for (ActiveRule rule : ocLintRulesProfile.getActiveRules()) {
profile.addActiveRule(rule);
}
//add tailor rules
config = new InputStreamReader(getClass().getResourceAsStream(TailorProfile.PROFILE_PATH));
RulesProfile ocTailorRulesProfile = this.tailorProfileImporter.importProfile(config, messages);
for (ActiveRule rule : ocTailorRulesProfile.getActiveRules()) {
profile.addActiveRule(rule);
}
return profile;
} finally {
Closeables.closeQuietly(config);
}
}
#location 21
#vulnerability type NULL_DEREFERENCE | #fixed code
@Override
public RulesProfile createProfile(final ValidationMessages messages) {
LOGGER.info("Creating Swift Profile");
Reader config = null;
final RulesProfile profile = RulesProfile.create("Swift", Swift.KEY);
profile.setDefaultProfile(true);
try {
// Add swift lint rules
config = new InputStreamReader(getClass().getResourceAsStream(SwiftLintProfile.PROFILE_PATH));
RulesProfile ocLintRulesProfile = this.swiftLintProfileImporter.importProfile(config, messages);
for (ActiveRule rule : ocLintRulesProfile.getActiveRules()) {
profile.addActiveRule(rule);
}
return profile;
} finally {
Closeables.closeQuietly(config);
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
public void next() {
if (_waitingToEmit.isEmpty()) {
fill();
}
while (true) {
MessageAndOffset msgAndOffset = _waitingToEmit.pollFirst();
if (msgAndOffset != null) {
Long key = msgAndOffset.offset();
Message msg = msgAndOffset.message();
try {
_lastEnquedOffset = key;
if (_lastEnquedOffset > _lastComittedOffset) {
if (msg.payload() != null) {
synchronized (_receiver) {
_receiver.store(new String(Utils.toByteArray(msg.payload())));
}
LOG.info("Store for topic " + _topic + " for partition " + _partition.partition + " is : "+ _lastEnquedOffset);
}
}
} catch (Exception e) {
LOG.info("Process Failed for offset " + key + " for "
+ _partition + " for topic " + _topic
+ " with Exception" + e.getMessage());
e.printStackTrace();
}
}else{
break;
}
}
long now = System.currentTimeMillis();
if ((_lastEnquedOffset > _lastComittedOffset) && ((now - _lastCommitMs) > _kafkaconfig._stateUpdateIntervalMs)) {
commit();
LOG.info("After commit , Waiting To Emit queue size is "
+ _waitingToEmit.size());
_lastCommitMs = System.currentTimeMillis();
}
}
#location 25
#vulnerability type THREAD_SAFETY_VIOLATION | #fixed code
public void next() {
if (_waitingToEmit.isEmpty()) {
fill();
}
while (true) {
MessageAndOffset msgAndOffset = _waitingToEmit.pollFirst();
if (msgAndOffset != null) {
Long key = msgAndOffset.offset();
Message msg = msgAndOffset.message();
try {
_lastEnquedOffset = key;
if (_lastEnquedOffset >= _lastComittedOffset) {
if (msg.payload() != null) {
_receiver.store(msg.payload());
LOG.info("Store for topic " + _topic + " for partition " + _partition.partition + " is : "+ _lastEnquedOffset);
}
}
} catch (Exception e) {
LOG.info("Process Failed for offset " + key + " for "
+ _partition + " for topic " + _topic
+ " with Exception" + e.getMessage());
e.printStackTrace();
}
}else{
break;
}
}
long now = System.currentTimeMillis();
if ((_lastEnquedOffset > _lastComittedOffset) && ((now - _lastCommitMs) > _kafkaconfig._stateUpdateIntervalMs)) {
commit();
LOG.info("After commit , Waiting To Emit queue size is "
+ _waitingToEmit.size());
_lastCommitMs = System.currentTimeMillis();
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
public void next() {
if (_waitingToEmit.isEmpty()) {
fill();
}
while (true) {
MessageAndOffset msgAndOffset = _waitingToEmit.pollFirst();
if (msgAndOffset != null) {
Long key = msgAndOffset.offset();
Message msg = msgAndOffset.message();
try {
_lastEnquedOffset = key;
if (_lastEnquedOffset > _lastComittedOffset) {
if (msg.payload() != null) {
synchronized (_receiver) {
_receiver.store(new String(Utils.toByteArray(msg.payload())));
}
LOG.info("Store for topic " + _topic + " for partition " + _partition.partition + " is : "+ _lastEnquedOffset);
}
}
} catch (Exception e) {
LOG.info("Process Failed for offset " + key + " for "
+ _partition + " for topic " + _topic
+ " with Exception" + e.getMessage());
e.printStackTrace();
}
}else{
break;
}
}
long now = System.currentTimeMillis();
if ((_lastEnquedOffset > _lastComittedOffset) && ((now - _lastCommitMs) > _kafkaconfig._stateUpdateIntervalMs)) {
commit();
LOG.info("After commit , Waiting To Emit queue size is "
+ _waitingToEmit.size());
_lastCommitMs = System.currentTimeMillis();
}
}
#location 43
#vulnerability type THREAD_SAFETY_VIOLATION | #fixed code
public void next() {
if (_waitingToEmit.isEmpty()) {
fill();
}
while (true) {
MessageAndOffset msgAndOffset = _waitingToEmit.pollFirst();
if (msgAndOffset != null) {
Long key = msgAndOffset.offset();
Message msg = msgAndOffset.message();
try {
_lastEnquedOffset = key;
if (_lastEnquedOffset >= _lastComittedOffset) {
if (msg.payload() != null) {
_receiver.store(msg.payload());
LOG.info("Store for topic " + _topic + " for partition " + _partition.partition + " is : "+ _lastEnquedOffset);
}
}
} catch (Exception e) {
LOG.info("Process Failed for offset " + key + " for "
+ _partition + " for topic " + _topic
+ " with Exception" + e.getMessage());
e.printStackTrace();
}
}else{
break;
}
}
long now = System.currentTimeMillis();
if ((_lastEnquedOffset > _lastComittedOffset) && ((now - _lastCommitMs) > _kafkaconfig._stateUpdateIntervalMs)) {
commit();
LOG.info("After commit , Waiting To Emit queue size is "
+ _waitingToEmit.size());
_lastCommitMs = System.currentTimeMillis();
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
public void next() {
if (_waitingToEmit.isEmpty()) {
fill();
}
while (true) {
MessageAndOffset msgAndOffset = _waitingToEmit.pollFirst();
if (msgAndOffset != null) {
Long key = msgAndOffset.offset();
Message msg = msgAndOffset.message();
try {
_lastEnquedOffset = key;
if (_lastEnquedOffset > _lastComittedOffset) {
if (msg.payload() != null) {
synchronized (_receiver) {
_receiver.store(new String(Utils.toByteArray(msg.payload())));
}
LOG.info("Store for topic " + _topic + " for partition " + _partition.partition + " is : "+ _lastEnquedOffset);
}
}
} catch (Exception e) {
LOG.info("Process Failed for offset " + key + " for "
+ _partition + " for topic " + _topic
+ " with Exception" + e.getMessage());
e.printStackTrace();
}
}else{
break;
}
}
long now = System.currentTimeMillis();
if ((_lastEnquedOffset > _lastComittedOffset) && ((now - _lastCommitMs) > _kafkaconfig._stateUpdateIntervalMs)) {
commit();
LOG.info("After commit , Waiting To Emit queue size is "
+ _waitingToEmit.size());
_lastCommitMs = System.currentTimeMillis();
}
}
#location 4
#vulnerability type THREAD_SAFETY_VIOLATION | #fixed code
public void next() {
if (_waitingToEmit.isEmpty()) {
fill();
}
while (true) {
MessageAndOffset msgAndOffset = _waitingToEmit.pollFirst();
if (msgAndOffset != null) {
Long key = msgAndOffset.offset();
Message msg = msgAndOffset.message();
try {
_lastEnquedOffset = key;
if (_lastEnquedOffset >= _lastComittedOffset) {
if (msg.payload() != null) {
_receiver.store(msg.payload());
LOG.info("Store for topic " + _topic + " for partition " + _partition.partition + " is : "+ _lastEnquedOffset);
}
}
} catch (Exception e) {
LOG.info("Process Failed for offset " + key + " for "
+ _partition + " for topic " + _topic
+ " with Exception" + e.getMessage());
e.printStackTrace();
}
}else{
break;
}
}
long now = System.currentTimeMillis();
if ((_lastEnquedOffset > _lastComittedOffset) && ((now - _lastCommitMs) > _kafkaconfig._stateUpdateIntervalMs)) {
commit();
LOG.info("After commit , Waiting To Emit queue size is "
+ _waitingToEmit.size());
_lastCommitMs = System.currentTimeMillis();
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
public void next() {
if (_waitingToEmit.isEmpty()) {
fill();
}
while (true) {
MessageAndOffset msgAndOffset = _waitingToEmit.pollFirst();
if (msgAndOffset != null) {
Long key = msgAndOffset.offset();
Message msg = msgAndOffset.message();
try {
_lastEnquedOffset = key;
if (_lastEnquedOffset > _lastComittedOffset) {
if (msg.payload() != null) {
synchronized (_receiver) {
_receiver.store(new String(Utils.toByteArray(msg.payload())));
}
LOG.info("Store for topic " + _topic + " for partition " + _partition.partition + " is : "+ _lastEnquedOffset);
}
}
} catch (Exception e) {
LOG.info("Process Failed for offset " + key + " for "
+ _partition + " for topic " + _topic
+ " with Exception" + e.getMessage());
e.printStackTrace();
}
}else{
break;
}
}
long now = System.currentTimeMillis();
if ((_lastEnquedOffset > _lastComittedOffset) && ((now - _lastCommitMs) > _kafkaconfig._stateUpdateIntervalMs)) {
commit();
LOG.info("After commit , Waiting To Emit queue size is "
+ _waitingToEmit.size());
_lastCommitMs = System.currentTimeMillis();
}
}
#location 42
#vulnerability type THREAD_SAFETY_VIOLATION | #fixed code
public void next() {
if (_waitingToEmit.isEmpty()) {
fill();
}
while (true) {
MessageAndOffset msgAndOffset = _waitingToEmit.pollFirst();
if (msgAndOffset != null) {
Long key = msgAndOffset.offset();
Message msg = msgAndOffset.message();
try {
_lastEnquedOffset = key;
if (_lastEnquedOffset >= _lastComittedOffset) {
if (msg.payload() != null) {
_receiver.store(msg.payload());
LOG.info("Store for topic " + _topic + " for partition " + _partition.partition + " is : "+ _lastEnquedOffset);
}
}
} catch (Exception e) {
LOG.info("Process Failed for offset " + key + " for "
+ _partition + " for topic " + _topic
+ " with Exception" + e.getMessage());
e.printStackTrace();
}
}else{
break;
}
}
long now = System.currentTimeMillis();
if ((_lastEnquedOffset > _lastComittedOffset) && ((now - _lastCommitMs) > _kafkaconfig._stateUpdateIntervalMs)) {
commit();
LOG.info("After commit , Waiting To Emit queue size is "
+ _waitingToEmit.size());
_lastCommitMs = System.currentTimeMillis();
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
private void run() {
String checkpointDirectory = "hdfs://10.252.5.113:9000/user/hadoop/spark";
int _partitionCount = 3;
List<JavaDStream<MessageAndMetadata>> streamsList = new ArrayList<JavaDStream<MessageAndMetadata>>(
_partitionCount);
JavaDStream<MessageAndMetadata> unionStreams;
SparkConf _sparkConf = new SparkConf().setAppName("KafkaReceiver")
.set("spark.streaming.receiver.writeAheadLog.enable", "true");;
JavaStreamingContext ssc = new JavaStreamingContext(_sparkConf,
new Duration(10000));
for (int i = 0; i < _partitionCount; i++) {
streamsList.add(ssc.receiverStream(new KafkaReceiver(_props, i)));
}
// Union all the streams if there is more than 1 stream
if (streamsList.size() > 1) {
unionStreams = ssc.union(streamsList.get(0),
streamsList.subList(1, streamsList.size()));
} else {
// Otherwise, just use the 1 stream
unionStreams = streamsList.get(0);
}
unionStreams.checkpoint(new Duration(10000));
try {
unionStreams
.foreachRDD(new Function2<JavaRDD<MessageAndMetadata>, Time, Void>() {
@Override
public Void call(JavaRDD<MessageAndMetadata> rdd,
Time time) throws Exception {
for (MessageAndMetadata record : rdd.collect()) {
if (record != null) {
System.out.println(new String(record
.getPayload()));
}
}
return null;
}
});
} catch (Exception ex) {
ex.printStackTrace();
}
ssc.checkpoint(checkpointDirectory);
ssc.start();
ssc.awaitTermination();
}
#location 61
#vulnerability type RESOURCE_LEAK | #fixed code
private void run() {
Properties props = new Properties();
props.put("zookeeper.hosts", "10.252.5.131");
props.put("zookeeper.port", "2181");
props.put("zookeeper.broker.path", "/brokers");
props.put("kafka.topic", "valid_subpub");
props.put("kafka.consumer.id", "valid_subpub");
props.put("zookeeper.consumer.connection", "10.252.5.113:2182");
props.put("zookeeper.consumer.path", "/kafka-new");
SparkConf _sparkConf = new SparkConf().setAppName("KafkaReceiver")
.set("spark.streaming.receiver.writeAheadLog.enable", "false");;
JavaStreamingContext ssc = new JavaStreamingContext(_sparkConf,
new Duration(10000));
//Specify number of Receivers you need.
//It should be less than or equal to number of Partitions of your topic
int numberOfReceivers = 2;
JavaDStream<MessageAndMetadata> unionStreams = ReceiverLauncher.launch(ssc, props, numberOfReceivers);
unionStreams
.foreachRDD(new Function2<JavaRDD<MessageAndMetadata>, Time, Void>() {
@Override
public Void call(JavaRDD<MessageAndMetadata> rdd,
Time time) throws Exception {
System.out.println("Number of records in this Batch is " + rdd.count());
return null;
}
});
ssc.start();
ssc.awaitTermination();
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
public void next() {
if (_waitingToEmit.isEmpty()) {
if (_lastFillTime == null
|| (System.currentTimeMillis() - _lastFillTime) > _kafkaconfig._fillFreqMs) {
LOG.info("_waitingToEmit is empty for topic " + _topic
+ " for partition " + _partition.partition
+ ".. Filling it every "+ _kafkaconfig._fillFreqMs +" miliseconds");
fill();
_lastFillTime = System.currentTimeMillis();
}
}
while (true) {
MessageAndOffset msgAndOffset = _waitingToEmit.pollFirst();
if (msgAndOffset != null) {
Long key = msgAndOffset.offset();
Message msg = msgAndOffset.message();
try {
_lastEnquedOffset = key;
if (_lastEnquedOffset >= _lastComittedOffset) {
if (msg.payload() != null) {
MessageAndMetadata mmeta = new MessageAndMetadata();
mmeta.setTopic(_topic);
mmeta.setConsumer(_ConsumerId);
mmeta.setOffset(_lastEnquedOffset);
mmeta.setPartition(_partition);
byte[] payload = new byte[msg.payload().remaining()];
msg.payload().get(payload);
mmeta.setPayload(payload);
if (msg.hasKey()){
byte[] msgKey = new byte[msg.key().remaining()];
msg.key().get(msgKey);
mmeta.setKey(msgKey);
}
_dataBuffer.add(mmeta);
LOG.info("Store for topic " + _topic
+ " for partition " + _partition.partition
+ " is : " + _lastEnquedOffset);
}
}
} catch (Exception e) {
LOG.error("Process Failed for offset " + key + " for "
+ _partition + " for topic " + _topic
+ " with Exception" + e.getMessage());
e.printStackTrace();
}
} else {
break;
}
}
if ((_lastEnquedOffset >= _lastComittedOffset)
&& (_waitingToEmit.isEmpty())) {
if(_dataBuffer.size() > 0){
try{
synchronized (_receiver) {
_receiver.store(_dataBuffer.iterator());
commit();
_dataBuffer.clear();
}
}catch(Exception ex){
_emittedToOffset = _lastComittedOffset;
_dataBuffer.clear();
_receiver.reportError("Error While Store for Partition "+ _partition, ex);
}
}
}
}
#location 10
#vulnerability type THREAD_SAFETY_VIOLATION | #fixed code
public void next() {
if (_waitingToEmit.isEmpty()) {
fill();
}
while (true) {
MessageAndOffset msgAndOffset = _waitingToEmit.pollFirst();
if (msgAndOffset != null) {
Long key = msgAndOffset.offset();
Message msg = msgAndOffset.message();
try {
_lastEnquedOffset = key;
if (_lastEnquedOffset >= _lastComittedOffset) {
if (msg.payload() != null) {
MessageAndMetadata mmeta = new MessageAndMetadata();
mmeta.setTopic(_topic);
mmeta.setConsumer(_ConsumerId);
mmeta.setOffset(_lastEnquedOffset);
mmeta.setPartition(_partition);
byte[] payload = new byte[msg.payload().remaining()];
msg.payload().get(payload);
mmeta.setPayload(payload);
if (msg.hasKey()){
byte[] msgKey = new byte[msg.key().remaining()];
msg.key().get(msgKey);
mmeta.setKey(msgKey);
}
_dataBuffer.add(mmeta);
LOG.info("Store for topic " + _topic
+ " for partition " + _partition.partition
+ " is : " + _lastEnquedOffset);
}
}
} catch (Exception e) {
LOG.error("Process Failed for offset " + key + " for "
+ _partition + " for topic " + _topic
+ " with Exception" + e.getMessage());
e.printStackTrace();
}
} else {
break;
}
}
if ((_lastEnquedOffset >= _lastComittedOffset)
&& (_waitingToEmit.isEmpty())) {
try{
synchronized (_receiver) {
if(!_dataBuffer.isEmpty())
_receiver.store(_dataBuffer.iterator());
commit();
_dataBuffer.clear();
}
}catch(Exception ex){
_emittedToOffset = _lastComittedOffset;
_dataBuffer.clear();
_receiver.reportError("Error While Store for Partition "+ _partition, ex);
}
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
public void next() {
if (_waitingToEmit.isEmpty()) {
fill();
}
while (true) {
MessageAndOffset msgAndOffset = _waitingToEmit.pollFirst();
if (msgAndOffset != null) {
Long key = msgAndOffset.offset();
Message msg = msgAndOffset.message();
try {
_lastEnquedOffset = key;
if (_lastEnquedOffset > _lastComittedOffset) {
if (msg.payload() != null) {
synchronized (_receiver) {
_receiver.store(new String(Utils.toByteArray(msg.payload())));
}
LOG.info("Store for topic " + _topic + " for partition " + _partition.partition + " is : "+ _lastEnquedOffset);
}
}
} catch (Exception e) {
LOG.info("Process Failed for offset " + key + " for "
+ _partition + " for topic " + _topic
+ " with Exception" + e.getMessage());
e.printStackTrace();
}
}else{
break;
}
}
long now = System.currentTimeMillis();
if ((_lastEnquedOffset > _lastComittedOffset) && ((now - _lastCommitMs) > _kafkaconfig._stateUpdateIntervalMs)) {
commit();
LOG.info("After commit , Waiting To Emit queue size is "
+ _waitingToEmit.size());
_lastCommitMs = System.currentTimeMillis();
}
}
#location 46
#vulnerability type THREAD_SAFETY_VIOLATION | #fixed code
public void next() {
if (_waitingToEmit.isEmpty()) {
fill();
}
while (true) {
MessageAndOffset msgAndOffset = _waitingToEmit.pollFirst();
if (msgAndOffset != null) {
Long key = msgAndOffset.offset();
Message msg = msgAndOffset.message();
try {
_lastEnquedOffset = key;
if (_lastEnquedOffset >= _lastComittedOffset) {
if (msg.payload() != null) {
_receiver.store(msg.payload());
LOG.info("Store for topic " + _topic + " for partition " + _partition.partition + " is : "+ _lastEnquedOffset);
}
}
} catch (Exception e) {
LOG.info("Process Failed for offset " + key + " for "
+ _partition + " for topic " + _topic
+ " with Exception" + e.getMessage());
e.printStackTrace();
}
}else{
break;
}
}
long now = System.currentTimeMillis();
if ((_lastEnquedOffset > _lastComittedOffset) && ((now - _lastCommitMs) > _kafkaconfig._stateUpdateIntervalMs)) {
commit();
LOG.info("After commit , Waiting To Emit queue size is "
+ _waitingToEmit.size());
_lastCommitMs = System.currentTimeMillis();
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
public void next() {
if (_waitingToEmit.isEmpty()) {
if (_lastFillTime == null
|| (System.currentTimeMillis() - _lastFillTime) > _kafkaconfig._fillFreqMs) {
LOG.info("_waitingToEmit is empty for topic " + _topic
+ " for partition " + _partition.partition
+ ".. Filling it every "+ _kafkaconfig._fillFreqMs +" miliseconds");
fill();
_lastFillTime = System.currentTimeMillis();
}
}
while (true) {
MessageAndOffset msgAndOffset = _waitingToEmit.pollFirst();
if (msgAndOffset != null) {
Long key = msgAndOffset.offset();
Message msg = msgAndOffset.message();
try {
_lastEnquedOffset = key;
if (_lastEnquedOffset >= _lastComittedOffset) {
if (msg.payload() != null) {
MessageAndMetadata mmeta = new MessageAndMetadata();
mmeta.setTopic(_topic);
mmeta.setConsumer(_ConsumerId);
mmeta.setOffset(_lastEnquedOffset);
mmeta.setPartition(_partition);
byte[] payload = new byte[msg.payload().remaining()];
msg.payload().get(payload);
mmeta.setPayload(payload);
if (msg.hasKey()){
byte[] msgKey = new byte[msg.key().remaining()];
msg.key().get(msgKey);
mmeta.setKey(msgKey);
}
_dataBuffer.add(mmeta);
LOG.info("Store for topic " + _topic
+ " for partition " + _partition.partition
+ " is : " + _lastEnquedOffset);
}
}
} catch (Exception e) {
LOG.error("Process Failed for offset " + key + " for "
+ _partition + " for topic " + _topic
+ " with Exception" + e.getMessage());
e.printStackTrace();
}
} else {
break;
}
}
if ((_lastEnquedOffset >= _lastComittedOffset)
&& (_waitingToEmit.isEmpty())) {
if(_dataBuffer.size() > 0){
try{
synchronized (_receiver) {
_receiver.store(_dataBuffer.iterator());
commit();
_dataBuffer.clear();
}
}catch(Exception ex){
_emittedToOffset = _lastComittedOffset;
_dataBuffer.clear();
_receiver.reportError("Error While Store for Partition "+ _partition, ex);
}
}
}
}
#location 5
#vulnerability type THREAD_SAFETY_VIOLATION | #fixed code
public void next() {
if (_waitingToEmit.isEmpty()) {
fill();
}
while (true) {
MessageAndOffset msgAndOffset = _waitingToEmit.pollFirst();
if (msgAndOffset != null) {
Long key = msgAndOffset.offset();
Message msg = msgAndOffset.message();
try {
_lastEnquedOffset = key;
if (_lastEnquedOffset >= _lastComittedOffset) {
if (msg.payload() != null) {
MessageAndMetadata mmeta = new MessageAndMetadata();
mmeta.setTopic(_topic);
mmeta.setConsumer(_ConsumerId);
mmeta.setOffset(_lastEnquedOffset);
mmeta.setPartition(_partition);
byte[] payload = new byte[msg.payload().remaining()];
msg.payload().get(payload);
mmeta.setPayload(payload);
if (msg.hasKey()){
byte[] msgKey = new byte[msg.key().remaining()];
msg.key().get(msgKey);
mmeta.setKey(msgKey);
}
_dataBuffer.add(mmeta);
LOG.info("Store for topic " + _topic
+ " for partition " + _partition.partition
+ " is : " + _lastEnquedOffset);
}
}
} catch (Exception e) {
LOG.error("Process Failed for offset " + key + " for "
+ _partition + " for topic " + _topic
+ " with Exception" + e.getMessage());
e.printStackTrace();
}
} else {
break;
}
}
if ((_lastEnquedOffset >= _lastComittedOffset)
&& (_waitingToEmit.isEmpty())) {
try{
synchronized (_receiver) {
if(!_dataBuffer.isEmpty())
_receiver.store(_dataBuffer.iterator());
commit();
_dataBuffer.clear();
}
}catch(Exception ex){
_emittedToOffset = _lastComittedOffset;
_dataBuffer.clear();
_receiver.reportError("Error While Store for Partition "+ _partition, ex);
}
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
public void next() {
if (_waitingToEmit.isEmpty()) {
fill();
}
while (true) {
MessageAndOffset msgAndOffset = _waitingToEmit.pollFirst();
if (msgAndOffset != null) {
Long key = msgAndOffset.offset();
Message msg = msgAndOffset.message();
try {
_lastEnquedOffset = key;
if (_lastEnquedOffset > _lastComittedOffset) {
if (msg.payload() != null) {
synchronized (_receiver) {
_receiver.store(new String(Utils.toByteArray(msg.payload())));
}
LOG.info("Store for topic " + _topic + " for partition " + _partition.partition + " is : "+ _lastEnquedOffset);
}
}
} catch (Exception e) {
LOG.info("Process Failed for offset " + key + " for "
+ _partition + " for topic " + _topic
+ " with Exception" + e.getMessage());
e.printStackTrace();
}
}else{
break;
}
}
long now = System.currentTimeMillis();
if ((_lastEnquedOffset > _lastComittedOffset) && ((now - _lastCommitMs) > _kafkaconfig._stateUpdateIntervalMs)) {
commit();
LOG.info("After commit , Waiting To Emit queue size is "
+ _waitingToEmit.size());
_lastCommitMs = System.currentTimeMillis();
}
}
#location 17
#vulnerability type THREAD_SAFETY_VIOLATION | #fixed code
public void next() {
if (_waitingToEmit.isEmpty()) {
fill();
}
while (true) {
MessageAndOffset msgAndOffset = _waitingToEmit.pollFirst();
if (msgAndOffset != null) {
Long key = msgAndOffset.offset();
Message msg = msgAndOffset.message();
try {
_lastEnquedOffset = key;
if (_lastEnquedOffset >= _lastComittedOffset) {
if (msg.payload() != null) {
_receiver.store(msg.payload());
LOG.info("Store for topic " + _topic + " for partition " + _partition.partition + " is : "+ _lastEnquedOffset);
}
}
} catch (Exception e) {
LOG.info("Process Failed for offset " + key + " for "
+ _partition + " for topic " + _topic
+ " with Exception" + e.getMessage());
e.printStackTrace();
}
}else{
break;
}
}
long now = System.currentTimeMillis();
if ((_lastEnquedOffset > _lastComittedOffset) && ((now - _lastCommitMs) > _kafkaconfig._stateUpdateIntervalMs)) {
commit();
LOG.info("After commit , Waiting To Emit queue size is "
+ _waitingToEmit.size());
_lastCommitMs = System.currentTimeMillis();
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Test
public void testSession_whenCreateIsTrue() {
when(servletRequest.getSession(true)).thenReturn(httpSession);
Request request = new Request(match, servletRequest);
assertEquals("A Session with an HTTPSession from the Request should have been created because create parameter " +
"was set to true",
httpSession, request.session(true).raw());
}
#location 10
#vulnerability type NULL_DEREFERENCE | #fixed code
@Test
public void testSession_whenCreateIsTrue() {
when(servletRequest.getSession(true)).thenReturn(httpSession);
assertEquals("A Session with an HTTPSession from the Request should have been created because create parameter " +
"was set to true",
httpSession, request.session(true).raw());
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
public boolean consume(HttpServletRequest httpRequest,
HttpServletResponse httpResponse) throws IOException {
if (staticResourceHandlers != null) {
for (AbstractResourceHandler staticResourceHandler : staticResourceHandlers) {
AbstractFileResolvingResource resource = staticResourceHandler.getResource(httpRequest);
if (resource != null && resource.isReadable()) {
OutputStream wrappedOutputStream = GzipUtils.checkAndWrap(httpRequest, httpResponse, false);
customHeaders.forEach(httpResponse::setHeader); //add all user-defined headers to response
IOUtils.copy(resource.getInputStream(), wrappedOutputStream);
wrappedOutputStream.flush();
wrappedOutputStream.close();
return true;
}
}
}
return false;
}
#location 5
#vulnerability type THREAD_SAFETY_VIOLATION | #fixed code
public boolean consume(HttpServletRequest httpRequest,
HttpServletResponse httpResponse) throws IOException {
if (consumeWithFileResourceHandlers(httpRequest, httpResponse)) {
return true;
}
if (consumeWithJarResourceHandler(httpRequest, httpResponse)) {
return true;
}
return false;
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@BeforeClass
public static void setup() {
testUtil = new SparkTestUtil(PORT);
final Server server = new Server();
ServerConnector connector = new ServerConnector(server);
// Set some timeout options to make debugging easier.
connector.setIdleTimeout(1000 * 60 * 60);
connector.setSoLingerTime(-1);
connector.setPort(PORT);
server.setConnectors(new Connector[] { connector });
WebAppContext bb = new WebAppContext();
bb.setServer(server);
bb.setContextPath(SOMEPATH);
bb.setWar("src/test/webapp");
server.setHandler(bb);
new Thread(new Runnable() {
@Override
public void run() {
try {
System.out.println(">>> STARTING EMBEDDED JETTY SERVER for jUnit testing of SparkFilter");
server.start();
System.in.read();
System.out.println(">>> STOPPING EMBEDDED JETTY SERVER");
server.stop();
server.join();
} catch (Exception e) {
e.printStackTrace();
System.exit(100);
}
}
}).start();
sleep(1000);
}
#location 12
#vulnerability type RESOURCE_LEAK | #fixed code
@BeforeClass
public static void setup() {
testUtil = new SparkTestUtil(PORT);
final Server server = new Server();
ServerConnector connector = new ServerConnector(server);
// Set some timeout options to make debugging easier.
connector.setIdleTimeout(1000 * 60 * 60);
connector.setSoLingerTime(-1);
connector.setPort(PORT);
server.setConnectors(new Connector[]{connector});
WebAppContext bb = new WebAppContext();
bb.setServer(server);
bb.setContextPath(SOMEPATH);
bb.setWar("src/test/webapp");
server.setHandler(bb);
new Thread(new Runnable() {
@Override
public void run() {
try {
System.out.println(">>> STARTING EMBEDDED JETTY SERVER for jUnit testing of SparkFilter");
server.start();
System.in.read();
System.out.println(">>> STOPPING EMBEDDED JETTY SERVER");
server.stop();
server.join();
} catch (Exception e) {
e.printStackTrace();
System.exit(100);
}
}
}).start();
sleep(1000);
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
public String body() {
if (body == null) {
if (servletRequest.getCharacterEncoding() != null) {
try {
body = new String(bodyAsBytes(), servletRequest.getCharacterEncoding());
} catch (UnsupportedEncodingException e) {
body = new String(bodyAsBytes());
}
} else {
body = new String(bodyAsBytes());
}
}
return body;
}
#location 7
#vulnerability type NULL_DEREFERENCE | #fixed code
public String body() {
if (body == null) {
body = StringUtils.toString(bodyAsBytes(), servletRequest.getCharacterEncoding());
}
return body;
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
public void clear() {
if (staticResourceHandlers != null) {
staticResourceHandlers.clear();
staticResourceHandlers = null;
}
if (jarResourceHandlers != null) {
jarResourceHandlers.clear();
jarResourceHandlers = null;
}
staticResourcesSet = false;
externalStaticResourcesSet = false;
}
#location 9
#vulnerability type THREAD_SAFETY_VIOLATION | #fixed code
public void clear() {
if (staticResourceHandlers != null) {
staticResourceHandlers.clear();
staticResourceHandlers = null;
}
staticResourcesSet = false;
externalStaticResourcesSet = false;
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
public static Object getFor(int status, Request request, Response response) {
Object customRenderer = CustomErrorPages.getInstance().customPages.get(status);
Object customPage;
if (customRenderer instanceof String) {
customPage = customRenderer;
} else {
try {
customPage = ((Route) customRenderer).handle(request, response);
} catch (Exception e) {
customPage = status == 400 ? NOT_FOUND : INTERNAL_ERROR;
}
}
return customPage;
}
#location 10
#vulnerability type NULL_DEREFERENCE | #fixed code
public static Object getFor(int status, Request request, Response response) {
Object customRenderer = CustomErrorPages.getInstance().customPages.get(status);
Object customPage;
customPage = status == 400 ? NOT_FOUND : INTERNAL_ERROR;
if (customRenderer instanceof String) {
customPage = customRenderer;
} else if (customRenderer instanceof Route) {
try {
customPage = ((Route) customRenderer).handle(request, response);
} catch (Exception e) {
// customPage is already set to default error so nothing needed here
}
}
return customPage;
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
public boolean consume(HttpServletRequest httpRequest,
HttpServletResponse httpResponse) throws IOException {
if (consumeWithFileResourceHandlers(httpRequest, httpResponse)) {
return true;
}
if (consumeWithJarResourceHandler(httpRequest, httpResponse)) {
return true;
}
return false;
}
#location 8
#vulnerability type THREAD_SAFETY_VIOLATION | #fixed code
public boolean consume(HttpServletRequest httpRequest,
HttpServletResponse httpResponse) throws IOException {
if (consumeWithFileResourceHandlers(httpRequest, httpResponse)) {
return true;
}
return false;
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
public void clear() {
if (staticResourceHandlers != null) {
staticResourceHandlers.clear();
staticResourceHandlers = null;
}
if (jarResourceHandlers != null) {
jarResourceHandlers.clear();
jarResourceHandlers = null;
}
staticResourcesSet = false;
externalStaticResourcesSet = false;
}
#location 10
#vulnerability type THREAD_SAFETY_VIOLATION | #fixed code
public void clear() {
if (staticResourceHandlers != null) {
staticResourceHandlers.clear();
staticResourceHandlers = null;
}
staticResourcesSet = false;
externalStaticResourcesSet = false;
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, // NOSONAR
FilterChain chain) throws IOException, ServletException { // NOSONAR
HttpServletRequest httpRequest = (HttpServletRequest) servletRequest; // NOSONAR
HttpServletResponse httpResponse = (HttpServletResponse) servletResponse;
// handle static resources
boolean consumedByStaticFile = StaticFiles.consume(httpRequest, httpResponse);
if (consumedByStaticFile) {
return;
}
String method = httpRequest.getHeader(HTTP_METHOD_OVERRIDE_HEADER);
if (method == null) {
method = httpRequest.getMethod();
}
String httpMethodStr = method.toLowerCase(); // NOSONAR
String uri = httpRequest.getPathInfo(); // NOSONAR
String acceptType = httpRequest.getHeader(ACCEPT_TYPE_REQUEST_MIME_HEADER);
Object bodyContent = null;
RequestWrapper requestWrapper = new RequestWrapper();
ResponseWrapper responseWrapper = new ResponseWrapper();
Response response = RequestResponseFactory.create(httpResponse);
LOG.debug("httpMethod:" + httpMethodStr + ", uri: " + uri);
try {
// BEFORE filters
List<RouteMatch> matchSet = routeMatcher.findTargetsForRequestedRoute(HttpMethod.before, uri, acceptType);
for (RouteMatch filterMatch : matchSet) {
Object filterTarget = filterMatch.getTarget();
if (filterTarget instanceof FilterImpl) {
Request request = RequestResponseFactory.create(filterMatch, httpRequest);
FilterImpl filter = (FilterImpl) filterTarget;
requestWrapper.setDelegate(request);
responseWrapper.setDelegate(response);
filter.handle(requestWrapper, responseWrapper);
String bodyAfterFilter = Access.getBody(response);
if (bodyAfterFilter != null) {
bodyContent = bodyAfterFilter;
}
}
}
// BEFORE filters, END
HttpMethod httpMethod = HttpMethod.valueOf(httpMethodStr);
RouteMatch match = null;
match = routeMatcher.findTargetForRequestedRoute(httpMethod, uri, acceptType);
Object target = null;
if (match != null) {
target = match.getTarget();
} else if (httpMethod == HttpMethod.head && bodyContent == null) {
// See if get is mapped to provide default head mapping
bodyContent =
routeMatcher.findTargetForRequestedRoute(HttpMethod.get, uri, acceptType) != null ? "" : null;
}
if (target != null) {
try {
Object result = null;
if (target instanceof RouteImpl) {
RouteImpl route = ((RouteImpl) target);
if (requestWrapper.getDelegate() == null) {
Request request = RequestResponseFactory.create(match, httpRequest);
requestWrapper.setDelegate(request);
} else {
requestWrapper.changeMatch(match);
}
responseWrapper.setDelegate(response);
Object element = route.handle(requestWrapper, responseWrapper);
result = route.render(element);
// result = element.toString(); // TODO: Remove later when render fixed
}
if (result != null) {
bodyContent = result;
}
} catch (HaltException hEx) { // NOSONAR
throw hEx; // NOSONAR
}
}
// AFTER filters
matchSet = routeMatcher.findTargetsForRequestedRoute(HttpMethod.after, uri, acceptType);
for (RouteMatch filterMatch : matchSet) {
Object filterTarget = filterMatch.getTarget();
if (filterTarget instanceof FilterImpl) {
if (requestWrapper.getDelegate() == null) {
Request request = RequestResponseFactory.create(filterMatch, httpRequest);
requestWrapper.setDelegate(request);
} else {
requestWrapper.changeMatch(filterMatch);
}
responseWrapper.setDelegate(response);
FilterImpl filter = (FilterImpl) filterTarget;
filter.handle(requestWrapper, responseWrapper);
String bodyAfterFilter = Access.getBody(response);
if (bodyAfterFilter != null) {
bodyContent = bodyAfterFilter;
}
}
}
// AFTER filters, END
} catch (HaltException hEx) {
LOG.debug("halt performed");
httpResponse.setStatus(hEx.getStatusCode());
if (hEx.getBody() != null) {
bodyContent = hEx.getBody();
} else {
bodyContent = "";
}
} catch (Exception e) {
ExceptionHandlerImpl handler = ExceptionMapper.getInstance().getHandler(e);
if (handler != null) {
handler.handle(e, requestWrapper, responseWrapper);
String bodyAfterFilter = Access.getBody(responseWrapper.getDelegate());
if (bodyAfterFilter != null) {
bodyContent = bodyAfterFilter;
}
} else {
LOG.error("", e);
httpResponse.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
bodyContent = INTERNAL_ERROR;
}
}
// If redirected and content is null set to empty string to not throw NotConsumedException
if (bodyContent == null && responseWrapper.isRedirected()) {
bodyContent = "";
}
boolean consumed = bodyContent != null;
if (!consumed && hasOtherHandlers) {
if (servletRequest instanceof HttpRequestWrapper) {
((HttpRequestWrapper) servletRequest).notConsumed(true);
return;
}
}
if (!consumed && !isServletContext) {
LOG.info("The requested route [" + uri + "] has not been mapped in Spark");
httpResponse.setStatus(HttpServletResponse.SC_NOT_FOUND);
bodyContent = String.format(NOT_FOUND);
consumed = true;
}
if (consumed) {
// Write body content
if (!httpResponse.isCommitted()) {
if (httpResponse.getContentType() == null) {
httpResponse.setContentType("text/html; charset=utf-8");
}
// Check if gzip is wanted/accepted and in that case handle that
OutputStream outputStream = GzipUtils.checkAndWrap(httpRequest, httpResponse);
// serialize the body to output stream
serializerChain.process(outputStream, bodyContent);
outputStream.flush();//needed for GZIP stream. NOt sure where the HTTP response actually gets cleaned up
}
} else if (chain != null) {
chain.doFilter(httpRequest, httpResponse);
}
}
#location 179
#vulnerability type RESOURCE_LEAK | #fixed code
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, // NOSONAR
FilterChain chain) throws IOException, ServletException { // NOSONAR
HttpServletRequest httpRequest = (HttpServletRequest) servletRequest; // NOSONAR
HttpServletResponse httpResponse = (HttpServletResponse) servletResponse;
// handle static resources
boolean consumedByStaticFile = StaticFiles.consume(httpRequest, httpResponse);
if (consumedByStaticFile) {
return;
}
String method = httpRequest.getHeader(HTTP_METHOD_OVERRIDE_HEADER);
if (method == null) {
method = httpRequest.getMethod();
}
String httpMethodStr = method.toLowerCase(); // NOSONAR
String uri = httpRequest.getPathInfo(); // NOSONAR
String acceptType = httpRequest.getHeader(ACCEPT_TYPE_REQUEST_MIME_HEADER);
Object bodyContent = null;
RequestWrapper requestWrapper = new RequestWrapper();
ResponseWrapper responseWrapper = new ResponseWrapper();
Response response = RequestResponseFactory.create(httpResponse);
LOG.debug("httpMethod:" + httpMethodStr + ", uri: " + uri);
try {
// BEFORE filters
List<RouteMatch> matchSet = routeMatcher.findTargetsForRequestedRoute(HttpMethod.before, uri, acceptType);
for (RouteMatch filterMatch : matchSet) {
Object filterTarget = filterMatch.getTarget();
if (filterTarget instanceof FilterImpl) {
Request request = RequestResponseFactory.create(filterMatch, httpRequest);
FilterImpl filter = (FilterImpl) filterTarget;
requestWrapper.setDelegate(request);
responseWrapper.setDelegate(response);
filter.handle(requestWrapper, responseWrapper);
String bodyAfterFilter = Access.getBody(response);
if (bodyAfterFilter != null) {
bodyContent = bodyAfterFilter;
}
}
}
// BEFORE filters, END
HttpMethod httpMethod = HttpMethod.valueOf(httpMethodStr);
RouteMatch match = null;
match = routeMatcher.findTargetForRequestedRoute(httpMethod, uri, acceptType);
Object target = null;
if (match != null) {
target = match.getTarget();
} else if (httpMethod == HttpMethod.head && bodyContent == null) {
// See if get is mapped to provide default head mapping
bodyContent =
routeMatcher.findTargetForRequestedRoute(HttpMethod.get, uri, acceptType) != null ? "" : null;
}
if (target != null) {
try {
Object result = null;
if (target instanceof RouteImpl) {
RouteImpl route = ((RouteImpl) target);
if (requestWrapper.getDelegate() == null) {
Request request = RequestResponseFactory.create(match, httpRequest);
requestWrapper.setDelegate(request);
} else {
requestWrapper.changeMatch(match);
}
responseWrapper.setDelegate(response);
Object element = route.handle(requestWrapper, responseWrapper);
result = route.render(element);
// result = element.toString(); // TODO: Remove later when render fixed
}
if (result != null) {
bodyContent = result;
}
} catch (HaltException hEx) { // NOSONAR
throw hEx; // NOSONAR
}
}
// AFTER filters
matchSet = routeMatcher.findTargetsForRequestedRoute(HttpMethod.after, uri, acceptType);
for (RouteMatch filterMatch : matchSet) {
Object filterTarget = filterMatch.getTarget();
if (filterTarget instanceof FilterImpl) {
if (requestWrapper.getDelegate() == null) {
Request request = RequestResponseFactory.create(filterMatch, httpRequest);
requestWrapper.setDelegate(request);
} else {
requestWrapper.changeMatch(filterMatch);
}
responseWrapper.setDelegate(response);
FilterImpl filter = (FilterImpl) filterTarget;
filter.handle(requestWrapper, responseWrapper);
String bodyAfterFilter = Access.getBody(response);
if (bodyAfterFilter != null) {
bodyContent = bodyAfterFilter;
}
}
}
// AFTER filters, END
} catch (HaltException hEx) {
LOG.debug("halt performed");
httpResponse.setStatus(hEx.getStatusCode());
if (hEx.getBody() != null) {
bodyContent = hEx.getBody();
} else {
bodyContent = "";
}
} catch (Exception e) {
ExceptionHandlerImpl handler = ExceptionMapper.getInstance().getHandler(e);
if (handler != null) {
handler.handle(e, requestWrapper, responseWrapper);
String bodyAfterFilter = Access.getBody(responseWrapper.getDelegate());
if (bodyAfterFilter != null) {
bodyContent = bodyAfterFilter;
}
} else {
LOG.error("", e);
httpResponse.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
bodyContent = INTERNAL_ERROR;
}
}
// If redirected and content is null set to empty string to not throw NotConsumedException
if (bodyContent == null && responseWrapper.isRedirected()) {
bodyContent = "";
}
boolean consumed = bodyContent != null;
if (!consumed && hasOtherHandlers) {
if (servletRequest instanceof HttpRequestWrapper) {
((HttpRequestWrapper) servletRequest).notConsumed(true);
return;
}
}
if (!consumed && !isServletContext) {
LOG.info("The requested route [" + uri + "] has not been mapped in Spark");
httpResponse.setStatus(HttpServletResponse.SC_NOT_FOUND);
bodyContent = String.format(NOT_FOUND);
consumed = true;
}
if (consumed) {
// Write body content
if (!httpResponse.isCommitted()) {
if (httpResponse.getContentType() == null) {
httpResponse.setContentType("text/html; charset=utf-8");
}
// Check if gzip is wanted/accepted and in that case handle that
OutputStream outputStream = GzipUtils.checkAndWrap(httpRequest, httpResponse, true);
// serialize the body to output stream
serializerChain.process(outputStream, bodyContent);
outputStream.flush(); // needed for GZIP stream. NOt sure where the HTTP response actually gets cleaned up
outputStream.close(); // needed for GZIP
}
} else if (chain != null) {
chain.doFilter(httpRequest, httpResponse);
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
public String getContent(InputStream instream, long contentLength, String charset) throws IOException {
try {
if (instream == null) {
return null;
}
int i = (int)contentLength;
if (i < 0) {
i = 4096;
}
Reader reader = new InputStreamReader(instream, charset);
CharArrayBuffer buffer = new CharArrayBuffer(i);
char[] tmp = new char[1024];
int l;
while((l = reader.read(tmp)) != -1) {
buffer.append(tmp, 0, l);
}
return buffer.toString();
} finally {
instream.reset();
}
}
#location 17
#vulnerability type RESOURCE_LEAK | #fixed code
public String getContent(InputStream instream, long contentLength, String charset) throws IOException {
try {
if (instream == null) {
return null;
}
int i = (int)contentLength;
if (i < 0) {
i = 4096;
}
Reader reader = new InputStreamReader(instream, charset);
CharArrayBuffer buffer = new CharArrayBuffer(i);
char[] tmp = new char[1024];
int l;
while((l = reader.read(tmp)) != -1) {
buffer.append(tmp, 0, l);
}
return buffer.toString();
} finally {
Objects.requireNonNull(instream).reset();
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Override
public void messageReceived(ChannelHandlerContext ctx, MessageEvent e) throws Exception {
if ((e.getMessage() instanceof CoapMessage) && receiveEnabled) {
CoapMessage coapMessage = (CoapMessage) e.getMessage();
receivedMessages.put(System.currentTimeMillis(), coapMessage);
log.info("Incoming (from " + e.getRemoteAddress() + ") # " + getReceivedMessages().size() + ": "
+ coapMessage);
if(writeEnabled && (coapMessage instanceof CoapRequest)){
if (responsesToSend.isEmpty()) {
fail("responsesToSend is empty. This could be caused by an unexpected request.");
}
MessageReceiverResponse responseToSend = responsesToSend.remove(0);
if (responseToSend == null) {
throw new InternalError("Unexpected request received. No response for: " + coapMessage);
}
CoapResponse coapResponse = responseToSend;
if (responseToSend.getReceiverSetsMsgID()) {
coapResponse.setMessageID(coapMessage.getMessageID());
}
if (responseToSend.getReceiverSetsToken()) {
coapResponse.setToken(coapMessage.getToken());
}
Channels.write(channel, coapResponse, e.getRemoteAddress());
}
}
}
#location 10
#vulnerability type THREAD_SAFETY_VIOLATION | #fixed code
@Override
public void messageReceived(ChannelHandlerContext ctx, MessageEvent e) throws Exception {
if ((e.getMessage() instanceof CoapMessage) && receiveEnabled) {
CoapMessage coapMessage = (CoapMessage) e.getMessage();
receivedMessages.put(System.currentTimeMillis(), coapMessage);
log.info("Incoming #{} (from {}): {}.",
new Object[]{getReceivedMessages().size(), e.getRemoteAddress(), coapMessage});
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#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 | #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);
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
public static OptionType getOptionType(OptionName opt_name){
return syntaxConstraints.get(opt_name).opt_type;
}
#location 2
#vulnerability type NULL_DEREFERENCE | #fixed code
public static OptionType getOptionType(OptionName opt_name){
OptionSyntaxConstraints osc = syntaxConstraints.get(opt_name);
if(osc == null) {
throw new NullPointerException("OptionSyntaxConstraints does not exists!");
}
return osc.opt_type;
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Override
public void writeRequested(ChannelHandlerContext ctx, MessageEvent me) throws Exception{
if(log.isDebugEnabled()){
log.debug("[IncomingMessageReliablityHandler] Handle Downstream Message Event.");
}
if(me.getMessage() instanceof CoapResponse){
CoapResponse coapResponse = (CoapResponse) me.getMessage();
if(log.isDebugEnabled()){
log.debug("[OutgoingMessageReliabilityHandler] Handle downstream event for message with ID " +
coapResponse.getMessageID() + " for " + me.getRemoteAddress() );
}
boolean alreadyConfirmed;
synchronized(monitor){
Object o = incomingMessagesToBeConfirmed.remove(me.getRemoteAddress(),
coapResponse.getMessageID());
if (o == null){
System.out.println("Object o ist NULL!!!");
}
else{
System.out.println("Object o ist NICHT NULL!!!");
}
alreadyConfirmed = (Boolean) o;
}
if(alreadyConfirmed){
coapResponse.getHeader().setMsgType(MsgType.CON);
}
else{
coapResponse.getHeader().setMsgType(MsgType.ACK);
}
}
ctx.sendDownstream(me);
}
#location 27
#vulnerability type NULL_DEREFERENCE | #fixed code
@Override
public void writeRequested(ChannelHandlerContext ctx, MessageEvent me) throws Exception{
if(log.isDebugEnabled()){
log.debug("[IncomingMessageReliablityHandler] Handle Downstream Message Event.");
}
if(me.getMessage() instanceof CoapResponse){
CoapResponse coapResponse = (CoapResponse) me.getMessage();
if(log.isDebugEnabled()){
log.debug("[IncomingMessageReliabilityHandler] Handle downstream event for message with ID " +
coapResponse.getMessageID() + " for " + me.getRemoteAddress() );
}
Boolean alreadyConfirmed;
synchronized(monitor){
alreadyConfirmed = incomingMessagesToBeConfirmed.remove(me.getRemoteAddress(),
coapResponse.getMessageID());
}
if (alreadyConfirmed == null){
System.out.println("Object o ist NULL!!!");
coapResponse.getHeader().setMsgType(MsgType.NON);
}
else{
System.out.println("Object o ist NICHT NULL!!!");
if(alreadyConfirmed){
coapResponse.getHeader().setMsgType(MsgType.CON);
}
else{
coapResponse.getHeader().setMsgType(MsgType.ACK);
}
}
}
ctx.sendDownstream(me);
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Override
public void handleRetransmissionTimout() {
if(receiveEnabled && !timeoutNotificationTimes.add(System.currentTimeMillis())){
log.error("Could not add notification time for retransmission timeout.");
}
}
#location 3
#vulnerability type THREAD_SAFETY_VIOLATION | #fixed code
@Override
public void handleRetransmissionTimout() {
if(!timeoutNotificationTimes.add(System.currentTimeMillis())){
log.error("Could not add notification time for retransmission timeout.");
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Override
public void messageReceived(ChannelHandlerContext ctx, MessageEvent me){
if(!(me.getMessage() instanceof CoapMessage)){
ctx.sendUpstream(me);
return;
}
if(me.getMessage() instanceof CoapResponse){
CoapResponse response = (CoapResponse) me.getMessage();
if(response.getMaxBlocksizeForResponse() != null){
final byte[] token = response.getToken();
//Add latest received payload to already received payload
BlockwiseTransfer transfer;
synchronized (incompleteResponseMonitor){
transfer = incompleteResponsePayload.get(new ByteArrayWrapper(token));
try {
if(response.getBlockNumber(BLOCK_2) == transfer.getNextBlockNumber()){
log.debug("Received response (Token: " + (new ByteArrayWrapper(token).toHexString()) +
" , Block: " + response.getBlockNumber(BLOCK_2) + "), ");
//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 duplicate 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
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");
}
}
//End the original ChannelFuture
me.getFuture().isSuccess();
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 20
#vulnerability type NULL_DEREFERENCE | #fixed 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);
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Override
public void receiveEmptyACK(){
if(receiveEnabled && !emptyAckNotificationTimes.add(System.currentTimeMillis())){
log.error("Could not add notification time for empty ACK.");
}
}
#location 3
#vulnerability type THREAD_SAFETY_VIOLATION | #fixed code
@Override
public void receiveEmptyACK(){
if(!emptyAckNotificationTimes.add(System.currentTimeMillis())){
log.error("Could not add notification time for empty ACK.");
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#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 | #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();
} | Below is the vulnerable code, please generate the patch based on the following information. |
#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 | #fixed code
@Override
public void messageReceived(ChannelHandlerContext ctx, MessageEvent me) throws Exception {
super.messageReceived(ctx, me);
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Override
public void receiveResponse(CoapResponse coapResponse) {
if (receiveEnabled) {
receivedResponses.put(System.currentTimeMillis(), coapResponse);
}
}
#location 3
#vulnerability type THREAD_SAFETY_VIOLATION | #fixed code
@Override
public void receiveResponse(CoapResponse coapResponse) {
receivedResponses.put(System.currentTimeMillis(), coapResponse);
} | Below is the vulnerable code, please generate the patch based on the following information. |
#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 | #fixed code
@Override
public void messageReceived(ChannelHandlerContext ctx, MessageEvent me) throws Exception {
super.messageReceived(ctx, me);
} | Below is the vulnerable code, please generate the patch based on the following information. |
#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 | #fixed code
@Override
public void messageReceived(ChannelHandlerContext ctx, MessageEvent me) throws Exception {
super.messageReceived(ctx, me);
} | Below is the vulnerable code, please generate the patch based on the following information. |
#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 | #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);
} | Below is the vulnerable code, please generate the patch based on the following information. |
#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 | #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));
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
@Test public void inputFile() throws IOException {
if (Platform.getNativePlatform().isUnix()) {
File inputFile = File.createTempFile("foo", null);
FileOutputStream inputStream = new FileOutputStream(inputFile);
inputStream.write("foo".getBytes("US-ASCII"));
inputStream.close();
int[] outputPipe = { -1, -1 };
long pid = -1;
try {
assertFalse(libc.pipe(outputPipe) < 0);
assertNotSame(-1, outputPipe[0]);
assertNotSame(-1, outputPipe[1]);
List<SpawnFileAction> actions = Arrays.asList(open(inputFile.getAbsolutePath(), 0, OpenFlags.O_RDONLY.intValue(), 0444),
dup(outputPipe[1], 1));
pid = posix.posix_spawnp("cat", actions, Arrays.asList("cat", "-"), emptyEnv);
assertTrue(pid != -1);
// close the write side of the output pipe, so read() will return immediately once the process has exited
posix.libc().close(outputPipe[1]);
ByteBuffer output = ByteBuffer.allocate(100);
long nbytes = posix.libc().read(outputPipe[0], output, output.remaining());
assertEquals(3L, nbytes);
output.position((int) nbytes).flip();
byte[] bytes = new byte[output.remaining()];
output.get(bytes);
assertEquals("foo", new String(bytes).trim());
} finally {
closePipe(outputPipe);
killChild(pid);
}
}
}
#location 32
#vulnerability type RESOURCE_LEAK | #fixed code
@Test public void inputFile() throws IOException {
if (Platform.getNativePlatform().isUnix()) {
File inputFile = File.createTempFile("foo", null);
FileOutputStream inputStream = new FileOutputStream(inputFile);
inputStream.write("foo".getBytes("US-ASCII"));
inputStream.close();
int[] outputPipe = { -1, -1 };
long pid = -1;
try {
assertFalse(libc.pipe(outputPipe) < 0);
assertNotSame(-1, outputPipe[0]);
assertNotSame(-1, outputPipe[1]);
List<SpawnFileAction> actions = Arrays.asList(open(inputFile.getAbsolutePath(), 0, OpenFlags.O_RDONLY.intValue(), 0444),
dup(outputPipe[1], 1), close(outputPipe[0]));
pid = posix.posix_spawnp("cat", actions, Arrays.asList("cat", "-"), emptyEnv);
assertTrue(pid != -1);
// close the write side of the output pipe, so read() will return immediately once the process has exited
posix.libc().close(outputPipe[1]);
ByteBuffer output = ByteBuffer.allocate(100);
long nbytes = posix.libc().read(outputPipe[0], output, output.remaining());
assertEquals(3L, nbytes);
output.position((int) nbytes).flip();
byte[] bytes = new byte[output.remaining()];
output.get(bytes);
assertEquals("foo", new String(bytes).trim());
} finally {
closePipe(outputPipe);
killChild(pid);
}
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#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 | #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);
} | Below is the vulnerable code, please generate the patch based on the following information. |
#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 | #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);
} | Below is the vulnerable code, please generate the patch based on the following information. |
#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 | #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);
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
public int fpathconf(int fd, Pathconf name) {
return libc().fpathconf(fd, name);
}
#location 2
#vulnerability type NULL_DEREFERENCE | #fixed code
public int fpathconf(int fd, Pathconf name) {
return posix().fpathconf(fd, name);
} | Below is the vulnerable code, please generate the patch based on the following information. |
#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 | #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);
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
public int confstr(Confstr name, ByteBuffer buf, int len) {
return libc().confstr(name, buf, len);
}
#location 2
#vulnerability type NULL_DEREFERENCE | #fixed code
public int confstr(Confstr name, ByteBuffer buf, int len) {
return posix().confstr(name, buf, len);
} | Below is the vulnerable code, please generate the patch based on the following information. |
#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 | #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);
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#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 | #fixed code
public FileStat allocateStat() {
if (freebsdVersion >= 12) {
return new FreeBSDFileStat12(this);
} else {
return new FreeBSDFileStat(this);
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#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 | #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);
} | Below is the vulnerable code, please generate the patch based on the following information. |
#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 | #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();
}
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#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 | #fixed code
public void triggerTest(String pack, List<String> tests) throws Exception {
parallelExecution(pack, tests);
} | Below is the vulnerable code, please generate the patch based on the following information. |
#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 | #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");
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#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 | #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;
} | Below is the vulnerable code, please generate the patch based on the following information. |
#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 | #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");
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#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 | #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();
}
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#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 | #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;
} | Below is the vulnerable code, please generate the patch based on the following information. |
#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 | #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();
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#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 | #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;
} | Below is the vulnerable code, please generate the patch based on the following information. |
#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 | #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;
} | Below is the vulnerable code, please generate the patch based on the following information. |
#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 | #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;
} | Below is the vulnerable code, please generate the patch based on the following information. |
#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 | #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;
} | Below is the vulnerable code, please generate the patch based on the following information. |
#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 | #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;
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#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 | #fixed code
public AppiumServiceBuilder getAppiumServiceBuilder(String methodName) throws Exception {
String webKitPort = iosDevice.startIOSWebKit(device_udid);
return appiumMan.appiumServerForIOS(device_udid, methodName, webKitPort);
} | Below is the vulnerable code, please generate the patch based on the following information. |
#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 | #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;
} | Below is the vulnerable code, please generate the patch based on the following information. |
#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 | #fixed code
public String getIOSDeviceProductTypeAndVersion(String udid) throws InterruptedException, IOException {
return commandPrompt.runCommandThruProcessBuilder("ideviceinfo --udid "+udid+" | grep ProductType");
} | Below is the vulnerable code, please generate the patch based on the following information. |
#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 | #fixed code
public void stopRecording() throws IOException {
Integer processId = androidScreenRecordProcess.get(Thread.currentThread().getId());
stopRunningProcess(processId);
} | Below is the vulnerable code, please generate the patch based on the following information. |
#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 28
#vulnerability type NULL_DEREFERENCE | #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");
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#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 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;
}
#location 8
#vulnerability type RESOURCE_LEAK | #fixed code
public synchronized AppiumDriver<MobileElement> startAppiumServerInParallel(String methodName) throws Exception {
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 (iosDevice.checkiOSDevice(device_udid)) {
driver = new IOSDriver<>(appiumMan.getAppiumUrl(), iosNative());
} else if (!iosDevice.checkiOSDevice(device_udid)){
driver = new AndroidDriver<>(appiumMan.getAppiumUrl(), androidNative());
}
}
return driver;
} | Below is the vulnerable code, please generate the patch based on the following information. |
#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 | #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;
} | Below is the vulnerable code, please generate the patch based on the following information. |
#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 | #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;
} | Below is the vulnerable code, please generate the patch based on the following information. |
#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 | #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;
} | Below is the vulnerable code, please generate the patch based on the following information. |
#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 | #fixed code
public AppiumServiceBuilder getAppiumServiceBuilder(String methodName) throws Exception {
String webKitPort = iosDevice.startIOSWebKit(device_udid);
return appiumMan.appiumServerForIOS(device_udid, methodName, webKitPort);
} | Below is the vulnerable code, please generate the patch based on the following information. |
#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 | #fixed code
public void startingServerInstance() throws Exception {
startingServerInstance(null, null);
} | Below is the vulnerable code, please generate the patch based on the following information. |
#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 | #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();
}
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
private Map<String, List<AppiumDevice>> getDevices() throws Exception {
String platform = System.getProperty(PLATFORM);
Map<String, List<AppiumDevice>> devicesByHost = new HashMap<>();
if (capabilityManager.getCapabilities().has("hostMachines")) {
JSONArray hostMachines = capabilityManager.getHostMachineObject();
for (Object hostMachine : hostMachines) {
JSONObject hostMachineJson = (JSONObject) hostMachine;
String machineIP = hostMachineJson.getString("machineIP");
IAppiumManager appiumManager = AppiumManagerFactory.getAppiumManager(machineIP);
List<Device> devices = appiumManager.getDevices(machineIP, platform);
if (!platform.equalsIgnoreCase("android")
&& capabilityManager.isSimulatorAppPresentInCapsJson()
&& hostMachineJson.has("simulators")) {
JSONArray simulators = hostMachineJson.getJSONArray("simulators");
List<Device> simulatorsToBoot = getSimulatorsToBoot(
machineIP, simulators);
devices.addAll(simulatorsToBoot);
}
List<AppiumDevice> appiumDevices = getAppiumDevices(machineIP, devices);
devicesByHost.put(machineIP, appiumDevices);
}
} else {
throw new RuntimeException("Provide hostMachine in Caps.json for execution");
}
return devicesByHost;
}
#location 10
#vulnerability type NULL_DEREFERENCE | #fixed code
private Map<String, List<AppiumDevice>> getDevices() throws Exception {
String platform = System.getenv(PLATFORM);
Map<String, List<AppiumDevice>> devicesByHost = new HashMap<>();
if (capabilityManager.getCapabilities().has("hostMachines")) {
JSONArray hostMachines = capabilityManager.getHostMachineObject();
for (Object hostMachine : hostMachines) {
JSONObject hostMachineJson = (JSONObject) hostMachine;
String machineIP = hostMachineJson.getString("machineIP");
IAppiumManager appiumManager = AppiumManagerFactory.getAppiumManager(machineIP);
List<Device> devices = appiumManager.getDevices(machineIP, platform);
if (!platform.equalsIgnoreCase("android")
&& capabilityManager.isSimulatorAppPresentInCapsJson()
&& hostMachineJson.has("simulators")) {
JSONArray simulators = hostMachineJson.getJSONArray("simulators");
List<Device> simulatorsToBoot = getSimulatorsToBoot(
machineIP, simulators);
devices.addAll(simulatorsToBoot);
}
List<AppiumDevice> appiumDevices = getAppiumDevices(machineIP, devices);
devicesByHost.put(machineIP, appiumDevices);
}
} else {
throw new RuntimeException("Provide hostMachine in Caps.json for execution");
}
return devicesByHost;
} | Below is the vulnerable code, please generate the patch based on the following information. |
#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 | #fixed code
public void stopRecording() throws IOException {
Integer processId = androidScreenRecordProcess.get(Thread.currentThread().getId());
stopRunningProcess(processId);
} | Below is the vulnerable code, please generate the patch based on the following information. |
#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 | #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();
} | Below is the vulnerable code, please generate the patch based on the following information. |
#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 | #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");
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#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 | #fixed code
public void startingServerInstance() throws Exception {
startingServerInstance(null, null);
} | Below is the vulnerable code, please generate the patch based on the following information. |
#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 | #fixed code
public String getAppiumServerPath(String host) throws Exception {
return appiumServerProp(host, "appiumServerPath");
} | Below is the vulnerable code, please generate the patch based on the following information. |
#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 | #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;
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#vulnerable code
public void captureScreenshot(String methodName, String device, String className)
throws IOException, InterruptedException {
String context = getDriver().getContext();
boolean contextChanged = false;
if (getDriver().toString().split(":")[0].trim().equals("AndroidDriver") && !context
.equals("NATIVE_APP")) {
getDriver().context("NATIVE_APP");
contextChanged = true;
}
scrFile = ((TakesScreenshot) driver).getScreenshotAs(OutputType.FILE);
if (contextChanged) {
getDriver().context(context);
}
FileUtils.copyFile(scrFile, new File(
CI_BASE_URI + "/target/screenshot/" + device + "/" + device_udid.replaceAll("\\W", "_")
+ "/" + className + "/" + methodName + "/" + deviceModel + "_" + methodName
+ "_failed" + ".png"));
Thread.sleep(3000);
}
#location 14
#vulnerability type THREAD_SAFETY_VIOLATION | #fixed code
public void captureScreenshot(String methodName, String device, String className)
throws IOException, InterruptedException {
String context = getDriver().getContext();
boolean contextChanged = false;
if (getDriver().toString().split(":")[0].trim().equals("AndroidDriver") && !context
.equals("NATIVE_APP")) {
getDriver().context("NATIVE_APP");
contextChanged = true;
}
scrFile = ((TakesScreenshot) driver).getScreenshotAs(OutputType.FILE);
if (contextChanged) {
getDriver().context(context);
}
FileUtils.copyFile(scrFile, new File(
"screenshot/" + device + "/" + device_udid.replaceAll("\\W", "_")
+ "/" + className + "/" + methodName + "/" + deviceModel + "_" + methodName
+ "_failed" + ".png"));
Thread.sleep(3000);
} | Below is the vulnerable code, please generate the patch based on the following information. |
#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 | #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);
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#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 | #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";
} | Below is the vulnerable code, please generate the patch based on the following information. |
#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 | #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;
} | Below is the vulnerable code, please generate the patch based on the following information. |
#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 | #fixed code
public void startingServerInstance() throws Exception {
startingServerInstance(null, null);
} | Below is the vulnerable code, please generate the patch based on the following information. |
#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 | #fixed code
public AppiumServiceBuilder getAppiumServiceBuilder(String methodName) throws Exception {
String webKitPort = iosDevice.startIOSWebKit(device_udid);
return appiumMan.appiumServerForIOS(device_udid, methodName, webKitPort);
} | Below is the vulnerable code, please generate the patch based on the following information. |
#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 | #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;
} | Below is the vulnerable code, please generate the patch based on the following information. |
#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 | #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");
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#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 | #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;
} | Below is the vulnerable code, please generate the patch based on the following information. |
#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 | #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;
} | Below is the vulnerable code, please generate the patch based on the following information. |
#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 | #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;
} | Below is the vulnerable code, please generate the patch based on the following information. |
#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 6
#vulnerability type NULL_DEREFERENCE | #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);
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#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 | #fixed code
public void startingServerInstance() throws Exception {
startingServerInstance(null, null);
} | Below is the vulnerable code, please generate the patch based on the following information. |
#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 | #fixed code
public AppiumServiceBuilder getAppiumServiceBuilder(String methodName) throws Exception {
String webKitPort = iosDevice.startIOSWebKit(device_udid);
return appiumMan.appiumServerForIOS(device_udid, methodName, webKitPort);
} | Below is the vulnerable code, please generate the patch based on the following information. |
#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 | #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();
}
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#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 | #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();
} | Below is the vulnerable code, please generate the patch based on the following information. |
#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 | #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;
} | Below is the vulnerable code, please generate the patch based on the following information. |
#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 | #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);
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#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 | #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;
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#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 | #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;
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#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 24
#vulnerability type RESOURCE_LEAK | #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;
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#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 | #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");
}
} | Below is the vulnerable code, please generate the patch based on the following information. |
#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 | #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;
} | Below is the vulnerable code, please generate the patch based on the following information. |
#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 | #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;
}
} | 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.