Example usage for java.nio.file.attribute PosixFilePermissions asFileAttribute

List of usage examples for java.nio.file.attribute PosixFilePermissions asFileAttribute

Introduction

In this page you can find the example usage for java.nio.file.attribute PosixFilePermissions asFileAttribute.

Prototype

public static FileAttribute<Set<PosixFilePermission>> asFileAttribute(Set<PosixFilePermission> perms) 

Source Link

Document

Creates a FileAttribute , encapsulating a copy of the given file permissions, suitable for passing to the java.nio.file.Files#createFile createFile or java.nio.file.Files#createDirectory createDirectory methods.

Usage

From source file:com.dowdandassociates.gentoo.bootstrap.DefaultKeyPairInformation.java

@PostConstruct
private void setup() {
    boolean nameSet = (null != name);
    boolean filenameSet = (null != filename);
    boolean keyExists = false;
    if (nameSet) {
        log.info("Checking if key pair \"" + name + "\" exists");
        keyExists = !(ec2Client/*from  w ww. ja  va 2  s.  co m*/
                .describeKeyPairs(new DescribeKeyPairsRequest()
                        .withFilters(new Filter().withName("key-name").withValues(name)))
                .getKeyPairs().isEmpty());
    }

    if (keyExists && !filenameSet) {
        log.warn("Key pair \"" + name + "\" exists, but private key location is not specified");
        keyExists = false;
    }

    if (!keyExists) {
        if (!nameSet) {
            name = "gentoo-bootstrap-"
                    + DateFormatUtils.formatUTC(System.currentTimeMillis(), "yyyyMMdd'T'HHmmssSSS'Z'");
        }

        if (!filenameSet) {
            try {
                filename = Files
                        .createTempFile(name, ".pem",
                                PosixFilePermissions
                                        .asFileAttribute(PosixFilePermissions.fromString("rw-------")))
                        .toString();
            } catch (IOException ioe) {
                log.warn("Cannot create temp file", ioe);
                filename = name + ".pem";
            }
        }

        log.info("Creating key pair \"" + name + "\"");

        CreateKeyPairResult createResult = ec2Client
                .createKeyPair(new CreateKeyPairRequest().withKeyName(name));

        try {
            log.info("Saving pem file to \"" + filename + "\"");

            BufferedWriter outfile = new BufferedWriter(new FileWriter(filename));

            try {
                outfile.write(createResult.getKeyPair().getKeyMaterial());
            } catch (IOException ioe) {
                String message = "Error writing to file \"" + filename + "\"";
                log.error(message, ioe);
                throw new RuntimeException(message, ioe);
            } finally {
                outfile.close();
            }
        } catch (IOException ioe) {
            String message = "Error opening file \"" + filename + "\"";
            log.error(message, ioe);
            throw new RuntimeException(message, ioe);
        }

        builtKeyPair = true;

        log.info("Key pair \"" + name + "\" built");
    } else {
        builtKeyPair = false;
        log.info("Key pair \"" + name + "\" exists");
    }

    if (filename.startsWith("~" + File.separator)) {
        filename = System.getProperty("user.home") + filename.substring(1);
    }
}

From source file:com.kamike.misc.FsUtils.java

public static void createDirectory(String dstPath) {

    Properties props = System.getProperties(); //    
    String osName = props.getProperty("os.name"); //???   
    Path newdir = FileSystems.getDefault().getPath(dstPath);

    boolean pathExists = Files.exists(newdir, new LinkOption[] { LinkOption.NOFOLLOW_LINKS });
    if (!pathExists) {
        Set<PosixFilePermission> perms = PosixFilePermissions.fromString("rwxrwxrwx");
        FileAttribute<Set<PosixFilePermission>> attr = PosixFilePermissions.asFileAttribute(perms);
        try {/*from  w  ww . ja  va  2 s  .  c om*/
            if (!osName.contains("Windows")) {
                Files.createDirectories(newdir, attr);
            } else {
                Files.createDirectories(newdir);
            }
        } catch (Exception e) {
            System.err.println(e);

        }
    }
}

From source file:org.roda.core.plugins.ReplicationPluginTest.java

@BeforeClass
public void setUp() throws Exception {
    basePath = TestsHelper.createBaseTempDir(getClass(), true,
            PosixFilePermissions.asFileAttribute(new HashSet<>(Arrays.asList(PosixFilePermission.OWNER_READ,
                    PosixFilePermission.OWNER_WRITE, PosixFilePermission.OWNER_EXECUTE,
                    PosixFilePermission.OTHERS_READ, PosixFilePermission.OTHERS_EXECUTE))));

    boolean deploySolr = true;
    boolean deployLdap = true;
    boolean deployFolderMonitor = true;
    boolean deployOrchestrator = true;
    boolean deployPluginManager = true;
    boolean deployDefaultResources = false;

    // embedded Apache Solr
    RodaCoreFactory.instantiateTest(deploySolr, deployLdap, deployFolderMonitor, deployOrchestrator,
            deployPluginManager, deployDefaultResources, SolrType.EMBEDDED);

    // // HTTP Apache Solr
    // RodaCoreFactory.instantiateTest(deploySolr, deployLdap,
    // deployFolderMonitor, deployOrchestrator,
    // deployPluginManager, deployDefaultResources, SolrType.HTTP);

    // // Cloud Apache Solr
    // RodaCoreFactory.instantiateTest(deploySolr, deployLdap,
    // deployFolderMonitor, deployOrchestrator,
    // deployPluginManager, deployDefaultResources, SolrType.HTTP_CLOUD);

    model = RodaCoreFactory.getModelService();
    index = RodaCoreFactory.getIndexService();
    storage = RodaCoreFactory.getStorageService();

    testPath = TestsHelper.createBaseTempDir(getClass(), true,
            PosixFilePermissions.asFileAttribute(new HashSet<>(Arrays.asList(PosixFilePermission.OWNER_READ,
                    PosixFilePermission.OWNER_WRITE, PosixFilePermission.OWNER_EXECUTE,
                    PosixFilePermission.OTHERS_READ, PosixFilePermission.OTHERS_EXECUTE))));

    Files.createDirectories(//  w ww .  j  a va2 s  .  com
            testPath.resolve(RodaConstants.CORE_STORAGE_FOLDER).resolve(RodaConstants.STORAGE_CONTAINER_AIP));
    Files.createDirectories(testPath.resolve(RodaConstants.CORE_STORAGE_FOLDER)
            .resolve(RodaConstants.STORAGE_CONTAINER_PRESERVATION)
            .resolve(RodaConstants.STORAGE_CONTAINER_PRESERVATION_AGENTS));

    LOGGER.info("Running {} tests under storage {}", getClass().getSimpleName(), basePath);
}

From source file:com.cloudera.livy.rsc.driver.RSCDriver.java

public RSCDriver(SparkConf conf, RSCConf livyConf) throws Exception {
    Set<PosixFilePermission> perms = PosixFilePermissions.fromString("rwx------");
    this.localTmpDir = Files.createTempDirectory("rsc-tmp", PosixFilePermissions.asFileAttribute(perms))
            .toFile();/*  w w  w .  j  ava 2s. c o  m*/
    this.executor = Executors.newCachedThreadPool();
    this.jobQueue = new LinkedList<>();
    this.clients = new ConcurrentLinkedDeque<>();
    this.serializer = new Serializer();

    this.conf = conf;
    this.livyConf = livyConf;
    this.jcLock = new Object();
    this.shutdownLock = new Object();

    this.activeJobs = new ConcurrentHashMap<>();
    this.bypassJobs = new ConcurrentLinkedDeque<>();
    this.idleTimeout = new AtomicReference<>();
}

From source file:org.roda.core.plugins.InternalPluginsTest.java

@BeforeClass
public void setUp() throws Exception {
    basePath = TestsHelper.createBaseTempDir(getClass(), true,
            PosixFilePermissions.asFileAttribute(new HashSet<>(Arrays.asList(PosixFilePermission.OWNER_READ,
                    PosixFilePermission.OWNER_WRITE, PosixFilePermission.OWNER_EXECUTE,
                    PosixFilePermission.OTHERS_READ, PosixFilePermission.OTHERS_EXECUTE))));

    boolean deploySolr = true;
    boolean deployLdap = true;
    boolean deployFolderMonitor = true;
    boolean deployOrchestrator = true;
    boolean deployPluginManager = true;
    boolean deployDefaultResources = false;
    RodaCoreFactory.instantiateTest(deploySolr, deployLdap, deployFolderMonitor, deployOrchestrator,
            deployPluginManager, deployDefaultResources);
    model = RodaCoreFactory.getModelService();
    index = RodaCoreFactory.getIndexService();

    LOGGER.info("Running internal plugins tests under storage {}", basePath);
}

From source file:org.mitre.mpf.wfm.util.PropertiesUtil.java

@PostConstruct
private void init() throws IOException, WfmProcessingException {

    parseCoreMpfNodes();//w w w .  ja v  a2  s.  com

    mpfPropertiesConfig = mpfPropertiesConfigBuilder.getCompleteConfiguration();

    if (!mediaTypesFile.exists()) {
        copyResource(mediaTypesFile, getMediaTypesTemplate());
    }

    Set<PosixFilePermission> permissions = new HashSet<>();
    permissions.add(PosixFilePermission.OWNER_READ);
    permissions.add(PosixFilePermission.OWNER_WRITE);
    permissions.add(PosixFilePermission.OWNER_EXECUTE);

    Path share = Paths.get(getSharePath()).toAbsolutePath();
    if (!Files.exists(share)) {
        share = Files.createDirectories(share, PosixFilePermissions.asFileAttribute(permissions));
    }

    if (!Files.exists(share) || !Files.isDirectory(share)) {
        throw new WfmProcessingException(
                String.format("Failed to create the path '%s'. It does not exist or it is not a directory.",
                        share.toString()));
    }

    artifactsDirectory = createOrFail(share, "artifacts", permissions);
    markupDirectory = createOrFail(share, "markup", permissions);
    outputObjectsDirectory = createOrFail(share, "output-objects", permissions);
    remoteMediaCacheDirectory = createOrFail(share, "remote-media", permissions);
    uploadedComponentsDirectory = createOrFail(share, getComponentUploadDirName(), permissions);
    createOrFail(getPluginDeploymentPath().toPath(), "",
            EnumSet.of(PosixFilePermission.OWNER_READ, PosixFilePermission.OWNER_WRITE,
                    PosixFilePermission.OWNER_EXECUTE, PosixFilePermission.GROUP_READ,
                    PosixFilePermission.GROUP_EXECUTE, PosixFilePermission.OTHERS_READ,
                    PosixFilePermission.OTHERS_EXECUTE));

    // create the default models directory, although the user may have set "detection.models.dir.path" to something else
    createOrFail(share, "models", permissions);

    log.info("All file resources are stored within the shared directory '{}'.", share);
    log.debug("Artifacts Directory = {}", artifactsDirectory);
    log.debug("Markup Directory = {}", markupDirectory);
    log.debug("Output Objects Directory = {}", outputObjectsDirectory);
    log.debug("Remote Media Cache Directory = {}", remoteMediaCacheDirectory);
    log.debug("Uploaded Components Directory = {}", uploadedComponentsDirectory);
}

From source file:de.unirostock.sems.cbarchive.web.VcImporter.java

private static File cloneHg(String link, ArchiveFromHg archive) throws IOException, TransformerException,
        JDOMException, ParseException, CombineArchiveException, CombineArchiveWebException {
    // create new temp dir
    File tempDir = Files// ww w  .j  av  a2s .c  om
            .createTempDirectory(Fields.TEMP_FILE_PREFIX,
                    PosixFilePermissions.asFileAttribute(PosixFilePermissions.fromString("rwx------")))
            .toFile();
    if (!tempDir.isDirectory() && !tempDir.mkdirs())
        throw new CombineArchiveWebException(
                "The temporary directories could not be created: " + tempDir.getAbsolutePath());

    // temp file for CombineArchive
    File archiveFile = File.createTempFile(Fields.TEMP_FILE_PREFIX, "ca-imported");
    archiveFile.delete(); // delete the tmp file, so the CombineArchive Lib will create a new file
    // create the archive
    CombineArchive ca = new CombineArchive(archiveFile);

    Repository repo = Repository.clone(tempDir, link);
    if (repo == null) {
        ca.close();
        LOGGER.error("Cannot clone Mercurial Repository ", link, " into ", tempDir);
        throw new CombineArchiveWebException("Cannot clone Mercurial Repository " + link + " into " + tempDir);
    }

    List<File> relevantFiles = scanRepository(tempDir, repo);
    System.out.println("before LogCommand");
    LogCommand logCmd = new LogCommand(repo);
    System.out.println("after LogCommand");
    for (File cur : relevantFiles) {
        List<Changeset> relevantVersions = logCmd.execute(cur.getAbsolutePath());

        ArchiveEntry caFile = ca.addEntry(tempDir, cur, Formatizer.guessFormat(cur));

        // lets create meta!
        List<Date> modified = new ArrayList<Date>();
        List<VCard> creators = new ArrayList<VCard>();

        HashMap<String, VCard> users = new HashMap<String, VCard>();
        for (Changeset cs : relevantVersions) {
            LOGGER.debug("cs: " + cs.getTimestamp().getDate() + " -- " + cs.getUser());
            modified.add(cs.getTimestamp().getDate());

            String vcuser = cs.getUser();
            String firstName = "";
            String lastName = "";
            String mail = "";

            String[] tokens = vcuser.split(" ");
            int lastNameToken = tokens.length - 1;
            // is there a mail address?
            if (tokens[lastNameToken].contains("@")) {
                mail = tokens[lastNameToken];
                if (mail.startsWith("<") && mail.endsWith(">"))
                    mail = mail.substring(1, mail.length() - 1);
                lastNameToken--;
            }

            // search for a non-empty last name
            while (lastNameToken >= 0) {
                if (tokens[lastNameToken].length() > 0) {
                    lastName = tokens[lastNameToken];
                    break;
                }
                lastNameToken--;
            }

            // and first name of course...
            for (int i = 0; i < lastNameToken; i++) {
                if (tokens[i].length() > 0)
                    firstName += tokens[i] + " ";
            }
            firstName = firstName.trim();

            String userid = "[" + firstName + "] -- [" + lastName + "] -- [" + mail + "]";
            LOGGER.debug("this is user: " + userid);
            if (users.get(userid) == null) {
                users.put(userid, new VCard(lastName, firstName, mail, null));
            }
        }

        for (VCard vc : users.values())
            creators.add(vc);

        caFile.addDescription(new OmexMetaDataObject(
                new OmexDescription(creators, modified, modified.get(modified.size() - 1))));

    }

    ca.pack();
    ca.close();
    repo.close();

    // clean up the directory
    FileUtils.deleteDirectory(tempDir);

    // add the combine archive to the dataholder
    if (archive != null) {
        //TODO ugly workaround with the lock. 
        archive.setArchiveFile(archiveFile, null);
        archive.getArchive().close();
    }

    return archiveFile;
}

From source file:de.huberlin.wbi.cuneiform.core.cre.LocalThread.java

@Override
public void run() {

    Path scriptFile, location, successMarker, reportFile, callLocation, stdErrFile, stdOutFile;
    // Path lockMarker;
    Process process;// ww  w.  j av a 2s. c  o m
    int exitValue;
    Set<JsonReportEntry> report;
    JsonReportEntry entry;
    String line;
    StringBuffer buf;
    Path srcPath, destPath;
    ProcessBuilder processBuilder;
    Ticket ticket;
    String script, stdOut, stdErr;
    long tic, toc;
    JSONObject obj;
    Message msg;
    Charset cs;
    int trial;
    boolean suc;
    Exception ex;

    if (log.isDebugEnabled())
        log.debug("Starting up local thread for ticket " + invoc.getTicketId() + ".");

    if (invoc == null)
        throw new NullPointerException("Invocation must not be null.");

    ticket = invoc.getTicket();
    process = null;
    stdOut = null;
    stdErr = null;
    // lockMarker = null;
    script = null;
    successMarker = null;
    cs = Charset.forName("UTF-8");

    try {

        callLocation = Paths.get(System.getProperty("user.dir"));
        location = buildDir.resolve(String.valueOf(invoc.getTicketId()));
        // lockMarker = location.resolve( Invocation.LOCK_FILENAME );
        successMarker = location.resolve(Invocation.SUCCESS_FILENAME);
        reportFile = location.resolve(Invocation.REPORT_FILENAME);
        script = invoc.toScript();

        // if( Files.exists( lockMarker ) )
        //   throw new IOException( "Lock held on ticket "+invoc.getTicketId() );

        if (!Files.exists(successMarker)) {

            deleteIfExists(location);
            Files.createDirectories(location);

            // Files.createFile( lockMarker );

            scriptFile = invoc.getExecutablePath(location);

            Files.createFile(scriptFile,
                    PosixFilePermissions.asFileAttribute(PosixFilePermissions.fromString("rwxr-x---")));

            // write executable script
            try (BufferedWriter writer = Files.newBufferedWriter(scriptFile, cs, StandardOpenOption.CREATE)) {
                writer.write(script);
            }

            // write executable log entry
            try (BufferedWriter writer = Files.newBufferedWriter(reportFile, cs, StandardOpenOption.CREATE)) {
                writer.write(ticket.getExecutableLogEntry().toString());
                writer.write('\n');
            }

            for (String filename : invoc.getStageInList()) {

                if (filename.charAt(0) == '/')
                    throw new UnsupportedOperationException("Absolute path encountered '" + filename + "'.");

                srcPath = centralRepo.resolve(filename);
                destPath = location.resolve(filename);

                if (!Files.exists(srcPath)) {

                    srcPath = callLocation.resolve(filename);
                    if (log.isTraceEnabled())
                        log.trace("Resolving relative path '" + srcPath + "'.");
                } else

                if (log.isTraceEnabled())
                    log.trace("Resolving path to central repository '" + srcPath + "'.");

                if (log.isTraceEnabled())
                    log.trace("Trying to create symbolic link from '" + srcPath + "' to '" + destPath + "'.");

                if (!Files.exists(destPath.getParent()))
                    Files.createDirectories(destPath.getParent());

                Files.createSymbolicLink(destPath, srcPath);

            }

            // run script
            processBuilder = new ProcessBuilder(invoc.getCmd());
            processBuilder.directory(location.toFile());

            stdOutFile = location.resolve(Invocation.STDOUT_FILENAME);
            stdErrFile = location.resolve(Invocation.STDERR_FILENAME);

            processBuilder.redirectOutput(stdOutFile.toFile());
            processBuilder.redirectError(stdErrFile.toFile());

            trial = 1;
            suc = false;
            ex = null;
            tic = System.currentTimeMillis();
            do {
                try {
                    process = processBuilder.start();

                    suc = true;
                } catch (IOException e) {

                    ex = e;
                    if (log.isWarnEnabled())
                        log.warn("Unable to start process on trial " + (trial++) + " Waiting " + WAIT_INTERVAL
                                + "ms: " + e.getMessage());
                    Thread.sleep(WAIT_INTERVAL);
                }
            } while (suc == false && trial <= MAX_TRIALS);

            if (process == null) {

                ticketSrc.sendMsg(new TicketFailedMsg(cre, ticket, ex, script, null, null));
                // Files.delete( lockMarker );
                return;
            }

            exitValue = process.waitFor();
            toc = System.currentTimeMillis();

            try (BufferedWriter writer = Files.newBufferedWriter(reportFile, cs, StandardOpenOption.APPEND)) {

                obj = new JSONObject();
                obj.put(JsonReportEntry.LABEL_REALTIME, toc - tic);
                entry = invoc.createJsonReportEntry(tic, JsonReportEntry.KEY_INVOC_TIME, obj);

                writer.write(entry.toString());
                writer.write('\n');

                try (BufferedReader reader = Files.newBufferedReader(stdOutFile, cs)) {

                    buf = new StringBuffer();
                    while ((line = reader.readLine()) != null)
                        buf.append(line).append('\n');

                    stdOut = buf.toString();

                    if (!stdOut.isEmpty()) {
                        entry = invoc.createJsonReportEntry(JsonReportEntry.KEY_INVOC_STDOUT, stdOut);
                        writer.write(entry.toString());
                        writer.write('\n');
                    }
                }

                try (BufferedReader reader = Files.newBufferedReader(stdErrFile, cs)) {

                    buf = new StringBuffer();
                    while ((line = reader.readLine()) != null)
                        buf.append(line).append('\n');

                    stdErr = buf.toString();
                    if (!stdErr.isEmpty()) {

                        entry = invoc.createJsonReportEntry(JsonReportEntry.KEY_INVOC_STDERR, stdErr);
                        writer.write(entry.toString());
                        writer.write('\n');
                    }
                }

                if (exitValue == 0)

                    Files.createFile(successMarker);

                else {

                    ticketSrc.sendMsg(new TicketFailedMsg(cre, ticket, null, script, stdOut, stdErr));
                    // Files.delete( lockMarker );
                    return;

                }
            }

        }

        // gather report
        report = new HashSet<>();
        try (BufferedReader reader = Files.newBufferedReader(reportFile, cs)) {

            while ((line = reader.readLine()) != null) {

                line = line.trim();

                if (line.isEmpty())
                    continue;

                entry = new JsonReportEntry(line);

                // If the report comes from the hard cache then the run id
                // is different from the run id of this invocation. This is
                // corrected here.
                entry.setRunId(invoc.getRunId());

                report.add(entry);
            }

        }

        invoc.evalReport(report);

        // create link in central data repository
        for (String f : invoc.getStageOutList()) {

            srcPath = location.resolve(f);
            destPath = centralRepo.resolve(f);

            if (Files.exists(destPath))
                continue;

            if (log.isTraceEnabled())
                log.trace("Creating link from " + srcPath + " to " + destPath + ".");

            Files.createSymbolicLink(destPath, srcPath);
        }

        ticketSrc.sendMsg(new TicketFinishedMsg(cre, invoc.getTicket(), report));

        if (log.isTraceEnabled())
            log.trace("Local thread ran through without exception.");

        // Files.deleteIfExists( lockMarker );

    } catch (InterruptedException e) {

        if (log.isTraceEnabled())
            log.trace("Local thread has been interrupted.");
    } catch (Exception e) {

        if (log.isTraceEnabled())
            log.trace("Something went wrong. Deleting success marker if present.");

        if (successMarker != null)
            try {
                Files.deleteIfExists(successMarker);
            } catch (IOException e1) {
                e1.printStackTrace();
            }

        msg = new TicketFailedMsg(cre, ticket, e, script, stdOut, stdErr);

        ticketSrc.sendMsg(msg);

    } finally {

        if (process != null) {

            if (log.isDebugEnabled())
                log.debug("Stopping local thread for ticket " + invoc.getTicketId() + ".");

            process.destroy();
        }
    }
}

From source file:org.mitre.mpf.wfm.util.PropertiesUtil.java

private static File createOrFail(Path parent, String subdirectory, Set<PosixFilePermission> permissions)
        throws IOException, WfmProcessingException {
    Path child = parent.resolve(subdirectory);
    if (!Files.exists(child)) {
        child = Files.createDirectories(child, PosixFilePermissions.asFileAttribute(permissions));
    }//from ww  w.  j a  va  2  s . co  m

    if (!Files.exists(child) || !Files.isDirectory(child)) {
        throw new WfmProcessingException(String
                .format("Failed to create the path '%s'. It does not exist or it is not a directory.", child));
    }

    return child.toAbsolutePath().toFile();
}

From source file:org.cirdles.squid.web.SquidReportingService.java

public Path generateReports(String myFileName, InputStream prawnFile, InputStream taskFile, boolean useSBM,
        boolean userLinFits, String refMatFilter, String concRefMatFilter, String preferredIndexIsotopeName)
        throws IOException, JAXBException, SAXException {

    IndexIsoptopesEnum preferredIndexIsotope = IndexIsoptopesEnum.valueOf(preferredIndexIsotopeName);

    // Posix attributes added to support web service on Linux - ignoring windows for now
    Set<PosixFilePermission> perms = EnumSet.of(OWNER_READ, OWNER_WRITE, OWNER_EXECUTE, GROUP_READ);

    // detect if prawnfile is zipped
    boolean prawnIsZip = false;
    String fileName = "";
    if (myFileName == null) {
        fileName = DEFAULT_PRAWNFILE_NAME;
    } else if (myFileName.toLowerCase().endsWith(".zip")) {
        fileName = FilenameUtils.removeExtension(myFileName);
        prawnIsZip = true;//from w w  w .  j  a  v  a 2 s.  co m
    } else {
        fileName = myFileName;
    }

    SquidProject squidProject = new SquidProject();
    prawnFileHandler = squidProject.getPrawnFileHandler();

    CalamariFileUtilities.initSampleParametersModels();

    Path reportsZip = null;
    Path reportsFolder = null;
    try {
        Path uploadDirectory = Files.createTempDirectory("upload");
        Path uploadDirectory2 = Files.createTempDirectory("upload2");

        Path prawnFilePath;
        Path taskFilePath;
        if (prawnIsZip) {
            Path prawnFilePathZip = uploadDirectory.resolve("prawn-file.zip");
            Files.copy(prawnFile, prawnFilePathZip);
            prawnFilePath = extractZippedFile(prawnFilePathZip.toFile(), uploadDirectory.toFile());
        } else {
            prawnFilePath = uploadDirectory.resolve("prawn-file.xml");
            Files.copy(prawnFile, prawnFilePath);
        }

        taskFilePath = uploadDirectory2.resolve("task-file.xls");
        Files.copy(taskFile, taskFilePath);

        ShrimpDataFileInterface prawnFileData = prawnFileHandler
                .unmarshallPrawnFileXML(prawnFilePath.toString(), true);
        squidProject.setPrawnFile(prawnFileData);

        // hard-wired for now
        squidProject.getTask().setCommonPbModel(CommonPbModel.getDefaultModel("GA Common Lead 2018", "1.0"));
        squidProject.getTask().setPhysicalConstantsModel(
                PhysicalConstantsModel.getDefaultModel(SQUID2_DEFAULT_PHYSICAL_CONSTANTS_MODEL_V1, "1.0"));
        File squidTaskFile = taskFilePath.toFile();

        squidProject.createTaskFromImportedSquid25Task(squidTaskFile);

        squidProject.setDelimiterForUnknownNames("-");

        TaskInterface task = squidProject.getTask();
        task.setFilterForRefMatSpotNames(refMatFilter);
        task.setFilterForConcRefMatSpotNames(concRefMatFilter);
        task.setUseSBM(useSBM);
        task.setUserLinFits(userLinFits);
        task.setSelectedIndexIsotope(preferredIndexIsotope);

        // process task           
        task.applyTaskIsotopeLabelsToMassStations();

        Path calamariReportsFolderAliasParent = Files.createTempDirectory("reports-destination");
        Path calamariReportsFolderAlias = calamariReportsFolderAliasParent
                .resolve(DEFAULT_SQUID3_REPORTS_FOLDER.getName() + "-from Web Service");
        File reportsDestinationFile = calamariReportsFolderAlias.toFile();

        reportsEngine = prawnFileHandler.getReportsEngine();
        prawnFileHandler.initReportsEngineWithCurrentPrawnFileName(fileName);
        reportsEngine.setFolderToWriteCalamariReports(reportsDestinationFile);

        reportsEngine.produceReports(task.getShrimpFractions(), (ShrimpFraction) task.getUnknownSpots().get(0),
                task.getReferenceMaterialSpots().size() > 0
                        ? (ShrimpFraction) task.getReferenceMaterialSpots().get(0)
                        : (ShrimpFraction) task.getUnknownSpots().get(0),
                true, false);

        squidProject.produceTaskAudit();

        squidProject.produceUnknownsCSV(true);
        squidProject.produceReferenceMaterialCSV(true);
        // next line report will show only super sample for now
        squidProject.produceUnknownsBySampleForETReduxCSV(true);

        Files.delete(prawnFilePath);

        reportsFolder = Paths.get(reportsEngine.getFolderToWriteCalamariReports().getParentFile().getPath());

    } catch (IOException | JAXBException | SAXException | SquidException iOException) {

        Path config = Files.createTempFile("SquidWebServiceMessage", "txt",
                PosixFilePermissions.asFileAttribute(perms));
        try (BufferedWriter writer = Files.newBufferedWriter(config, StandardCharsets.UTF_8)) {
            writer.write("Squid Reporting web service was not able to process supplied files.");
            writer.newLine();
            writer.write(iOException.getMessage());
            writer.newLine();
        }
        File message = config.toFile();

        Path messageDirectory = Files.createTempDirectory("message");
        Path messageFilePath = messageDirectory.resolve("Squid Web Service Message.txt");
        Files.copy(message.toPath(), messageFilePath);

        reportsFolder = messageFilePath.getParent();
    }

    reportsZip = ZipUtility.recursivelyZip(reportsFolder);
    FileUtilities.recursiveDelete(reportsFolder);

    return reportsZip;
}