Example usage for java.nio.file Files createTempFile

List of usage examples for java.nio.file Files createTempFile

Introduction

In this page you can find the example usage for java.nio.file Files createTempFile.

Prototype

public static Path createTempFile(String prefix, String suffix, FileAttribute<?>... attrs) throws IOException 

Source Link

Document

Creates an empty file in the default temporary-file directory, using the given prefix and suffix to generate its name.

Usage

From source file:org.egov.infra.filestore.service.impl.LocalDiskFileStoreServiceTest.java

@Test
public final void testUploadStreams() throws IOException {
    Set<InputStream> files = new HashSet<>();
    for (int no = 0; no < 10; no++) {
        final File newFile = Files.createTempFile(tempFilePath, "xyz" + no, "txt").toFile();
        FileUtils.write(newFile, "Test", UTF_8);
        FileInputStream fin = new FileInputStream(newFile);
        files.add(fin);/*from ww w .j a v a  2s .  c  om*/
    }
    FileUtils.deleteDirectory(tempFilePath.toFile());
}

From source file:org.guvnor.ala.build.maven.executor.MavenDependencyConfigExecutorTest.java

protected Path getPom(final String groupId, final String artifactId, final String version) throws IOException {
    String pom = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
            + "<project xmlns=\"http://maven.apache.org/POM/4.0.0\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\n"
            + "         xsi:schemaLocation=\"http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd\">\n"
            + "  <modelVersion>4.0.0</modelVersion>\n" + "\n" + "  <groupId>" + groupId + "</groupId>\n"
            + "  <artifactId>" + artifactId + "</artifactId>\n" + "  <version>" + version + "</version>\n"
            + "  <packaging>pom</packaging>\n" + "\n";
    pom += "</project>";

    final Path pomXmlPath = Files.createTempFile(m2Folder.toPath(), "pom", ".xml");
    Files.write(pomXmlPath, pom.getBytes());
    return pomXmlPath;
}

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  www. j  a va2  s.c om*/
    } 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;
}

From source file:nl.salp.warcraft4j.config.PropertyWarcraft4jConfigTest.java

@Test(expected = Warcraft4jConfigException.class)
public void shouldThrowExceptionForFileCacheDir() throws Exception {
    Path testFile = Files.createTempFile(testDir, "cacheDir", "file");

    when(configuration.getString(eq(PropertyWarcraft4jConfig.CACHE_DIR_KEY), anyString()))
            .thenReturn(String.valueOf(testFile));

    new PropertyWarcraft4jConfig(configuration);
}

From source file:org.egov.infra.filestore.service.impl.LocalDiskFileStoreServiceTest.java

@Test
public final void testFetchAll() throws IOException {
    Set<File> files = new HashSet<>();
    for (int no = 0; no < 10; no++) {
        final File newFile = Files.createTempFile(tempFilePath, "xyz" + no, "txt").toFile();
        FileUtils.write(newFile, "Test", UTF_8);
        files.add(newFile);//ww  w. j  av  a 2 s .c  o  m
    }
    final Set<FileStoreMapper> maps = new HashSet<>();
    for (File file : files)
        maps.add(diskFileService.store(file, "fileName", "text/plain", "testmodule"));

    final Set<File> returnfiles = diskFileService.fetchAll(maps, "testmodule");
    assertNotNull(returnfiles);
    assertTrue(returnfiles.size() == 10);

    for (File file : files) {
        Files.deleteIfExists(file.toPath());
    }
}

From source file:gobblin.source.extractor.extract.google.GoogleCommon.java

private static File copyToLocal(FileSystem fs, Path keyPath) throws IOException {
    java.nio.file.Path tmpKeyPath = Files.createTempFile(GoogleCommon.class.getSimpleName(), "tmp",
            PosixFilePermissions.asFileAttribute(PosixFilePermissions.fromString("rwx------")));
    File copied = tmpKeyPath.toFile();
    copied.deleteOnExit();/* ww  w  . j  ava  2 s .co  m*/

    fs.copyToLocalFile(keyPath, new Path(copied.getAbsolutePath()));
    return copied;
}

From source file:org.egov.infra.filestore.service.impl.LocalDiskFileStoreServiceTest.java

@Test
public final void testDeleteFile() throws IOException {
    final File newFile = Files.createTempFile(tempFilePath, "xyz", "txt").toFile();
    FileUtils.write(newFile, "Test", UTF_8);
    FileStoreMapper fileStoreMapper = diskFileService.store(newFile, "fileName", "text/plain", "testmodule");
    diskFileService.delete(fileStoreMapper.getFileStoreId(), "testmodule");
    Files.deleteIfExists(newFile.toPath());
}

From source file:edu.stanford.muse.datacache.BlobStore.java

/**
 * add a new piece of data with content copied from is.
 * if owner is not set on the data, we will set it to this data store's owner.
 * computes content hash and sets it./*from ww  w  . j a v  a  2 s . c o m*/
 * will close the stream when done.
 * Performance critical!
 * returns # of bytes in inputstream
 */
public long add(Blob blob, InputStream is) throws IOException {
    long nBytes = -1;
    /* we no longer assume that if 2 blobs have the same name and file size, their contents must be the same!
    synchronized (this) {
    if (this.contains(blob)) {
        log.info("Item is already present: " + blob);
        return nBytes;
    }
            
    add(blob);
    Util.ASSERT(this.contains(blob));
    }
    */
    // release the lock here because we dont want a long op like reading the object's stream
    // and storing the file to be serialized across threads.

    // copy the stream, if it throws IOException, then we cancel the item
    try {
        // this code is slightly tricky because blob equality (and therefore its membership in this blob store) depends on the hash , which we don't have yet.
        // so we first read the stream into a temp file. As we read the temp file, we get its checksum. We use the checksum to initialize the blob object completely
        // and check if it already exists in the blob store. if not, we assign it in the id_map etc. and then rename the temp file to the proper location in the blob store.

        DigestInputStream din = new DigestInputStream(is, MessageDigest.getInstance("SHA-1"));
        log.info(" adding file to blob store = " + blob.filename);
        Path tmpPath = Files.createTempFile(new File(System.getProperty("java.io.tmpdir")).toPath(), "epadd.",
                ".temp");
        File tmpFile = tmpPath.toFile();
        nBytes = Util.copy_stream_to_file(din, tmpFile.getAbsolutePath());

        // now set the blob size and digest
        blob.size = nBytes; // overwrite this -- earlier we had the part size stored in blob size
        // be careful -- add the blob only after its size and SHA-1 has been updated
        byte byteArray[] = din.getMessageDigest().digest();
        blob.setContentHash(byteArray);

        // ok, now blob is finally set up and can be compared
        // if the blob is already present, fetching the bytes was a waste, but there would no other way to know its checksum.
        // we'll delete the file that is in the tmp dir

        if (uniqueBlobs.contains(blob)) {
            tmpFile.delete();
            return nBytes;
        }

        // blob doesn't already exist, add it, and move it from the temp dir to its actual place in the blobstore

        add(blob);
        // move it from the temp file to the blobs dir. don't do this before add(blob), because full_filename will not be set up correctly until the blob object can be lookedup
        String destination = dir + File.separatorChar + full_filename(blob);
        Files.move(tmpPath, new File(destination).toPath());
    } catch (IOException ioe) {
        // we couldn't copy the stream to the data store, so undo everything
        Util.print_exception("IO Error copying blob to blobstore", ioe, log);
        remove(blob);
        Util.ASSERT(!this.contains(blob));
        throw ioe;
    } catch (NoSuchAlgorithmException nsae) {
        // we couldn't copy the stream to the data store, so undo everything
        remove(blob);
        Util.ASSERT(!this.contains(blob));
        throw new RuntimeException(nsae);
    }

    Util.ASSERT(this.contains(blob));

    // packing needs to be done more efficiently (batch mode or incremental)
    if ((uniqueBlobs.size() % 100) == 0)
        pack();

    return nBytes;
}

From source file:dk.dma.ais.downloader.QueryService.java

/**
 * Execute the given query/*from w  ww .  j  a  v  a 2  s.c  o  m*/
 * @param clientId the client id
 * @param async whether to execute synchronously or asynchronously
 * @param params the query parameters
 * @return the result file
 */
@RequestMapping(value = "/execute/{clientId}", method = RequestMethod.GET)
@ResponseBody
public RepoFile executeQuery(@PathVariable("clientId") String clientId,
        @RequestParam(value = "async", defaultValue = "true") boolean async,
        @RequestParam("params") String params) throws IOException {
    String url = aisViewUrl + params;

    // Create the client ID folder
    Path dir = repoRoot.resolve(clientId);
    if (!Files.exists(dir)) {
        Files.createDirectories(dir);
    }

    // Create a new file to hold the result
    // (could have used Files.createTempFile, but this should be enough to create a unique file)
    Date now = new Date();
    Path file = Files.createTempFile(dir, new SimpleDateFormat("MM-dd HHmmss ").format(now),
            fileType(url) + DOWNLOAD_SUFFIX);
    String fileName = file.getFileName().toString();

    // Load the file
    Future<Path> result = asyncLoadFile(url, file);
    if (!async) {
        try {
            Path path = result.get();
            // The resulting path may actually by an error file
            fileName = path.getFileName().toString();
        } catch (Exception e) {
            log.severe("Error executing query: " + params + ", error: " + e);
        }
    }

    // Return a RepoFile for the newly created file
    RepoFile vo = new RepoFile();
    vo.setName(fileName);
    vo.setPath(clientId + "/" + fileName);
    vo.setUpdated(now);
    vo.setSize(0L);
    return vo;
}

From source file:org.roda_project.commons_ip.model.impl.eark.EARKMETSUtils.java

private static void addMETSToZip(Map<String, ZipEntryInfo> zipEntries, MetsWrapper metsWrapper, String metsPath,
        Path buildDir, boolean mainMets) throws JAXBException, IOException, IPException {
    Path temp = Files.createTempFile(buildDir, IPConstants.METS_FILE_NAME, IPConstants.METS_FILE_EXTENSION);
    ZIPUtils.addMETSFileToZip(zipEntries, temp, metsPath, metsWrapper.getMets(), mainMets);
}