Example usage for java.nio.file Path getParent

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

Introduction

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

Prototype

Path getParent();

Source Link

Document

Returns the parent path, or null if this path does not have a parent.

Usage

From source file:org.codice.ddf.security.migratable.impl.SecurityMigratableTest.java

private void setup(String ddfHomeStr, String tag, String productVersion) throws IOException {
    ddfHome = tempDir.newFolder(ddfHomeStr).toPath().toRealPath();
    Path binDir = ddfHome.resolve("bin");
    Files.createDirectory(binDir);
    System.setProperty(DDF_HOME_SYSTEM_PROP_KEY, ddfHome.toRealPath().toString());
    setupBrandingFile(SUPPORTED_BRANDING);
    setupVersionFile(productVersion);/*from   ww w  .  j  a v a2s  .co m*/
    setupMigrationProperties(SUPPORTED_PRODUCT_VERSION);
    for (Path path : PROPERTIES_FILES) {
        Path p = ddfHome.resolve(path);
        Files.createDirectories(p.getParent());
        Files.createFile(p);
        if (p.endsWith(Paths.get("server", "encryption.properties"))) {
            writeProperties(p, CRL_PROP_KEY, CRL.toString(),
                    String.format("%s&%s", p.toRealPath().toString(), tag));
        } else {
            writeProperties(p, "something", "else", String.format("%s&%s", p.toRealPath().toString(), tag));
        }
    }
    Files.createDirectory(ddfHome.resolve(PDP_POLICIES_DIR));

    setupCrl(tag);
    setupPdpFiles(tag);
    Files.createDirectory(ddfHome.resolve(SECURITY_POLICIES_DIR));
    setupPolicyFiles(tag);
}

From source file:com.serena.rlc.provider.filesystem.client.FilesystemClient.java

public void localExec(String execScript, String execDir, String execParams, boolean ignoreErrors)
        throws FilesystemClientException {
    Path script = Paths.get(execDir + File.separatorChar + execScript);

    try {/*w  ww.  j  a  va 2  s  .co m*/
        if (!Files.exists(script)) {
            if (ignoreErrors) {
                logger.debug("Execution script " + script.toString() + " does not exist, ignoring...");
            } else {
                throw new FilesystemClientException(
                        "Execution script " + script.toString() + " does not exist");
            }
        } else {
            ProcessBuilder pb = new ProcessBuilder(script.toString());
            pb.directory(new File(script.getParent().toString()));
            System.out.println(pb.directory().toString());
            logger.debug("Executing script " + execScript + " in directory " + execDir + " with parameters: "
                    + execParams);
            Process p = pb.start(); // Start the process.
            p.waitFor(); // Wait for the process to finish.
            logger.debug("Executed script " + execScript + " successfully.");
        }
    } catch (Exception e) {
        logger.debug(e.getLocalizedMessage());
        throw new FilesystemClientException(e.getLocalizedMessage());
    }

}

From source file:org.eclipse.winery.repository.backend.filebased.FilebasedRepository.java

/**
 * {@inheritDoc}/* ww w .  j  a  v a  2s  . c  om*/
 */
@Override
public void putContentToFile(RepositoryFileReference ref, InputStream inputStream, MediaType mediaType)
        throws IOException {
    if (mediaType == null) {
        // quick hack for storing mime type called this method
        assert (ref.getFileName().endsWith(Constants.SUFFIX_MIMETYPE));
        // we do not need to store the mime type of the file containing the mime type
        // information
    } else {
        this.setMimeType(ref, mediaType);
    }
    Path targetPath = this.ref2AbsolutePath(ref);
    // ensure that parent directory exists
    FileUtils.createDirectory(targetPath.getParent());

    try {
        Files.copy(inputStream, targetPath, StandardCopyOption.REPLACE_EXISTING);
    } catch (IllegalStateException e) {
        FilebasedRepository.logger.debug("Guessing that stream with length 0 is to be written to a file", e);
        // copy throws an "java.lang.IllegalStateException: Stream already closed" if the
        // InputStream contains 0 bytes
        // For instance, this case happens if SugarCE-6.4.2.zip.removed is tried to be uploaded
        // We work around the Java7 issue and create an empty file
        if (Files.exists(targetPath)) {
            // semantics of putContentToFile: existing content is replaced without notification
            Files.delete(targetPath);
        }
        Files.createFile(targetPath);
    }
}

From source file:org.niord.core.batch.BatchService.java

/**
 * Called every minute to monitor the batch job "[jobName]/in" folders. If a file has been
 * placed in one of these folders, the cause the "jobName" batch job to be started.
 *///from  w  ww .  j  a  v a 2s  . c  o m
@Schedule(persistent = false, second = "48", minute = "*/1", hour = "*/1")
protected void monitorBatchJobInFolderInitiation() {

    // Resolve the list of batch job "in" folders
    List<Path> executionFolders = getBatchJobSubFolders("in");

    // Check for new batch-initiating files in each folder
    for (Path dir : executionFolders) {
        for (Path file : getDirectoryFiles(dir)) {
            String jobName = file.getParent().getParent().getFileName().toString();
            log.info("Found file " + file.getFileName() + " for batch job " + jobName);

            try {
                startBatchJobWithDataFile(jobName, file, new HashMap<>());
            } catch (IOException e) {
                log.error("Failed starting batch job " + jobName + " with file " + file.getFileName());
            } finally {
                // Delete the file
                // Note to self: Move to error folder?
                try {
                    Files.delete(file);
                } catch (IOException ignored) {
                }
            }
        }
    }
}

From source file:com.romeikat.datamessie.core.base.util.FileUtil.java

private static Path getNonExisting(Path path) {
    // Return path, if it does not exist
    if (!Files.exists(path)) {
        return path;
    }/* ww w  . j  a v  a  2 s .c o m*/
    // Determine name and extension
    final String name = path.getFileName().toString();
    final int fileTypeIndex = name.lastIndexOf(".");
    String nameWithoutExtension;
    String extension;
    if (fileTypeIndex == -1) {
        nameWithoutExtension = name;
        extension = "";
    } else {
        nameWithoutExtension = name.substring(0, fileTypeIndex);
        extension = name.substring(fileTypeIndex);
    }
    // Determine number
    final int underscoreIndex = name.lastIndexOf("_");
    String nameWithoutExtensionWithoutNumber;
    Integer nextNumber = 1;
    if (underscoreIndex == -1) {
        nameWithoutExtensionWithoutNumber = nameWithoutExtension;
    } else {
        nameWithoutExtensionWithoutNumber = nameWithoutExtension.substring(0, underscoreIndex);
        final String numberString = name.substring(underscoreIndex + 1);
        try {
            nextNumber = Integer.parseInt(numberString) + 1;
        } catch (final NumberFormatException e) {
        }
    }
    // Determine next candidate
    String nextName;
    while (true) {
        nextName = nameWithoutExtensionWithoutNumber + "_" + nextNumber++ + extension;
        path = Paths.get(path.getParent().toString(), nextName);
        if (!Files.exists(path)) {
            return path;
        }
    }
}

From source file:org.niord.core.batch.BatchService.java

/**
 * Starts a new file-based batch job/*www  .  jav  a 2s  .c  o m*/
 *
 * @param jobName the batch job name
 */
public long startBatchJobWithDataFile(String jobName, InputStream in, String dataFileName,
        Map<String, Object> properties) throws IOException {

    BatchData job = initBatchData(jobName, properties);

    if (in != null) {
        job.setDataFileName(dataFileName);
        Path path = computeBatchJobPath(job.computeDataFilePath());
        createDirectories(path.getParent());
        Files.copy(in, path, StandardCopyOption.REPLACE_EXISTING);
    }

    return startBatchJob(job);
}

From source file:org.niord.core.batch.BatchService.java

/**
 * Starts a new batch job//from  w w w .j  a  v  a  2 s  . co m
 *
 * @param jobName the batch job name
 */
public long startBatchJobWithJsonData(String jobName, Object data, String dataFileName,
        Map<String, Object> properties) throws Exception {

    BatchData job = initBatchData(jobName, properties);

    if (data != null) {
        dataFileName = StringUtils.isNotBlank(dataFileName) ? dataFileName : "batch-data.json";
        job.setDataFileName(dataFileName);
        Path path = computeBatchJobPath(job.computeDataFilePath());
        createDirectories(path.getParent());
        JsonUtils.writeJson(data, path);
    }

    return startBatchJob(job);
}

From source file:org.niord.core.batch.BatchService.java

/**
 * Starts a new batch job/*  w w  w  . ja v  a  2  s  .  c om*/
 *
 * @param jobName the batch job name
 */
public long startBatchJobWithDeflatedData(String jobName, Object data, String dataFileName,
        Map<String, Object> properties) throws Exception {

    BatchData job = initBatchData(jobName, properties);

    if (data != null) {
        dataFileName = StringUtils.isNotBlank(dataFileName) ? dataFileName : "batch-data.zip";
        job.setDataFileName(dataFileName);
        Path path = computeBatchJobPath(job.computeDataFilePath());
        createDirectories(path.getParent());
        try (FileOutputStream file = new FileOutputStream(path.toFile());
                GZIPOutputStream gzipOut = new GZIPOutputStream(file);
                ObjectOutputStream objectOut = new ObjectOutputStream(gzipOut)) {
            objectOut.writeObject(data);
        }
    }

    return startBatchJob(job);
}

From source file:com.facebook.buck.util.unarchive.Untar.java

/**
 * Cleans up the destination for the symlink, and symlink file -> symlink target is recorded in
 * {@code windowsSymlinkMap}//from   w  w w.j  av a2s  .c  om
 */
private void recordSymbolicLinkForWindows(DirectoryCreator creator, Path destPath, TarArchiveEntry entry,
        Map<Path, Path> windowsSymlinkMap) throws IOException {
    prepareForFile(creator, destPath);
    Path linkPath = Paths.get(entry.getLinkName());
    if (destPath.isAbsolute()) {
        windowsSymlinkMap.put(destPath, linkPath);
    } else {
        // Symlink might be '../foo/Bar', so make sure we resolve relative to the src file
        // We make them relative to the file again when we write them out
        Path destinationRelativeTargetPath = destPath.getParent().resolve(linkPath).normalize();
        windowsSymlinkMap.put(destPath, destinationRelativeTargetPath);
    }
}

From source file:com.google.cloud.tools.managedcloudsdk.install.ZipExtractorProvider.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();

    // Use ZipFile instead of ZipArchiveInputStream so that we can obtain file permissions
    // on unix-like systems via getUnixMode(). ZipArchiveInputStream doesn't have access to
    // all the zip file data and will return "0" for any call to getUnixMode().
    try (ZipFile zipFile = new ZipFile(archive.toFile())) {
        // TextProgressBar progressBar = textBarFactory.newProgressBar(messageListener, count);
        Enumeration<ZipArchiveEntry> zipEntries = zipFile.getEntries();
        while (zipEntries.hasMoreElements()) {
            ZipArchiveEntry entry = zipEntries.nextElement();
            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());
            }//from  w w  w.jav  a  2  s .  co  m

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

            if (entry.isDirectory()) {
                if (!Files.exists(entryTarget)) {
                    Files.createDirectories(entryTarget);
                }
            } else {
                if (!Files.exists(entryTarget.getParent())) {
                    Files.createDirectories(entryTarget.getParent());
                }
                try (OutputStream out = new BufferedOutputStream(Files.newOutputStream(entryTarget))) {
                    try (InputStream in = zipFile.getInputStream(entry)) {
                        IOUtils.copy(in, out);
                        PosixFileAttributeView attributeView = Files.getFileAttributeView(entryTarget,
                                PosixFileAttributeView.class);
                        if (attributeView != null) {
                            attributeView
                                    .setPermissions(PosixUtil.getPosixFilePermissions(entry.getUnixMode()));
                        }
                    }
                }
            }
        }
    }
    progressListener.done();
}