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:com.evolveum.midpoint.tools.schemadist.SchemaDistMojo.java

private String resolveSchemaLocation(String namespace, Path filePath, File workDir)
        throws MojoExecutionException, IOException {
    for (ArtifactItem artifactItem : artifactItems) {
        Catalog catalog = artifactItem.getResolveCatalog();
        String publicId = namespace;
        if (publicId.endsWith("#")) {
            publicId = publicId.substring(0, publicId.length() - 1);
        }//from  w w  w.  ja va 2  s. c  o  m
        String resolvedString = catalog.resolveEntity(filePath.toString(), publicId, publicId);
        if (resolvedString != null) {
            getLog().debug("-------------------");
            getLog().debug(
                    "Resolved namespace " + namespace + " to " + resolvedString + " using catalog " + catalog);
            URL resolvedUrl = new URL(resolvedString);
            String resolvedPathString = resolvedUrl.getPath();
            Path resolvedPath = new File(resolvedPathString).toPath();
            Path workDirPath = workDir.toPath();

            Path resolvedRelativeToCatalogWorkdir = artifactItem.getWorkDir().toPath().relativize(resolvedPath);
            Path fileRelativeToWorkdir = workDirPath.relativize(filePath);

            getLog().debug("workDirPath: " + workDirPath);
            getLog().debug("resolvedRelativeToCatalogWorkdir: " + resolvedRelativeToCatalogWorkdir
                    + ",  fileRelativeToWorkdir: " + fileRelativeToWorkdir);

            Path relativePath = fileRelativeToWorkdir.getParent().relativize(resolvedRelativeToCatalogWorkdir);
            getLog().debug("Rel: " + relativePath);
            return relativePath.toString();
        }
    }
    throw new MojoExecutionException(
            "Cannot resolve namespace " + namespace + " in file " + filePath + " using any of the catalogs");
}

From source file:org.cryptomator.ui.controllers.MainController.java

/**
 * adds the given directory or selects it if it is already in the list of directories.
 * /*from w ww.  j a  va  2 s  .  c  o  m*/
 * @param path non-null, writable, existing directory
 */
public void addVault(final Path path, boolean select) {
    // TODO: `|| !Files.isWritable(path)` is broken on windows. Fix in Java 8u72, see https://bugs.openjdk.java.net/browse/JDK-8034057
    if (path == null) {
        return;
    }

    final Path vaultPath;
    if (path != null && Files.isDirectory(path)) {
        vaultPath = path;
    } else if (path != null && Files.isRegularFile(path)) {
        vaultPath = path.getParent();
    } else {
        return;
    }

    final Vault vault = vaultFactoy.createVault(vaultPath);
    if (!vaults.contains(vault)) {
        vaults.add(vault);
    }
    vaultList.getSelectionModel().select(vault);
}

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;//w  w  w  . j  ava 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();
    }
}

From source file:org.apache.archiva.repository.maven2.MavenRepositoryProvider.java

private ManagedRepositoryConfiguration getStageRepoConfig(ManagedRepositoryConfiguration repository) {
    ManagedRepositoryConfiguration stagingRepository = new ManagedRepositoryConfiguration();
    stagingRepository.setId(repository.getId() + StagingRepositoryFeature.STAGING_REPO_POSTFIX);
    stagingRepository.setLayout(repository.getLayout());
    stagingRepository.setName(repository.getName() + StagingRepositoryFeature.STAGING_REPO_POSTFIX);
    stagingRepository.setBlockRedeployments(repository.isBlockRedeployments());
    stagingRepository.setRetentionPeriod(repository.getRetentionPeriod());
    stagingRepository.setDeleteReleasedSnapshots(repository.isDeleteReleasedSnapshots());
    stagingRepository.setStageRepoNeeded(false);

    String path = repository.getLocation();
    int lastIndex = path.replace('\\', '/').lastIndexOf('/');
    stagingRepository.setLocation(path.substring(0, lastIndex) + "/" + stagingRepository.getId());

    if (StringUtils.isNotBlank(repository.getIndexDir())) {
        Path indexDir = null;
        try {//www. j a v  a  2  s  .  c o  m
            indexDir = Paths
                    .get(new URI(repository.getIndexDir().startsWith("file://") ? repository.getIndexDir()
                            : "file://" + repository.getIndexDir()));
            if (indexDir.isAbsolute()) {
                Path newDir = indexDir.getParent()
                        .resolve(indexDir.getFileName() + StagingRepositoryFeature.STAGING_REPO_POSTFIX);
                log.debug("Changing index directory {} -> {}", indexDir, newDir);
                stagingRepository.setIndexDir(newDir.toString());
            } else {
                log.debug("Keeping index directory {}", repository.getIndexDir());
                stagingRepository.setIndexDir(repository.getIndexDir());
            }
        } catch (URISyntaxException e) {
            log.error("Could not parse index path as uri {}", repository.getIndexDir());
            stagingRepository.setIndexDir("");
        }
        // in case of absolute dir do not use the same
    }
    if (StringUtils.isNotBlank(repository.getPackedIndexDir())) {
        Path packedIndexDir = null;
        try {
            packedIndexDir = Paths.get(new URI(
                    repository.getPackedIndexDir().startsWith("file://") ? repository.getPackedIndexDir()
                            : "file://" + repository.getPackedIndexDir()));
            if (packedIndexDir.isAbsolute()) {
                Path newDir = packedIndexDir.getParent()
                        .resolve(packedIndexDir.getFileName() + StagingRepositoryFeature.STAGING_REPO_POSTFIX);
                log.debug("Changing index directory {} -> {}", packedIndexDir, newDir);
                stagingRepository.setPackedIndexDir(newDir.toString());
            } else {
                log.debug("Keeping index directory {}", repository.getPackedIndexDir());
                stagingRepository.setPackedIndexDir(repository.getPackedIndexDir());
            }
        } catch (URISyntaxException e) {
            log.error("Could not parse index path as uri {}", repository.getPackedIndexDir());
            stagingRepository.setPackedIndexDir("");
        }
        // in case of absolute dir do not use the same
    }
    stagingRepository.setRefreshCronExpression(repository.getRefreshCronExpression());
    stagingRepository.setReleases(repository.isReleases());
    stagingRepository.setRetentionCount(repository.getRetentionCount());
    stagingRepository.setScanned(repository.isScanned());
    stagingRepository.setSnapshots(repository.isSnapshots());
    stagingRepository.setSkipPackedIndexCreation(repository.isSkipPackedIndexCreation());
    // do not duplicate description
    //stagingRepository.getDescription("")
    return stagingRepository;
}

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

/** Create the output object file in the specified streaming job output objects directory
 * @param time the time associated with the job output
 * @param parentDir this streaming job's output objects directory
 * @return output object File that was created under the specified output objects directory
 * @throws IOException//from   w  ww  .j  a  v  a2  s .c  om
 */
public File createStreamingOutputObjectsFile(LocalDateTime time, File parentDir) throws IOException {
    String fileName = String.format("summary-report %s.json", TimeUtils.getLocalDateTimeAsString(time));
    Path path = Paths.get(parentDir.toURI()).resolve(fileName).normalize().toAbsolutePath();
    Files.createDirectories(path.getParent());
    return path.toFile();
}

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

/** Create the File to be used for storing output objects from a job, plus create the directory path to that File
 * @param jobId unique id that has been assigned to the job
 * @param parentDir parent directory for the file to be created
 * @param outputObjectType pre-defined type of output object for the job
 * @return File to be used for storing an output object for this job
 * @throws IOException//from   www . j  av  a2 s .c  o m
 */
private File createOutputObjectsFile(long jobId, File parentDir, String outputObjectType) throws IOException {
    String fileName = String.format("%d/%s.json", jobId, TextUtils.trimToEmpty(outputObjectType));
    Path path = Paths.get(parentDir.toURI()).resolve(fileName).normalize().toAbsolutePath();
    Files.createDirectories(path.getParent());
    return path.toFile();
}

From source file:org.savantbuild.io.tar.TarTools.java

/**
 * Untars a TAR file. This also handles tar.gz files by checking the file extension. If the file extension ends in .gz
 * it will read the tarball through a GZIPInputStream.
 *
 * @param file     The TAR file./*from  ww  w  .  j a v a2s . com*/
 * @param to       The directory to untar to.
 * @param useGroup Determines if the group name in the archive is used.
 * @param useOwner Determines if the owner name in the archive is used.
 * @throws IOException If the untar fails.
 */
public static void untar(Path file, Path to, boolean useGroup, boolean useOwner) throws IOException {
    if (Files.notExists(to)) {
        Files.createDirectories(to);
    }

    InputStream is = Files.newInputStream(file);
    if (file.toString().endsWith(".gz")) {
        is = new GZIPInputStream(is);
    }

    try (TarArchiveInputStream tis = new TarArchiveInputStream(is)) {
        TarArchiveEntry entry;
        while ((entry = tis.getNextTarEntry()) != null) {
            Path entryPath = to.resolve(entry.getName());
            if (entry.isDirectory()) {
                // Skip directory entries that don't add any value
                if (entry.getMode() == 0 && entry.getGroupName() == null && entry.getUserName() == null) {
                    continue;
                }

                if (Files.notExists(entryPath)) {
                    Files.createDirectories(entryPath);
                }

                if (entry.getMode() != 0) {
                    Set<PosixFilePermission> permissions = FileTools.toPosixPermissions(entry.getMode());
                    Files.setPosixFilePermissions(entryPath, permissions);
                }

                if (useGroup && entry.getGroupName() != null && !entry.getGroupName().trim().isEmpty()) {
                    GroupPrincipal group = FileSystems.getDefault().getUserPrincipalLookupService()
                            .lookupPrincipalByGroupName(entry.getGroupName());
                    Files.getFileAttributeView(entryPath, PosixFileAttributeView.class).setGroup(group);
                }

                if (useOwner && entry.getUserName() != null && !entry.getUserName().trim().isEmpty()) {
                    UserPrincipal user = FileSystems.getDefault().getUserPrincipalLookupService()
                            .lookupPrincipalByName(entry.getUserName());
                    Files.getFileAttributeView(entryPath, PosixFileAttributeView.class).setOwner(user);
                }
            } else {
                if (Files.notExists(entryPath.getParent())) {
                    Files.createDirectories(entryPath.getParent());
                }

                if (Files.isRegularFile(entryPath)) {
                    if (Files.size(entryPath) == entry.getSize()) {
                        continue;
                    } else {
                        Files.delete(entryPath);
                    }
                }

                Files.createFile(entryPath);

                try (OutputStream os = Files.newOutputStream(entryPath)) {
                    byte[] ba = new byte[1024];
                    int read;
                    while ((read = tis.read(ba)) != -1) {
                        if (read > 0) {
                            os.write(ba, 0, read);
                        }
                    }
                }

                if (entry.getMode() != 0) {
                    Set<PosixFilePermission> permissions = FileTools.toPosixPermissions(entry.getMode());
                    Files.setPosixFilePermissions(entryPath, permissions);
                }

                if (useGroup && entry.getGroupName() != null && !entry.getGroupName().trim().isEmpty()) {
                    GroupPrincipal group = FileSystems.getDefault().getUserPrincipalLookupService()
                            .lookupPrincipalByGroupName(entry.getGroupName());
                    Files.getFileAttributeView(entryPath, PosixFileAttributeView.class).setGroup(group);
                }

                if (useOwner && entry.getUserName() != null && !entry.getUserName().trim().isEmpty()) {
                    UserPrincipal user = FileSystems.getDefault().getUserPrincipalLookupService()
                            .lookupPrincipalByName(entry.getUserName());
                    Files.getFileAttributeView(entryPath, PosixFileAttributeView.class).setOwner(user);
                }
            }
        }
    }
}

From source file:org.fao.geonet.api.records.formatters.FormatterApiIntegrationTest.java

private String configureGroovyTestFormatter() throws URISyntaxException, IOException {
    final String formatterName = "groovy-test-formatter";
    final URL testFormatterViewFile = FormatterApiIntegrationTest.class
            .getResource(formatterName + "/view.groovy");
    final Path testFormatter = IO.toPath(testFormatterViewFile.toURI()).getParent();
    final Path formatterDir = this.dataDirectory.getFormatterDir();
    IO.copyDirectoryOrFile(testFormatter, formatterDir.resolve(formatterName), false);
    final String groovySharedClasses = "groovy";
    IO.copyDirectoryOrFile(testFormatter.getParent().resolve(groovySharedClasses),
            formatterDir.resolve(groovySharedClasses), false);

    final Path iso19139ConfigProperties = this.schemaManager.getSchemaDir("iso19139")
            .resolve("formatter/config.properties");
    Files.write(iso19139ConfigProperties, "dependsOn=dublin-core".getBytes("UTF-8"));

    final Path dublinCoreSchemaDir = this.schemaManager.getSchemaDir("dublin-core").resolve("formatter/groovy");
    Files.createDirectories(dublinCoreSchemaDir);
    IO.copyDirectoryOrFile(IO.toPath(/*from   w w w  .ja  va2s.c o  m*/
            FormatterApiIntegrationTest.class.getResource(formatterName + "/dublin-core-groovy").toURI()),
            dublinCoreSchemaDir.resolve("DCFunctions.groovy"), false);
    return formatterName;
}

From source file:org.artifactory.storage.binstore.service.providers.DoubleFileBinaryProviderImpl.java

private void copyShaBetweenProviders(DynamicFileBinaryProviderImpl myProvider,
        DynamicFileBinaryProviderImpl otherProvider, String sha1) {
    log.info("Copying missing checksum file " + sha1 + " from '"
            + otherProvider.getBinariesDir().getAbsolutePath() + "' to '"
            + myProvider.getBinariesDir().getAbsolutePath() + "'");
    File src = otherProvider.getFile(sha1);
    File destFile = myProvider.getFile(sha1);
    if (destFile.exists()) {
        log.info("Checksum file '" + destFile.getAbsolutePath() + "' already exists");
        return;/* w w w  .  j  a va 2s.  co m*/
    }
    File tempBinFile = null;
    try {
        tempBinFile = BinaryProviderHelper.createTempBinFile(myProvider.tempBinariesDir);
        FileUtils.copyFile(src, tempBinFile);
        Path target = destFile.toPath();
        if (!java.nio.file.Files.exists(target)) {
            // move the file from the pre-filestore to the filestore
            java.nio.file.Files.createDirectories(target.getParent());
            try {
                log.trace("Moving {} to {}", tempBinFile.getAbsolutePath(), target);
                java.nio.file.Files.move(tempBinFile.toPath(), target, StandardCopyOption.ATOMIC_MOVE);
                log.trace("Moved  {} to {}", tempBinFile.getAbsolutePath(), target);
            } catch (FileAlreadyExistsException ignore) {
                // May happen in heavy concurrency cases
                log.trace("Failed moving {} to {}. File already exist", tempBinFile.getAbsolutePath(), target);
            }
            tempBinFile = null;
        } else {
            log.trace("File {} already exist in the file store. Deleting temp file: {}", target,
                    tempBinFile.getAbsolutePath());
        }
    } catch (IOException e) {
        String msg = "Error copying file " + src.getAbsolutePath() + " into " + destFile.getAbsolutePath();
        if (log.isDebugEnabled()) {
            log.warn(msg, e);
        } else {
            log.warn(msg + " due to: " + e.getMessage());
        }
    } finally {
        if (tempBinFile != null && tempBinFile.exists()) {
            if (!tempBinFile.delete()) {
                log.error("Could not delete temp file {}", tempBinFile.getAbsolutePath());
            }
        }
    }
}

From source file:com.dotosoft.dotoquiz.tools.thirdparty.PicasawebClient.java

public GphotoEntry uploadImageToAlbum(Path imageFilePath, Object remotePhoto, Object albumEntry)
        throws Exception {
    if (imageFilePath.getParent().toFile().exists() && !imageFilePath.toFile().exists()) {
        log.error("File is not found at '" + imageFilePath.toString()
                + "'. Please put the file and start this app again.");
        System.exit(1);/*from   w w  w  .j a v a 2s. c o  m*/
    }
    return (GphotoEntry) uploadImageToAlbum(imageFilePath.toFile(), (GphotoEntry) remotePhoto,
            (GphotoEntry) albumEntry, MD5Checksum.getMD5Checksum(imageFilePath.toString()));
}