output
stringlengths
64
73.2k
input
stringlengths
208
73.3k
instruction
stringclasses
1 value
#fixed code private DatasetVersion createNewDatasetVersion() { DatasetVersion dsv = new DatasetVersion(); dsv.setVersionState(DatasetVersion.VersionState.DRAFT); DatasetVersion latestVersion = getLatestVersion(); //if the latest version has values get them copied over if (latestVersion.getDatasetFields() != null && !latestVersion.getDatasetFields().isEmpty()) { dsv.setDatasetFields(dsv.copyDatasetFields(latestVersion.getDatasetFields())); } dsv.setFileMetadatas(new ArrayList()); for (FileMetadata fm : latestVersion.getFileMetadatas()) { FileMetadata newFm = new FileMetadata(); newFm.setCategory(fm.getCategory()); newFm.setDescription(fm.getDescription()); newFm.setLabel(fm.getLabel()); newFm.setDataFile(fm.getDataFile()); newFm.setDatasetVersion(dsv); dsv.getFileMetadatas().add(newFm); } // I'm adding the version to the list so it will be persisted when // the study object is persisted. getVersions().add(0, dsv); dsv.setDataset(this); return dsv; }
#vulnerable code private DatasetVersion createNewDatasetVersion() { DatasetVersion dsv = new DatasetVersion(); dsv.setVersionState(DatasetVersion.VersionState.DRAFT); DatasetVersion latestVersion = getLatestVersion(); //if the latest version has values get them copied over if (latestVersion.getDatasetFields() != null && !latestVersion.getDatasetFields().isEmpty()) { dsv.setDatasetFields(dsv.copyDatasetFields(latestVersion.getDatasetFields())); } dsv.setFileMetadatas(new ArrayList()); for (FileMetadata fm : latestVersion.getFileMetadatas()) { FileMetadata newFm = new FileMetadata(); newFm.setCategory(fm.getCategory()); newFm.setDescription(fm.getDescription()); newFm.setLabel(fm.getLabel()); newFm.setDataFile(fm.getDataFile()); newFm.setDatasetVersion(dsv); dsv.getFileMetadatas().add(newFm); } dsv.setVersionNumber(latestVersion.getVersionNumber() + 1); // I'm adding the version to the list so it will be persisted when // the study object is persisted. getVersions().add(0, dsv); dsv.setDataset(this); return dsv; } #location 12 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code DepositReceipt replaceOrAddFiles(String uri, Deposit deposit, AuthCredentials authCredentials, SwordConfiguration swordConfiguration, boolean shouldReplace) throws SwordError, SwordAuthException, SwordServerException { DataverseUser vdcUser = swordAuth.auth(authCredentials); urlManager.processUrl(uri); String globalId = urlManager.getTargetIdentifier(); if (urlManager.getTargetType().equals("study") && globalId != null) { // EditStudyService editStudyService; Context ctx; try { ctx = new InitialContext(); // editStudyService = (EditStudyService) ctx.lookup("java:comp/env/editStudy"); } catch (NamingException ex) { logger.info("problem looking up editStudyService"); throw new SwordServerException("problem looking up editStudyService"); } logger.fine("looking up study with globalId " + globalId); Dataset study = datasetService.findByGlobalId(globalId); if (study == null) { throw new SwordError(UriRegistry.ERROR_BAD_REQUEST, "Could not find study with global ID of " + globalId); } // StudyLock studyLock = study.getStudyLock(); // if (studyLock != null) { // String message = Util.getStudyLockMessage(studyLock, study.getGlobalId()); // throw new SwordError(UriRegistry.ERROR_BAD_REQUEST, message); // } Long studyId; try { studyId = study.getId(); } catch (NullPointerException ex) { throw new SwordError(UriRegistry.ERROR_BAD_REQUEST, "couldn't find study with global ID of " + globalId); } Dataverse dvThatOwnsStudy = study.getOwner(); if (swordAuth.hasAccessToModifyDataverse(vdcUser, dvThatOwnsStudy)) { // editStudyService.setStudyVersion(studyId); // editStudyService.save(dvThatOwnsStudy.getId(), vdcUser.getId()); // // EditStudyFilesService editStudyFilesService; // try { // editStudyFilesService = (EditStudyFilesService) ctx.lookup("java:comp/env/editStudyFiles"); // } catch (NamingException ex) { // logger.info("problem looking up editStudyFilesService"); // throw new SwordServerException("problem looking up editStudyFilesService"); // } // editStudyFilesService.setStudyVersionByGlobalId(globalId); // List studyFileEditBeans = editStudyFilesService.getCurrentFiles(); List<String> exisitingFilenames = new ArrayList<String>(); // for (Iterator it = studyFileEditBeans.iterator(); it.hasNext();) { // StudyFileEditBean studyFileEditBean = (StudyFileEditBean) it.next(); if (shouldReplace) { // studyFileEditBean.setDeleteFlag(true); // logger.fine("marked for deletion: " + studyFileEditBean.getStudyFile().getFileName()); } else { // String filename = studyFileEditBean.getStudyFile().getFileName(); // exisitingFilenames.add(filename); } } // editStudyFilesService.save(dvThatOwnsStudy.getId(), vdcUser.getId()); if (!deposit.getPackaging().equals(UriRegistry.PACKAGE_SIMPLE_ZIP)) { throw new SwordError(UriRegistry.ERROR_CONTENT, 415, "Package format " + UriRegistry.PACKAGE_SIMPLE_ZIP + " is required but format specified in 'Packaging' HTTP header was " + deposit.getPackaging()); } // Right now we are only supporting UriRegistry.PACKAGE_SIMPLE_ZIP but // in the future maybe we'll support other formats? Rdata files? Stata files? // That's what the uploadDir was going to be for, but for now it's commented out // String importDirString; File importDir; String swordTempDirString = swordConfiguration.getTempDirectory(); if (swordTempDirString == null) { throw new SwordError(UriRegistry.ERROR_BAD_REQUEST, "Could not determine temp directory"); } else { importDirString = swordTempDirString + File.separator + "import" + File.separator + study.getId().toString(); importDir = new File(importDirString); if (!importDir.exists()) { if (!importDir.mkdirs()) { logger.info("couldn't create directory: " + importDir.getAbsolutePath()); throw new SwordServerException("couldn't create import directory"); } } } if (true) { DataFile dFile = new DataFile("application/octet-stream"); dFile.setOwner(study); datasetService.generateFileSystemName(dFile); // if (true) { // throw returnEarly("dataFile.getFileSystemName(): " + dFile.getFileSystemName()); // } InputStream depositInputStream = deposit.getInputStream(); try { Files.copy(depositInputStream, Paths.get(importDirString, dFile.getFileSystemName()), StandardCopyOption.REPLACE_EXISTING); } catch (IOException ex) { throw new SwordError("problem running Files.copy"); } study.getFiles().add(dFile); DatasetVersion editVersion = study.getEditVersion(); // boolean metadataExtracted = false; // try { // metadataExtracted = ingestService.extractIndexableMetadata(importDir.getAbsolutePath() + File.separator + dFile.getFileSystemName(), dFile, editVersion); // } catch (IOException ex) { // throw returnEarly("couldn't extract metadata" + ex); // } FileMetadata fmd = new FileMetadata(); fmd.setDataFile(dFile); fmd.setLabel("myLabel"); fmd.setDatasetVersion(editVersion); dFile.getFileMetadatas().add(fmd); Command<Dataset> cmd; cmd = new UpdateDatasetCommand(study, vdcUser); try { /** * @todo at update time indexing is run but the file is not * indexed. Why? Manually re-indexing later finds it. Fix * this. Related to * https://redmine.hmdc.harvard.edu/issues/3809 ? */ study = commandEngine.submit(cmd); } catch (CommandException ex) { throw returnEarly("couldn't update dataset"); } catch (EJBException ex) { Throwable cause = ex; StringBuilder sb = new StringBuilder(); sb.append(ex.getLocalizedMessage()); while (cause.getCause() != null) { cause = cause.getCause(); sb.append(cause + " "); if (cause instanceof ConstraintViolationException) { ConstraintViolationException constraintViolationException = (ConstraintViolationException) cause; for (ConstraintViolation<?> violation : constraintViolationException.getConstraintViolations()) { sb.append(" Invalid value: <<<").append(violation.getInvalidValue()).append(">>> for ") .append(violation.getPropertyPath()).append(" at ") .append(violation.getLeafBean()).append(" - ") .append(violation.getMessage()); } } } throw returnEarly("EJBException: " + sb.toString()); } } /** * @todo remove this comment after confirming that the upstream jar * now has our bugfix */ // the first character of the filename is truncated with the official jar // so we use include the bug fix at https://github.com/IQSS/swordv2-java-server-library/commit/aeaef83 // and use this jar: https://build.hmdc.harvard.edu:8443/job/swordv2-java-server-library-iqss/2/ String uploadedZipFilename = deposit.getFilename(); ZipInputStream ziStream = new ZipInputStream(deposit.getInputStream()); ZipEntry zEntry; FileOutputStream tempOutStream = null; // List<StudyFileEditBean> fbList = new ArrayList<StudyFileEditBean>(); try { // copied from createStudyFilesFromZip in AddFilesPage while ((zEntry = ziStream.getNextEntry()) != null) { // Note that some zip entries may be directories - we // simply skip them: if (!zEntry.isDirectory()) { String fileEntryName = zEntry.getName(); logger.fine("file found: " + fileEntryName); String dirName = null; String finalFileName = null; int ind = fileEntryName.lastIndexOf('/'); if (ind > -1) { finalFileName = fileEntryName.substring(ind + 1); if (ind > 0) { dirName = fileEntryName.substring(0, ind); dirName = dirName.replace('/', '-'); } } else { finalFileName = fileEntryName; } if (".DS_Store".equals(finalFileName)) { continue; } // http://superuser.com/questions/212896/is-there-any-way-to-prevent-a-mac-from-creating-dot-underscore-files if (finalFileName.startsWith("._")) { continue; } File tempUploadedFile = new File(importDir, finalFileName); tempOutStream = new FileOutputStream(tempUploadedFile); byte[] dataBuffer = new byte[8192]; int i = 0; while ((i = ziStream.read(dataBuffer)) > 0) { tempOutStream.write(dataBuffer, 0, i); tempOutStream.flush(); } tempOutStream.close(); // We now have the unzipped file saved in the upload directory; // zero-length dta files (for example) are skipped during zip // upload in the GUI, so we'll skip them here as well if (tempUploadedFile.length() != 0) { if (true) { // tempUploadedFile; // UploadedFile uFile = tempUploadedFile; // DataFile dataFile = new DataFile(); // throw new SwordError("let's create a file"); } // StudyFileEditBean tempFileBean = new StudyFileEditBean(tempUploadedFile, studyService.generateFileSystemNameSequence(), study); // tempFileBean.setSizeFormatted(tempUploadedFile.length()); String finalFileNameAfterReplace = finalFileName; // if (tempFileBean.getStudyFile() instanceof TabularDataFile) { // predict what the tabular file name will be // finalFileNameAfterReplace = FileUtil.replaceExtension(finalFileName); // } // validateFileName(exisitingFilenames, finalFileNameAfterReplace, study); // And, if this file was in a legit (non-null) directory, // we'll use its name as the file category: if (dirName != null) { // tempFileBean.getFileMetadata().setCategory(dirName); } // fbList.add(tempFileBean); } } else { logger.fine("directory found: " + zEntry.getName()); } } } catch (IOException ex) { throw new SwordError(UriRegistry.ERROR_BAD_REQUEST, "Problem with file: " + uploadedZipFilename); } finally { /** * @todo shouldn't we delete this uploadDir? Commented out in * DVN 3.x */ // if (!uploadDir.delete()) { // logger.fine("Unable to delete " + uploadDir.getAbsolutePath()); // } } // if (fbList.size() > 0) { // StudyFileServiceLocal studyFileService; // try { // studyFileService = (StudyFileServiceLocal) ctx.lookup("java:comp/env/studyFileService"); // } catch (NamingException ex) { // logger.info("problem looking up studyFileService"); // throw new SwordServerException("problem looking up studyFileService"); // } try { // studyFileService.addFiles(study.getLatestVersion(), fbList, vdcUser); } catch (EJBException ex) { throw new SwordError(UriRegistry.ERROR_BAD_REQUEST, "Unable to add file(s) to study: " + ex.getMessage()); } ReceiptGenerator receiptGenerator = new ReceiptGenerator(); String baseUrl = urlManager.getHostnamePlusBaseUrlPath(uri); DepositReceipt depositReceipt = receiptGenerator.createReceipt(baseUrl, study); return depositReceipt; } else { // throw new SwordError(UriRegistry.ERROR_BAD_REQUEST, "Problem with zip file '" + uploadedZipFilename + "'. Number of files unzipped: " + fbList.size()); } // } else { // throw new SwordError(UriRegistry.ERROR_BAD_REQUEST, "user " + vdcUser.getUserName() + " is not authorized to modify study with global ID " + study.getGlobalId()); return new DepositReceipt(); // added just to get this to compile 2014-05-14 }
#vulnerable code DepositReceipt replaceOrAddFiles(String uri, Deposit deposit, AuthCredentials authCredentials, SwordConfiguration swordConfiguration, boolean shouldReplace) throws SwordError, SwordAuthException, SwordServerException { DataverseUser vdcUser = swordAuth.auth(authCredentials); urlManager.processUrl(uri); String globalId = urlManager.getTargetIdentifier(); if (urlManager.getTargetType().equals("study") && globalId != null) { // EditStudyService editStudyService; Context ctx; try { ctx = new InitialContext(); // editStudyService = (EditStudyService) ctx.lookup("java:comp/env/editStudy"); } catch (NamingException ex) { logger.info("problem looking up editStudyService"); throw new SwordServerException("problem looking up editStudyService"); } logger.fine("looking up study with globalId " + globalId); /** * @todo don't hard code this, obviously. In DVN 3.x we had a method * for editStudyService.getStudyByGlobalId(globalId) */ // Study study = editStudyService.getStudyByGlobalId(globalId); long databaseIdForRoastingAtHomeDataset = 10; Dataset study = datasetService.find(databaseIdForRoastingAtHomeDataset); if (study == null) { throw new SwordError(UriRegistry.ERROR_BAD_REQUEST, "Could not find study with global ID of " + globalId); } // StudyLock studyLock = study.getStudyLock(); // if (studyLock != null) { // String message = Util.getStudyLockMessage(studyLock, study.getGlobalId()); // throw new SwordError(UriRegistry.ERROR_BAD_REQUEST, message); // } Long studyId; try { studyId = study.getId(); } catch (NullPointerException ex) { throw new SwordError(UriRegistry.ERROR_BAD_REQUEST, "couldn't find study with global ID of " + globalId); } Dataverse dvThatOwnsStudy = study.getOwner(); if (swordAuth.hasAccessToModifyDataverse(vdcUser, dvThatOwnsStudy)) { // editStudyService.setStudyVersion(studyId); // editStudyService.save(dvThatOwnsStudy.getId(), vdcUser.getId()); // // EditStudyFilesService editStudyFilesService; // try { // editStudyFilesService = (EditStudyFilesService) ctx.lookup("java:comp/env/editStudyFiles"); // } catch (NamingException ex) { // logger.info("problem looking up editStudyFilesService"); // throw new SwordServerException("problem looking up editStudyFilesService"); // } // editStudyFilesService.setStudyVersionByGlobalId(globalId); // List studyFileEditBeans = editStudyFilesService.getCurrentFiles(); List<String> exisitingFilenames = new ArrayList<String>(); // for (Iterator it = studyFileEditBeans.iterator(); it.hasNext();) { // StudyFileEditBean studyFileEditBean = (StudyFileEditBean) it.next(); if (shouldReplace) { // studyFileEditBean.setDeleteFlag(true); // logger.fine("marked for deletion: " + studyFileEditBean.getStudyFile().getFileName()); } else { // String filename = studyFileEditBean.getStudyFile().getFileName(); // exisitingFilenames.add(filename); } } // editStudyFilesService.save(dvThatOwnsStudy.getId(), vdcUser.getId()); if (!deposit.getPackaging().equals(UriRegistry.PACKAGE_SIMPLE_ZIP)) { throw new SwordError(UriRegistry.ERROR_CONTENT, 415, "Package format " + UriRegistry.PACKAGE_SIMPLE_ZIP + " is required but format specified in 'Packaging' HTTP header was " + deposit.getPackaging()); } // Right now we are only supporting UriRegistry.PACKAGE_SIMPLE_ZIP but // in the future maybe we'll support other formats? Rdata files? Stata files? // That's what the uploadDir was going to be for, but for now it's commented out // String importDirString; File importDir; String swordTempDirString = swordConfiguration.getTempDirectory(); if (swordTempDirString == null) { throw new SwordError(UriRegistry.ERROR_BAD_REQUEST, "Could not determine temp directory"); } else { importDirString = swordTempDirString + File.separator + "import" + File.separator + study.getId().toString(); importDir = new File(importDirString); if (!importDir.exists()) { if (!importDir.mkdirs()) { logger.info("couldn't create directory: " + importDir.getAbsolutePath()); throw new SwordServerException("couldn't create import directory"); } } } if (true) { DataFile dFile = new DataFile("application/octet-stream"); dFile.setOwner(study); datasetService.generateFileSystemName(dFile); // if (true) { // throw returnEarly("dataFile.getFileSystemName(): " + dFile.getFileSystemName()); // } InputStream depositInputStream = deposit.getInputStream(); try { Files.copy(depositInputStream, Paths.get(importDirString, dFile.getFileSystemName()), StandardCopyOption.REPLACE_EXISTING); } catch (IOException ex) { throw new SwordError("problem running Files.copy"); } study.getFiles().add(dFile); DatasetVersion editVersion = study.getEditVersion(); // boolean metadataExtracted = false; // try { // metadataExtracted = ingestService.extractIndexableMetadata(importDir.getAbsolutePath() + File.separator + dFile.getFileSystemName(), dFile, editVersion); // } catch (IOException ex) { // throw returnEarly("couldn't extract metadata" + ex); // } FileMetadata fmd = new FileMetadata(); fmd.setDataFile(dFile); fmd.setLabel("myLabel"); fmd.setDatasetVersion(editVersion); dFile.getFileMetadatas().add(fmd); Command<Dataset> cmd; cmd = new UpdateDatasetCommand(study, vdcUser); try { /** * @todo at update time indexing is run but the file is not * indexed. Why? Manually re-indexing later finds it. Fix * this. Related to * https://redmine.hmdc.harvard.edu/issues/3809 ? */ study = commandEngine.submit(cmd); } catch (CommandException ex) { throw returnEarly("couldn't update dataset"); } catch (EJBException ex) { Throwable cause = ex; StringBuilder sb = new StringBuilder(); sb.append(ex.getLocalizedMessage()); while (cause.getCause() != null) { cause = cause.getCause(); sb.append(cause + " "); if (cause instanceof ConstraintViolationException) { ConstraintViolationException constraintViolationException = (ConstraintViolationException) cause; for (ConstraintViolation<?> violation : constraintViolationException.getConstraintViolations()) { sb.append(" Invalid value: <<<").append(violation.getInvalidValue()).append(">>> for ") .append(violation.getPropertyPath()).append(" at ") .append(violation.getLeafBean()).append(" - ") .append(violation.getMessage()); } } } throw returnEarly("EJBException: " + sb.toString()); } } /** * @todo remove this comment after confirming that the upstream jar * now has our bugfix */ // the first character of the filename is truncated with the official jar // so we use include the bug fix at https://github.com/IQSS/swordv2-java-server-library/commit/aeaef83 // and use this jar: https://build.hmdc.harvard.edu:8443/job/swordv2-java-server-library-iqss/2/ String uploadedZipFilename = deposit.getFilename(); ZipInputStream ziStream = new ZipInputStream(deposit.getInputStream()); ZipEntry zEntry; FileOutputStream tempOutStream = null; // List<StudyFileEditBean> fbList = new ArrayList<StudyFileEditBean>(); try { // copied from createStudyFilesFromZip in AddFilesPage while ((zEntry = ziStream.getNextEntry()) != null) { // Note that some zip entries may be directories - we // simply skip them: if (!zEntry.isDirectory()) { String fileEntryName = zEntry.getName(); logger.fine("file found: " + fileEntryName); String dirName = null; String finalFileName = null; int ind = fileEntryName.lastIndexOf('/'); if (ind > -1) { finalFileName = fileEntryName.substring(ind + 1); if (ind > 0) { dirName = fileEntryName.substring(0, ind); dirName = dirName.replace('/', '-'); } } else { finalFileName = fileEntryName; } if (".DS_Store".equals(finalFileName)) { continue; } // http://superuser.com/questions/212896/is-there-any-way-to-prevent-a-mac-from-creating-dot-underscore-files if (finalFileName.startsWith("._")) { continue; } File tempUploadedFile = new File(importDir, finalFileName); tempOutStream = new FileOutputStream(tempUploadedFile); byte[] dataBuffer = new byte[8192]; int i = 0; while ((i = ziStream.read(dataBuffer)) > 0) { tempOutStream.write(dataBuffer, 0, i); tempOutStream.flush(); } tempOutStream.close(); // We now have the unzipped file saved in the upload directory; // zero-length dta files (for example) are skipped during zip // upload in the GUI, so we'll skip them here as well if (tempUploadedFile.length() != 0) { if (true) { // tempUploadedFile; // UploadedFile uFile = tempUploadedFile; // DataFile dataFile = new DataFile(); // throw new SwordError("let's create a file"); } // StudyFileEditBean tempFileBean = new StudyFileEditBean(tempUploadedFile, studyService.generateFileSystemNameSequence(), study); // tempFileBean.setSizeFormatted(tempUploadedFile.length()); String finalFileNameAfterReplace = finalFileName; // if (tempFileBean.getStudyFile() instanceof TabularDataFile) { // predict what the tabular file name will be // finalFileNameAfterReplace = FileUtil.replaceExtension(finalFileName); // } // validateFileName(exisitingFilenames, finalFileNameAfterReplace, study); // And, if this file was in a legit (non-null) directory, // we'll use its name as the file category: if (dirName != null) { // tempFileBean.getFileMetadata().setCategory(dirName); } // fbList.add(tempFileBean); } } else { logger.fine("directory found: " + zEntry.getName()); } } } catch (IOException ex) { throw new SwordError(UriRegistry.ERROR_BAD_REQUEST, "Problem with file: " + uploadedZipFilename); } finally { /** * @todo shouldn't we delete this uploadDir? Commented out in * DVN 3.x */ // if (!uploadDir.delete()) { // logger.fine("Unable to delete " + uploadDir.getAbsolutePath()); // } } // if (fbList.size() > 0) { // StudyFileServiceLocal studyFileService; // try { // studyFileService = (StudyFileServiceLocal) ctx.lookup("java:comp/env/studyFileService"); // } catch (NamingException ex) { // logger.info("problem looking up studyFileService"); // throw new SwordServerException("problem looking up studyFileService"); // } try { // studyFileService.addFiles(study.getLatestVersion(), fbList, vdcUser); } catch (EJBException ex) { throw new SwordError(UriRegistry.ERROR_BAD_REQUEST, "Unable to add file(s) to study: " + ex.getMessage()); } ReceiptGenerator receiptGenerator = new ReceiptGenerator(); String baseUrl = urlManager.getHostnamePlusBaseUrlPath(uri); DepositReceipt depositReceipt = receiptGenerator.createReceipt(baseUrl, study); return depositReceipt; } else { // throw new SwordError(UriRegistry.ERROR_BAD_REQUEST, "Problem with zip file '" + uploadedZipFilename + "'. Number of files unzipped: " + fbList.size()); } // } else { // throw new SwordError(UriRegistry.ERROR_BAD_REQUEST, "user " + vdcUser.getUserName() + " is not authorized to modify study with global ID " + study.getGlobalId()); return new DepositReceipt(); // added just to get this to compile 2014-05-14 } #location 39 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public synchronized String CalculateMD5 (String datafile) { FileInputStream fis = null; try { fis = new FileInputStream(datafile); } catch (FileNotFoundException ex) { throw new RuntimeException(ex); } return CalculateMD5(fis); /* byte[] dataBytes = new byte[1024]; int nread; try { while ((nread = fis.read(dataBytes)) != -1) { md.update(dataBytes, 0, nread); } } catch (IOException ex) { throw new RuntimeException(ex); } byte[] mdbytes = md.digest(); StringBuilder sb = new StringBuilder(""); for (int i = 0; i < mdbytes.length; i++) { sb.append(Integer.toString((mdbytes[i] & 0xff) + 0x100, 16).substring(1)); } return sb.toString(); */ }
#vulnerable code public synchronized String CalculateMD5 (String datafile) { MessageDigest md = null; try { md = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException e) { throw new RuntimeException(e); } FileInputStream fis = null; try { fis = new FileInputStream(datafile); } catch (FileNotFoundException ex) { throw new RuntimeException(ex); } byte[] dataBytes = new byte[1024]; int nread; try { while ((nread = fis.read(dataBytes)) != -1) { md.update(dataBytes, 0, nread); } } catch (IOException ex) { throw new RuntimeException(ex); } byte[] mdbytes = md.digest(); StringBuilder sb = new StringBuilder(""); for (int i = 0; i < mdbytes.length; i++) { sb.append(Integer.toString((mdbytes[i] & 0xff) + 0x100, 16).substring(1)); } return sb.toString(); } #location 26 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public DataModel getDatasetFieldsDataModel() { List values = new ArrayList(); int i = 0; for (DatasetFieldValue dsfv : editVersion.getDatasetFieldValues()){ DatasetField datasetField = dsfv.getDatasetField(); Object[] row = new Object[4]; row[0] = datasetField; row[1] = getValuesDataModel(dsfv); row[2] = new Integer(i); row[3] = datasetField; values.add(row); i++; } return new ListDataModel(values); }
#vulnerable code public DataModel getDatasetFieldsDataModel() { List values = new ArrayList(); int i = 0; for (DatasetFieldValue dsfv : dataset.getEditVersion().getDatasetFieldValues()){ DatasetField datasetField = dsfv.getDatasetField(); Object[] row = new Object[4]; row[0] = datasetField; row[1] = getValuesDataModel(datasetField); row[2] = new Integer(i); row[3] = datasetField; values.add(row); i++; } return new ListDataModel(values); } #location 4 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Test public void testFlowWithLoops() throws Exception { URI resource = getClass().getResource("/yaml/loops/simple_loop.sl").toURI(); URI operation1 = getClass().getResource("/yaml/loops/print.sl").toURI(); Set<SlangSource> path = Sets.newHashSet(SlangSource.fromFile(operation1)); CompilationArtifact compilationArtifact = slang.compile(SlangSource.fromFile(resource), path); Map<String, Serializable> userInputs = new HashMap<>(); Set<SystemProperty> systemProperties = new HashSet<>(); systemProperties.add( SystemProperty.createSystemProperty("loop", "for.prop1", "for_value") ); Map<String, StepData> stepsData = triggerWithData(compilationArtifact, userInputs, systemProperties).getTasks(); StepData firstTask = stepsData.get(FIRST_STEP_PATH); StepData secondTask = stepsData.get(SECOND_STEP_KEY); StepData thirdTask = stepsData.get(THIRD_STEP_KEY); Map<String, Serializable> expectedInputs = new HashMap<>(); expectedInputs.put("text", 1); expectedInputs.put("sp_arg", "for_value"); Assert.assertEquals(expectedInputs, firstTask.getInputs()); expectedInputs.put("text", 2); Assert.assertEquals(expectedInputs, secondTask.getInputs()); expectedInputs.put("text", 3); Assert.assertEquals(expectedInputs, thirdTask.getInputs()); }
#vulnerable code @Test public void testFlowWithLoops() throws Exception { URI resource = getClass().getResource("/yaml/loops/simple_loop.sl").toURI(); URI operation1 = getClass().getResource("/yaml/loops/print.sl").toURI(); Set<SlangSource> path = Sets.newHashSet(SlangSource.fromFile(operation1)); CompilationArtifact compilationArtifact = slang.compile(SlangSource.fromFile(resource), path); Map<String, Serializable> userInputs = new HashMap<>(); Map<String, StepData> stepsData = triggerWithData(compilationArtifact, userInputs, EMPTY_SET).getTasks(); StepData firstTask = stepsData.get(FIRST_STEP_PATH); StepData secondTask = stepsData.get(SECOND_STEP_KEY); StepData thirdTask = stepsData.get(THIRD_STEP_KEY); Assert.assertTrue(firstTask.getInputs().containsValue(1)); Assert.assertTrue(secondTask.getInputs().containsValue(2)); Assert.assertTrue(thirdTask.getInputs().containsValue(3)); } #location 14 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public ReturnValues getExecutionReturnValues(){ // if(StringUtils.isEmpty(result)){ // throw new RuntimeException("Result of executing the test " + testCaseName + " cannot be empty"); // } return new ReturnValues(outputs, result); }
#vulnerable code public ReturnValues getExecutionReturnValues(){ if(StringUtils.isEmpty(result)){ throw new RuntimeException("Result of executing the test " + testCaseName + " cannot be empty"); } if (outputs == null){ outputs = new HashMap<>(); } return new ReturnValues(outputs, result); } #location 2 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Test public void testValidStatementAndTrim() throws Exception { ForLoopStatement statement = transformer.transform(" min in collection "); ListForLoopStatement listForLoopStatement = validateListForLoopStatement(statement); Assert.assertEquals("min", listForLoopStatement.getVarName()); Assert.assertEquals("collection", listForLoopStatement.getCollectionExpression()); }
#vulnerable code @Test public void testValidStatementAndTrim() throws Exception { ForLoopStatement statement = transformer.transform(" min in collection "); Assert.assertEquals(ForLoopStatement.Type.LIST, statement.getType()); Assert.assertEquals("min", statement.getVarName()); Assert.assertEquals("collection", statement.getCollectionExpression()); } #location 4 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Test public void testValidMapStatement() throws Exception { ForLoopStatement statement = transformer.transform("k, v in collection"); MapForLoopStatement mapForLoopStatement = validateMapForLoopStatement(statement); Assert.assertEquals("k", mapForLoopStatement.getKeyName()); Assert.assertEquals("v", mapForLoopStatement.getValueName()); Assert.assertEquals("collection", statement.getCollectionExpression()); }
#vulnerable code @Test public void testValidMapStatement() throws Exception { ForLoopStatement statement = transformer.transform("k, v in collection"); Assert.assertEquals(ForLoopStatement.Type.MAP, statement.getType()); Assert.assertEquals("k v", statement.getVarName()); Assert.assertEquals("collection", statement.getCollectionExpression()); } #location 4 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Test public void testValidStatement() throws Exception { ForLoopStatement statement = transformer.transform("x in collection"); ListForLoopStatement listForLoopStatement = validateListForLoopStatement(statement); Assert.assertEquals("x", listForLoopStatement.getVarName()); Assert.assertEquals("collection", listForLoopStatement.getCollectionExpression()); }
#vulnerable code @Test public void testValidStatement() throws Exception { ForLoopStatement statement = transformer.transform("x in collection"); Assert.assertEquals(ForLoopStatement.Type.LIST, statement.getType()); Assert.assertEquals("x", statement.getVarName()); Assert.assertEquals("collection", statement.getCollectionExpression()); } #location 4 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public static void main(String[] args) { String repositoryPath = System.getProperty("path"); String testsPath = System.getProperty("testPath"); String testSuitsArg = System.getProperty("testSuits"); Validate.notNull(repositoryPath, "You must pass a path to your repository"); repositoryPath = FilenameUtils.separatorsToSystem(repositoryPath); Validate.isTrue(new File(repositoryPath).isDirectory(), "Directory path argument \'" + repositoryPath + "\' does not lead to a directory"); String[] testSuits = null; if(testSuitsArg != null){ testSuits = testSuitsArg.split(","); } ApplicationContext context = new ClassPathXmlApplicationContext("/META-INF/spring/testRunnerContext.xml"); SlangBuild slangBuild = context.getBean(SlangBuild.class); try { int numberOfValidSlangFiles = slangBuild.buildSlangContent(repositoryPath, testsPath, testSuits); System.out.println("SUCCESS: Found " + numberOfValidSlangFiles + " slang files under directory: \"" + repositoryPath + "\" and all are valid."); System.exit(0); } catch (Exception e) { System.out.println(e.getMessage() + "\n\nFAILURE: Validation of slang files under directory: \"" + repositoryPath + "\" failed."); // TODO - do we want to throw exception or exit with 1? System.exit(1); } }
#vulnerable code public static void main(String[] args) { String repositoryPath = System.getProperty("path"); String testsPath = System.getProperty("testPath"); String testSuitsArg = System.getProperty("testSuits"); Validate.notNull(repositoryPath, "You must pass a path to your repository"); repositoryPath = FilenameUtils.separatorsToSystem(repositoryPath); Validate.isTrue(new File(repositoryPath).isDirectory(), "Directory path argument \'" + repositoryPath + "\' does not lead to a directory"); String[] testSuits = null; if(testSuitsArg != null){ testSuits = testSuitsArg.split(","); } ApplicationContext context = new AnnotationConfigApplicationContext(SlangBuildSpringConfiguration.class); SlangBuild slangBuild = context.getBean(SlangBuild.class); try { int numberOfValidSlangFiles = slangBuild.buildSlangContent(repositoryPath, testsPath, testSuits); System.out.println("SUCCESS: Found " + numberOfValidSlangFiles + " slang files under directory: \"" + repositoryPath + "\" and all are valid."); System.exit(0); } catch (Exception e) { System.out.println(e.getMessage() + "\n\nFAILURE: Validation of slang files under directory: \"" + repositoryPath + "\" failed."); // TODO - do we want to throw exception or exit with 1? System.exit(1); } } #location 15 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code private List<RuntimeException> validateModelWithDependencies( Executable executable, Map<String, Executable> dependencies, Set<Executable> verifiedExecutables, List<RuntimeException> errors) { //validate that all required & non private parameters with no default value of a reference are provided if(!SlangTextualKeys.FLOW_TYPE.equals(executable.getType()) || verifiedExecutables.contains(executable)){ return errors; } verifiedExecutables.add(executable); Flow flow = (Flow) executable; Collection<Step> steps = flow.getWorkflow().getSteps(); Set<Executable> flowReferences = new HashSet<>(); for (Step step : steps) { String refId = step.getRefId(); Executable reference = dependencies.get(refId); try { validateMandatoryInputsAreWired(flow, step, reference); validateStepInputNamesDifferentFromDependencyOutputNames(flow, step, reference); validateDependenciesResultsHaveMatchingNavigations(executable, refId, step, reference); } catch (RuntimeException e) { errors.add(e); } flowReferences.add(reference); } for (Executable reference : flowReferences) { validateModelWithDependencies(reference, dependencies, verifiedExecutables, errors); } return errors; }
#vulnerable code private List<RuntimeException> validateModelWithDependencies( Executable executable, Map<String, Executable> dependencies, Set<Executable> verifiedExecutables, List<RuntimeException> errors) { //validate that all required & non private parameters with no default value of a reference are provided if(!SlangTextualKeys.FLOW_TYPE.equals(executable.getType()) || verifiedExecutables.contains(executable)){ return errors; } verifiedExecutables.add(executable); Flow flow = (Flow) executable; Collection<Step> steps = flow.getWorkflow().getSteps(); Set<Executable> flowReferences = new HashSet<>(); for (Step step : steps) { String refId = step.getRefId(); Executable reference = dependencies.get(refId); List<String> mandatoryInputNames = getMandatoryInputNames(reference); List<String> stepInputNames = getStepInputNames(step); List<String> inputsNotWired = getInputsNotWired(mandatoryInputNames, stepInputNames); try { validateInputNamesEmpty(inputsNotWired, flow, step, reference); validateStepInputNamesDifferentFromDependencyOutputNames(flow, step, reference); validateDependenciesResultsHaveMatchingNavigations(executable, refId, step, reference); } catch (RuntimeException e) { errors.add(e); } flowReferences.add(reference); } for (Executable reference : flowReferences) { validateModelWithDependencies(reference, dependencies, verifiedExecutables, errors); } return errors; } #location 19 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public List<Value> bindAsyncLoopList( AsyncLoopStatement asyncLoopStatement, Context flowContext, Set<SystemProperty> systemProperties, String nodeName) { Validate.notNull(asyncLoopStatement, "async loop statement cannot be null"); Validate.notNull(flowContext, "flow context cannot be null"); Validate.notNull(systemProperties, "system properties cannot be null"); Validate.notNull(nodeName, "node name cannot be null"); List<Value> result = new ArrayList<>(); try { Value evalResult = scriptEvaluator.evalExpr(asyncLoopStatement.getExpression(), flowContext.getImmutableViewOfVariables(), systemProperties); if (evalResult != null && evalResult.get() != null) { //noinspection unchecked for (Serializable serializable : ((List<Serializable>)evalResult.get())) { Value value = ValueFactory.create(serializable, evalResult.isSensitive()); result.add(value); } } } catch (Throwable t) { throw new RuntimeException(generateAsyncLoopExpressionMessage(nodeName, t.getMessage()), t); } if (CollectionUtils.isEmpty(result)) { throw new RuntimeException(generateAsyncLoopExpressionMessage(nodeName, "expression is empty")); } return result; }
#vulnerable code public List<Value> bindAsyncLoopList( AsyncLoopStatement asyncLoopStatement, Context flowContext, Set<SystemProperty> systemProperties, String nodeName) { Validate.notNull(asyncLoopStatement, "async loop statement cannot be null"); Validate.notNull(flowContext, "flow context cannot be null"); Validate.notNull(systemProperties, "system properties cannot be null"); Validate.notNull(nodeName, "node name cannot be null"); List<Value> result = new ArrayList<>(); try { Value evalResult = scriptEvaluator.evalExpr(asyncLoopStatement.getExpression(), flowContext.getImmutableViewOfVariables(), systemProperties); if (evalResult.get() != null) { //noinspection unchecked for (Serializable serializable : ((List<Serializable>)evalResult.get())) { Value value = serializable instanceof Value ? (Value)serializable : ValueFactory.create(serializable, evalResult.isSensitive()); result.add(value); } } } catch (Throwable t) { throw new RuntimeException(generateAsyncLoopExpressionMessage(nodeName, t.getMessage()), t); } if (CollectionUtils.isEmpty(result)) { throw new RuntimeException(generateAsyncLoopExpressionMessage(nodeName, "expression is empty")); } return result; } #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 testValues() throws Exception { // compile URI resource = getClass().getResource("/yaml/formats/values_flow.sl").toURI(); URI operation1 = getClass().getResource("/yaml/formats/values_op.sl").toURI(); URI operation2 = getClass().getResource("/yaml/noop.sl").toURI(); SlangSource dep1 = SlangSource.fromFile(operation1); SlangSource dep2 = SlangSource.fromFile(operation2); Set<SlangSource> path = Sets.newHashSet(dep1, dep2); CompilationArtifact compilationArtifact = slang.compile(SlangSource.fromFile(resource), path); // trigger Map<String, StepData> steps = prepareAndRun(compilationArtifact); // verify StepData flowData = steps.get(EXEC_START_PATH); StepData stepData = steps.get(FIRST_STEP_PATH); verifyExecutableInputs(flowData); verifyExecutableOutputs(flowData); verifyStepInputs(stepData); verifySuccessResult(flowData); }
#vulnerable code @Test public void testValues() throws Exception { // compile URI resource = getClass().getResource("/yaml/formats/values_flow.sl").toURI(); URI operation1 = getClass().getResource("/yaml/formats/values_op.sl").toURI(); URI operation2 = getClass().getResource("/yaml/noop.sl").toURI(); SlangSource dep1 = SlangSource.fromFile(operation1); SlangSource dep2 = SlangSource.fromFile(operation2); Set<SlangSource> path = Sets.newHashSet(dep1, dep2); CompilationArtifact compilationArtifact = slang.compile(SlangSource.fromFile(resource), path); // trigger Map<String, StepData> steps = prepareAndRun(compilationArtifact); // verify StepData flowData = steps.get(EXEC_START_PATH); StepData stepData = steps.get(FIRST_STEP_PATH); verifyExecutableInputs(flowData); verifyExecutableOutputs(flowData); verifyStepInputs(stepData); verifyStepPublishValues(stepData); verifySuccessResult(flowData); } #location 23 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Test public void testMultipleInsAreTrimmed() throws Exception { ForLoopStatement statement = transformer.transform(" in in in "); ListForLoopStatement listForLoopStatement = validateListForLoopStatement(statement); Assert.assertEquals("in", listForLoopStatement.getCollectionExpression()); }
#vulnerable code @Test public void testMultipleInsAreTrimmed() throws Exception { ForLoopStatement statement = transformer.transform(" in in in "); Assert.assertEquals("in", statement.getVarName()); Assert.assertEquals("in", statement.getCollectionExpression()); } #location 4 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Test public void testValidMapStatementAndTrimMultipleWhitSpaces() throws Exception { ForLoopStatement statement = transformer.transform(" k, v in collection "); MapForLoopStatement mapForLoopStatement = validateMapForLoopStatement(statement); Assert.assertEquals("k", mapForLoopStatement.getKeyName()); Assert.assertEquals("v", mapForLoopStatement.getValueName()); Assert.assertEquals("collection", statement.getCollectionExpression()); }
#vulnerable code @Test public void testValidMapStatementAndTrimMultipleWhitSpaces() throws Exception { ForLoopStatement statement = transformer.transform(" k, v in collection "); Assert.assertEquals(ForLoopStatement.Type.MAP, statement.getType()); Assert.assertEquals("k v", statement.getVarName()); Assert.assertEquals("collection", statement.getCollectionExpression()); } #location 4 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public void beginTask(@Param(ScoreLangConstants.TASK_INPUTS_KEY) List<Input> taskInputs, @Param(ScoreLangConstants.LOOP_KEY) LoopStatement loop, @Param(ScoreLangConstants.RUN_ENV) RunEnvironment runEnv, @Param(EXECUTION_RUNTIME_SERVICES) ExecutionRuntimeServices executionRuntimeServices, @Param(ScoreLangConstants.NODE_NAME_KEY) String nodeName, @Param(ExecutionParametersConsts.RUNNING_EXECUTION_PLAN_ID) Long RUNNING_EXECUTION_PLAN_ID, @Param(ScoreLangConstants.NEXT_STEP_ID_KEY) Long nextStepId, @Param(ScoreLangConstants.REF_ID) String refId) { try { startStepExecutionPathCalc(runEnv); runEnv.removeCallArguments(); runEnv.removeReturnValues(); Context flowContext = runEnv.getStack().popContext(); Map<String, Serializable> flowVariables = flowContext.getImmutableViewOfVariables(); fireEvent(executionRuntimeServices, runEnv, ScoreLangConstants.EVENT_INPUT_START, "Task inputs start Binding", Pair.of(LanguageEventData.BOUND_INPUTS,(Serializable)retrieveInputs(taskInputs)), Pair.of( LanguageEventData.levelName.TASK_NAME.name(), nodeName)); //loops if (loopStatementExist(loop)) { LoopCondition loopCondition = loopsBinding.getOrCreateLoopCondition(loop, flowContext, nodeName); if (!loopCondition.hasMore()) { runEnv.putNextStepPosition(nextStepId); runEnv.getStack().pushContext(flowContext); return; } if (loopCondition instanceof ForLoopCondition) { ForLoopCondition forLoopCondition = (ForLoopCondition) loopCondition; if (loop instanceof ListForLoopStatement) { // normal iteration String varName = ((ListForLoopStatement) loop).getVarName(); loopsBinding.incrementListForLoop(varName, flowContext, forLoopCondition); } else { // map iteration MapForLoopStatement mapForLoopStatement = (MapForLoopStatement) loop; String keyName = mapForLoopStatement.getKeyName(); String valueName = mapForLoopStatement.getValueName(); loopsBinding.incrementMapForLoop(keyName, valueName, flowContext, forLoopCondition); } } } // Map<String, Serializable> flowVariables = flowContext.getImmutableViewOfVariables(); Map<String, Serializable> operationArguments = inputsBinding.bindInputs(taskInputs, flowVariables, runEnv.getSystemProperties()); //todo: hook sendBindingInputsEvent(taskInputs, operationArguments, runEnv, executionRuntimeServices, "Task inputs resolved", nodeName, LanguageEventData.levelName.TASK_NAME); updateCallArgumentsAndPushContextToStack(runEnv, flowContext, operationArguments); // request the score engine to switch to the execution plan of the given ref requestSwitchToRefExecutableExecutionPlan(runEnv, executionRuntimeServices, RUNNING_EXECUTION_PLAN_ID, refId, nextStepId); // set the start step of the given ref as the next step to execute (in the new running execution plan that will be set) runEnv.putNextStepPosition(executionRuntimeServices.getSubFlowBeginStep(refId)); // runEnv.getExecutionPath().down(); } catch (RuntimeException e) { logger.error("There was an error running the begin task execution step of: \'" + nodeName + "\'. Error is: " + e.getMessage()); throw new RuntimeException("Error running: " + nodeName + ": " + e.getMessage(), e); } }
#vulnerable code public void beginTask(@Param(ScoreLangConstants.TASK_INPUTS_KEY) List<Input> taskInputs, @Param(ScoreLangConstants.LOOP_KEY) LoopStatement loop, @Param(ScoreLangConstants.RUN_ENV) RunEnvironment runEnv, @Param(EXECUTION_RUNTIME_SERVICES) ExecutionRuntimeServices executionRuntimeServices, @Param(ScoreLangConstants.NODE_NAME_KEY) String nodeName, @Param(ExecutionParametersConsts.RUNNING_EXECUTION_PLAN_ID) Long RUNNING_EXECUTION_PLAN_ID, @Param(ScoreLangConstants.NEXT_STEP_ID_KEY) Long nextStepId, @Param(ScoreLangConstants.REF_ID) String refId) { try { runEnv.getExecutionPath().forward(); runEnv.removeCallArguments(); runEnv.removeReturnValues(); Context flowContext = runEnv.getStack().popContext(); //loops if (loopStatementExist(loop)) { LoopCondition loopCondition = loopsBinding.getOrCreateLoopCondition(loop, flowContext, nodeName); if (!loopCondition.hasMore()) { runEnv.putNextStepPosition(nextStepId); runEnv.getStack().pushContext(flowContext); return; } if (loopCondition instanceof ForLoopCondition) { ForLoopCondition forLoopCondition = (ForLoopCondition) loopCondition; if (loop instanceof ListForLoopStatement) { // normal iteration String varName = ((ListForLoopStatement) loop).getVarName(); loopsBinding.incrementListForLoop(varName, flowContext, forLoopCondition); } else { // map iteration MapForLoopStatement mapForLoopStatement = (MapForLoopStatement) loop; String keyName = mapForLoopStatement.getKeyName(); String valueName = mapForLoopStatement.getValueName(); loopsBinding.incrementMapForLoop(keyName, valueName, flowContext, forLoopCondition); } } } Map<String, Serializable> flowVariables = flowContext.getImmutableViewOfVariables(); Map<String, Serializable> operationArguments = inputsBinding.bindInputs(taskInputs, flowVariables, runEnv.getSystemProperties()); //todo: hook sendBindingInputsEvent(taskInputs, operationArguments, runEnv, executionRuntimeServices, "Task inputs resolved", nodeName, LanguageEventData.levelName.TASK_NAME); updateCallArgumentsAndPushContextToStack(runEnv, flowContext, operationArguments); // request the score engine to switch to the execution plan of the given ref requestSwitchToRefExecutableExecutionPlan(runEnv, executionRuntimeServices, RUNNING_EXECUTION_PLAN_ID, refId, nextStepId); // set the start step of the given ref as the next step to execute (in the new running execution plan that will be set) runEnv.putNextStepPosition(executionRuntimeServices.getSubFlowBeginStep(refId)); runEnv.getExecutionPath().down(); } catch (RuntimeException e) { logger.error("There was an error running the begin task execution step of: \'" + nodeName + "\'. Error is: " + e.getMessage()); throw new RuntimeException("Error running: " + nodeName + ": " + e.getMessage(), e); } } #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 testValues() throws Exception { // compile URI resource = getClass().getResource("/yaml/sensitive/sensitive_values_op.sl").toURI(); CompilationArtifact compilationArtifact = slang.compile(SlangSource.fromFile(resource), new HashSet<SlangSource>()); // trigger Map<String, StepData> steps = prepareAndRun(compilationArtifact); // verify StepData flowData = steps.get(EXEC_START_PATH); verifyInOutParams(flowData.getInputs()); verifyInOutParams(flowData.getOutputs()); }
#vulnerable code @Test public void testValues() throws Exception { // compile URI resource = getClass().getResource("/yaml/sensitive/sensitive_values_op.sl").toURI(); CompilationArtifact compilationArtifact = slang.compile(SlangSource.fromFile(resource), new HashSet<SlangSource>()); // trigger Map<String, StepData> steps = prepareAndRun(compilationArtifact); // verify StepData flowData = steps.get(EXEC_START_PATH); StepData stepData = steps.get(FIRST_STEP_PATH); verifyInOutParams(flowData.getInputs()); verifyInOutParams(flowData.getOutputs()); verifyInOutParams(stepData.getInputs()); verifyInOutParams(stepData.getOutputs()); verifySuccessResult(flowData); } #location 16 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public ReturnValues getExecutionReturnValues(){ // if(StringUtils.isEmpty(result)){ // throw new RuntimeException("Result of executing the test " + testCaseName + " cannot be empty"); // } return new ReturnValues(outputs, result); }
#vulnerable code public ReturnValues getExecutionReturnValues(){ if(StringUtils.isEmpty(result)){ throw new RuntimeException("Result of executing the test " + testCaseName + " cannot be empty"); } if (outputs == null){ outputs = new HashMap<>(); } return new ReturnValues(outputs, result); } #location 6 #vulnerability type THREAD_SAFETY_VIOLATION
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Test(timeout = DEFAULT_TIMEOUT) public void doJavaActionSetKeyOnNonSerializableSessionTest() { //prepare doAction arguments RunEnvironment runEnv = new RunEnvironment(); HashMap<String, Object> nonSerializableExecutionData = new HashMap<>(); GlobalSessionObject<ContentTestActions.NonSerializableObject> sessionObject = new GlobalSessionObject<>(); ContentTestActions.NonSerializableObject employee = new ContentTestActions.NonSerializableObject("John"); sessionObject.setResource(new ContentTestActions.NonSerializableSessionResource(employee)); nonSerializableExecutionData.put("name", sessionObject); Map<String, Serializable> initialCallArguments = new HashMap<>(); initialCallArguments.put("value", "David"); runEnv.putCallArguments(initialCallArguments); //invoke doAction actionSteps.doAction(runEnv, nonSerializableExecutionData, JAVA, ContentTestActions.class.getName(), "setNameOnNonSerializableSession", executionRuntimeServicesMock, null, 2L); Assert.assertTrue(nonSerializableExecutionData.containsKey("name")); @SuppressWarnings("unchecked") GlobalSessionObject<ContentTestActions.NonSerializableObject> updatedSessionObject = (GlobalSessionObject<ContentTestActions.NonSerializableObject>) nonSerializableExecutionData.get("name"); ContentTestActions.NonSerializableObject nonSerializableObject = updatedSessionObject.get(); String actualName = nonSerializableObject.getName(); Assert.assertEquals("David", actualName); }
#vulnerable code @Test(timeout = DEFAULT_TIMEOUT) public void doJavaActionSetKeyOnNonSerializableSessionTest() { //prepare doAction arguments RunEnvironment runEnv = new RunEnvironment(); HashMap<String, Object> nonSerializableExecutionData = new HashMap<>(); GlobalSessionObject<ContentTestActions.NonSerializableObject> sessionObject = new GlobalSessionObject<>(); ContentTestActions.NonSerializableObject employee = new ContentTestActions.NonSerializableObject("John"); sessionObject.setResource(new ContentTestActions.NonSerializableSessionResource(employee)); nonSerializableExecutionData.put("name", sessionObject); Map<String, Serializable> initialCallArguments = new HashMap<>(); initialCallArguments.put("value", "David"); runEnv.putCallArguments(initialCallArguments); //invoke doAction actionSteps.doAction(runEnv, nonSerializableExecutionData, JAVA, ContentTestActions.class.getName(), "setNameOnNonSerializableSession", executionRuntimeServicesMock, null, 2L); Map<String, Serializable> outputs = runEnv.removeReturnValues().getOutputs(); Assert.assertTrue(outputs.containsKey("name")); Assert.assertEquals("David", outputs.get("name")); } #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 testValidMapStatementWithoutSpaceAfterComma() throws Exception { ForLoopStatement statement = transformer.transform("k,v in collection"); MapForLoopStatement mapForLoopStatement = validateMapForLoopStatement(statement); Assert.assertEquals("k", mapForLoopStatement.getKeyName()); Assert.assertEquals("v", mapForLoopStatement.getValueName()); Assert.assertEquals("collection", statement.getCollectionExpression()); }
#vulnerable code @Test public void testValidMapStatementWithoutSpaceAfterComma() throws Exception { ForLoopStatement statement = transformer.transform("k,v in collection"); Assert.assertEquals(ForLoopStatement.Type.MAP, statement.getType()); Assert.assertEquals("k v", statement.getVarName()); Assert.assertEquals("collection", statement.getCollectionExpression()); } #location 4 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Test public void testFlowWithLoopsWithCustomNavigation() throws Exception { URI resource = getClass().getResource("/yaml/loops/loop_with_custom_navigation.sl").toURI(); URI operation1 = getClass().getResource("/yaml/loops/print.sl").toURI(); Set<SlangSource> path = Sets.newHashSet(SlangSource.fromFile(operation1)); CompilationArtifact compilationArtifact = slang.compile(SlangSource.fromFile(resource), path); Map<String, Serializable> userInputs = new HashMap<>(); Map<String, StepData> stepsData = triggerWithData(compilationArtifact, userInputs, EMPTY_SET).getSteps(); StepData thirdStep = stepsData.get(THIRD_STEP_KEY); Assert.assertEquals("print_other_values", thirdStep.getName()); }
#vulnerable code @Test public void testFlowWithLoopsWithCustomNavigation() throws Exception { URI resource = getClass().getResource("/yaml/loops/loop_with_custom_navigation.sl").toURI(); URI operation1 = getClass().getResource("/yaml/loops/print.sl").toURI(); Set<SlangSource> path = Sets.newHashSet(SlangSource.fromFile(operation1)); CompilationArtifact compilationArtifact = slang.compile(SlangSource.fromFile(resource), path); Map<String, Serializable> userInputs = new HashMap<>(); Map<String, StepData> stepsData = triggerWithData(compilationArtifact, userInputs, EMPTY_SET).getSteps(); StepData thirdTask = stepsData.get(THIRD_STEP_KEY); Assert.assertEquals("print_other_values", thirdTask.getName()); } #location 12 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Test public void testFunctionsBasic() throws Exception { URL resource = getClass().getResource("/yaml/functions/functions_test_flow.sl"); URI operation = getClass().getResource("/yaml/functions/functions_test_op.sl").toURI(); Set<SlangSource> path = Sets.newHashSet(SlangSource.fromFile(operation)); CompilationArtifact compilationArtifact = slang.compile(SlangSource.fromFile(resource.toURI()), path); Map<String, Serializable> userInputs = prepareUserInputs(); Set<SystemProperty> systemProperties = prepareSystemProperties(); // trigger ExecutionPlan RuntimeInformation runtimeInformation = triggerWithData(compilationArtifact, userInputs, systemProperties); Map<String, StepData> executionData = runtimeInformation.getTasks(); StepData flowData = executionData.get(EXEC_START_PATH); StepData taskData = executionData.get(FIRST_STEP_PATH); Assert.assertNotNull("flow data is null", flowData); Assert.assertNotNull("task data is null", taskData); verifyFlowInputs(flowData); verifyTaskArguments(taskData); verifyTaskPublishValues(taskData); verifyFlowOutputs(flowData); // verify 'get' function worked in result expressions Assert.assertEquals("Function evaluation problem in result expression", "FUNCTIONS_KEY_EXISTS", flowData.getResult()); }
#vulnerable code @Test public void testFunctionsBasic() throws Exception { URL resource = getClass().getResource("/yaml/functions/functions_test_flow.sl"); URI operation = getClass().getResource("/yaml/functions/functions_test_op.sl").toURI(); Set<SlangSource> path = Sets.newHashSet(SlangSource.fromFile(operation)); CompilationArtifact compilationArtifact = slang.compile(SlangSource.fromFile(resource.toURI()), path); Map<String, Serializable> userInputs = prepareUserInputs(); Set<SystemProperty> systemProperties = prepareSystemProperties(); // trigger ExecutionPlan RuntimeInformation runtimeInformation = triggerWithData(compilationArtifact, userInputs, systemProperties); Map<String, StepData> executionData = runtimeInformation.getTasks(); StepData flowData = executionData.get(EXEC_START_PATH); StepData taskData = executionData.get(FIRST_STEP_PATH); Assert.assertNotNull("flow data is null", flowData); Assert.assertNotNull("task data is null", taskData); verifyFlowInputs(flowData); verifyTaskArguments(taskData); verifyTaskPublishValues(taskData); // verify 'get' function worked in result expressions Assert.assertEquals("Function evaluation problem in result expression", "FUNCTIONS_KEY_EXISTS", flowData.getResult()); } #location 26 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public Long trigger(SlangTestCase testCase, CompilationArtifact compilationArtifact, Map<String, ? extends Serializable> inputs, Map<String, ? extends Serializable> systemProperties) { String testCaseName = testCase.getName(); String result = testCase.getResult(); //add start event Set<String> handlerTypes = new HashSet<>(); handlerTypes.add(ScoreLangConstants.EVENT_EXECUTION_FINISHED); handlerTypes.add(ScoreLangConstants.SLANG_EXECUTION_EXCEPTION); handlerTypes.add(ScoreLangConstants.EVENT_OUTPUT_END); handlerTypes.add(EventConstants.SCORE_ERROR_EVENT); handlerTypes.add(EventConstants.SCORE_FAILURE_EVENT); handlerTypes.add(EventConstants.SCORE_FINISHED_EVENT); TriggerTestCaseEventListener testsEventListener = new TriggerTestCaseEventListener(testCaseName, result); slang.subscribeOnEvents(testsEventListener, handlerTypes); Long executionId = slang.run(compilationArtifact, inputs, systemProperties); while (!testsEventListener.isFlowFinished()) { try { Thread.sleep(200); } catch (InterruptedException ignore) {} } slang.unSubscribeOnEvents(testsEventListener); ReturnValues executionReturnValues = testsEventListener.getExecutionReturnValues(); String executionResult = executionReturnValues.getResult(); String errorMessageFlowExecution = testsEventListener.getErrorMessage(); if (BooleanUtils.isTrue(testCase.getThrowsException())) { if(StringUtils.isBlank(errorMessageFlowExecution)) { throw new RuntimeException("Failed test: " + testCaseName + " - " + testCase.getDescription() + "\nFlow " + compilationArtifact.getExecutionPlan().getName() +" did not throw an exception as expected"); } return executionId; } if(StringUtils.isNotBlank(errorMessageFlowExecution)){ // unexpected exception occurred during flow execution throw new RuntimeException("Error occured while running test: " + testCaseName + " - " + testCase.getDescription() + "\n" + errorMessageFlowExecution); } if (result != null && !result.equals(executionResult)){ throw new RuntimeException("Failed test: " + testCaseName +" - " + testCase.getDescription() + "\nExpected result: " + result + "\nActual result: " + executionResult); } return executionId; }
#vulnerable code public Long trigger(SlangTestCase testCase, CompilationArtifact compilationArtifact, Map<String, ? extends Serializable> inputs, Map<String, ? extends Serializable> systemProperties) { String testCaseName = testCase.getName(); String result = testCase.getResult(); //add start event Set<String> handlerTypes = new HashSet<>(); handlerTypes.add(ScoreLangConstants.EVENT_EXECUTION_FINISHED); handlerTypes.add(ScoreLangConstants.SLANG_EXECUTION_EXCEPTION); handlerTypes.add(ScoreLangConstants.EVENT_OUTPUT_END); handlerTypes.add(EventConstants.SCORE_ERROR_EVENT); handlerTypes.add(EventConstants.SCORE_FAILURE_EVENT); handlerTypes.add(EventConstants.SCORE_FINISHED_EVENT); TriggerTestCaseEventListener testsEventListener = new TriggerTestCaseEventListener(testCaseName, result); slang.subscribeOnEvents(testsEventListener, handlerTypes); Long executionId = slang.run(compilationArtifact, inputs, systemProperties); while (!testsEventListener.isFlowFinished()) { try { Thread.sleep(200); } catch (InterruptedException ignore) {} } slang.unSubscribeOnEvents(testsEventListener); ReturnValues executionReturnValues = testsEventListener.getExecutionReturnValues(); String executionResult = executionReturnValues.getResult(); String errorMessageFlowExecution = testsEventListener.getErrorMessage(); if(StringUtils.isBlank(errorMessageFlowExecution) && BooleanUtils.isTrue(testCase.getThrowsException())){ throw new RuntimeException("Failed test: " + testCaseName + " - " + testCase.getDescription() + "\nFlow " + compilationArtifact.getExecutionPlan().getName() +" did not throw an exception as expected"); } if(StringUtils.isNotBlank(errorMessageFlowExecution) && BooleanUtils.isFalse(testCase.getThrowsException())){ // unexpected exception occurred during flow execution throw new RuntimeException("Error occured while running test: " + testCaseName + " - " + testCase.getDescription() + "\n" + errorMessageFlowExecution); } if (result != null && !executionResult.equals(result)){ throw new RuntimeException("Failed test: " + testCaseName +" - " + testCase.getDescription() + "\nExpected result: " + result + "\nActual result: " + executionResult); } return executionId; } #location 41 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Test public void testFlowWithMapLoopsWithCustomNavigation() throws Exception { URI resource = getClass().getResource("/yaml/loops/loop_with_custom_navigation_with_map.sl").toURI(); URI operation1 = getClass().getResource("/yaml/loops/print.sl").toURI(); Set<SlangSource> path = Sets.newHashSet(SlangSource.fromFile(operation1)); CompilationArtifact compilationArtifact = slang.compile(SlangSource.fromFile(resource), path); Map<String, Serializable> userInputs = new HashMap<>(); Map<String, StepData> stepsData = triggerWithData(compilationArtifact, userInputs, EMPTY_SET).getSteps(); StepData fourthStep = stepsData.get(FOURTH_STEP_KEY); Assert.assertEquals("print_other_values", fourthStep.getName()); }
#vulnerable code @Test public void testFlowWithMapLoopsWithCustomNavigation() throws Exception { URI resource = getClass().getResource("/yaml/loops/loop_with_custom_navigation_with_map.sl").toURI(); URI operation1 = getClass().getResource("/yaml/loops/print.sl").toURI(); Set<SlangSource> path = Sets.newHashSet(SlangSource.fromFile(operation1)); CompilationArtifact compilationArtifact = slang.compile(SlangSource.fromFile(resource), path); Map<String, Serializable> userInputs = new HashMap<>(); Map<String, StepData> stepsData = triggerWithData(compilationArtifact, userInputs, EMPTY_SET).getSteps(); StepData fourthTask = stepsData.get(FOURTH_STEP_KEY); Assert.assertEquals("print_other_values", fourthTask.getName()); } #location 12 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public void joinBranches(@Param(ScoreLangConstants.RUN_ENV) RunEnvironment runEnv, @Param(EXECUTION_RUNTIME_SERVICES) ExecutionRuntimeServices executionRuntimeServices, @Param(ScoreLangConstants.TASK_AGGREGATE_KEY) List<Output> taskAggregateValues, @Param(ScoreLangConstants.TASK_NAVIGATION_KEY) Map<String, ResultNavigation> taskNavigationValues, @Param(ScoreLangConstants.NODE_NAME_KEY) String nodeName) { try { List<Map<String, Serializable>> branchesContext = Lists.newArrayList(); Context flowContext = runEnv.getStack().popContext(); Map<String, Serializable> contextBeforeSplit = flowContext.getImmutableViewOfVariables(); List<String> branchesResult = Lists.newArrayList(); collectBranchesData(runEnv, executionRuntimeServices, nodeName, branchesContext, branchesResult); Map<String, Serializable> publishValues = bindAggregateOutputs( runEnv, executionRuntimeServices, taskAggregateValues, (Serializable) taskNavigationValues, nodeName, (Serializable) branchesContext, contextBeforeSplit ); flowContext.putVariables(publishValues); String asyncLoopResult = getAsyncLoopResult(branchesResult); handleNavigationAndReturnValues(runEnv, executionRuntimeServices, taskNavigationValues, nodeName, publishValues, asyncLoopResult); runEnv.getStack().pushContext(flowContext); } catch (RuntimeException e) { logger.error("There was an error running the end task execution step of: \'" + nodeName + "\'. Error is: " + e.getMessage()); throw new RuntimeException("Error running: \'" + nodeName + "\': " + e.getMessage(), e); } }
#vulnerable code public void joinBranches(@Param(ScoreLangConstants.RUN_ENV) RunEnvironment runEnv, @Param(EXECUTION_RUNTIME_SERVICES) ExecutionRuntimeServices executionRuntimeServices, @Param(ScoreLangConstants.TASK_AGGREGATE_KEY) List<Output> taskAggregateValues, @Param(ScoreLangConstants.TASK_NAVIGATION_KEY) Map<String, ResultNavigation> taskNavigationValues, @Param(ScoreLangConstants.NODE_NAME_KEY) String nodeName) { try { List<EndBranchDataContainer> branches = executionRuntimeServices.getFinishedChildBranchesData(); List<Map<String, Serializable>> branchesContext = Lists.newArrayList(); Context flowContext = runEnv.getStack().popContext(); Map<String, Serializable> contextBeforeSplit = flowContext.getImmutableViewOfVariables(); List<String> branchesResult = Lists.newArrayList(); for (EndBranchDataContainer branch : branches) { Map<String, Serializable> branchContext = branch.getContexts(); RunEnvironment branchRuntimeEnvironment = (RunEnvironment) branchContext.get(ScoreLangConstants.RUN_ENV); branchesContext.add(branchRuntimeEnvironment.getStack().popContext().getImmutableViewOfVariables()); ReturnValues executableReturnValues = branchRuntimeEnvironment.removeReturnValues(); branchesResult.add(executableReturnValues.getResult()); fireEvent( executionRuntimeServices, runEnv, ScoreLangConstants.EVENT_BRANCH_END, "async loop branch ended", Pair.of(RuntimeConstants.BRANCH_RETURN_VALUES_KEY, executableReturnValues), Pair.of(LanguageEventData.levelName.TASK_NAME.name(), nodeName) ); } Map<String, Serializable> aggregateContext = new HashMap<>(); aggregateContext.put(RuntimeConstants.BRANCHES_CONTEXT_KEY, (Serializable) branchesContext); fireEvent( executionRuntimeServices, runEnv, ScoreLangConstants.EVENT_ASYNC_LOOP_OUTPUT_START, "Async loop output binding started", Pair.of(ScoreLangConstants.TASK_AGGREGATE_KEY, (Serializable) taskAggregateValues), Pair.of(ScoreLangConstants.TASK_NAVIGATION_KEY, (Serializable) taskNavigationValues), Pair.of(LanguageEventData.levelName.TASK_NAME.name(), nodeName)); Map<String, Serializable> publishValues = outputsBinding.bindOutputs(contextBeforeSplit, aggregateContext, taskAggregateValues); flowContext.putVariables(publishValues); // if one of the branches failed then return with FAILURE, otherwise return with SUCCESS String asyncLoopResult = ScoreLangConstants.SUCCESS_RESULT; for (String branchResult : branchesResult) { if (branchResult.equals(ScoreLangConstants.FAILURE_RESULT)) { asyncLoopResult = ScoreLangConstants.FAILURE_RESULT; break; } } // set the position of the next step - for the use of the navigation // find in the navigation values the correct next step position, according to the async loop result, and set it ResultNavigation navigation = taskNavigationValues.get(asyncLoopResult); if (navigation == null) { // should always have the executable response mapped to a navigation by the task, if not, it is an error throw new RuntimeException("Task: " + nodeName + " has no matching navigation for the async loop result: " + asyncLoopResult); } Long nextStepPosition = navigation.getNextStepId(); String presetResult = navigation.getPresetResult(); HashMap<String, Serializable> outputs = new HashMap<>(publishValues); ReturnValues returnValues = new ReturnValues(outputs, presetResult != null ? presetResult : asyncLoopResult); fireEvent( executionRuntimeServices, runEnv, ScoreLangConstants.EVENT_ASYNC_LOOP_OUTPUT_END, "Async loop output binding finished", Pair.of(LanguageEventData.OUTPUTS, (Serializable) publishValues), Pair.of(LanguageEventData.RESULT, returnValues.getResult()), Pair.of(LanguageEventData.NEXT_STEP_POSITION, nextStepPosition), Pair.of(LanguageEventData.levelName.TASK_NAME.name(), nodeName)); runEnv.getStack().pushContext(flowContext); runEnv.putReturnValues(returnValues); runEnv.putNextStepPosition(nextStepPosition); } catch (RuntimeException e) { logger.error("There was an error running the end task execution step of: \'" + nodeName + "\'. Error is: " + e.getMessage()); throw new RuntimeException("Error running: \'" + nodeName + "\': " + e.getMessage(), e); } } #location 21 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Test public void testValidMapStatementAndTrim() throws Exception { ForLoopStatement statement = transformer.transform(" k, v in collection "); MapForLoopStatement mapForLoopStatement = validateMapForLoopStatement(statement); Assert.assertEquals("k", mapForLoopStatement.getKeyName()); Assert.assertEquals("v", mapForLoopStatement.getValueName()); Assert.assertEquals("collection", statement.getCollectionExpression()); }
#vulnerable code @Test public void testValidMapStatementAndTrim() throws Exception { ForLoopStatement statement = transformer.transform(" k, v in collection "); Assert.assertEquals(ForLoopStatement.Type.MAP, statement.getType()); Assert.assertEquals("k v", statement.getVarName()); Assert.assertEquals("collection", statement.getCollectionExpression()); } #location 4 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Test public void testStepPublishValues() throws Exception { URL resource = getClass().getResource("/yaml/binding_scope_flow.sl"); URI operation = getClass().getResource("/yaml/binding_scope_op.sl").toURI(); Set<SlangSource> path = Sets.newHashSet(SlangSource.fromFile(operation)); CompilationArtifact compilationArtifact = slang.compile(SlangSource.fromFile(resource.toURI()), path); Map<String, Value> userInputs = Collections.emptyMap(); Set<SystemProperty> systemProperties = Collections.emptySet(); // trigger ExecutionPlan RuntimeInformation runtimeInformation = triggerWithData(compilationArtifact, userInputs, systemProperties); Map<String, StepData> executionData = runtimeInformation.getSteps(); StepData stepData = executionData.get(FIRST_STEP_PATH); Assert.assertNotNull("step data is null", stepData); }
#vulnerable code @Test public void testStepPublishValues() throws Exception { URL resource = getClass().getResource("/yaml/binding_scope_flow.sl"); URI operation = getClass().getResource("/yaml/binding_scope_op.sl").toURI(); Set<SlangSource> path = Sets.newHashSet(SlangSource.fromFile(operation)); CompilationArtifact compilationArtifact = slang.compile(SlangSource.fromFile(resource.toURI()), path); Map<String, Value> userInputs = Collections.emptyMap(); Set<SystemProperty> systemProperties = Collections.emptySet(); // trigger ExecutionPlan RuntimeInformation runtimeInformation = triggerWithData(compilationArtifact, userInputs, systemProperties); Map<String, StepData> executionData = runtimeInformation.getSteps(); StepData stepData = executionData.get(FIRST_STEP_PATH); Assert.assertNotNull("step data is null", stepData); verifyStepPublishValues(stepData); } #location 19 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Test public void testValidMapStatementSpaceBeforeComma() throws Exception { ForLoopStatement statement = transformer.transform("k ,v in collection"); MapForLoopStatement mapForLoopStatement = validateMapForLoopStatement(statement); Assert.assertEquals("k", mapForLoopStatement.getKeyName()); Assert.assertEquals("v", mapForLoopStatement.getValueName()); Assert.assertEquals("collection", statement.getCollectionExpression()); }
#vulnerable code @Test public void testValidMapStatementSpaceBeforeComma() throws Exception { ForLoopStatement statement = transformer.transform("k ,v in collection"); Assert.assertEquals(ForLoopStatement.Type.MAP, statement.getType()); Assert.assertEquals("k v", statement.getVarName()); Assert.assertEquals("collection", statement.getCollectionExpression()); } #location 4 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Test public void testValues() throws Exception { // compile URI resource = getClass().getResource("/yaml/formats/values_flow.sl").toURI(); URI operation1 = getClass().getResource("/yaml/formats/values_op.sl").toURI(); URI operation2 = getClass().getResource("/yaml/noop.sl").toURI(); SlangSource dep1 = SlangSource.fromFile(operation1); SlangSource dep2 = SlangSource.fromFile(operation2); Set<SlangSource> path = Sets.newHashSet(dep1, dep2); CompilationArtifact compilationArtifact = slang.compile(SlangSource.fromFile(resource), path); // trigger Map<String, StepData> steps = prepareAndRun(compilationArtifact); // verify StepData flowData = steps.get(EXEC_START_PATH); StepData taskData = steps.get(FIRST_STEP_PATH); verifyExecutableInputs(flowData); verifyExecutableOutputs(flowData); verifyTaskInputs(taskData); verifyTaskPublishValues(taskData); verifySuccessResult(flowData); }
#vulnerable code @Test public void testValues() throws Exception { // compile URI resource = getClass().getResource("/yaml/formats/values_flow.sl").toURI(); URI operation1 = getClass().getResource("/yaml/formats/values_op.sl").toURI(); URI operation2 = getClass().getResource("/yaml/noop.sl").toURI(); SlangSource dep1 = SlangSource.fromFile(operation1); SlangSource dep2 = SlangSource.fromFile(operation2); Set<SlangSource> path = Sets.newHashSet(dep1, dep2); CompilationArtifact compilationArtifact = slang.compile(SlangSource.fromFile(resource), path); // trigger Map<String, StepData> steps = prepareAndRun(compilationArtifact); // verify StepData flowData = steps.get(EXEC_START_PATH); StepData taskData = steps.get(FIRST_STEP_PATH); StepData oneLinerTaskData = steps.get(SECOND_STEP_KEY); verifyExecutableInputs(flowData); verifyExecutableOutputs(flowData); verifyTaskInputs(taskData); verifyTaskPublishValues(taskData); verifyOneLinerInputs(oneLinerTaskData); verifySuccessResult(flowData); } #location 25 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Test public void testFlowWithMapLoopsWithCustomNavigation() throws Exception { URI resource = getClass().getResource("/yaml/loops/loop_with_custom_navigation_with_map.sl").toURI(); URI operation1 = getClass().getResource("/yaml/loops/print.sl").toURI(); Set<SlangSource> path = Sets.newHashSet(SlangSource.fromFile(operation1)); CompilationArtifact compilationArtifact = slang.compile(SlangSource.fromFile(resource), path); Map<String, Serializable> userInputs = new HashMap<>(); Map<String, StepData> stepsData = triggerWithData(compilationArtifact, userInputs, null); StepData fourthTask = stepsData.get(FOURTH_STEP_KEY); Assert.assertEquals("print_other_values", fourthTask.getName()); }
#vulnerable code @Test public void testFlowWithMapLoopsWithCustomNavigation() throws Exception { URI resource = getClass().getResource("/yaml/loops/loop_with_custom_navigation_with_map.sl").toURI(); URI operation1 = getClass().getResource("/yaml/loops/print.sl").toURI(); Set<SlangSource> path = Sets.newHashSet(SlangSource.fromFile(operation1)); CompilationArtifact compilationArtifact = slang.compile(SlangSource.fromFile(resource), path); Map<String, Serializable> userInputs = new HashMap<>(); Map<String, StepData> stepsData = triggerWithData(compilationArtifact, userInputs, null); StepData thirdTask = stepsData.get(FOURTH_STEP_KEY); Assert.assertEquals("print_other_values", thirdTask.getName()); } #location 12 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Test public void testValidMapStatementWithExpression() throws Exception { ForLoopStatement statement = transformer.transform("k, v in dictionary.items()"); MapForLoopStatement mapForLoopStatement = validateMapForLoopStatement(statement); Assert.assertEquals("k", mapForLoopStatement.getKeyName()); Assert.assertEquals("v", mapForLoopStatement.getValueName()); Assert.assertEquals("dictionary.items()", statement.getCollectionExpression()); }
#vulnerable code @Test public void testValidMapStatementWithExpression() throws Exception { ForLoopStatement statement = transformer.transform("k, v in dictionary.items()"); Assert.assertEquals(ForLoopStatement.Type.MAP, statement.getType()); Assert.assertEquals("k v", statement.getVarName()); Assert.assertEquals("dictionary.items()", statement.getCollectionExpression()); } #location 4 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code private List<StepData> buildBranchesData(List<LanguageEventData> data) { List<StepData> branches = Lists.newArrayList(); for (LanguageEventData branchData : data) { String path = branchData.getPath(); String stepName = branchData.getStepName(); branches.add( new StepData( path, stepName, new HashMap<String, Value>(), new HashMap<String, Value>(), null, (String)branchData.get(LanguageEventData.RESULT) ) ); } return branches; }
#vulnerable code private List<StepData> buildBranchesData(List<LanguageEventData> data) { List<StepData> branches = Lists.newArrayList(); for (LanguageEventData branchData : data) { String path = branchData.getPath(); String stepName = branchData.getStepName(); ReturnValues returnValues = (ReturnValues) branchData.get(RuntimeConstants.BRANCH_RETURN_VALUES_KEY); branches.add( new StepData( path, stepName, new HashMap<String, Value>(), returnValues.getOutputs(), null, returnValues.getResult() ) ); } return branches; } #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 testFlowWithLoops() throws Exception { URI resource = getClass().getResource("/yaml/loops/simple_loop.sl").toURI(); URI operation1 = getClass().getResource("/yaml/loops/print.sl").toURI(); Set<SlangSource> path = Sets.newHashSet(SlangSource.fromFile(operation1)); CompilationArtifact compilationArtifact = slang.compile(SlangSource.fromFile(resource), path); Map<String, Serializable> userInputs = new HashMap<>(); Set<SystemProperty> systemProperties = new HashSet<>(); systemProperties.add( SystemProperty.createSystemProperty("loop", "for.prop1", "for_value") ); Map<String, StepData> stepsData = triggerWithData(compilationArtifact, userInputs, systemProperties).getTasks(); StepData firstTask = stepsData.get(FIRST_STEP_PATH); StepData secondTask = stepsData.get(SECOND_STEP_KEY); StepData thirdTask = stepsData.get(THIRD_STEP_KEY); Map<String, Serializable> expectedInputs = new HashMap<>(); expectedInputs.put("text", 1); expectedInputs.put("sp_arg", "for_value"); Assert.assertEquals(expectedInputs, firstTask.getInputs()); expectedInputs.put("text", 2); Assert.assertEquals(expectedInputs, secondTask.getInputs()); expectedInputs.put("text", 3); Assert.assertEquals(expectedInputs, thirdTask.getInputs()); }
#vulnerable code @Test public void testFlowWithLoops() throws Exception { URI resource = getClass().getResource("/yaml/loops/simple_loop.sl").toURI(); URI operation1 = getClass().getResource("/yaml/loops/print.sl").toURI(); Set<SlangSource> path = Sets.newHashSet(SlangSource.fromFile(operation1)); CompilationArtifact compilationArtifact = slang.compile(SlangSource.fromFile(resource), path); Map<String, Serializable> userInputs = new HashMap<>(); Map<String, StepData> stepsData = triggerWithData(compilationArtifact, userInputs, EMPTY_SET).getTasks(); StepData firstTask = stepsData.get(FIRST_STEP_PATH); StepData secondTask = stepsData.get(SECOND_STEP_KEY); StepData thirdTask = stepsData.get(THIRD_STEP_KEY); Assert.assertTrue(firstTask.getInputs().containsValue(1)); Assert.assertTrue(secondTask.getInputs().containsValue(2)); Assert.assertTrue(thirdTask.getInputs().containsValue(3)); } #location 16 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Test public void testValidStatementWithSpaces() throws Exception { ForLoopStatement statement = transformer.transform("x in range(0, 9)"); ListForLoopStatement listForLoopStatement = validateListForLoopStatement(statement); Assert.assertEquals("x", listForLoopStatement.getVarName()); Assert.assertEquals("range(0, 9)", listForLoopStatement.getCollectionExpression()); }
#vulnerable code @Test public void testValidStatementWithSpaces() throws Exception { ForLoopStatement statement = transformer.transform("x in range(0, 9)"); Assert.assertEquals(ForLoopStatement.Type.LIST, statement.getType()); Assert.assertEquals("x", statement.getVarName()); Assert.assertEquals("range(0, 9)", statement.getCollectionExpression()); } #location 4 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Test public void testFlowWithLoopsWithBreak() throws Exception { URI resource = getClass().getResource("/yaml/loops/loop_with_break.sl").toURI(); URI operation1 = getClass().getResource("/yaml/loops/operation_that_goes_to_custom_when_value_is_2.sl").toURI(); URI operation2 = getClass().getResource("/yaml/loops/print.sl").toURI(); Set<SlangSource> path = Sets.newHashSet(SlangSource.fromFile(operation1), SlangSource.fromFile(operation2)); CompilationArtifact compilationArtifact = slang.compile(SlangSource.fromFile(resource), path); Map<String, Serializable> userInputs = new HashMap<>(); Map<String, StepData> stepsData = triggerWithData(compilationArtifact, userInputs, EMPTY_SET).getSteps(); List<String> actualSteps = getStepsOnly(stepsData); Assert.assertEquals(3, actualSteps.size()); StepData thirdStep = stepsData.get(THIRD_STEP_KEY); Assert.assertEquals("print_other_values", thirdStep.getName()); }
#vulnerable code @Test public void testFlowWithLoopsWithBreak() throws Exception { URI resource = getClass().getResource("/yaml/loops/loop_with_break.sl").toURI(); URI operation1 = getClass().getResource("/yaml/loops/operation_that_goes_to_custom_when_value_is_2.sl").toURI(); URI operation2 = getClass().getResource("/yaml/loops/print.sl").toURI(); Set<SlangSource> path = Sets.newHashSet(SlangSource.fromFile(operation1), SlangSource.fromFile(operation2)); CompilationArtifact compilationArtifact = slang.compile(SlangSource.fromFile(resource), path); Map<String, Serializable> userInputs = new HashMap<>(); Map<String, StepData> stepsData = triggerWithData(compilationArtifact, userInputs, EMPTY_SET).getSteps(); List<String> actualTasks = getTasksOnly(stepsData); Assert.assertEquals(3, actualTasks.size()); StepData thirdTask = stepsData.get(THIRD_STEP_KEY); Assert.assertEquals("print_other_values", thirdTask.getName()); } #location 15 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code private List<RuntimeException> validateModelWithDependencies( Executable executable, Map<String, Executable> dependencies, Set<Executable> verifiedExecutables, List<RuntimeException> errors) { //validate that all required & non private parameters with no default value of a reference are provided if(!SlangTextualKeys.FLOW_TYPE.equals(executable.getType()) || verifiedExecutables.contains(executable)){ return errors; } verifiedExecutables.add(executable); Flow flow = (Flow) executable; Collection<Step> steps = flow.getWorkflow().getSteps(); Set<Executable> flowReferences = new HashSet<>(); for (Step step : steps) { Executable reference = dependencies.get(step.getRefId()); errors.addAll(validateStepAgainstItsDependency(flow, step, dependencies)); flowReferences.add(reference); } for (Executable reference : flowReferences) { validateModelWithDependencies(reference, dependencies, verifiedExecutables, errors); } return errors; }
#vulnerable code private List<RuntimeException> validateModelWithDependencies( Executable executable, Map<String, Executable> dependencies, Set<Executable> verifiedExecutables, List<RuntimeException> errors) { //validate that all required & non private parameters with no default value of a reference are provided if(!SlangTextualKeys.FLOW_TYPE.equals(executable.getType()) || verifiedExecutables.contains(executable)){ return errors; } verifiedExecutables.add(executable); Flow flow = (Flow) executable; Collection<Step> steps = flow.getWorkflow().getSteps(); Set<Executable> flowReferences = new HashSet<>(); for (Step step : steps) { String refId = step.getRefId(); Executable reference = dependencies.get(refId); try { validateMandatoryInputsAreWired(flow, step, reference); validateStepInputNamesDifferentFromDependencyOutputNames(flow, step, reference); validateDependenciesResultsHaveMatchingNavigations(executable, refId, step, reference); } catch (RuntimeException e) { errors.add(e); } flowReferences.add(reference); } for (Executable reference : flowReferences) { validateModelWithDependencies(reference, dependencies, verifiedExecutables, errors); } return errors; } #location 21 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public void contextInitialized(ServletContextEvent servletContextEvent) { final ServletContext servletContext = servletContextEvent.getServletContext(); stopThreads = ! "false".equals(servletContext.getInitParameter("ClassLoaderLeakPreventor.stopThreads")); stopTimerThreads = ! "false".equals(servletContext.getInitParameter("ClassLoaderLeakPreventor.stopTimerThreads")); executeShutdownHooks = ! "false".equals(servletContext.getInitParameter("ClassLoaderLeakPreventor.executeShutdownHooks")); threadWaitMs = getIntInitParameter(servletContext, "ClassLoaderLeakPreventor.threadWaitMs", THREAD_WAIT_MS_DEFAULT); shutdownHookWaitMs = getIntInitParameter(servletContext, "ClassLoaderLeakPreventor.shutdownHookWaitMs", SHUTDOWN_HOOK_WAIT_MS_DEFAULT); info("Settings for " + this.getClass().getName() + ":"); info(" stopThreads = " + stopThreads); info(" stopTimerThreads = " + stopTimerThreads); info(" executeShutdownHooks = " + executeShutdownHooks); info(" threadWaitMs = " + threadWaitMs + " ms"); info(" shutdownHookWaitMs = " + shutdownHookWaitMs + " ms"); info("Initializing context by loading some known offenders with system classloader"); // This part is heavily inspired by Tomcats JreMemoryLeakPreventionListener // See http://svn.apache.org/viewvc/tomcat/trunk/java/org/apache/catalina/core/JreMemoryLeakPreventionListener.java?view=markup final ClassLoader contextClassLoader = Thread.currentThread().getContextClassLoader(); try { // Switch to system classloader in before we load/call some JRE stuff that will cause // the current classloader to be available for gerbage collection Thread.currentThread().setContextClassLoader(ClassLoader.getSystemClassLoader()); java.awt.Toolkit.getDefaultToolkit(); // Will start a Thread java.security.Security.getProviders(); java.sql.DriverManager.getDrivers(); // Load initial drivers using system classloader javax.imageio.ImageIO.getCacheDirectory(); // Will call sun.awt.AppContext.getAppContext() try { Class.forName("javax.security.auth.Policy") .getMethod("getPolicy") .invoke(null); } catch (IllegalAccessException iaex) { error(iaex); } catch (InvocationTargetException itex) { error(itex); } catch (NoSuchMethodException nsmex) { error(nsmex); } catch (ClassNotFoundException e) { // Ignore silently - class is deprecated } try { javax.xml.parsers.DocumentBuilderFactory.newInstance().newDocumentBuilder(); } catch (ParserConfigurationException pcex) { error(pcex); } try { Class.forName("javax.security.auth.login.Configuration", true, ClassLoader.getSystemClassLoader()); } catch (ClassNotFoundException e) { // Do nothing } // This probably does not affect classloaders, but prevents some problems with .jar files try { // URL needs to be well-formed, but does not need to exist new URL("jar:file://dummy.jar!/").openConnection().setDefaultUseCaches(false); } catch (Exception ex) { error(ex); } ///////////////////////////////////////////////////// // Load Sun specific classes that may cause leaks final boolean isSunJRE = System.getProperty("java.vendor").startsWith("Sun"); try { Class.forName("com.sun.jndi.ldap.LdapPoolManager"); } catch(ClassNotFoundException cnfex) { if(isSunJRE) error(cnfex); } try { Class.forName("sun.java2d.Disposer"); // Will start a Thread } catch (ClassNotFoundException cnfex) { if(isSunJRE) error(cnfex); } try { Class<?> gcClass = Class.forName("sun.misc.GC"); final Method requestLatency = gcClass.getDeclaredMethod("requestLatency", long.class); requestLatency.invoke(null, 3600000L); } catch (ClassNotFoundException cnfex) { if(isSunJRE) error(cnfex); } catch (NoSuchMethodException nsmex) { error(nsmex); } catch (IllegalAccessException iaex) { error(iaex); } catch (InvocationTargetException itex) { error(itex); } } finally { // Reset original classloader Thread.currentThread().setContextClassLoader(contextClassLoader); } }
#vulnerable code public void contextInitialized(ServletContextEvent servletContextEvent) { info(getClass().getName() + " initializing context by loading some known offenders with system classloader"); // This part is heavily inspired by Tomcats JreMemoryLeakPreventionListener // See http://svn.apache.org/viewvc/tomcat/trunk/java/org/apache/catalina/core/JreMemoryLeakPreventionListener.java?view=markup final ClassLoader contextClassLoader = Thread.currentThread().getContextClassLoader(); try { // Switch to system classloader in before we load/call some JRE stuff that will cause // the current classloader to be available for gerbage collection Thread.currentThread().setContextClassLoader(ClassLoader.getSystemClassLoader()); java.awt.Toolkit.getDefaultToolkit(); // Will start a Thread java.security.Security.getProviders(); java.sql.DriverManager.getDrivers(); // Load initial drivers using system classloader javax.imageio.ImageIO.getCacheDirectory(); // Will call sun.awt.AppContext.getAppContext() try { Class.forName("javax.security.auth.Policy") .getMethod("getPolicy") .invoke(null); } catch (IllegalAccessException iaex) { error(iaex); } catch (InvocationTargetException itex) { error(itex); } catch (NoSuchMethodException nsmex) { error(nsmex); } catch (ClassNotFoundException e) { // Ignore silently - class is deprecated } try { javax.xml.parsers.DocumentBuilderFactory.newInstance().newDocumentBuilder(); } catch (ParserConfigurationException pcex) { error(pcex); } try { Class.forName("javax.security.auth.login.Configuration", true, ClassLoader.getSystemClassLoader()); } catch (ClassNotFoundException e) { // Do nothing } // This probably does not affect classloaders, but prevents some problems with .jar files try { // URL needs to be well-formed, but does not need to exist new URL("jar:file://dummy.jar!/").openConnection().setDefaultUseCaches(false); } catch (Exception ex) { error(ex); } ///////////////////////////////////////////////////// // Load Sun specific classes that may cause leaks final boolean isSunJRE = System.getProperty("java.vendor").startsWith("Sun"); try { Class.forName("com.sun.jndi.ldap.LdapPoolManager"); } catch(ClassNotFoundException cnfex) { if(isSunJRE) error(cnfex); } try { Class.forName("sun.java2d.Disposer"); // Will start a Thread } catch (ClassNotFoundException cnfex) { if(isSunJRE) error(cnfex); } try { Class<?> gcClass = Class.forName("sun.misc.GC"); final Method requestLatency = gcClass.getDeclaredMethod("requestLatency", long.class); requestLatency.invoke(null, 3600000L); } catch (ClassNotFoundException cnfex) { if(isSunJRE) error(cnfex); } catch (NoSuchMethodException nsmex) { error(nsmex); } catch (IllegalAccessException iaex) { error(iaex); } catch (InvocationTargetException itex) { error(itex); } } finally { // Reset original classloader Thread.currentThread().setContextClassLoader(contextClassLoader); } } #location 65 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public void testRetryForResult() { // Given retry for null exec = new AsyncExecution(callable, new RetryPolicy().retryWhen(null), scheduler, future, null); // When / Then assertFalse(exec.complete(null)); assertTrue(exec.retryFor(null)); exec.prepare(); assertFalse(exec.retryFor(1)); // Then assertEquals(exec.getExecutions(), 2); assertTrue(exec.isComplete()); assertEquals(exec.getLastResult(), Integer.valueOf(1)); assertNull(exec.getLastFailure()); verifyScheduler(1); verify(future).complete(1, null, true); // Given 2 max retries exec = new AsyncExecution(callable, new RetryPolicy().retryWhen(null).withMaxRetries(1), scheduler, future, null); // When / Then resetMocks(); assertFalse(exec.complete(null)); exec.prepare(); assertTrue(exec.retryFor(null)); exec.prepare(); assertFalse(exec.retryFor(null)); // Then assertEquals(exec.getExecutions(), 2); assertTrue(exec.isComplete()); assertNull(exec.getLastResult()); assertNull(exec.getLastFailure()); verifyScheduler(1); verify(future).complete(null, null, false); }
#vulnerable code public void testRetryForResult() { // Given retry for null inv = new AsyncExecution(callable, new RetryPolicy().retryWhen(null), scheduler, future, null); // When / Then assertFalse(inv.complete(null)); assertTrue(inv.retryFor(null)); inv.prepare(); assertFalse(inv.retryFor(1)); // Then assertEquals(inv.getExecutions(), 2); assertTrue(inv.isComplete()); assertEquals(inv.getLastResult(), Integer.valueOf(1)); assertNull(inv.getLastFailure()); verifyScheduler(1); verify(future).complete(1, null, true); // Given 2 max retries inv = new AsyncExecution(callable, new RetryPolicy().retryWhen(null).withMaxRetries(1), scheduler, future, null); // When / Then resetMocks(); assertFalse(inv.complete(null)); inv.prepare(); assertTrue(inv.retryFor(null)); inv.prepare(); assertFalse(inv.retryFor(null)); // Then assertEquals(inv.getExecutions(), 2); assertTrue(inv.isComplete()); assertNull(inv.getLastResult()); assertNull(inv.getLastFailure()); verifyScheduler(1); verify(future).complete(null, null, false); } #location 8 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @SuppressWarnings("unchecked") public void testRetryOn() { // Given retry on IllegalArgumentException exec = new AsyncExecution(callable, new RetryPolicy().retryOn(IllegalArgumentException.class), scheduler, future, null); // When / Then assertTrue(exec.retryOn(new IllegalArgumentException())); exec.prepare(); assertFalse(exec.retryOn(e)); // Then assertEquals(exec.getExecutions(), 2); assertTrue(exec.isComplete()); assertNull(exec.getLastResult()); assertEquals(exec.getLastFailure(), e); verifyScheduler(1); verify(future).complete(null, e, false); // Given 2 max retries exec = new AsyncExecution(callable, new RetryPolicy().withMaxRetries(1), scheduler, future, null); // When / Then resetMocks(); assertTrue(exec.retryOn(e)); exec.prepare(); assertFalse(exec.retryOn(e)); // Then assertEquals(exec.getExecutions(), 2); assertTrue(exec.isComplete()); assertNull(exec.getLastResult()); assertEquals(exec.getLastFailure(), e); verifyScheduler(1); verify(future).complete(null, e, false); }
#vulnerable code @SuppressWarnings("unchecked") public void testRetryOn() { // Given retry on IllegalArgumentException inv = new AsyncExecution(callable, new RetryPolicy().retryOn(IllegalArgumentException.class), scheduler, future, null); // When / Then assertTrue(inv.retryOn(new IllegalArgumentException())); inv.prepare(); assertFalse(inv.retryOn(e)); // Then assertEquals(inv.getExecutions(), 2); assertTrue(inv.isComplete()); assertNull(inv.getLastResult()); assertEquals(inv.getLastFailure(), e); verifyScheduler(1); verify(future).complete(null, e, false); // Given 2 max retries inv = new AsyncExecution(callable, new RetryPolicy().withMaxRetries(1), scheduler, future, null); // When / Then resetMocks(); assertTrue(inv.retryOn(e)); inv.prepare(); assertFalse(inv.retryOn(e)); // Then assertEquals(inv.getExecutions(), 2); assertTrue(inv.isComplete()); assertNull(inv.getLastResult()); assertEquals(inv.getLastFailure(), e); verifyScheduler(1); verify(future).complete(null, e, false); } #location 9 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @SuppressWarnings({ "rawtypes", "unchecked" }) private void assertGetFuture(Object callable) throws Throwable { // Fail twice then succeed when(service.connect()).thenThrow(failures(2, SocketException.class)).thenReturn(true); boolean result = (boolean) (callable instanceof Callable ? Recurrent.future((Callable) callable, new RetryPolicy(), executor).get() : Recurrent.future((ContextualCallable) callable, new RetryPolicy(), executor).get()); assertEquals(result, true); verify(service, times(3)).connect(); // Fail three times reset(service); when(service.connect()).thenThrow(failures(10, SocketException.class)).thenReturn(true); Throwable failure = callable instanceof Callable ? getThrowable(() -> Recurrent.future((Callable) callable, retryTwice, executor).get()) : getThrowable(() -> Recurrent.future((ContextualCallable) callable, retryTwice, executor).get()); assertMatches(failure, futureAsyncThrowables); verify(service, times(3)).connect(); }
#vulnerable code @SuppressWarnings({ "rawtypes", "unchecked" }) private void assertGetFuture(Object callable) throws Throwable { // Fail twice then succeed when(service.connect()).thenThrow(failures(2, SocketException.class)).thenReturn(true); boolean result = (boolean) (callable instanceof Callable ? Recurrent.future((Callable) callable, new RetryPolicy(), executor).get() : Recurrent.future((ContextualCallable) callable, new RetryPolicy(), executor).get()); assertEquals(result, true); verify(service, times(3)).connect(); // Fail three times reset(service); when(service.connect()).thenThrow(failures(10, SocketException.class)).thenReturn(true); Throwable failure = callable instanceof Callable ? getThrowable(() -> Recurrent.future((Callable) callable, retryTwice, executor).get()) : getThrowable(() -> Recurrent.future((ContextualCallable) callable, retryTwice, executor).get()); assertTrue(SocketException.class.isAssignableFrom(failure.getClass())); verify(service, times(3)).connect(); } #location 17 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public void testRetryForResultAndThrowable() { // Given retry for null exec = new AsyncExecution(callable, new RetryPolicy().retryWhen(null), scheduler, future, null); // When / Then assertFalse(exec.complete(null)); assertTrue(exec.retryFor(null, null)); exec.prepare(); assertTrue(exec.retryFor(1, new IllegalArgumentException())); exec.prepare(); assertFalse(exec.retryFor(1, null)); // Then assertEquals(exec.getExecutions(), 3); assertTrue(exec.isComplete()); assertEquals(exec.getLastResult(), Integer.valueOf(1)); assertNull(exec.getLastFailure()); verifyScheduler(2); verify(future).complete(1, null, true); // Given 2 max retries exec = new AsyncExecution(callable, new RetryPolicy().retryWhen(null).withMaxRetries(1), scheduler, future, null); // When / Then resetMocks(); assertFalse(exec.complete(null)); assertTrue(exec.retryFor(null, e)); exec.prepare(); assertFalse(exec.retryFor(null, e)); // Then assertEquals(exec.getExecutions(), 2); assertTrue(exec.isComplete()); assertNull(exec.getLastResult()); assertEquals(exec.getLastFailure(), e); verifyScheduler(1); verify(future).complete(null, e, false); }
#vulnerable code public void testRetryForResultAndThrowable() { // Given retry for null inv = new AsyncExecution(callable, new RetryPolicy().retryWhen(null), scheduler, future, null); // When / Then assertFalse(inv.complete(null)); assertTrue(inv.retryFor(null, null)); inv.prepare(); assertTrue(inv.retryFor(1, new IllegalArgumentException())); inv.prepare(); assertFalse(inv.retryFor(1, null)); // Then assertEquals(inv.getExecutions(), 3); assertTrue(inv.isComplete()); assertEquals(inv.getLastResult(), Integer.valueOf(1)); assertNull(inv.getLastFailure()); verifyScheduler(2); verify(future).complete(1, null, true); // Given 2 max retries inv = new AsyncExecution(callable, new RetryPolicy().retryWhen(null).withMaxRetries(1), scheduler, future, null); // When / Then resetMocks(); assertFalse(inv.complete(null)); assertTrue(inv.retryFor(null, e)); inv.prepare(); assertFalse(inv.retryFor(null, e)); // Then assertEquals(inv.getExecutions(), 2); assertTrue(inv.isComplete()); assertNull(inv.getLastResult()); assertEquals(inv.getLastFailure(), e); verifyScheduler(1); verify(future).complete(null, e, false); } #location 8 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public void testCompleteOrRetry() { // Given retry on IllegalArgumentException exec = new AsyncExecution(callable, scheduler, future, configFor(new RetryPolicy())); // When / Then exec.completeOrRetry(null, e); assertFalse(exec.isComplete()); exec.before(); exec.completeOrRetry(null, null); // Then assertEquals(exec.getExecutions(), 2); assertTrue(exec.isComplete()); assertNull(exec.getLastResult()); assertNull(exec.getLastFailure()); verifyScheduler(1); verify(future).complete(null, null, null, true); }
#vulnerable code public void testCompleteOrRetry() { // Given retry on IllegalArgumentException exec = new AsyncExecution(callable, scheduler, future, configFor(new RetryPolicy())); // When / Then exec.completeOrRetry(null, e); assertFalse(exec.isComplete()); exec.before(); exec.completeOrRetry(null, null); // Then assertEquals(exec.getExecutions(), 2); assertTrue(exec.isComplete()); assertNull(exec.getLastResult()); assertNull(exec.getLastFailure()); verifyScheduler(1); verify(future).complete(null, null, null); } #location 8 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @SuppressWarnings("unchecked") public void testRetryOn() { // Given retry on IllegalArgumentException exec = new AsyncExecution(callable, scheduler, future, configFor(new RetryPolicy().retryOn(IllegalArgumentException.class))); // When / Then assertTrue(exec.retryOn(new IllegalArgumentException())); exec.before(); assertFalse(exec.retryOn(e)); // Then assertEquals(exec.getExecutions(), 2); assertTrue(exec.isComplete()); assertNull(exec.getLastResult()); assertEquals(exec.getLastFailure(), e); verifyScheduler(1); verify(future).complete(null, e, null, false); // Given 2 max retries exec = new AsyncExecution(callable, scheduler, future, configFor(new RetryPolicy().withMaxRetries(1))); // When / Then resetMocks(); assertTrue(exec.retryOn(e)); exec.before(); assertFalse(exec.retryOn(e)); // Then assertEquals(exec.getExecutions(), 2); assertTrue(exec.isComplete()); assertNull(exec.getLastResult()); assertEquals(exec.getLastFailure(), e); verifyScheduler(1); verify(future).complete(null, e, null, false); }
#vulnerable code @SuppressWarnings("unchecked") public void testRetryOn() { // Given retry on IllegalArgumentException exec = new AsyncExecution(callable, scheduler, future, configFor(new RetryPolicy().retryOn(IllegalArgumentException.class))); // When / Then assertTrue(exec.retryOn(new IllegalArgumentException())); exec.before(); assertFalse(exec.retryOn(e)); // Then assertEquals(exec.getExecutions(), 2); assertTrue(exec.isComplete()); assertNull(exec.getLastResult()); assertEquals(exec.getLastFailure(), e); verifyScheduler(1); verify(future).complete(null, e, null); // Given 2 max retries exec = new AsyncExecution(callable, scheduler, future, configFor(new RetryPolicy().withMaxRetries(1))); // When / Then resetMocks(); assertTrue(exec.retryOn(e)); exec.before(); assertFalse(exec.retryOn(e)); // Then assertEquals(exec.getExecutions(), 2); assertTrue(exec.isComplete()); assertNull(exec.getLastResult()); assertEquals(exec.getLastFailure(), e); verifyScheduler(1); verify(future).complete(null, e, null); } #location 9 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public void testGetAttemptCount() { exec = new AsyncExecution(callable, new RetryPolicy(), scheduler, future, null); exec.retryOn(e); exec.prepare(); exec.retryOn(e); assertEquals(exec.getExecutions(), 2); }
#vulnerable code public void testGetAttemptCount() { inv = new AsyncExecution(callable, new RetryPolicy(), scheduler, future, null); inv.retryOn(e); inv.prepare(); inv.retryOn(e); assertEquals(inv.getExecutions(), 2); } #location 4 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Override public void execute() throws MojoExecutionException, MojoFailureException { try { // check uncommitted changes checkUncommittedChanges(); // git for-each-ref --format='%(refname:short)' refs/heads/release/* final String releaseBranch = gitFindBranches( gitFlowConfig.getReleaseBranchPrefix(), false).trim(); if (StringUtils.isBlank(releaseBranch)) { throw new MojoFailureException("There is no release branch."); } else if (StringUtils.countMatches(releaseBranch, gitFlowConfig.getReleaseBranchPrefix()) > 1) { throw new MojoFailureException( "More than one release branch exists. Cannot finish release."); } if (!skipTestProject) { // git checkout release/... gitCheckout(releaseBranch); // mvn clean test mvnCleanTest(); } // git checkout master gitCheckout(gitFlowConfig.getProductionBranch()); // git merge --no-ff release/... gitMergeNoff(releaseBranch); // get current project version from pom final String currentVersion = getCurrentProjectVersion(); if (!skipTag) { String tagVersion = currentVersion; if (tychoBuild && ArtifactUtils.isSnapshot(currentVersion)) { tagVersion = currentVersion.replace("-" + Artifact.SNAPSHOT_VERSION, ""); } // git tag -a ... gitTag(gitFlowConfig.getVersionTagPrefix() + tagVersion, "tagging release"); } // git checkout develop gitCheckout(gitFlowConfig.getDevelopmentBranch()); // git merge --no-ff release/... gitMergeNoff(releaseBranch); String nextSnapshotVersion = null; // get next snapshot version try { final DefaultVersionInfo versionInfo = new DefaultVersionInfo( currentVersion); nextSnapshotVersion = versionInfo.getNextVersion() .getSnapshotVersionString(); } catch (VersionParseException e) { if (getLog().isDebugEnabled()) { getLog().debug(e); } } if (StringUtils.isBlank(nextSnapshotVersion)) { throw new MojoFailureException( "Next snapshot version is blank."); } // mvn versions:set -DnewVersion=... -DgenerateBackupPoms=false mvnSetVersions(nextSnapshotVersion); // git commit -a -m updating for next development version gitCommit("updating for next development version"); if (installProject) { // mvn clean install mvnCleanInstall(); } if (!keepBranch) { // git branch -d release/... gitBranchDelete(releaseBranch); } } catch (CommandLineException e) { getLog().error(e); } }
#vulnerable code @Override public void execute() throws MojoExecutionException, MojoFailureException { try { // check uncommitted changes checkUncommittedChanges(); // git for-each-ref --format='%(refname:short)' refs/heads/release/* final String releaseBranch = gitFindBranches( gitFlowConfig.getReleaseBranchPrefix()).trim(); if (StringUtils.isBlank(releaseBranch)) { throw new MojoFailureException("There is no release branch."); } else if (StringUtils.countMatches(releaseBranch, gitFlowConfig.getReleaseBranchPrefix()) > 1) { throw new MojoFailureException( "More than one release branch exists. Cannot finish release."); } if (!skipTestProject) { // git checkout release/... gitCheckout(releaseBranch); // mvn clean test mvnCleanTest(); } // git checkout master gitCheckout(gitFlowConfig.getProductionBranch()); // git merge --no-ff release/... gitMergeNoff(releaseBranch); // get current project version from pom final String currentVersion = getCurrentProjectVersion(); if (!skipTag) { String tagVersion = currentVersion; if (tychoBuild && ArtifactUtils.isSnapshot(currentVersion)) { tagVersion = currentVersion.replace("-" + Artifact.SNAPSHOT_VERSION, ""); } // git tag -a ... gitTag(gitFlowConfig.getVersionTagPrefix() + tagVersion, "tagging release"); } // git checkout develop gitCheckout(gitFlowConfig.getDevelopmentBranch()); // git merge --no-ff release/... gitMergeNoff(releaseBranch); String nextSnapshotVersion = null; // get next snapshot version try { final DefaultVersionInfo versionInfo = new DefaultVersionInfo( currentVersion); nextSnapshotVersion = versionInfo.getNextVersion() .getSnapshotVersionString(); } catch (VersionParseException e) { if (getLog().isDebugEnabled()) { getLog().debug(e); } } if (StringUtils.isBlank(nextSnapshotVersion)) { throw new MojoFailureException( "Next snapshot version is blank."); } // mvn versions:set -DnewVersion=... -DgenerateBackupPoms=false mvnSetVersions(nextSnapshotVersion); // git commit -a -m updating for next development version gitCommit("updating for next development version"); if (installProject) { // mvn clean install mvnCleanInstall(); } if (!keepBranch) { // git branch -d release/... gitBranchDelete(releaseBranch); } } catch (CommandLineException e) { getLog().error(e); } } #location 9 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Override public void execute() throws MojoExecutionException, MojoFailureException { try { // check uncommitted changes checkUncommittedChanges(); // git for-each-ref --format='%(refname:short)' refs/heads/hotfix/* final String hotfixBranches = executeGitCommandReturn( "for-each-ref", "--format=\"%(refname:short)\"", "refs/heads/" + gitFlowConfig.getHotfixBranchPrefix() + "*"); if (StringUtils.isBlank(hotfixBranches)) { throw new MojoFailureException("There is no hotfix branches."); } String[] branches = hotfixBranches.split("\\r?\\n"); List<String> numberedList = new ArrayList<String>(); StringBuffer str = new StringBuffer( "hotfix branch name to finish: ["); for (int i = 0; i < branches.length; i++) { str.append((i + 1) + ". " + branches[i] + " "); numberedList.add("" + (i + 1)); } str.append("]"); String hotfixNumber = null; try { while (StringUtils.isBlank(hotfixNumber)) { hotfixNumber = prompter .prompt(str.toString(), numberedList); } } catch (PrompterException e) { getLog().error(e); } String hotfixName = null; if (hotfixNumber != null) { int num = Integer.parseInt(hotfixNumber); hotfixName = branches[num - 1]; } if (StringUtils.isBlank(hotfixName)) { throw new MojoFailureException( "Hotfix name to finish is blank."); } // git checkout master executeGitCommand("checkout", gitFlowConfig.getProductionBranch()); // git merge --no-ff hotfix/... executeGitCommand("merge", "--no-ff", hotfixName); // git tag -a ... executeGitCommand( "tag", "-a", gitFlowConfig.getVersionTagPrefix() + hotfixName.replaceFirst( gitFlowConfig.getHotfixBranchPrefix(), ""), "-m", "tagging hotfix"); // check whether release branch exists // git for-each-ref --count=1 --format="%(refname:short)" // refs/heads/release/* final String releaseBranch = executeGitCommandReturn( "for-each-ref", "--count=1", "--format=\"%(refname:short)\"", "refs/heads/" + gitFlowConfig.getReleaseBranchPrefix() + "*"); // if release branch exists merge hotfix changes into it if (StringUtils.isNotBlank(releaseBranch)) { // git checkout release executeGitCommand("checkout", releaseBranch); // git merge --no-ff hotfix/... executeGitCommand("merge", "--no-ff", hotfixName); } else { // git checkout develop executeGitCommand("checkout", gitFlowConfig.getDevelopmentBranch()); // git merge --no-ff hotfix/... executeGitCommand("merge", "--no-ff", hotfixName); // get current project version from pom String currentVersion = getCurrentProjectVersion(); String nextSnapshotVersion = null; // get next snapshot version try { DefaultVersionInfo versionInfo = new DefaultVersionInfo( currentVersion); nextSnapshotVersion = versionInfo.getNextVersion() .getSnapshotVersionString(); } catch (VersionParseException e) { if (getLog().isDebugEnabled()) { getLog().debug(e); } } if (StringUtils.isBlank(nextSnapshotVersion)) { throw new MojoFailureException( "Next snapshot version is blank."); } // mvn versions:set -DnewVersion=... -DgenerateBackupPoms=false executeMvnCommand(VERSIONS_MAVEN_PLUGIN + ":set", "-DnewVersion=" + nextSnapshotVersion, "-DgenerateBackupPoms=false"); // git commit -a -m updating poms for next development version executeGitCommand("commit", "-a", "-m", "updating poms for next development version"); } // git branch -d hotfix/... executeGitCommand("branch", "-d", hotfixName); } catch (CommandLineException e) { e.printStackTrace(); } }
#vulnerable code @Override public void execute() throws MojoExecutionException, MojoFailureException { try { // check uncommitted changes checkUncommittedChanges(); // git for-each-ref --format='%(refname:short)' refs/heads/hotfix/* final String hotfixBranches = executeGitCommandReturn( "for-each-ref", "--format=\"%(refname:short)\"", "refs/heads/" + gitFlowConfig.getHotfixBranchPrefix() + "*"); if (StringUtils.isBlank(hotfixBranches)) { throw new MojoFailureException("There is no hotfix branches."); } String[] branches = hotfixBranches.split("\\r?\\n"); List<String> numberedList = new ArrayList<String>(); StringBuffer str = new StringBuffer( "hotfix branch name to finish: ["); for (int i = 0; i < branches.length; i++) { str.append((i + 1) + ". " + branches[i] + " "); numberedList.add("" + (i + 1)); } str.append("]"); String hotfixNumber = null; try { while (StringUtils.isBlank(hotfixNumber)) { hotfixNumber = prompter .prompt(str.toString(), numberedList); } } catch (PrompterException e) { getLog().error(e); } String hotfixName = null; if (hotfixNumber != null) { int num = Integer.parseInt(hotfixNumber); hotfixName = branches[num - 1]; } if (StringUtils.isBlank(hotfixName)) { throw new MojoFailureException( "Hotfix name to finish is blank."); } // git checkout master executeGitCommand("checkout", gitFlowConfig.getProductionBranch()); // git merge --no-ff hotfix/... executeGitCommand("merge", "--no-ff", hotfixName); // git tag -a ... executeGitCommand( "tag", "-a", gitFlowConfig.getVersionTagPrefix() + hotfixName.replaceFirst( gitFlowConfig.getHotfixBranchPrefix(), ""), "-m", "tagging hotfix"); // check whether release branch exists // git for-each-ref --count=1 --format="%(refname:short)" // refs/heads/release/* final String releaseBranch = executeGitCommandReturn( "for-each-ref", "--count=1", "--format=\"%(refname:short)\"", "refs/heads/" + gitFlowConfig.getReleaseBranchPrefix() + "*"); // if release branch exists merge hotfix changes into it if (StringUtils.isNotBlank(releaseBranch)) { // git checkout release executeGitCommand("checkout", releaseBranch); // git merge --no-ff hotfix/... executeGitCommand("merge", "--no-ff", hotfixName); } else { // git checkout develop executeGitCommand("checkout", gitFlowConfig.getDevelopmentBranch()); // git merge --no-ff hotfix/... executeGitCommand("merge", "--no-ff", hotfixName); String nextSnapshotVersion = null; // get next snapshot version try { DefaultVersionInfo versionInfo = new DefaultVersionInfo( project.getVersion()); nextSnapshotVersion = versionInfo.getNextVersion() .getSnapshotVersionString(); } catch (VersionParseException e) { if (getLog().isDebugEnabled()) { getLog().debug(e); } } if (StringUtils.isBlank(nextSnapshotVersion)) { throw new MojoFailureException( "Next snapshot version is blank."); } // mvn versions:set -DnewVersion=... -DgenerateBackupPoms=false executeMvnCommand(VERSIONS_MAVEN_PLUGIN + ":set", "-DnewVersion=" + nextSnapshotVersion, "-DgenerateBackupPoms=false"); // git commit -a -m updating poms for next development version executeGitCommand("commit", "-a", "-m", "updating poms for next development version"); } // git branch -d hotfix/... executeGitCommand("branch", "-d", hotfixName); } catch (CommandLineException e) { e.printStackTrace(); } } #location 59 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Override public void execute() throws MojoExecutionException, MojoFailureException { try { // check uncommitted changes checkUncommittedChanges(); // git for-each-ref --format='%(refname:short)' refs/heads/release/* final String releaseBranch = gitFindBranches( gitFlowConfig.getReleaseBranchPrefix()).trim(); if (StringUtils.isBlank(releaseBranch)) { throw new MojoFailureException("There is no release branch."); } else if (StringUtils.countMatches(releaseBranch, gitFlowConfig.getReleaseBranchPrefix()) > 1) { throw new MojoFailureException( "More than one release branch exists. Cannot finish release."); } if (!skipTestProject) { // git checkout release/... gitCheckout(releaseBranch); // mvn clean test mvnCleanTest(); } // git checkout master gitCheckout(gitFlowConfig.getProductionBranch()); // git merge --no-ff release/... gitMergeNoff(releaseBranch); // get current project version from pom final String currentVersion = getCurrentProjectVersion(); if (!skipTag) { String tagVersion = currentVersion; if (tychoBuild && ArtifactUtils.isSnapshot(currentVersion)) { tagVersion = currentVersion.replace("-" + Artifact.SNAPSHOT_VERSION, ""); } // git tag -a ... gitTag(gitFlowConfig.getVersionTagPrefix() + tagVersion, "tagging release"); } // git checkout develop gitCheckout(gitFlowConfig.getDevelopmentBranch()); // git merge --no-ff release/... gitMergeNoff(releaseBranch); String nextSnapshotVersion = null; // get next snapshot version try { final DefaultVersionInfo versionInfo = new DefaultVersionInfo( currentVersion); nextSnapshotVersion = versionInfo.getNextVersion() .getSnapshotVersionString(); } catch (VersionParseException e) { if (getLog().isDebugEnabled()) { getLog().debug(e); } } if (StringUtils.isBlank(nextSnapshotVersion)) { throw new MojoFailureException( "Next snapshot version is blank."); } // mvn versions:set -DnewVersion=... -DgenerateBackupPoms=false mvnSetVersions(nextSnapshotVersion); // git commit -a -m updating for next development version gitCommit("updating for next development version"); if (installProject) { // mvn clean install mvnCleanInstall(); } if (!keepBranch) { // git branch -d release/... gitBranchDelete(releaseBranch); } } catch (CommandLineException e) { getLog().error(e); } }
#vulnerable code @Override public void execute() throws MojoExecutionException, MojoFailureException { try { // check uncommitted changes checkUncommittedChanges(); // git for-each-ref --format='%(refname:short)' refs/heads/release/* final String releaseBranches = gitFindBranches(gitFlowConfig .getReleaseBranchPrefix()); String releaseVersion = null; if (StringUtils.isBlank(releaseBranches)) { throw new MojoFailureException("There is no release branch."); } else if (StringUtils.countMatches(releaseBranches, gitFlowConfig.getReleaseBranchPrefix()) > 1) { throw new MojoFailureException( "More than one release branch exists. Cannot finish release."); } else { releaseVersion = releaseBranches.trim().substring( releaseBranches.lastIndexOf(gitFlowConfig .getReleaseBranchPrefix()) + gitFlowConfig.getReleaseBranchPrefix() .length()); } if (StringUtils.isBlank(releaseVersion)) { throw new MojoFailureException("Release version is blank."); } if (!skipTestProject) { // git checkout release/... gitCheckout(releaseBranches.trim()); // mvn clean test mvnCleanTest(); } // git checkout master gitCheckout(gitFlowConfig.getProductionBranch()); // git merge --no-ff release/... gitMergeNoff(gitFlowConfig.getReleaseBranchPrefix() + releaseVersion); // get current project version from pom final String currentVersion = getCurrentProjectVersion(); if (!skipTag) { String tagVersion = currentVersion; if (tychoBuild && ArtifactUtils.isSnapshot(currentVersion)) { tagVersion = currentVersion.replace("-" + Artifact.SNAPSHOT_VERSION, ""); } // git tag -a ... gitTag(gitFlowConfig.getVersionTagPrefix() + tagVersion, "tagging release"); } // git checkout develop gitCheckout(gitFlowConfig.getDevelopmentBranch()); // git merge --no-ff release/... gitMergeNoff(gitFlowConfig.getReleaseBranchPrefix() + releaseVersion); String nextSnapshotVersion = null; // get next snapshot version try { final DefaultVersionInfo versionInfo = new DefaultVersionInfo( currentVersion); nextSnapshotVersion = versionInfo.getNextVersion() .getSnapshotVersionString(); } catch (VersionParseException e) { if (getLog().isDebugEnabled()) { getLog().debug(e); } } if (StringUtils.isBlank(nextSnapshotVersion)) { throw new MojoFailureException( "Next snapshot version is blank."); } // mvn versions:set -DnewVersion=... -DgenerateBackupPoms=false mvnSetVersions(nextSnapshotVersion); // git commit -a -m updating for next development version gitCommit("updating for next development version"); if (installProject) { // mvn clean install mvnCleanInstall(); } if (!keepBranch) { // git branch -d release/... gitBranchDelete(gitFlowConfig.getReleaseBranchPrefix() + releaseVersion); } } catch (CommandLineException e) { getLog().error(e); } } #location 20 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Override public void execute() throws MojoExecutionException, MojoFailureException { try { // set git flow configuration initGitFlowConfig(); // check uncommitted changes checkUncommittedChanges(); // check snapshots dependencies if (!allowSnapshots) { checkSnapshotDependencies(); } // fetch and check remote if (fetchRemote) { if (notSameProdDevName()) { gitFetchRemoteAndCompare(gitFlowConfig .getDevelopmentBranch()); } gitFetchRemoteAndCompare(gitFlowConfig.getProductionBranch()); } // git for-each-ref --count=1 refs/heads/release/* final String releaseBranch = gitFindBranches( gitFlowConfig.getReleaseBranchPrefix(), true); if (StringUtils.isNotBlank(releaseBranch)) { throw new MojoFailureException( "Release branch already exists. Cannot start release."); } // need to be in develop to get correct project version // git checkout develop gitCheckout(gitFlowConfig.getDevelopmentBranch()); if (!skipTestProject) { // mvn clean test mvnCleanTest(); } // get current project version from pom final String currentVersion = getCurrentProjectVersion(); String defaultVersion = null; if (tychoBuild) { defaultVersion = currentVersion; } else { // get default release version try { final DefaultVersionInfo versionInfo = new DefaultVersionInfo( currentVersion); defaultVersion = versionInfo.getReleaseVersionString(); } catch (VersionParseException e) { if (getLog().isDebugEnabled()) { getLog().debug(e); } } } if (defaultVersion == null) { throw new MojoFailureException( "Cannot get default project version."); } String version = null; if (settings.isInteractiveMode()) { try { version = prompter.prompt("What is release version? [" + defaultVersion + "]"); } catch (PrompterException e) { getLog().error(e); } } else { version = releaseVersion; } if (StringUtils.isBlank(version)) { version = defaultVersion; } // execute if version changed if (!version.equals(currentVersion)) { // mvn set version mvnSetVersions(version); // git commit -a -m updating versions for release gitCommit(commitMessages.getReleaseStartMessage()); } if (notSameProdDevName()) { // git checkout master gitCheckout(gitFlowConfig.getProductionBranch()); gitMerge(gitFlowConfig.getDevelopmentBranch(), releaseRebase, releaseMergeNoFF); } if (!skipTag) { if (tychoBuild && ArtifactUtils.isSnapshot(version)) { version = version.replace("-" + Artifact.SNAPSHOT_VERSION, ""); } // git tag -a ... gitTag(gitFlowConfig.getVersionTagPrefix() + version, commitMessages.getTagReleaseMessage()); } if (notSameProdDevName()) { // git checkout develop gitCheckout(gitFlowConfig.getDevelopmentBranch()); } String nextSnapshotVersion = null; // get next snapshot version try { final DefaultVersionInfo versionInfo = new DefaultVersionInfo( version); nextSnapshotVersion = versionInfo.getNextVersion() .getSnapshotVersionString(); } catch (VersionParseException e) { if (getLog().isDebugEnabled()) { getLog().debug(e); } } if (StringUtils.isBlank(nextSnapshotVersion)) { throw new MojoFailureException( "Next snapshot version is blank."); } // mvn set version mvnSetVersions(nextSnapshotVersion); // git commit -a -m updating for next development version gitCommit(commitMessages.getReleaseFinishMessage()); if (installProject) { // mvn clean install mvnCleanInstall(); } if (pushRemote) { gitPush(gitFlowConfig.getProductionBranch(), !skipTag); if (notSameProdDevName()) { gitPush(gitFlowConfig.getDevelopmentBranch(), !skipTag); } } } catch (CommandLineException e) { getLog().error(e); } }
#vulnerable code @Override public void execute() throws MojoExecutionException, MojoFailureException { try { // set git flow configuration initGitFlowConfig(); // check uncommitted changes checkUncommittedChanges(); // check snapshots dependencies if (!allowSnapshots) { checkSnapshotDependencies(); } // fetch and check remote if (fetchRemote) { if (notSameProdDevName()) { gitFetchRemoteAndCompare(gitFlowConfig .getDevelopmentBranch()); } gitFetchRemoteAndCompare(gitFlowConfig.getProductionBranch()); } // git for-each-ref --count=1 refs/heads/release/* final String releaseBranch = gitFindBranches( gitFlowConfig.getReleaseBranchPrefix(), true); if (StringUtils.isNotBlank(releaseBranch)) { throw new MojoFailureException( "Release branch already exists. Cannot start release."); } // need to be in develop to get correct project version // git checkout develop gitCheckout(gitFlowConfig.getDevelopmentBranch()); if (!skipTestProject) { // mvn clean test mvnCleanTest(); } // get current project version from pom final String currentVersion = getCurrentProjectVersion(); String defaultVersion = null; if (tychoBuild) { defaultVersion = currentVersion; } else { // get default release version try { final DefaultVersionInfo versionInfo = new DefaultVersionInfo( currentVersion); defaultVersion = versionInfo.getReleaseVersionString(); } catch (VersionParseException e) { if (getLog().isDebugEnabled()) { getLog().debug(e); } } } if (defaultVersion == null) { throw new MojoFailureException( "Cannot get default project version."); } String version = null; if (settings.isInteractiveMode()) { try { version = prompter.prompt("What is release version? [" + defaultVersion + "]"); } catch (PrompterException e) { getLog().error(e); } } if (StringUtils.isBlank(version)) { version = defaultVersion; } // execute if version changed if (!version.equals(currentVersion)) { // mvn set version mvnSetVersions(version); // git commit -a -m updating versions for release gitCommit(commitMessages.getReleaseStartMessage()); } if (notSameProdDevName()) { // git checkout master gitCheckout(gitFlowConfig.getProductionBranch()); gitMerge(gitFlowConfig.getDevelopmentBranch(), releaseRebase, releaseMergeNoFF); } if (!skipTag) { if (tychoBuild && ArtifactUtils.isSnapshot(version)) { version = version.replace("-" + Artifact.SNAPSHOT_VERSION, ""); } // git tag -a ... gitTag(gitFlowConfig.getVersionTagPrefix() + version, commitMessages.getTagReleaseMessage()); } if (notSameProdDevName()) { // git checkout develop gitCheckout(gitFlowConfig.getDevelopmentBranch()); } String nextSnapshotVersion = null; // get next snapshot version try { final DefaultVersionInfo versionInfo = new DefaultVersionInfo( version); nextSnapshotVersion = versionInfo.getNextVersion() .getSnapshotVersionString(); } catch (VersionParseException e) { if (getLog().isDebugEnabled()) { getLog().debug(e); } } if (StringUtils.isBlank(nextSnapshotVersion)) { throw new MojoFailureException( "Next snapshot version is blank."); } // mvn set version mvnSetVersions(nextSnapshotVersion); // git commit -a -m updating for next development version gitCommit(commitMessages.getReleaseFinishMessage()); if (installProject) { // mvn clean install mvnCleanInstall(); } if (pushRemote) { gitPush(gitFlowConfig.getProductionBranch(), !skipTag); if (notSameProdDevName()) { gitPush(gitFlowConfig.getDevelopmentBranch(), !skipTag); } } } catch (CommandLineException e) { getLog().error(e); } } #location 81 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Override public void execute() throws MojoExecutionException, MojoFailureException { try { // set git flow configuration initGitFlowConfig(); // check uncommitted changes checkUncommittedChanges(); // check snapshots dependencies if (!allowSnapshots) { checkSnapshotDependencies(); } // git for-each-ref --count=1 refs/heads/release/* final String releaseBranch = gitFindBranches( gitFlowConfig.getReleaseBranchPrefix(), true); if (StringUtils.isNotBlank(releaseBranch)) { throw new MojoFailureException( "Release branch already exists. Cannot start release."); } // fetch and check remote if (fetchRemote) { gitFetchRemoteAndCompare(gitFlowConfig.getDevelopmentBranch()); } // need to be in develop to get correct project version // git checkout develop gitCheckout(gitFlowConfig.getDevelopmentBranch()); // get current project version from pom final String currentVersion = getCurrentProjectVersion(); String defaultVersion = null; if (tychoBuild) { defaultVersion = currentVersion; } else { // get default release version try { final DefaultVersionInfo versionInfo = new DefaultVersionInfo( currentVersion); defaultVersion = versionInfo.getReleaseVersionString(); } catch (VersionParseException e) { if (getLog().isDebugEnabled()) { getLog().debug(e); } } } if (defaultVersion == null) { throw new MojoFailureException( "Cannot get default project version."); } String version = null; if (settings.isInteractiveMode()) { try { version = prompter.prompt("What is release version? [" + defaultVersion + "]"); } catch (PrompterException e) { getLog().error(e); } } else { version = releaseVersion; } if (StringUtils.isBlank(version)) { version = defaultVersion; } String branchName = gitFlowConfig.getReleaseBranchPrefix(); if (!sameBranchName) { branchName += version; } // git checkout -b release/... develop gitCreateAndCheckout(branchName, gitFlowConfig.getDevelopmentBranch()); // execute if version changed if (!version.equals(currentVersion)) { // mvn versions:set -DnewVersion=... -DgenerateBackupPoms=false mvnSetVersions(version); // git commit -a -m updating versions for release gitCommit(commitMessages.getReleaseStartMessage()); } if (installProject) { // mvn clean install mvnCleanInstall(); } } catch (CommandLineException e) { getLog().error(e); } }
#vulnerable code @Override public void execute() throws MojoExecutionException, MojoFailureException { try { // set git flow configuration initGitFlowConfig(); // check uncommitted changes checkUncommittedChanges(); // check snapshots dependencies if (!allowSnapshots) { checkSnapshotDependencies(); } // git for-each-ref --count=1 refs/heads/release/* final String releaseBranch = gitFindBranches( gitFlowConfig.getReleaseBranchPrefix(), true); if (StringUtils.isNotBlank(releaseBranch)) { throw new MojoFailureException( "Release branch already exists. Cannot start release."); } // fetch and check remote if (fetchRemote) { gitFetchRemoteAndCompare(gitFlowConfig.getDevelopmentBranch()); } // need to be in develop to get correct project version // git checkout develop gitCheckout(gitFlowConfig.getDevelopmentBranch()); // get current project version from pom final String currentVersion = getCurrentProjectVersion(); String defaultVersion = null; if (tychoBuild) { defaultVersion = currentVersion; } else { // get default release version try { final DefaultVersionInfo versionInfo = new DefaultVersionInfo( currentVersion); defaultVersion = versionInfo.getReleaseVersionString(); } catch (VersionParseException e) { if (getLog().isDebugEnabled()) { getLog().debug(e); } } } if (defaultVersion == null) { throw new MojoFailureException( "Cannot get default project version."); } String version = null; if (settings.isInteractiveMode()) { try { version = prompter.prompt("What is release version? [" + defaultVersion + "]"); } catch (PrompterException e) { getLog().error(e); } } if (StringUtils.isBlank(version)) { version = defaultVersion; } String branchName = gitFlowConfig.getReleaseBranchPrefix(); if (!sameBranchName) { branchName += version; } // git checkout -b release/... develop gitCreateAndCheckout(branchName, gitFlowConfig.getDevelopmentBranch()); // execute if version changed if (!version.equals(currentVersion)) { // mvn versions:set -DnewVersion=... -DgenerateBackupPoms=false mvnSetVersions(version); // git commit -a -m updating versions for release gitCommit(commitMessages.getReleaseStartMessage()); } if (installProject) { // mvn clean install mvnCleanInstall(); } } catch (CommandLineException e) { getLog().error(e); } } #location 81 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Override public void execute() throws MojoExecutionException, MojoFailureException { validateConfiguration(); try { // set git flow configuration initGitFlowConfig(); // check uncommitted changes checkUncommittedChanges(); String tag = null; if (settings.isInteractiveMode()) { // get tags String tagsStr = gitFindTags(); if (StringUtils.isBlank(tagsStr)) { throw new MojoFailureException("There are no tags."); } try { tag = prompter.prompt("Choose tag to start support branch", Arrays.asList(tagsStr.split("\\r?\\n"))); } catch (PrompterException e) { throw new MojoFailureException("support-start", e); } } else if (StringUtils.isNotBlank(tagName)) { if (gitCheckTagExists(tagName)) { tag = tagName; } else { throw new MojoFailureException("The tag '" + tagName + "' doesn't exist."); } } else { getLog().info("The tagName is blank. Using the last tag."); tag = gitFindLastTag(); } if (StringUtils.isBlank(tag)) { throw new MojoFailureException("Tag is blank."); } // git for-each-ref refs/heads/support/... final boolean supportBranchExists = gitCheckBranchExists(gitFlowConfig .getSupportBranchPrefix() + tag); if (supportBranchExists) { throw new MojoFailureException( "Support branch with that name already exists."); } // git checkout -b ... tag gitCreateAndCheckout(gitFlowConfig.getSupportBranchPrefix() + tag, tag); if (installProject) { // mvn clean install mvnCleanInstall(); } if (pushRemote) { gitPush(gitFlowConfig.getSupportBranchPrefix() + tag, false); } } catch (CommandLineException e) { throw new MojoFailureException("support-start", e); } }
#vulnerable code @Override public void execute() throws MojoExecutionException, MojoFailureException { validateConfiguration(); try { // set git flow configuration initGitFlowConfig(); // check uncommitted changes checkUncommittedChanges(); // get tags String tagsStr = gitFindTags(); if (StringUtils.isBlank(tagsStr)) { throw new MojoFailureException("There are no tags."); } String tagName = null; try { tagName = prompter.prompt("Choose tag to start support branch", Arrays.asList(tagsStr.split("\\r?\\n"))); } catch (PrompterException e) { throw new MojoFailureException("support-start", e); } // git for-each-ref refs/heads/support/... final boolean supportBranchExists = gitCheckBranchExists(gitFlowConfig .getSupportBranchPrefix() + tagName); if (supportBranchExists) { throw new MojoFailureException( "Support branch with that name already exists."); } // git checkout -b ... tag gitCreateAndCheckout(gitFlowConfig.getSupportBranchPrefix() + tagName, tagName); if (installProject) { // mvn clean install mvnCleanInstall(); } if (pushRemote) { gitPush(gitFlowConfig.getSupportBranchPrefix() + tagName, false); } } catch (CommandLineException e) { throw new MojoFailureException("support-start", e); } } #location 22 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Override public void execute() throws MojoExecutionException, MojoFailureException { try { // check uncommitted changes checkUncommittedChanges(); // git for-each-ref --format='%(refname:short)' refs/heads/hotfix/* final String hotfixBranches = executeGitCommandReturn( "for-each-ref", "--format=\"%(refname:short)\"", "refs/heads/" + gitFlowConfig.getHotfixBranchPrefix() + "*"); if (StringUtils.isBlank(hotfixBranches)) { throw new MojoFailureException("There is no hotfix branches."); } String[] branches = hotfixBranches.split("\\r?\\n"); List<String> numberedList = new ArrayList<String>(); StringBuffer str = new StringBuffer( "hotfix branch name to finish: ["); for (int i = 0; i < branches.length; i++) { str.append((i + 1) + ". " + branches[i] + " "); numberedList.add("" + (i + 1)); } str.append("]"); String hotfixNumber = null; try { while (StringUtils.isBlank(hotfixNumber)) { hotfixNumber = prompter .prompt(str.toString(), numberedList); } } catch (PrompterException e) { getLog().error(e); } String hotfixBranchName = null; if (hotfixNumber != null) { int num = Integer.parseInt(hotfixNumber); hotfixBranchName = branches[num - 1]; } if (StringUtils.isBlank(hotfixBranchName)) { throw new MojoFailureException( "Hotfix name to finish is blank."); } // git checkout hotfix/... executeGitCommand("checkout", hotfixBranchName); // mvn clean install executeMvnCommand("clean", "install"); // git checkout master executeGitCommand("checkout", gitFlowConfig.getProductionBranch()); // git merge --no-ff hotfix/... executeGitCommand("merge", "--no-ff", hotfixBranchName); // git tag -a ... executeGitCommand( "tag", "-a", gitFlowConfig.getVersionTagPrefix() + hotfixBranchName.replaceFirst( gitFlowConfig.getHotfixBranchPrefix(), ""), "-m", "tagging hotfix"); // check whether release branch exists // git for-each-ref --count=1 --format="%(refname:short)" // refs/heads/release/* final String releaseBranch = executeGitCommandReturn( "for-each-ref", "--count=1", "--format=\"%(refname:short)\"", "refs/heads/" + gitFlowConfig.getReleaseBranchPrefix() + "*"); // if release branch exists merge hotfix changes into it if (StringUtils.isNotBlank(releaseBranch)) { // git checkout release executeGitCommand("checkout", releaseBranch); // git merge --no-ff hotfix/... executeGitCommand("merge", "--no-ff", hotfixBranchName); } else { // git checkout develop executeGitCommand("checkout", gitFlowConfig.getDevelopmentBranch()); // git merge --no-ff hotfix/... executeGitCommand("merge", "--no-ff", hotfixBranchName); // get current project version from pom String currentVersion = getCurrentProjectVersion(); String nextSnapshotVersion = null; // get next snapshot version try { DefaultVersionInfo versionInfo = new DefaultVersionInfo( currentVersion); nextSnapshotVersion = versionInfo.getNextVersion() .getSnapshotVersionString(); } catch (VersionParseException e) { if (getLog().isDebugEnabled()) { getLog().debug(e); } } if (StringUtils.isBlank(nextSnapshotVersion)) { throw new MojoFailureException( "Next snapshot version is blank."); } // mvn versions:set -DnewVersion=... -DgenerateBackupPoms=false executeMvnCommand(VERSIONS_MAVEN_PLUGIN + ":set", "-DnewVersion=" + nextSnapshotVersion, "-DgenerateBackupPoms=false"); // git commit -a -m updating poms for next development version executeGitCommand("commit", "-a", "-m", "updating poms for next development version"); } // git branch -d hotfix/... executeGitCommand("branch", "-d", hotfixBranchName); } catch (CommandLineException e) { e.printStackTrace(); } }
#vulnerable code @Override public void execute() throws MojoExecutionException, MojoFailureException { try { // check uncommitted changes checkUncommittedChanges(); // git for-each-ref --format='%(refname:short)' refs/heads/hotfix/* final String hotfixBranches = executeGitCommandReturn( "for-each-ref", "--format=\"%(refname:short)\"", "refs/heads/" + gitFlowConfig.getHotfixBranchPrefix() + "*"); if (StringUtils.isBlank(hotfixBranches)) { throw new MojoFailureException("There is no hotfix branches."); } String[] branches = hotfixBranches.split("\\r?\\n"); List<String> numberedList = new ArrayList<String>(); StringBuffer str = new StringBuffer( "hotfix branch name to finish: ["); for (int i = 0; i < branches.length; i++) { str.append((i + 1) + ". " + branches[i] + " "); numberedList.add("" + (i + 1)); } str.append("]"); String hotfixNumber = null; try { while (StringUtils.isBlank(hotfixNumber)) { hotfixNumber = prompter .prompt(str.toString(), numberedList); } } catch (PrompterException e) { getLog().error(e); } String hotfixName = null; if (hotfixNumber != null) { int num = Integer.parseInt(hotfixNumber); hotfixName = branches[num - 1]; } if (StringUtils.isBlank(hotfixName)) { throw new MojoFailureException( "Hotfix name to finish is blank."); } // git checkout master executeGitCommand("checkout", gitFlowConfig.getProductionBranch()); // git merge --no-ff hotfix/... executeGitCommand("merge", "--no-ff", hotfixName); // git tag -a ... executeGitCommand( "tag", "-a", gitFlowConfig.getVersionTagPrefix() + hotfixName.replaceFirst( gitFlowConfig.getHotfixBranchPrefix(), ""), "-m", "tagging hotfix"); // check whether release branch exists // git for-each-ref --count=1 --format="%(refname:short)" // refs/heads/release/* final String releaseBranch = executeGitCommandReturn( "for-each-ref", "--count=1", "--format=\"%(refname:short)\"", "refs/heads/" + gitFlowConfig.getReleaseBranchPrefix() + "*"); // if release branch exists merge hotfix changes into it if (StringUtils.isNotBlank(releaseBranch)) { // git checkout release executeGitCommand("checkout", releaseBranch); // git merge --no-ff hotfix/... executeGitCommand("merge", "--no-ff", hotfixName); } else { // git checkout develop executeGitCommand("checkout", gitFlowConfig.getDevelopmentBranch()); // git merge --no-ff hotfix/... executeGitCommand("merge", "--no-ff", hotfixName); // get current project version from pom String currentVersion = getCurrentProjectVersion(); String nextSnapshotVersion = null; // get next snapshot version try { DefaultVersionInfo versionInfo = new DefaultVersionInfo( currentVersion); nextSnapshotVersion = versionInfo.getNextVersion() .getSnapshotVersionString(); } catch (VersionParseException e) { if (getLog().isDebugEnabled()) { getLog().debug(e); } } if (StringUtils.isBlank(nextSnapshotVersion)) { throw new MojoFailureException( "Next snapshot version is blank."); } // mvn versions:set -DnewVersion=... -DgenerateBackupPoms=false executeMvnCommand(VERSIONS_MAVEN_PLUGIN + ":set", "-DnewVersion=" + nextSnapshotVersion, "-DgenerateBackupPoms=false"); // git commit -a -m updating poms for next development version executeGitCommand("commit", "-a", "-m", "updating poms for next development version"); } // git branch -d hotfix/... executeGitCommand("branch", "-d", hotfixName); } catch (CommandLineException e) { e.printStackTrace(); } } #location 59 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public <T, S extends Geometry> RTree<T, S> deserialize(long sizeBytes, InputStream is, Func1<byte[], T> deserializer) throws IOException { byte[] bytes = readFully(is, (int) sizeBytes); Tree_ t = Tree_.getRootAsTree_(ByteBuffer.wrap(bytes)); Node_ node = t.root(); Context<T, S> context = new Context<T, S>(t.context().minChildren(), t.context().maxChildren(), new SelectorRStar(), new SplitterRStar(), new FactoryImmutable<T, S>()); final Node<T, S> root; if (node.childrenLength() > 0) root = new NonLeafFlatBuffersStatic<T, S>(node, context, deserializer); else { List<Entry<T, S>> entries = FlatBuffersHelper.createEntries(node, deserializer); root = new LeafDefault<T, S>(entries, context); } return SerializerHelper.create(Optional.of(root), (int) t.size(), context); }
#vulnerable code public <T, S extends Geometry> RTree<T, S> deserialize(long sizeBytes, InputStream is, Func1<byte[], T> deserializer) throws IOException { byte[] bytes = readFully(is, (int) sizeBytes); Tree_ t = Tree_.getRootAsTree_(ByteBuffer.wrap(bytes)); Node_ node = t.root(); Context<T, S> context = new Context<T, S>(t.context().minChildren(), t.context().maxChildren(), new SelectorRStar(), new SplitterRStar(), new FactoryImmutable<T, S>()); Node<T, S> root = new NonLeafFlatBuffersStatic<T, S>(node, context, deserializer); return SerializerHelper.create(Optional.of(root), 1, context); } #location 9 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @SuppressWarnings("unchecked") static <T, S extends Geometry> List<Entry<T, S>> createEntries(Node_ node, Func1<byte[], T> deserializer) { List<Entry<T, S>> list = new ArrayList<Entry<T, S>>(node.entriesLength()); for (int i = 0; i < node.entriesLength(); i++) { Entry_ entry = node.entries(i); Geometry_ g = entry.geometry(); final Geometry geometry; if (g.type() == GeometryType_.Box) { Box_ b = g.box(); geometry = Rectangle.create(b.minX(), b.minY(), b.maxX(), b.maxY()); } else if (g.type() == GeometryType_.Point) { Point_ p = g.point(); geometry = Point.create(p.x(), p.y()); } else if (g.type() == GeometryType_.Circle) { Circle_ c = g.circle(); geometry = Circle.create(c.x(), c.y(), c.radius()); } else throw new RuntimeException("unexpected"); ByteBuffer bb = entry.objectAsByteBuffer(); byte[] bytes = Arrays.copyOfRange(bb.array(), bb.position(), bb.limit()); list.add(EntryDefault.<T, S> entry(deserializer.call(bytes), (S) geometry)); } return list; }
#vulnerable code @SuppressWarnings("unchecked") static <T, S extends Geometry> List<Entry<T, S>> createEntries(Node_ node, Func1<byte[], T> deserializer) { List<Entry<T, S>> list = new ArrayList<Entry<T, S>>(node.entriesLength()); for (int i = 0; i < node.entriesLength(); i++) { Entry_ entry = node.entries(i); Geometry_ g = node.entries(i).geometry(); final Geometry geometry; if (g.type() == GeometryType_.Box) { Box_ b = g.box(); geometry = Rectangle.create(b.minX(), b.minY(), b.maxX(), b.maxY()); } else if (g.type() == GeometryType_.Point) { Point_ p = g.point(); geometry = Point.create(p.x(), p.y()); } else if (g.type() == GeometryType_.Circle) { Circle_ c = g.circle(); geometry = Circle.create(c.x(), c.y(), c.radius()); } else throw new RuntimeException("unexpected"); ByteBuffer bb = entry.objectAsByteBuffer(); byte[] bytes = Arrays.copyOfRange(bb.array(), bb.position(), bb.limit()); list.add(EntryDefault.<T, S> entry(deserializer.call(bytes), (S) geometry)); } return list; } #location 7 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code private List<Node<T, S>> createChildren() { List<Node<T, S>> children = new ArrayList<Node<T, S>>(node.childrenLength()); for (int i = 0; i < node.childrenLength(); i++) { Node_ child = node.children(i); if (child.childrenLength() > 0) children.add(new NonLeafFlatBuffersStatic<T, S>(child, context, deserializer)); else children.add(new LeafDefault<T, S>( FlatBuffersHelper.<T, S> createEntries(child, deserializer), context)); } return children; }
#vulnerable code private List<Node<T, S>> createChildren() { List<Node<T, S>> children = new ArrayList<Node<T, S>>(node.childrenLength()); for (int i = 0; i < node.childrenLength(); i++) { children.add( new NonLeafFlatBuffersStatic<T, S>(node.children(i), context, deserializer)); } return children; } #location 5 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code private void roundTrip(InternalStructure structure, boolean backpressure) throws Exception { RTree<Object, Point> tree = RTree.star().maxChildren(10).create(); tree = tree.add(GreekEarthquakes.entries()).last().toBlocking().single(); long t = System.currentTimeMillis(); File file = new File("target/file"); FileOutputStream os = new FileOutputStream(file); Serializer<Object, Point> fbSerializer = createSerializer(); serialize(tree, t, file, os, fbSerializer); deserialize(structure, file, fbSerializer, backpressure); }
#vulnerable code private void roundTrip(InternalStructure structure, boolean backpressure) throws Exception { RTree<Object, Point> tree = RTree.star().maxChildren(10).create(); tree = tree.add(GreekEarthquakes.entries()).last().toBlocking().single(); long t = System.currentTimeMillis(); File file = new File("target/file"); FileOutputStream os = new FileOutputStream(file); SerializerFlatBuffers<Object, Point> fbSerializer = createSerializer(); serialize(tree, t, file, os, fbSerializer); deserialize(structure, file, fbSerializer, backpressure); } #location 9 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code private List<Node<T, S>> createChildren() { List<Node<T, S>> children = new ArrayList<Node<T, S>>(node.childrenLength()); // reduce allocations by resusing objects int numChildren = node.childrenLength(); for (int i = 0; i < numChildren; i++) { Node_ child = node.children(i); if (child.childrenLength()>0) { children.add(new NonLeafFlatBuffers<T, S>(child, context, deserializer)); } else { children.add(new LeafFlatBuffers<T,S>(child, context, deserializer)); } } return children; }
#vulnerable code private List<Node<T, S>> createChildren() { List<Node<T, S>> children = new ArrayList<Node<T, S>>(node.childrenLength()); // reduce allocations by resusing objects int numChildren = node.childrenLength(); for (int i = 0; i < numChildren; i++) { Node_ child = node.children(i); children.add(new NonLeafFlatBuffers<T, S>(child, context, deserializer)); } return children; } #location 7 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @SuppressWarnings("unchecked") static <S extends Geometry> S toGeometry(Geometry_ g) { final Geometry result; byte type = g.type(); if (type == GeometryType_.Box) { result = createBox(g.box()); } else if (type == GeometryType_.Point) { result = Geometries.point(g.point().x(), g.point().y()); } else if (type == GeometryType_.Circle) { Circle_ c = g.circle(); result = Geometries.circle(c.x(), c.y(), c.radius()); } else if (type == GeometryType_.Line) { result = createLine(g.line()); } else throw new UnsupportedOperationException(); return (S) result; }
#vulnerable code @SuppressWarnings("unchecked") static <S extends Geometry> S toGeometry(Geometry_ g) { final Geometry result; byte type = g.type(); if (type == GeometryType_.Box) { result = createBox(g.box()); } else if (type == GeometryType_.Point) { result = Geometries.point(g.point().x(), g.point().y()); } else if (type == GeometryType_.Circle) { Circle_ c = g.circle(); result = Geometries.circle(c.x(), c.y(), c.radius()); } else if (type == GeometryType_.Line) { result = createBox(g.line()); } else throw new UnsupportedOperationException(); return (S) result; } #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 testSerializeRoundTrip() throws IOException { RTree<Object, Point> tree = RTree.star().maxChildren(10).create(); tree = tree.add(GreekEarthquakes.entries()).last().toBlocking().single(); long t = System.currentTimeMillis(); File output = new File("target/file"); FileOutputStream os = new FileOutputStream(output); FlatBuffersSerializer serializer = new FlatBuffersSerializer(); serializer.serialize(tree, new Func1<Object, byte[]>() { @Override public byte[] call(Object o) { return EMPTY; } }, os); os.close(); System.out.println("written in " + (System.currentTimeMillis() - t) + "ms, " + "file size=" + output.length() / 1000000.0 + "MB"); System.out.println("bytes per entry=" + output.length() / tree.size()); InputStream is = new FileInputStream(output); t = System.currentTimeMillis(); RTree<Object, Geometry> tr = serializer.deserialize(output.length(), is, new Func1<byte[], Object>() { @Override public Object call(byte[] bytes) { return "a"; } }); System.out.println("read in " + (System.currentTimeMillis() - t) + "ms"); int found = tr.search(Geometries.rectangle(40, 27.0, 40.5, 27.5)).count().toBlocking() .single(); System.out.println("found=" + found); assertEquals(22, found); }
#vulnerable code @Test public void testSerializeRoundTrip() throws IOException { RTree<Object, Point> tree = RTree.star().maxChildren(10).create(); tree = tree.add(GreekEarthquakes.entries()).last().toBlocking().single(); long t = System.currentTimeMillis(); File output = new File("target/file"); FileOutputStream os = new FileOutputStream(output); FlatBuffersSerializer serializer = new FlatBuffersSerializer(); serializer.serialize(tree, new Func1<Object, byte[]>() { @Override public byte[] call(Object o) { return EMPTY; } }, os); os.close(); System.out.println("written in " + (System.currentTimeMillis() - t) + "ms, " + "file size=" + output.length() / 1000000.0 + "MB"); System.out.println("bytes per entry=" + output.length() / tree.size()); InputStream is = new FileInputStream(output); if (false) { RTree<Object, Geometry> tr = serializer.deserialize(is, new Func1<byte[], Object>() { @Override public Object call(byte[] bytes) { return "a"; } }); } } #location 20 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Override protected SearchRequestBuilder _explain() throws SqlParseException { setWhere(select.getWhere()); AggregationBuilder<?> lastAgg = null; if (select.getGroupBys().size() > 0) { Field field = select.getGroupBys().get(0); lastAgg = aggMaker.makeGroupAgg(field); if (lastAgg != null && lastAgg instanceof TermsBuilder) { ((TermsBuilder) lastAgg).size(select.getRowCount()); } request.addAggregation(lastAgg); for (int i = 1; i < select.getGroupBys().size(); i++) { field = select.getGroupBys().get(i); AggregationBuilder<?> subAgg = aggMaker.makeGroupAgg(field); if(subAgg instanceof TermsBuilder){ ((TermsBuilder)subAgg).size(0) ; } lastAgg.subAggregation(subAgg); lastAgg = subAgg; } } Map<String, KVValue> groupMap = aggMaker.getGroupMap(); // add field if (select.getFields().size() > 0) { explanFields(request, select.getFields(), lastAgg); } // add order if (lastAgg != null && select.getOrderBys().size() > 0) { KVValue temp = null; TermsBuilder termsBuilder = null; for (Order order : select.getOrderBys()) { temp = groupMap.get(order.getName()); termsBuilder = (TermsBuilder) temp.value; switch (temp.key) { case "COUNT": termsBuilder.order(Terms.Order.count(isASC(order))); break; case "KEY": termsBuilder.order(Terms.Order.term(isASC(order))); break; case "FIELD": termsBuilder.order(Terms.Order.aggregation(order.getName(), isASC(order))); break; default: throw new SqlParseException(order.getName() + " can not to order"); } } } request.setSize(0); request.setSearchType(SearchType.DEFAULT); return request; }
#vulnerable code @Override protected SearchRequestBuilder _explain() throws SqlParseException { BoolFilterBuilder boolFilter = null; // set where Where where = select.getWhere(); AggregationBuilder<?> lastAgg = null; FilterAggregationBuilder filter = null; if (where != null) { boolFilter = FilterMaker.explan(where); request.setQuery(QueryBuilders.filteredQuery(null, boolFilter)); } // if (select.getGroupBys().size() > 0) { Field field = select.getGroupBys().get(0); lastAgg = aggMaker.makeGroupAgg(field); if (lastAgg != null && lastAgg instanceof TermsBuilder) { ((TermsBuilder) lastAgg).size(select.getRowCount()); } if (filter != null) { filter.subAggregation(lastAgg); } else { request.addAggregation(lastAgg); } for (int i = 1; i < select.getGroupBys().size(); i++) { field = select.getGroupBys().get(i); AggregationBuilder<?> subAgg = aggMaker.makeGroupAgg(field); if(subAgg instanceof TermsBuilder){ ((TermsBuilder)subAgg).size(0) ; } lastAgg.subAggregation(subAgg); lastAgg = subAgg; } } Map<String, KVValue> groupMap = aggMaker.getGroupMap(); // add field if (select.getFields().size() > 0) { explanFields(request, select.getFields(), lastAgg, filter); } // add order if (lastAgg != null && select.getOrderBys().size() > 0) { KVValue temp = null; TermsBuilder termsBuilder = null; for (Order order : select.getOrderBys()) { temp = groupMap.get(order.getName()); termsBuilder = (TermsBuilder) temp.value; switch (temp.key) { case "COUNT": termsBuilder.order(Terms.Order.count(isASC(order))); break; case "KEY": termsBuilder.order(Terms.Order.term(isASC(order))); break; case "FIELD": termsBuilder.order(Terms.Order.aggregation(order.getName(), isASC(order))); break; default: throw new SqlParseException(order.getName() + " can not to order"); } } } request.setSize(0); request.setSearchType(SearchType.DEFAULT); return request; } #location 38 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public static void main(String[] args) throws IOException { Client client = new TransportClient().addTransportAddress(new InetSocketTransportAddress("localhost", 9300)); BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(new File("/home/ansj/temp/20140421.txt")))); String temp = null; int a = 0 ; while ((temp = br.readLine()) != null) { if(a++%100==0) System.out.println(a); try { JSONObject job = JSON.parseObject(br.readLine()); client.prepareIndex().setIndex("testdoc").setType("testdoc").setSource(job).setTimeout("10s").execute().actionGet(); } catch (Exception e) { e.printStackTrace(); } } }
#vulnerable code public static void main(String[] args) throws IOException { Client client = new TransportClient().addTransportAddress(new InetSocketTransportAddress("localhost", 9300)); BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(new File("/home/ansj/temp/20140421.txt")))); String temp = null; while ((temp = br.readLine()) != null) { System.out.println("in"); try { JSONObject job = JSON.parseObject(br.readLine()); client.prepareIndex().setIndex("testdoc").setType("testdoc").setSource(job).execute().actionGet(); } catch (Exception e) { e.printStackTrace(); } } } #location 14 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code private void findOrderBy(MySqlSelectQueryBlock query, Select select) throws SqlParseException { SQLOrderBy orderBy = query.getOrderBy(); if (orderBy == null) { return; } List<SQLSelectOrderByItem> items = orderBy.getItems(); addOrderByToSelect(select, items, null); }
#vulnerable code private void findOrderBy(MySqlSelectQueryBlock query, Select select) throws SqlParseException { SQLOrderBy orderBy = query.getOrderBy(); if (orderBy == null) { return; } List<SQLSelectOrderByItem> items = orderBy.getItems(); List<String> lists = new ArrayList<>(); for (SQLSelectOrderByItem sqlSelectOrderByItem : items) { SQLExpr expr = sqlSelectOrderByItem.getExpr(); lists.add(FieldMaker.makeField(expr, null,null).toString()); if (sqlSelectOrderByItem.getType() == null) { sqlSelectOrderByItem.setType(SQLOrderingSpecification.ASC); } String type = sqlSelectOrderByItem.getType().toString(); for (String name : lists) { name = name.replace("`", ""); select.addOrderBy(name, type); } lists.clear(); } } #location 15 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code private SearchRequestBuilder explan(SQLQueryExpr SQLQueryExpr) throws SqlParseException { Select select = new SqlParser().parseSelect(SQLQueryExpr); Query query = null; if (select.isAgg) { query = new AggregationQuery(client, select); } else { query = new DefaultQuery(client, select); } return query.explan(); }
#vulnerable code private SearchRequestBuilder explan(SQLQueryExpr SQLQueryExpr) throws SqlParseException { Select select = new SqlParser().parseSelect(SQLQueryExpr); Query query = null; Client client = new TransportClient(); if (select.isAgg) { query = new AggregationQuery(client, select); } else { query = new DefaultQuery(client, select); } return query.explan(); } #location 13 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public IonValue singleValue(String ionText) { CloseableIterator<IonValue> it = iterate(ionText); return singleValue(it); }
#vulnerable code public IonValue singleValue(String ionText) { Iterator<IonValue> it = iterate(ionText); return singleValue(it); } #location 4 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Test public void testWriteValueCopiesFieldName() throws Exception { IonStruct data = struct("{a:{b:10}}"); IonReader ir = system().newReader(data); ir.next(); ir.stepIn(); expectNextField(ir, "a"); iw = makeWriter(); iw.stepIn(IonType.STRUCT); iw.writeValue(ir); iw.stepOut(); assertEquals(data, reloadSingleValue()); }
#vulnerable code @Test public void testWriteValueCopiesFieldName() throws Exception { IonStruct data = struct("{a:{b:10}}"); IonReader ir = system().newReader(data); ir.next(); ir.stepIn(); expectNextField(ir, "a"); iw = makeWriter(); iw.stepIn(IonType.STRUCT); iw.writeValue(ir); iw.stepOut(); assertEquals(data, reloadSingleValue()); IonValue a = data.get("a"); ir = system().newReader(a); ir.next(); iw = makeWriter(); iw.stepIn(IonType.STRUCT); iw.writeValue(ir); iw.stepOut(); assertEquals(data, reloadSingleValue()); } #location 17 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public IonValue singleValue(byte[] ionData) { CloseableIterator<IonValue> iterator = iterate(ionData); return singleValue(iterator); }
#vulnerable code public IonValue singleValue(byte[] ionData) { Iterator<IonValue> it = iterate(ionData); return singleValue(it); } #location 4 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Test public void testFlushingUnlockedSymtab() throws Exception { byte[] bytes = flushUnlockedSymtab(false); assertEquals(0, bytes.length); }
#vulnerable code @Test public void testFlushingUnlockedSymtab() throws Exception { iw = makeWriter(); iw.writeSymbol("force a local symtab"); SymbolTable symtab = iw.getSymbolTable(); symtab.intern("fred_1"); symtab.intern("fred_2"); iw.writeSymbol("fred_1"); // This would cause an appended LST to be written before the next value. iw.flush(); IonReader reader = IonReaderBuilder.standard().build(myOutputStream.toByteArray()); assertEquals(IonType.SYMBOL, reader.next()); assertEquals("force a local symtab", reader.stringValue()); assertEquals(IonType.SYMBOL, reader.next()); assertEquals("fred_1", reader.stringValue()); assertNull(reader.next()); } #location 20 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code protected void testTypeAnnotationHashCode(String text, IonType type) { String sharedSymbolTable = "$ion_symbol_table::{imports:[{name:\"foo\", version: 1, max_id:90}]}"; checkType(type, oneValue("annot1::" + text)); checkType(type, oneValue(sharedSymbolTable + "$99::" + text)); assertIonEqImpliesHashEq(oneValue("annot1::" + text), oneValue("annot2::" + text)); assertIonEqImpliesHashEq(oneValue("annot1::annot2::" + text), oneValue("annot1::annot2::" + text)); assertIonEqImpliesHashEq(oneValue("annot1::annot2::annot3::" + text), oneValue("annot1::annot2::annot3::" + text)); assertIonEqImpliesHashEq(oneValue(sharedSymbolTable + "$99::" + text), oneValue(sharedSymbolTable + "$98::" + text)); assertIonEqImpliesHashEq(oneValue(sharedSymbolTable + "$99::$98::" + text), oneValue(sharedSymbolTable + "$99::$98::" + text)); assertIonEqImpliesHashEq(oneValue(sharedSymbolTable + "$99::$98::$97::" + text), oneValue(sharedSymbolTable + "$99::$98::$97::" + text)); assertIonNotEqImpliesHashNotEq("annot1::" + text, "annot2::" + text); assertIonNotEqImpliesHashNotEq("annot1::annot2::" + text, "annot2::annot1::" + text); assertIonNotEqImpliesHashNotEq("annot1::annot2::annot3::" + text, "annot3::annot2::annot1::" + text); assertIonNotEqImpliesHashNotEq(sharedSymbolTable + "$99::" + text, sharedSymbolTable + "$98::" + text); assertIonNotEqImpliesHashNotEq(sharedSymbolTable + "$99::$98::" + text, sharedSymbolTable + "$98::$99::" + text); assertIonNotEqImpliesHashNotEq(sharedSymbolTable + "$99::$98::$97::" + text, sharedSymbolTable + "$97::$98::$99::" + text); }
#vulnerable code protected void testTypeAnnotationHashCode(String text, IonType type) { checkType(type, oneValue("annot1::" + text)); checkType(type, oneValue("$99::" + text)); assertIonEqImpliesHashEq(oneValue("annot1::" + text), oneValue("annot2::" + text)); assertIonEqImpliesHashEq(oneValue("annot1::annot2::" + text), oneValue("annot1::annot2::" + text)); assertIonEqImpliesHashEq(oneValue("annot1::annot2::annot3::" + text), oneValue("annot1::annot2::annot3::" + text)); assertIonEqImpliesHashEq(oneValue("$99::" + text), oneValue("$98::" + text)); assertIonEqImpliesHashEq(oneValue("$99::$98::" + text), oneValue("$99::$98::" + text)); assertIonEqImpliesHashEq(oneValue("$99::$98::$97::" + text), oneValue("$99::$98::$97::" + text)); assertIonNotEqImpliesHashNotEq("annot1::" + text, "annot2::" + text); assertIonNotEqImpliesHashNotEq("annot1::annot2::" + text, "annot2::annot1::" + text); assertIonNotEqImpliesHashNotEq("annot1::annot2::annot3::" + text, "annot3::annot2::annot1::" + text); assertIonNotEqImpliesHashNotEq("$99::" + text, "$98::" + text); assertIonNotEqImpliesHashNotEq("$99::$98::" + text, "$98::$99::" + text); assertIonNotEqImpliesHashNotEq("$99::$98::$97::" + text, "$97::$98::$99::" + text); } #location 4 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Ignore("Not ready yet") public void testGetTVChangesList() throws MovieDbException { LOG.info("getPersonChangesList"); List<ChangeListItem> result = instance.getChangeList(MethodBase.PERSON, null, null, null); assertFalse("No TV changes.", result.isEmpty()); }
#vulnerable code @Ignore("Not ready yet") public void testGetTVChangesList() throws MovieDbException { LOG.info("getPersonChangesList"); TmdbResultsList<ChangedMedia> result = instance.getChangeList(MethodBase.PERSON, null, null, null); assertFalse("No TV changes.", result.getResults().isEmpty()); } #location 4 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Test public void testGetMovieChangesList() throws MovieDbException { LOG.info("getMovieChangesList"); List<ChangeListItem> result = instance.getChangeList(MethodBase.MOVIE, null, null, null); assertFalse("No movie changes.", result.isEmpty()); }
#vulnerable code @Test public void testGetMovieChangesList() throws MovieDbException { LOG.info("getMovieChangesList"); TmdbResultsList<ChangedMedia> result = instance.getChangeList(MethodBase.MOVIE, null, null, null); assertFalse("No movie changes.", result.getResults().isEmpty()); } #location 4 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Ignore("Not ready yet") public void testGetPersonChangesList() throws MovieDbException { LOG.info("getPersonChangesList"); List<ChangeListItem> result = instance.getChangeList(MethodBase.PERSON, null, null, null); assertFalse("No Person changes.", result.isEmpty()); }
#vulnerable code @Ignore("Not ready yet") public void testGetPersonChangesList() throws MovieDbException { LOG.info("getPersonChangesList"); TmdbResultsList<ChangedMedia> result = instance.getChangeList(MethodBase.PERSON, null, null, null); assertFalse("No Person changes.", result.getResults().isEmpty()); } #location 4 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Test public void skillViolationAtAct1_shouldWork(){ SolutionAnalyser analyser = new SolutionAnalyser(vrp,solution, new SolutionAnalyser.DistanceCalculator() { @Override public double getDistance(String fromLocationId, String toLocationId) { return vrp.getTransportCosts().getTransportCost(fromLocationId,toLocationId,0.,null,null); } }); VehicleRoute route = solution.getRoutes().iterator().next(); Boolean violated = analyser.hasSkillConstraintViolationAtActivity(route.getActivities().get(0), route); assertFalse(violated); }
#vulnerable code @Test public void skillViolationAtAct1_shouldWork(){ SolutionAnalyser analyser = new SolutionAnalyser(vrp,solution, new SolutionAnalyser.DistanceCalculator() { @Override public double getDistance(String fromLocationId, String toLocationId) { return vrp.getTransportCosts().getTransportCost(fromLocationId,toLocationId,0.,null,null); } }); VehicleRoute route = solution.getRoutes().iterator().next(); Boolean violated = analyser.skillConstraintIsViolatedAtActivity(route.getActivities().get(0),route); assertFalse(violated); } #location 11 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Override public void begin(VehicleRoute route) { currentLoad = stateManager.getRouteState(route, StateFactory.LOAD_AT_BEGINNING, Capacity.class); this.route = route; }
#vulnerable code @Override public void begin(VehicleRoute route) { currentLoad = (int) stateManager.getRouteState(route, StateFactory.LOAD_AT_BEGINNING).toDouble(); this.route = route; } #location 3 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public VehicleRoutingAlgorithm createAlgorithm(VehicleRoutingProblem vrp){ AlgorithmConfig algorithmConfig = new AlgorithmConfig(); URL resource = Resource.getAsURL("greedySchrimpf.xml"); new AlgorithmConfigXmlReader(algorithmConfig).read(resource); return VehicleRoutingAlgorithms.createAlgorithm(vrp, algorithmConfig); }
#vulnerable code public VehicleRoutingAlgorithm createAlgorithm(VehicleRoutingProblem vrp){ AlgorithmConfig algorithmConfig = new AlgorithmConfig(); URL resource = Resource.getAsURL("greedySchrimpf.xml"); new AlgorithmConfigXmlReader(algorithmConfig).read(resource.getPath()); return VehicleRoutingAlgorithms.createAlgorithm(vrp, algorithmConfig); } #location 4 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Override public void informJobInserted(Job job2insert, VehicleRoute inRoute, double additionalCosts, double additionalTime) { if(job2insert instanceof Delivery){ int loadAtDepot = (int) stateManager.getRouteState(inRoute, StateIdFactory.LOAD_AT_BEGINNING).toDouble(); // log.info("loadAtDepot="+loadAtDepot); stateManager.putRouteState(inRoute, StateIdFactory.LOAD_AT_BEGINNING, new StateImpl(loadAtDepot + job2insert.getCapacityDemand())); } else if(job2insert instanceof Pickup || job2insert instanceof Service){ int loadAtEnd = (int) stateManager.getRouteState(inRoute, StateIdFactory.LOAD).toDouble(); // log.info("loadAtEnd="+loadAtEnd); stateManager.putRouteState(inRoute, StateIdFactory.LOAD, new StateImpl(loadAtEnd + job2insert.getCapacityDemand())); } }
#vulnerable code @Override public void informJobInserted(Job job2insert, VehicleRoute inRoute, double additionalCosts, double additionalTime) { if(job2insert instanceof Delivery){ int loadAtDepot = (int) stateManager.getRouteState(inRoute, StateIdFactory.LOAD_AT_DEPOT).toDouble(); // log.info("loadAtDepot="+loadAtDepot); stateManager.putRouteState(inRoute, StateIdFactory.LOAD_AT_DEPOT, new StateImpl(loadAtDepot + job2insert.getCapacityDemand())); } else if(job2insert instanceof Pickup || job2insert instanceof Service){ int loadAtEnd = (int) stateManager.getRouteState(inRoute, StateIdFactory.LOAD).toDouble(); // log.info("loadAtEnd="+loadAtEnd); stateManager.putRouteState(inRoute, StateIdFactory.LOAD, new StateImpl(loadAtEnd + job2insert.getCapacityDemand())); } } #location 4 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public VehicleRoutingAlgorithm createAlgorithm(VehicleRoutingProblem vrp){ AlgorithmConfig algorithmConfig = new AlgorithmConfig(); URL resource = Resource.getAsURL("schrimpf.xml"); new AlgorithmConfigXmlReader(algorithmConfig).read(resource); return VehicleRoutingAlgorithms.createAlgorithm(vrp, algorithmConfig); }
#vulnerable code public VehicleRoutingAlgorithm createAlgorithm(VehicleRoutingProblem vrp){ AlgorithmConfig algorithmConfig = new AlgorithmConfig(); URL resource = Resource.getAsURL("schrimpf.xml"); new AlgorithmConfigXmlReader(algorithmConfig).read(resource.getPath()); return VehicleRoutingAlgorithms.createAlgorithm(vrp, algorithmConfig); } #location 4 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code private static void readDistances(Builder matrixBuilder) throws IOException { BufferedReader reader = new BufferedReader(new FileReader(new File("src/test/resources/refuseCollectionExample_Distances"))); String line = null; boolean firstLine = true; while((line = reader.readLine()) != null){ if(firstLine) { firstLine = false; continue; } String[] lineTokens = line.split(","); matrixBuilder.addTransportDistance(lineTokens[0],lineTokens[1], Integer.parseInt(lineTokens[2])); matrixBuilder.addTransportTime(lineTokens[0],lineTokens[1], Integer.parseInt(lineTokens[2])); } reader.close(); }
#vulnerable code private static void readDistances(Builder matrixBuilder) throws IOException { BufferedReader reader = new BufferedReader(new FileReader(new File("src/test/resources/refuseCollectionExample_Distances"))); String line = null; boolean firstLine = true; while((line = reader.readLine()) != null){ if(firstLine) { firstLine = false; continue; } String[] lineTokens = line.split(","); matrixBuilder.addTransportDistance(lineTokens[0],lineTokens[1], Integer.parseInt(lineTokens[2])); } reader.close(); } #location 9 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Test public void whenSolving_deliverService1_shouldBeInRoute(){ VehicleRoutingProblem.Builder vrpBuilder = VehicleRoutingProblem.Builder.newInstance(); new VrpXMLReader(vrpBuilder).read("src/test/resources/simpleProblem_iniRoutes.xml"); VehicleRoutingProblem vrp = vrpBuilder.build(); VehicleRoutingAlgorithm vra = new SchrimpfFactory().createAlgorithm(vrp); Collection<VehicleRoutingProblemSolution> solutions = vra.searchSolutions(); VehicleRoutingProblemSolution solution = Solutions.bestOf(solutions); SolutionPrinter.print(vrp,solution, SolutionPrinter.Print.VERBOSE); Job job = getInitialJob("1",vrp); assertTrue(hasActivityIn(solution,"veh1", job)); }
#vulnerable code @Test public void whenSolving_deliverService1_shouldBeInRoute(){ VehicleRoutingProblem.Builder vrpBuilder = VehicleRoutingProblem.Builder.newInstance(); new VrpXMLReader(vrpBuilder).read("src/test/resources/simpleProblem_iniRoutes.xml"); VehicleRoutingProblem vrp = vrpBuilder.build(); VehicleRoutingAlgorithm vra = new SchrimpfFactory().createAlgorithm(vrp); Collection<VehicleRoutingProblemSolution> solutions = vra.searchSolutions(); VehicleRoutingProblemSolution solution = Solutions.bestOf(solutions); assertTrue(hasActivityIn(solution.getRoutes().iterator().next(),"1")); } #location 12 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public void read(String filename){ BufferedReader reader = getBufferedReader(filename); String line; Coordinate[] coords = null; int[] demands = null; Integer capacity = null; List<Integer> depotIds = new ArrayList<Integer>(); boolean isCoordSection = false; boolean isDemandSection = false; boolean isDepotSection = false; int dimensions = 0; while( ( line = getLine(reader) ) != null ){ if(line.startsWith("EOF")){ break; } if(line.startsWith("DIMENSION")){ String[] tokens = line.split(":"); String dim = tokens[1].trim(); dimensions = Integer.parseInt(dim); coords = new Coordinate[dimensions]; demands = new int[dimensions]; continue; } if(line.startsWith("CAPACITY")){ String[] tokens = line.split(":"); capacity = Integer.parseInt(tokens[1].trim()); continue; } if(line.startsWith("NODE_COORD_SECTION")){ isCoordSection = true; isDemandSection = false; isDepotSection = false; continue; } if(line.startsWith("DEMAND_SECTION")){ isDemandSection = true; isCoordSection = false; isDepotSection = false; continue; } if(line.startsWith("DEPOT_SECTION")){ isDepotSection = true; isDemandSection = false; isCoordSection = false; continue; } if(isCoordSection){ if(coords == null) throw new IllegalStateException("DIMENSION tag missing"); String[] tokens = line.trim().split("\\s+"); coords[Integer.parseInt(tokens[0]) - 1] = Coordinate.newInstance(Double.parseDouble(tokens[1]), Double.parseDouble(tokens[2])); continue; } if(isDemandSection){ if(demands == null) throw new IllegalStateException("DIMENSION tag missing"); String[] tokens = line.trim().split("\\s+"); demands[Integer.parseInt(tokens[0]) - 1] = Integer.parseInt(tokens[1]); continue; } if(isDepotSection){ if(line.equals("-1")){ isDepotSection = false; } else{ depotIds.add(Integer.parseInt(line)); } } } close(reader); vrpBuilder.setFleetSize(VehicleRoutingProblem.FleetSize.INFINITE); for(Integer depotId : depotIds){ VehicleTypeImpl type = VehicleTypeImpl.Builder.newInstance("typeId").addCapacityDimension(0,capacity).build(); VehicleImpl vehicle = VehicleImpl.Builder.newInstance("vehicle").setStartLocationId(depotId.toString()) .setStartLocationCoordinate(coords[depotId - 1]).setType(type).build(); vrpBuilder.addVehicle(vehicle); } for (int i = 0; i < coords.length; i++) { String id = "" + (i + 1); if(depotIds.isEmpty()){ if(i==0) { VehicleImpl vehicle = VehicleImpl.Builder.newInstance("start") .setStartLocation(Location.Builder.newInstance().setId(id) .setCoordinate(coords[i]).build()) .build(); vrpBuilder.addVehicle(vehicle); continue; } } Service service = Service.Builder.newInstance(id) .setLocation(Location.Builder.newInstance().setId(id).setCoordinate(coords[i]).build()) .addSizeDimension(0, demands[i]).build(); vrpBuilder.addJob(service); } }
#vulnerable code public void read(String filename){ BufferedReader reader = getBufferedReader(filename); String line; Coordinate[] coords = null; Integer[] demands = null; Integer capacity = null; List<Integer> depotIds = new ArrayList<Integer>(); boolean isCoordSection = false; boolean isDemandSection = false; boolean isDepotSection = false; while( ( line = getLine(reader) ) != null ){ if(line.startsWith("DIMENSION")){ String[] tokens = line.split(":"); String dim = tokens[1].trim(); coords = new Coordinate[Integer.parseInt(dim)]; demands = new Integer[Integer.parseInt(dim)]; continue; } if(line.startsWith("CAPACITY")){ String[] tokens = line.split(":"); capacity = Integer.parseInt(tokens[1].trim()); continue; } if(line.startsWith("NODE_COORD_SECTION")){ isCoordSection = true; isDemandSection = false; isDepotSection = false; continue; } if(line.startsWith("DEMAND_SECTION")){ isDemandSection = true; isCoordSection = false; isDepotSection = false; continue; } if(line.startsWith("DEPOT_SECTION")){ isDepotSection = true; isDemandSection = false; isCoordSection = false; continue; } if(isCoordSection){ if(coords == null) throw new IllegalStateException("DIMENSION tag missing"); String[] tokens = line.split("\\s+"); coords[Integer.parseInt(tokens[0]) - 1] = Coordinate.newInstance(Double.parseDouble(tokens[1]), Double.parseDouble(tokens[2])); continue; } if(isDemandSection){ if(demands == null) throw new IllegalStateException("DIMENSION tag missing"); String[] tokens = line.split("\\s+"); demands[Integer.parseInt(tokens[0]) - 1] = Integer.parseInt(tokens[1]); continue; } if(isDepotSection){ if(line.equals("-1")){ isDepotSection = false; } else{ depotIds.add(Integer.parseInt(line)); } } } close(reader); vrpBuilder.setFleetSize(VehicleRoutingProblem.FleetSize.INFINITE); for(Integer depotId : depotIds){ VehicleTypeImpl type = VehicleTypeImpl.Builder.newInstance("typeId").addCapacityDimension(0,capacity).build(); VehicleImpl vehicle = VehicleImpl.Builder.newInstance("vehicle").setStartLocationId(depotId.toString()) .setStartLocationCoordinate(coords[depotId - 1]).setType(type).build(); vrpBuilder.addVehicle(vehicle); } for(int i=0;i<demands.length;i++){ if(demands[i] == 0) continue; String id = "" + (i+1); Service service = Service.Builder.newInstance(id).setLocationId(id).setCoord(coords[i]).addSizeDimension(0,demands[i]).build(); vrpBuilder.addJob(service); } } #location 71 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Override public Collection<Job> ruinRoutes(Collection<VehicleRoute> vehicleRoutes) { if (vehicleRoutes.isEmpty()) { return Collections.emptyList(); } int nOfJobs2BeRemoved = Math.min(ruinShareFactory.createNumberToBeRemoved(), noJobsToMemorize); if (nOfJobs2BeRemoved == 0) { return Collections.emptyList(); } List<Job> jobs = getJobsWithLocation(vrp.getJobs().values()); Job randomJob = RandomUtils.nextJob(jobs, random); return ruinRoutes(vehicleRoutes, randomJob, nOfJobs2BeRemoved); }
#vulnerable code @Override public Collection<Job> ruinRoutes(Collection<VehicleRoute> vehicleRoutes) { if (vehicleRoutes.isEmpty()) { return Collections.emptyList(); } int nOfJobs2BeRemoved = Math.min(ruinShareFactory.createNumberToBeRemoved(), noJobsToMemorize); if (nOfJobs2BeRemoved == 0) { return Collections.emptyList(); } Job randomJob = RandomUtils.nextJob(vrp.getJobs().values(), random); return ruinRoutes(vehicleRoutes, randomJob, nOfJobs2BeRemoved); } #location 11 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Override public void begin(VehicleRoute route) { currentLoad = (int) stateManager.getRouteState(route, StateIdFactory.LOAD_AT_BEGINNING).toDouble(); this.route = route; }
#vulnerable code @Override public void begin(VehicleRoute route) { currentLoad = (int) stateManager.getRouteState(route, StateIdFactory.LOAD_AT_DEPOT).toDouble(); this.route = route; } #location 3 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public void read(String filename){ BufferedReader reader = getReader(filename); String line = null; boolean firstline = true; Coordinate depotCoord = null; int customerCount=0; Integer nuOfCustomer = 0; while((line=readLine(reader))!=null){ String trimedLine = line.trim(); if(trimedLine.startsWith("//")) continue; String[] tokens = trimedLine.split("\\s+"); if(firstline){ nuOfCustomer=Integer.parseInt(tokens[0]); customerCount=0; firstline=false; } else if(customerCount<=nuOfCustomer) { if(customerCount == 0){ depotCoord = Coordinate.newInstance(Double.parseDouble(tokens[1]), Double.parseDouble(tokens[2])); } else{ Service.Builder serviceBuilder = Service.Builder.newInstance(tokens[0]).addSizeDimension(0, Integer.parseInt(tokens[3])); serviceBuilder.setCoord(Coordinate.newInstance(Double.parseDouble(tokens[1]), Double.parseDouble(tokens[2]))); vrpBuilder.addJob(serviceBuilder.build()); } customerCount++; } else if(trimedLine.startsWith("v")){ VehicleTypeImpl.Builder typeBuilder = VehicleTypeImpl.Builder.newInstance("type_"+tokens[1]).addCapacityDimension(0, Integer.parseInt(tokens[2])); int nuOfVehicles = 1; if(vrphType.equals(VrphType.FSMF)){ typeBuilder.setFixedCost(Double.parseDouble(tokens[3])); } else if(vrphType.equals(VrphType.FSMFD)){ typeBuilder.setFixedCost(Double.parseDouble(tokens[3])); if(tokens.length > 4){ typeBuilder.setCostPerDistance(Double.parseDouble(tokens[4])); } else throw new IllegalStateException("option " + vrphType + " cannot be applied with this instance"); } else if(vrphType.equals(VrphType.FSMD)){ if(tokens.length > 4){ typeBuilder.setCostPerDistance(Double.parseDouble(tokens[4])); } else throw new IllegalStateException("option " + vrphType + " cannot be applied with this instance"); } else if(vrphType.equals(VrphType.HVRPD)){ if(tokens.length > 4){ typeBuilder.setCostPerDistance(Double.parseDouble(tokens[4])); nuOfVehicles = Integer.parseInt(tokens[5]); vrpBuilder.setFleetSize(FleetSize.FINITE); vrpBuilder.addPenaltyVehicles(5.0, 5000); } else throw new IllegalStateException("option " + vrphType + " cannot be applied with this instance"); } else if (vrphType.equals(VrphType.HVRPFD)){ if(tokens.length > 4){ typeBuilder.setFixedCost(Double.parseDouble(tokens[3])); typeBuilder.setCostPerDistance(Double.parseDouble(tokens[4])); nuOfVehicles = Integer.parseInt(tokens[5]); vrpBuilder.setFleetSize(FleetSize.FINITE); vrpBuilder.addPenaltyVehicles(5.0, 5000); } else throw new IllegalStateException("option " + vrphType + " cannot be applied with this instance"); } for(int i=0;i<nuOfVehicles;i++){ VehicleTypeImpl type = typeBuilder.build(); Vehicle vehicle = VehicleImpl.Builder.newInstance("vehicle_"+tokens[1]+"_"+i) .setStartLocationCoordinate(depotCoord).setType(type).build(); vrpBuilder.addVehicle(vehicle); } } } closeReader(reader); }
#vulnerable code public void read(String filename){ BufferedReader reader = getReader(filename); String line = null; boolean firstline = true; Coordinate depotCoord = null; int customerCount=0; Integer nuOfCustomer = 0; while((line=readLine(reader))!=null){ String trimedLine = line.trim(); if(trimedLine.startsWith("//")) continue; String[] tokens = trimedLine.split("\\s+"); if(firstline){ nuOfCustomer=Integer.parseInt(tokens[0]); customerCount=0; firstline=false; } else if(customerCount<=nuOfCustomer) { if(customerCount == 0){ depotCoord = Coordinate.newInstance(Double.parseDouble(tokens[1]), Double.parseDouble(tokens[2])); } else{ Service.Builder serviceBuilder = Service.Builder.newInstance(tokens[0], Integer.parseInt(tokens[3])); serviceBuilder.setCoord(Coordinate.newInstance(Double.parseDouble(tokens[1]), Double.parseDouble(tokens[2]))); vrpBuilder.addJob(serviceBuilder.build()); } customerCount++; } else if(trimedLine.startsWith("v")){ VehicleTypeImpl.Builder typeBuilder = VehicleTypeImpl.Builder.newInstance("type_"+tokens[1], Integer.parseInt(tokens[2])); int nuOfVehicles = 1; if(vrphType.equals(VrphType.FSMF)){ typeBuilder.setFixedCost(Double.parseDouble(tokens[3])); } else if(vrphType.equals(VrphType.FSMFD)){ typeBuilder.setFixedCost(Double.parseDouble(tokens[3])); if(tokens.length > 4){ typeBuilder.setCostPerDistance(Double.parseDouble(tokens[4])); } else throw new IllegalStateException("option " + vrphType + " cannot be applied with this instance"); } else if(vrphType.equals(VrphType.FSMD)){ if(tokens.length > 4){ typeBuilder.setCostPerDistance(Double.parseDouble(tokens[4])); } else throw new IllegalStateException("option " + vrphType + " cannot be applied with this instance"); } else if(vrphType.equals(VrphType.HVRPD)){ if(tokens.length > 4){ typeBuilder.setCostPerDistance(Double.parseDouble(tokens[4])); nuOfVehicles = Integer.parseInt(tokens[5]); vrpBuilder.setFleetSize(FleetSize.FINITE); vrpBuilder.addPenaltyVehicles(5.0, 5000); } else throw new IllegalStateException("option " + vrphType + " cannot be applied with this instance"); } else if (vrphType.equals(VrphType.HVRPFD)){ if(tokens.length > 4){ typeBuilder.setFixedCost(Double.parseDouble(tokens[3])); typeBuilder.setCostPerDistance(Double.parseDouble(tokens[4])); nuOfVehicles = Integer.parseInt(tokens[5]); vrpBuilder.setFleetSize(FleetSize.FINITE); vrpBuilder.addPenaltyVehicles(5.0, 5000); } else throw new IllegalStateException("option " + vrphType + " cannot be applied with this instance"); } for(int i=0;i<nuOfVehicles;i++){ VehicleTypeImpl type = typeBuilder.build(); Vehicle vehicle = VehicleImpl.Builder.newInstance("vehicle_"+tokens[1]+"_"+i) .setLocationCoord(depotCoord).setType(type).build(); vrpBuilder.addVehicle(vehicle); } } } closeReader(reader); } #location 16 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public void read(String filename){ BufferedReader reader = getBufferedReader(filename); String line; Coordinate[] coords = null; int[] demands = null; Integer capacity = null; String edgeType = null; String edgeWeightFormat = null; List<Integer> depotIds = new ArrayList<Integer>(); boolean isCoordSection = false; boolean isDemandSection = false; boolean isDepotSection = false; boolean isEdgeWeightSection = false; List<Double> edgeWeights = new ArrayList<Double>(); int dimensions = 0; int coordIndex = 0; Map<Integer,Integer> indexMap = new HashMap<Integer, Integer>(); while( ( line = getLine(reader) ) != null ){ if(line.startsWith("EOF") || line.contains("EOF")){ break; } if(line.startsWith("DIMENSION")){ String[] tokens = line.split(":"); String dim = tokens[1].trim(); dimensions = Integer.parseInt(dim); coords = new Coordinate[dimensions]; demands = new int[dimensions]; continue; } if(line.startsWith("CAPACITY")){ String[] tokens = line.trim().split(":"); capacity = Integer.parseInt(tokens[1].trim()); continue; } if(line.startsWith("EDGE_WEIGHT_TYPE")){ String[] tokens = line.trim().split(":"); edgeType = tokens[1].trim(); continue; } if(line.startsWith("EDGE_WEIGHT_FORMAT")){ String[] tokens = line.trim().split(":"); edgeWeightFormat = tokens[1].trim(); continue; } if(line.startsWith("NODE_COORD_SECTION")){ isCoordSection = true; isDemandSection = false; isDepotSection = false; isEdgeWeightSection = false; continue; } if(line.startsWith("DEMAND_SECTION")){ isDemandSection = true; isCoordSection = false; isDepotSection = false; isEdgeWeightSection = false; continue; } if(line.startsWith("DEPOT_SECTION")){ isDepotSection = true; isDemandSection = false; isCoordSection = false; isEdgeWeightSection = false; continue; } if(line.startsWith("EDGE_WEIGHT_SECTION")){ isDepotSection = false; isCoordSection = false; isDemandSection = false; isEdgeWeightSection = true; continue; } if(line.startsWith("DISPLAY_DATA_SECTION")){ isDepotSection = false; isCoordSection = true; isDemandSection = false; isEdgeWeightSection = false; continue; } if(isCoordSection){ if(coords == null) throw new IllegalStateException("DIMENSION tag missing"); String[] tokens = line.trim().split("\\s+"); Integer id = Integer.parseInt(tokens[0]); coords[coordIndex] = Coordinate.newInstance(Double.parseDouble(tokens[1]), Double.parseDouble(tokens[2])); indexMap.put(id,coordIndex); coordIndex++; continue; } if(isDemandSection){ if(demands == null) throw new IllegalStateException("DIMENSION tag missing"); String[] tokens = line.trim().split("\\s+"); Integer id = Integer.parseInt(tokens[0]); int index = indexMap.get(id); demands[index] = Integer.parseInt(tokens[1]); continue; } if(isDepotSection){ if(line.equals("-1")){ isDepotSection = false; } else{ depotIds.add(Integer.parseInt(line)); } continue; } if(isEdgeWeightSection){ String[] tokens = line.trim().split("\\s+"); for (String s : tokens) edgeWeights.add(Double.parseDouble(s)); continue; } } close(reader); vrpBuilder.setFleetSize(VehicleRoutingProblem.FleetSize.FINITE); for(Integer depotId : depotIds){ VehicleTypeImpl type = VehicleTypeImpl.Builder.newInstance("type").addCapacityDimension(0,capacity).build(); VehicleImpl vehicle = VehicleImpl.Builder.newInstance("vehicle").setStartLocationId(depotId.toString()) .setStartLocationCoordinate(coords[depotId - 1]).setType(type).build(); vrpBuilder.addVehicle(vehicle); } for (Integer id_ : indexMap.keySet()) { String id = id_.toString(); int index = indexMap.get(id_); if(depotIds.isEmpty()){ if(index == 0) { VehicleImpl vehicle = VehicleImpl.Builder.newInstance("traveling_salesman") .setStartLocation(Location.Builder.newInstance().setId(id) .setCoordinate(coords[index]).setIndex(index).build()) .build(); vrpBuilder.addVehicle(vehicle); continue; } } Service service = Service.Builder.newInstance(id) .setLocation(Location.Builder.newInstance().setId(id) .setCoordinate(coords[index]).setIndex(index).build()) .addSizeDimension(0, demands[index]).build(); vrpBuilder.addJob(service); } if(edgeType.equals("GEO")){ List<Location> locations = new ArrayList<Location>(); for(Vehicle v : vrpBuilder.getAddedVehicles()) locations.add(v.getStartLocation()); for(Job j : vrpBuilder.getAddedJobs()) locations.add(((Service)j).getLocation()); vrpBuilder.setRoutingCost(getGEOMatrix(locations)); } else if(edgeType.equals("EXPLICIT")){ if(edgeWeightFormat.equals("UPPER_ROW")){ FastVehicleRoutingTransportCostsMatrix.Builder matrixBuilder = FastVehicleRoutingTransportCostsMatrix.Builder.newInstance(dimensions,true); int fromIndex = 0; int toIndex = 1; for(int i=0;i<edgeWeights.size();i++){ if(toIndex == dimensions){ fromIndex++; toIndex = fromIndex + 1; } matrixBuilder.addTransportDistance(fromIndex, toIndex, edgeWeights.get(i)); matrixBuilder.addTransportTime(fromIndex,toIndex,edgeWeights.get(i)); toIndex++; } vrpBuilder.setRoutingCost(matrixBuilder.build()); } else if(edgeWeightFormat.equals("UPPER_DIAG_ROW")){ FastVehicleRoutingTransportCostsMatrix.Builder matrixBuilder = FastVehicleRoutingTransportCostsMatrix.Builder.newInstance(dimensions,true); int fromIndex = 0; int toIndex = 0; for(int i=0;i<edgeWeights.size();i++){ if(toIndex == dimensions){ fromIndex++; toIndex = fromIndex; } matrixBuilder.addTransportDistance(fromIndex,toIndex,edgeWeights.get(i)); matrixBuilder.addTransportTime(fromIndex,toIndex,edgeWeights.get(i)); toIndex++; } vrpBuilder.setRoutingCost(matrixBuilder.build()); } else if(edgeWeightFormat.equals("LOWER_DIAG_ROW")){ FastVehicleRoutingTransportCostsMatrix.Builder matrixBuilder = FastVehicleRoutingTransportCostsMatrix.Builder.newInstance(dimensions,true); int fromIndex = 0; int toIndex = 0; for(int i=0;i<edgeWeights.size();i++){ if(toIndex > fromIndex){ fromIndex++; toIndex = 0; } matrixBuilder.addTransportDistance(fromIndex,toIndex,edgeWeights.get(i)); matrixBuilder.addTransportTime(fromIndex,toIndex,edgeWeights.get(i)); toIndex++; } vrpBuilder.setRoutingCost(matrixBuilder.build()); } else if(edgeWeightFormat.equals("FULL_MATRIX")){ FastVehicleRoutingTransportCostsMatrix.Builder matrixBuilder = FastVehicleRoutingTransportCostsMatrix.Builder.newInstance(dimensions,false); int fromIndex = 0; int toIndex = 0; for(int i=0;i<edgeWeights.size();i++){ if(toIndex == dimensions){ fromIndex++; toIndex = 0; } matrixBuilder.addTransportDistance(fromIndex,toIndex,edgeWeights.get(i)); matrixBuilder.addTransportTime(fromIndex,toIndex,edgeWeights.get(i)); toIndex++; } vrpBuilder.setRoutingCost(matrixBuilder.build()); } } }
#vulnerable code public void read(String filename){ BufferedReader reader = getBufferedReader(filename); String line; Coordinate[] coords = null; int[] demands = null; Integer capacity = null; String edgeType = null; String edgeWeightFormat = null; List<Integer> depotIds = new ArrayList<Integer>(); boolean isCoordSection = false; boolean isDemandSection = false; boolean isDepotSection = false; boolean isEdgeWeightSection = false; List<Double> edgeWeights = new ArrayList<Double>(); int dimensions = 0; while( ( line = getLine(reader) ) != null ){ if(line.startsWith("EOF") || line.contains("EOF")){ break; } if(line.startsWith("DIMENSION")){ String[] tokens = line.split(":"); String dim = tokens[1].trim(); dimensions = Integer.parseInt(dim); coords = new Coordinate[dimensions]; demands = new int[dimensions]; continue; } if(line.startsWith("CAPACITY")){ String[] tokens = line.trim().split(":"); capacity = Integer.parseInt(tokens[1].trim()); continue; } if(line.startsWith("EDGE_WEIGHT_TYPE")){ String[] tokens = line.trim().split(":"); edgeType = tokens[1].trim(); continue; } if(line.startsWith("EDGE_WEIGHT_FORMAT")){ String[] tokens = line.trim().split(":"); edgeWeightFormat = tokens[1].trim(); continue; } if(line.startsWith("NODE_COORD_SECTION")){ isCoordSection = true; isDemandSection = false; isDepotSection = false; isEdgeWeightSection = false; continue; } if(line.startsWith("DEMAND_SECTION")){ isDemandSection = true; isCoordSection = false; isDepotSection = false; isEdgeWeightSection = false; continue; } if(line.startsWith("DEPOT_SECTION")){ isDepotSection = true; isDemandSection = false; isCoordSection = false; isEdgeWeightSection = false; continue; } if(line.startsWith("EDGE_WEIGHT_SECTION")){ isDepotSection = false; isCoordSection = false; isDemandSection = false; isEdgeWeightSection = true; continue; } if(line.startsWith("DISPLAY_DATA_SECTION")){ isDepotSection = false; isCoordSection = true; isDemandSection = false; isEdgeWeightSection = false; continue; } if(isCoordSection){ if(coords == null) throw new IllegalStateException("DIMENSION tag missing"); String[] tokens = line.trim().split("\\s+"); coords[Integer.parseInt(tokens[0]) - 1] = Coordinate.newInstance(Double.parseDouble(tokens[1]), Double.parseDouble(tokens[2])); continue; } if(isDemandSection){ if(demands == null) throw new IllegalStateException("DIMENSION tag missing"); String[] tokens = line.trim().split("\\s+"); demands[Integer.parseInt(tokens[0]) - 1] = Integer.parseInt(tokens[1]); continue; } if(isDepotSection){ if(line.equals("-1")){ isDepotSection = false; } else{ depotIds.add(Integer.parseInt(line)); } continue; } if(isEdgeWeightSection){ String[] tokens = line.trim().split("\\s+"); for (String s : tokens) edgeWeights.add(Double.parseDouble(s)); continue; } } close(reader); vrpBuilder.setFleetSize(VehicleRoutingProblem.FleetSize.FINITE); for(Integer depotId : depotIds){ VehicleTypeImpl type = VehicleTypeImpl.Builder.newInstance("type").addCapacityDimension(0,capacity).build(); VehicleImpl vehicle = VehicleImpl.Builder.newInstance("vehicle").setStartLocationId(depotId.toString()) .setStartLocationCoordinate(coords[depotId - 1]).setType(type).build(); vrpBuilder.addVehicle(vehicle); } for (int i = 0; i < coords.length; i++) { String id = "" + (i + 1); if(depotIds.isEmpty()){ if(i==0) { VehicleImpl vehicle = VehicleImpl.Builder.newInstance("traveling_salesman") .setStartLocation(Location.Builder.newInstance().setId(id) .setCoordinate(coords[i]).setIndex(i).build()) .build(); vrpBuilder.addVehicle(vehicle); continue; } } Service service = Service.Builder.newInstance(id) .setLocation(Location.Builder.newInstance().setId(id) .setCoordinate(coords[i]).setIndex(i).build()) .addSizeDimension(0, demands[i]).build(); vrpBuilder.addJob(service); } if(edgeType.equals("GEO")){ List<Location> locations = new ArrayList<Location>(); for(Vehicle v : vrpBuilder.getAddedVehicles()) locations.add(v.getStartLocation()); for(Job j : vrpBuilder.getAddedJobs()) locations.add(((Service)j).getLocation()); vrpBuilder.setRoutingCost(getGEOMatrix(locations)); } else if(edgeType.equals("EXPLICIT")){ if(edgeWeightFormat.equals("UPPER_ROW")){ FastVehicleRoutingTransportCostsMatrix.Builder matrixBuilder = FastVehicleRoutingTransportCostsMatrix.Builder.newInstance(dimensions,true); int fromIndex = 0; int toIndex = 1; for(int i=0;i<edgeWeights.size();i++){ if(toIndex == dimensions){ fromIndex++; toIndex = fromIndex + 1; } matrixBuilder.addTransportDistance(fromIndex, toIndex, edgeWeights.get(i)); matrixBuilder.addTransportTime(fromIndex,toIndex,edgeWeights.get(i)); toIndex++; } vrpBuilder.setRoutingCost(matrixBuilder.build()); } else if(edgeWeightFormat.equals("UPPER_DIAG_ROW")){ FastVehicleRoutingTransportCostsMatrix.Builder matrixBuilder = FastVehicleRoutingTransportCostsMatrix.Builder.newInstance(dimensions,true); int fromIndex = 0; int toIndex = 0; for(int i=0;i<edgeWeights.size();i++){ if(toIndex == dimensions){ fromIndex++; toIndex = fromIndex; } matrixBuilder.addTransportDistance(fromIndex,toIndex,edgeWeights.get(i)); matrixBuilder.addTransportTime(fromIndex,toIndex,edgeWeights.get(i)); toIndex++; } vrpBuilder.setRoutingCost(matrixBuilder.build()); } else if(edgeWeightFormat.equals("LOWER_DIAG_ROW")){ FastVehicleRoutingTransportCostsMatrix.Builder matrixBuilder = FastVehicleRoutingTransportCostsMatrix.Builder.newInstance(dimensions,true); int fromIndex = 0; int toIndex = 0; for(int i=0;i<edgeWeights.size();i++){ if(toIndex > fromIndex){ fromIndex++; toIndex = 0; } matrixBuilder.addTransportDistance(fromIndex,toIndex,edgeWeights.get(i)); matrixBuilder.addTransportTime(fromIndex,toIndex,edgeWeights.get(i)); toIndex++; } vrpBuilder.setRoutingCost(matrixBuilder.build()); } else if(edgeWeightFormat.equals("FULL_MATRIX")){ FastVehicleRoutingTransportCostsMatrix.Builder matrixBuilder = FastVehicleRoutingTransportCostsMatrix.Builder.newInstance(dimensions,true); int fromIndex = 0; int toIndex = 0; for(int i=0;i<edgeWeights.size();i++){ if(toIndex == dimensions){ fromIndex++; toIndex = 0; } matrixBuilder.addTransportDistance(fromIndex,toIndex,edgeWeights.get(i)); matrixBuilder.addTransportTime(fromIndex,toIndex,edgeWeights.get(i)); toIndex++; } vrpBuilder.setRoutingCost(matrixBuilder.build()); } } } #location 115 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Override public void informJobInserted(Job job2insert, VehicleRoute inRoute, double additionalCosts, double additionalTime) { if(job2insert instanceof Delivery){ Capacity loadAtDepot = stateManager.getRouteState(inRoute, StateFactory.LOAD_AT_BEGINNING, Capacity.class); stateManager.putInternalRouteState_(inRoute, StateFactory.LOAD_AT_BEGINNING, Capacity.class, Capacity.addup(loadAtDepot, job2insert.getSize())); } else if(job2insert instanceof Pickup || job2insert instanceof Service){ Capacity loadAtEnd = stateManager.getRouteState(inRoute, StateFactory.LOAD_AT_END, Capacity.class); stateManager.putInternalRouteState_(inRoute, StateFactory.LOAD_AT_END, Capacity.class, Capacity.addup(loadAtEnd, job2insert.getSize())); } }
#vulnerable code @Override public void informJobInserted(Job job2insert, VehicleRoute inRoute, double additionalCosts, double additionalTime) { if(job2insert instanceof Delivery){ int loadAtDepot = (int) stateManager.getRouteState(inRoute, StateFactory.LOAD_AT_BEGINNING).toDouble(); stateManager.putInternalRouteState(inRoute, StateFactory.LOAD_AT_BEGINNING, StateFactory.createState(loadAtDepot + job2insert.getCapacityDemand())); } else if(job2insert instanceof Pickup || job2insert instanceof Service){ int loadAtEnd = (int) stateManager.getRouteState(inRoute, StateFactory.LOAD_AT_END).toDouble(); stateManager.putInternalRouteState(inRoute, StateFactory.LOAD_AT_END, StateFactory.createState(loadAtEnd + job2insert.getCapacityDemand())); } } #location 4 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Test public void skillViolationAtAct4_shouldWork(){ SolutionAnalyser analyser = new SolutionAnalyser(vrp,solution, new SolutionAnalyser.DistanceCalculator() { @Override public double getDistance(String fromLocationId, String toLocationId) { return vrp.getTransportCosts().getTransportCost(fromLocationId,toLocationId,0.,null,null); } }); VehicleRoute route = solution.getRoutes().iterator().next(); Boolean violated = analyser.hasSkillConstraintViolationAtActivity(route.getActivities().get(3), route); assertFalse(violated); }
#vulnerable code @Test public void skillViolationAtAct4_shouldWork(){ SolutionAnalyser analyser = new SolutionAnalyser(vrp,solution, new SolutionAnalyser.DistanceCalculator() { @Override public double getDistance(String fromLocationId, String toLocationId) { return vrp.getTransportCosts().getTransportCost(fromLocationId,toLocationId,0.,null,null); } }); VehicleRoute route = solution.getRoutes().iterator().next(); Boolean violated = analyser.skillConstraintIsViolatedAtActivity(route.getActivities().get(3),route); assertFalse(violated); } #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 skillViolationAtAct2_shouldWork(){ SolutionAnalyser analyser = new SolutionAnalyser(vrp,solution, new SolutionAnalyser.DistanceCalculator() { @Override public double getDistance(String fromLocationId, String toLocationId) { return vrp.getTransportCosts().getTransportCost(fromLocationId,toLocationId,0.,null,null); } }); VehicleRoute route = solution.getRoutes().iterator().next(); Boolean violated = analyser.hasSkillConstraintViolationAtActivity(route.getActivities().get(1), route); assertTrue(violated); }
#vulnerable code @Test public void skillViolationAtAct2_shouldWork(){ SolutionAnalyser analyser = new SolutionAnalyser(vrp,solution, new SolutionAnalyser.DistanceCalculator() { @Override public double getDistance(String fromLocationId, String toLocationId) { return vrp.getTransportCosts().getTransportCost(fromLocationId,toLocationId,0.,null,null); } }); VehicleRoute route = solution.getRoutes().iterator().next(); Boolean violated = analyser.skillConstraintIsViolatedAtActivity(route.getActivities().get(1),route); assertTrue(violated); } #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 whenVehicleRouteIsEmpty_loadsAtBeginningAndEndShouldBeZero(){ StateManager stateManager = new StateManager(mock(VehicleRoutingTransportCosts.class)); UpdateLoads updateLoads = new UpdateLoads(stateManager); VehicleRoute route = VehicleRoute.emptyRoute(); updateLoads.informInsertionStarts(Arrays.asList(route), Collections.<Job>emptyList()); Capacity loadAtBeginning = stateManager.getRouteState(route, StateFactory.LOAD_AT_BEGINNING, Capacity.class); assertEquals(0.,loadAtBeginning.get(0),0.1); assertEquals(0.,stateManager.getRouteState(route, StateFactory.LOAD_AT_END, Capacity.class).get(0),0.1); }
#vulnerable code @Test public void whenVehicleRouteIsEmpty_loadsAtBeginningAndEndShouldBeZero(){ StateManager stateManager = new StateManager(mock(VehicleRoutingProblem.class)); UpdateLoads updateLoads = new UpdateLoads(stateManager); VehicleRoute route = VehicleRoute.emptyRoute(); updateLoads.informInsertionStarts(Arrays.asList(route), Collections.<Job>emptyList()); assertEquals(0.,stateManager.getRouteState(route, StateFactory.LOAD_AT_BEGINNING).toDouble(),0.1); assertEquals(0.,stateManager.getRouteState(route, StateFactory.LOAD_AT_END).toDouble(),0.1); } #location 10 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Test public void testStatesOfAct1(){ states.informInsertionStarts(Arrays.asList(vehicleRoute), null); assertEquals(10.0, states.getActivityState(act1, StateFactory.COSTS).toDouble(),0.05); assertEquals(5.0, states.getActivityState(act1, StateFactory.LOAD).toDouble(),0.05); assertEquals(20.0, states.getActivityState(act1, StateFactory.LATEST_OPERATION_START_TIME).toDouble(),0.05); }
#vulnerable code @Test public void testStatesOfAct1(){ states.informInsertionStarts(Arrays.asList(vehicleRoute), null); assertEquals(10.0, states.getActivityState(tour.getActivities().get(0), StateFactory.COSTS).toDouble(),0.05); assertEquals(5.0, states.getActivityState(tour.getActivities().get(0), StateFactory.LOAD).toDouble(),0.05); // assertEquals(10.0, states.getActivityState(tour.getActivities().get(0), StateTypes.EARLIEST_OPERATION_START_TIME).toDouble(),0.05); assertEquals(20.0, states.getActivityState(tour.getActivities().get(0), StateFactory.LATEST_OPERATION_START_TIME).toDouble(),0.05); } #location 4 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Test public void whenWritingVehicleV1_itsStartLocationMustBeWrittenCorrectly(){ Builder builder = VehicleRoutingProblem.Builder.newInstance(); VehicleTypeImpl type1 = VehicleTypeImpl.Builder.newInstance("vehType").addCapacityDimension(0, 20).build(); VehicleTypeImpl type2 = VehicleTypeImpl.Builder.newInstance("vehType2").addCapacityDimension(0, 200).build(); VehicleImpl v1 = VehicleImpl.Builder.newInstance("v1").setStartLocation(TestUtils.loc("loc")).setType(type1).build(); VehicleImpl v2 = VehicleImpl.Builder.newInstance("v2").setStartLocation(TestUtils.loc("loc")).setType(type2).build(); builder.addVehicle(v1); builder.addVehicle(v2); Service s1 = Service.Builder.newInstance("1").addSizeDimension(0, 1).setLocation(TestUtils.loc("loc")).setServiceTime(2.0).build(); Service s2 = Service.Builder.newInstance("2").addSizeDimension(0, 1).setLocation(TestUtils.loc("loc2")).setServiceTime(4.0).build(); VehicleRoutingProblem vrp = builder.addJob(s1).addJob(s2).build(); new VrpXMLWriter(vrp, null).write(infileName); VehicleRoutingProblem.Builder vrpToReadBuilder = VehicleRoutingProblem.Builder.newInstance(); new VrpXMLReader(vrpToReadBuilder, null).read(infileName); VehicleRoutingProblem readVrp = vrpToReadBuilder.build(); Vehicle v = getVehicle("v1",readVrp.getVehicles()); assertEquals("loc",v.getStartLocation().getId()); assertEquals("loc",v.getEndLocation().getId()); }
#vulnerable code @Test public void whenWritingVehicleV1_itsStartLocationMustBeWrittenCorrectly(){ Builder builder = VehicleRoutingProblem.Builder.newInstance(); VehicleTypeImpl type1 = VehicleTypeImpl.Builder.newInstance("vehType").addCapacityDimension(0, 20).build(); VehicleTypeImpl type2 = VehicleTypeImpl.Builder.newInstance("vehType2").addCapacityDimension(0, 200).build(); VehicleImpl v1 = VehicleImpl.Builder.newInstance("v1").setStartLocationId("loc").setType(type1).build(); VehicleImpl v2 = VehicleImpl.Builder.newInstance("v2").setStartLocationId("loc").setType(type2).build(); builder.addVehicle(v1); builder.addVehicle(v2); Service s1 = Service.Builder.newInstance("1").addSizeDimension(0, 1).setLocationId("loc").setServiceTime(2.0).build(); Service s2 = Service.Builder.newInstance("2").addSizeDimension(0, 1).setLocationId("loc2").setServiceTime(4.0).build(); VehicleRoutingProblem vrp = builder.addJob(s1).addJob(s2).build(); new VrpXMLWriter(vrp, null).write(infileName); VehicleRoutingProblem.Builder vrpToReadBuilder = VehicleRoutingProblem.Builder.newInstance(); new VrpXMLReader(vrpToReadBuilder, null).read(infileName); VehicleRoutingProblem readVrp = vrpToReadBuilder.build(); Vehicle v = getVehicle("v1",readVrp.getVehicles()); assertEquals("loc",v.getStartLocationId()); assertEquals("loc",v.getEndLocationId()); } #location 24 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public void read(String filename){ BufferedReader reader = getBufferedReader(filename); String line; Coordinate[] coords = null; Integer[] demands = null; Integer capacity = null; List<Integer> depotIds = new ArrayList<Integer>(); boolean isCoordSection = false; boolean isDemandSection = false; boolean isDepotSection = false; while( ( line = getLine(reader) ) != null ){ if(line.startsWith("DIMENSION")){ String[] tokens = line.split(":"); String dim = tokens[1].trim(); coords = new Coordinate[Integer.parseInt(dim)]; demands = new Integer[Integer.parseInt(dim)]; continue; } if(line.startsWith("CAPACITY")){ String[] tokens = line.split(":"); capacity = Integer.parseInt(tokens[1].trim()); continue; } if(line.startsWith("NODE_COORD_SECTION")){ isCoordSection = true; isDemandSection = false; isDepotSection = false; continue; } if(line.startsWith("DEMAND_SECTION")){ isDemandSection = true; isCoordSection = false; isDepotSection = false; continue; } if(line.startsWith("DEPOT_SECTION")){ isDepotSection = true; isDemandSection = false; isCoordSection = false; continue; } if(isCoordSection){ if(coords == null) throw new IllegalStateException("DIMENSION tag missing"); String[] tokens = line.split("\\s+"); coords[Integer.parseInt(tokens[0]) - 1] = Coordinate.newInstance(Double.parseDouble(tokens[1]), Double.parseDouble(tokens[2])); continue; } if(isDemandSection){ if(demands == null) throw new IllegalStateException("DIMENSION tag missing"); String[] tokens = line.split("\\s+"); demands[Integer.parseInt(tokens[0]) - 1] = Integer.parseInt(tokens[1]); continue; } if(isDepotSection){ if(line.equals("-1")){ isDepotSection = false; } else{ depotIds.add(Integer.parseInt(line)); } } } close(reader); vrpBuilder.setFleetSize(VehicleRoutingProblem.FleetSize.INFINITE); for(Integer depotId : depotIds){ VehicleTypeImpl type = VehicleTypeImpl.Builder.newInstance("typeId").addCapacityDimension(0,capacity).build(); VehicleImpl vehicle = VehicleImpl.Builder.newInstance("vehicle").setStartLocationId(depotId.toString()) .setStartLocationCoordinate(coords[depotId - 1]).setType(type).build(); vrpBuilder.addVehicle(vehicle); } for(int i=0;i<demands.length;i++){ if(demands[i] == 0) continue; String id = "" + (i+1); Service service = Service.Builder.newInstance(id).setLocationId(id).setCoord(coords[i]).addSizeDimension(0,demands[i]).build(); vrpBuilder.addJob(service); } }
#vulnerable code public void read(String filename){ BufferedReader reader = getBufferedReader(filename); String line; Coordinate[] coords = null; Integer[] demands = null; Integer capacity = null; List<Integer> depotIds = new ArrayList<Integer>(); boolean isCoordSection = false; boolean isDemandSection = false; boolean isDepotSection = false; while( ( line = getLine(reader) ) != null ){ if(line.startsWith("DIMENSION")){ String[] tokens = line.split(":"); String dim = tokens[1].trim(); coords = new Coordinate[Integer.parseInt(dim)]; demands = new Integer[Integer.parseInt(dim)]; continue; } if(line.startsWith("CAPACITY")){ String[] tokens = line.split(":"); capacity = Integer.parseInt(tokens[1].trim()); continue; } if(line.startsWith("NODE_COORD_SECTION")){ isCoordSection = true; isDemandSection = false; isDepotSection = false; continue; } if(line.startsWith("DEMAND_SECTION")){ isDemandSection = true; isCoordSection = false; isDepotSection = false; continue; } if(line.startsWith("DEPOT_SECTION")){ isDepotSection = true; isDemandSection = false; isCoordSection = false; continue; } if(isCoordSection){ if(coords == null) throw new IllegalStateException("DIMENSION tag missing"); String[] tokens = line.split("\\s+"); coords[Integer.parseInt(tokens[0]) - 1] = Coordinate.newInstance(Double.parseDouble(tokens[1]), Double.parseDouble(tokens[2])); continue; } if(isDemandSection){ if(demands == null) throw new IllegalStateException("DIMENSION tag missing"); String[] tokens = line.split("\\s+"); demands[Integer.parseInt(tokens[0]) - 1] = Integer.parseInt(tokens[1]); continue; } if(isDepotSection){ if(line.equals("-1")){ isDepotSection = false; } else{ depotIds.add(Integer.parseInt(line)); } } } vrpBuilder.setFleetSize(VehicleRoutingProblem.FleetSize.INFINITE); for(Integer depotId : depotIds){ VehicleTypeImpl type = VehicleTypeImpl.Builder.newInstance("typeId").addCapacityDimension(0,capacity).build(); VehicleImpl vehicle = VehicleImpl.Builder.newInstance("vehicle").setStartLocationId(depotId.toString()) .setStartLocationCoordinate(coords[depotId - 1]).setType(type).build(); vrpBuilder.addVehicle(vehicle); } for(int i=0;i<demands.length;i++){ if(demands[i] == 0) continue; String id = "" + (i+1); Service service = Service.Builder.newInstance(id).setLocationId(id).setCoord(coords[i]).addSizeDimension(0,demands[i]).build(); vrpBuilder.addJob(service); } } #location 63 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Override public void informJobInserted(Job job2insert, VehicleRoute inRoute, double additionalCosts, double additionalTime) { if(job2insert instanceof Delivery){ Capacity loadAtDepot = stateManager.getRouteState(inRoute, StateFactory.LOAD_AT_BEGINNING, Capacity.class); stateManager.putInternalRouteState_(inRoute, StateFactory.LOAD_AT_BEGINNING, Capacity.class, Capacity.addup(loadAtDepot, job2insert.getSize())); } else if(job2insert instanceof Pickup || job2insert instanceof Service){ Capacity loadAtEnd = stateManager.getRouteState(inRoute, StateFactory.LOAD_AT_END, Capacity.class); stateManager.putInternalRouteState_(inRoute, StateFactory.LOAD_AT_END, Capacity.class, Capacity.addup(loadAtEnd, job2insert.getSize())); } }
#vulnerable code @Override public void informJobInserted(Job job2insert, VehicleRoute inRoute, double additionalCosts, double additionalTime) { if(job2insert instanceof Delivery){ int loadAtDepot = (int) stateManager.getRouteState(inRoute, StateFactory.LOAD_AT_BEGINNING).toDouble(); stateManager.putInternalRouteState(inRoute, StateFactory.LOAD_AT_BEGINNING, StateFactory.createState(loadAtDepot + job2insert.getCapacityDemand())); } else if(job2insert instanceof Pickup || job2insert instanceof Service){ int loadAtEnd = (int) stateManager.getRouteState(inRoute, StateFactory.LOAD_AT_END).toDouble(); stateManager.putInternalRouteState(inRoute, StateFactory.LOAD_AT_END, StateFactory.createState(loadAtEnd + job2insert.getCapacityDemand())); } } #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 whenWritingVehicleV2_readingItsLocationsAgainReturnsCorrectLocations(){ Builder builder = VehicleRoutingProblem.Builder.newInstance(); VehicleTypeImpl type1 = VehicleTypeImpl.Builder.newInstance("vehType").addCapacityDimension(0, 20).build(); VehicleTypeImpl type2 = VehicleTypeImpl.Builder.newInstance("vehType2").addCapacityDimension(0, 200).build(); VehicleImpl v1 = VehicleImpl.Builder.newInstance("v1").setReturnToDepot(false).setStartLocation(TestUtils.loc("loc")).setType(type1).build(); VehicleImpl v2 = VehicleImpl.Builder.newInstance("v2") .setStartLocation(TestUtils.loc("startLoc", Coordinate.newInstance(1, 2))) .setEndLocation(TestUtils.loc("endLoc", Coordinate.newInstance(4, 5))).setType(type2).build(); builder.addVehicle(v1); builder.addVehicle(v2); Service s1 = Service.Builder.newInstance("1").addSizeDimension(0, 1).setLocation(TestUtils.loc("loc")).setServiceTime(2.0).build(); Service s2 = Service.Builder.newInstance("2").addSizeDimension(0, 1).setLocation(TestUtils.loc("loc2")).setServiceTime(4.0).build(); VehicleRoutingProblem vrp = builder.addJob(s1).addJob(s2).build(); new VrpXMLWriter(vrp, null).write(infileName); VehicleRoutingProblem.Builder vrpToReadBuilder = VehicleRoutingProblem.Builder.newInstance(); new VrpXMLReader(vrpToReadBuilder, null).read(infileName); VehicleRoutingProblem readVrp = vrpToReadBuilder.build(); Vehicle v = getVehicle("v2",readVrp.getVehicles()); assertEquals("startLoc",v.getStartLocation().getId()); assertEquals("endLoc",v.getEndLocation().getId()); }
#vulnerable code @Test public void whenWritingVehicleV2_readingItsLocationsAgainReturnsCorrectLocations(){ Builder builder = VehicleRoutingProblem.Builder.newInstance(); VehicleTypeImpl type1 = VehicleTypeImpl.Builder.newInstance("vehType").addCapacityDimension(0, 20).build(); VehicleTypeImpl type2 = VehicleTypeImpl.Builder.newInstance("vehType2").addCapacityDimension(0, 200).build(); VehicleImpl v1 = VehicleImpl.Builder.newInstance("v1").setReturnToDepot(false).setStartLocationId("loc").setType(type1).build(); VehicleImpl v2 = VehicleImpl.Builder.newInstance("v2").setStartLocationId("startLoc").setStartLocationCoordinate(Coordinate.newInstance(1, 2)) .setEndLocationId("endLoc").setEndLocationCoordinate(Coordinate.newInstance(4, 5)).setType(type2).build(); builder.addVehicle(v1); builder.addVehicle(v2); Service s1 = Service.Builder.newInstance("1").addSizeDimension(0, 1).setLocationId("loc").setServiceTime(2.0).build(); Service s2 = Service.Builder.newInstance("2").addSizeDimension(0, 1).setLocationId("loc2").setServiceTime(4.0).build(); VehicleRoutingProblem vrp = builder.addJob(s1).addJob(s2).build(); new VrpXMLWriter(vrp, null).write(infileName); VehicleRoutingProblem.Builder vrpToReadBuilder = VehicleRoutingProblem.Builder.newInstance(); new VrpXMLReader(vrpToReadBuilder, null).read(infileName); VehicleRoutingProblem readVrp = vrpToReadBuilder.build(); Vehicle v = getVehicle("v2",readVrp.getVehicles()); assertEquals("startLoc",v.getStartLocationId()); assertEquals("endLoc",v.getEndLocationId()); } #location 25 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public void read(String fileName){ vrpBuilder.setFleetSize(FleetSize.INFINITE); BufferedReader reader = getReader(fileName); int vehicleCapacity = 0; double serviceTime = 0.0; double endTime = Double.MAX_VALUE; int counter = 0; String line = null; while((line = readLine(reader)) != null){ line = line.replace("\r", ""); line = line.trim(); String[] tokens = line.split(" "); if(counter == 0){ vehicleCapacity = Integer.parseInt(tokens[1].trim()); endTime = Double.parseDouble(tokens[2].trim()); serviceTime = Double.parseDouble(tokens[3].trim()); } else if(counter == 1){ Coordinate depotCoord = makeCoord(tokens[0].trim(),tokens[1].trim()); VehicleTypeImpl vehicleType = VehicleTypeImpl.Builder.newInstance("christophidesType").addCapacityDimension(0, vehicleCapacity). setCostPerDistance(1.0).build(); Vehicle vehicle = VehicleImpl.Builder.newInstance("christophidesVehicle").setLatestArrival(endTime).setStartLocationCoordinate(depotCoord). setType(vehicleType).build(); vrpBuilder.addVehicle(vehicle); } else{ Coordinate customerCoord = makeCoord(tokens[0].trim(),tokens[1].trim()); int demand = Integer.parseInt(tokens[2].trim()); String customer = Integer.valueOf(counter-1).toString(); Service service = Service.Builder.newInstance(customer).addSizeDimension(0, demand).setServiceTime(serviceTime).setCoord(customerCoord).build(); vrpBuilder.addJob(service); } counter++; } close(reader); }
#vulnerable code public void read(String fileName){ vrpBuilder.setFleetSize(FleetSize.INFINITE); BufferedReader reader = getReader(fileName); int vehicleCapacity = 0; double serviceTime = 0.0; double endTime = Double.MAX_VALUE; int counter = 0; String line = null; while((line = readLine(reader)) != null){ line = line.replace("\r", ""); line = line.trim(); String[] tokens = line.split(" "); if(counter == 0){ vehicleCapacity = Integer.parseInt(tokens[1].trim()); endTime = Double.parseDouble(tokens[2].trim()); serviceTime = Double.parseDouble(tokens[3].trim()); } else if(counter == 1){ Coordinate depotCoord = makeCoord(tokens[0].trim(),tokens[1].trim()); VehicleTypeImpl vehicleType = VehicleTypeImpl.Builder.newInstance("christophidesType", vehicleCapacity). setCostPerDistance(1.0).build(); Vehicle vehicle = VehicleImpl.Builder.newInstance("christophidesVehicle").setLatestArrival(endTime).setLocationCoord(depotCoord). setType(vehicleType).build(); vrpBuilder.addVehicle(vehicle); } else{ Coordinate customerCoord = makeCoord(tokens[0].trim(),tokens[1].trim()); int demand = Integer.parseInt(tokens[2].trim()); String customer = Integer.valueOf(counter-1).toString(); Service service = Service.Builder.newInstance(customer, demand).setServiceTime(serviceTime).setCoord(customerCoord).build(); vrpBuilder.addJob(service); } counter++; } close(reader); } #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 testStatesOfAct2(){ states.informInsertionStarts(Arrays.asList(vehicleRoute), null); assertEquals(30.0, states.getActivityState(act2, StateFactory.COSTS).toDouble(),0.05); assertEquals(10.0, states.getActivityState(act2, StateFactory.LOAD).toDouble(),0.05); assertEquals(40.0, states.getActivityState(act2, StateFactory.LATEST_OPERATION_START_TIME).toDouble(),0.05); }
#vulnerable code @Test public void testStatesOfAct2(){ states.informInsertionStarts(Arrays.asList(vehicleRoute), null); assertEquals(30.0, states.getActivityState(tour.getActivities().get(1), StateFactory.COSTS).toDouble(),0.05); assertEquals(10.0, states.getActivityState(tour.getActivities().get(1), StateFactory.LOAD).toDouble(),0.05); // assertEquals(10.0, states.getActivityState(tour.getActivities().get(0), StateTypes.EARLIEST_OPERATION_START_TIME).toDouble(),0.05); assertEquals(40.0, states.getActivityState(tour.getActivities().get(1), StateFactory.LATEST_OPERATION_START_TIME).toDouble(),0.05); } #location 5 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Test public void whenWritingVehicleV2_readingItsLocationsCoordsAgainReturnsCorrectLocationsCoords(){ Builder builder = VehicleRoutingProblem.Builder.newInstance(); VehicleTypeImpl type1 = VehicleTypeImpl.Builder.newInstance("vehType").addCapacityDimension(0, 20).build(); VehicleTypeImpl type2 = VehicleTypeImpl.Builder.newInstance("vehType2").addCapacityDimension(0, 200).build(); VehicleImpl v1 = VehicleImpl.Builder.newInstance("v1").setReturnToDepot(false) .setStartLocation(TestUtils.loc("loc")).setType(type1).build(); VehicleImpl v2 = VehicleImpl.Builder.newInstance("v2") .setStartLocation(TestUtils.loc("startLoc", Coordinate.newInstance(1, 2))) .setEndLocation(TestUtils.loc("endLoc",Coordinate.newInstance(4, 5))).setType(type2).build(); builder.addVehicle(v1); builder.addVehicle(v2); Service s1 = Service.Builder.newInstance("1").addSizeDimension(0, 1).setLocation(TestUtils.loc("loc")).setServiceTime(2.0).build(); Service s2 = Service.Builder.newInstance("2").addSizeDimension(0, 1).setLocation(TestUtils.loc("loc2")).setServiceTime(4.0).build(); VehicleRoutingProblem vrp = builder.addJob(s1).addJob(s2).build(); new VrpXMLWriter(vrp, null).write(infileName); VehicleRoutingProblem.Builder vrpToReadBuilder = VehicleRoutingProblem.Builder.newInstance(); new VrpXMLReader(vrpToReadBuilder, null).read(infileName); VehicleRoutingProblem readVrp = vrpToReadBuilder.build(); Vehicle v = getVehicle("v2",readVrp.getVehicles()); assertEquals(1.0,v.getStartLocation().getCoordinate().getX(),0.01); assertEquals(2.0,v.getStartLocation().getCoordinate().getY(),0.01); assertEquals(4.0,v.getEndLocation().getCoordinate().getX(),0.01); assertEquals(5.0,v.getEndLocation().getCoordinate().getY(),0.01); }
#vulnerable code @Test public void whenWritingVehicleV2_readingItsLocationsCoordsAgainReturnsCorrectLocationsCoords(){ Builder builder = VehicleRoutingProblem.Builder.newInstance(); VehicleTypeImpl type1 = VehicleTypeImpl.Builder.newInstance("vehType").addCapacityDimension(0, 20).build(); VehicleTypeImpl type2 = VehicleTypeImpl.Builder.newInstance("vehType2").addCapacityDimension(0, 200).build(); VehicleImpl v1 = VehicleImpl.Builder.newInstance("v1").setReturnToDepot(false).setStartLocationId("loc").setType(type1).build(); VehicleImpl v2 = VehicleImpl.Builder.newInstance("v2").setStartLocationId("startLoc").setStartLocationCoordinate(Coordinate.newInstance(1, 2)) .setEndLocationId("endLoc").setEndLocationCoordinate(Coordinate.newInstance(4, 5)).setType(type2).build(); builder.addVehicle(v1); builder.addVehicle(v2); Service s1 = Service.Builder.newInstance("1").addSizeDimension(0, 1).setLocationId("loc").setServiceTime(2.0).build(); Service s2 = Service.Builder.newInstance("2").addSizeDimension(0, 1).setLocationId("loc2").setServiceTime(4.0).build(); VehicleRoutingProblem vrp = builder.addJob(s1).addJob(s2).build(); new VrpXMLWriter(vrp, null).write(infileName); VehicleRoutingProblem.Builder vrpToReadBuilder = VehicleRoutingProblem.Builder.newInstance(); new VrpXMLReader(vrpToReadBuilder, null).read(infileName); VehicleRoutingProblem readVrp = vrpToReadBuilder.build(); Vehicle v = getVehicle("v2",readVrp.getVehicles()); assertEquals(1.0,v.getStartLocationCoordinate().getX(),0.01); assertEquals(2.0,v.getStartLocationCoordinate().getY(),0.01); assertEquals(4.0,v.getEndLocationCoordinate().getX(),0.01); assertEquals(5.0,v.getEndLocationCoordinate().getY(),0.01); } #location 25 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Test @Category(IntegrationTest.class) public void test() { try { Collection<VehicleRoutingProblemSolution> solutions = vra.searchSolutions(); Assert.assertTrue(true); } catch (Exception e) { Assert.assertTrue(false); } }
#vulnerable code @Test @Category(IntegrationTest.class) public void test() { try { Collection<VehicleRoutingProblemSolution> solutions = vra.searchSolutions(); System.out.println(Solutions.bestOf(solutions).getCost()); Assert.assertTrue(true); } catch (Exception e) { Assert.assertTrue(false); } } #location 6 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Override public InsertionData calculate(final VehicleRoute currentRoute, final Job jobToInsert, final Vehicle newVehicle, double newVehicleDepartureTime, final Driver newDriver, final double bestKnownCosts) { if(jobToInsert == null) throw new IllegalStateException("jobToInsert is missing."); if(newVehicle == null || newVehicle instanceof NoVehicle) throw new IllegalStateException("newVehicle is missing."); if(!(jobToInsert instanceof Shipment)) throw new IllegalStateException("jobToInsert should be of type Shipment!"); InsertionContext insertionContext = new InsertionContext(currentRoute, jobToInsert, newVehicle, newDriver, newVehicleDepartureTime); if(!hardRouteLevelConstraint.fulfilled(insertionContext)){ return InsertionData.noInsertionFound(); } double bestCost = bestKnownCosts; Shipment shipment = (Shipment)jobToInsert; TourActivity pickupShipment = activityFactory.createPickup(shipment); TourActivity deliveryShipment = activityFactory.createDelivery(shipment); int pickupInsertionIndex = InsertionData.NO_INDEX; int deliveryInsertionIndex = InsertionData.NO_INDEX; // int insertionIndex = 0; Start start = Start.newInstance(newVehicle.getLocationId(), newVehicle.getEarliestDeparture(), newVehicle.getLatestArrival()); start.setEndTime(newVehicleDepartureTime); End end = End.newInstance(newVehicle.getLocationId(), 0.0, newVehicle.getLatestArrival()); TourActivity prevAct = start; double prevActEndTime = newVehicleDepartureTime; //pickupShipmentLoop List<TourActivity> activities = currentRoute.getTourActivities().getActivities(); for(int i=0;i<activities.size();i++){ ActivityInsertionCosts pickupAIC = calculate(insertionContext,prevAct,pickupShipment,activities.get(i),prevActEndTime); if(pickupAIC == null){ double nextActArrTime = prevActEndTime + transportCosts.getTransportTime(prevAct.getLocationId(), activities.get(i).getLocationId(), prevActEndTime, newDriver, newVehicle); prevActEndTime = CalcUtils.getActivityEndTime(nextActArrTime, activities.get(i)); continue; } TourActivity prevAct_deliveryLoop = pickupShipment; double shipmentPickupArrTime = prevActEndTime + transportCosts.getTransportTime(prevAct.getLocationId(), pickupShipment.getLocationId(), prevActEndTime, newDriver, newVehicle); double shipmentPickupEndTime = CalcUtils.getActivityEndTime(shipmentPickupArrTime, pickupShipment); double prevActEndTime_deliveryLoop = shipmentPickupEndTime; //deliverShipmentLoop for(int j=i;j<activities.size();j++){ ActivityInsertionCosts deliveryAIC = calculate(insertionContext,prevAct_deliveryLoop,deliveryShipment,activities.get(j),prevActEndTime_deliveryLoop); if(deliveryAIC != null){ double totalActivityInsertionCosts = pickupAIC.getAdditionalCosts() + deliveryAIC.getAdditionalCosts(); if(totalActivityInsertionCosts < bestCost){ bestCost = totalActivityInsertionCosts; pickupInsertionIndex = i; deliveryInsertionIndex = j; } } //update prevAct and endTime double nextActArrTime = prevActEndTime_deliveryLoop + transportCosts.getTransportTime(prevAct_deliveryLoop.getLocationId(), activities.get(j).getLocationId(), prevActEndTime_deliveryLoop, newDriver, newVehicle); prevActEndTime_deliveryLoop = CalcUtils.getActivityEndTime(nextActArrTime, activities.get(j)); prevAct_deliveryLoop = activities.get(j); } //endInsertion ActivityInsertionCosts deliveryAIC = calculate(insertionContext,prevAct_deliveryLoop,deliveryShipment,end,prevActEndTime_deliveryLoop); if(deliveryAIC != null){ double totalActivityInsertionCosts = pickupAIC.getAdditionalCosts() + deliveryAIC.getAdditionalCosts(); if(totalActivityInsertionCosts < bestCost){ bestCost = totalActivityInsertionCosts; pickupInsertionIndex = i; deliveryInsertionIndex = activities.size() - 1; } } //update prevAct and endTime double nextActArrTime = prevActEndTime + transportCosts.getTransportTime(prevAct.getLocationId(), activities.get(i).getLocationId(), prevActEndTime, newDriver, newVehicle); prevActEndTime = CalcUtils.getActivityEndTime(nextActArrTime, activities.get(i)); prevAct = activities.get(i); } //endInsertion ActivityInsertionCosts pickupAIC = calculate(insertionContext,prevAct,pickupShipment,end,prevActEndTime); if(pickupAIC != null){ //evaluate delivery TourActivity prevAct_deliveryLoop = pickupShipment; double shipmentPickupArrTime = prevActEndTime + transportCosts.getTransportTime(prevAct.getLocationId(), pickupShipment.getLocationId(), prevActEndTime, newDriver, newVehicle); double shipmentPickupEndTime = CalcUtils.getActivityEndTime(shipmentPickupArrTime, pickupShipment); double prevActEndTime_deliveryLoop = shipmentPickupEndTime; ActivityInsertionCosts deliveryAIC = calculate(insertionContext,prevAct_deliveryLoop,deliveryShipment,end,prevActEndTime_deliveryLoop); if(deliveryAIC != null){ double totalActivityInsertionCosts = pickupAIC.getAdditionalCosts() + deliveryAIC.getAdditionalCosts(); if(totalActivityInsertionCosts < bestCost){ bestCost = totalActivityInsertionCosts; pickupInsertionIndex = activities.size() - 1; deliveryInsertionIndex = activities.size() - 1; } } } // for(TourActivity nextAct : activities){ // if(neighborhood.areNeighbors(deliveryAct2Insert.getLocationId(), prevAct.getLocationId()) && neighborhood.areNeighbors(deliveryAct2Insert.getLocationId(), nextAct.getLocationId())){ // ActivityInsertionCosts mc = calculate(insertionContext, prevAct, nextAct, deliveryAct2Insert, prevActEndTime); // if(mc != null){ // if(mc.getAdditionalCosts() < bestCost){ // bestCost = mc.getAdditionalCosts(); // bestMarginals = mc; // insertionIndex = actIndex; // } // } // } // double nextActArrTime = prevActEndTime + transportCosts.getTransportTime(prevAct.getLocationId(), nextAct.getLocationId(), prevActEndTime, newDriver, newVehicle); // double nextActEndTime = CalcUtils.getActivityEndTime(nextActArrTime, nextAct); // // prevActEndTime = nextActEndTime; // // prevAct = nextAct; // actIndex++; // } // End nextAct = end; // if(neighborhood.areNeighbors(deliveryAct2Insert.getLocationId(), prevAct.getLocationId()) && neighborhood.areNeighbors(deliveryAct2Insert.getLocationId(), nextAct.getLocationId())){ // ActivityInsertionCosts mc = calculate(insertionContext, prevAct, nextAct, deliveryAct2Insert, prevActEndTime); // if(mc != null) { // if(mc.getAdditionalCosts() < bestCost){ // bestCost = mc.getAdditionalCosts(); // bestMarginals = mc; // insertionIndex = actIndex; // } // } // } if(pickupInsertionIndex == InsertionData.NO_INDEX) { return InsertionData.noInsertionFound(); } InsertionData insertionData = new InsertionData(bestCost, pickupInsertionIndex, deliveryInsertionIndex, newVehicle, newDriver); insertionData.setVehicleDepartureTime(newVehicleDepartureTime); return insertionData; }
#vulnerable code @Override public InsertionData calculate(final VehicleRoute currentRoute, final Job jobToInsert, final Vehicle newVehicle, double newVehicleDepartureTime, final Driver newDriver, final double bestKnownCosts) { if(jobToInsert == null) throw new IllegalStateException("jobToInsert is missing."); if(newVehicle == null || newVehicle instanceof NoVehicle) throw new IllegalStateException("newVehicle is missing."); if(!(jobToInsert instanceof Shipment)) throw new IllegalStateException("jobToInsert should be of type Shipment!"); InsertionContext insertionContext = new InsertionContext(currentRoute, jobToInsert, newVehicle, newDriver, newVehicleDepartureTime); if(!hardRouteLevelConstraint.fulfilled(insertionContext)){ return InsertionData.noInsertionFound(); } double bestCost = bestKnownCosts; ActivityInsertionCosts bestMarginals = null; Shipment shipment = (Shipment)jobToInsert; TourActivity pickupShipment = activityFactory.createPickup(shipment); TourActivity deliveryShipment = activityFactory.createDelivery(shipment); int pickupInsertionIndex = InsertionData.NO_INDEX; int deliveryInsertionIndex = InsertionData.NO_INDEX; int insertionIndex = 0; Start start = Start.newInstance(newVehicle.getLocationId(), newVehicle.getEarliestDeparture(), newVehicle.getLatestArrival()); start.setEndTime(newVehicleDepartureTime); End end = End.newInstance(newVehicle.getLocationId(), 0.0, newVehicle.getLatestArrival()); // TourActivity prevAct = start; // double prevActStartTime = newVehicleDepartureTime; // int actIndex = 0; //// currentRoute.getTourActivities().getActivities(). // for(int i=0) // for(TourActivity nextAct : currentRoute.getTourActivities().getActivities()){ // if(neighborhood.areNeighbors(deliveryAct2Insert.getLocationId(), prevAct.getLocationId()) && neighborhood.areNeighbors(deliveryAct2Insert.getLocationId(), nextAct.getLocationId())){ // ActivityInsertionCosts mc = calculate(insertionContext, prevAct, nextAct, deliveryAct2Insert, prevActStartTime); // if(mc != null){ // if(mc.getAdditionalCosts() < bestCost){ // bestCost = mc.getAdditionalCosts(); // bestMarginals = mc; // insertionIndex = actIndex; // } // } // } // double nextActArrTime = prevActStartTime + transportCosts.getTransportTime(prevAct.getLocationId(), nextAct.getLocationId(), prevActStartTime, newDriver, newVehicle); // double nextActEndTime = CalcUtils.getActivityEndTime(nextActArrTime, nextAct); // // prevActStartTime = nextActEndTime; // // prevAct = nextAct; // actIndex++; // } // End nextAct = end; // if(neighborhood.areNeighbors(deliveryAct2Insert.getLocationId(), prevAct.getLocationId()) && neighborhood.areNeighbors(deliveryAct2Insert.getLocationId(), nextAct.getLocationId())){ // ActivityInsertionCosts mc = calculate(insertionContext, prevAct, nextAct, deliveryAct2Insert, prevActStartTime); // if(mc != null) { // if(mc.getAdditionalCosts() < bestCost){ // bestCost = mc.getAdditionalCosts(); // bestMarginals = mc; // insertionIndex = actIndex; // } // } // } // // if(insertionIndex == InsertionData.NO_INDEX) { // return InsertionData.noInsertionFound(); // } InsertionData insertionData = new InsertionData(bestCost, InsertionData.NO_INDEX, insertionIndex, newVehicle, newDriver); insertionData.setVehicleDepartureTime(newVehicleDepartureTime); insertionData.setAdditionalTime(bestMarginals.getAdditionalTime()); return insertionData; } #location 66 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code public void read(String matrixFile){ BufferedReader reader = getBufferedReader(matrixFile); String line; boolean isEdgeWeights = false; int fromIndex = 0; while( ( line = getLine(reader) ) != null ){ if(line.startsWith("EDGE_WEIGHT_SECTION")){ isEdgeWeights = true; continue; } if(line.startsWith("DEMAND_SECTION")){ isEdgeWeights = false; continue; } if(isEdgeWeights){ String[] tokens = line.split("\\s+"); String fromId = "" + (fromIndex + 1); for(int i=0;i<tokens.length;i++){ double distance = Double.parseDouble(tokens[i]); String toId = "" + (i+1); costMatrixBuilder.addTransportDistance(fromId,toId,distance); costMatrixBuilder.addTransportTime(fromId, toId, distance); } fromIndex++; } } close(reader); }
#vulnerable code public void read(String matrixFile){ BufferedReader reader = getBufferedReader(matrixFile); String line; boolean isEdgeWeights = false; int fromIndex = 0; while( ( line = getLine(reader) ) != null ){ if(line.startsWith("EDGE_WEIGHT_SECTION")){ isEdgeWeights = true; continue; } if(line.startsWith("DEMAND_SECTION")){ isEdgeWeights = false; continue; } if(isEdgeWeights){ String[] tokens = line.split("\\s+"); String fromId = "" + (fromIndex + 1); for(int i=0;i<tokens.length;i++){ double distance = Double.parseDouble(tokens[i]); String toId = "" + (i+1); costMatrixBuilder.addTransportDistance(fromId,toId,distance); costMatrixBuilder.addTransportTime(fromId, toId, distance); } fromIndex++; } } } #location 10 #vulnerability type RESOURCE_LEAK
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Test public void whenVehicleRouteIsEmpty_loadsAtBeginningAndEndShouldBeZero(){ StateManager stateManager = new StateManager(mock(VehicleRoutingTransportCosts.class)); UpdateLoads updateLoads = new UpdateLoads(stateManager); VehicleRoute route = VehicleRoute.emptyRoute(); updateLoads.informInsertionStarts(Arrays.asList(route), Collections.<Job>emptyList()); Capacity loadAtBeginning = stateManager.getRouteState(route, StateFactory.LOAD_AT_BEGINNING, Capacity.class); assertEquals(0.,loadAtBeginning.get(0),0.1); assertEquals(0.,stateManager.getRouteState(route, StateFactory.LOAD_AT_END, Capacity.class).get(0),0.1); }
#vulnerable code @Test public void whenVehicleRouteIsEmpty_loadsAtBeginningAndEndShouldBeZero(){ StateManager stateManager = new StateManager(mock(VehicleRoutingProblem.class)); UpdateLoads updateLoads = new UpdateLoads(stateManager); VehicleRoute route = VehicleRoute.emptyRoute(); updateLoads.informInsertionStarts(Arrays.asList(route), Collections.<Job>emptyList()); assertEquals(0.,stateManager.getRouteState(route, StateFactory.LOAD_AT_BEGINNING).toDouble(),0.1); assertEquals(0.,stateManager.getRouteState(route, StateFactory.LOAD_AT_END).toDouble(),0.1); } #location 9 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Test public void testStatesOfAct1(){ states.informInsertionStarts(Arrays.asList(vehicleRoute), null); assertEquals(10.0, states.getActivityState(act1, StateFactory.COSTS).toDouble(),0.05); assertEquals(5.0, states.getActivityState(act1, StateFactory.LOAD).toDouble(),0.05); assertEquals(20.0, states.getActivityState(act1, StateFactory.LATEST_OPERATION_START_TIME).toDouble(),0.05); }
#vulnerable code @Test public void testStatesOfAct1(){ states.informInsertionStarts(Arrays.asList(vehicleRoute), null); assertEquals(10.0, states.getActivityState(tour.getActivities().get(0), StateFactory.COSTS).toDouble(),0.05); assertEquals(5.0, states.getActivityState(tour.getActivities().get(0), StateFactory.LOAD).toDouble(),0.05); // assertEquals(10.0, states.getActivityState(tour.getActivities().get(0), StateTypes.EARLIEST_OPERATION_START_TIME).toDouble(),0.05); assertEquals(20.0, states.getActivityState(tour.getActivities().get(0), StateFactory.LATEST_OPERATION_START_TIME).toDouble(),0.05); } #location 5 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.
#fixed code @Override public double getActivityStartTime(TourActivity activity, double arrivalTime) { return Math.max(arrivalTime,activity.getTheoreticalEarliestOperationStartTime()); // TimeWindow last = null; // for(int i=activity.getTimeWindows().size()-1; i >= 0; i--){ // TimeWindow tw = activity.getTimeWindows().get(i); // if(tw.getStart() <= arrivalTime && tw.getEnd() >= arrivalTime){ // return arrivalTime; // } // else if(arrivalTime > tw.getEnd()){ // if(last != null) return last.getStart(); // else return arrivalTime; // } // last = tw; // } // return Math.max(arrivalTime,last.getStart()); }
#vulnerable code @Override public double getActivityStartTime(TourActivity activity, double arrivalTime) { TimeWindow last = null; for(int i=activity.getTimeWindows().size()-1; i >= 0; i--){ TimeWindow tw = activity.getTimeWindows().get(i); if(tw.getStart() <= arrivalTime && tw.getEnd() >= arrivalTime){ return arrivalTime; } else if(arrivalTime > tw.getEnd()){ if(last != null) return last.getStart(); else return arrivalTime; } last = tw; } return Math.max(arrivalTime,last.getStart()); } #location 15 #vulnerability type NULL_DEREFERENCE
Below is the vulnerable code, please generate the patch based on the following information.