#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
#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
    }