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:au.org.ands.vocabs.toolkit.provider.harvest.SesameHarvestProvider.java

/** Do a harvest. Update the message parameter with the result
 * of the harvest.//from  w w  w.  ja v a 2s  .  c o  m
 * @param taskInfo The TaskInfo object describing the entire task.
 * @param subtask The details of the subtask
 * @param results HashMap representing the result of the harvest.
 * @return True, iff the harvest succeeded.
 */
@Override
public final boolean harvest(final TaskInfo taskInfo, final JsonNode subtask,
        final HashMap<String, String> results) {

    if (subtask.get("repository_base") == null) {
        TaskUtils.updateMessageAndTaskStatus(logger, taskInfo.getTask(), results, TaskStatus.ERROR,
                "No Sesame repository_base specified.");
        return false;
    }

    String remoteBase = subtask.get("repository_base").textValue();
    if (remoteBase.isEmpty()) {
        TaskUtils.updateMessageAndTaskStatus(logger, taskInfo.getTask(), results, TaskStatus.ERROR,
                "Blank Sesame repository_base specified.");
        return false;
    }

    if (subtask.get("repository_id") == null) {
        TaskUtils.updateMessageAndTaskStatus(logger, taskInfo.getTask(), results, TaskStatus.ERROR,
                "No Sesame repository_id specified.");
        return false;
    }

    String repositoryId = subtask.get("repository_id").textValue();
    if (repositoryId.isEmpty()) {
        TaskUtils.updateMessageAndTaskStatus(logger, taskInfo.getTask(), results, TaskStatus.ERROR,
                "Blank Sesame repository_id specified.");
        return false;
    }

    // Future work: support accessing via basic authentication.
    //        String username = PROPS.getProperty(
    //                PropertyConstants.POOLPARTYHARVESTER_USERNAME);
    //        String password = PROPS.getProperty(
    //                PropertyConstants.POOLPARTYHARVESTER_PASSWORD);

    logger.debug("Getting project from " + remoteBase + ", repository id " + repositoryId);

    RepositoryManager manager = null;
    try {
        manager = RepositoryProvider.getRepositoryManager(remoteBase);

        Repository repository = manager.getRepository(repositoryId);
        if (repository == null) {
            // Repository is missing. This is bad.
            logger.error("Sesame import, repository missing");
            return false;
        }

        RepositoryConnection con = null;
        try {
            con = repository.getConnection();

            Path dir = Paths.get(ToolkitFileUtils.getTaskHarvestOutputPath(taskInfo));
            ToolkitFileUtils.requireDirectory(dir.toString());

            // Future work: support getting just one context.
            //                String contextUri = null;
            //                Resource context;
            //                if (contextUri != null &&  !(contextUri.isEmpty())) {
            //                    context = repository.getValueFactory()
            //                            .createURI(contextUri);
            //                    results.put("contextUri", contextUri);
            //                }

            File outputFile = new File(dir.resolve(repositoryId + ".rdf").toString());
            OutputStream output = new FileOutputStream(outputFile);
            RDFXMLWriter rdfxmlfWriter = new RDFXMLWriter(output);
            con.export(rdfxmlfWriter);
            //                output.write('\n');

        } catch (FileNotFoundException e) {
            results.put(TaskStatus.EXCEPTION, "Sesame harvest, can't create output file");
            logger.error("Sesame harvest, can't create output file: ", e);
            return false;
        } catch (RDFHandlerException e) {
            results.put(TaskStatus.EXCEPTION, "Sesame harvest, can't serialize");
            logger.error("Sesame harvest, can't serialize: ", e);
            return false;
        } finally {
            if (con != null) {
                con.close();
            }
        }
    } catch (RepositoryConfigException | RepositoryException e) {
        results.put(TaskStatus.EXCEPTION, "Exception in Sesame harvest");
        logger.error("Exception in Sesame harvest", e);
        return false;
    }
    return true;
}

From source file:com.google.gerrit.pgm.init.InitAdminUser.java

private AccountSshKey readSshKey(Account.Id id) throws IOException {
    String defaultPublicSshKeyFile = "";
    Path defaultPublicSshKeyPath = Paths.get(System.getProperty("user.home"), ".ssh", "id_rsa.pub");
    if (Files.exists(defaultPublicSshKeyPath)) {
        defaultPublicSshKeyFile = defaultPublicSshKeyPath.toString();
    }// w  w  w.  j av  a  2s  . co  m
    String publicSshKeyFile = ui.readString(defaultPublicSshKeyFile, "public SSH key file");
    return !Strings.isNullOrEmpty(publicSshKeyFile) ? createSshKey(id, publicSshKeyFile) : null;
}

From source file:Control.LoadImage.java

private Boolean isImageFile(Path filePath) {
    String[] supportedExtensions = { ".jpg", ".png", ".JPG", ".PNG" };

    for (String extension : supportedExtensions) {
        if (filePath.toString().endsWith(extension)) {
            return true;
        }// w  w  w .  j  av a 2 s .  c o m
    }

    return false;
}

From source file:com.netflix.spinnaker.halyard.deploy.services.v1.VaultService.java

public void publishSecret(DeploymentConfiguration deploymentConfiguration, String name, Path path) {
    String contents;/*  ww  w.  j  a v  a 2  s  . co m*/
    try {
        contents = IOUtils.toString(new FileInputStream(path.toFile()));
    } catch (IOException e) {
        throw new HalException(Problem.Severity.FATAL,
                "Failed to read config file " + path.toString() + ": " + e.getMessage());
    }

    publishSecret(deploymentConfiguration, name, contents);
}

From source file:cn.codepub.redis.directory.RedisLockFactory.java

@Override
public Lock obtainLock(@NonNull Directory dir, String lockName) throws IOException {
    if (!(dir instanceof RedisDirectory)) {
        throw new IllegalArgumentException("Expect argument of type [" + RedisDirectory.class.getName() + "]!");
    }//from   w w w . j  a va  2s.c o  m
    Path lockFile = lockFileDirectory.resolve(lockName);
    try {
        Files.createFile(lockFile);
        log.debug("Lock file path = {}", lockFile.toFile().getAbsolutePath());
    } catch (IOException ignore) {
        //ignore
        log.debug("Lock file already exists!");
    }
    final Path realPath = lockFile.toRealPath();
    final FileTime creationTime = Files.readAttributes(realPath, BasicFileAttributes.class).creationTime();
    if (LOCK_HELD.add(realPath.toString())) {
        FileChannel fileChannel = null;
        FileLock lock = null;
        try {
            fileChannel = FileChannel.open(realPath, StandardOpenOption.CREATE, StandardOpenOption.WRITE);
            lock = fileChannel.tryLock();
            if (lock != null) {
                return new RedisLock(lock, fileChannel, realPath, creationTime);
            } else {
                throw new LockObtainFailedException("Lock held by another program: " + realPath);
            }
        } finally {
            if (lock == null) {
                IOUtils.closeQuietly(fileChannel);
                clearLockHeld(realPath);
            }
        }
    } else {
        throw new LockObtainFailedException("Lock held by this virtual machine: " + realPath);
    }
}

From source file:com.mkl.websuites.internal.tests.ScenarioFolderTest.java

private void processRecursivelyFolder(Path folderPath, TestSuite parentSuite) {

    TestSuite currentFolderSuite;//  w ww . j  a v  a2s .  com
    if (isTopTest) {
        currentFolderSuite = new TestSuite(folderPath.toString());
        isTopTest = false;
    } else {
        currentFolderSuite = new TestSuite(
                folderPath.subpath(folderPath.getNameCount() - 1, folderPath.getNameCount()).toString());
    }

    List<Test> testsInCurrentFolder = processScenarioFilesInFolder(folderPath.toString());

    for (Test test : testsInCurrentFolder) {
        currentFolderSuite.addTest(test);
    }

    parentSuite.addTest(currentFolderSuite);

    if (ignoreSubfolders) {
        return;
    }

    File folder = new File(folderPath.toString());

    File[] nestedFolders = folder.listFiles(new FileFilter() {

        @Override
        public boolean accept(File file) {
            return file.isDirectory();
        }
    });

    if (nestedFolders == null) {
        throw new WebServiceException(String.format("Error while traversing through folder "
                + "structure starting from path '%s'. Probably there is something wrong "
                + "in the path string.", folderPath));
    }

    sort(nestedFolders);

    for (File nested : nestedFolders) {

        processRecursivelyFolder(Paths.get(nested.toURI()), currentFolderSuite);
    }

}

From source file:eu.itesla_project.iidm.datasource.Bzip2FileDataSource.java

@Override
public OutputStream newOutputStream(String suffix, String ext, boolean append) throws IOException {
    Path path = getPath(suffix, ext);
    OutputStream os = new BZip2CompressorOutputStream(new BufferedOutputStream(
            Files.newOutputStream(path, append ? StandardOpenOption.APPEND : StandardOpenOption.CREATE)));
    return observer != null ? new ObservableOutputStream(os, path.toString(), observer) : os;
}

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

private void writeCsvTDResults(Path folder, Map<String, Map<String, Boolean>> tdSimulationsResults)
        throws IOException {
    Path csvFile = getFile(folder, "simulation-results.csv");
    System.out.println("writing simulation results to file " + csvFile.toString());
    Set<String> securityIndexIds = new LinkedHashSet<>();
    tdSimulationsResults.values().stream().filter(m -> m != null)
            .forEach(m -> securityIndexIds.addAll(m.keySet()));
    String[] indexIds = securityIndexIds.toArray(new String[securityIndexIds.size()]);
    Arrays.sort(indexIds);//from w  w w .  j a  va  2  s .  co m
    try (FileWriter content = new FileWriter(csvFile.toFile())) {
        CsvWriter cvsWriter = null;
        try {
            cvsWriter = new CsvWriter(content, ',');
            String[] headers = new String[indexIds.length + 1];
            headers[0] = "Basecase";
            int i = 1;
            for (String securityIndexId : indexIds)
                headers[i++] = securityIndexId;
            cvsWriter.writeRecord(headers);
            for (String caseBasename : tdSimulationsResults.keySet()) {
                String[] values = new String[indexIds.length + 1];
                values[0] = caseBasename;
                i = 1;
                for (String securityIndexId : indexIds) {
                    String result = "NA";
                    if (tdSimulationsResults.get(caseBasename).containsKey(securityIndexId))
                        result = tdSimulationsResults.get(caseBasename).get(securityIndexId) ? "OK" : "KO";
                    values[i++] = result;
                }
                cvsWriter.writeRecord(values);
            }
            cvsWriter.flush();
        } finally {
            if (cvsWriter != null)
                cvsWriter.close();
        }
    }
}

From source file:h2backup.BackupFileService.java

public Path backupDatabase(BackupMethod method, String directory, String filePrefix,
        String dateTimeFormatPattern) {
    try {/*from   www  .j  a va  2 s  . c  om*/
        String fileNameWithoutExt = filePrefix + "_"
                + DateTimeFormatter.ofPattern(dateTimeFormatPattern).format(LocalDateTime.now(clock)) + "_"
                + method.getFileSuffix();
        final Path path = Paths.get(directory, fileNameWithoutExt + ZIP_EXTENSION);
        final Path tmpPath = Paths.get(directory, fileNameWithoutExt + TMP_SUFFIX + ZIP_EXTENSION);

        log.info("Starting backup to file {} using {} method", tmpPath, method);
        method.getStrategy().backupDatabase(dataSource, tmpPath.toString());

        if (Files.exists(path) && FileUtils.contentEquals(tmpPath.toFile(), path.toFile())) {
            log.info("Deleting backup {} because it is identical to previous backup {}", tmpPath, path);
            Files.delete(tmpPath);
            return null;
        }

        int maxIndex = 0;
        do {
            maxIndex++;
        } while (Files.exists(Paths.get(directory, fileNameWithoutExt + "_" + maxIndex + ZIP_EXTENSION)));

        for (int index = maxIndex; index >= 1; index--) {
            Path oldPath = Paths.get(directory,
                    fileNameWithoutExt + (index > 1 ? "_" + (index - 1) : "") + ZIP_EXTENSION);
            Path newPath = Paths.get(directory, fileNameWithoutExt + "_" + index + ZIP_EXTENSION);
            if (Files.exists(oldPath)) {
                log.debug("Moving file {} to {}", oldPath, newPath);
                Files.move(oldPath, newPath);
            }
        }

        Files.move(tmpPath, path);

        return path;
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}

From source file:dk.dma.ais.lib.FileConvert.java

/** {@inheritDoc} */
@Override//from w  w w  . j ava  2  s. c o  m
protected void run(Injector injector) throws Exception {
    configureFileEnding();

    final EConsumer<String> consumer = new EConsumer<String>() {

        @Override
        public void accept(String s) throws IllegalArgumentException, IllegalAccessException,
                NoSuchFieldException, SecurityException, IOException, InterruptedException {
            Path path = Paths.get(s);
            LOG.debug("Started processing file " + path);

            Path endPath;
            if (keepFileStructure) {
                Path relative;
                relative = path;
                endPath = Paths.get(Paths.get(convertTo).toString(), relative.toString());
                new File(endPath.toString()).mkdirs();
            } else {
                endPath = Paths.get("");
            }

            String filename = path.getFileName().toString();
            if (!filename.endsWith(fileEnding))
                filename = FilenameUtils.removeExtension(filename) + fileEnding;
            Path filePath = Paths.get(endPath.toString(), filename);

            LOG.debug("Output File: " + filePath.toString());

            final OutputStream fos = new FileOutputStream(filePath.toString()); // 2

            final boolean createSituationFolder = !StringUtils.isBlank(kmzSnapshotAt);
            final long snapshotAtEpochMillis = createSituationFolder
                    ? LocalDateTime.parse(kmzSnapshotAt, formatter).toInstant(ZoneOffset.UTC).toEpochMilli()
                    : -1;

            OutputStreamSink<AisPacket> sink;
            if ("kmz".equals(outputSinkFormat)) {
                //AisPacketKMZOutputSink(filter, createSituationFolder, createMovementsFolder, createTracksFolder, isPrimaryTarget, isSecondaryTarget, triggerSnapshot, snapshotDescriptionSupplier, movementInterpolationStep, supplyTitle, supplyDescription, iconHrefSupplier);
                sink = AisPacketOutputSinks.newKmzSink(e -> true, // this.filter = e -> true;
                        createSituationFolder, // this.createSituationFolder = true;
                        true, // createMovementsFolder = true;
                        true, // this.createTracksFolder = true;
                        e -> kmzPrimaryMmsi <= 0 ? false : e.tryGetAisMessage().getUserId() == kmzPrimaryMmsi, // this.isPrimaryTarget = e -> false;
                        e -> kmzSecondaryMmsi <= 0 ? false
                                : e.tryGetAisMessage().getUserId() == kmzSecondaryMmsi, // this.isSecondaryTarget = e -> false;
                        e -> e.getBestTimestamp() >= snapshotAtEpochMillis, // this.triggerSnapshot = e -> false;
                        () -> "Situation at " + kmzSnapshotAt, // this.snapshotDescriptionSupplier = null;
                        () -> 10, // this.title = defaultTitleSupplier;
                        () -> "description", // this.description = defaultDescriptionSupplier;
                        () -> "10", //this.movementInterpolationStep = defaultMovementInterpolationStepSupplier;
                        (shipTypeCargo, navigationalStatus) -> "" // this.iconHrefSupplier = defaultIconHrefSupplier;
                );

            } else
                sink = AisPacketOutputSinks.getOutputSink(outputSinkFormat, columns);

            sink.closeWhenFooterWritten();

            AisPacketReader apis = AisPacketReader.createFromFile(path, false);

            apis.writeTo(fos, sink);
            apis.close();
            fos.close();
        }
    };

    /*
     * Creates a pool of executors, 4 threads. Each thread will open a file using an aispacket reader, 10000 files can be
     * submitted to the queue, afterwards the calling thread will execute the job instead.
     */
    ThreadPoolExecutor threadpoolexecutor = new ThreadPoolExecutor(4, 4, 1, TimeUnit.SECONDS,
            new ArrayBlockingQueue<>(10000), new ThreadPoolExecutor.CallerRunsPolicy());
    for (final String s : sources) {
        threadpoolexecutor.execute(() -> {
            try {
                consumer.accept(s);
            } catch (Exception e) {
                e.printStackTrace();
            }

        });
    }

    threadpoolexecutor.shutdown();
    threadpoolexecutor.awaitTermination(999, TimeUnit.DAYS);
}