Example usage for java.nio.file Path toString

List of usage examples for java.nio.file Path toString

Introduction

In this page you can find the example usage for java.nio.file Path toString.

Prototype

String toString();

Source Link

Document

Returns the string representation of this path.

Usage

From source file:com.highcharts.export.controller.ExportController.java

@RequestMapping(value = "/files/{name}.{ext}", method = RequestMethod.GET)
public HttpEntity<byte[]> getFile(@PathVariable("name") String name, @PathVariable("ext") String extension)
        throws SVGConverterException, IOException {

    Path path = Paths.get(TempDir.getOutputDir().toString(), name + "." + extension);
    String filename = path.toString();
    MimeType mime = getMime(extension);

    ByteArrayOutputStream stream = writeFileToStream(filename);

    HttpHeaders headers = new HttpHeaders();
    headers.add("Content-Type", mime.getType() + "; charset=utf-8");
    headers.setContentLength(stream.size());

    return new HttpEntity<byte[]>(stream.toByteArray(), headers);
}

From source file:com.ibm.streamsx.topology.internal.context.remote.ZippedToolkitRemoteContext.java

public Future<File> createCodeArchive(File toolkitRoot, JsonObject submission)
        throws IOException, URISyntaxException {

    String tkName = toolkitRoot.getName();

    Path zipOutPath = pack(toolkitRoot.toPath(), graph(submission), tkName);

    if (keepBuildArchive || keepArtifacts(submission)) {
        final JsonObject submissionResult = GsonUtilities.objectCreate(submission,
                RemoteContext.SUBMISSION_RESULTS);
        submissionResult.addProperty(SubmissionResultsKeys.ARCHIVE_PATH, zipOutPath.toString());
    }//from ww w .j  av a 2s  . c  o m

    JsonObject deployInfo = object(submission, SUBMISSION_DEPLOY);
    deleteToolkit(toolkitRoot, deployInfo);

    return new CompletedFuture<File>(zipOutPath.toFile());
}

From source file:com.sumzerotrading.reporting.csv.ReportGeneratorTest.java

@Test
public void testWriteRoundTrip() throws Exception {
    Path path = Files.createTempFile("ReportGeneratorUnitTest", ".txt");
    reportGenerator.outputFile = path.toString();
    String expected = "2016-03-19T07:01:10,Long,ABC,100,100.23,0,2016-03-20T06:01:10,101.23,0,Short,XYZ,50,250.34,0,251.34,0";

    Ticker longTicker = new StockTicker("ABC");
    Ticker shortTicker = new StockTicker("XYZ");
    int longSize = 100;
    int shortSize = 50;
    double longEntryFillPrice = 100.23;
    double longExitFillPrice = 101.23;
    double shortEntryFillPrice = 250.34;
    double shortExitFillPrice = 251.34;
    ZonedDateTime entryTime = ZonedDateTime.of(2016, 3, 19, 7, 1, 10, 0, ZoneId.systemDefault());
    ZonedDateTime exitTime = ZonedDateTime.of(2016, 3, 20, 6, 1, 10, 0, ZoneId.systemDefault());

    TradeOrder longEntry = new TradeOrder("123", longTicker, longSize, TradeDirection.BUY);
    longEntry.setFilledPrice(longEntryFillPrice);
    longEntry.setOrderFilledTime(entryTime);

    TradeOrder longExit = new TradeOrder("123", longTicker, longSize, TradeDirection.SELL);
    longExit.setFilledPrice(longExitFillPrice);
    longExit.setOrderFilledTime(exitTime);

    TradeOrder shortEntry = new TradeOrder("123", shortTicker, shortSize, TradeDirection.SELL);
    shortEntry.setFilledPrice(shortEntryFillPrice);
    shortEntry.setOrderFilledTime(entryTime);

    TradeOrder shortExit = new TradeOrder("123", shortTicker, shortSize, TradeDirection.BUY);
    shortExit.setFilledPrice(shortExitFillPrice);
    shortExit.setOrderFilledTime(exitTime);

    PairTradeRoundTrip roundTrip = new PairTradeRoundTrip();
    roundTrip.longEntry = longEntry;//from   ww  w .j a  v a2  s. com
    roundTrip.longExit = longExit;
    roundTrip.shortEntry = shortEntry;
    roundTrip.shortExit = shortExit;

    System.out.println("Writing out to file: " + path);

    reportGenerator.writeRoundTripToFile(roundTrip);

    List<String> lines = Files.readAllLines(path);
    assertEquals(1, lines.size());
    assertEquals(expected, lines.get(0));

    Files.deleteIfExists(path);

}

From source file:eu.forgetit.middleware.component.Contextualizer.java

public void executeTextContextualization(Exchange exchange) {

    taskStep = "CONTEXTUALIZER_CONTEXTUALIZE_DOCUMENTS";

    logger.debug("New message retrieved for " + taskStep);

    JsonObjectBuilder job = Json.createObjectBuilder();

    JsonObject headers = MessageTools.getHeaders(exchange);

    long taskId = Long.parseLong(headers.getString("taskId"));
    scheduler.updateTask(taskId, TaskStatus.RUNNING, taskStep, null);

    JsonObject jsonBody = MessageTools.getBody(exchange);

    String cmisServerId = null;/* w  w w .  j av  a2s  . c o m*/

    if (jsonBody != null) {

        cmisServerId = jsonBody.getString("cmisServerId");
        JsonArray jsonEntities = jsonBody.getJsonArray("entities");

        job.add("cmisServerId", cmisServerId);
        job.add("entities", jsonEntities);

        for (JsonValue jsonValue : jsonEntities) {

            JsonObject jsonObject = (JsonObject) jsonValue;

            String type = jsonObject.getString("type");

            if (type.equals(Collection.class.getName()))
                continue;

            long pofId = jsonObject.getInt("pofId");

            try {

                String collectorStorageFolder = ConfigurationManager.getConfiguration()
                        .getString("collector.storage.folder");

                Path sipPath = Paths.get(collectorStorageFolder + File.separator + pofId);

                Path metadataPath = Paths.get(sipPath.toString(), "metadata");

                Path contentPath = Paths.get(sipPath.toString(), "content");

                Path contextAnalysisPath = Paths.get(metadataPath.toString(), "worldContext.json");

                logger.debug("Looking for text documents in folder: " + contentPath);

                List<File> documentList = getFilteredDocumentList(contentPath);

                logger.debug("Document List for Contextualization: " + documentList);

                if (documentList != null && !documentList.isEmpty()) {

                    File[] documents = documentList.stream().toArray(File[]::new);

                    context = service.contextualize(documents);

                    logger.debug("World Context:\n");

                    for (String contextEntry : context) {

                        logger.debug(contextEntry);
                    }

                    StringBuilder contextResult = new StringBuilder();

                    for (int i = 0; i < context.length; i++) {

                        Map<String, String> jsonMap = new HashMap<>();
                        jsonMap.put("filename", documents[i].getName());
                        jsonMap.put("context", context[i]);

                        contextResult.append(jsonMap.toString());

                    }

                    FileUtils.writeStringToFile(contextAnalysisPath.toFile(), contextResult.toString());

                    logger.debug("Document Contextualization completed for " + documentList);

                }

            } catch (IOException | ResourceInstantiationException | ExecutionException e) {

                e.printStackTrace();

            }

        }

        exchange.getOut().setBody(job.build().toString());
        exchange.getOut().setHeaders(exchange.getIn().getHeaders());

    } else {

        scheduler.updateTask(taskId, TaskStatus.FAILED, taskStep, null);

        job.add("Message", "Task " + taskId + " failed");

        scheduler.sendMessage("activemq:queue:ERROR.QUEUE", exchange.getIn().getHeaders(), job.build());

    }

}

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

/**
 * Creates a path from the repo file relative to the repo root
 * @param repoFile the repo file/*w  w  w. ja v  a  2s. c om*/
 * @return the path for the file
 */
public String getRepoPath(Path repoFile) {
    Path filePath = getRepoRoot().relativize(repoFile);
    return filePath.toString().replace('\\', '/');
}

From source file:com.ecofactor.qa.automation.platform.ops.impl.AbstractDriverOperations.java

/**
 * Gets the target screenshot path./*from  w w  w.  j a va  2s.c  o  m*/
 * @param fileNames the file names
 * @return the target screenshot path
 * @throws IOException Signals that an I/O exception has occurred.
 */
protected Path getTargetScreenshotPath(final String... fileNames) throws IOException {

    final String dir = System.getProperty("user.dir");
    final String folders = arrayToStringDelimited(fileNames, "/");
    final Path baseDir = Paths.get(dir, fileNames != null && fileNames.length > 1 ? "" : "target/screenshots/");
    LOGGER.debug("Screenshot Base directory is : " + baseDir, true);
    final Path screenShotDir = Paths.get(baseDir.toString(),
            folders.indexOf('/') == -1 ? "" : folders.substring(0, folders.lastIndexOf('/')));
    LOGGER.debug("Actual Screenshot directory is : " + screenShotDir, true);
    Files.createDirectories(screenShotDir);
    if (SystemUtil.isMac()) {
        final String command = "chmod -R 777 " + baseDir;
        Runtime.getRuntime().exec(command);
    }
    return Paths.get(baseDir.toString(), folders + ".png");
}

From source file:io.github.sn0cr.rapidRunner.testRunner.TestCaseFinder.java

public TestCaseFinder(Path parentFolder, String filePattern, String inExtension, String outExtension) {
    final String[] files = parentFolder.toFile().list(new WildcardFileFilter(filePattern));
    Arrays.sort(files, new NaturalOrderComparator());
    for (final String filename : files) {
        final String extension = FilenameUtils.getExtension(filename);
        final String name = FilenameUtils.getBaseName(filename);
        final Path toFile = Paths.get(parentFolder.toString(), filename);
        Pair<Path, Path> testCasePair;
        if (this.testCases.containsKey(name)) {
            testCasePair = this.testCases.get(name);
        } else {/*from   www  .  j  a v  a 2 s. com*/
            testCasePair = new Pair<Path, Path>();
        }
        if (extension.equals(inExtension)) {
            testCasePair.setA(toFile);
        } else if (extension.equals(outExtension)) {
            testCasePair.setB(toFile);
        }
        if (testCasePair.notEmpty()) {
            this.testCases.put(name, testCasePair);
        }
    }
}

From source file:com.surevine.gateway.scm.IncomingProcessorImpl.java

public Collection<Path> extractTarGz(final Path archivePath) throws IOException {
    TarArchiveInputStream archive = openTarGz(archivePath);

    if (!tarGzHasExpectedContents(archive)) {
        LOGGER.debug(archivePath.toString()
                + " does not have the correct contents - exactly one .bundle and exactly one .metadata.json");
        return null;
    }/*from  w  ww  . j a  v  a  2s.co m*/

    // We need to re-open the archive as the Iterator implementation
    // has #reset as a no-op
    archive.close();
    archive = openTarGz(archivePath);

    final Path tmpDir = getTmpExtractionPath(archivePath);
    Files.createDirectories(tmpDir);

    final Collection<Path> extractedFiles = new ArrayList<Path>();
    LOGGER.debug("Extracting " + archivePath.toString() + " to " + tmpDir);

    final File tmp = tmpDir.toFile();

    TarArchiveEntry entry = archive.getNextTarEntry();
    while (entry != null) {
        final File outputFile = new File(tmp, entry.getName());

        if (!entry.isFile()) {
            continue;
        }

        LOGGER.debug("Creating output file " + outputFile.getAbsolutePath());
        registerCreatedFile(outputFile);

        final OutputStream outputFileStream = new FileOutputStream(outputFile);
        IOUtils.copy(archive, outputFileStream);
        outputFileStream.close();

        extractedFiles.add(outputFile.toPath());
        entry = archive.getNextTarEntry();
    }
    archive.close();

    return extractedFiles;
}

From source file:eu.itesla_project.online.tools.AmplExportOnlineWorkflowStatesTool.java

private void exportState(OnlineDb onlinedb, String workflowId, Integer stateId, Path folder) {
    System.out.println("Exporting network data of workflow " + workflowId + ", state " + stateId);
    Network network = onlinedb.getState(workflowId, stateId);
    if (network == null) {
        System.out.println(//from   w  ww.j ava2s.  c  om
                "Cannot export network data: no stored state " + stateId + " for workflow " + workflowId);
        return;
    }
    Path stateFolder = Paths.get(folder.toString(), "wf_" + workflowId + "_state_" + stateId);
    System.out.println("Exporting network data of workflow " + workflowId + ", state " + stateId + " to folder "
            + stateFolder);
    if (stateFolder.toFile().exists()) {
        System.out.println("Cannot export network data of workflow " + workflowId + ", state " + stateId
                + ": folder " + stateFolder + " already exists");
        return;
    }
    if (!stateFolder.toFile().mkdirs()) {
        System.out.println("Cannot export network data of workflow " + workflowId + ", state " + stateId
                + ": unable to create " + stateFolder + " folder");
        return;
    }
    DataSource dataSource = new FileDataSource(stateFolder, "wf_" + workflowId + "_state_" + stateId);
    Exporters.export("AMPL", network, new Properties(), dataSource);
}

From source file:com.google.cloud.tools.managedcloudsdk.install.TarGzExtractorProvider.java

@Override
public void extract(Path archive, Path destination, ProgressListener progressListener) throws IOException {

    progressListener.start("Extracting archive: " + archive.getFileName(), ProgressListener.UNKNOWN);

    String canonicalDestination = destination.toFile().getCanonicalPath();

    GzipCompressorInputStream gzipIn = new GzipCompressorInputStream(Files.newInputStream(archive));
    try (TarArchiveInputStream in = new TarArchiveInputStream(gzipIn)) {
        TarArchiveEntry entry;/*from  w  w w  .ja  va  2s  . co m*/
        while ((entry = in.getNextTarEntry()) != null) {
            Path entryTarget = destination.resolve(entry.getName());

            String canonicalTarget = entryTarget.toFile().getCanonicalPath();
            if (!canonicalTarget.startsWith(canonicalDestination + File.separator)) {
                throw new IOException("Blocked unzipping files outside destination: " + entry.getName());
            }

            progressListener.update(1);
            logger.fine(entryTarget.toString());

            if (entry.isDirectory()) {
                if (!Files.exists(entryTarget)) {
                    Files.createDirectories(entryTarget);
                }
            } else if (entry.isFile()) {
                if (!Files.exists(entryTarget.getParent())) {
                    Files.createDirectories(entryTarget.getParent());
                }
                try (OutputStream out = new BufferedOutputStream(Files.newOutputStream(entryTarget))) {
                    IOUtils.copy(in, out);
                    PosixFileAttributeView attributeView = Files.getFileAttributeView(entryTarget,
                            PosixFileAttributeView.class);
                    if (attributeView != null) {
                        attributeView.setPermissions(PosixUtil.getPosixFilePermissions(entry.getMode()));
                    }
                }
            } else {
                // we don't know what kind of entry this is (we only process directories and files).
                logger.warning("Skipping entry (unknown type): " + entry.getName());
            }
        }
        progressListener.done();
    }
}