output
stringlengths 64
73.2k
| input
stringlengths 208
73.3k
| instruction
stringclasses 1
value |
---|---|---|
#fixed code
@Test
public void testAddWorkdaysFromFriday() {
Calendar startDate = Calendar.getInstance();
// adjust to FRIDAY
startDate.set(Calendar.DAY_OF_WEEK, Calendar.FRIDAY);
System.out.println("Startdate=" + startDate.getTime());
// adjust -3 Workdays -> THUSEDAY
Assert.assertEquals(Calendar.TUESDAY,
workflowSchedulerService.addWorkDays(startDate, 2).get(Calendar.DAY_OF_WEEK));
Assert.assertEquals(Calendar.WEDNESDAY,
workflowSchedulerService.addWorkDays(startDate, 8).get(Calendar.DAY_OF_WEEK));
Assert.assertEquals(Calendar.FRIDAY,
workflowSchedulerService.addWorkDays(startDate, 10).get(Calendar.DAY_OF_WEEK));
Assert.assertEquals(Calendar.THURSDAY,
workflowSchedulerService.addWorkDays(startDate, 14).get(Calendar.DAY_OF_WEEK));
} | #vulnerable code
@Test
public void testAddWorkdaysFromFriday() {
Calendar startDate = Calendar.getInstance();
// adjust to FRIDAY
startDate.set(Calendar.DAY_OF_WEEK, Calendar.FRIDAY);
System.out.println("Startdate=" + startDate.getTime());
// adjust -3 Workdays -> THUSEDAY
Assert.assertEquals(Calendar.TUESDAY,
WorkflowSchedulerService.addWorkDays(startDate, 2).get(Calendar.DAY_OF_WEEK));
Assert.assertEquals(Calendar.WEDNESDAY,
WorkflowSchedulerService.addWorkDays(startDate, 8).get(Calendar.DAY_OF_WEEK));
Assert.assertEquals(Calendar.FRIDAY,
WorkflowSchedulerService.addWorkDays(startDate, 10).get(Calendar.DAY_OF_WEEK));
Assert.assertEquals(Calendar.THURSDAY,
WorkflowSchedulerService.addWorkDays(startDate, 14).get(Calendar.DAY_OF_WEEK));
}
#location 11
#vulnerability type NULL_DEREFERENCE | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
public void removeDocument(String uniqueID) throws LuceneException {
IndexWriter awriter = null;
long ltime = System.currentTimeMillis();
try {
awriter = createIndexWriter();
Term term = new Term("$uniqueid", uniqueID);
awriter.deleteDocuments(term);
} catch (CorruptIndexException e) {
throw new LuceneException(INVALID_INDEX, "Unable to remove workitem '" + uniqueID + "' from search index",
e);
} catch (LockObtainFailedException e) {
throw new LuceneException(INVALID_INDEX, "Unable to remove workitem '" + uniqueID + "' from search index",
e);
} catch (IOException e) {
throw new LuceneException(INVALID_INDEX, "Unable to remove workitem '" + uniqueID + "' from search index",
e);
}
finally {
// close writer!
if (awriter != null) {
logger.fine("lucene close IndexWriter...");
try {
awriter.close();
} catch (CorruptIndexException e) {
throw new LuceneException(INVALID_INDEX, "Unable to close lucene IndexWriter: ", e);
} catch (IOException e) {
throw new LuceneException(INVALID_INDEX, "Unable to close lucene IndexWriter: ", e);
}
}
}
logger.fine("lucene removeDocument in " + (System.currentTimeMillis() - ltime) + " ms");
} | #vulnerable code
public void removeDocument(String uniqueID) throws LuceneException {
IndexWriter awriter = null;
try {
awriter = createIndexWriter();
Term term = new Term("$uniqueid", uniqueID);
awriter.deleteDocuments(term);
} catch (CorruptIndexException e) {
throw new LuceneException(INVALID_INDEX, "Unable to remove workitem '" + uniqueID + "' from search index",
e);
} catch (LockObtainFailedException e) {
throw new LuceneException(INVALID_INDEX, "Unable to remove workitem '" + uniqueID + "' from search index",
e);
} catch (IOException e) {
throw new LuceneException(INVALID_INDEX, "Unable to remove workitem '" + uniqueID + "' from search index",
e);
}
}
#location 6
#vulnerability type RESOURCE_LEAK | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Test
public void testMinusWorkdaysFromFriday() {
Calendar startDate = Calendar.getInstance();
// adjust to FRIDAY
startDate.set(Calendar.DAY_OF_WEEK, Calendar.FRIDAY);
System.out.println("Startdate=" + startDate.getTime());
// adjust -3 Workdays -> THUSEDAY
Assert.assertEquals(Calendar.THURSDAY,
workflowSchedulerService.addWorkDays(startDate, -1).get(Calendar.DAY_OF_WEEK));
Assert.assertEquals(Calendar.WEDNESDAY,
workflowSchedulerService.addWorkDays(startDate, -2).get(Calendar.DAY_OF_WEEK));
Assert.assertEquals(Calendar.MONDAY,
workflowSchedulerService.addWorkDays(startDate, -4).get(Calendar.DAY_OF_WEEK));
// friday - 5
Assert.assertEquals(Calendar.FRIDAY,
workflowSchedulerService.addWorkDays(startDate, -5).get(Calendar.DAY_OF_WEEK));
Assert.assertEquals(Calendar.MONDAY,
workflowSchedulerService.addWorkDays(startDate, -9).get(Calendar.DAY_OF_WEEK));
Assert.assertEquals(Calendar.FRIDAY,
workflowSchedulerService.addWorkDays(startDate, -10).get(Calendar.DAY_OF_WEEK));
} | #vulnerable code
@Test
public void testMinusWorkdaysFromFriday() {
Calendar startDate = Calendar.getInstance();
// adjust to FRIDAY
startDate.set(Calendar.DAY_OF_WEEK, Calendar.FRIDAY);
System.out.println("Startdate=" + startDate.getTime());
// adjust -3 Workdays -> THUSEDAY
Assert.assertEquals(Calendar.THURSDAY,
WorkflowSchedulerService.addWorkDays(startDate, -1).get(Calendar.DAY_OF_WEEK));
Assert.assertEquals(Calendar.WEDNESDAY,
WorkflowSchedulerService.addWorkDays(startDate, -2).get(Calendar.DAY_OF_WEEK));
Assert.assertEquals(Calendar.MONDAY,
WorkflowSchedulerService.addWorkDays(startDate, -4).get(Calendar.DAY_OF_WEEK));
// friday - 5
Assert.assertEquals(Calendar.FRIDAY,
WorkflowSchedulerService.addWorkDays(startDate, -5).get(Calendar.DAY_OF_WEEK));
Assert.assertEquals(Calendar.MONDAY,
WorkflowSchedulerService.addWorkDays(startDate, -9).get(Calendar.DAY_OF_WEEK));
Assert.assertEquals(Calendar.FRIDAY,
WorkflowSchedulerService.addWorkDays(startDate, -10).get(Calendar.DAY_OF_WEEK));
}
#location 13
#vulnerability type NULL_DEREFERENCE | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Test
@Category(org.imixs.workflow.ItemCollection.class)
public void testFileData() {
ItemCollection itemColSource = new ItemCollection();
// add a dummy file
byte[] empty = { 0 };
itemColSource.addFileData(new FileData( "test1.txt", empty,"application/xml",null));
ItemCollection itemColTarget = new ItemCollection();
itemColTarget.addFileData(itemColSource.getFileData("test1.txt"));
FileData filedata = itemColTarget.getFileData("test1.txt");
Assert.assertNotNull(filedata);
Assert.assertEquals("test1.txt", filedata.getName());
Assert.assertEquals("application/xml", filedata.getContentType());
// test the byte content of itemColSource
byte[] file1Data1 =itemColSource.getFileData("test1.txt").getContent();
// we expect the new dummy array { 1, 2, 3 }
Assert.assertArrayEquals(empty, file1Data1);
// test the byte content of itemColTarget
file1Data1 = itemColTarget.getFileData("test1.txt").getContent();
// we expect the new dummy array { 1, 2, 3 }
Assert.assertArrayEquals(empty, file1Data1);
} | #vulnerable code
@Test
@Category(org.imixs.workflow.ItemCollection.class)
public void testFileData() {
ItemCollection itemColSource = new ItemCollection();
// add a dummy file
byte[] empty = { 0 };
itemColSource.addFile(empty, "test1.txt", "application/xml");
ItemCollection itemColTarget = new ItemCollection();
itemColTarget.addFileData(itemColSource.getFileData("test1.txt"));
FileData filedata = itemColTarget.getFileData("test1.txt");
Assert.assertNotNull(filedata);
Assert.assertEquals("test1.txt", filedata.getName());
Assert.assertEquals("application/xml", filedata.getContentType());
// test the byte content of itemColSource
Map<String, List<Object>> conedFiles1 = itemColSource.getFiles();
List<Object> fileContent1 = conedFiles1.get("test1.txt");
byte[] file1Data1 = (byte[]) fileContent1.get(1);
// we expect the new dummy array { 1, 2, 3 }
Assert.assertArrayEquals(empty, file1Data1);
// test the byte content of itemColTarget
conedFiles1 = itemColTarget.getFiles();
fileContent1 = conedFiles1.get("test1.txt");
file1Data1 = (byte[]) fileContent1.get(1);
// we expect the new dummy array { 1, 2, 3 }
Assert.assertArrayEquals(empty, file1Data1);
}
#location 21
#vulnerability type NULL_DEREFERENCE | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@DELETE
@Path("/reports/{name}")
public void deleteReport(@PathParam("name") String name) {
try {
ItemCollection itemCol = reportService.findReport(name);
entityService.remove(itemCol);
} catch (Exception e) {
e.printStackTrace();
}
} | #vulnerable code
@DELETE
@Path("/reports/{name}")
public void deleteReport(@PathParam("name") String name) {
try {
ItemCollection itemCol = reportService.getReport(name);
entityService.remove(itemCol);
} catch (Exception e) {
e.printStackTrace();
}
}
#location 6
#vulnerability type NULL_DEREFERENCE | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Test
public void testParseResult() {
List<ItemCollection> result=null;
String testString = "{\n" +
" \"responseHeader\":{\n" +
" \"status\":0,\n" +
" \"QTime\":4,\n" +
" \"params\":{\n" +
" \"q\":\"*:*\",\n" +
" \"_\":\"1567286252995\"}},\n" +
" \"response\":{\"numFound\":2,\"start\":0,\"docs\":[\n" +
" {\n" +
" \"type\":[\"model\"],\n" +
" \"id\":\"3a182d18-33d9-4951-8970-d9eaf9d337ff\",\n" +
" \"_modified\":[20190831211617],\n" +
" \"_created\":[20190831211617],\n" +
" \"_version_\":1643418672068296704},\n" +
" {\n" +
" \"type\":[\"adminp\"],\n" +
" \"id\":\"60825929-4d7d-4346-9333-afd7dbfca457\",\n" +
" \"_modified\":[20190831211618],\n" +
" \"_created\":[20190831211618],\n" +
" \"_version_\":1643418672172105728}]\n" +
" }}";
result=solrSearchService.parseQueryResult(testString);
Assert.assertEquals(2,result.size());
ItemCollection document=null;
document=result.get(0);
Assert.assertEquals("model", document.getItemValueString("type"));
Assert.assertEquals("3a182d18-33d9-4951-8970-d9eaf9d337ff", document.getItemValueString("id"));
Assert.assertEquals(1567278977000l, document.getItemValueDate("_modified").getTime());
Assert.assertEquals(1567278977000l, document.getItemValueDate("_created").getTime());
document=result.get(1);
Assert.assertEquals("adminp", document.getItemValueString("type"));
Assert.assertEquals("60825929-4d7d-4346-9333-afd7dbfca457",document.getItemValueString("id"));
Assert.assertEquals(1567278978000l, document.getItemValueDate("_created").getTime());
} | #vulnerable code
@Test
public void testParseResult() {
List<ItemCollection> result=null;
String testString = "{\n" +
" \"responseHeader\":{\n" +
" \"status\":0,\n" +
" \"QTime\":4,\n" +
" \"params\":{\n" +
" \"q\":\"*:*\",\n" +
" \"_\":\"1567286252995\"}},\n" +
" \"response\":{\"numFound\":2,\"start\":0,\"docs\":[\n" +
" {\n" +
" \"type\":[\"model\"],\n" +
" \"id\":\"3a182d18-33d9-4951-8970-d9eaf9d337ff\",\n" +
" \"_modified\":[20190831211617],\n" +
" \"_created\":[20190831211617],\n" +
" \"_version_\":1643418672068296704},\n" +
" {\n" +
" \"type\":[\"adminp\"],\n" +
" \"id\":\"60825929-4d7d-4346-9333-afd7dbfca457\",\n" +
" \"_modified\":[20190831211618],\n" +
" \"_created\":[20190831211618],\n" +
" \"_version_\":1643418672172105728}]\n" +
" }}";
result=solrSearchService.parseQueryResult(testString);
Assert.assertEquals(2,result.size());
ItemCollection document=null;
document=result.get(0);
Assert.assertEquals("model", document.getItemValueString("type"));
Assert.assertEquals("3a182d18-33d9-4951-8970-d9eaf9d337ff", document.getUniqueID());
Assert.assertEquals(1567278977000l, document.getItemValueDate("$modified").getTime());
Assert.assertEquals(1567278977000l, document.getItemValueDate("$created").getTime());
document=result.get(1);
Assert.assertEquals("adminp", document.getItemValueString("type"));
Assert.assertEquals("60825929-4d7d-4346-9333-afd7dbfca457", document.getUniqueID());
Assert.assertEquals(1567278978000l, document.getItemValueDate("$created").getTime());
}
#location 36
#vulnerability type NULL_DEREFERENCE | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Test
public void testMinusWorkdaysFromSunday() {
Calendar startDate = Calendar.getInstance();
// adjust to SATURDAY
startDate.set(Calendar.DAY_OF_WEEK, Calendar.SUNDAY);
System.out.println("Startdate=" + startDate.getTime());
// adjust -1 Workdays -> THURSDAY
Assert.assertEquals(Calendar.THURSDAY,
workflowSchedulerService.addWorkDays(startDate, -1).get(Calendar.DAY_OF_WEEK));
Assert.assertEquals(Calendar.FRIDAY,
workflowSchedulerService.addWorkDays(startDate, -5).get(Calendar.DAY_OF_WEEK));
} | #vulnerable code
@Test
public void testMinusWorkdaysFromSunday() {
Calendar startDate = Calendar.getInstance();
// adjust to SATURDAY
startDate.set(Calendar.DAY_OF_WEEK, Calendar.SUNDAY);
System.out.println("Startdate=" + startDate.getTime());
// adjust -1 Workdays -> THURSDAY
Assert.assertEquals(Calendar.THURSDAY,
WorkflowSchedulerService.addWorkDays(startDate, -1).get(Calendar.DAY_OF_WEEK));
Assert.assertEquals(Calendar.FRIDAY,
WorkflowSchedulerService.addWorkDays(startDate, -5).get(Calendar.DAY_OF_WEEK));
}
#location 11
#vulnerability type NULL_DEREFERENCE | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@SuppressWarnings({ "unchecked", "rawtypes" })
@Override
public void endElement(String uri, String localName, String qName) throws SAXException {
// end of bpmn2:process
if (qName.equalsIgnoreCase("bpmn2:process")) {
if (currentWorkflowGroup != null) {
currentWorkflowGroup = null;
}
}
// end of bpmn2:task -
if (bImixsTask && qName.equalsIgnoreCase("bpmn2:task")) {
bImixsTask = false;
taskCache.put(bpmnID, currentEntity);
}
if (qName.equalsIgnoreCase("bpmn2:extensionElements")) {
bExtensionElements = false;
}
// end of bpmn2:intermediateCatchEvent -
if (bImixsEvent && (qName.equalsIgnoreCase("bpmn2:intermediateCatchEvent")
|| qName.equalsIgnoreCase("bpmn2:intermediateThrowEvent"))) {
bImixsEvent = false;
// we need to cache the activities because the sequenceflows must be
// analysed later
eventCache.put(bpmnID, currentEntity);
}
/*
* End of a imixs:value
*/
if (qName.equalsIgnoreCase("imixs:value")) {
if (bExtensionElements && bItemValue && currentEntity != null && characterStream != null) {
String svalue = characterStream.toString();
List valueList = currentEntity.getItemValue(currentItemName);
if ("xs:boolean".equals(currentItemType.toLowerCase())) {
valueList.add(Boolean.valueOf(svalue));
} else if ("xs:integer".equals(currentItemType.toLowerCase())) {
valueList.add(Integer.valueOf(svalue));
} else {
valueList.add(svalue);
}
// item will only be added if it is not listed in the ignoreItem
// List!
if (!ignoreItemList.contains(currentItemName)) {
currentEntity.replaceItemValue(currentItemName, valueList);
}
}
bItemValue = false;
characterStream = null;
}
if (qName.equalsIgnoreCase("bpmn2:documentation")) {
if (currentEntity != null) {
currentEntity.replaceItemValue("rtfdescription", characterStream.toString());
}
// bpmn2:message?
if (bMessage) {
// cache the message...
messageCache.put(currentMessageName, characterStream.toString());
bMessage = false;
}
// bpmn2:annotation?
if (bAnnotation) {
// cache the annotation
annotationCache.put(currentAnnotationName, characterStream.toString());
bAnnotation = false;
}
characterStream = null;
bdocumentation = false;
}
// end of bpmn2:intermediateThrowEvent -
if (bLinkThrowEvent && !bLinkCatchEvent && (qName.equalsIgnoreCase("bpmn2:linkEventDefinition"))) {
bLinkThrowEvent = false;
// we need to cache the link name
linkThrowEventCache.put(bpmnID, currentLinkName);
}
// end of bpmn2:intermediateCatchEvent -
if (bLinkCatchEvent && !bLinkThrowEvent && (qName.equalsIgnoreCase("bpmn2:linkEventDefinition"))) {
bLinkCatchEvent = false;
// we need to cache the link name
linkCatchEventCache.put(currentLinkName, bpmnID);
}
// test conditional sequence flow...
if (bSequenceFlow && bconditionExpression && qName.equalsIgnoreCase("bpmn2:conditionExpression")) {
String svalue = characterStream.toString();
logger.fine("conditional SequenceFlow:" + bpmnID + "=" + svalue);
bconditionExpression = false;
conditionCache.put(bpmnID, svalue);
}
} | #vulnerable code
@SuppressWarnings({ "unchecked", "rawtypes" })
@Override
public void endElement(String uri, String localName, String qName) throws SAXException {
// end of bpmn2:process
if (qName.equalsIgnoreCase("bpmn2:process")) {
if (currentWorkflowGroup != null) {
currentWorkflowGroup = null;
}
}
// end of bpmn2:task -
if (bImixsTask && qName.equalsIgnoreCase("bpmn2:task")) {
bImixsTask = false;
taskCache.put(bpmnID, currentEntity);
}
if (qName.equalsIgnoreCase("bpmn2:extensionElements")) {
bExtensionElements = false;
}
// end of bpmn2:intermediateCatchEvent -
if (bImixsEvent && (qName.equalsIgnoreCase("bpmn2:intermediateCatchEvent")
|| qName.equalsIgnoreCase("bpmn2:intermediateThrowEvent"))) {
bImixsEvent = false;
// we need to cache the activities because the sequenceflows must be
// analysed later
eventCache.put(bpmnID, currentEntity);
}
/*
* End of a imixs:value
*/
if (qName.equalsIgnoreCase("imixs:value")) {
if (bExtensionElements && bItemValue && currentEntity != null && characterStream != null) {
String svalue = characterStream.toString();
List valueList = currentEntity.getItemValue(currentItemName);
if ("xs:boolean".equals(currentItemType.toLowerCase())) {
valueList.add(Boolean.valueOf(svalue));
} else if ("xs:integer".equals(currentItemType.toLowerCase())) {
valueList.add(Integer.valueOf(svalue));
} else {
valueList.add(svalue);
}
// item will only be added if it is not listed in the ignoreItem
// List!
if (!ignoreItemList.contains(currentItemName)) {
currentEntity.replaceItemValue(currentItemName, valueList);
}
}
bItemValue = false;
characterStream = null;
}
if (qName.equalsIgnoreCase("bpmn2:documentation")) {
if (currentEntity != null) {
currentEntity.replaceItemValue("rtfdescription", characterStream.toString());
}
// bpmn2:message?
if (bMessage) {
// cache the message...
messageCache.put(currentMessageName, characterStream.toString());
bMessage = false;
}
// bpmn2:annotation?
if (bAnnotation) {
// cache the annotation
annotationCache.put(currentAnnotationName, characterStream.toString());
bAnnotation = false;
}
characterStream = null;
bdocumentation = false;
}
// end of bpmn2:intermediateThrowEvent -
if (bLinkThrowEvent && !bLinkCatchEvent && (qName.equalsIgnoreCase("bpmn2:linkEventDefinition"))) {
bLinkThrowEvent = false;
// we need to cache the link name
linkThrowEventCache.put(bpmnID, currentLinkName);
}
// end of bpmn2:intermediateCatchEvent -
if (bLinkCatchEvent && !bLinkThrowEvent && (qName.equalsIgnoreCase("bpmn2:linkEventDefinition"))) {
bLinkCatchEvent = false;
// we need to cache the link name
linkCatchEventCache.put(currentLinkName, bpmnID);
}
}
#location 60
#vulnerability type NULL_DEREFERENCE | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
public List<ItemCollection> getActivities() {
if (activityList != null)
return activityList;
activityList = new ArrayList<ItemCollection>();
if (getWorkitem() == null)
return activityList;
int processId = getWorkitem().getItemValueInteger("$processid");
if (processId == 0)
return activityList;
// verify if modelversion is defined by workitem
String sversion = getWorkitem().getItemValueString("$modelversion");
if (sversion == null || "".equals(sversion)) {
try {
// try to get latest version...
sversion = this.getModelService().getLatestVersionByWorkitem(
getWorkitem());
} catch (ModelException e) {
logger.warning("[WorkflwoControler] unable to getactivitylist: "
+ e.getMessage());
}
}
// get Workflow-Activities by version
List<ItemCollection> col = null;
col = this.getModelService().getPublicActivities(processId, sversion);
if (col == null || col.size() == 0) {
// try to upgrade model version
try {
sversion = this.getModelService().getLatestVersionByWorkitem(
getWorkitem());
col = this.getModelService().getPublicActivities(processId,
sversion);
} catch (ModelException e) {
logger.warning("[WorkflwoControler] unable to getactivitylist: "
+ e.getMessage());
}
}
for (ItemCollection aworkitem : col) {
activityList.add(aworkitem);
}
return activityList;
} | #vulnerable code
public List<ItemCollection> getActivities() {
if (activityList != null)
return activityList;
activityList = new ArrayList<ItemCollection>();
if (getWorkitem() == null)
return activityList;
int processId = getWorkitem().getItemValueInteger("$processid");
if (processId == 0)
return activityList;
String sversion = getWorkitem().getItemValueString("$modelversion");
// get Workflow-Activities by version if provided by the workitem
List<ItemCollection> col = null;
if (sversion != null && !"".equals(sversion))
col = this.getModelService().getPublicActivities(processId,
sversion);
for (ItemCollection aworkitem : col) {
activityList.add(aworkitem);
}
return activityList;
}
#location 23
#vulnerability type NULL_DEREFERENCE | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
public ItemCollection load(String id) {
long lLoadTime = System.currentTimeMillis();
Document persistedDocument = null;
if (id == null || id.isEmpty()) {
return null;
}
persistedDocument = manager.find(Document.class, id);
// create instance of ItemCollection
if (persistedDocument != null && isCallerReader(persistedDocument)) {
ItemCollection result = null;// new ItemCollection();
if (persistedDocument.isPending()) {
// we clone but do not detach
logger.finest("......clone manged entity '" + id + "' pending status=" + persistedDocument.isPending());
result = new ItemCollection(persistedDocument.getData());
} else {
// the document is not managed, so we detach it
result = new ItemCollection();
result.setAllItems(persistedDocument.getData());
manager.detach(persistedDocument);
}
// if disable Optimistic Locking is TRUE we do not add the version
// number
if (disableOptimisticLocking) {
result.removeItem("$Version");
} else {
result.replaceItemValue("$Version", persistedDocument.getVersion());
}
// update the $isauthor flag
result.replaceItemValue("$isauthor", isCallerAuthor(persistedDocument));
// fire event
if (documentEvents != null) {
documentEvents.fire(new DocumentEvent(result, DocumentEvent.ON_DOCUMENT_LOAD));
} else {
logger.warning("Missing CDI support for Event<DocumentEvent> !");
}
logger.fine(
"...'" + result.getUniqueID() + "' loaded in " + (System.currentTimeMillis() - lLoadTime) + "ms");
return result;
} else
return null;
} | #vulnerable code
public ItemCollection load(String id) {
long lLoadTime = System.currentTimeMillis();
Document persistedDocument = null;
if (id==null || id.isEmpty()) {
return null;
}
persistedDocument = manager.find(Document.class, id);
// create instance of ItemCollection
if (persistedDocument != null && isCallerReader(persistedDocument)) {
ItemCollection result = null;// new ItemCollection();
if (persistedDocument.isPending()) {
// we clone but do not detach
logger.finest("......clone manged entity '" + id + "' pending status=" + persistedDocument.isPending());
result = new ItemCollection(persistedDocument.getData());
} else {
// the document is not managed, so we detach it
result = new ItemCollection();
result.setAllItems(persistedDocument.getData());
manager.detach(persistedDocument);
}
// if disable Optimistic Locking is TRUE we do not add the version
// number
if (disableOptimisticLocking) {
result.removeItem("$Version");
} else {
result.replaceItemValue("$Version", persistedDocument.getVersion());
}
// update the $isauthor flag
result.replaceItemValue("$isauthor", isCallerAuthor(persistedDocument));
// fire event
if (events != null) {
events.fire(new DocumentEvent(result, DocumentEvent.ON_DOCUMENT_LOAD));
} else {
logger.warning("Missing CDI support for Event<DocumentEvent> !");
}
logger.fine(
"...'" + result.getUniqueID() + "' loaded in " + (System.currentTimeMillis() - lLoadTime) + "ms");
return result;
} else
return null;
}
#location 43
#vulnerability type NULL_DEREFERENCE | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Test
public void testParseResult() {
List<ItemCollection> result=null;
String testString = "{\n" +
" \"responseHeader\":{\n" +
" \"status\":0,\n" +
" \"QTime\":4,\n" +
" \"params\":{\n" +
" \"q\":\"*:*\",\n" +
" \"_\":\"1567286252995\"}},\n" +
" \"response\":{\"numFound\":2,\"start\":0,\"docs\":[\n" +
" {\n" +
" \"type\":[\"model\"],\n" +
" \"id\":\"3a182d18-33d9-4951-8970-d9eaf9d337ff\",\n" +
" \"_modified\":[20190831211617],\n" +
" \"_created\":[20190831211617],\n" +
" \"_version_\":1643418672068296704},\n" +
" {\n" +
" \"type\":[\"adminp\"],\n" +
" \"id\":\"60825929-4d7d-4346-9333-afd7dbfca457\",\n" +
" \"_modified\":[20190831211618],\n" +
" \"_created\":[20190831211618],\n" +
" \"_version_\":1643418672172105728}]\n" +
" }}";
result=solrSearchService.parseQueryResult(testString);
Assert.assertEquals(2,result.size());
ItemCollection document=null;
document=result.get(0);
Assert.assertEquals("model", document.getItemValueString("type"));
Assert.assertEquals("3a182d18-33d9-4951-8970-d9eaf9d337ff", document.getItemValueString("id"));
Calendar cal=Calendar.getInstance();
cal.setTime(document.getItemValueDate("_modified"));
Assert.assertEquals(7,cal.get(Calendar.MONTH));
Assert.assertEquals(31,cal.get(Calendar.DAY_OF_MONTH));
document=result.get(1);
Assert.assertEquals("adminp", document.getItemValueString("type"));
} | #vulnerable code
@Test
public void testParseResult() {
List<ItemCollection> result=null;
String testString = "{\n" +
" \"responseHeader\":{\n" +
" \"status\":0,\n" +
" \"QTime\":4,\n" +
" \"params\":{\n" +
" \"q\":\"*:*\",\n" +
" \"_\":\"1567286252995\"}},\n" +
" \"response\":{\"numFound\":2,\"start\":0,\"docs\":[\n" +
" {\n" +
" \"type\":[\"model\"],\n" +
" \"id\":\"3a182d18-33d9-4951-8970-d9eaf9d337ff\",\n" +
" \"_modified\":[20190831211617],\n" +
" \"_created\":[20190831211617],\n" +
" \"_version_\":1643418672068296704},\n" +
" {\n" +
" \"type\":[\"adminp\"],\n" +
" \"id\":\"60825929-4d7d-4346-9333-afd7dbfca457\",\n" +
" \"_modified\":[20190831211618],\n" +
" \"_created\":[20190831211618],\n" +
" \"_version_\":1643418672172105728}]\n" +
" }}";
result=solrSearchService.parseQueryResult(testString);
Assert.assertEquals(2,result.size());
ItemCollection document=null;
document=result.get(0);
Assert.assertEquals("model", document.getItemValueString("type"));
Assert.assertEquals("3a182d18-33d9-4951-8970-d9eaf9d337ff", document.getItemValueString("id"));
Assert.assertEquals(1567278977000l, document.getItemValueDate("_modified").getTime());
Assert.assertEquals(1567278977000l, document.getItemValueDate("_created").getTime());
document=result.get(1);
Assert.assertEquals("adminp", document.getItemValueString("type"));
Assert.assertEquals("60825929-4d7d-4346-9333-afd7dbfca457",document.getItemValueString("id"));
Assert.assertEquals(1567278978000l, document.getItemValueDate("_created").getTime());
}
#location 36
#vulnerability type NULL_DEREFERENCE | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Test
public void testMinusWorkdaysFromFriday() {
Calendar startDate = Calendar.getInstance();
// adjust to FRIDAY
startDate.set(Calendar.DAY_OF_WEEK, Calendar.FRIDAY);
System.out.println("Startdate=" + startDate.getTime());
// adjust -3 Workdays -> THUSEDAY
Assert.assertEquals(Calendar.THURSDAY,
workflowSchedulerService.addWorkDays(startDate, -1).get(Calendar.DAY_OF_WEEK));
Assert.assertEquals(Calendar.WEDNESDAY,
workflowSchedulerService.addWorkDays(startDate, -2).get(Calendar.DAY_OF_WEEK));
Assert.assertEquals(Calendar.MONDAY,
workflowSchedulerService.addWorkDays(startDate, -4).get(Calendar.DAY_OF_WEEK));
// friday - 5
Assert.assertEquals(Calendar.FRIDAY,
workflowSchedulerService.addWorkDays(startDate, -5).get(Calendar.DAY_OF_WEEK));
Assert.assertEquals(Calendar.MONDAY,
workflowSchedulerService.addWorkDays(startDate, -9).get(Calendar.DAY_OF_WEEK));
Assert.assertEquals(Calendar.FRIDAY,
workflowSchedulerService.addWorkDays(startDate, -10).get(Calendar.DAY_OF_WEEK));
} | #vulnerable code
@Test
public void testMinusWorkdaysFromFriday() {
Calendar startDate = Calendar.getInstance();
// adjust to FRIDAY
startDate.set(Calendar.DAY_OF_WEEK, Calendar.FRIDAY);
System.out.println("Startdate=" + startDate.getTime());
// adjust -3 Workdays -> THUSEDAY
Assert.assertEquals(Calendar.THURSDAY,
WorkflowSchedulerService.addWorkDays(startDate, -1).get(Calendar.DAY_OF_WEEK));
Assert.assertEquals(Calendar.WEDNESDAY,
WorkflowSchedulerService.addWorkDays(startDate, -2).get(Calendar.DAY_OF_WEEK));
Assert.assertEquals(Calendar.MONDAY,
WorkflowSchedulerService.addWorkDays(startDate, -4).get(Calendar.DAY_OF_WEEK));
// friday - 5
Assert.assertEquals(Calendar.FRIDAY,
WorkflowSchedulerService.addWorkDays(startDate, -5).get(Calendar.DAY_OF_WEEK));
Assert.assertEquals(Calendar.MONDAY,
WorkflowSchedulerService.addWorkDays(startDate, -9).get(Calendar.DAY_OF_WEEK));
Assert.assertEquals(Calendar.FRIDAY,
WorkflowSchedulerService.addWorkDays(startDate, -10).get(Calendar.DAY_OF_WEEK));
}
#location 20
#vulnerability type NULL_DEREFERENCE | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Test
public void testAddWorkdaysFromSunday() {
Calendar startDate = Calendar.getInstance();
// adjust to SATURDAY
startDate.set(Calendar.DAY_OF_WEEK, Calendar.SUNDAY);
System.out.println("Startdate=" + startDate.getTime());
// adjust -1 Workdays -> TUESDAY
Assert.assertEquals(Calendar.TUESDAY,
workflowSchedulerService.addWorkDays(startDate, 1).get(Calendar.DAY_OF_WEEK));
Assert.assertEquals(Calendar.FRIDAY,
workflowSchedulerService.addWorkDays(startDate, 4).get(Calendar.DAY_OF_WEEK));
Assert.assertEquals(Calendar.MONDAY,
workflowSchedulerService.addWorkDays(startDate, 5).get(Calendar.DAY_OF_WEEK));
} | #vulnerable code
@Test
public void testAddWorkdaysFromSunday() {
Calendar startDate = Calendar.getInstance();
// adjust to SATURDAY
startDate.set(Calendar.DAY_OF_WEEK, Calendar.SUNDAY);
System.out.println("Startdate=" + startDate.getTime());
// adjust -1 Workdays -> TUESDAY
Assert.assertEquals(Calendar.TUESDAY,
WorkflowSchedulerService.addWorkDays(startDate, 1).get(Calendar.DAY_OF_WEEK));
Assert.assertEquals(Calendar.FRIDAY,
WorkflowSchedulerService.addWorkDays(startDate, 4).get(Calendar.DAY_OF_WEEK));
Assert.assertEquals(Calendar.MONDAY,
WorkflowSchedulerService.addWorkDays(startDate, 5).get(Calendar.DAY_OF_WEEK));
}
#location 11
#vulnerability type NULL_DEREFERENCE | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@GET
@Path("/{name}.ixr")
public Response getExcecuteReport(@PathParam("name") String name, @DefaultValue("0") @QueryParam("start") int start,
@DefaultValue("10") @QueryParam("count") int count,
@DefaultValue("") @QueryParam("encoding") String encoding, @Context UriInfo uriInfo) {
Collection<ItemCollection> col = null;
String reportName = null;
String sXSL;
String sContentType;
try {
reportName = name + ".ixr";
ItemCollection itemCol = reportService.getReport(reportName);
if (itemCol==null) {
logger.severe("Report '" +reportName + "' not defined!");
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).build();
}
sXSL = itemCol.getItemValueString("txtXSL").trim();
sContentType = itemCol.getItemValueString("txtcontenttype");
if ("".equals(sContentType))
sContentType = "text/html";
// if no encoding is provided by the query string than the encoding
// from the report will be taken
if ("".equals(encoding))
encoding = itemCol.getItemValueString("txtencoding");
// no encoding defined so take a default encoding
// (UTF-8)
if ("".equals(encoding))
encoding = "UTF-8";
// execute report
Map<String, String> params = getQueryParams(uriInfo);
col = reportService.executeReport(reportName, start, count, params, null);
// if no XSL is provided return standard html format...?
if ("".equals(sXSL)) {
Response.ResponseBuilder builder = Response.ok(XMLItemCollectionAdapter.putCollection(col),
"text/html");
return builder.build();
}
// Transform XML per XSL and generate output
DocumentCollection xmlCol = XMLItemCollectionAdapter.putCollection(col);
StringWriter writer = new StringWriter();
JAXBContext context = JAXBContext.newInstance(DocumentCollection.class);
Marshaller m = context.createMarshaller();
m.setProperty("jaxb.encoding", encoding);
m.marshal(xmlCol, writer);
// create a ByteArray Output Stream
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
try {
// test if FOP Tranformation
if ("application/pdf".equals(sContentType.toLowerCase()))
ReportRestService.fopTranformation(writer.toString(), sXSL, encoding, outputStream);
else
ReportRestService.xslTranformation(writer.toString(), sXSL, encoding, outputStream);
} finally {
outputStream.close();
}
/*
* outputStream.toByteArray() did not work here because the encoding
* will not be considered. For that reason we use the
* toString(encoding) method here.
*
* 8.9.2012:
*
* after some tests we see that only toByteArray will work on things
* like fop processing. So for that reason we switched back to the
* toByteArray method again. But we still need to solve the encoding
* issue
*/
Response.ResponseBuilder builder = Response.ok(outputStream.toByteArray(), sContentType);
// Response.ResponseBuilder builder = Response.ok(
// outputStream.toString(encoding), sContentType);
return builder.build();
} catch (Exception e) {
e.printStackTrace();
}
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).build();
} | #vulnerable code
@GET
@Path("/{name}.ixr")
public Response getExcecuteReport(@PathParam("name") String name, @DefaultValue("0") @QueryParam("start") int start,
@DefaultValue("10") @QueryParam("count") int count,
@DefaultValue("") @QueryParam("encoding") String encoding, @Context UriInfo uriInfo) {
Collection<ItemCollection> col = null;
String reportName = null;
String sXSL;
String sContentType;
try {
reportName = name + ".ixr";
ItemCollection itemCol = reportService.getReport(reportName);
sXSL = itemCol.getItemValueString("txtXSL").trim();
sContentType = itemCol.getItemValueString("txtcontenttype");
if ("".equals(sContentType))
sContentType = "text/html";
// if no encoding is provided by the query string than the encoding
// from the report will be taken
if ("".equals(encoding))
encoding = itemCol.getItemValueString("txtencoding");
// no encoding defined so take a default encoding
// (UTF-8)
if ("".equals(encoding))
encoding = "UTF-8";
// execute report
Map<String, String> params = getQueryParams(uriInfo);
col = reportService.executeReport(reportName, start, count, params, null);
// if no XSL is provided return standard html format...?
if ("".equals(sXSL)) {
Response.ResponseBuilder builder = Response.ok(XMLItemCollectionAdapter.putCollection(col),
"text/html");
return builder.build();
}
// Transform XML per XSL and generate output
DocumentCollection xmlCol = XMLItemCollectionAdapter.putCollection(col);
StringWriter writer = new StringWriter();
JAXBContext context = JAXBContext.newInstance(DocumentCollection.class);
Marshaller m = context.createMarshaller();
m.setProperty("jaxb.encoding", encoding);
m.marshal(xmlCol, writer);
// create a ByteArray Output Stream
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
try {
// test if FOP Tranformation
if ("application/pdf".equals(sContentType.toLowerCase()))
ReportRestService.fopTranformation(writer.toString(), sXSL, encoding, outputStream);
else
ReportRestService.xslTranformation(writer.toString(), sXSL, encoding, outputStream);
} finally {
outputStream.close();
}
/*
* outputStream.toByteArray() did not work here because the encoding
* will not be considered. For that reason we use the
* toString(encoding) method here.
*
* 8.9.2012:
*
* after some tests we see that only toByteArray will work on things
* like fop processing. So for that reason we switched back to the
* toByteArray method again. But we still need to solve the encoding
* issue
*/
Response.ResponseBuilder builder = Response.ok(outputStream.toByteArray(), sContentType);
// Response.ResponseBuilder builder = Response.ok(
// outputStream.toString(encoding), sContentType);
return builder.build();
} catch (Exception e) {
e.printStackTrace();
}
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).build();
}
#location 15
#vulnerability type NULL_DEREFERENCE | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Test
public void testAddWorkdaysFromMonday() {
Calendar startDate = Calendar.getInstance();
// adjust to FRIDAY
startDate.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY);
System.out.println("Startdate=" + startDate.getTime());
Assert.assertEquals(Calendar.TUESDAY,
workflowSchedulerService.addWorkDays(startDate, 1).get(Calendar.DAY_OF_WEEK));
Assert.assertEquals(Calendar.WEDNESDAY,
workflowSchedulerService.addWorkDays(startDate, 2).get(Calendar.DAY_OF_WEEK));
Assert.assertEquals(Calendar.FRIDAY,
workflowSchedulerService.addWorkDays(startDate, 4).get(Calendar.DAY_OF_WEEK));
Assert.assertEquals(Calendar.MONDAY,
workflowSchedulerService.addWorkDays(startDate, 5).get(Calendar.DAY_OF_WEEK));
Assert.assertEquals(Calendar.FRIDAY,
workflowSchedulerService.addWorkDays(startDate, 9).get(Calendar.DAY_OF_WEEK));
Assert.assertEquals(Calendar.MONDAY,
workflowSchedulerService.addWorkDays(startDate, 10).get(Calendar.DAY_OF_WEEK));
} | #vulnerable code
@Test
public void testAddWorkdaysFromMonday() {
Calendar startDate = Calendar.getInstance();
// adjust to FRIDAY
startDate.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY);
System.out.println("Startdate=" + startDate.getTime());
Assert.assertEquals(Calendar.TUESDAY,
WorkflowSchedulerService.addWorkDays(startDate, 1).get(Calendar.DAY_OF_WEEK));
Assert.assertEquals(Calendar.WEDNESDAY,
WorkflowSchedulerService.addWorkDays(startDate, 2).get(Calendar.DAY_OF_WEEK));
Assert.assertEquals(Calendar.FRIDAY,
WorkflowSchedulerService.addWorkDays(startDate, 4).get(Calendar.DAY_OF_WEEK));
Assert.assertEquals(Calendar.MONDAY,
WorkflowSchedulerService.addWorkDays(startDate, 5).get(Calendar.DAY_OF_WEEK));
Assert.assertEquals(Calendar.FRIDAY,
WorkflowSchedulerService.addWorkDays(startDate, 9).get(Calendar.DAY_OF_WEEK));
Assert.assertEquals(Calendar.MONDAY,
WorkflowSchedulerService.addWorkDays(startDate, 10).get(Calendar.DAY_OF_WEEK));
}
#location 13
#vulnerability type NULL_DEREFERENCE | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Test
public void testMinusWorkdaysFromFriday() {
Calendar startDate = Calendar.getInstance();
// adjust to FRIDAY
startDate.set(Calendar.DAY_OF_WEEK, Calendar.FRIDAY);
System.out.println("Startdate=" + startDate.getTime());
// adjust -3 Workdays -> THUSEDAY
Assert.assertEquals(Calendar.THURSDAY,
workflowSchedulerService.addWorkDays(startDate, -1).get(Calendar.DAY_OF_WEEK));
Assert.assertEquals(Calendar.WEDNESDAY,
workflowSchedulerService.addWorkDays(startDate, -2).get(Calendar.DAY_OF_WEEK));
Assert.assertEquals(Calendar.MONDAY,
workflowSchedulerService.addWorkDays(startDate, -4).get(Calendar.DAY_OF_WEEK));
// friday - 5
Assert.assertEquals(Calendar.FRIDAY,
workflowSchedulerService.addWorkDays(startDate, -5).get(Calendar.DAY_OF_WEEK));
Assert.assertEquals(Calendar.MONDAY,
workflowSchedulerService.addWorkDays(startDate, -9).get(Calendar.DAY_OF_WEEK));
Assert.assertEquals(Calendar.FRIDAY,
workflowSchedulerService.addWorkDays(startDate, -10).get(Calendar.DAY_OF_WEEK));
} | #vulnerable code
@Test
public void testMinusWorkdaysFromFriday() {
Calendar startDate = Calendar.getInstance();
// adjust to FRIDAY
startDate.set(Calendar.DAY_OF_WEEK, Calendar.FRIDAY);
System.out.println("Startdate=" + startDate.getTime());
// adjust -3 Workdays -> THUSEDAY
Assert.assertEquals(Calendar.THURSDAY,
WorkflowSchedulerService.addWorkDays(startDate, -1).get(Calendar.DAY_OF_WEEK));
Assert.assertEquals(Calendar.WEDNESDAY,
WorkflowSchedulerService.addWorkDays(startDate, -2).get(Calendar.DAY_OF_WEEK));
Assert.assertEquals(Calendar.MONDAY,
WorkflowSchedulerService.addWorkDays(startDate, -4).get(Calendar.DAY_OF_WEEK));
// friday - 5
Assert.assertEquals(Calendar.FRIDAY,
WorkflowSchedulerService.addWorkDays(startDate, -5).get(Calendar.DAY_OF_WEEK));
Assert.assertEquals(Calendar.MONDAY,
WorkflowSchedulerService.addWorkDays(startDate, -9).get(Calendar.DAY_OF_WEEK));
Assert.assertEquals(Calendar.FRIDAY,
WorkflowSchedulerService.addWorkDays(startDate, -10).get(Calendar.DAY_OF_WEEK));
}
#location 15
#vulnerability type NULL_DEREFERENCE | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Test
public void testAddWorkdaysFromSunday() {
Calendar startDate = Calendar.getInstance();
// adjust to SATURDAY
startDate.set(Calendar.DAY_OF_WEEK, Calendar.SUNDAY);
System.out.println("Startdate=" + startDate.getTime());
// adjust -1 Workdays -> TUESDAY
Assert.assertEquals(Calendar.TUESDAY,
workflowSchedulerService.addWorkDays(startDate, 1).get(Calendar.DAY_OF_WEEK));
Assert.assertEquals(Calendar.FRIDAY,
workflowSchedulerService.addWorkDays(startDate, 4).get(Calendar.DAY_OF_WEEK));
Assert.assertEquals(Calendar.MONDAY,
workflowSchedulerService.addWorkDays(startDate, 5).get(Calendar.DAY_OF_WEEK));
} | #vulnerable code
@Test
public void testAddWorkdaysFromSunday() {
Calendar startDate = Calendar.getInstance();
// adjust to SATURDAY
startDate.set(Calendar.DAY_OF_WEEK, Calendar.SUNDAY);
System.out.println("Startdate=" + startDate.getTime());
// adjust -1 Workdays -> TUESDAY
Assert.assertEquals(Calendar.TUESDAY,
WorkflowSchedulerService.addWorkDays(startDate, 1).get(Calendar.DAY_OF_WEEK));
Assert.assertEquals(Calendar.FRIDAY,
WorkflowSchedulerService.addWorkDays(startDate, 4).get(Calendar.DAY_OF_WEEK));
Assert.assertEquals(Calendar.MONDAY,
WorkflowSchedulerService.addWorkDays(startDate, 5).get(Calendar.DAY_OF_WEEK));
}
#location 14
#vulnerability type NULL_DEREFERENCE | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Test
public void testParseResult() {
List<ItemCollection> result=null;
String testString = "{\n" +
" \"responseHeader\":{\n" +
" \"status\":0,\n" +
" \"QTime\":4,\n" +
" \"params\":{\n" +
" \"q\":\"*:*\",\n" +
" \"_\":\"1567286252995\"}},\n" +
" \"response\":{\"numFound\":2,\"start\":0,\"docs\":[\n" +
" {\n" +
" \"type\":[\"model\"],\n" +
" \"id\":\"3a182d18-33d9-4951-8970-d9eaf9d337ff\",\n" +
" \"_modified\":[20190831211617],\n" +
" \"_created\":[20190831211617],\n" +
" \"_version_\":1643418672068296704},\n" +
" {\n" +
" \"type\":[\"adminp\"],\n" +
" \"id\":\"60825929-4d7d-4346-9333-afd7dbfca457\",\n" +
" \"_modified\":[20190831211618],\n" +
" \"_created\":[20190831211618],\n" +
" \"_version_\":1643418672172105728}]\n" +
" }}";
result=solrSearchService.parseQueryResult(testString);
Assert.assertEquals(2,result.size());
ItemCollection document=null;
document=result.get(0);
Assert.assertEquals("model", document.getItemValueString("type"));
Assert.assertEquals("3a182d18-33d9-4951-8970-d9eaf9d337ff", document.getItemValueString("id"));
Assert.assertEquals(1567278977000l, document.getItemValueDate("_modified").getTime());
Assert.assertEquals(1567278977000l, document.getItemValueDate("_created").getTime());
document=result.get(1);
Assert.assertEquals("adminp", document.getItemValueString("type"));
Assert.assertEquals("60825929-4d7d-4346-9333-afd7dbfca457",document.getItemValueString("id"));
Assert.assertEquals(1567278978000l, document.getItemValueDate("_created").getTime());
} | #vulnerable code
@Test
public void testParseResult() {
List<ItemCollection> result=null;
String testString = "{\n" +
" \"responseHeader\":{\n" +
" \"status\":0,\n" +
" \"QTime\":4,\n" +
" \"params\":{\n" +
" \"q\":\"*:*\",\n" +
" \"_\":\"1567286252995\"}},\n" +
" \"response\":{\"numFound\":2,\"start\":0,\"docs\":[\n" +
" {\n" +
" \"type\":[\"model\"],\n" +
" \"id\":\"3a182d18-33d9-4951-8970-d9eaf9d337ff\",\n" +
" \"_modified\":[20190831211617],\n" +
" \"_created\":[20190831211617],\n" +
" \"_version_\":1643418672068296704},\n" +
" {\n" +
" \"type\":[\"adminp\"],\n" +
" \"id\":\"60825929-4d7d-4346-9333-afd7dbfca457\",\n" +
" \"_modified\":[20190831211618],\n" +
" \"_created\":[20190831211618],\n" +
" \"_version_\":1643418672172105728}]\n" +
" }}";
result=solrSearchService.parseQueryResult(testString);
Assert.assertEquals(2,result.size());
ItemCollection document=null;
document=result.get(0);
Assert.assertEquals("model", document.getItemValueString("type"));
Assert.assertEquals("3a182d18-33d9-4951-8970-d9eaf9d337ff", document.getUniqueID());
Assert.assertEquals(1567278977000l, document.getItemValueDate("$modified").getTime());
Assert.assertEquals(1567278977000l, document.getItemValueDate("$created").getTime());
document=result.get(1);
Assert.assertEquals("adminp", document.getItemValueString("type"));
Assert.assertEquals("60825929-4d7d-4346-9333-afd7dbfca457", document.getUniqueID());
Assert.assertEquals(1567278978000l, document.getItemValueDate("$created").getTime());
}
#location 42
#vulnerability type NULL_DEREFERENCE | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@SuppressWarnings({ "unchecked", "rawtypes" })
@Override
public void endElement(String uri, String localName, String qName) throws SAXException {
// end of bpmn2:process
if (qName.equalsIgnoreCase("bpmn2:process")) {
if (currentWorkflowGroup != null) {
currentWorkflowGroup = null;
}
}
// end of bpmn2:task -
if (bImixsTask && qName.equalsIgnoreCase("bpmn2:task")) {
bImixsTask = false;
taskCache.put(bpmnID, currentEntity);
}
if (qName.equalsIgnoreCase("bpmn2:extensionElements")) {
bExtensionElements = false;
}
// end of bpmn2:intermediateCatchEvent -
if (bImixsEvent && (qName.equalsIgnoreCase("bpmn2:intermediateCatchEvent")
|| qName.equalsIgnoreCase("bpmn2:intermediateThrowEvent"))) {
bImixsEvent = false;
// we need to cache the activities because the sequenceflows must be
// analysed later
eventCache.put(bpmnID, currentEntity);
}
/*
* End of a imixs:value
*/
if (qName.equalsIgnoreCase("imixs:value")) {
if (bExtensionElements && bItemValue && currentEntity != null && characterStream != null) {
String svalue = characterStream.toString();
List valueList = currentEntity.getItemValue(currentItemName);
if ("xs:boolean".equals(currentItemType.toLowerCase())) {
valueList.add(Boolean.valueOf(svalue));
} else if ("xs:integer".equals(currentItemType.toLowerCase())) {
valueList.add(Integer.valueOf(svalue));
} else {
valueList.add(svalue);
}
// item will only be added if it is not listed in the ignoreItem
// List!
if (!ignoreItemList.contains(currentItemName)) {
currentEntity.replaceItemValue(currentItemName, valueList);
}
}
bItemValue = false;
characterStream = null;
}
if (qName.equalsIgnoreCase("bpmn2:documentation")) {
if (currentEntity != null) {
currentEntity.replaceItemValue("rtfdescription", characterStream.toString());
}
// bpmn2:message?
if (bMessage) {
// cache the message...
messageCache.put(currentMessageName, characterStream.toString());
bMessage = false;
}
// bpmn2:annotation?
if (bAnnotation) {
// cache the annotation
annotationCache.put(currentAnnotationName, characterStream.toString());
bAnnotation = false;
}
characterStream = null;
bdocumentation = false;
}
// end of bpmn2:intermediateThrowEvent -
if (bLinkThrowEvent && !bLinkCatchEvent && (qName.equalsIgnoreCase("bpmn2:linkEventDefinition"))) {
bLinkThrowEvent = false;
// we need to cache the link name
linkThrowEventCache.put(bpmnID, currentLinkName);
}
// end of bpmn2:intermediateCatchEvent -
if (bLinkCatchEvent && !bLinkThrowEvent && (qName.equalsIgnoreCase("bpmn2:linkEventDefinition"))) {
bLinkCatchEvent = false;
// we need to cache the link name
linkCatchEventCache.put(currentLinkName, bpmnID);
}
// test conditional sequence flow...
if (bSequenceFlow && bconditionExpression && qName.equalsIgnoreCase("bpmn2:conditionExpression")) {
String svalue = characterStream.toString();
logger.fine("conditional SequenceFlow:" + bpmnID + "=" + svalue);
bconditionExpression = false;
conditionCache.put(bpmnID, svalue);
}
} | #vulnerable code
@SuppressWarnings({ "unchecked", "rawtypes" })
@Override
public void endElement(String uri, String localName, String qName) throws SAXException {
// end of bpmn2:process
if (qName.equalsIgnoreCase("bpmn2:process")) {
if (currentWorkflowGroup != null) {
currentWorkflowGroup = null;
}
}
// end of bpmn2:task -
if (bImixsTask && qName.equalsIgnoreCase("bpmn2:task")) {
bImixsTask = false;
taskCache.put(bpmnID, currentEntity);
}
if (qName.equalsIgnoreCase("bpmn2:extensionElements")) {
bExtensionElements = false;
}
// end of bpmn2:intermediateCatchEvent -
if (bImixsEvent && (qName.equalsIgnoreCase("bpmn2:intermediateCatchEvent")
|| qName.equalsIgnoreCase("bpmn2:intermediateThrowEvent"))) {
bImixsEvent = false;
// we need to cache the activities because the sequenceflows must be
// analysed later
eventCache.put(bpmnID, currentEntity);
}
/*
* End of a imixs:value
*/
if (qName.equalsIgnoreCase("imixs:value")) {
if (bExtensionElements && bItemValue && currentEntity != null && characterStream != null) {
String svalue = characterStream.toString();
List valueList = currentEntity.getItemValue(currentItemName);
if ("xs:boolean".equals(currentItemType.toLowerCase())) {
valueList.add(Boolean.valueOf(svalue));
} else if ("xs:integer".equals(currentItemType.toLowerCase())) {
valueList.add(Integer.valueOf(svalue));
} else {
valueList.add(svalue);
}
// item will only be added if it is not listed in the ignoreItem
// List!
if (!ignoreItemList.contains(currentItemName)) {
currentEntity.replaceItemValue(currentItemName, valueList);
}
}
bItemValue = false;
characterStream = null;
}
if (qName.equalsIgnoreCase("bpmn2:documentation")) {
if (currentEntity != null) {
currentEntity.replaceItemValue("rtfdescription", characterStream.toString());
}
// bpmn2:message?
if (bMessage) {
// cache the message...
messageCache.put(currentMessageName, characterStream.toString());
bMessage = false;
}
// bpmn2:annotation?
if (bAnnotation) {
// cache the annotation
annotationCache.put(currentAnnotationName, characterStream.toString());
bAnnotation = false;
}
characterStream = null;
bdocumentation = false;
}
// end of bpmn2:intermediateThrowEvent -
if (bLinkThrowEvent && !bLinkCatchEvent && (qName.equalsIgnoreCase("bpmn2:linkEventDefinition"))) {
bLinkThrowEvent = false;
// we need to cache the link name
linkThrowEventCache.put(bpmnID, currentLinkName);
}
// end of bpmn2:intermediateCatchEvent -
if (bLinkCatchEvent && !bLinkThrowEvent && (qName.equalsIgnoreCase("bpmn2:linkEventDefinition"))) {
bLinkCatchEvent = false;
// we need to cache the link name
linkCatchEventCache.put(currentLinkName, bpmnID);
}
}
#location 66
#vulnerability type NULL_DEREFERENCE | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
public Object[] evaluateScriptObject(ScriptEngine engine, String expression) {
Object[] params = null;
if (engine == null) {
logger.severe("RulePlugin evaluateScritpObject error: no script engine! - call run()");
return null;
}
// first test if expression is a basic string var
Object objectResult = engine.get(expression);
if (objectResult != null && objectResult instanceof String) {
// just return a simple array with one value
params = new String[1];
params[0] = objectResult.toString();
return params;
}
// now try to pass the object to engine and convert it into a
// ArryList....
try {
// Nashorn: check for importClass function and then load if missing
// See: issue #124
String jsNashorn = " if (typeof importClass != 'function') { load('nashorn:mozilla_compat.js');}";
String jsCode = "importPackage(java.util);" + "var _evaluateScriptParam = Arrays.asList(" + expression
+ "); ";
// pass a collection from javascript to java;
engine.eval(jsNashorn + jsCode);
@SuppressWarnings("unchecked")
List<Object> resultList = (List<Object>) engine.get("_evaluateScriptParam");
if (resultList==null) {
return null;
}
if ("[undefined]".equals(resultList.toString())) {
return null;
}
// logging
if (logger.isLoggable(Level.FINE)) {
logger.fine("evalueateScript object to Java");
for (Object val : resultList) {
logger.fine(val.toString());
}
}
return resultList.toArray();
} catch (ScriptException se) {
// not convertable!
// se.printStackTrace();
logger.fine("[RulePlugin] error evaluating " + expression + " - " + se.getMessage());
return null;
}
} | #vulnerable code
public Object[] evaluateScriptObject(ScriptEngine engine, String expression) {
Object[] params = null;
if (engine == null) {
logger.severe("RulePlugin evaluateScritpObject error: no script engine! - call run()");
return null;
}
// first test if expression is a basic string var
Object objectResult = engine.get(expression);
if (objectResult != null && objectResult instanceof String) {
// just return a simple array with one value
params = new String[1];
params[0] = objectResult.toString();
return params;
}
// now try to pass the object to engine and convert it into a
// ArryList....
try {
String jsCode = "importPackage(java.util);"
+ "var _evaluateScriptParam = Arrays.asList(" + expression
+ "); ";
// pass a collection from javascript to java;
engine.eval(jsCode);
@SuppressWarnings("unchecked")
List<Object> resultList = (List<Object>) engine
.get("_evaluateScriptParam");
// logging
if (logger.isLoggable(Level.FINE)) {
logger.fine("evalueateScript object to Java");
for (Object val : resultList) {
logger.fine(val.toString());
}
}
return resultList.toArray();
} catch (ScriptException se) {
// not convertable!
// se.printStackTrace();
logger.fine("[RulePlugin] error evaluating " + expression + " - "
+ se.getMessage());
return null;
}
}
#location 38
#vulnerability type NULL_DEREFERENCE | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Test
public void testAddWorkdaysFromMonday() {
Calendar startDate = Calendar.getInstance();
// adjust to FRIDAY
startDate.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY);
System.out.println("Startdate=" + startDate.getTime());
Assert.assertEquals(Calendar.TUESDAY,
workflowSchedulerService.addWorkDays(startDate, 1).get(Calendar.DAY_OF_WEEK));
Assert.assertEquals(Calendar.WEDNESDAY,
workflowSchedulerService.addWorkDays(startDate, 2).get(Calendar.DAY_OF_WEEK));
Assert.assertEquals(Calendar.FRIDAY,
workflowSchedulerService.addWorkDays(startDate, 4).get(Calendar.DAY_OF_WEEK));
Assert.assertEquals(Calendar.MONDAY,
workflowSchedulerService.addWorkDays(startDate, 5).get(Calendar.DAY_OF_WEEK));
Assert.assertEquals(Calendar.FRIDAY,
workflowSchedulerService.addWorkDays(startDate, 9).get(Calendar.DAY_OF_WEEK));
Assert.assertEquals(Calendar.MONDAY,
workflowSchedulerService.addWorkDays(startDate, 10).get(Calendar.DAY_OF_WEEK));
} | #vulnerable code
@Test
public void testAddWorkdaysFromMonday() {
Calendar startDate = Calendar.getInstance();
// adjust to FRIDAY
startDate.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY);
System.out.println("Startdate=" + startDate.getTime());
Assert.assertEquals(Calendar.TUESDAY,
WorkflowSchedulerService.addWorkDays(startDate, 1).get(Calendar.DAY_OF_WEEK));
Assert.assertEquals(Calendar.WEDNESDAY,
WorkflowSchedulerService.addWorkDays(startDate, 2).get(Calendar.DAY_OF_WEEK));
Assert.assertEquals(Calendar.FRIDAY,
WorkflowSchedulerService.addWorkDays(startDate, 4).get(Calendar.DAY_OF_WEEK));
Assert.assertEquals(Calendar.MONDAY,
WorkflowSchedulerService.addWorkDays(startDate, 5).get(Calendar.DAY_OF_WEEK));
Assert.assertEquals(Calendar.FRIDAY,
WorkflowSchedulerService.addWorkDays(startDate, 9).get(Calendar.DAY_OF_WEEK));
Assert.assertEquals(Calendar.MONDAY,
WorkflowSchedulerService.addWorkDays(startDate, 10).get(Calendar.DAY_OF_WEEK));
}
#location 15
#vulnerability type NULL_DEREFERENCE | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Test
public void testMinusWorkdaysFromSunday() {
Calendar startDate = Calendar.getInstance();
// adjust to SATURDAY
startDate.set(Calendar.DAY_OF_WEEK, Calendar.SUNDAY);
System.out.println("Startdate=" + startDate.getTime());
// adjust -1 Workdays -> THURSDAY
Assert.assertEquals(Calendar.THURSDAY,
workflowSchedulerService.addWorkDays(startDate, -1).get(Calendar.DAY_OF_WEEK));
Assert.assertEquals(Calendar.FRIDAY,
workflowSchedulerService.addWorkDays(startDate, -5).get(Calendar.DAY_OF_WEEK));
} | #vulnerable code
@Test
public void testMinusWorkdaysFromSunday() {
Calendar startDate = Calendar.getInstance();
// adjust to SATURDAY
startDate.set(Calendar.DAY_OF_WEEK, Calendar.SUNDAY);
System.out.println("Startdate=" + startDate.getTime());
// adjust -1 Workdays -> THURSDAY
Assert.assertEquals(Calendar.THURSDAY,
WorkflowSchedulerService.addWorkDays(startDate, -1).get(Calendar.DAY_OF_WEEK));
Assert.assertEquals(Calendar.FRIDAY,
WorkflowSchedulerService.addWorkDays(startDate, -5).get(Calendar.DAY_OF_WEEK));
}
#location 13
#vulnerability type NULL_DEREFERENCE | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Test
@Category(org.imixs.workflow.ItemCollection.class)
public void testFileData() {
ItemCollection itemColSource = new ItemCollection();
// add a dummy file
byte[] empty = { 0 };
itemColSource.addFileData(new FileData( "test1.txt", empty,"application/xml",null));
ItemCollection itemColTarget = new ItemCollection();
itemColTarget.addFileData(itemColSource.getFileData("test1.txt"));
FileData filedata = itemColTarget.getFileData("test1.txt");
Assert.assertNotNull(filedata);
Assert.assertEquals("test1.txt", filedata.getName());
Assert.assertEquals("application/xml", filedata.getContentType());
// test the byte content of itemColSource
byte[] file1Data1 =itemColSource.getFileData("test1.txt").getContent();
// we expect the new dummy array { 1, 2, 3 }
Assert.assertArrayEquals(empty, file1Data1);
// test the byte content of itemColTarget
file1Data1 = itemColTarget.getFileData("test1.txt").getContent();
// we expect the new dummy array { 1, 2, 3 }
Assert.assertArrayEquals(empty, file1Data1);
} | #vulnerable code
@Test
@Category(org.imixs.workflow.ItemCollection.class)
public void testFileData() {
ItemCollection itemColSource = new ItemCollection();
// add a dummy file
byte[] empty = { 0 };
itemColSource.addFile(empty, "test1.txt", "application/xml");
ItemCollection itemColTarget = new ItemCollection();
itemColTarget.addFileData(itemColSource.getFileData("test1.txt"));
FileData filedata = itemColTarget.getFileData("test1.txt");
Assert.assertNotNull(filedata);
Assert.assertEquals("test1.txt", filedata.getName());
Assert.assertEquals("application/xml", filedata.getContentType());
// test the byte content of itemColSource
Map<String, List<Object>> conedFiles1 = itemColSource.getFiles();
List<Object> fileContent1 = conedFiles1.get("test1.txt");
byte[] file1Data1 = (byte[]) fileContent1.get(1);
// we expect the new dummy array { 1, 2, 3 }
Assert.assertArrayEquals(empty, file1Data1);
// test the byte content of itemColTarget
conedFiles1 = itemColTarget.getFiles();
fileContent1 = conedFiles1.get("test1.txt");
file1Data1 = (byte[]) fileContent1.get(1);
// we expect the new dummy array { 1, 2, 3 }
Assert.assertArrayEquals(empty, file1Data1);
}
#location 28
#vulnerability type NULL_DEREFERENCE | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Test
public void testAddWorkdaysFromFriday() {
Calendar startDate = Calendar.getInstance();
// adjust to FRIDAY
startDate.set(Calendar.DAY_OF_WEEK, Calendar.FRIDAY);
System.out.println("Startdate=" + startDate.getTime());
// adjust -3 Workdays -> THUSEDAY
Assert.assertEquals(Calendar.TUESDAY,
workflowSchedulerService.addWorkDays(startDate, 2).get(Calendar.DAY_OF_WEEK));
Assert.assertEquals(Calendar.WEDNESDAY,
workflowSchedulerService.addWorkDays(startDate, 8).get(Calendar.DAY_OF_WEEK));
Assert.assertEquals(Calendar.FRIDAY,
workflowSchedulerService.addWorkDays(startDate, 10).get(Calendar.DAY_OF_WEEK));
Assert.assertEquals(Calendar.THURSDAY,
workflowSchedulerService.addWorkDays(startDate, 14).get(Calendar.DAY_OF_WEEK));
} | #vulnerable code
@Test
public void testAddWorkdaysFromFriday() {
Calendar startDate = Calendar.getInstance();
// adjust to FRIDAY
startDate.set(Calendar.DAY_OF_WEEK, Calendar.FRIDAY);
System.out.println("Startdate=" + startDate.getTime());
// adjust -3 Workdays -> THUSEDAY
Assert.assertEquals(Calendar.TUESDAY,
WorkflowSchedulerService.addWorkDays(startDate, 2).get(Calendar.DAY_OF_WEEK));
Assert.assertEquals(Calendar.WEDNESDAY,
WorkflowSchedulerService.addWorkDays(startDate, 8).get(Calendar.DAY_OF_WEEK));
Assert.assertEquals(Calendar.FRIDAY,
WorkflowSchedulerService.addWorkDays(startDate, 10).get(Calendar.DAY_OF_WEEK));
Assert.assertEquals(Calendar.THURSDAY,
WorkflowSchedulerService.addWorkDays(startDate, 14).get(Calendar.DAY_OF_WEEK));
}
#location 20
#vulnerability type NULL_DEREFERENCE | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@SuppressWarnings({ "rawtypes" })
public int run(ItemCollection documentContext,
ItemCollection documentActivity) throws PluginException {
mailMessage = null;
// check if mail is active?
if ("1".equals(documentActivity.getItemValueString("keyMailInactive")))
return Plugin.PLUGIN_OK;
List vectorRecipients = getRecipients(documentContext, documentActivity);
if (vectorRecipients.isEmpty()) {
logger.fine("[MailPlugin] No Receipients defined for this Activity...");
return Plugin.PLUGIN_OK;
}
try {
// first initialize mail message object
initMailMessage();
if (mailMessage == null) {
logger.warning("[MailPlugin] mailMessage = null");
return Plugin.PLUGIN_WARNING;
}
// set FROM
mailMessage.setFrom(getInternetAddress(getFrom(documentContext,
documentActivity)));
// set Recipient
mailMessage.setRecipients(Message.RecipientType.TO,
getInternetAddressArray(vectorRecipients));
// build CC
mailMessage.setRecipients(
Message.RecipientType.CC,
getInternetAddressArray(getRecipientsCC(documentContext,
documentActivity)));
// replay to?
String sReplyTo = getReplyTo(documentContext, documentActivity);
if ((sReplyTo != null) && (!sReplyTo.isEmpty())) {
InternetAddress[] resplysAdrs = new InternetAddress[1];
resplysAdrs[0] = getInternetAddress(sReplyTo);
mailMessage.setReplyTo(resplysAdrs);
}
// set Subject
mailMessage.setSubject(
getSubject(documentContext, documentActivity),
this.getCharSet());
// set Body
String aBodyText = getBody(documentContext, documentActivity);
if (aBodyText == null) {
aBodyText = "";
}
// set mailbody
MimeBodyPart messagePart = new MimeBodyPart();
logger.fine("[MailPlugin] ContentType: '" + getContentType() + "'");
messagePart.setContent(aBodyText, getContentType());
// append message part
mimeMultipart.addBodyPart(messagePart);
// mimeMulitPart object can be extended from subclases
} catch (Exception e) {
logger.warning("[MailPlugin] run - Warning:" + e.toString());
e.printStackTrace();
return Plugin.PLUGIN_WARNING;
}
return Plugin.PLUGIN_OK;
} | #vulnerable code
@SuppressWarnings({ "rawtypes" })
public int run(ItemCollection documentContext,
ItemCollection documentActivity) throws PluginException {
mailMessage = null;
// check if mail is active?
if ("1".equals(documentActivity.getItemValueString("keyMailInactive")))
return Plugin.PLUGIN_OK;
List vectorRecipients = getRecipients(documentContext, documentActivity);
if (vectorRecipients.isEmpty()) {
logger.fine("[MailPlugin] No Receipients defined for this Activity...");
return Plugin.PLUGIN_OK;
}
try {
// first initialize mail message object
initMailMessage();
// set FROM
mailMessage.setFrom(getInternetAddress(getFrom(documentContext,
documentActivity)));
// set Recipient
mailMessage.setRecipients(Message.RecipientType.TO,
getInternetAddressArray(vectorRecipients));
// build CC
mailMessage.setRecipients(
Message.RecipientType.CC,
getInternetAddressArray(getRecipientsCC(documentContext,
documentActivity)));
// replay to?
String sReplyTo = getReplyTo(documentContext, documentActivity);
if ((sReplyTo != null) && (!sReplyTo.isEmpty())) {
InternetAddress[] resplysAdrs = new InternetAddress[1];
resplysAdrs[0] = getInternetAddress(sReplyTo);
mailMessage.setReplyTo(resplysAdrs);
}
// set Subject
mailMessage.setSubject(
getSubject(documentContext, documentActivity),
this.getCharSet());
// set Body
String aBodyText = getBody(documentContext, documentActivity);
if (aBodyText == null) {
aBodyText = "";
}
// set mailbody
MimeBodyPart messagePart = new MimeBodyPart();
logger.fine("[MailPlugin] ContentType: '" + getContentType() + "'");
messagePart.setContent(aBodyText, getContentType());
// append message part
mimeMultipart.addBodyPart(messagePart);
// mimeMulitPart object can be extended from subclases
} catch (Exception e) {
logger.warning("[MailPlugin] run - Warning:" + e.toString());
e.printStackTrace();
return Plugin.PLUGIN_WARNING;
}
return Plugin.PLUGIN_OK;
}
#location 23
#vulnerability type NULL_DEREFERENCE | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Test
// @Ignore
public void testWrite() {
List<ItemCollection> col = null;
// read default content
try {
col = XMLItemCollectionAdapter
.readCollectionFromInputStream(getClass().getResourceAsStream("/document-example.xml"));
} catch (JAXBException e) {
Assert.fail();
} catch (IOException e) {
Assert.fail();
}
// create JAXB object
DocumentCollection xmlCol = null;
try {
xmlCol = XMLItemCollectionAdapter.putDocuments(col);
} catch (Exception e1) {
e1.printStackTrace();
Assert.fail();
}
// now write back to file
File file = null;
try {
file = new File("src/test/resources/export-test.xml");
JAXBContext jaxbContext = JAXBContext.newInstance(DocumentCollection.class);
Marshaller jaxbMarshaller = jaxbContext.createMarshaller();
// output pretty printed
jaxbMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
jaxbMarshaller.marshal(xmlCol, file);
jaxbMarshaller.marshal(xmlCol, System.out);
} catch (JAXBException e) {
e.printStackTrace();
Assert.fail();
}
Assert.assertNotNull(file);
} | #vulnerable code
@Test
// @Ignore
public void testWrite() {
List<ItemCollection> col = null;
// read default content
try {
col = XMLItemCollectionAdapter
.readCollectionFromInputStream(getClass().getResourceAsStream("/document-example.xml"));
} catch (JAXBException e) {
Assert.fail();
} catch (IOException e) {
Assert.fail();
}
// create JAXB object
DocumentCollection xmlCol = null;
try {
xmlCol = XMLItemCollectionAdapter.putCollection(col);
} catch (Exception e1) {
e1.printStackTrace();
Assert.fail();
}
// now write back to file
File file = null;
try {
file = new File("src/test/resources/export-test.xml");
JAXBContext jaxbContext = JAXBContext.newInstance(DocumentCollection.class);
Marshaller jaxbMarshaller = jaxbContext.createMarshaller();
// output pretty printed
jaxbMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
jaxbMarshaller.marshal(xmlCol, file);
jaxbMarshaller.marshal(xmlCol, System.out);
} catch (JAXBException e) {
e.printStackTrace();
Assert.fail();
}
Assert.assertNotNull(file);
}
#location 18
#vulnerability type NULL_DEREFERENCE | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@SuppressWarnings("unchecked")
@Test
public void testUpdateOriginProcess() throws ModelException {
String orignUniqueID = documentContext.getUniqueID();
/*
* 1.) create test result for new subprcoess.....
*/
try {
documentActivity = this.getModel().getEvent(100, 20);
splitAndJoinPlugin.run(documentContext, documentActivity);
} catch (PluginException e) {
e.printStackTrace();
Assert.fail();
}
Assert.assertNotNull(documentContext);
// now load the subprocess
List<String> workitemRefList = documentContext.getItemValue(SplitAndJoinPlugin.LINK_PROPERTY);
String subprocessUniqueid = workitemRefList.get(0);
ItemCollection subprocess = this.documentService.load(subprocessUniqueid);
// test data in subprocess
Assert.assertNotNull(subprocess);
Assert.assertEquals(100, subprocess.getProcessID());
/*
* 2.) process the subprocess to test if the origin process will be
* updated correctly
*/
// add some custom data
subprocess.replaceItemValue("_sub_data", "some test data");
// now we process the subprocess
try {
documentActivity = this.getModel().getEvent(100, 50);
splitAndJoinPlugin.run(subprocess, documentActivity);
} catch (PluginException e) {
e.printStackTrace();
Assert.fail();
}
// test orign ref
Assert.assertEquals(orignUniqueID,subprocess.getItemValueString(SplitAndJoinPlugin.ORIGIN_REF));
// load origin document
documentContext = documentService.load(orignUniqueID);
Assert.assertNotNull(documentContext);
// test data.... (new $processId=200 and _sub_data from subprocess
Assert.assertEquals(100, documentContext.getProcessID());
Assert.assertEquals("some test data", documentContext.getItemValueString("_sub_data"));
} | #vulnerable code
@SuppressWarnings("unchecked")
@Test
public void testUpdateOriginProcess() throws ModelException {
String orignUniqueID = documentContext.getUniqueID();
/*
* 1.) create test result for new subprcoess.....
*/
try {
documentActivity = this.getModel().getEvent(100, 20);
splitAndJoinPlugin.run(documentContext, documentActivity);
} catch (PluginException e) {
e.printStackTrace();
Assert.fail();
}
Assert.assertNotNull(documentContext);
// now load the subprocess
List<String> workitemRefList = documentContext.getItemValue(SplitAndJoinPlugin.LINK_PROPERTY);
String subprocessUniqueid = workitemRefList.get(0);
ItemCollection subprocess = this.documentService.load(subprocessUniqueid);
// test data in subprocess
Assert.assertNotNull(subprocess);
Assert.assertEquals(100, subprocess.getProcessID());
/*
* 2.) process the subprocess to test if the origin process will be
* updated correctly
*/
// add some custom data
subprocess.replaceItemValue("_sub_data", "some test data");
// now we process the subprocess
try {
documentActivity = this.getModel().getEvent(100, 50);
splitAndJoinPlugin.run(subprocess, documentActivity);
} catch (PluginException e) {
e.printStackTrace();
Assert.fail();
}
// load origin document
documentContext = documentService.load(orignUniqueID);
Assert.assertNotNull(documentContext);
// test data.... (new $processId=200 and _sub_data from subprocess
Assert.assertEquals(100, documentContext.getProcessID());
Assert.assertEquals("some test data", documentContext.getItemValueString("_sub_data"));
}
#location 48
#vulnerability type NULL_DEREFERENCE | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
public Object[] evaluateScriptObject(ScriptEngine engine, String expression) {
Object[] params = null;
if (engine == null) {
logger.severe("RulePlugin evaluateScritpObject error: no script engine! - call run()");
return null;
}
// first test if expression is a basic string var
Object objectResult = engine.get(expression);
if (objectResult != null && objectResult instanceof String) {
// just return a simple array with one value
params = new String[1];
params[0] = objectResult.toString();
return params;
}
// now try to pass the object to engine and convert it into a
// ArryList....
try {
// Nashorn: check for importClass function and then load if missing
// See: issue #124
String jsNashorn = " if (typeof importClass != 'function') { load('nashorn:mozilla_compat.js');}";
String jsCode = "importPackage(java.util);" + "var _evaluateScriptParam = Arrays.asList(" + expression
+ "); ";
// pass a collection from javascript to java;
engine.eval(jsNashorn + jsCode);
@SuppressWarnings("unchecked")
List<Object> resultList = (List<Object>) engine.get("_evaluateScriptParam");
if (resultList==null) {
return null;
}
if ("[undefined]".equals(resultList.toString())) {
return null;
}
// logging
if (logger.isLoggable(Level.FINE)) {
logger.fine("evalueateScript object to Java");
for (Object val : resultList) {
logger.fine(val.toString());
}
}
return resultList.toArray();
} catch (ScriptException se) {
// not convertable!
// se.printStackTrace();
logger.fine("[RulePlugin] error evaluating " + expression + " - " + se.getMessage());
return null;
}
} | #vulnerable code
public Object[] evaluateScriptObject(ScriptEngine engine, String expression) {
Object[] params = null;
if (engine == null) {
logger.severe("RulePlugin evaluateScritpObject error: no script engine! - call run()");
return null;
}
// first test if expression is a basic string var
Object objectResult = engine.get(expression);
if (objectResult != null && objectResult instanceof String) {
// just return a simple array with one value
params = new String[1];
params[0] = objectResult.toString();
return params;
}
// now try to pass the object to engine and convert it into a
// ArryList....
try {
String jsCode = "importPackage(java.util);"
+ "var _evaluateScriptParam = Arrays.asList(" + expression
+ "); ";
// pass a collection from javascript to java;
engine.eval(jsCode);
@SuppressWarnings("unchecked")
List<Object> resultList = (List<Object>) engine
.get("_evaluateScriptParam");
// logging
if (logger.isLoggable(Level.FINE)) {
logger.fine("evalueateScript object to Java");
for (Object val : resultList) {
logger.fine(val.toString());
}
}
return resultList.toArray();
} catch (ScriptException se) {
// not convertable!
// se.printStackTrace();
logger.fine("[RulePlugin] error evaluating " + expression + " - "
+ se.getMessage());
return null;
}
}
#location 33
#vulnerability type NULL_DEREFERENCE | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Test
public void testMinusWorkdaysFromMonday() {
Calendar startDate = Calendar.getInstance();
// adjust to FRIDAY
startDate.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY);
System.out.println("Startdate=" + startDate.getTime());
// adjust -3 Workdays -> THUSEDAY
Assert.assertEquals(Calendar.THURSDAY,
workflowSchedulerService.addWorkDays(startDate, -2).get(Calendar.DAY_OF_WEEK));
} | #vulnerable code
@Test
public void testMinusWorkdaysFromMonday() {
Calendar startDate = Calendar.getInstance();
// adjust to FRIDAY
startDate.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY);
System.out.println("Startdate=" + startDate.getTime());
// adjust -3 Workdays -> THUSEDAY
Assert.assertEquals(Calendar.THURSDAY,
WorkflowSchedulerService.addWorkDays(startDate, -2).get(Calendar.DAY_OF_WEEK));
}
#location 11
#vulnerability type NULL_DEREFERENCE | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
public int compare(ItemCollection a, ItemCollection b) {
// date compare?
if (a.isItemValueDate(itemName)) {
Date dateA = a.getItemValueDate(itemName);
Date dateB = b.getItemValueDate(itemName);
if (dateA==null && dateB !=null) {
return 1;
}
if (dateB==null && dateA !=null) {
return -1;
}
if (dateB==null && dateA ==null) {
return 0;
}
int result = dateB.compareTo(dateA);
if (!this.ascending) {
result = -result;
}
return result;
}
// integer compare?
if (a.isItemValueInteger(itemName)) {
int result = a.getItemValueInteger(itemName)
- b.getItemValueInteger(itemName);
if (!this.ascending) {
result = -result;
}
return result;
}
// String compare
int result = this.collator.compare(a.getItemValueString(itemName),
b.getItemValueString(itemName));
if (!this.ascending) {
result = -result;
}
return result;
} | #vulnerable code
public int compare(ItemCollection a, ItemCollection b) {
// date compare?
if (a.isItemValueDate(itemName)) {
Date dateA = a.getItemValueDate(itemName);
Date dateB = b.getItemValueDate(itemName);
int result = dateB.compareTo(dateA);
if (!this.ascending) {
result = -result;
}
return result;
}
// integer compare?
if (a.isItemValueInteger(itemName)) {
int result = a.getItemValueInteger(itemName)
- b.getItemValueInteger(itemName);
if (!this.ascending) {
result = -result;
}
return result;
}
// String compare
int result = this.collator.compare(a.getItemValueString(itemName),
b.getItemValueString(itemName));
if (!this.ascending) {
result = -result;
}
return result;
}
#location 8
#vulnerability type NULL_DEREFERENCE | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Test
public void testMinusWorkdaysFromSaturday() {
Calendar startDate = Calendar.getInstance();
// adjust to SATURDAY
startDate.set(Calendar.DAY_OF_WEEK, Calendar.SATURDAY);
System.out.println("Startdate=" + startDate.getTime());
// adjust -1 Workdays -> THURSDAY
Assert.assertEquals(Calendar.THURSDAY,
workflowSchedulerService.addWorkDays(startDate, -1).get(Calendar.DAY_OF_WEEK));
Assert.assertEquals(Calendar.FRIDAY,
workflowSchedulerService.addWorkDays(startDate, -5).get(Calendar.DAY_OF_WEEK));
} | #vulnerable code
@Test
public void testMinusWorkdaysFromSaturday() {
Calendar startDate = Calendar.getInstance();
// adjust to SATURDAY
startDate.set(Calendar.DAY_OF_WEEK, Calendar.SATURDAY);
System.out.println("Startdate=" + startDate.getTime());
// adjust -1 Workdays -> THURSDAY
Assert.assertEquals(Calendar.THURSDAY,
WorkflowSchedulerService.addWorkDays(startDate, -1).get(Calendar.DAY_OF_WEEK));
Assert.assertEquals(Calendar.FRIDAY,
WorkflowSchedulerService.addWorkDays(startDate, -5).get(Calendar.DAY_OF_WEEK));
}
#location 11
#vulnerability type NULL_DEREFERENCE | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Test
public void testAddWorkdaysFromSunday() {
Calendar startDate = Calendar.getInstance();
// adjust to SATURDAY
startDate.set(Calendar.DAY_OF_WEEK, Calendar.SUNDAY);
System.out.println("Startdate=" + startDate.getTime());
// adjust -1 Workdays -> TUESDAY
Assert.assertEquals(Calendar.TUESDAY,
workflowSchedulerService.addWorkDays(startDate, 1).get(Calendar.DAY_OF_WEEK));
Assert.assertEquals(Calendar.FRIDAY,
workflowSchedulerService.addWorkDays(startDate, 4).get(Calendar.DAY_OF_WEEK));
Assert.assertEquals(Calendar.MONDAY,
workflowSchedulerService.addWorkDays(startDate, 5).get(Calendar.DAY_OF_WEEK));
} | #vulnerable code
@Test
public void testAddWorkdaysFromSunday() {
Calendar startDate = Calendar.getInstance();
// adjust to SATURDAY
startDate.set(Calendar.DAY_OF_WEEK, Calendar.SUNDAY);
System.out.println("Startdate=" + startDate.getTime());
// adjust -1 Workdays -> TUESDAY
Assert.assertEquals(Calendar.TUESDAY,
WorkflowSchedulerService.addWorkDays(startDate, 1).get(Calendar.DAY_OF_WEEK));
Assert.assertEquals(Calendar.FRIDAY,
WorkflowSchedulerService.addWorkDays(startDate, 4).get(Calendar.DAY_OF_WEEK));
Assert.assertEquals(Calendar.MONDAY,
WorkflowSchedulerService.addWorkDays(startDate, 5).get(Calendar.DAY_OF_WEEK));
}
#location 18
#vulnerability type NULL_DEREFERENCE | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Test
public void testMinusWorkdaysFromSaturday() {
Calendar startDate = Calendar.getInstance();
// adjust to SATURDAY
startDate.set(Calendar.DAY_OF_WEEK, Calendar.SATURDAY);
System.out.println("Startdate=" + startDate.getTime());
// adjust -1 Workdays -> THURSDAY
Assert.assertEquals(Calendar.THURSDAY,
workflowSchedulerService.addWorkDays(startDate, -1).get(Calendar.DAY_OF_WEEK));
Assert.assertEquals(Calendar.FRIDAY,
workflowSchedulerService.addWorkDays(startDate, -5).get(Calendar.DAY_OF_WEEK));
} | #vulnerable code
@Test
public void testMinusWorkdaysFromSaturday() {
Calendar startDate = Calendar.getInstance();
// adjust to SATURDAY
startDate.set(Calendar.DAY_OF_WEEK, Calendar.SATURDAY);
System.out.println("Startdate=" + startDate.getTime());
// adjust -1 Workdays -> THURSDAY
Assert.assertEquals(Calendar.THURSDAY,
WorkflowSchedulerService.addWorkDays(startDate, -1).get(Calendar.DAY_OF_WEEK));
Assert.assertEquals(Calendar.FRIDAY,
WorkflowSchedulerService.addWorkDays(startDate, -5).get(Calendar.DAY_OF_WEEK));
}
#location 13
#vulnerability type NULL_DEREFERENCE | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Test
public void testAddWorkdaysFromFriday() {
Calendar startDate = Calendar.getInstance();
// adjust to FRIDAY
startDate.set(Calendar.DAY_OF_WEEK, Calendar.FRIDAY);
System.out.println("Startdate=" + startDate.getTime());
// adjust -3 Workdays -> THUSEDAY
Assert.assertEquals(Calendar.TUESDAY,
workflowSchedulerService.addWorkDays(startDate, 2).get(Calendar.DAY_OF_WEEK));
Assert.assertEquals(Calendar.WEDNESDAY,
workflowSchedulerService.addWorkDays(startDate, 8).get(Calendar.DAY_OF_WEEK));
Assert.assertEquals(Calendar.FRIDAY,
workflowSchedulerService.addWorkDays(startDate, 10).get(Calendar.DAY_OF_WEEK));
Assert.assertEquals(Calendar.THURSDAY,
workflowSchedulerService.addWorkDays(startDate, 14).get(Calendar.DAY_OF_WEEK));
} | #vulnerable code
@Test
public void testAddWorkdaysFromFriday() {
Calendar startDate = Calendar.getInstance();
// adjust to FRIDAY
startDate.set(Calendar.DAY_OF_WEEK, Calendar.FRIDAY);
System.out.println("Startdate=" + startDate.getTime());
// adjust -3 Workdays -> THUSEDAY
Assert.assertEquals(Calendar.TUESDAY,
WorkflowSchedulerService.addWorkDays(startDate, 2).get(Calendar.DAY_OF_WEEK));
Assert.assertEquals(Calendar.WEDNESDAY,
WorkflowSchedulerService.addWorkDays(startDate, 8).get(Calendar.DAY_OF_WEEK));
Assert.assertEquals(Calendar.FRIDAY,
WorkflowSchedulerService.addWorkDays(startDate, 10).get(Calendar.DAY_OF_WEEK));
Assert.assertEquals(Calendar.THURSDAY,
WorkflowSchedulerService.addWorkDays(startDate, 14).get(Calendar.DAY_OF_WEEK));
}
#location 14
#vulnerability type NULL_DEREFERENCE | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Test
public void testMinusWorkdaysFromFriday() {
Calendar startDate = Calendar.getInstance();
// adjust to FRIDAY
startDate.set(Calendar.DAY_OF_WEEK, Calendar.FRIDAY);
System.out.println("Startdate=" + startDate.getTime());
// adjust -3 Workdays -> THUSEDAY
Assert.assertEquals(Calendar.THURSDAY,
workflowSchedulerService.addWorkDays(startDate, -1).get(Calendar.DAY_OF_WEEK));
Assert.assertEquals(Calendar.WEDNESDAY,
workflowSchedulerService.addWorkDays(startDate, -2).get(Calendar.DAY_OF_WEEK));
Assert.assertEquals(Calendar.MONDAY,
workflowSchedulerService.addWorkDays(startDate, -4).get(Calendar.DAY_OF_WEEK));
// friday - 5
Assert.assertEquals(Calendar.FRIDAY,
workflowSchedulerService.addWorkDays(startDate, -5).get(Calendar.DAY_OF_WEEK));
Assert.assertEquals(Calendar.MONDAY,
workflowSchedulerService.addWorkDays(startDate, -9).get(Calendar.DAY_OF_WEEK));
Assert.assertEquals(Calendar.FRIDAY,
workflowSchedulerService.addWorkDays(startDate, -10).get(Calendar.DAY_OF_WEEK));
} | #vulnerable code
@Test
public void testMinusWorkdaysFromFriday() {
Calendar startDate = Calendar.getInstance();
// adjust to FRIDAY
startDate.set(Calendar.DAY_OF_WEEK, Calendar.FRIDAY);
System.out.println("Startdate=" + startDate.getTime());
// adjust -3 Workdays -> THUSEDAY
Assert.assertEquals(Calendar.THURSDAY,
WorkflowSchedulerService.addWorkDays(startDate, -1).get(Calendar.DAY_OF_WEEK));
Assert.assertEquals(Calendar.WEDNESDAY,
WorkflowSchedulerService.addWorkDays(startDate, -2).get(Calendar.DAY_OF_WEEK));
Assert.assertEquals(Calendar.MONDAY,
WorkflowSchedulerService.addWorkDays(startDate, -4).get(Calendar.DAY_OF_WEEK));
// friday - 5
Assert.assertEquals(Calendar.FRIDAY,
WorkflowSchedulerService.addWorkDays(startDate, -5).get(Calendar.DAY_OF_WEEK));
Assert.assertEquals(Calendar.MONDAY,
WorkflowSchedulerService.addWorkDays(startDate, -9).get(Calendar.DAY_OF_WEEK));
Assert.assertEquals(Calendar.FRIDAY,
WorkflowSchedulerService.addWorkDays(startDate, -10).get(Calendar.DAY_OF_WEEK));
}
#location 18
#vulnerability type NULL_DEREFERENCE | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Test
public void testParseResult() {
List<ItemCollection> result=null;
String testString = "{\n" +
" \"responseHeader\":{\n" +
" \"status\":0,\n" +
" \"QTime\":4,\n" +
" \"params\":{\n" +
" \"q\":\"*:*\",\n" +
" \"_\":\"1567286252995\"}},\n" +
" \"response\":{\"numFound\":2,\"start\":0,\"docs\":[\n" +
" {\n" +
" \"type\":[\"model\"],\n" +
" \"id\":\"3a182d18-33d9-4951-8970-d9eaf9d337ff\",\n" +
" \"_modified\":[20190831211617],\n" +
" \"_created\":[20190831211617],\n" +
" \"_version_\":1643418672068296704},\n" +
" {\n" +
" \"type\":[\"adminp\"],\n" +
" \"id\":\"60825929-4d7d-4346-9333-afd7dbfca457\",\n" +
" \"_modified\":[20190831211618],\n" +
" \"_created\":[20190831211618],\n" +
" \"_version_\":1643418672172105728}]\n" +
" }}";
result=solrSearchService.parseQueryResult(testString);
Assert.assertEquals(2,result.size());
ItemCollection document=null;
document=result.get(0);
Assert.assertEquals("model", document.getItemValueString("type"));
Assert.assertEquals("3a182d18-33d9-4951-8970-d9eaf9d337ff", document.getItemValueString("id"));
Calendar cal=Calendar.getInstance();
cal.setTime(document.getItemValueDate("_modified"));
Assert.assertEquals(7,cal.get(Calendar.MONTH));
Assert.assertEquals(31,cal.get(Calendar.DAY_OF_MONTH));
document=result.get(1);
Assert.assertEquals("adminp", document.getItemValueString("type"));
} | #vulnerable code
@Test
public void testParseResult() {
List<ItemCollection> result=null;
String testString = "{\n" +
" \"responseHeader\":{\n" +
" \"status\":0,\n" +
" \"QTime\":4,\n" +
" \"params\":{\n" +
" \"q\":\"*:*\",\n" +
" \"_\":\"1567286252995\"}},\n" +
" \"response\":{\"numFound\":2,\"start\":0,\"docs\":[\n" +
" {\n" +
" \"type\":[\"model\"],\n" +
" \"id\":\"3a182d18-33d9-4951-8970-d9eaf9d337ff\",\n" +
" \"_modified\":[20190831211617],\n" +
" \"_created\":[20190831211617],\n" +
" \"_version_\":1643418672068296704},\n" +
" {\n" +
" \"type\":[\"adminp\"],\n" +
" \"id\":\"60825929-4d7d-4346-9333-afd7dbfca457\",\n" +
" \"_modified\":[20190831211618],\n" +
" \"_created\":[20190831211618],\n" +
" \"_version_\":1643418672172105728}]\n" +
" }}";
result=solrSearchService.parseQueryResult(testString);
Assert.assertEquals(2,result.size());
ItemCollection document=null;
document=result.get(0);
Assert.assertEquals("model", document.getItemValueString("type"));
Assert.assertEquals("3a182d18-33d9-4951-8970-d9eaf9d337ff", document.getItemValueString("id"));
Assert.assertEquals(1567278977000l, document.getItemValueDate("_modified").getTime());
Assert.assertEquals(1567278977000l, document.getItemValueDate("_created").getTime());
document=result.get(1);
Assert.assertEquals("adminp", document.getItemValueString("type"));
Assert.assertEquals("60825929-4d7d-4346-9333-afd7dbfca457",document.getItemValueString("id"));
Assert.assertEquals(1567278978000l, document.getItemValueDate("_created").getTime());
}
#location 42
#vulnerability type NULL_DEREFERENCE | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
private void readResponse(URLConnection urlConnection) throws IOException {
// get content of result
logger.finest("...... readResponse....");
StringWriter writer = new StringWriter();
BufferedReader in = null;
try {
// test if content encoding is provided
String sContentEncoding = urlConnection.getContentEncoding();
if (sContentEncoding == null || sContentEncoding.isEmpty()) {
// no so lets see if the client has defined an encoding..
if (encoding != null && !encoding.isEmpty())
sContentEncoding = encoding;
}
// if an encoding is provided read stream with encoding.....
if (sContentEncoding != null && !sContentEncoding.isEmpty())
in = new BufferedReader(new InputStreamReader(urlConnection.getInputStream(), sContentEncoding));
else
in = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
String inputLine;
while ((inputLine = in.readLine()) != null) {
logger.finest("......"+inputLine);
writer.write(inputLine);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (in != null)
in.close();
}
setContent(writer.toString());
} | #vulnerable code
private void readResponse(URLConnection urlConnection) throws IOException {
// get content of result
logger.fine("[RestClient] readResponse....");
StringWriter writer = new StringWriter();
BufferedReader in = null;
try {
// test if content encoding is provided
String sContentEncoding = urlConnection.getContentEncoding();
if (sContentEncoding == null || sContentEncoding.isEmpty()) {
// no so lets see if the client has defined an encoding..
if (encoding != null && !encoding.isEmpty())
sContentEncoding = encoding;
}
// if an encoding is provided read stream with encoding.....
if (sContentEncoding != null && !sContentEncoding.isEmpty())
in = new BufferedReader(new InputStreamReader(urlConnection.getInputStream(), sContentEncoding));
else
in = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
String inputLine;
while ((inputLine = in.readLine()) != null) {
logger.fine(inputLine);
writer.write(inputLine);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (in != null)
in.close();
}
setContent(writer.toString());
}
#location 17
#vulnerability type RESOURCE_LEAK | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Test
public void testSimple() throws ParseException {
InputStream inputStream = getClass()
.getResourceAsStream("/json/simple.json");
ItemCollection itemCol=null;
try {
itemCol = JSONParser.parseWorkitem(inputStream,"UTF-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
Assert.fail();
}
Assert.assertNotNull(itemCol);
Assert.assertEquals("Anna", itemCol.getItemValueString("$readaccess"));
List<?> list=itemCol.getItemValue("txtLog");
Assert.assertEquals(3, list.size());
Assert.assertEquals("C", list.get(2));
Assert.assertEquals(10, itemCol.getItemValueInteger("$ActivityID"));
} | #vulnerable code
@Test
public void testSimple() throws ParseException {
InputStream inputStream = getClass()
.getResourceAsStream("/json/simple.json");
ItemCollection itemCol = JSONParser.parseWorkitem(inputStream);
Assert.assertNotNull(itemCol);
Assert.assertEquals("Anna", itemCol.getItemValueString("$readaccess"));
List<?> list=itemCol.getItemValue("txtLog");
Assert.assertEquals(3, list.size());
Assert.assertEquals("C", list.get(2));
Assert.assertEquals(10, itemCol.getItemValueInteger("$ActivityID"));
}
#location 11
#vulnerability type NULL_DEREFERENCE | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Test
public void testAddWorkdaysFromMonday() {
Calendar startDate = Calendar.getInstance();
// adjust to FRIDAY
startDate.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY);
System.out.println("Startdate=" + startDate.getTime());
Assert.assertEquals(Calendar.TUESDAY,
workflowSchedulerService.addWorkDays(startDate, 1).get(Calendar.DAY_OF_WEEK));
Assert.assertEquals(Calendar.WEDNESDAY,
workflowSchedulerService.addWorkDays(startDate, 2).get(Calendar.DAY_OF_WEEK));
Assert.assertEquals(Calendar.FRIDAY,
workflowSchedulerService.addWorkDays(startDate, 4).get(Calendar.DAY_OF_WEEK));
Assert.assertEquals(Calendar.MONDAY,
workflowSchedulerService.addWorkDays(startDate, 5).get(Calendar.DAY_OF_WEEK));
Assert.assertEquals(Calendar.FRIDAY,
workflowSchedulerService.addWorkDays(startDate, 9).get(Calendar.DAY_OF_WEEK));
Assert.assertEquals(Calendar.MONDAY,
workflowSchedulerService.addWorkDays(startDate, 10).get(Calendar.DAY_OF_WEEK));
} | #vulnerable code
@Test
public void testAddWorkdaysFromMonday() {
Calendar startDate = Calendar.getInstance();
// adjust to FRIDAY
startDate.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY);
System.out.println("Startdate=" + startDate.getTime());
Assert.assertEquals(Calendar.TUESDAY,
WorkflowSchedulerService.addWorkDays(startDate, 1).get(Calendar.DAY_OF_WEEK));
Assert.assertEquals(Calendar.WEDNESDAY,
WorkflowSchedulerService.addWorkDays(startDate, 2).get(Calendar.DAY_OF_WEEK));
Assert.assertEquals(Calendar.FRIDAY,
WorkflowSchedulerService.addWorkDays(startDate, 4).get(Calendar.DAY_OF_WEEK));
Assert.assertEquals(Calendar.MONDAY,
WorkflowSchedulerService.addWorkDays(startDate, 5).get(Calendar.DAY_OF_WEEK));
Assert.assertEquals(Calendar.FRIDAY,
WorkflowSchedulerService.addWorkDays(startDate, 9).get(Calendar.DAY_OF_WEEK));
Assert.assertEquals(Calendar.MONDAY,
WorkflowSchedulerService.addWorkDays(startDate, 10).get(Calendar.DAY_OF_WEEK));
}
#location 11
#vulnerability type NULL_DEREFERENCE | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Test
public void testAddWorkdaysFromFriday() {
Calendar startDate = Calendar.getInstance();
// adjust to FRIDAY
startDate.set(Calendar.DAY_OF_WEEK, Calendar.FRIDAY);
System.out.println("Startdate=" + startDate.getTime());
// adjust -3 Workdays -> THUSEDAY
Assert.assertEquals(Calendar.TUESDAY,
workflowSchedulerService.addWorkDays(startDate, 2).get(Calendar.DAY_OF_WEEK));
Assert.assertEquals(Calendar.WEDNESDAY,
workflowSchedulerService.addWorkDays(startDate, 8).get(Calendar.DAY_OF_WEEK));
Assert.assertEquals(Calendar.FRIDAY,
workflowSchedulerService.addWorkDays(startDate, 10).get(Calendar.DAY_OF_WEEK));
Assert.assertEquals(Calendar.THURSDAY,
workflowSchedulerService.addWorkDays(startDate, 14).get(Calendar.DAY_OF_WEEK));
} | #vulnerable code
@Test
public void testAddWorkdaysFromFriday() {
Calendar startDate = Calendar.getInstance();
// adjust to FRIDAY
startDate.set(Calendar.DAY_OF_WEEK, Calendar.FRIDAY);
System.out.println("Startdate=" + startDate.getTime());
// adjust -3 Workdays -> THUSEDAY
Assert.assertEquals(Calendar.TUESDAY,
WorkflowSchedulerService.addWorkDays(startDate, 2).get(Calendar.DAY_OF_WEEK));
Assert.assertEquals(Calendar.WEDNESDAY,
WorkflowSchedulerService.addWorkDays(startDate, 8).get(Calendar.DAY_OF_WEEK));
Assert.assertEquals(Calendar.FRIDAY,
WorkflowSchedulerService.addWorkDays(startDate, 10).get(Calendar.DAY_OF_WEEK));
Assert.assertEquals(Calendar.THURSDAY,
WorkflowSchedulerService.addWorkDays(startDate, 14).get(Calendar.DAY_OF_WEEK));
}
#location 17
#vulnerability type NULL_DEREFERENCE | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
ChannelManager(AsteriskServerImpl server)
{
this.server = server;
this.channels = new HashSet<AsteriskChannelImpl>();
} | #vulnerable code
void handleNewChannelEvent(NewChannelEvent event)
{
final AsteriskChannelImpl channel = getChannelImplById(event.getUniqueId());
if (channel == null)
{
if (event.getChannel() == null)
{
logger.info("Ignored NewChannelEvent with empty channel name (uniqueId=" + event.getUniqueId() + ")");
}
else
{
addNewChannel(
event.getUniqueId(), event.getChannel(), event.getDateReceived(),
event.getCallerIdNum(), event.getCallerIdName(),
ChannelState.valueOf(event.getChannelState()), event.getAccountCode());
}
}
else
{
// channel had already been created probably by a NewCallerIdEvent
synchronized (channel)
{
channel.nameChanged(event.getDateReceived(), event.getChannel());
channel.setCallerId(new CallerId(event.getCallerIdName(), event.getCallerIdNum()));
channel.stateChanged(event.getDateReceived(), ChannelState.valueOf(event.getChannelState()));
}
}
}
#location 13
#vulnerability type THREAD_SAFETY_VIOLATION | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
public int[] getVersion(String file) throws ManagerCommunicationException
{
String fileVersion = null;
String[] parts;
int[] intParts;
initializeIfNeeded();
if (versions == null)
{
Map<String, String> map;
ManagerResponse response;
map = new HashMap<String, String>();
try
{
final String command;
if (eventConnection.getVersion().isAtLeast(AsteriskVersion.ASTERISK_1_6))
{
command = SHOW_VERSION_FILES_1_6_COMMAND;
}
else
{
command = SHOW_VERSION_FILES_COMMAND;
}
response = sendAction(new CommandAction(command));
if (response instanceof CommandResponse)
{
List<String> result;
result = ((CommandResponse) response).getResult();
for (int i = 2; i < result.size(); i++)
{
String line;
Matcher matcher;
line = result.get(i);
matcher = SHOW_VERSION_FILES_PATTERN.matcher(line);
if (matcher.find())
{
String key = matcher.group(1);
String value = matcher.group(2);
map.put(key, value);
}
}
fileVersion = map.get(file);
versions = map;
}
else
{
logger.error("Response to CommandAction(\""
+ SHOW_VERSION_FILES_COMMAND
+ "\") was not a CommandResponse but " + response);
}
}
catch (Exception e)
{
logger.warn("Unable to send '" + SHOW_VERSION_FILES_COMMAND + "' command.", e);
}
}
else
{
synchronized (versions)
{
fileVersion = versions.get(file);
}
}
if (fileVersion == null)
{
return null;
}
parts = fileVersion.split("\\.");
intParts = new int[parts.length];
for (int i = 0; i < parts.length; i++)
{
try
{
intParts[i] = Integer.parseInt(parts[i]);
}
catch (NumberFormatException e)
{
intParts[i] = 0;
}
}
return intParts;
} | #vulnerable code
public int[] getVersion(String file) throws ManagerCommunicationException
{
String fileVersion = null;
String[] parts;
int[] intParts;
initializeIfNeeded();
if (versions == null)
{
Map<String, String> map;
ManagerResponse response;
map = new HashMap<String, String>();
try
{
response = sendAction(new CommandAction(SHOW_VERSION_FILES_COMMAND));
if (response instanceof CommandResponse)
{
List<String> result;
result = ((CommandResponse) response).getResult();
for (int i = 2; i < result.size(); i++)
{
String line;
Matcher matcher;
line = result.get(i);
matcher = SHOW_VERSION_FILES_PATTERN.matcher(line);
if (matcher.find())
{
String key = matcher.group(1);
String value = matcher.group(2);
map.put(key, value);
}
}
fileVersion = map.get(file);
versions = map;
}
else
{
logger.error("Response to CommandAction(\""
+ SHOW_VERSION_FILES_COMMAND
+ "\") was not a CommandResponse but " + response);
}
}
catch (Exception e)
{
logger.warn("Unable to send '" + SHOW_VERSION_FILES_COMMAND + "' command.", e);
}
}
else
{
synchronized (versions)
{
fileVersion = versions.get(file);
}
}
if (fileVersion == null)
{
return null;
}
parts = fileVersion.split("\\.");
intParts = new int[parts.length];
for (int i = 0; i < parts.length; i++)
{
try
{
intParts[i] = Integer.parseInt(parts[i]);
}
catch (NumberFormatException e)
{
intParts[i] = 0;
}
}
return intParts;
}
#location 16
#vulnerability type THREAD_SAFETY_VIOLATION | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Override
public void onManagerEvent(final org.asteriskjava.manager.event.ManagerEvent event)
{
// logger.error(event);
boolean wanted = false;
/**
* Dump any events we arn't interested in ASAP to minimise the
* processing overhead of these events.
*/
// Only enqueue the events that are of interest to one of our listeners.
synchronized (this.globalEvents)
{
Class< ? extends ManagerEvent> shadowEvent = CoherentEventFactory.getShadowEvent(event);
if (this.globalEvents.contains(shadowEvent))
{
wanted = true;
}
}
if (wanted)
{
// We don't support all events.
this._eventQueue.add(new EventLifeMonitor<>(event));
if (_eventQueue.remainingCapacity() < QUEUE_SIZE / 10
&& suppressQueueSizeErrorUntil < System.currentTimeMillis())
{
suppressQueueSizeErrorUntil = System.currentTimeMillis() + 1000;
logger.error("EventQueue more than 90% full");
}
}
} | #vulnerable code
@Override
public void onManagerEvent(final org.asteriskjava.manager.event.ManagerEvent event)
{
// logger.error(event);
boolean wanted = false;
/**
* Dump any events we arn't interested in ASAP to minimise the
* processing overhead of these events.
*/
// Only enqueue the events that are of interest to one of our listeners.
synchronized (this.globalEvents)
{
Class< ? extends ManagerEvent> shadowEvent = CoherentEventFactory.getShadowEvent(event);
if (this.globalEvents.contains(shadowEvent))
{
wanted = true;
}
}
if (wanted)
{
// We don't support all events.
this._eventQueue.add(new EventLifeMonitor<>(event));
final int queueSize = this._eventQueue.size();
if (this._queueMaxSize < queueSize)
{
this._queueMaxSize = queueSize;
}
this._queueSum += queueSize;
this._queueCount++;
if (CoherentManagerEventQueue.logger.isDebugEnabled())
{
if (this._eventQueue.size() > ((this._queueMaxSize + (this._queueSum / this._queueCount)) / 2))
{
CoherentManagerEventQueue.logger.debug("queue gtr max avg: size=" + queueSize + " max:" //$NON-NLS-1$ //$NON-NLS-2$
+ this._queueMaxSize + " avg:" + (this._queueSum / this._queueCount)); //$NON-NLS-1$
}
}
}
}
#location 31
#vulnerability type THREAD_SAFETY_VIOLATION | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
public void dispatchEvent(ManagerEvent event)
{
// shouldn't happen
if (event == null)
{
logger.error("Unable to dispatch null event");
return;
}
logger.debug("Dispatching event:\n" + event.toString());
// dispatch ResponseEvents to the appropriate responseEventHandler
if (event instanceof ResponseEvent)
{
ResponseEvent responseEvent;
String internalActionId;
responseEvent = (ResponseEvent) event;
internalActionId = responseEvent.getInternalActionId();
if (internalActionId != null)
{
synchronized (responseEventListeners)
{
ManagerEventListener listener;
listener = responseEventListeners.get(internalActionId);
if (listener != null)
{
try
{
listener.onManagerEvent(event);
}
catch (RuntimeException e)
{
logger.warn("Unexpected exception in event listener "
+ listener.getClass().getName(), e);
}
}
}
}
else
{
// ResponseEvent without internalActionId:
// this happens if the same event class is used as response event
// and as an event that is not triggered by a Manager command
// example: QueueMemberStatusEvent.
//logger.debug("ResponseEvent without "
// + "internalActionId:\n" + responseEvent);
}
}
if (event instanceof DisconnectEvent)
{
if (state == CONNECTED)
{
state = RECONNECTING;
cleanup();
reconnectThread = new Thread(new Runnable()
{
public void run()
{
reconnect();
}
});
reconnectThread.setName("ReconnectThread-" + reconnectThreadNum.getAndIncrement());
reconnectThread.setDaemon(true);
reconnectThread.start();
}
}
if (event instanceof ProtocolIdentifierReceivedEvent)
{
ProtocolIdentifierReceivedEvent protocolIdentifierReceivedEvent;
String protocolIdentifier;
protocolIdentifierReceivedEvent = (ProtocolIdentifierReceivedEvent) event;
protocolIdentifier = protocolIdentifierReceivedEvent.getProtocolIdentifier();
setProtocolIdentifier(protocolIdentifier);
}
// dispatch to listeners registered by users
synchronized (eventListeners)
{
for (ManagerEventListener listener : eventListeners)
{
try
{
listener.onManagerEvent(event);
}
catch (RuntimeException e)
{
logger.warn("Unexpected exception in eventHandler "
+ listener.getClass().getName(), e);
}
}
}
} | #vulnerable code
public void dispatchEvent(ManagerEvent event)
{
// shouldn't happen
if (event == null)
{
logger.error("Unable to dispatch null event");
return;
}
logger.debug("Dispatching event:\n" + event.toString());
// dispatch ResponseEvents to the appropriate responseEventHandler
if (event instanceof ResponseEvent)
{
ResponseEvent responseEvent;
String internalActionId;
responseEvent = (ResponseEvent) event;
internalActionId = responseEvent.getInternalActionId();
if (internalActionId != null)
{
synchronized (responseEventListeners)
{
ManagerEventListener listener;
listener = responseEventListeners.get(internalActionId);
if (listener != null)
{
try
{
listener.onManagerEvent(event);
}
catch (RuntimeException e)
{
logger.warn("Unexpected exception in event listener "
+ listener.getClass().getName(), e);
}
}
}
}
else
{
// ResponseEvent without internalActionId:
// this happens if the same event class is used as response event
// and as an event that is not triggered by a Manager command
// example: QueueMemberStatusEvent.
//logger.debug("ResponseEvent without "
// + "internalActionId:\n" + responseEvent);
}
}
if (event instanceof DisconnectEvent)
{
if (state == CONNECTED)
{
state = RECONNECTING;
cleanup();
reconnectThread = new Thread(new Runnable()
{
public void run()
{
reconnect();
}
});
reconnectThread.setName("ReconnectThread-" + reconnectThreadNum++);
reconnectThread.setDaemon(true);
reconnectThread.start();
}
}
if (event instanceof ProtocolIdentifierReceivedEvent)
{
ProtocolIdentifierReceivedEvent protocolIdentifierReceivedEvent;
String protocolIdentifier;
protocolIdentifierReceivedEvent = (ProtocolIdentifierReceivedEvent) event;
protocolIdentifier = protocolIdentifierReceivedEvent.getProtocolIdentifier();
setProtocolIdentifier(protocolIdentifier);
}
// dispatch to listeners registered by users
synchronized (eventListeners)
{
for (ManagerEventListener listener : eventListeners)
{
try
{
listener.onManagerEvent(event);
}
catch (RuntimeException e)
{
logger.warn("Unexpected exception in eventHandler "
+ listener.getClass().getName(), e);
}
}
}
}
#location 64
#vulnerability type THREAD_SAFETY_VIOLATION | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
public int[] getVersion(String file)
{
String fileVersion = null;
String[] parts;
int[] intParts;
if (versions == null)
{
Map<String, String> map;
ManagerResponse response;
map = new HashMap<String, String>();
try
{
response = sendAction(new CommandAction("show version files"));
if (response instanceof CommandResponse)
{
List<String> result;
result = ((CommandResponse) response).getResult();
for (int i = 2; i < result.size(); i++)
{
String line;
Matcher matcher;
line = (String) result.get(i);
matcher = SHOW_VERSION_FILES_PATTERN.matcher(line);
if (matcher.find())
{
String key = matcher.group(1);
String value = matcher.group(2);
map.put(key, value);
}
}
fileVersion = (String) map.get(file);
versions = map;
}
}
catch (Exception e)
{
logger.warn("Unable to send 'show version files' command.", e);
}
}
else
{
synchronized (versions)
{
fileVersion = versions.get(file);
}
}
if (fileVersion == null)
{
return null;
}
parts = fileVersion.split("\\.");
intParts = new int[parts.length];
for (int i = 0; i < parts.length; i++)
{
try
{
intParts[i] = Integer.parseInt(parts[i]);
}
catch (NumberFormatException e)
{
intParts[i] = 0;
}
}
return intParts;
} | #vulnerable code
public int[] getVersion(String file)
{
String fileVersion = null;
String[] parts;
int[] intParts;
if (versions == null)
{
Map<String, String> map;
ManagerResponse response;
map = new HashMap<String, String>();
try
{
response = eventConnection.sendAction(new CommandAction(
"show version files"));
if (response instanceof CommandResponse)
{
List<String> result;
result = ((CommandResponse) response).getResult();
for (int i = 2; i < result.size(); i++)
{
String line;
Matcher matcher;
line = (String) result.get(i);
matcher = SHOW_VERSION_FILES_PATTERN.matcher(line);
if (matcher.find())
{
String key = matcher.group(1);
String value = matcher.group(2);
map.put(key, value);
}
}
fileVersion = (String) map.get(file);
versions = map;
}
}
catch (Exception e)
{
logger.warn("Unable to send 'show version files' command.", e);
}
}
else
{
synchronized (versions)
{
fileVersion = versions.get(file);
}
}
if (fileVersion == null)
{
return null;
}
parts = fileVersion.split("\\.");
intParts = new int[parts.length];
for (int i = 0; i < parts.length; i++)
{
try
{
intParts[i] = Integer.parseInt(parts[i]);
}
catch (NumberFormatException e)
{
intParts[i] = 0;
}
}
return intParts;
}
#location 15
#vulnerability type THREAD_SAFETY_VIOLATION | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
public ManagerResponse sendAction(ManagerAction action, long timeout)
throws IOException, TimeoutException, IllegalArgumentException,
IllegalStateException
{
ResponseHandlerResult result;
ManagerResponseHandler callbackHandler;
result = new ResponseHandlerResult();
callbackHandler = new DefaultResponseHandler(result);
synchronized (result)
{
sendAction(action, callbackHandler);
try
{
result.wait(timeout);
}
catch (InterruptedException ex)
{
//TODO fix logging
System.err.println("Interrupted!");
}
}
// still no response?
if (result.getResponse() == null)
{
throw new TimeoutException("Timeout waiting for response to "
+ action.getAction());
}
return result.getResponse();
} | #vulnerable code
public ManagerResponse sendAction(ManagerAction action, long timeout)
throws IOException, TimeoutException, IllegalArgumentException,
IllegalStateException
{
long start;
long timeSpent;
ResponseHandlerResult result;
ManagerResponseHandler callbackHandler;
result = new ResponseHandlerResult();
callbackHandler = new DefaultResponseHandler(result, Thread
.currentThread());
sendAction(action, callbackHandler);
start = System.currentTimeMillis();
timeSpent = 0;
while (result.getResponse() == null)
{
try
{
Thread.sleep(timeout - timeSpent);
}
catch (InterruptedException ex)
{
}
// still no response and timed out?
timeSpent = System.currentTimeMillis() - start;
if (result.getResponse() == null && timeSpent > timeout)
{
throw new TimeoutException("Timeout waiting for response to "
+ action.getAction());
}
}
return result.getResponse();
}
#location 14
#vulnerability type THREAD_SAFETY_VIOLATION | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
public void dispatchEvent(ManagerEvent event)
{
// shouldn't happen
if (event == null)
{
logger.error("Unable to dispatch null event. This should never happen. Please file a bug.");
return;
}
logger.debug("Dispatching event:\n" + event.toString());
// Some events need special treatment besides forwarding them to the
// registered eventListeners (clients)
// These events are handled here at first:
// Dispatch ResponseEvents to the appropriate responseEventListener
if (event instanceof ResponseEvent)
{
ResponseEvent responseEvent;
String internalActionId;
responseEvent = (ResponseEvent) event;
internalActionId = responseEvent.getInternalActionId();
if (internalActionId != null)
{
synchronized (responseEventListeners)
{
ManagerEventListener listener;
listener = responseEventListeners.get(internalActionId);
if (listener != null)
{
try
{
listener.onManagerEvent(event);
}
catch (Exception e)
{
logger.warn("Unexpected exception in response event listener " + listener.getClass().getName(),
e);
}
}
}
}
else
{
// ResponseEvent without internalActionId:
// this happens if the same event class is used as response
// event
// and as an event that is not triggered by a Manager command
// Example: QueueMemberStatusEvent.
// logger.debug("ResponseEvent without "
// + "internalActionId:\n" + responseEvent);
} // NOPMD
}
if (event instanceof DisconnectEvent)
{
// When we receive get disconnected while we are connected start
// a new reconnect thread and set the state to RECONNECTING.
if (state == CONNECTED)
{
state = RECONNECTING;
// close socket if still open and remove reference to
// readerThread
// After sending the DisconnectThread that thread will die
// anyway.
cleanup();
Thread reconnectThread = new Thread(new Runnable()
{
public void run()
{
reconnect();
}
});
reconnectThread.setName("Asterisk-Java ManagerConnection-" + id + "-Reconnect-"
+ reconnectThreadCounter.getAndIncrement());
reconnectThread.setDaemon(true);
reconnectThread.start();
// now the DisconnectEvent is dispatched to registered
// eventListeners
// (clients) and after that the ManagerReaderThread is gone.
// So effectively we replaced the reader thread by a
// ReconnectThread.
}
else
{
// when we receive a DisconnectEvent while not connected we
// ignore it and do not send it to clients
return;
}
}
if (event instanceof ProtocolIdentifierReceivedEvent)
{
ProtocolIdentifierReceivedEvent protocolIdentifierReceivedEvent;
String protocolIdentifier;
protocolIdentifierReceivedEvent = (ProtocolIdentifierReceivedEvent) event;
protocolIdentifier = protocolIdentifierReceivedEvent.getProtocolIdentifier();
setProtocolIdentifier(protocolIdentifier);
// no need to send this event to clients
return;
}
fireEvent(event);
} | #vulnerable code
public void dispatchEvent(ManagerEvent event)
{
// shouldn't happen
if (event == null)
{
logger.error("Unable to dispatch null event. This should never happen. Please file a bug.");
return;
}
logger.debug("Dispatching event:\n" + event.toString());
// Some events need special treatment besides forwarding them to the
// registered eventListeners (clients)
// These events are handled here at first:
// Dispatch ResponseEvents to the appropriate responseEventListener
if (event instanceof ResponseEvent)
{
ResponseEvent responseEvent;
String internalActionId;
responseEvent = (ResponseEvent) event;
internalActionId = responseEvent.getInternalActionId();
if (internalActionId != null)
{
synchronized (responseEventListeners)
{
ManagerEventListener listener;
listener = responseEventListeners.get(internalActionId);
if (listener != null)
{
try
{
listener.onManagerEvent(event);
}
catch (Exception e)
{
logger.warn("Unexpected exception in response event listener " + listener.getClass().getName(),
e);
}
}
}
}
else
{
// ResponseEvent without internalActionId:
// this happens if the same event class is used as response
// event
// and as an event that is not triggered by a Manager command
// Example: QueueMemberStatusEvent.
// logger.debug("ResponseEvent without "
// + "internalActionId:\n" + responseEvent);
} // NOPMD
}
if (event instanceof DisconnectEvent)
{
// When we receive get disconnected while we are connected start
// a new reconnect thread and set the state to RECONNECTING.
if (state == CONNECTED)
{
state = RECONNECTING;
// close socket if still open and remove reference to
// readerThread
// After sending the DisconnectThread that thread will die
// anyway.
cleanup();
reconnectThread = new Thread(new Runnable()
{
public void run()
{
reconnect();
}
});
reconnectThread.setName("Asterisk-Java ManagerConnection-" + id + "-Reconnect-"
+ reconnectThreadCounter.getAndIncrement());
reconnectThread.setDaemon(true);
reconnectThread.start();
// now the DisconnectEvent is dispatched to registered
// eventListeners
// (clients) and after that the ManagerReaderThread is gone.
// So effectively we replaced the reader thread by a
// ReconnectThread.
}
else
{
// when we receive a DisconnectEvent while not connected we
// ignore it and do not send it to clients
return;
}
}
if (event instanceof ProtocolIdentifierReceivedEvent)
{
ProtocolIdentifierReceivedEvent protocolIdentifierReceivedEvent;
String protocolIdentifier;
protocolIdentifierReceivedEvent = (ProtocolIdentifierReceivedEvent) event;
protocolIdentifier = protocolIdentifierReceivedEvent.getProtocolIdentifier();
setProtocolIdentifier(protocolIdentifier);
// no need to send this event to clients
return;
}
fireEvent(event);
}
#location 78
#vulnerability type THREAD_SAFETY_VIOLATION | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
public void redirectBothLegs(String context, String exten, int priority) throws ManagerCommunicationException,
NoSuchChannelException
{
ManagerResponse response;
if (linkedChannels.isEmpty())
{
response = server.sendAction(new RedirectAction(name, context, exten, priority));
}
else
{
response = server.sendAction(new RedirectAction(name, linkedChannels.get(0).getName(), context, exten, priority,
context, exten, priority));
}
if (response instanceof ManagerError)
{
throw new NoSuchChannelException("Channel '" + name + "' is not available: " + response.getMessage());
}
} | #vulnerable code
public void redirectBothLegs(String context, String exten, int priority) throws ManagerCommunicationException,
NoSuchChannelException
{
ManagerResponse response;
if (linkedChannel == null)
{
response = server.sendAction(new RedirectAction(name, context, exten, priority));
}
else
{
response = server.sendAction(new RedirectAction(name, linkedChannel.getName(), context, exten, priority,
context, exten, priority));
}
if (response instanceof ManagerError)
{
throw new NoSuchChannelException("Channel '" + name + "' is not available: " + response.getMessage());
}
}
#location 12
#vulnerability type THREAD_SAFETY_VIOLATION | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
OriginateResult originate(final EndPoint local, final EndPoint target, final HashMap<String, String> myVars,
final CallerID callerID, final Integer timeout, final boolean hideCallerId, final String context)
{
OriginateBaseClass.logger.info("originate called");
this.originateSeen = false;
this.channelSeen = false;
if (this.hungup)
{
// the monitored channel already hungup so just return false and
// shutdown
return null;
}
OriginateBaseClass.logger.info("originate connection endPoint \n" + local + " to endPoint " + target //$NON-NLS-2$
+ " vars " + myVars);
ManagerResponse response = null;
final AsteriskSettings settings = PBXFactory.getActiveProfile();
final OriginateAction originate = new OriginateAction();
this.originateID = originate.getActionId();
channelId = "" + (System.currentTimeMillis() / 1000) + ".AJ" + originateSeed.incrementAndGet();
originate.setChannelId(channelId);
Integer localTimeout = timeout;
if (timeout == null)
{
localTimeout = 30000;
try
{
localTimeout = settings.getDialTimeout() * 1000;
}
catch (final Exception e)
{
OriginateBaseClass.logger.error("Invalid dial timeout value");
}
}
// Whilst the originate document says that it takes a channel it
// actually takes an
// end point. I haven't check but I'm skeptical that you can actually
// originate to
// a channel as the doco talks about 'dialing the channel'. I suspect
// this
// may be part of asterisk's sloppy terminology.
if (local.isLocal())
{
originate.setEndPoint(local);
originate.setOption("/n");
}
else
{
originate.setEndPoint(local);
}
originate.setContext(context);
originate.setExten(target);
originate.setPriority(1);
// Set the caller id.
if (hideCallerId)
{
// hide callerID
originate.setCallingPres(32);
}
else
{
originate.setCallerId(callerID);
}
originate.setVariables(myVars);
originate.setAsync(true);
originate.setTimeout(localTimeout);
try
{
// Just add us as an asterisk event listener.
this.startListener();
response = pbx.sendAction(originate, localTimeout);
OriginateBaseClass.logger.info("Originate.sendAction completed");
if (response.getResponse().compareToIgnoreCase("Success") != 0)
{
OriginateBaseClass.logger
.error("Error Originating call" + originate.toString() + " : " + response.getMessage());//$NON-NLS-2$
throw new ManagerCommunicationException(response.getMessage(), null);
}
// wait the set timeout +1 second to allow for
// asterisk to start the originate
if (!originateLatch.await(localTimeout + 1000, TimeUnit.MILLISECONDS))
{
logger.error("Originate Latch timed out");
}
}
catch (final InterruptedException e)
{
OriginateBaseClass.logger.debug(e, e);
}
catch (final Exception e)
{
OriginateBaseClass.logger.error(e, e);
}
finally
{
this.close();
}
if (this.originateSuccess)
{
this.result.setSuccess(true);
this.result.setChannelData(this.newChannel);
OriginateBaseClass.logger.info("new channel ok: " + this.newChannel);
}
else
{
OriginateBaseClass.logger.warn("originate failed to connect endPoint: " + local + " to ext " + target); //$NON-NLS-2$
if (this.newChannel != null)
{
try
{
logger.warn("Hanging up");
pbx.hangup(this.newChannel);
}
catch (IllegalArgumentException | IllegalStateException | PBXException e)
{
logger.error(e, e);
}
}
}
return this.result;
} | #vulnerable code
OriginateResult originate(final EndPoint local, final EndPoint target, final HashMap<String, String> myVars,
final CallerID callerID, final Integer timeout, final boolean hideCallerId, final String context)
{
OriginateBaseClass.logger.warn("originate called");
this.originateSeen = false;
this.channelSeen = false;
if (this.hungup)
{
// the monitored channel already hungup so just return false and
// shutdown
return null;
}
OriginateBaseClass.logger.warn("originate connection endPoint \n" + local + " to endPoint " + target //$NON-NLS-2$
+ " vars " + myVars);
ManagerResponse response = null;
final AsteriskSettings settings = PBXFactory.getActiveProfile();
final OriginateAction originate = new OriginateAction();
this.originateID = originate.getActionId();
channelId = "" + (System.currentTimeMillis() / 1000) + ".AJ" + originateSeed.incrementAndGet();
originate.setChannelId(channelId);
Integer localTimeout = timeout;
if (timeout == null)
{
localTimeout = 30000;
try
{
localTimeout = settings.getDialTimeout() * 1000;
}
catch (final Exception e)
{
OriginateBaseClass.logger.error("Invalid dial timeout value");
}
}
// Whilst the originate document says that it takes a channel it
// actually takes an
// end point. I haven't check but I'm skeptical that you can actually
// originate to
// a channel as the doco talks about 'dialing the channel'. I suspect
// this
// may be part of asterisk's sloppy terminology.
if (local.isLocal())
{
originate.setEndPoint(local);
originate.setOption("/n");
}
else
{
originate.setEndPoint(local);
}
originate.setContext(context);
originate.setExten(target);
originate.setPriority(1);
// Set the caller id.
if (hideCallerId)
{
// hide callerID
originate.setCallingPres(32);
}
else
{
originate.setCallerId(callerID);
}
originate.setVariables(myVars);
originate.setAsync(true);
originate.setTimeout(localTimeout);
try
{
// Just add us as an asterisk event listener.
this.startListener();
response = pbx.sendAction(originate, localTimeout);
OriginateBaseClass.logger.warn("Originate.sendAction completed");
if (response.getResponse().compareToIgnoreCase("Success") != 0)
{
OriginateBaseClass.logger
.error("Error Originating call" + originate.toString() + " : " + response.getMessage());//$NON-NLS-2$
throw new ManagerCommunicationException(response.getMessage(), null);
}
// wait the set timeout +1 second to allow for
// asterisk to start the originate
if (!originateLatch.await(localTimeout + 1000, TimeUnit.MILLISECONDS))
{
logger.error("Originate Latch timed out");
}
}
catch (final InterruptedException e)
{
OriginateBaseClass.logger.debug(e, e);
}
catch (final Exception e)
{
OriginateBaseClass.logger.error(e, e);
}
finally
{
this.close();
}
if (this.originateSuccess)
{
this.result.setSuccess(true);
this.result.setChannelData(this.newChannel);
OriginateBaseClass.logger.warn("new channel ok: " + this.newChannel);
}
else
{
OriginateBaseClass.logger.warn("originate failed to connect endPoint: " + local + " to ext " + target); //$NON-NLS-2$
if (this.newChannel != null)
{
try
{
logger.warn("Hanging up");
pbx.hangup(this.newChannel);
}
catch (IllegalArgumentException | IllegalStateException | PBXException e)
{
logger.error(e, e);
}
}
}
logger.warn("Manager Events seen " + managerEventsSeen.get());
return this.result;
}
#location 127
#vulnerability type THREAD_SAFETY_VIOLATION | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
public AsteriskChannel getLinkedChannel()
{
synchronized(linkedChannels) {
if (linkedChannels.isEmpty()) return null;
return linkedChannels.get(0);
}
} | #vulnerable code
public AsteriskChannel getLinkedChannel()
{
return linkedChannel;
}
#location 3
#vulnerability type THREAD_SAFETY_VIOLATION | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Override
public void onManagerEvent(final org.asteriskjava.manager.event.ManagerEvent event)
{
// logger.error(event);
boolean wanted = false;
/**
* Dump any events we arn't interested in ASAP to minimise the
* processing overhead of these events.
*/
// Only enqueue the events that are of interest to one of our listeners.
synchronized (this.globalEvents)
{
Class< ? extends ManagerEvent> shadowEvent = CoherentEventFactory.getShadowEvent(event);
if (this.globalEvents.contains(shadowEvent))
{
wanted = true;
}
}
if (wanted)
{
// We don't support all events.
this._eventQueue.add(new EventLifeMonitor<>(event));
if (_eventQueue.remainingCapacity() < QUEUE_SIZE / 10
&& suppressQueueSizeErrorUntil < System.currentTimeMillis())
{
suppressQueueSizeErrorUntil = System.currentTimeMillis() + 1000;
logger.error("EventQueue more than 90% full");
}
}
} | #vulnerable code
@Override
public void onManagerEvent(final org.asteriskjava.manager.event.ManagerEvent event)
{
// logger.error(event);
boolean wanted = false;
/**
* Dump any events we arn't interested in ASAP to minimise the
* processing overhead of these events.
*/
// Only enqueue the events that are of interest to one of our listeners.
synchronized (this.globalEvents)
{
Class< ? extends ManagerEvent> shadowEvent = CoherentEventFactory.getShadowEvent(event);
if (this.globalEvents.contains(shadowEvent))
{
wanted = true;
}
}
if (wanted)
{
// We don't support all events.
this._eventQueue.add(new EventLifeMonitor<>(event));
final int queueSize = this._eventQueue.size();
if (this._queueMaxSize < queueSize)
{
this._queueMaxSize = queueSize;
}
this._queueSum += queueSize;
this._queueCount++;
if (CoherentManagerEventQueue.logger.isDebugEnabled())
{
if (this._eventQueue.size() > ((this._queueMaxSize + (this._queueSum / this._queueCount)) / 2))
{
CoherentManagerEventQueue.logger.debug("queue gtr max avg: size=" + queueSize + " max:" //$NON-NLS-1$ //$NON-NLS-2$
+ this._queueMaxSize + " avg:" + (this._queueSum / this._queueCount)); //$NON-NLS-1$
}
}
}
}
#location 29
#vulnerability type THREAD_SAFETY_VIOLATION | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
public ManagerResponse sendAction(ManagerAction action, long timeout)
throws IOException, TimeoutException, IllegalArgumentException, IllegalStateException
{
ResponseHandlerResult result = new ResponseHandlerResult();
SendActionCallback callbackHandler = new DefaultSendActionCallback(result);
sendAction(action, callbackHandler);
// definitely return null for the response of user events
if (action instanceof UserEventAction)
{
return null;
}
// only wait if we did not yet receive the response.
// Responses may be returned really fast.
if (result.getResponse() == null)
{
try
{
result.await(timeout);
}
catch (InterruptedException ex)
{
logger.warn("Interrupted while waiting for result");
Thread.currentThread().interrupt();
}
}
// still no response?
if (result.getResponse() == null)
{
throw new TimeoutException("Timeout waiting for response to " + action.getAction()
+ (action.getActionId() == null ? "" : " (actionId: " + action.getActionId() + ")"));
}
return result.getResponse();
} | #vulnerable code
public ManagerResponse sendAction(ManagerAction action, long timeout)
throws IOException, TimeoutException, IllegalArgumentException, IllegalStateException
{
ResponseHandlerResult result;
SendActionCallback callbackHandler;
result = new ResponseHandlerResult();
callbackHandler = new DefaultSendActionCallback(result);
synchronized (result)
{
sendAction(action, callbackHandler);
// definitely return null for the response of user events
if (action instanceof UserEventAction)
{
return null;
}
// only wait if we did not yet receive the response.
// Responses may be returned really fast.
if (result.getResponse() == null)
{
try
{
result.wait(timeout);
}
catch (InterruptedException ex)
{
logger.warn("Interrupted while waiting for result");
Thread.currentThread().interrupt();
}
}
}
// still no response?
if (result.getResponse() == null)
{
throw new TimeoutException("Timeout waiting for response to " + action.getAction()
+ (action.getActionId() == null ? "" : " (actionId: " + action.getActionId() + ")"));
}
return result.getResponse();
}
#location 12
#vulnerability type THREAD_SAFETY_VIOLATION | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
public void dispatchEvent(ManagerEvent event)
{
// shouldn't happen
if (event == null)
{
logger.error("Unable to dispatch null event. This should never happen. Please file a bug.");
return;
}
logger.debug("Dispatching event:\n" + event.toString());
// Some events need special treatment besides forwarding them to the
// registered eventListeners (clients)
// These events are handled here at first:
// Dispatch ResponseEvents to the appropriate responseEventListener
if (event instanceof ResponseEvent)
{
ResponseEvent responseEvent;
String internalActionId;
responseEvent = (ResponseEvent) event;
internalActionId = responseEvent.getInternalActionId();
if (internalActionId != null)
{
synchronized (responseEventListeners)
{
ManagerEventListener listener;
listener = responseEventListeners.get(internalActionId);
if (listener != null)
{
try
{
listener.onManagerEvent(event);
}
catch (Exception e)
{
logger.warn("Unexpected exception in response event listener "
+ listener.getClass().getName(), e);
}
}
}
}
else
{
// ResponseEvent without internalActionId:
// this happens if the same event class is used as response event
// and as an event that is not triggered by a Manager command
// Example: QueueMemberStatusEvent.
//logger.debug("ResponseEvent without "
// + "internalActionId:\n" + responseEvent);
}
}
if (event instanceof DisconnectEvent)
{
// When we receive get disconnected while we are connected start
// a new reconnect thread and set the state to RECONNECTING.
if (state == CONNECTED)
{
state = RECONNECTING;
// close socket if still open and remove reference to readerThread
// After sending the DisconnectThread that thread will die anyway.
cleanup();
reconnectThread = new Thread(new Runnable()
{
public void run()
{
reconnect();
}
});
reconnectThread.setName("ReconnectThread-" + reconnectThreadNum.getAndIncrement());
reconnectThread.setDaemon(true);
reconnectThread.start();
// now the DisconnectEvent is dispatched to registered eventListeners
// (clients) and after that the ManagerReaderThread is gone.
// So effectively we replaced the reader thread by a ReconnectThread.
}
else
{
// when we receive a DisconnectEvent while not connected we
// ignore it and do not send it to clients
return;
}
}
if (event instanceof ProtocolIdentifierReceivedEvent)
{
ProtocolIdentifierReceivedEvent protocolIdentifierReceivedEvent;
String protocolIdentifier;
protocolIdentifierReceivedEvent = (ProtocolIdentifierReceivedEvent) event;
protocolIdentifier = protocolIdentifierReceivedEvent.getProtocolIdentifier();
setProtocolIdentifier(protocolIdentifier);
// no need to send this event to clients
return;
}
fireEvent(event);
} | #vulnerable code
public void dispatchEvent(ManagerEvent event)
{
// shouldn't happen
if (event == null)
{
logger.error("Unable to dispatch null event");
return;
}
logger.debug("Dispatching event:\n" + event.toString());
// dispatch ResponseEvents to the appropriate responseEventHandler
if (event instanceof ResponseEvent)
{
ResponseEvent responseEvent;
String internalActionId;
responseEvent = (ResponseEvent) event;
internalActionId = responseEvent.getInternalActionId();
if (internalActionId != null)
{
synchronized (responseEventListeners)
{
ManagerEventListener listener;
listener = responseEventListeners.get(internalActionId);
if (listener != null)
{
try
{
listener.onManagerEvent(event);
}
catch (RuntimeException e)
{
logger.warn("Unexpected exception in event listener "
+ listener.getClass().getName(), e);
}
}
}
}
else
{
// ResponseEvent without internalActionId:
// this happens if the same event class is used as response event
// and as an event that is not triggered by a Manager command
// example: QueueMemberStatusEvent.
//logger.debug("ResponseEvent without "
// + "internalActionId:\n" + responseEvent);
}
}
if (event instanceof DisconnectEvent)
{
if (state == CONNECTED)
{
state = RECONNECTING;
cleanup();
reconnectThread = new Thread(new Runnable()
{
public void run()
{
reconnect();
}
});
reconnectThread.setName("ReconnectThread-" + reconnectThreadNum.getAndIncrement());
reconnectThread.setDaemon(true);
reconnectThread.start();
}
}
if (event instanceof ProtocolIdentifierReceivedEvent)
{
ProtocolIdentifierReceivedEvent protocolIdentifierReceivedEvent;
String protocolIdentifier;
protocolIdentifierReceivedEvent = (ProtocolIdentifierReceivedEvent) event;
protocolIdentifier = protocolIdentifierReceivedEvent.getProtocolIdentifier();
setProtocolIdentifier(protocolIdentifier);
}
// dispatch to listeners registered by users
synchronized (eventListeners)
{
for (ManagerEventListener listener : eventListeners)
{
try
{
listener.onManagerEvent(event);
}
catch (RuntimeException e)
{
logger.warn("Unexpected exception in eventHandler "
+ listener.getClass().getName(), e);
}
}
}
}
#location 66
#vulnerability type THREAD_SAFETY_VIOLATION | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Override
public void onManagerEvent(final org.asteriskjava.manager.event.ManagerEvent event)
{
// logger.error(event);
boolean wanted = false;
/**
* Dump any events we arn't interested in ASAP to minimise the
* processing overhead of these events.
*/
// Only enqueue the events that are of interest to one of our listeners.
synchronized (this.globalEvents)
{
Class< ? extends ManagerEvent> shadowEvent = CoherentEventFactory.getShadowEvent(event);
if (this.globalEvents.contains(shadowEvent))
{
wanted = true;
}
}
if (wanted)
{
// We don't support all events.
this._eventQueue.add(new EventLifeMonitor<>(event));
if (_eventQueue.remainingCapacity() < QUEUE_SIZE / 10
&& suppressQueueSizeErrorUntil < System.currentTimeMillis())
{
suppressQueueSizeErrorUntil = System.currentTimeMillis() + 1000;
logger.error("EventQueue more than 90% full");
}
}
} | #vulnerable code
@Override
public void onManagerEvent(final org.asteriskjava.manager.event.ManagerEvent event)
{
// logger.error(event);
boolean wanted = false;
/**
* Dump any events we arn't interested in ASAP to minimise the
* processing overhead of these events.
*/
// Only enqueue the events that are of interest to one of our listeners.
synchronized (this.globalEvents)
{
Class< ? extends ManagerEvent> shadowEvent = CoherentEventFactory.getShadowEvent(event);
if (this.globalEvents.contains(shadowEvent))
{
wanted = true;
}
}
if (wanted)
{
// We don't support all events.
this._eventQueue.add(new EventLifeMonitor<>(event));
final int queueSize = this._eventQueue.size();
if (this._queueMaxSize < queueSize)
{
this._queueMaxSize = queueSize;
}
this._queueSum += queueSize;
this._queueCount++;
if (CoherentManagerEventQueue.logger.isDebugEnabled())
{
if (this._eventQueue.size() > ((this._queueMaxSize + (this._queueSum / this._queueCount)) / 2))
{
CoherentManagerEventQueue.logger.debug("queue gtr max avg: size=" + queueSize + " max:" //$NON-NLS-1$ //$NON-NLS-2$
+ this._queueMaxSize + " avg:" + (this._queueSum / this._queueCount)); //$NON-NLS-1$
}
}
}
}
#location 32
#vulnerability type THREAD_SAFETY_VIOLATION | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
public void dispatchEvent(ManagerEvent event)
{
// shouldn't happen
if (event == null)
{
logger.error("Unable to dispatch null event. This should never happen. Please file a bug.");
return;
}
logger.debug("Dispatching event:\n" + event.toString());
// Some events need special treatment besides forwarding them to the
// registered eventListeners (clients)
// These events are handled here at first:
// Dispatch ResponseEvents to the appropriate responseEventListener
if (event instanceof ResponseEvent)
{
ResponseEvent responseEvent;
String internalActionId;
responseEvent = (ResponseEvent) event;
internalActionId = responseEvent.getInternalActionId();
if (internalActionId != null)
{
synchronized (responseEventListeners)
{
ManagerEventListener listener;
listener = responseEventListeners.get(internalActionId);
if (listener != null)
{
try
{
listener.onManagerEvent(event);
}
catch (Exception e)
{
logger.warn("Unexpected exception in response event listener " + listener.getClass().getName(),
e);
}
}
}
}
else
{
// ResponseEvent without internalActionId:
// this happens if the same event class is used as response
// event
// and as an event that is not triggered by a Manager command
// Example: QueueMemberStatusEvent.
// logger.debug("ResponseEvent without "
// + "internalActionId:\n" + responseEvent);
} // NOPMD
}
if (event instanceof DisconnectEvent)
{
// When we receive get disconnected while we are connected start
// a new reconnect thread and set the state to RECONNECTING.
if (state == CONNECTED)
{
state = RECONNECTING;
// close socket if still open and remove reference to
// readerThread
// After sending the DisconnectThread that thread will die
// anyway.
cleanup();
Thread reconnectThread = new Thread(new Runnable()
{
public void run()
{
reconnect();
}
});
reconnectThread.setName("Asterisk-Java ManagerConnection-" + id + "-Reconnect-"
+ reconnectThreadCounter.getAndIncrement());
reconnectThread.setDaemon(true);
reconnectThread.start();
// now the DisconnectEvent is dispatched to registered
// eventListeners
// (clients) and after that the ManagerReaderThread is gone.
// So effectively we replaced the reader thread by a
// ReconnectThread.
}
else
{
// when we receive a DisconnectEvent while not connected we
// ignore it and do not send it to clients
return;
}
}
if (event instanceof ProtocolIdentifierReceivedEvent)
{
ProtocolIdentifierReceivedEvent protocolIdentifierReceivedEvent;
String protocolIdentifier;
protocolIdentifierReceivedEvent = (ProtocolIdentifierReceivedEvent) event;
protocolIdentifier = protocolIdentifierReceivedEvent.getProtocolIdentifier();
setProtocolIdentifier(protocolIdentifier);
// no need to send this event to clients
return;
}
fireEvent(event);
} | #vulnerable code
public void dispatchEvent(ManagerEvent event)
{
// shouldn't happen
if (event == null)
{
logger.error("Unable to dispatch null event. This should never happen. Please file a bug.");
return;
}
logger.debug("Dispatching event:\n" + event.toString());
// Some events need special treatment besides forwarding them to the
// registered eventListeners (clients)
// These events are handled here at first:
// Dispatch ResponseEvents to the appropriate responseEventListener
if (event instanceof ResponseEvent)
{
ResponseEvent responseEvent;
String internalActionId;
responseEvent = (ResponseEvent) event;
internalActionId = responseEvent.getInternalActionId();
if (internalActionId != null)
{
synchronized (responseEventListeners)
{
ManagerEventListener listener;
listener = responseEventListeners.get(internalActionId);
if (listener != null)
{
try
{
listener.onManagerEvent(event);
}
catch (Exception e)
{
logger.warn("Unexpected exception in response event listener " + listener.getClass().getName(),
e);
}
}
}
}
else
{
// ResponseEvent without internalActionId:
// this happens if the same event class is used as response
// event
// and as an event that is not triggered by a Manager command
// Example: QueueMemberStatusEvent.
// logger.debug("ResponseEvent without "
// + "internalActionId:\n" + responseEvent);
} // NOPMD
}
if (event instanceof DisconnectEvent)
{
// When we receive get disconnected while we are connected start
// a new reconnect thread and set the state to RECONNECTING.
if (state == CONNECTED)
{
state = RECONNECTING;
// close socket if still open and remove reference to
// readerThread
// After sending the DisconnectThread that thread will die
// anyway.
cleanup();
reconnectThread = new Thread(new Runnable()
{
public void run()
{
reconnect();
}
});
reconnectThread.setName("Asterisk-Java ManagerConnection-" + id + "-Reconnect-"
+ reconnectThreadCounter.getAndIncrement());
reconnectThread.setDaemon(true);
reconnectThread.start();
// now the DisconnectEvent is dispatched to registered
// eventListeners
// (clients) and after that the ManagerReaderThread is gone.
// So effectively we replaced the reader thread by a
// ReconnectThread.
}
else
{
// when we receive a DisconnectEvent while not connected we
// ignore it and do not send it to clients
return;
}
}
if (event instanceof ProtocolIdentifierReceivedEvent)
{
ProtocolIdentifierReceivedEvent protocolIdentifierReceivedEvent;
String protocolIdentifier;
protocolIdentifierReceivedEvent = (ProtocolIdentifierReceivedEvent) event;
protocolIdentifier = protocolIdentifierReceivedEvent.getProtocolIdentifier();
setProtocolIdentifier(protocolIdentifier);
// no need to send this event to clients
return;
}
fireEvent(event);
}
#location 68
#vulnerability type THREAD_SAFETY_VIOLATION | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
ChannelManager(AsteriskServerImpl server)
{
this.server = server;
this.channels = new HashSet<AsteriskChannelImpl>();
} | #vulnerable code
void handleNewStateEvent(NewStateEvent event)
{
AsteriskChannelImpl channel = getChannelImplById(event.getUniqueId());
if (channel == null)
{
// NewStateEvent can occur for an existing channel that now has a different unique id (originate with Local/)
channel = getChannelImplByNameAndActive(event.getChannel());
if (channel != null)
{
logger.info("Changing unique id for '" + channel.getName() + "' from " + channel.getId() + " to " + event.getUniqueId());
channel.idChanged(event.getDateReceived(), event.getUniqueId());
}
if (channel == null)
{
logger.info("Creating new channel due to NewStateEvent '" + event.getChannel() + "' unique id " + event.getUniqueId());
// NewStateEvent can occur instead of a NewChannelEvent
channel = addNewChannel(
event.getUniqueId(), event.getChannel(), event.getDateReceived(),
event.getCallerIdNum(), event.getCallerIdName(),
ChannelState.valueOf(event.getChannelState()), null /* account code not available */);
}
}
// NewStateEvent can provide a new CallerIdNum or CallerIdName not previously received through a
// NewCallerIdEvent. This happens at least on outgoing legs from the queue application to agents.
if (event.getCallerIdNum() != null || event.getCallerIdName() != null)
{
String cidnum = "";
String cidname = "";
CallerId currentCallerId = channel.getCallerId();
if (currentCallerId != null)
{
cidnum = currentCallerId.getNumber();
cidname = currentCallerId.getName();
}
if (event.getCallerIdNum() != null)
{
cidnum = event.getCallerIdNum();
}
if (event.getCallerIdName() != null)
{
cidname = event.getCallerIdName();
}
CallerId newCallerId = new CallerId(cidname, cidnum);
logger.debug("Updating CallerId (following NewStateEvent) to: " + newCallerId.toString());
channel.setCallerId(newCallerId);
// Also, NewStateEvent can return a new channel name for the same channel uniqueid, indicating the channel has been
// renamed but no related RenameEvent has been received.
// This happens with mISDN channels (see AJ-153)
if (event.getChannel() != null && !event.getChannel().equals(channel.getName()))
{
logger.info("Renaming channel (following NewStateEvent) '" + channel.getName() + "' to '" + event.getChannel() + "'");
synchronized (channel)
{
channel.nameChanged(event.getDateReceived(), event.getChannel());
}
}
}
if (event.getChannelState() != null)
{
synchronized (channel)
{
channel.stateChanged(event.getDateReceived(), ChannelState.valueOf(event.getChannelState()));
}
}
}
#location 11
#vulnerability type THREAD_SAFETY_VIOLATION | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Override public void shutdown() {
if (eventConnection != null && (eventConnection.getState() == ManagerConnectionState.CONNECTED || eventConnection.getState() == ManagerConnectionState.RECONNECTING)) {
try {
eventConnection.logoff();
} catch (Exception ignore) {}
}
if (managerEventListenerProxy != null) {
if (eventConnection != null) {
eventConnection.removeEventListener(managerEventListenerProxy);
}
managerEventListenerProxy.shutdown();
}
if (eventConnection != null && eventListener != null) {
eventConnection.removeEventListener(eventListener);
}
managerEventListenerProxy = null;
eventListener = null;
if (initialized) {//incredible, but it happened
handleDisconnectEvent(null);
}//i
} | #vulnerable code
@Override public void shutdown() {
if (eventConnection != null && (eventConnection.getState() == ManagerConnectionState.CONNECTED || eventConnection.getState() == ManagerConnectionState.RECONNECTING)) {
try {
eventConnection.logoff();
} catch (Exception ignore) {}
}
if (managerEventListenerProxy != null) {
if (eventConnection != null) {
eventConnection.removeEventListener(managerEventListenerProxy);
}
managerEventListenerProxy.shutdown();
}
if (eventConnection != null && eventListener != null) {
eventConnection.removeEventListener(eventListener);
}
managerEventListenerProxy = null;
eventListener = null;
if (initialized) {//incredible, but it happened
handleDisconnectEvent(null);
}//i
}
#location 23
#vulnerability type THREAD_SAFETY_VIOLATION | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
private synchronized Map<String, String[]> parseParameters(String s)
{
Map<String, List<String>> parameterMap;
Map<String, String[]> result;
StringTokenizer st;
parameterMap = new HashMap<String, List<String>>();
result = new HashMap<String, String[]>();
if (s == null)
{
return result;
}
st = new StringTokenizer(s, "&");
while (st.hasMoreTokens())
{
String parameter;
Matcher parameterMatcher;
String name;
String value;
List<String> values;
parameter = st.nextToken();
parameterMatcher = PARAMETER_PATTERN.matcher(parameter);
if (parameterMatcher.matches())
{
try
{
name = URLDecoder.decode(parameterMatcher.group(1), "UTF-8");
value = URLDecoder.decode(parameterMatcher.group(2), "UTF-8");
}
catch (UnsupportedEncodingException e)
{
logger.error("Unable to decode parameter '" + parameter + "'", e);
continue;
}
}
else
{
try
{
name = URLDecoder.decode(parameter, "UTF-8");
value = "";
}
catch (UnsupportedEncodingException e)
{
logger.error("Unable to decode parameter '" + parameter + "'", e);
continue;
}
}
if (parameterMap.get(name) == null)
{
values = new ArrayList<String>();
values.add(value);
parameterMap.put(name, values);
}
else
{
values = parameterMap.get(name);
values.add(value);
}
}
for (Map.Entry<String, List<String>> entry : parameterMap.entrySet())
{
String[] valueArray;
valueArray = new String[entry.getValue().size()];
result.put(entry.getKey(), entry.getValue().toArray(valueArray));
}
return result;
} | #vulnerable code
private synchronized Map<String, String[]> parseParameters(String s)
{
Map<String, List<String>> parameterMap;
Map<String, String[]> result;
StringTokenizer st;
parameterMap = new HashMap<String, List<String>>();
result = new HashMap<String, String[]>();
if (s == null)
{
return result;
}
st = new StringTokenizer(s, "&");
while (st.hasMoreTokens())
{
String parameter;
Matcher parameterMatcher;
String name;
String value;
List<String> values;
parameter = st.nextToken();
parameterMatcher = PARAMETER_PATTERN.matcher(parameter);
if (parameterMatcher.matches())
{
try
{
name = URLDecoder.decode(parameterMatcher.group(1), "UTF-8");
value = URLDecoder.decode(parameterMatcher.group(2), "UTF-8");
}
catch (UnsupportedEncodingException e)
{
logger.error("Unable to decode parameter '" + parameter + "'", e);
continue;
}
}
else
{
try
{
name = URLDecoder.decode(parameter, "UTF-8");
value = "";
}
catch (UnsupportedEncodingException e)
{
logger.error("Unable to decode parameter '" + parameter + "'", e);
continue;
}
}
if (parameterMap.get(name) == null)
{
values = new ArrayList<String>();
values.add(value);
parameterMap.put(name, values);
}
else
{
values = parameterMap.get(name);
values.add(value);
}
}
for (String name : parameterMap.keySet())
{
List<String> values;
String[] valueArray;
values = parameterMap.get(name);
valueArray = new String[values.size()];
result.put(name, values.toArray(valueArray));
}
return result;
}
#location 72
#vulnerability type NULL_DEREFERENCE | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
public String getProtocolIdentifier()
{
return protocolIdentifier.getValue();
} | #vulnerable code
public String getProtocolIdentifier()
{
return protocolIdentifier.value;
}
#location 3
#vulnerability type THREAD_SAFETY_VIOLATION | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
ChannelManager(AsteriskServerImpl server)
{
this.server = server;
this.channels = new HashSet<AsteriskChannelImpl>();
} | #vulnerable code
void handleNewStateEvent(NewStateEvent event)
{
AsteriskChannelImpl channel = getChannelImplById(event.getUniqueId());
if (channel == null)
{
// NewStateEvent can occur for an existing channel that now has a different unique id (originate with Local/)
channel = getChannelImplByNameAndActive(event.getChannel());
if (channel != null)
{
logger.info("Changing unique id for '" + channel.getName() + "' from " + channel.getId() + " to " + event.getUniqueId());
channel.idChanged(event.getDateReceived(), event.getUniqueId());
}
if (channel == null)
{
logger.info("Creating new channel due to NewStateEvent '" + event.getChannel() + "' unique id " + event.getUniqueId());
// NewStateEvent can occur instead of a NewChannelEvent
channel = addNewChannel(
event.getUniqueId(), event.getChannel(), event.getDateReceived(),
event.getCallerIdNum(), event.getCallerIdName(),
ChannelState.valueOf(event.getChannelState()), null /* account code not available */);
}
}
// NewStateEvent can provide a new CallerIdNum or CallerIdName not previously received through a
// NewCallerIdEvent. This happens at least on outgoing legs from the queue application to agents.
if (event.getCallerIdNum() != null || event.getCallerIdName() != null)
{
String cidnum = "";
String cidname = "";
CallerId currentCallerId = channel.getCallerId();
if (currentCallerId != null)
{
cidnum = currentCallerId.getNumber();
cidname = currentCallerId.getName();
}
if (event.getCallerIdNum() != null)
{
cidnum = event.getCallerIdNum();
}
if (event.getCallerIdName() != null)
{
cidname = event.getCallerIdName();
}
CallerId newCallerId = new CallerId(cidname, cidnum);
logger.debug("Updating CallerId (following NewStateEvent) to: " + newCallerId.toString());
channel.setCallerId(newCallerId);
// Also, NewStateEvent can return a new channel name for the same channel uniqueid, indicating the channel has been
// renamed but no related RenameEvent has been received.
// This happens with mISDN channels (see AJ-153)
if (event.getChannel() != null && !event.getChannel().equals(channel.getName()))
{
logger.info("Renaming channel (following NewStateEvent) '" + channel.getName() + "' to '" + event.getChannel() + "'");
synchronized (channel)
{
channel.nameChanged(event.getDateReceived(), event.getChannel());
}
}
}
if (event.getChannelState() != null)
{
synchronized (channel)
{
channel.stateChanged(event.getDateReceived(), ChannelState.valueOf(event.getChannelState()));
}
}
}
#location 11
#vulnerability type THREAD_SAFETY_VIOLATION | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
ChannelManager(AsteriskServerImpl server)
{
this.server = server;
this.channels = new HashSet<AsteriskChannelImpl>();
} | #vulnerable code
void handleNewStateEvent(NewStateEvent event)
{
AsteriskChannelImpl channel = getChannelImplById(event.getUniqueId());
if (channel == null)
{
// NewStateEvent can occur for an existing channel that now has a different unique id (originate with Local/)
channel = getChannelImplByNameAndActive(event.getChannel());
if (channel != null)
{
logger.info("Changing unique id for '" + channel.getName() + "' from " + channel.getId() + " to " + event.getUniqueId());
channel.idChanged(event.getDateReceived(), event.getUniqueId());
}
if (channel == null)
{
logger.info("Creating new channel due to NewStateEvent '" + event.getChannel() + "' unique id " + event.getUniqueId());
// NewStateEvent can occur instead of a NewChannelEvent
channel = addNewChannel(
event.getUniqueId(), event.getChannel(), event.getDateReceived(),
event.getCallerIdNum(), event.getCallerIdName(),
ChannelState.valueOf(event.getChannelState()), null /* account code not available */);
}
}
// NewStateEvent can provide a new CallerIdNum or CallerIdName not previously received through a
// NewCallerIdEvent. This happens at least on outgoing legs from the queue application to agents.
if (event.getCallerIdNum() != null || event.getCallerIdName() != null)
{
String cidnum = "";
String cidname = "";
CallerId currentCallerId = channel.getCallerId();
if (currentCallerId != null)
{
cidnum = currentCallerId.getNumber();
cidname = currentCallerId.getName();
}
if (event.getCallerIdNum() != null)
{
cidnum = event.getCallerIdNum();
}
if (event.getCallerIdName() != null)
{
cidname = event.getCallerIdName();
}
CallerId newCallerId = new CallerId(cidname, cidnum);
logger.debug("Updating CallerId (following NewStateEvent) to: " + newCallerId.toString());
channel.setCallerId(newCallerId);
// Also, NewStateEvent can return a new channel name for the same channel uniqueid, indicating the channel has been
// renamed but no related RenameEvent has been received.
// This happens with mISDN channels (see AJ-153)
if (event.getChannel() != null && !event.getChannel().equals(channel.getName()))
{
logger.info("Renaming channel (following NewStateEvent) '" + channel.getName() + "' to '" + event.getChannel() + "'");
synchronized (channel)
{
channel.nameChanged(event.getDateReceived(), event.getChannel());
}
}
}
if (event.getChannelState() != null)
{
synchronized (channel)
{
channel.stateChanged(event.getDateReceived(), ChannelState.valueOf(event.getChannelState()));
}
}
}
#location 19
#vulnerability type THREAD_SAFETY_VIOLATION | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Override
public void onManagerEvent(final org.asteriskjava.manager.event.ManagerEvent event)
{
// logger.error(event);
boolean wanted = false;
/**
* Dump any events we arn't interested in ASAP to minimise the
* processing overhead of these events.
*/
// Only enqueue the events that are of interest to one of our listeners.
synchronized (this.globalEvents)
{
Class< ? extends ManagerEvent> shadowEvent = CoherentEventFactory.getShadowEvent(event);
if (this.globalEvents.contains(shadowEvent))
{
wanted = true;
}
}
if (wanted)
{
// We don't support all events.
this._eventQueue.add(new EventLifeMonitor<>(event));
if (_eventQueue.remainingCapacity() < QUEUE_SIZE / 10
&& suppressQueueSizeErrorUntil < System.currentTimeMillis())
{
suppressQueueSizeErrorUntil = System.currentTimeMillis() + 1000;
logger.error("EventQueue more than 90% full");
}
}
} | #vulnerable code
@Override
public void onManagerEvent(final org.asteriskjava.manager.event.ManagerEvent event)
{
// logger.error(event);
boolean wanted = false;
/**
* Dump any events we arn't interested in ASAP to minimise the
* processing overhead of these events.
*/
// Only enqueue the events that are of interest to one of our listeners.
synchronized (this.globalEvents)
{
Class< ? extends ManagerEvent> shadowEvent = CoherentEventFactory.getShadowEvent(event);
if (this.globalEvents.contains(shadowEvent))
{
wanted = true;
}
}
if (wanted)
{
// We don't support all events.
this._eventQueue.add(new EventLifeMonitor<>(event));
final int queueSize = this._eventQueue.size();
if (this._queueMaxSize < queueSize)
{
this._queueMaxSize = queueSize;
}
this._queueSum += queueSize;
this._queueCount++;
if (CoherentManagerEventQueue.logger.isDebugEnabled())
{
if (this._eventQueue.size() > ((this._queueMaxSize + (this._queueSum / this._queueCount)) / 2))
{
CoherentManagerEventQueue.logger.debug("queue gtr max avg: size=" + queueSize + " max:" //$NON-NLS-1$ //$NON-NLS-2$
+ this._queueMaxSize + " avg:" + (this._queueSum / this._queueCount)); //$NON-NLS-1$
}
}
}
}
#location 36
#vulnerability type THREAD_SAFETY_VIOLATION | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
ChannelManager(AsteriskServerImpl server)
{
this.server = server;
this.channels = new HashSet<AsteriskChannelImpl>();
} | #vulnerable code
void handleNewStateEvent(NewStateEvent event)
{
AsteriskChannelImpl channel = getChannelImplById(event.getUniqueId());
if (channel == null)
{
// NewStateEvent can occur for an existing channel that now has a different unique id (originate with Local/)
channel = getChannelImplByNameAndActive(event.getChannel());
if (channel != null)
{
logger.info("Changing unique id for '" + channel.getName() + "' from " + channel.getId() + " to " + event.getUniqueId());
channel.idChanged(event.getDateReceived(), event.getUniqueId());
}
if (channel == null)
{
logger.info("Creating new channel due to NewStateEvent '" + event.getChannel() + "' unique id " + event.getUniqueId());
// NewStateEvent can occur instead of a NewChannelEvent
channel = addNewChannel(
event.getUniqueId(), event.getChannel(), event.getDateReceived(),
event.getCallerIdNum(), event.getCallerIdName(),
ChannelState.valueOf(event.getChannelState()), null /* account code not available */);
}
}
// NewStateEvent can provide a new CallerIdNum or CallerIdName not previously received through a
// NewCallerIdEvent. This happens at least on outgoing legs from the queue application to agents.
if (event.getCallerIdNum() != null || event.getCallerIdName() != null)
{
String cidnum = "";
String cidname = "";
CallerId currentCallerId = channel.getCallerId();
if (currentCallerId != null)
{
cidnum = currentCallerId.getNumber();
cidname = currentCallerId.getName();
}
if (event.getCallerIdNum() != null)
{
cidnum = event.getCallerIdNum();
}
if (event.getCallerIdName() != null)
{
cidname = event.getCallerIdName();
}
CallerId newCallerId = new CallerId(cidname, cidnum);
logger.debug("Updating CallerId (following NewStateEvent) to: " + newCallerId.toString());
channel.setCallerId(newCallerId);
// Also, NewStateEvent can return a new channel name for the same channel uniqueid, indicating the channel has been
// renamed but no related RenameEvent has been received.
// This happens with mISDN channels (see AJ-153)
if (event.getChannel() != null && !event.getChannel().equals(channel.getName()))
{
logger.info("Renaming channel (following NewStateEvent) '" + channel.getName() + "' to '" + event.getChannel() + "'");
synchronized (channel)
{
channel.nameChanged(event.getDateReceived(), event.getChannel());
}
}
}
if (event.getChannelState() != null)
{
synchronized (channel)
{
channel.stateChanged(event.getDateReceived(), ChannelState.valueOf(event.getChannelState()));
}
}
}
#location 19
#vulnerability type THREAD_SAFETY_VIOLATION | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
public AsteriskChannel originateToExtension(String channel, String context, String exten, int priority, long timeout) throws ManagerCommunicationException, NoSuchChannelException
{
return originateToExtension(channel, context, exten, priority, timeout, null, null);
} | #vulnerable code
public AsteriskChannel originateToExtension(String channel, String context, String exten, int priority, long timeout) throws ManagerCommunicationException
{
return originateToExtension(channel, context, exten, priority, timeout, null, null);
}
#location 3
#vulnerability type NULL_DEREFERENCE | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
ChannelManager(AsteriskServerImpl server)
{
this.server = server;
} | #vulnerable code
void handleNewStateEvent(NewStateEvent event)
{
AsteriskChannelImpl channel = getChannelImplById(event.getUniqueId());
if (channel == null)
{
// NewStateEvent can occur for an existing channel that now has a different unique id (originate with Local/)
channel = getChannelImplByNameAndActive(event.getChannel());
idChanged(channel, event);
if (channel == null)
{
logger.info("Creating new channel due to NewStateEvent '" + event.getChannel() + "' unique id " + event.getUniqueId());
// NewStateEvent can occur instead of a NewChannelEvent
channel = addNewChannel(
event.getUniqueId(), event.getChannel(), event.getDateReceived(),
event.getCallerIdNum(), event.getCallerIdName(),
ChannelState.valueOf(event.getChannelState()), null /* account code not available */);
}
}
// NewStateEvent can provide a new CallerIdNum or CallerIdName not previously received through a
// NewCallerIdEvent. This happens at least on outgoing legs from the queue application to agents.
if (event.getCallerIdNum() != null || event.getCallerIdName() != null)
{
String cidnum = "";
String cidname = "";
CallerId currentCallerId = channel.getCallerId();
if (currentCallerId != null)
{
cidnum = currentCallerId.getNumber();
cidname = currentCallerId.getName();
}
if (event.getCallerIdNum() != null)
{
cidnum = event.getCallerIdNum();
}
if (event.getCallerIdName() != null)
{
cidname = event.getCallerIdName();
}
CallerId newCallerId = new CallerId(cidname, cidnum);
logger.debug("Updating CallerId (following NewStateEvent) to: " + newCallerId.toString());
channel.setCallerId(newCallerId);
// Also, NewStateEvent can return a new channel name for the same channel uniqueid, indicating the channel has been
// renamed but no related RenameEvent has been received.
// This happens with mISDN channels (see AJ-153)
if (event.getChannel() != null && !event.getChannel().equals(channel.getName()))
{
logger.info("Renaming channel (following NewStateEvent) '" + channel.getName() + "' to '" + event.getChannel() + "'");
synchronized (channel)
{
channel.nameChanged(event.getDateReceived(), event.getChannel());
}
}
}
if (event.getChannelState() != null)
{
synchronized (channel)
{
channel.stateChanged(event.getDateReceived(), ChannelState.valueOf(event.getChannelState()));
}
}
}
#location 9
#vulnerability type THREAD_SAFETY_VIOLATION | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
OriginateResult originate(final EndPoint local, final EndPoint target, final HashMap<String, String> myVars,
final CallerID callerID, final Integer timeout, final boolean hideCallerId, final String context)
{
OriginateBaseClass.logger.debug("originate called");
this.originateSeen = false;
this.channelSeen = false;
if (this.hungup)
{
// the monitored channel already hungup so just return false and
// shutdown
return null;
}
OriginateBaseClass.logger.debug("originate connection endPoint \n" + local + " to endPoint " + target //$NON-NLS-2$
+ " vars " + myVars);
ManagerResponse response = null;
final AsteriskSettings settings = PBXFactory.getActiveProfile();
final OriginateAction originate = new OriginateAction();
this.originateID = originate.getActionId();
channelId = "" + (System.currentTimeMillis() / 1000) + ".AJ" + originateSeed.incrementAndGet();
originate.setChannelId(channelId);
Integer localTimeout = timeout;
if (timeout == null)
{
localTimeout = 30000;
try
{
localTimeout = settings.getDialTimeout() * 1000;
}
catch (final Exception e)
{
OriginateBaseClass.logger.error("Invalid dial timeout value");
}
}
// Whilst the originate document says that it takes a channel it
// actually takes an
// end point. I haven't check but I'm skeptical that you can actually
// originate to
// a channel as the doco talks about 'dialing the channel'. I suspect
// this
// may be part of asterisk's sloppy terminology.
if (local.isLocal())
{
originate.setEndPoint(local);
originate.setOption("/n");
}
else
{
originate.setEndPoint(local);
}
originate.setContext(context);
originate.setExten(target);
originate.setPriority(1);
// Set the caller id.
if (hideCallerId)
{
// hide callerID
originate.setCallingPres(32);
}
else
{
originate.setCallerId(callerID);
}
originate.setVariables(myVars);
originate.setAsync(true);
originate.setTimeout(localTimeout);
try
{
// Just add us as an asterisk event listener.
this.startListener();
response = pbx.sendAction(originate, localTimeout);
OriginateBaseClass.logger.debug("Originate.sendAction completed");
if (response.getResponse().compareToIgnoreCase("Success") != 0)
{
OriginateBaseClass.logger
.error("Error Originating call" + originate.toString() + " : " + response.getMessage());//$NON-NLS-2$
throw new ManagerCommunicationException(response.getMessage(), null);
}
// wait the set timeout +1 second to allow for
// asterisk to start the originate
originateLatch.await(localTimeout + 1000, TimeUnit.MILLISECONDS);
}
catch (final InterruptedException e)
{
OriginateBaseClass.logger.debug(e, e);
}
catch (final Exception e)
{
OriginateBaseClass.logger.error(e, e);
}
finally
{
this.close();
}
if (this.originateSuccess)
{
this.result.setSuccess(true);
this.result.setChannelData(this.newChannel);
OriginateBaseClass.logger.debug("new channel ok: " + this.newChannel);
}
else
{
OriginateBaseClass.logger.warn("originate failed to connect endPoint: " + local + " to ext " + target); //$NON-NLS-2$
if (this.newChannel != null)
{
try
{
logger.info("Hanging up");
pbx.hangup(this.newChannel);
}
catch (IllegalArgumentException | IllegalStateException | PBXException e)
{
logger.error(e, e);
}
}
}
return this.result;
} | #vulnerable code
OriginateResult originate(final EndPoint local, final EndPoint target, final HashMap<String, String> myVars,
final CallerID callerID, final Integer timeout, final boolean hideCallerId, final String context)
{
OriginateBaseClass.logger.debug("originate called");
this.originateSeen = false;
this.channelSeen = false;
if (this.hungup == true)
{
// the monitored channel already hungup so just return false and
// shutdown
return null;
}
OriginateBaseClass.logger.debug("originate connection endPoint \n" + local + " to endPoint " + target //$NON-NLS-2$
+ " vars " + myVars);
ManagerResponse response = null;
final AsteriskSettings settings = PBXFactory.getActiveProfile();
final OriginateAction originate = new OriginateAction();
this.originateID = originate.getActionId();
channelId = "" + (System.currentTimeMillis() / 1000) + ".AJ" + originateSeed.incrementAndGet();
originate.setChannelId(channelId);
Integer localTimeout = timeout;
if (timeout == null)
{
localTimeout = 30000;
try
{
localTimeout = settings.getDialTimeout() * 1000;
}
catch (final Exception e)
{
OriginateBaseClass.logger.error("Invalid dial timeout value");
}
}
// Whilst the originate document says that it takes a channel it
// actually takes an
// end point. I haven't check but I'm skeptical that you can actually
// originate to
// a channel as the doco talks about 'dialing the channel'. I suspect
// this
// may be part of asterisk's sloppy terminology.
if (local.isLocal())
{
originate.setEndPoint(local);
originate.setOption("/n");
}
else
{
originate.setEndPoint(local);
}
originate.setContext(context);
originate.setExten(target);
originate.setPriority(1);
// Set the caller id.
if (hideCallerId)
{
// hide callerID
originate.setCallingPres(32);
}
else
{
originate.setCallerId(callerID);
}
originate.setVariables(myVars);
originate.setAsync(true);
originate.setTimeout(localTimeout);
try
{
// Just add us as an asterisk event listener.
this.startListener();
response = pbx.sendAction(originate, localTimeout);
OriginateBaseClass.logger.debug("Originate.sendAction completed");
if (response.getResponse().compareToIgnoreCase("Success") != 0)
{
OriginateBaseClass.logger
.error("Error Originating call" + originate.toString() + " : " + response.getMessage());//$NON-NLS-2$
throw new ManagerCommunicationException(response.getMessage(), null);
}
// wait the set timeout +1 second to allow for
// asterisk to start the originate
originateLatch.await(localTimeout + 1000, TimeUnit.MILLISECONDS);
}
catch (final InterruptedException e)
{
OriginateBaseClass.logger.debug(e, e);
}
catch (final Exception e)
{
OriginateBaseClass.logger.error(e, e);
}
finally
{
this.close();
}
if (this.originateSuccess == true)
{
this.result.setSuccess(true);
this.result.setChannelData(this.newChannel);
OriginateBaseClass.logger.debug("new channel ok: " + this.newChannel);
}
else
{
OriginateBaseClass.logger.warn("originate failed to connect endPoint: " + local + " to ext " + target); //$NON-NLS-2$
if (this.newChannel != null)
{
try
{
logger.info("Hanging up");
pbx.hangup(this.newChannel);
}
catch (IllegalArgumentException | IllegalStateException | PBXException e)
{
logger.error(e, e);
}
}
}
return this.result;
}
#location 6
#vulnerability type THREAD_SAFETY_VIOLATION | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
ChannelManager(AsteriskServerImpl server)
{
this.server = server;
} | #vulnerable code
void handleNewCallerIdEvent(NewCallerIdEvent event)
{
AsteriskChannelImpl channel = getChannelImplById(event.getUniqueId());
if (channel == null)
{
// NewCallerIdEvent can occur for an existing channel that now has a different unique id (originate with Local/)
channel = getChannelImplByNameAndActive(event.getChannel());
idChanged(channel, event);
if (channel == null)
{
// NewCallerIdEvent can occur before NewChannelEvent
channel = addNewChannel(
event.getUniqueId(), event.getChannel(), event.getDateReceived(),
event.getCallerIdNum(), event.getCallerIdName(),
ChannelState.DOWN, null /* account code not available */);
}
}
synchronized (channel)
{
channel.setCallerId(new CallerId(event.getCallerIdName(), event.getCallerIdNum()));
}
}
#location 9
#vulnerability type THREAD_SAFETY_VIOLATION | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
OriginateResult originate(final EndPoint local, final EndPoint target, final HashMap<String, String> myVars,
final CallerID callerID, final Integer timeout, final boolean hideCallerId, final String context)
{
OriginateBaseClass.logger.info("originate called");
this.originateSeen = false;
this.channelSeen = false;
if (this.hungup)
{
// the monitored channel already hungup so just return false and
// shutdown
return null;
}
OriginateBaseClass.logger.info("originate connection endPoint \n" + local + " to endPoint " + target //$NON-NLS-2$
+ " vars " + myVars);
ManagerResponse response = null;
final AsteriskSettings settings = PBXFactory.getActiveProfile();
final OriginateAction originate = new OriginateAction();
this.originateID = originate.getActionId();
channelId = "" + (System.currentTimeMillis() / 1000) + ".AJ" + originateSeed.incrementAndGet();
originate.setChannelId(channelId);
Integer localTimeout = timeout;
if (timeout == null)
{
localTimeout = 30000;
try
{
localTimeout = settings.getDialTimeout() * 1000;
}
catch (final Exception e)
{
OriginateBaseClass.logger.error("Invalid dial timeout value");
}
}
// Whilst the originate document says that it takes a channel it
// actually takes an
// end point. I haven't check but I'm skeptical that you can actually
// originate to
// a channel as the doco talks about 'dialing the channel'. I suspect
// this
// may be part of asterisk's sloppy terminology.
if (local.isLocal())
{
originate.setEndPoint(local);
originate.setOption("/n");
}
else
{
originate.setEndPoint(local);
}
originate.setContext(context);
originate.setExten(target);
originate.setPriority(1);
// Set the caller id.
if (hideCallerId)
{
// hide callerID
originate.setCallingPres(32);
}
else
{
originate.setCallerId(callerID);
}
originate.setVariables(myVars);
originate.setAsync(true);
originate.setTimeout(localTimeout);
try
{
// Just add us as an asterisk event listener.
this.startListener();
response = pbx.sendAction(originate, localTimeout);
OriginateBaseClass.logger.info("Originate.sendAction completed");
if (response.getResponse().compareToIgnoreCase("Success") != 0)
{
OriginateBaseClass.logger
.error("Error Originating call" + originate.toString() + " : " + response.getMessage());//$NON-NLS-2$
throw new ManagerCommunicationException(response.getMessage(), null);
}
// wait the set timeout +1 second to allow for
// asterisk to start the originate
if (!originateLatch.await(localTimeout + 1000, TimeUnit.MILLISECONDS))
{
logger.error("Originate Latch timed out");
}
}
catch (final InterruptedException e)
{
OriginateBaseClass.logger.debug(e, e);
}
catch (final Exception e)
{
OriginateBaseClass.logger.error(e, e);
}
finally
{
this.close();
}
if (this.originateSuccess)
{
this.result.setSuccess(true);
this.result.setChannelData(this.newChannel);
OriginateBaseClass.logger.info("new channel ok: " + this.newChannel);
}
else
{
OriginateBaseClass.logger.warn("originate failed to connect endPoint: " + local + " to ext " + target); //$NON-NLS-2$
if (this.newChannel != null)
{
try
{
logger.warn("Hanging up");
pbx.hangup(this.newChannel);
}
catch (IllegalArgumentException | IllegalStateException | PBXException e)
{
logger.error(e, e);
}
}
}
return this.result;
} | #vulnerable code
OriginateResult originate(final EndPoint local, final EndPoint target, final HashMap<String, String> myVars,
final CallerID callerID, final Integer timeout, final boolean hideCallerId, final String context)
{
OriginateBaseClass.logger.warn("originate called");
this.originateSeen = false;
this.channelSeen = false;
if (this.hungup)
{
// the monitored channel already hungup so just return false and
// shutdown
return null;
}
OriginateBaseClass.logger.warn("originate connection endPoint \n" + local + " to endPoint " + target //$NON-NLS-2$
+ " vars " + myVars);
ManagerResponse response = null;
final AsteriskSettings settings = PBXFactory.getActiveProfile();
final OriginateAction originate = new OriginateAction();
this.originateID = originate.getActionId();
channelId = "" + (System.currentTimeMillis() / 1000) + ".AJ" + originateSeed.incrementAndGet();
originate.setChannelId(channelId);
Integer localTimeout = timeout;
if (timeout == null)
{
localTimeout = 30000;
try
{
localTimeout = settings.getDialTimeout() * 1000;
}
catch (final Exception e)
{
OriginateBaseClass.logger.error("Invalid dial timeout value");
}
}
// Whilst the originate document says that it takes a channel it
// actually takes an
// end point. I haven't check but I'm skeptical that you can actually
// originate to
// a channel as the doco talks about 'dialing the channel'. I suspect
// this
// may be part of asterisk's sloppy terminology.
if (local.isLocal())
{
originate.setEndPoint(local);
originate.setOption("/n");
}
else
{
originate.setEndPoint(local);
}
originate.setContext(context);
originate.setExten(target);
originate.setPriority(1);
// Set the caller id.
if (hideCallerId)
{
// hide callerID
originate.setCallingPres(32);
}
else
{
originate.setCallerId(callerID);
}
originate.setVariables(myVars);
originate.setAsync(true);
originate.setTimeout(localTimeout);
try
{
// Just add us as an asterisk event listener.
this.startListener();
response = pbx.sendAction(originate, localTimeout);
OriginateBaseClass.logger.warn("Originate.sendAction completed");
if (response.getResponse().compareToIgnoreCase("Success") != 0)
{
OriginateBaseClass.logger
.error("Error Originating call" + originate.toString() + " : " + response.getMessage());//$NON-NLS-2$
throw new ManagerCommunicationException(response.getMessage(), null);
}
// wait the set timeout +1 second to allow for
// asterisk to start the originate
if (!originateLatch.await(localTimeout + 1000, TimeUnit.MILLISECONDS))
{
logger.error("Originate Latch timed out");
}
}
catch (final InterruptedException e)
{
OriginateBaseClass.logger.debug(e, e);
}
catch (final Exception e)
{
OriginateBaseClass.logger.error(e, e);
}
finally
{
this.close();
}
if (this.originateSuccess)
{
this.result.setSuccess(true);
this.result.setChannelData(this.newChannel);
OriginateBaseClass.logger.warn("new channel ok: " + this.newChannel);
}
else
{
OriginateBaseClass.logger.warn("originate failed to connect endPoint: " + local + " to ext " + target); //$NON-NLS-2$
if (this.newChannel != null)
{
try
{
logger.warn("Hanging up");
pbx.hangup(this.newChannel);
}
catch (IllegalArgumentException | IllegalStateException | PBXException e)
{
logger.error(e, e);
}
}
}
logger.warn("Manager Events seen " + managerEventsSeen.get());
return this.result;
}
#location 5
#vulnerability type THREAD_SAFETY_VIOLATION | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
public boolean getPaused()
{
return isPaused();
} | #vulnerable code
public boolean getPaused()
{
return paused;
}
#location 3
#vulnerability type THREAD_SAFETY_VIOLATION | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
public AsteriskChannel getDialedChannel()
{
synchronized(dialedChannels) {
for (AsteriskChannel channel:dialedChannels) {
if (channel != null) return channel;
}
}
return null;
} | #vulnerable code
public AsteriskChannel getDialedChannel()
{
return dialedChannel;
}
#location 3
#vulnerability type THREAD_SAFETY_VIOLATION | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
protected AsteriskVersion determineVersion() throws IOException, TimeoutException
{
int attempts = 0;
logger.info("Got asterisk protocol identifier version " + protocolIdentifier.getValue());
while (attempts++ < MAX_VERSION_ATTEMPTS)
{
try {
AsteriskVersion version = determineVersionByCoreSettings();
if (version != null) return version;
} catch (Exception e) {
}
try {
AsteriskVersion version = determineVersionByCoreShowVersion();
if (version != null) return version;
} catch (Exception e) {
}
try
{
Thread.sleep(RECONNECTION_VERSION_INTERVAL);
}
catch (Exception ex)
{
// ignore
} // NOPMD
}
logger.error("Unable to determine asterisk version, assuming " + DEFAULT_ASTERISK_VERSION + "... you should expect problems to follow.");
return DEFAULT_ASTERISK_VERSION;
} | #vulnerable code
protected AsteriskVersion determineVersion() throws IOException, TimeoutException
{
int attempts = 0;
// if ("Asterisk Call Manager/1.1".equals(protocolIdentifier.value))
// {
// return AsteriskVersion.ASTERISK_1_6;
// }
while (attempts++ < MAX_VERSION_ATTEMPTS)
{
final ManagerResponse showVersionFilesResponse;
final List<String> showVersionFilesResult;
boolean Asterisk14outputPresent = false;
// increase timeout as output is quite large
showVersionFilesResponse = sendAction(new CommandAction("show version files pbx.c"), defaultResponseTimeout * 2);
if (!(showVersionFilesResponse instanceof CommandResponse))
{
// return early in case of permission problems
// org.asteriskjava.manager.response.ManagerError:
// actionId='null'; message='Permission denied';
// response='Error';
// uniqueId='null'; systemHashcode=15231583
if (showVersionFilesResponse.getOutput() != null)
{
Asterisk14outputPresent = true;
}
else
{
break;
}
}
if (Asterisk14outputPresent)
{
List<String> outputList = Arrays
.asList(showVersionFilesResponse.getOutput().split(SocketConnectionFacadeImpl.NL_PATTERN.pattern()));
showVersionFilesResult = outputList;
}
else
{
showVersionFilesResult = ((CommandResponse) showVersionFilesResponse).getResult();
}
if (showVersionFilesResult != null && !showVersionFilesResult.isEmpty())
{
final String line1 = showVersionFilesResult.get(0);
if (line1 != null && line1.startsWith("File"))
{
final String rawVersion;
rawVersion = getRawVersion();
if (rawVersion != null && rawVersion.startsWith("Asterisk 1.4"))
{
return AsteriskVersion.ASTERISK_1_4;
}
return AsteriskVersion.ASTERISK_1_2;
}
else if (line1 != null && line1.contains("No such command"))
{
final ManagerResponse coreShowVersionResponse = sendAction(new CommandAction("core show version"),
defaultResponseTimeout * 2);
if (coreShowVersionResponse != null && coreShowVersionResponse instanceof CommandResponse)
{
final List<String> coreShowVersionResult = ((CommandResponse) coreShowVersionResponse).getResult();
if (coreShowVersionResult != null && !coreShowVersionResult.isEmpty())
{
final String coreLine = coreShowVersionResult.get(0);
if (VERSION_PATTERN_1_6.matcher(coreLine).matches())
{
return AsteriskVersion.ASTERISK_1_6;
}
else if (VERSION_PATTERN_1_8.matcher(coreLine).matches())
{
return AsteriskVersion.ASTERISK_1_8;
}
else if (VERSION_PATTERN_10.matcher(coreLine).matches())
{
return AsteriskVersion.ASTERISK_10;
}
else if (VERSION_PATTERN_11.matcher(coreLine).matches())
{
return AsteriskVersion.ASTERISK_11;
}
else if (VERSION_PATTERN_CERTIFIED_11.matcher(coreLine).matches())
{
return AsteriskVersion.ASTERISK_11;
}
else if (VERSION_PATTERN_12.matcher(coreLine).matches())
{
return AsteriskVersion.ASTERISK_12;
}
else if (VERSION_PATTERN_13.matcher(coreLine).matches())
{
return AsteriskVersion.ASTERISK_13;
}
else if (VERSION_PATTERN_CERTIFIED_13.matcher(coreLine).matches())
{
return AsteriskVersion.ASTERISK_13;
}
else if (VERSION_PATTERN_14.matcher(coreLine).matches())
{
return AsteriskVersion.ASTERISK_14;
}
else if (VERSION_PATTERN_15.matcher(coreLine).matches())
{
return AsteriskVersion.ASTERISK_15;
}
}
}
try
{
Thread.sleep(RECONNECTION_VERSION_INTERVAL);
}
catch (Exception ex)
{
// ingnore
} // NOPMD
}
else
{
// if it isn't the "no such command", break and return the
// lowest version immediately
break;
}
}
}
// TODO: add retry logic; in a reconnect scenario the version fails to
// be identified leading to errors
// as a fallback assume 1.6
logger.error("Unable to determine asterisk version, assuming 1.6... you should expect problems to follow.");
return AsteriskVersion.ASTERISK_1_6;
}
#location 51
#vulnerability type THREAD_SAFETY_VIOLATION | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
OriginateResult originate(final EndPoint local, final EndPoint target, final HashMap<String, String> myVars,
final CallerID callerID, final Integer timeout, final boolean hideCallerId, final String context)
{
OriginateBaseClass.logger.info("originate called");
this.originateSeen = false;
this.channelSeen = false;
if (this.hungup)
{
// the monitored channel already hungup so just return false and
// shutdown
return null;
}
OriginateBaseClass.logger.info("originate connection endPoint \n" + local + " to endPoint " + target //$NON-NLS-2$
+ " vars " + myVars);
ManagerResponse response = null;
final AsteriskSettings settings = PBXFactory.getActiveProfile();
final OriginateAction originate = new OriginateAction();
this.originateID = originate.getActionId();
channelId = "" + (System.currentTimeMillis() / 1000) + ".AJ" + originateSeed.incrementAndGet();
originate.setChannelId(channelId);
Integer localTimeout = timeout;
if (timeout == null)
{
localTimeout = 30000;
try
{
localTimeout = settings.getDialTimeout() * 1000;
}
catch (final Exception e)
{
OriginateBaseClass.logger.error("Invalid dial timeout value");
}
}
// Whilst the originate document says that it takes a channel it
// actually takes an
// end point. I haven't check but I'm skeptical that you can actually
// originate to
// a channel as the doco talks about 'dialing the channel'. I suspect
// this
// may be part of asterisk's sloppy terminology.
if (local.isLocal())
{
originate.setEndPoint(local);
originate.setOption("/n");
}
else
{
originate.setEndPoint(local);
}
originate.setContext(context);
originate.setExten(target);
originate.setPriority(1);
// Set the caller id.
if (hideCallerId)
{
// hide callerID
originate.setCallingPres(32);
}
else
{
originate.setCallerId(callerID);
}
originate.setVariables(myVars);
originate.setAsync(true);
originate.setTimeout(localTimeout);
try
{
// Just add us as an asterisk event listener.
this.startListener();
response = pbx.sendAction(originate, localTimeout);
OriginateBaseClass.logger.info("Originate.sendAction completed");
if (response.getResponse().compareToIgnoreCase("Success") != 0)
{
OriginateBaseClass.logger
.error("Error Originating call" + originate.toString() + " : " + response.getMessage());//$NON-NLS-2$
throw new ManagerCommunicationException(response.getMessage(), null);
}
// wait the set timeout +1 second to allow for
// asterisk to start the originate
if (!originateLatch.await(localTimeout + 1000, TimeUnit.MILLISECONDS))
{
logger.error("Originate Latch timed out");
}
}
catch (final InterruptedException e)
{
OriginateBaseClass.logger.debug(e, e);
}
catch (final Exception e)
{
OriginateBaseClass.logger.error(e, e);
}
finally
{
this.close();
}
if (this.originateSuccess)
{
this.result.setSuccess(true);
this.result.setChannelData(this.newChannel);
OriginateBaseClass.logger.info("new channel ok: " + this.newChannel);
}
else
{
OriginateBaseClass.logger.warn("originate failed to connect endPoint: " + local + " to ext " + target); //$NON-NLS-2$
if (this.newChannel != null)
{
try
{
logger.warn("Hanging up");
pbx.hangup(this.newChannel);
}
catch (IllegalArgumentException | IllegalStateException | PBXException e)
{
logger.error(e, e);
}
}
}
return this.result;
} | #vulnerable code
OriginateResult originate(final EndPoint local, final EndPoint target, final HashMap<String, String> myVars,
final CallerID callerID, final Integer timeout, final boolean hideCallerId, final String context)
{
OriginateBaseClass.logger.warn("originate called");
this.originateSeen = false;
this.channelSeen = false;
if (this.hungup)
{
// the monitored channel already hungup so just return false and
// shutdown
return null;
}
OriginateBaseClass.logger.warn("originate connection endPoint \n" + local + " to endPoint " + target //$NON-NLS-2$
+ " vars " + myVars);
ManagerResponse response = null;
final AsteriskSettings settings = PBXFactory.getActiveProfile();
final OriginateAction originate = new OriginateAction();
this.originateID = originate.getActionId();
channelId = "" + (System.currentTimeMillis() / 1000) + ".AJ" + originateSeed.incrementAndGet();
originate.setChannelId(channelId);
Integer localTimeout = timeout;
if (timeout == null)
{
localTimeout = 30000;
try
{
localTimeout = settings.getDialTimeout() * 1000;
}
catch (final Exception e)
{
OriginateBaseClass.logger.error("Invalid dial timeout value");
}
}
// Whilst the originate document says that it takes a channel it
// actually takes an
// end point. I haven't check but I'm skeptical that you can actually
// originate to
// a channel as the doco talks about 'dialing the channel'. I suspect
// this
// may be part of asterisk's sloppy terminology.
if (local.isLocal())
{
originate.setEndPoint(local);
originate.setOption("/n");
}
else
{
originate.setEndPoint(local);
}
originate.setContext(context);
originate.setExten(target);
originate.setPriority(1);
// Set the caller id.
if (hideCallerId)
{
// hide callerID
originate.setCallingPres(32);
}
else
{
originate.setCallerId(callerID);
}
originate.setVariables(myVars);
originate.setAsync(true);
originate.setTimeout(localTimeout);
try
{
// Just add us as an asterisk event listener.
this.startListener();
response = pbx.sendAction(originate, localTimeout);
OriginateBaseClass.logger.warn("Originate.sendAction completed");
if (response.getResponse().compareToIgnoreCase("Success") != 0)
{
OriginateBaseClass.logger
.error("Error Originating call" + originate.toString() + " : " + response.getMessage());//$NON-NLS-2$
throw new ManagerCommunicationException(response.getMessage(), null);
}
// wait the set timeout +1 second to allow for
// asterisk to start the originate
if (!originateLatch.await(localTimeout + 1000, TimeUnit.MILLISECONDS))
{
logger.error("Originate Latch timed out");
}
}
catch (final InterruptedException e)
{
OriginateBaseClass.logger.debug(e, e);
}
catch (final Exception e)
{
OriginateBaseClass.logger.error(e, e);
}
finally
{
this.close();
}
if (this.originateSuccess)
{
this.result.setSuccess(true);
this.result.setChannelData(this.newChannel);
OriginateBaseClass.logger.warn("new channel ok: " + this.newChannel);
}
else
{
OriginateBaseClass.logger.warn("originate failed to connect endPoint: " + local + " to ext " + target); //$NON-NLS-2$
if (this.newChannel != null)
{
try
{
logger.warn("Hanging up");
pbx.hangup(this.newChannel);
}
catch (IllegalArgumentException | IllegalStateException | PBXException e)
{
logger.error(e, e);
}
}
}
logger.warn("Manager Events seen " + managerEventsSeen.get());
return this.result;
}
#location 6
#vulnerability type THREAD_SAFETY_VIOLATION | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
ChannelManager(AsteriskServerImpl server)
{
this.server = server;
this.channels = new HashSet<AsteriskChannelImpl>();
} | #vulnerable code
void handleNewCallerIdEvent(NewCallerIdEvent event)
{
AsteriskChannelImpl channel = getChannelImplById(event.getUniqueId());
if (channel == null)
{
// NewCallerIdEvent can occur for an existing channel that now has a different unique id (originate with Local/)
channel = getChannelImplByNameAndActive(event.getChannel());
if (channel != null)
{
logger.info("Changing unique id for '" + channel.getName() + "' from " + channel.getId() + " to " + event.getUniqueId());
channel.idChanged(event.getDateReceived(), event.getUniqueId());
}
if (channel == null)
{
// NewCallerIdEvent can occur before NewChannelEvent
channel = addNewChannel(
event.getUniqueId(), event.getChannel(), event.getDateReceived(),
event.getCallerIdNum(), event.getCallerIdName(),
ChannelState.DOWN, null /* account code not available */);
}
}
synchronized (channel)
{
channel.setCallerId(new CallerId(event.getCallerIdName(), event.getCallerIdNum()));
}
}
#location 18
#vulnerability type THREAD_SAFETY_VIOLATION | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Override
public String toString()
{
final StringBuffer sb;
sb = new StringBuffer("AsteriskAgent[");
sb.append("agentId='").append(getAgentId()).append("',");
sb.append("name='").append(getName()).append("',");
sb.append("state=").append(getState()).append(",");
sb.append("systemHashcode=").append(System.identityHashCode(this));
sb.append("]");
return sb.toString();
} | #vulnerable code
@Override
public String toString()
{
final StringBuffer sb;
sb = new StringBuffer("AsteriskAgent[");
sb.append("agentId='").append(getAgentId()).append("',");
sb.append("name='").append(getName()).append("',");
sb.append("state=").append(getStatus()).append(",");
sb.append("systemHashcode=").append(System.identityHashCode(this));
sb.append("]");
return sb.toString();
}
#location 9
#vulnerability type THREAD_SAFETY_VIOLATION | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
public AsteriskChannel getDialingChannel()
{
synchronized(dialingChannels) {
if (dialingChannels.isEmpty()) return null;
return dialingChannels.get(0);
}
} | #vulnerable code
public AsteriskChannel getDialingChannel()
{
return dialingChannel;
}
#location 3
#vulnerability type THREAD_SAFETY_VIOLATION | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Override
public void onManagerEvent(final org.asteriskjava.manager.event.ManagerEvent event)
{
// logger.error(event);
boolean wanted = false;
/**
* Dump any events we arn't interested in ASAP to minimise the
* processing overhead of these events.
*/
// Only enqueue the events that are of interest to one of our listeners.
synchronized (this.globalEvents)
{
Class< ? extends ManagerEvent> shadowEvent = CoherentEventFactory.getShadowEvent(event);
if (this.globalEvents.contains(shadowEvent))
{
wanted = true;
}
}
if (wanted)
{
// We don't support all events.
this._eventQueue.add(new EventLifeMonitor<>(event));
if (_eventQueue.remainingCapacity() < QUEUE_SIZE / 10
&& suppressQueueSizeErrorUntil < System.currentTimeMillis())
{
suppressQueueSizeErrorUntil = System.currentTimeMillis() + 1000;
logger.error("EventQueue more than 90% full");
}
}
} | #vulnerable code
@Override
public void onManagerEvent(final org.asteriskjava.manager.event.ManagerEvent event)
{
// logger.error(event);
boolean wanted = false;
/**
* Dump any events we arn't interested in ASAP to minimise the
* processing overhead of these events.
*/
// Only enqueue the events that are of interest to one of our listeners.
synchronized (this.globalEvents)
{
Class< ? extends ManagerEvent> shadowEvent = CoherentEventFactory.getShadowEvent(event);
if (this.globalEvents.contains(shadowEvent))
{
wanted = true;
}
}
if (wanted)
{
// We don't support all events.
this._eventQueue.add(new EventLifeMonitor<>(event));
final int queueSize = this._eventQueue.size();
if (this._queueMaxSize < queueSize)
{
this._queueMaxSize = queueSize;
}
this._queueSum += queueSize;
this._queueCount++;
if (CoherentManagerEventQueue.logger.isDebugEnabled())
{
if (this._eventQueue.size() > ((this._queueMaxSize + (this._queueSum / this._queueCount)) / 2))
{
CoherentManagerEventQueue.logger.debug("queue gtr max avg: size=" + queueSize + " max:" //$NON-NLS-1$ //$NON-NLS-2$
+ this._queueMaxSize + " avg:" + (this._queueSum / this._queueCount)); //$NON-NLS-1$
}
}
}
}
#location 38
#vulnerability type THREAD_SAFETY_VIOLATION | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
ChannelManager(AsteriskServerImpl server)
{
this.server = server;
this.channels = new HashSet<AsteriskChannelImpl>();
} | #vulnerable code
void handleNewCallerIdEvent(NewCallerIdEvent event)
{
AsteriskChannelImpl channel = getChannelImplById(event.getUniqueId());
if (channel == null)
{
// NewCallerIdEvent can occur for an existing channel that now has a different unique id (originate with Local/)
channel = getChannelImplByNameAndActive(event.getChannel());
if (channel != null)
{
logger.info("Changing unique id for '" + channel.getName() + "' from " + channel.getId() + " to " + event.getUniqueId());
channel.idChanged(event.getDateReceived(), event.getUniqueId());
}
if (channel == null)
{
// NewCallerIdEvent can occur before NewChannelEvent
channel = addNewChannel(
event.getUniqueId(), event.getChannel(), event.getDateReceived(),
event.getCallerIdNum(), event.getCallerIdName(),
ChannelState.DOWN, null /* account code not available */);
}
}
synchronized (channel)
{
channel.setCallerId(new CallerId(event.getCallerIdName(), event.getCallerIdNum()));
}
}
#location 11
#vulnerability type THREAD_SAFETY_VIOLATION | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
ChannelManager(AsteriskServerImpl server)
{
this.server = server;
} | #vulnerable code
void handleNewStateEvent(NewStateEvent event)
{
AsteriskChannelImpl channel = getChannelImplById(event.getUniqueId());
if (channel == null)
{
// NewStateEvent can occur for an existing channel that now has a different unique id (originate with Local/)
channel = getChannelImplByNameAndActive(event.getChannel());
idChanged(channel, event);
if (channel == null)
{
logger.info("Creating new channel due to NewStateEvent '" + event.getChannel() + "' unique id " + event.getUniqueId());
// NewStateEvent can occur instead of a NewChannelEvent
channel = addNewChannel(
event.getUniqueId(), event.getChannel(), event.getDateReceived(),
event.getCallerIdNum(), event.getCallerIdName(),
ChannelState.valueOf(event.getChannelState()), null /* account code not available */);
}
}
// NewStateEvent can provide a new CallerIdNum or CallerIdName not previously received through a
// NewCallerIdEvent. This happens at least on outgoing legs from the queue application to agents.
if (event.getCallerIdNum() != null || event.getCallerIdName() != null)
{
String cidnum = "";
String cidname = "";
CallerId currentCallerId = channel.getCallerId();
if (currentCallerId != null)
{
cidnum = currentCallerId.getNumber();
cidname = currentCallerId.getName();
}
if (event.getCallerIdNum() != null)
{
cidnum = event.getCallerIdNum();
}
if (event.getCallerIdName() != null)
{
cidname = event.getCallerIdName();
}
CallerId newCallerId = new CallerId(cidname, cidnum);
logger.debug("Updating CallerId (following NewStateEvent) to: " + newCallerId.toString());
channel.setCallerId(newCallerId);
// Also, NewStateEvent can return a new channel name for the same channel uniqueid, indicating the channel has been
// renamed but no related RenameEvent has been received.
// This happens with mISDN channels (see AJ-153)
if (event.getChannel() != null && !event.getChannel().equals(channel.getName()))
{
logger.info("Renaming channel (following NewStateEvent) '" + channel.getName() + "' to '" + event.getChannel() + "'");
synchronized (channel)
{
channel.nameChanged(event.getDateReceived(), event.getChannel());
}
}
}
if (event.getChannelState() != null)
{
synchronized (channel)
{
channel.stateChanged(event.getDateReceived(), ChannelState.valueOf(event.getChannelState()));
}
}
}
#location 9
#vulnerability type THREAD_SAFETY_VIOLATION | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
ChannelManager(AsteriskServerImpl server)
{
this.server = server;
this.channels = new HashSet<AsteriskChannelImpl>();
} | #vulnerable code
void handleNewChannelEvent(NewChannelEvent event)
{
final AsteriskChannelImpl channel = getChannelImplById(event.getUniqueId());
if (channel == null)
{
if (event.getChannel() == null)
{
logger.info("Ignored NewChannelEvent with empty channel name (uniqueId=" + event.getUniqueId() + ")");
}
else
{
addNewChannel(
event.getUniqueId(), event.getChannel(), event.getDateReceived(),
event.getCallerIdNum(), event.getCallerIdName(),
ChannelState.valueOf(event.getChannelState()), event.getAccountCode());
}
}
else
{
// channel had already been created probably by a NewCallerIdEvent
synchronized (channel)
{
channel.nameChanged(event.getDateReceived(), event.getChannel());
channel.setCallerId(new CallerId(event.getCallerIdName(), event.getCallerIdNum()));
channel.stateChanged(event.getDateReceived(), ChannelState.valueOf(event.getChannelState()));
}
}
}
#location 13
#vulnerability type THREAD_SAFETY_VIOLATION | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
public AsteriskChannel originateToApplication(String channel, String application, String data, long timeout) throws ManagerCommunicationException, NoSuchChannelException
{
return originateToApplication(channel, application, data, timeout, null, null);
} | #vulnerable code
public AsteriskChannel originateToApplication(String channel, String application, String data, long timeout) throws ManagerCommunicationException
{
return originateToApplication(channel, application, data, timeout, null, null);
}
#location 3
#vulnerability type NULL_DEREFERENCE | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
OriginateResult originate(final EndPoint local, final EndPoint target, final HashMap<String, String> myVars,
final CallerID callerID, final Integer timeout, final boolean hideCallerId, final String context)
{
OriginateBaseClass.logger.debug("originate called");
this.originateSeen = false;
this.channelSeen = false;
if (this.hungup)
{
// the monitored channel already hungup so just return false and
// shutdown
return null;
}
OriginateBaseClass.logger.debug("originate connection endPoint \n" + local + " to endPoint " + target //$NON-NLS-2$
+ " vars " + myVars);
ManagerResponse response = null;
final AsteriskSettings settings = PBXFactory.getActiveProfile();
final OriginateAction originate = new OriginateAction();
this.originateID = originate.getActionId();
channelId = "" + (System.currentTimeMillis() / 1000) + ".AJ" + originateSeed.incrementAndGet();
originate.setChannelId(channelId);
Integer localTimeout = timeout;
if (timeout == null)
{
localTimeout = 30000;
try
{
localTimeout = settings.getDialTimeout() * 1000;
}
catch (final Exception e)
{
OriginateBaseClass.logger.error("Invalid dial timeout value");
}
}
// Whilst the originate document says that it takes a channel it
// actually takes an
// end point. I haven't check but I'm skeptical that you can actually
// originate to
// a channel as the doco talks about 'dialing the channel'. I suspect
// this
// may be part of asterisk's sloppy terminology.
if (local.isLocal())
{
originate.setEndPoint(local);
originate.setOption("/n");
}
else
{
originate.setEndPoint(local);
}
originate.setContext(context);
originate.setExten(target);
originate.setPriority(1);
// Set the caller id.
if (hideCallerId)
{
// hide callerID
originate.setCallingPres(32);
}
else
{
originate.setCallerId(callerID);
}
originate.setVariables(myVars);
originate.setAsync(true);
originate.setTimeout(localTimeout);
try
{
// Just add us as an asterisk event listener.
this.startListener();
response = pbx.sendAction(originate, localTimeout);
OriginateBaseClass.logger.debug("Originate.sendAction completed");
if (response.getResponse().compareToIgnoreCase("Success") != 0)
{
OriginateBaseClass.logger
.error("Error Originating call" + originate.toString() + " : " + response.getMessage());//$NON-NLS-2$
throw new ManagerCommunicationException(response.getMessage(), null);
}
// wait the set timeout +1 second to allow for
// asterisk to start the originate
originateLatch.await(localTimeout + 1000, TimeUnit.MILLISECONDS);
}
catch (final InterruptedException e)
{
OriginateBaseClass.logger.debug(e, e);
}
catch (final Exception e)
{
OriginateBaseClass.logger.error(e, e);
}
finally
{
this.close();
}
if (this.originateSuccess)
{
this.result.setSuccess(true);
this.result.setChannelData(this.newChannel);
OriginateBaseClass.logger.debug("new channel ok: " + this.newChannel);
}
else
{
OriginateBaseClass.logger.warn("originate failed to connect endPoint: " + local + " to ext " + target); //$NON-NLS-2$
if (this.newChannel != null)
{
try
{
logger.info("Hanging up");
pbx.hangup(this.newChannel);
}
catch (IllegalArgumentException | IllegalStateException | PBXException e)
{
logger.error(e, e);
}
}
}
return this.result;
} | #vulnerable code
OriginateResult originate(final EndPoint local, final EndPoint target, final HashMap<String, String> myVars,
final CallerID callerID, final Integer timeout, final boolean hideCallerId, final String context)
{
OriginateBaseClass.logger.debug("originate called");
this.originateSeen = false;
this.channelSeen = false;
if (this.hungup == true)
{
// the monitored channel already hungup so just return false and
// shutdown
return null;
}
OriginateBaseClass.logger.debug("originate connection endPoint \n" + local + " to endPoint " + target //$NON-NLS-2$
+ " vars " + myVars);
ManagerResponse response = null;
final AsteriskSettings settings = PBXFactory.getActiveProfile();
final OriginateAction originate = new OriginateAction();
this.originateID = originate.getActionId();
channelId = "" + (System.currentTimeMillis() / 1000) + ".AJ" + originateSeed.incrementAndGet();
originate.setChannelId(channelId);
Integer localTimeout = timeout;
if (timeout == null)
{
localTimeout = 30000;
try
{
localTimeout = settings.getDialTimeout() * 1000;
}
catch (final Exception e)
{
OriginateBaseClass.logger.error("Invalid dial timeout value");
}
}
// Whilst the originate document says that it takes a channel it
// actually takes an
// end point. I haven't check but I'm skeptical that you can actually
// originate to
// a channel as the doco talks about 'dialing the channel'. I suspect
// this
// may be part of asterisk's sloppy terminology.
if (local.isLocal())
{
originate.setEndPoint(local);
originate.setOption("/n");
}
else
{
originate.setEndPoint(local);
}
originate.setContext(context);
originate.setExten(target);
originate.setPriority(1);
// Set the caller id.
if (hideCallerId)
{
// hide callerID
originate.setCallingPres(32);
}
else
{
originate.setCallerId(callerID);
}
originate.setVariables(myVars);
originate.setAsync(true);
originate.setTimeout(localTimeout);
try
{
// Just add us as an asterisk event listener.
this.startListener();
response = pbx.sendAction(originate, localTimeout);
OriginateBaseClass.logger.debug("Originate.sendAction completed");
if (response.getResponse().compareToIgnoreCase("Success") != 0)
{
OriginateBaseClass.logger
.error("Error Originating call" + originate.toString() + " : " + response.getMessage());//$NON-NLS-2$
throw new ManagerCommunicationException(response.getMessage(), null);
}
// wait the set timeout +1 second to allow for
// asterisk to start the originate
originateLatch.await(localTimeout + 1000, TimeUnit.MILLISECONDS);
}
catch (final InterruptedException e)
{
OriginateBaseClass.logger.debug(e, e);
}
catch (final Exception e)
{
OriginateBaseClass.logger.error(e, e);
}
finally
{
this.close();
}
if (this.originateSuccess == true)
{
this.result.setSuccess(true);
this.result.setChannelData(this.newChannel);
OriginateBaseClass.logger.debug("new channel ok: " + this.newChannel);
}
else
{
OriginateBaseClass.logger.warn("originate failed to connect endPoint: " + local + " to ext " + target); //$NON-NLS-2$
if (this.newChannel != null)
{
try
{
logger.info("Hanging up");
pbx.hangup(this.newChannel);
}
catch (IllegalArgumentException | IllegalStateException | PBXException e)
{
logger.error(e, e);
}
}
}
return this.result;
}
#location 8
#vulnerability type THREAD_SAFETY_VIOLATION | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
private void fastScannerSpeedTest(Pattern pattern) throws Exception
{
try
{
for (int i = 10; i-- > 0;)
{
Socket echoSocket = new Socket("127.0.0.1", FastScannerTestSocketSource.portNumber);
InputStreamReader reader = getReader(echoSocket);
System.out.print("Fast " + i + ":\t");
FastScanner scanner = FastScannerFactory.getReader(reader, pattern);
long start = System.currentTimeMillis();
try
{
int ctr = 0;
@SuppressWarnings("unused")
String t;
while ((t = scanner.next()) != null)
{
// System.out.println(t);
ctr++;
}
System.out.print(ctr + "\t");
}
catch (NoSuchElementException e)
{
}
System.out.println((System.currentTimeMillis() - start) + " ms");
}
}
catch (Exception e)
{
System.out.println(
"If you want to run FastScannerSpeedTestOnSocket, you'll need to run FastScannerTestSocketSource first");
}
} | #vulnerable code
private void fastScannerSpeedTest(Pattern pattern) throws Exception
{
try
{
for (int i = 10; i-- > 0;)
{
InputStreamReader reader = getReader();
System.out.print("Fast " + i + ":\t");
FastScanner scanner = FastScannerFactory.getReader(reader, pattern);
long start = System.currentTimeMillis();
try
{
int ctr = 0;
@SuppressWarnings("unused")
String t;
while ((t = scanner.next()) != null)
{
// System.out.println(t);
ctr++;
}
System.out.print(ctr + "\t");
}
catch (NoSuchElementException e)
{
}
System.out.println((System.currentTimeMillis() - start) + " ms");
}
}
catch (Exception e)
{
System.out.println(
"If you want to run FastScannerSpeedTestOnSocket, you'll need to run FastScannerTestSocketSource first");
}
}
#location 10
#vulnerability type RESOURCE_LEAK | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
OriginateResult originate(final EndPoint local, final EndPoint target, final HashMap<String, String> myVars,
final CallerID callerID, final Integer timeout, final boolean hideCallerId, final String context)
{
OriginateBaseClass.logger.debug("originate called");
this.originateSeen = false;
this.channelSeen = false;
if (this.hungup)
{
// the monitored channel already hungup so just return false and
// shutdown
return null;
}
OriginateBaseClass.logger.debug("originate connection endPoint \n" + local + " to endPoint " + target //$NON-NLS-2$
+ " vars " + myVars);
ManagerResponse response = null;
final AsteriskSettings settings = PBXFactory.getActiveProfile();
final OriginateAction originate = new OriginateAction();
this.originateID = originate.getActionId();
channelId = "" + (System.currentTimeMillis() / 1000) + ".AJ" + originateSeed.incrementAndGet();
originate.setChannelId(channelId);
Integer localTimeout = timeout;
if (timeout == null)
{
localTimeout = 30000;
try
{
localTimeout = settings.getDialTimeout() * 1000;
}
catch (final Exception e)
{
OriginateBaseClass.logger.error("Invalid dial timeout value");
}
}
// Whilst the originate document says that it takes a channel it
// actually takes an
// end point. I haven't check but I'm skeptical that you can actually
// originate to
// a channel as the doco talks about 'dialing the channel'. I suspect
// this
// may be part of asterisk's sloppy terminology.
if (local.isLocal())
{
originate.setEndPoint(local);
originate.setOption("/n");
}
else
{
originate.setEndPoint(local);
}
originate.setContext(context);
originate.setExten(target);
originate.setPriority(1);
// Set the caller id.
if (hideCallerId)
{
// hide callerID
originate.setCallingPres(32);
}
else
{
originate.setCallerId(callerID);
}
originate.setVariables(myVars);
originate.setAsync(true);
originate.setTimeout(localTimeout);
try
{
// Just add us as an asterisk event listener.
this.startListener();
response = pbx.sendAction(originate, localTimeout);
OriginateBaseClass.logger.debug("Originate.sendAction completed");
if (response.getResponse().compareToIgnoreCase("Success") != 0)
{
OriginateBaseClass.logger
.error("Error Originating call" + originate.toString() + " : " + response.getMessage());//$NON-NLS-2$
throw new ManagerCommunicationException(response.getMessage(), null);
}
// wait the set timeout +1 second to allow for
// asterisk to start the originate
originateLatch.await(localTimeout + 1000, TimeUnit.MILLISECONDS);
}
catch (final InterruptedException e)
{
OriginateBaseClass.logger.debug(e, e);
}
catch (final Exception e)
{
OriginateBaseClass.logger.error(e, e);
}
finally
{
this.close();
}
if (this.originateSuccess)
{
this.result.setSuccess(true);
this.result.setChannelData(this.newChannel);
OriginateBaseClass.logger.debug("new channel ok: " + this.newChannel);
}
else
{
OriginateBaseClass.logger.warn("originate failed to connect endPoint: " + local + " to ext " + target); //$NON-NLS-2$
if (this.newChannel != null)
{
try
{
logger.info("Hanging up");
pbx.hangup(this.newChannel);
}
catch (IllegalArgumentException | IllegalStateException | PBXException e)
{
logger.error(e, e);
}
}
}
return this.result;
} | #vulnerable code
OriginateResult originate(final EndPoint local, final EndPoint target, final HashMap<String, String> myVars,
final CallerID callerID, final Integer timeout, final boolean hideCallerId, final String context)
{
OriginateBaseClass.logger.debug("originate called");
this.originateSeen = false;
this.channelSeen = false;
if (this.hungup == true)
{
// the monitored channel already hungup so just return false and
// shutdown
return null;
}
OriginateBaseClass.logger.debug("originate connection endPoint \n" + local + " to endPoint " + target //$NON-NLS-2$
+ " vars " + myVars);
ManagerResponse response = null;
final AsteriskSettings settings = PBXFactory.getActiveProfile();
final OriginateAction originate = new OriginateAction();
this.originateID = originate.getActionId();
channelId = "" + (System.currentTimeMillis() / 1000) + ".AJ" + originateSeed.incrementAndGet();
originate.setChannelId(channelId);
Integer localTimeout = timeout;
if (timeout == null)
{
localTimeout = 30000;
try
{
localTimeout = settings.getDialTimeout() * 1000;
}
catch (final Exception e)
{
OriginateBaseClass.logger.error("Invalid dial timeout value");
}
}
// Whilst the originate document says that it takes a channel it
// actually takes an
// end point. I haven't check but I'm skeptical that you can actually
// originate to
// a channel as the doco talks about 'dialing the channel'. I suspect
// this
// may be part of asterisk's sloppy terminology.
if (local.isLocal())
{
originate.setEndPoint(local);
originate.setOption("/n");
}
else
{
originate.setEndPoint(local);
}
originate.setContext(context);
originate.setExten(target);
originate.setPriority(1);
// Set the caller id.
if (hideCallerId)
{
// hide callerID
originate.setCallingPres(32);
}
else
{
originate.setCallerId(callerID);
}
originate.setVariables(myVars);
originate.setAsync(true);
originate.setTimeout(localTimeout);
try
{
// Just add us as an asterisk event listener.
this.startListener();
response = pbx.sendAction(originate, localTimeout);
OriginateBaseClass.logger.debug("Originate.sendAction completed");
if (response.getResponse().compareToIgnoreCase("Success") != 0)
{
OriginateBaseClass.logger
.error("Error Originating call" + originate.toString() + " : " + response.getMessage());//$NON-NLS-2$
throw new ManagerCommunicationException(response.getMessage(), null);
}
// wait the set timeout +1 second to allow for
// asterisk to start the originate
originateLatch.await(localTimeout + 1000, TimeUnit.MILLISECONDS);
}
catch (final InterruptedException e)
{
OriginateBaseClass.logger.debug(e, e);
}
catch (final Exception e)
{
OriginateBaseClass.logger.error(e, e);
}
finally
{
this.close();
}
if (this.originateSuccess == true)
{
this.result.setSuccess(true);
this.result.setChannelData(this.newChannel);
OriginateBaseClass.logger.debug("new channel ok: " + this.newChannel);
}
else
{
OriginateBaseClass.logger.warn("originate failed to connect endPoint: " + local + " to ext " + target); //$NON-NLS-2$
if (this.newChannel != null)
{
try
{
logger.info("Hanging up");
pbx.hangup(this.newChannel);
}
catch (IllegalArgumentException | IllegalStateException | PBXException e)
{
logger.error(e, e);
}
}
}
return this.result;
}
#location 5
#vulnerability type THREAD_SAFETY_VIOLATION | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
ChannelManager(AsteriskServerImpl server)
{
this.server = server;
this.channels = new HashSet<AsteriskChannelImpl>();
} | #vulnerable code
void handleNewCallerIdEvent(NewCallerIdEvent event)
{
AsteriskChannelImpl channel = getChannelImplById(event.getUniqueId());
if (channel == null)
{
// NewCallerIdEvent can occur for an existing channel that now has a different unique id (originate with Local/)
channel = getChannelImplByNameAndActive(event.getChannel());
if (channel != null)
{
logger.info("Changing unique id for '" + channel.getName() + "' from " + channel.getId() + " to " + event.getUniqueId());
channel.idChanged(event.getDateReceived(), event.getUniqueId());
}
if (channel == null)
{
// NewCallerIdEvent can occur before NewChannelEvent
channel = addNewChannel(
event.getUniqueId(), event.getChannel(), event.getDateReceived(),
event.getCallerIdNum(), event.getCallerIdName(),
ChannelState.DOWN, null /* account code not available */);
}
}
synchronized (channel)
{
channel.setCallerId(new CallerId(event.getCallerIdName(), event.getCallerIdNum()));
}
}
#location 11
#vulnerability type THREAD_SAFETY_VIOLATION | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
ChannelManager(AsteriskServerImpl server)
{
this.server = server;
this.channels = new HashSet<AsteriskChannelImpl>();
} | #vulnerable code
void handleNewCallerIdEvent(NewCallerIdEvent event)
{
AsteriskChannelImpl channel = getChannelImplById(event.getUniqueId());
if (channel == null)
{
// NewCallerIdEvent can occur for an existing channel that now has a different unique id (originate with Local/)
channel = getChannelImplByNameAndActive(event.getChannel());
if (channel != null)
{
logger.info("Changing unique id for '" + channel.getName() + "' from " + channel.getId() + " to " + event.getUniqueId());
channel.idChanged(event.getDateReceived(), event.getUniqueId());
}
if (channel == null)
{
// NewCallerIdEvent can occur before NewChannelEvent
channel = addNewChannel(
event.getUniqueId(), event.getChannel(), event.getDateReceived(),
event.getCallerIdNum(), event.getCallerIdName(),
ChannelState.DOWN, null /* account code not available */);
}
}
synchronized (channel)
{
channel.setCallerId(new CallerId(event.getCallerIdName(), event.getCallerIdNum()));
}
}
#location 18
#vulnerability type THREAD_SAFETY_VIOLATION | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
public ResponseEvents sendEventGeneratingAction(
EventGeneratingAction action, long timeout) throws IOException,
EventTimeoutException, IllegalArgumentException,
IllegalStateException
{
ResponseEventsImpl responseEvents;
ResponseEventHandler responseEventHandler;
String internalActionId;
if (action == null)
{
throw new IllegalArgumentException(
"Unable to send action: action is null.");
}
else if (action.getActionCompleteEventClass() == null)
{
throw new IllegalArgumentException(
"Unable to send action: actionCompleteEventClass is null.");
}
else if (!ResponseEvent.class.isAssignableFrom(action
.getActionCompleteEventClass()))
{
throw new IllegalArgumentException(
"Unable to send action: actionCompleteEventClass is not a ResponseEvent.");
}
if (socket == null)
{
throw new IllegalStateException("Unable to send "
+ action.getAction() + " action: not connected.");
}
responseEvents = new ResponseEventsImpl();
responseEventHandler = new ResponseEventHandler(responseEvents, action
.getActionCompleteEventClass());
internalActionId = createInternalActionId();
// register response handler...
synchronized (this.responseHandlers)
{
this.responseHandlers.put(internalActionId, responseEventHandler);
}
// ...and event handler.
synchronized (this.responseEventHandlers)
{
this.responseEventHandlers.put(internalActionId,
responseEventHandler);
}
synchronized (responseEvents)
{
writer.sendAction(action, internalActionId);
try
{
responseEvents.wait(timeout);
}
catch (InterruptedException ex)
{
//TODO fix logging
System.err.println("Interrupted");
}
}
// still no response or not all events received and timed out?
if ((responseEvents.getResponse() == null || !responseEvents
.isComplete()))
{
// clean up
synchronized (this.responseEventHandlers)
{
this.responseEventHandlers.remove(internalActionId);
}
throw new EventTimeoutException(
"Timeout waiting for response or response events to "
+ action.getAction(), responseEvents);
}
// remove the event handler (note: the response handler is removed
// automatically when the response is received)
synchronized (this.responseEventHandlers)
{
this.responseEventHandlers.remove(internalActionId);
}
return responseEvents;
} | #vulnerable code
public ResponseEvents sendEventGeneratingAction(
EventGeneratingAction action, long timeout) throws IOException,
EventTimeoutException, IllegalArgumentException,
IllegalStateException
{
ResponseEventsImpl responseEvents;
ResponseEventHandler responseEventHandler;
String internalActionId;
long start;
long timeSpent;
if (action == null)
{
throw new IllegalArgumentException(
"Unable to send action: action is null.");
}
else if (action.getActionCompleteEventClass() == null)
{
throw new IllegalArgumentException(
"Unable to send action: actionCompleteEventClass is null.");
}
else if (!ResponseEvent.class.isAssignableFrom(action
.getActionCompleteEventClass()))
{
throw new IllegalArgumentException(
"Unable to send action: actionCompleteEventClass is not a ResponseEvent.");
}
if (socket == null)
{
throw new IllegalStateException("Unable to send "
+ action.getAction() + " action: not connected.");
}
responseEvents = new ResponseEventsImpl();
responseEventHandler = new ResponseEventHandler(responseEvents, action
.getActionCompleteEventClass(), Thread.currentThread());
internalActionId = createInternalActionId();
// register response handler...
synchronized (this.responseHandlers)
{
this.responseHandlers.put(internalActionId, responseEventHandler);
}
// ...and event handler.
synchronized (this.responseEventHandlers)
{
this.responseEventHandlers.put(internalActionId,
responseEventHandler);
}
writer.sendAction(action, internalActionId);
// let's wait to see what we get
start = System.currentTimeMillis();
timeSpent = 0;
while (responseEvents.getResponse() == null
|| !responseEvents.isComplete())
{
try
{
Thread.sleep(timeout - timeSpent);
}
catch (InterruptedException ex)
{
}
// still no response or not all events received and timed out?
timeSpent = System.currentTimeMillis() - start;
if ((responseEvents.getResponse() == null || !responseEvents
.isComplete())
&& timeSpent > timeout)
{
// clean up
synchronized (this.responseEventHandlers)
{
this.responseEventHandlers.remove(internalActionId);
}
throw new EventTimeoutException(
"Timeout waiting for response or response events to "
+ action.getAction(), responseEvents);
}
}
// remove the event handler (note: the response handler is removed
// automatically when the response is received)
synchronized (this.responseEventHandlers)
{
this.responseEventHandlers.remove(internalActionId);
}
return responseEvents;
}
#location 54
#vulnerability type THREAD_SAFETY_VIOLATION | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
ChannelManager(AsteriskServerImpl server)
{
this.server = server;
} | #vulnerable code
void handleNewCallerIdEvent(NewCallerIdEvent event)
{
AsteriskChannelImpl channel = getChannelImplById(event.getUniqueId());
if (channel == null)
{
// NewCallerIdEvent can occur for an existing channel that now has a different unique id (originate with Local/)
channel = getChannelImplByNameAndActive(event.getChannel());
idChanged(channel, event);
if (channel == null)
{
// NewCallerIdEvent can occur before NewChannelEvent
channel = addNewChannel(
event.getUniqueId(), event.getChannel(), event.getDateReceived(),
event.getCallerIdNum(), event.getCallerIdName(),
ChannelState.DOWN, null /* account code not available */);
}
}
synchronized (channel)
{
channel.setCallerId(new CallerId(event.getCallerIdName(), event.getCallerIdNum()));
}
}
#location 9
#vulnerability type THREAD_SAFETY_VIOLATION | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Override
public ReadablePeriod deserialize(JsonParser p, DeserializationContext ctxt)
throws IOException
{
JsonToken t = p.currentToken();
if (t == JsonToken.VALUE_STRING) {
return _fromString(p, ctxt, p.getText());
}
if (t == JsonToken.VALUE_NUMBER_INT) {
return new Period(p.getLongValue());
}
if (t != JsonToken.START_OBJECT && t != JsonToken.FIELD_NAME) {
return (ReadablePeriod) ctxt.handleUnexpectedToken(handledType(), t, p,
"expected JSON Number, String or Object");
}
return _fromObject(p, ctxt);
} | #vulnerable code
@Override
public ReadablePeriod deserialize(JsonParser p, DeserializationContext ctxt)
throws IOException
{
JsonToken t = p.currentToken();
if (t == JsonToken.VALUE_STRING) {
String str = p.getText().trim();
if (str.isEmpty()) {
return null;
}
return _format.parsePeriod(ctxt, str);
}
if (t == JsonToken.VALUE_NUMBER_INT) {
return new Period(p.getLongValue());
}
if (t != JsonToken.START_OBJECT && t != JsonToken.FIELD_NAME) {
return (ReadablePeriod) ctxt.handleUnexpectedToken(handledType(), t, p,
"expected JSON Number, String or Object");
}
JsonNode treeNode = p.readValueAsTree();
String periodType = treeNode.path("fieldType").path("name").asText();
String periodName = treeNode.path("periodType").path("name").asText();
// any "weird" numbers we should worry about?
int periodValue = treeNode.path(periodType).asInt();
ReadablePeriod rp;
if (periodName.equals( "Seconds" )) {
rp = Seconds.seconds( periodValue );
}
else if (periodName.equals( "Minutes" )) {
rp = Minutes.minutes( periodValue );
}
else if (periodName.equals( "Hours" )) {
rp = Hours.hours( periodValue );
}
else if (periodName.equals( "Days" )) {
rp = Days.days( periodValue );
}
else if (periodName.equals( "Weeks" )) {
rp = Weeks.weeks( periodValue );
}
else if (periodName.equals( "Months" )) {
rp = Months.months( periodValue );
}
else if (periodName.equals( "Years" )) {
rp = Years.years( periodValue );
} else {
ctxt.reportInputMismatch(handledType(),
"Don't know how to deserialize %s using periodName '%s'",
handledType().getName(), periodName);
rp = null; // never gets here
}
if (_requireFullPeriod && !(rp instanceof Period)) {
rp = rp.toPeriod();
}
return rp;
}
#location 57
#vulnerability type NULL_DEREFERENCE | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
private boolean isZipFile(final File file) {
DataInputStream in = null;
try {
in = new DataInputStream(new FileInputStream(file));
final int n = in.readInt();
return n == 0x504b0304;
} catch (IOException ex) {
// silently ignore read exceptions
return false;
} finally {
if (in != null) {
try {
in.close();
} catch (IOException ex) {
// ignore
}
}
}
} | #vulnerable code
private boolean isZipFile(final File file) throws IOException {
final DataInputStream in = new DataInputStream(new FileInputStream(file));
final int n = in.readInt();
in.close();
return n == 0x504b0304;
}
#location 5
#vulnerability type RESOURCE_LEAK | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
private void updateTranslationProgressMap(String langCode, int value) {
if (getDefaultLanguageCode().equals(langCode)) {
return;
}
double defsize = getDefaultLanguage().size();
double approved = value;
Map<String, Integer> progress = getTranslationProgressMap();
Integer percent = progress.get(langCode);
if (value == PLUS) {
approved = Math.round(percent * (defsize / 100) + 1);
} else if (value == MINUS) {
approved = Math.round(percent * (defsize / 100) - 1);
}
// allow 3 identical words per language (i.e. Email, etc)
if (approved >= defsize - 5) {
approved = defsize;
}
if (((int) defsize) == 0) {
progress.put(langCode, 0);
} else {
progress.put(langCode, (int) ((approved / defsize) * 100));
}
Sysprop updatedProgress = new Sysprop(progressKey);
for (Map.Entry<String, Integer> entry : progress.entrySet()) {
updatedProgress.addProperty(entry.getKey(), entry.getValue());
}
langProgressCache = updatedProgress;
if (percent < 100 && !percent.equals(progress.get(langCode))) {
pc.create(updatedProgress);
}
} | #vulnerable code
private void updateTranslationProgressMap(String langCode, int value) {
if (getDefaultLanguageCode().equals(langCode)) {
return;
}
double defsize = getDefaultLanguage().size();
double approved = value;
Map<String, Integer> progress = getTranslationProgressMap();
Integer percent = progress.get(langCode);
if (value == PLUS) {
approved = Math.round(percent * (defsize / 100) + 1);
} else if (value == MINUS) {
approved = Math.round(percent * (defsize / 100) - 1);
}
// allow 3 identical words per language (i.e. Email, etc)
if (approved >= defsize - 5) {
approved = defsize;
}
if (((int) defsize) == 0) {
progress.put(langCode, 0);
} else {
progress.put(langCode, (int) ((approved / defsize) * 100));
}
if (percent < 100 && !percent.equals(progress.get(langCode))) {
Sysprop s = new Sysprop(progressKey);
for (Map.Entry<String, Integer> entry : progress.entrySet()) {
s.addProperty(entry.getKey(), entry.getValue());
}
pc.create(s);
}
}
#location 27
#vulnerability type NULL_DEREFERENCE | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Test
public void testTaskCreate() {
setupContextForTaskExecutionListener();
DefaultTaskListenerConfiguration.TestTaskExecutionListener taskExecutionListener =
context.getBean(DefaultTaskListenerConfiguration.TestTaskExecutionListener.class);
TaskExecution taskExecution = new TaskExecution(0, null, "wombat",
new Date(), new Date(), null, new ArrayList<String>(), null, null);
verifyListenerResults(true, false, false, taskExecution,taskExecutionListener);
} | #vulnerable code
@Test
public void testTaskCreate() {
setupContextForTaskExecutionListener();
DefaultTaskListenerConfiguration.TestTaskExecutionListener taskExecutionListener =
context.getBean(DefaultTaskListenerConfiguration.TestTaskExecutionListener.class);
TaskExecution taskExecution = new TaskExecution(0, null, "wombat",
new Date(), new Date(), null, new ArrayList<String>(), null);
verifyListenerResults(true, false, false, taskExecution,taskExecutionListener);
}
#location 8
#vulnerability type NULL_DEREFERENCE | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
@Test
public void testAnnotationCreate() throws Exception {
setupContextForAnnotatedListener();
DefaultAnnotationConfiguration.AnnotatedTaskListener annotatedListener =
context.getBean(DefaultAnnotationConfiguration.AnnotatedTaskListener.class);
TaskExecution taskExecution = new TaskExecution(0, null, "wombat",
new Date(), new Date(), null, new ArrayList<String>(), null, null);
verifyListenerResults(true, false, false, taskExecution,annotatedListener);
} | #vulnerable code
@Test
public void testAnnotationCreate() throws Exception {
setupContextForAnnotatedListener();
DefaultAnnotationConfiguration.AnnotatedTaskListener annotatedListener =
context.getBean(DefaultAnnotationConfiguration.AnnotatedTaskListener.class);
TaskExecution taskExecution = new TaskExecution(0, null, "wombat",
new Date(), new Date(), null, new ArrayList<String>(), null);
verifyListenerResults(true, false, false, taskExecution,annotatedListener);
}
#location 8
#vulnerability type NULL_DEREFERENCE | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
File getImage() {
//获取当前时间作为名字
Date current = new Date();
SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");
String curDate = df.format(current);
File curPhoto = new File(HERO_PATH, curDate + ".png");
//截屏存到手机本地
try {
while(!curPhoto.exists()) {
Process process = Runtime.getRuntime().exec(ADB_PATH
+ " shell /system/bin/screencap -p /sdcard/screenshot.png");
process.waitFor();
//将截图放在电脑本地
process = Runtime.getRuntime().exec(ADB_PATH
+ " pull /sdcard/screenshot.png " + curPhoto.getAbsolutePath());
process.waitFor();
}
//返回当前图片名字
return curPhoto;
} catch (IOException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.err.println("获取图片失败");
return null;
} | #vulnerable code
File getImage() {
//获取当前时间作为名字
Date current = new Date();
SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");
String curDate = df.format(current);
File curPhoto = new File(HERO_PATH, curDate + ".png");
//截屏存到手机本地
try {
while(!curPhoto.exists()) {
Runtime.getRuntime().exec(ADB_PATH
+ " shell /system/bin/screencap -p /sdcard/screenshot.png");
Thread.sleep(700);
//将截图放在电脑本地
Runtime.getRuntime().exec(ADB_PATH
+ " pull /sdcard/screenshot.png " + curPhoto.getAbsolutePath());
Thread.sleep(200);
}
//返回当前图片名字
return curPhoto;
} catch (IOException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.err.println("获取图片失败");
return null;
}
#location 10
#vulnerability type RESOURCE_LEAK | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
Search(String question) {
this.question = question;
} | #vulnerable code
Long search(String question) throws IOException {
String path = "http://www.baidu.com/s?tn=ichuner&lm=-1&word=" +
URLEncoder.encode(question, "gb2312") + "&rn=1";
boolean findIt = false;
String line = null;
while (!findIt) {
URL url = new URL(path);
BufferedReader breaded = new BufferedReader(new InputStreamReader(url.openStream()));
while ((line = breaded.readLine()) != null) {
if (line.contains("百度为您找到相关结果约")) {
findIt = true;
int start = line.indexOf("百度为您找到相关结果约") + 11;
line = line.substring(start);
int end = line.indexOf("个");
line = line.substring(0, end);
break;
}
}
}
line = line.replace(",", "");
return Long.valueOf(line);
}
#location 23
#vulnerability type RESOURCE_LEAK | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
private Long searchAndOpen(String question) throws IOException {
String path = null;
try {
path = "http://www.baidu.com/s?tn=ichuner&lm=-1&word=" +
URLEncoder.encode(question, "gb2312") + "&rn=20";
//获取操作系统的名字
String osName = System.getProperty("os.name", "");
if (osName.startsWith("Mac OS")) {
//苹果的打开方式
Class fileMgr = Class.forName("com.apple.eio.FileManager");
Method openURL = fileMgr.getDeclaredMethod("openURL", new Class[]{String.class});
openURL.invoke(null, new Object[]{path});
} else if (osName.startsWith("Windows")) {
//windows的打开方式。
Runtime.getRuntime().exec("rundll32 url.dll,FileProtocolHandler " + path);
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
} catch (NoSuchMethodException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
// Runtime.getRuntime().exec("rundll32 url.dll,FileProtocolHandler " + path);
return new Search(question).search(question);
} | #vulnerable code
private Long searchAndOpen(String question) throws IOException {
String path = "http://www.baidu.com/s?tn=ichuner&lm=-1&word=" +
URLEncoder.encode(question, "gb2312") + "&rn=20";
Runtime.getRuntime().exec("rundll32 url.dll,FileProtocolHandler " + path);
return new Search(question).search(question);
}
#location 4
#vulnerability type RESOURCE_LEAK | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
Search(String question) {
this.question = question;
} | #vulnerable code
Long search(String question) throws IOException {
String path = "http://www.baidu.com/s?tn=ichuner&lm=-1&word=" +
URLEncoder.encode(question, "gb2312") + "&rn=1";
boolean findIt = false;
String line = null;
while (!findIt) {
URL url = new URL(path);
BufferedReader breaded = new BufferedReader(new InputStreamReader(url.openStream()));
while ((line = breaded.readLine()) != null) {
if (line.contains("百度为您找到相关结果约")) {
findIt = true;
int start = line.indexOf("百度为您找到相关结果约") + 11;
line = line.substring(start);
int end = line.indexOf("个");
line = line.substring(0, end);
break;
}
}
}
line = line.replace(",", "");
return Long.valueOf(line);
}
#location 11
#vulnerability type RESOURCE_LEAK | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
public static void main(String[] args) throws IOException {
// Setting the width and height of frame
frame.setSize(500, 800);
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
try{
loadConfig();
}catch (Exception e){
initConfig();
}
loadConfig();
// 创建面板
JPanel panel = new JPanel();
frame.add(panel);
panel.setLayout(null);
addAdbPath(panel);
addImagePath(panel);
addOCRSelection(panel);
addSearchSelection(panel);
addSetFinishButton(panel);
addRunButton(panel);
addResultTextArea(panel);
addPatternSelection(panel);
// 设置界面可见
frame.setVisible(true);
} | #vulnerable code
public static void main(String[] args) throws IOException {
// Setting the width and height of frame
frame.setSize(500, 800);
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
String path=MainGUI.class.getProtectionDomain().getCodeSource().getLocation().getFile();
path=path.substring(0,path.lastIndexOf("/"));
System.out.println(path);
File config = new File(path, "hero.config");
System.out.println(config.getAbsolutePath());
if(config.createNewFile()){
FileOutputStream fileOutputStream=new FileOutputStream(config);
fileOutputStream.write("测试".getBytes());
}else{
System.out.println("nothing");
}
System.out.println(config.getAbsolutePath());
// 创建面板
JPanel panel = new JPanel();
frame.add(panel);
panel.setLayout(null);
addAdbPath(panel);
addImagePath(panel);
addOCRSelection(panel);
addSearchSelection(panel);
addSetFinishButton(panel);
addRunButton(panel);
addResultTextArea(panel);
addPatternSelection(panel);
// 设置界面可见
frame.setVisible(true);
}
#location 12
#vulnerability type RESOURCE_LEAK | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
File getImage() {
//获取当前时间作为名字
Date current = new Date();
SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");
String curDate = df.format(current);
File curPhoto = new File(HERO_PATH, curDate + ".png");
//截屏存到手机本地
try {
while(!curPhoto.exists()) {
Process process = Runtime.getRuntime().exec(ADB_PATH
+ " shell /system/bin/screencap -p /sdcard/screenshot.png");
process.waitFor();
//将截图放在电脑本地
process = Runtime.getRuntime().exec(ADB_PATH
+ " pull /sdcard/screenshot.png " + curPhoto.getAbsolutePath());
process.waitFor();
}
//返回当前图片名字
return curPhoto;
} catch (IOException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.err.println("获取图片失败");
return null;
} | #vulnerable code
File getImage() {
//获取当前时间作为名字
Date current = new Date();
SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");
String curDate = df.format(current);
File curPhoto = new File(HERO_PATH, curDate + ".png");
//截屏存到手机本地
try {
while(!curPhoto.exists()) {
Runtime.getRuntime().exec(ADB_PATH
+ " shell /system/bin/screencap -p /sdcard/screenshot.png");
Thread.sleep(700);
//将截图放在电脑本地
Runtime.getRuntime().exec(ADB_PATH
+ " pull /sdcard/screenshot.png " + curPhoto.getAbsolutePath());
Thread.sleep(200);
}
//返回当前图片名字
return curPhoto;
} catch (IOException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.err.println("获取图片失败");
return null;
}
#location 10
#vulnerability type RESOURCE_LEAK | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
public String tamper(String sqlQueryDefault) {
String lead = null;
String sqlQuery = null;
String trail = null;
// Transform only SQL query without HTTP parameters and syntax changed, like p=1'+[sql]
Matcher matcherSql = Pattern.compile("(?s)(.*<tampering>)(.*)(</tampering>.*)").matcher(sqlQueryDefault);
if (matcherSql.find()) {
lead = matcherSql.group(1);
sqlQuery = matcherSql.group(2);
trail = matcherSql.group(3);
}
if (this.isEval) {
sqlQuery = eval(sqlQuery, this.customTamper);
}
if (this.isRandomCase) {
sqlQuery = eval(sqlQuery, TamperingType.RANDOM_CASE.instance().getJavascript());
}
if (this.isEqualToLike) {
sqlQuery = eval(sqlQuery, TamperingType.EQUAL_TO_LIKE.instance().getJavascript());
}
sqlQuery = lead + sqlQuery + trail;
sqlQuery = sqlQuery.replaceAll("(?i)<tampering>", StringUtils.EMPTY);
sqlQuery = sqlQuery.replaceAll("(?i)</tampering>", StringUtils.EMPTY);
// Empty when checking character insertion
if (StringUtils.isEmpty(sqlQuery)) {
return StringUtils.EMPTY;
}
// Transform all query, SQL and HTTP
if (this.isHexToChar) {
sqlQuery = eval(sqlQuery, TamperingType.HEX_TO_CHAR.instance().getJavascript());
}
if (this.isStringToChar) {
sqlQuery = eval(sqlQuery, TamperingType.STRING_TO_CHAR.instance().getJavascript());
}
if (this.isFunctionComment) {
sqlQuery = eval(sqlQuery, TamperingType.COMMENT_TO_METHOD_SIGNATURE.instance().getJavascript());
}
if (this.isVersionComment) {
sqlQuery = eval(sqlQuery, TamperingType.VERSIONED_COMMENT_TO_METHOD_SIGNATURE.instance().getJavascript());
}
// Dependency to: EQUAL_TO_LIKE
if (this.isSpaceToDashComment) {
sqlQuery = eval(sqlQuery, TamperingType.SPACE_TO_DASH_COMMENT.instance().getJavascript());
} else if (this.isSpaceToMultilineComment) {
sqlQuery = eval(sqlQuery, TamperingType.SPACE_TO_MULTILINE_COMMENT.instance().getJavascript());
} else if (this.isSpaceToSharpComment) {
sqlQuery = eval(sqlQuery, TamperingType.SPACE_TO_SHARP_COMMENT.instance().getJavascript());
}
if (this.isBase64) {
sqlQuery = eval(sqlQuery, TamperingType.BASE64.instance().getJavascript());
}
// Include character insertion at the beginning of query
if (this.isQuoteToUtf8) {
sqlQuery = eval(sqlQuery, TamperingType.QUOTE_TO_UTF8.instance().getJavascript());
}
return sqlQuery;
} | #vulnerable code
public String tamper(String sqlQueryDefault) {
String lead = null;
String sqlQuery = null;
String trail = null;
Matcher matcherSql = Pattern.compile("(?s)(.*<tampering>)(.*)(</tampering>.*)").matcher(sqlQueryDefault);
if (matcherSql.find()) {
lead = matcherSql.group(1);
sqlQuery = matcherSql.group(2);
trail = matcherSql.group(3);
}
// Empty when checking character insertion
if (StringUtils.isEmpty(sqlQuery)) {
return StringUtils.EMPTY;
}
if (this.isHexToChar) {
sqlQuery = eval(sqlQuery, TamperingType.HEX_TO_CHAR.instance().getJavascript());
}
if (this.isStringToChar) {
sqlQuery = eval(sqlQuery, TamperingType.STRING_TO_CHAR.instance().getJavascript());
}
if (this.isFunctionComment) {
sqlQuery = eval(sqlQuery, TamperingType.COMMENT_TO_METHOD_SIGNATURE.instance().getJavascript());
}
if (this.isVersionComment) {
sqlQuery = eval(sqlQuery, TamperingType.VERSIONED_COMMENT_TO_METHOD_SIGNATURE.instance().getJavascript());
}
if (this.isEqualToLike) {
sqlQuery = eval(sqlQuery, TamperingType.EQUAL_TO_LIKE.instance().getJavascript());
}
// Dependency to: EQUAL_TO_LIKE
if (this.isSpaceToDashComment) {
sqlQuery = eval(sqlQuery, TamperingType.SPACE_TO_DASH_COMMENT.instance().getJavascript());
} else if (this.isSpaceToMultilineComment) {
sqlQuery = eval(sqlQuery, TamperingType.SPACE_TO_MULTILINE_COMMENT.instance().getJavascript());
} else if (this.isSpaceToSharpComment) {
sqlQuery = eval(sqlQuery, TamperingType.SPACE_TO_SHARP_COMMENT.instance().getJavascript());
}
if (this.isRandomCase) {
sqlQuery = eval(sqlQuery, TamperingType.RANDOM_CASE.instance().getJavascript());
}
if (this.isEval) {
sqlQuery = eval(sqlQuery, this.customTamper);
}
if (this.isBase64) {
sqlQuery = eval(sqlQuery, TamperingType.BASE64.instance().getJavascript());
}
sqlQuery = lead + sqlQuery + trail;
// Include character insertion at the beginning of query
if (this.isQuoteToUtf8) {
sqlQuery = eval(sqlQuery, TamperingType.QUOTE_TO_UTF8.instance().getJavascript());
}
// Problme si le tag contient des caractres spciaux
sqlQuery = sqlQuery.replaceAll("(?i)<tampering>", StringUtils.EMPTY);
sqlQuery = sqlQuery.replaceAll("(?i)</tampering>", StringUtils.EMPTY);
return sqlQuery;
}
#location 68
#vulnerability type NULL_DEREFERENCE | Below is the vulnerable code, please generate the patch based on the following information. |
#fixed code
public String tamper(String sqlQueryDefault) {
String lead = null;
String sqlQuery = null;
String trail = null;
// Transform only SQL query without HTTP parameters and syntax changed, like p=1'+[sql]
Matcher matcherSql = Pattern.compile("(?s)(.*<tampering>)(.*)(</tampering>.*)").matcher(sqlQueryDefault);
if (matcherSql.find()) {
lead = matcherSql.group(1);
sqlQuery = matcherSql.group(2);
trail = matcherSql.group(3);
}
if (this.isEval) {
sqlQuery = eval(sqlQuery, this.customTamper);
}
if (this.isRandomCase) {
sqlQuery = eval(sqlQuery, TamperingType.RANDOM_CASE.instance().getJavascript());
}
if (this.isEqualToLike) {
sqlQuery = eval(sqlQuery, TamperingType.EQUAL_TO_LIKE.instance().getJavascript());
}
sqlQuery = lead + sqlQuery + trail;
sqlQuery = sqlQuery.replaceAll("(?i)<tampering>", StringUtils.EMPTY);
sqlQuery = sqlQuery.replaceAll("(?i)</tampering>", StringUtils.EMPTY);
// Empty when checking character insertion
if (StringUtils.isEmpty(sqlQuery)) {
return StringUtils.EMPTY;
}
// Transform all query, SQL and HTTP
if (this.isHexToChar) {
sqlQuery = eval(sqlQuery, TamperingType.HEX_TO_CHAR.instance().getJavascript());
}
if (this.isStringToChar) {
sqlQuery = eval(sqlQuery, TamperingType.STRING_TO_CHAR.instance().getJavascript());
}
if (this.isFunctionComment) {
sqlQuery = eval(sqlQuery, TamperingType.COMMENT_TO_METHOD_SIGNATURE.instance().getJavascript());
}
if (this.isVersionComment) {
sqlQuery = eval(sqlQuery, TamperingType.VERSIONED_COMMENT_TO_METHOD_SIGNATURE.instance().getJavascript());
}
// Dependency to: EQUAL_TO_LIKE
if (this.isSpaceToDashComment) {
sqlQuery = eval(sqlQuery, TamperingType.SPACE_TO_DASH_COMMENT.instance().getJavascript());
} else if (this.isSpaceToMultilineComment) {
sqlQuery = eval(sqlQuery, TamperingType.SPACE_TO_MULTILINE_COMMENT.instance().getJavascript());
} else if (this.isSpaceToSharpComment) {
sqlQuery = eval(sqlQuery, TamperingType.SPACE_TO_SHARP_COMMENT.instance().getJavascript());
}
if (this.isBase64) {
sqlQuery = eval(sqlQuery, TamperingType.BASE64.instance().getJavascript());
}
// Include character insertion at the beginning of query
if (this.isQuoteToUtf8) {
sqlQuery = eval(sqlQuery, TamperingType.QUOTE_TO_UTF8.instance().getJavascript());
}
return sqlQuery;
} | #vulnerable code
public String tamper(String sqlQueryDefault) {
String lead = null;
String sqlQuery = null;
String trail = null;
Matcher matcherSql = Pattern.compile("(?s)(.*<tampering>)(.*)(</tampering>.*)").matcher(sqlQueryDefault);
if (matcherSql.find()) {
lead = matcherSql.group(1);
sqlQuery = matcherSql.group(2);
trail = matcherSql.group(3);
}
// Empty when checking character insertion
if (StringUtils.isEmpty(sqlQuery)) {
return StringUtils.EMPTY;
}
if (this.isHexToChar) {
sqlQuery = eval(sqlQuery, TamperingType.HEX_TO_CHAR.instance().getJavascript());
}
if (this.isStringToChar) {
sqlQuery = eval(sqlQuery, TamperingType.STRING_TO_CHAR.instance().getJavascript());
}
if (this.isFunctionComment) {
sqlQuery = eval(sqlQuery, TamperingType.COMMENT_TO_METHOD_SIGNATURE.instance().getJavascript());
}
if (this.isVersionComment) {
sqlQuery = eval(sqlQuery, TamperingType.VERSIONED_COMMENT_TO_METHOD_SIGNATURE.instance().getJavascript());
}
if (this.isEqualToLike) {
sqlQuery = eval(sqlQuery, TamperingType.EQUAL_TO_LIKE.instance().getJavascript());
}
// Dependency to: EQUAL_TO_LIKE
if (this.isSpaceToDashComment) {
sqlQuery = eval(sqlQuery, TamperingType.SPACE_TO_DASH_COMMENT.instance().getJavascript());
} else if (this.isSpaceToMultilineComment) {
sqlQuery = eval(sqlQuery, TamperingType.SPACE_TO_MULTILINE_COMMENT.instance().getJavascript());
} else if (this.isSpaceToSharpComment) {
sqlQuery = eval(sqlQuery, TamperingType.SPACE_TO_SHARP_COMMENT.instance().getJavascript());
}
if (this.isRandomCase) {
sqlQuery = eval(sqlQuery, TamperingType.RANDOM_CASE.instance().getJavascript());
}
if (this.isEval) {
sqlQuery = eval(sqlQuery, this.customTamper);
}
if (this.isBase64) {
sqlQuery = eval(sqlQuery, TamperingType.BASE64.instance().getJavascript());
}
sqlQuery = lead + sqlQuery + trail;
// Include character insertion at the beginning of query
if (this.isQuoteToUtf8) {
sqlQuery = eval(sqlQuery, TamperingType.QUOTE_TO_UTF8.instance().getJavascript());
}
// Problme si le tag contient des caractres spciaux
sqlQuery = sqlQuery.replaceAll("(?i)<tampering>", StringUtils.EMPTY);
sqlQuery = sqlQuery.replaceAll("(?i)</tampering>", StringUtils.EMPTY);
return sqlQuery;
}
#location 24
#vulnerability type NULL_DEREFERENCE | Below is the vulnerable code, please generate the patch based on the following information. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.