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.roda.core.storage.fs.FSUtils.java

/**
 * Moves a directory/file from one path to another
 * /*from   w ww. j  ava 2s  .c o  m*/
 * @param sourcePath
 *          source path
 * @param targetPath
 *          target path
 * @param replaceExisting
 *          true if the target directory/file should be replaced if it already
 *          exists; false otherwise
 * @throws AlreadyExistsException
 * @throws GenericException
 * @throws NotFoundException
 * 
 */
public static void move(final Path sourcePath, final Path targetPath, boolean replaceExisting)
        throws AlreadyExistsException, GenericException, NotFoundException {

    // check if we can replace existing
    if (!replaceExisting && FSUtils.exists(targetPath)) {
        throw new AlreadyExistsException("Cannot copy because target path already exists: " + targetPath);
    }

    // ensure parent directory exists or can be created
    try {
        if (targetPath != null) {
            Files.createDirectories(targetPath.getParent());
        }
    } catch (FileAlreadyExistsException e) {
        // do nothing
    } catch (IOException e) {
        throw new GenericException("Error while creating target directory parent folder", e);
    }

    CopyOption[] copyOptions = replaceExisting ? new CopyOption[] { StandardCopyOption.REPLACE_EXISTING }
            : new CopyOption[] {};

    if (FSUtils.isDirectory(sourcePath)) {
        try {
            Files.move(sourcePath, targetPath, copyOptions);
        } catch (DirectoryNotEmptyException e) {
            // 20160826 hsilva: this might happen in some filesystems (e.g. XFS)
            // because moving a directory implies also moving its entries. In Ext4
            // this doesn't happen.
            LOGGER.debug("Moving recursively, as a fallback & instead of a simple move, from {} to {}",
                    sourcePath, targetPath);
            moveRecursively(sourcePath, targetPath, replaceExisting);
        } catch (IOException e) {
            throw new GenericException("Error while moving directory from " + sourcePath + " to " + targetPath,
                    e);
        }
    } else {
        try {
            Files.move(sourcePath, targetPath, copyOptions);
        } catch (NoSuchFileException e) {
            throw new NotFoundException("Could not find resource to move", e);
        } catch (IOException e) {
            throw new GenericException("Error while copying one file into another", e);
        }
    }
}

From source file:ru.xxlabaza.popa.pack.PackingService.java

private String correctURLs(Path path, String content) {
    Matcher matcher = CSS_URL_PATTERN.matcher(content);
    StringBuffer buffer = new StringBuffer(content.length());
    while (matcher.find()) {
        String url = matcher.group(1);

        String[] tokens = url.split("[\\?#]", 2);

        Path pathToUrlFile = path.getParent().resolve(tokens[0]);
        Path urlPath = build.relativize(pathToUrlFile);
        if (Files.exists(pathToUrlFile)) {
            FileSystemUtils.copy(pathToUrlFile, compressed.resolve(urlPath));
        }/*from w w w  .j a  v  a2  s  .co  m*/

        StringBuilder sb = new StringBuilder('/');
        sb.append(urlPath);
        if (tokens.length > 1) {
            sb.append(url.contains("?") ? '?' : '#').append(tokens[1]);
        }
        matcher.appendReplacement(buffer, sb.toString());
    }
    matcher.appendTail(buffer);
    return buffer.toString();
}

From source file:codes.writeonce.maven.plugins.soy.CompileMojo.java

private void generateJs(List<Path> soyFiles, SoyFileSet soyFileSet, SoyMsgBundle soyMsgBundle, Path outputPath)
        throws IOException {

    final List<String> compiledSources = soyFileSet
            .compileToJsSrc(firstNonNull(jsSrcOptions, new SoyJsSrcOptions()), soyMsgBundle);

    final Iterator<Path> soyFilePathIt = soyFiles.iterator();

    for (final String compiledSource : compiledSources) {

        final Path targetPath = outputPath
                .resolve(Utils.changeSuffix(soyFilePathIt.next(), SOY_EXTENSION, JS_EXTENSION));

        Files.createDirectories(targetPath.getParent());

        try (FileOutputStream out = new FileOutputStream(targetPath.toFile());
                OutputStreamWriter writer = new OutputStreamWriter(out, jsOutputCharsetName)) {
            writer.write(compiledSource);
        }/*from   ww w .ja v a2 s.c om*/
    }
}

From source file:org.codice.ddf.configuration.migration.PathUtilsTest.java

@Test
public void testGetChecksumForWithSoftlink() throws Exception {
    final Path absoluteFilePath = ddfHome.resolve(createFile("test.txt")).toAbsolutePath();
    final Path path2 = ddfHome
            .resolve(createSoftLink(absoluteFilePath.getParent(), "test2.txt", absoluteFilePath))
            .toAbsolutePath();/*from  w w w . j a v  a2 s .co m*/

    final String checksum = pathUtils.getChecksumFor(absoluteFilePath);
    final String checksum2 = pathUtils.getChecksumFor(path2);

    Assert.assertThat(checksum2, Matchers.equalTo(checksum));
}

From source file:company.gonapps.loghut.dao.TagDao.java

public void createTagNameIndex() throws IOException, TemplateException {

    if (tagNameIndexTemplate == null)
        tagNameIndexTemplate = freeMarkerConfigurer.getConfiguration().getTemplate("blog/tag_name_index.ftl");

    List<String> tagNames = getTagNames();
    StringWriter temporaryBuffer = new StringWriter();
    Map<String, Object> modelMap = new HashMap<>();
    modelMap.put("settings", settingDao);
    modelMap.put("tagNames", tagNames);

    tagNameIndexTemplate.process(modelMap, temporaryBuffer);

    Path tagNameIndexPath = Paths.get(settingDao.getSetting("tags.directory") + "/index.html");
    rrwl.writeLock().lock();/*w w w.j  a va2s . co m*/
    Files.createDirectories(tagNameIndexPath.getParent());
    try (BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(tagNameIndexPath.toFile()))) {
        bufferedWriter.write(temporaryBuffer.toString());
    } finally {
        rrwl.writeLock().unlock();
    }
}

From source file:de.thomasbolz.renamer.Renamer.java

/**
 * Step 1 of the renaming process://from   w  w  w . java 2 s . c om
 * Analysis steps in the renaming process. Walks the whole file tree of the source directory and creates a CopyTask
 * for each file or directory that is found and does not match the exclusion list.
 * @return a list of all CopyTasks
 */
public Map<Path, List<CopyTask>> prepareCopyTasks() {

    try {
        Files.walkFileTree(source, EnumSet.of(FileVisitOption.FOLLOW_LINKS), Integer.MAX_VALUE,
                new SimpleFileVisitor<Path>() {

                    /**
                     * If we find a directory create/copy it and add a counter
                     *
                     * @param dir
                     * @param attrs
                     * @return
                     * @throws java.io.IOException
                     */
                    @Override
                    public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs)
                            throws IOException {
                        Path targetdir = target.resolve(source.relativize(dir));
                        copyTasks.put(dir, new ArrayList<CopyTask>());
                        return FileVisitResult.CONTINUE;
                    }

                    @Override
                    public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
                        if (!file.getFileName().toString().toLowerCase().matches(EXLUSION_REGEX)) {
                            copyTasks.get(file.getParent()).add(new CopyTask(file, null));
                        } else {
                            excludedFiles.add(file);
                        }
                        return FileVisitResult.CONTINUE;
                    }
                });
    } catch (IOException e) {
        e.printStackTrace();
    }
    sortCopyTasks();
    //        generateTargetFilenames();
    return copyTasks;
}

From source file:com.facebook.buck.android.ResourcesFilter.java

@Override
public ImmutableList<Step> getBuildSteps(BuildContext context, BuildableContext buildableContext) {
    ImmutableList.Builder<Step> steps = ImmutableList.builder();

    ImmutableList.Builder<Path> filteredResDirectoriesBuilder = ImmutableList.builder();
    ImmutableSet<Path> whitelistedStringPaths = whitelistedStringDirs.stream()
            .map(sourcePath -> getProjectFilesystem()
                    .relativize(context.getSourcePathResolver().getAbsolutePath(sourcePath)))
            .collect(ImmutableSet.toImmutableSet());
    ImmutableList<Path> resPaths = resDirectories.stream()
            .map(sourcePath -> getProjectFilesystem()
                    .relativize(context.getSourcePathResolver().getAbsolutePath(sourcePath)))
            .collect(ImmutableList.toImmutableList());
    ImmutableBiMap<Path, Path> inResDirToOutResDirMap = createInResDirToOutResDirMap(resPaths,
            filteredResDirectoriesBuilder);
    FilterResourcesSteps filterResourcesSteps = createFilterResourcesSteps(whitelistedStringPaths, locales,
            localizedStringFileName, inResDirToOutResDirMap);
    steps.add(filterResourcesSteps.getCopyStep());
    maybeAddPostFilterCmdStep(context, buildableContext, steps, inResDirToOutResDirMap);
    steps.add(filterResourcesSteps.getScaleStep());

    ImmutableList.Builder<Path> stringFilesBuilder = ImmutableList.builder();
    // The list of strings.xml files is only needed to build string assets
    if (resourceCompressionMode.isStoreStringsAsAssets()) {
        GetStringsFilesStep getStringsFilesStep = new GetStringsFilesStep(getProjectFilesystem(), resPaths,
                stringFilesBuilder);/*from   w  w w . j a v  a2s  .  c  o  m*/
        steps.add(getStringsFilesStep);
    }

    ImmutableList<Path> filteredResDirectories = filteredResDirectoriesBuilder.build();
    for (Path outputResourceDir : filteredResDirectories) {
        buildableContext.recordArtifact(outputResourceDir);
    }

    steps.add(new AbstractExecutionStep("record_build_output") {
        @Override
        public StepExecutionResult execute(ExecutionContext context) throws IOException {
            if (postFilterResourcesCmd.isPresent()) {
                buildableContext.recordArtifact(getRDotJsonPath());
            }
            Path stringFiles = getStringFilesPath();
            getProjectFilesystem().mkdirs(stringFiles.getParent());
            getProjectFilesystem().writeLinesToPath(
                    stringFilesBuilder.build().stream().map(Object::toString)::iterator, stringFiles);
            buildableContext.recordArtifact(stringFiles);
            return StepExecutionResults.SUCCESS;
        }
    });

    return steps.build();
}

From source file:company.gonapps.loghut.dao.TagDao.java

public void create(TagDto tag) throws IOException {
    Path tagPath = Paths.get(settingDao.getSetting("tags.directory") + tag.getLocalPath());
    rrwl.writeLock().lock();/*from  w  w w.  j a v a2 s .  c o  m*/
    try {
        Files.createDirectories(tagPath.getParent());
        Files.createFile(tagPath);
    } finally {
        rrwl.writeLock().unlock();
    }
}

From source file:com.qwazr.library.archiver.ArchiverTool.java

public void extract(final Path sourceFile, final Path destDir) throws IOException, ArchiveException {
    try (final InputStream is = new BufferedInputStream(Files.newInputStream(sourceFile))) {
        try (final ArchiveInputStream in = new ArchiveStreamFactory().createArchiveInputStream(is)) {
            ArchiveEntry entry;// w  w w  .ja v  a  2  s.  c  o  m
            while ((entry = in.getNextEntry()) != null) {
                if (!in.canReadEntryData(entry))
                    continue;
                if (entry.isDirectory()) {
                    final Path newDir = destDir.resolve(entry.getName());
                    if (!Files.exists(newDir))
                        Files.createDirectory(newDir);
                    continue;
                }
                if (entry instanceof ZipArchiveEntry)
                    if (((ZipArchiveEntry) entry).isUnixSymlink())
                        continue;
                final Path destFile = destDir.resolve(entry.getName());
                final Path parentDir = destFile.getParent();
                if (!Files.exists(parentDir))
                    Files.createDirectories(parentDir);
                final long entryLastModified = entry.getLastModifiedDate().getTime();
                if (Files.exists(destFile) && Files.isRegularFile(destFile)
                        && Files.getLastModifiedTime(destFile).toMillis() == entryLastModified
                        && entry.getSize() == Files.size(destFile))
                    continue;
                IOUtils.copy(in, destFile);
                Files.setLastModifiedTime(destFile, FileTime.fromMillis(entryLastModified));
            }
        } catch (IOException e) {
            throw new IOException("Unable to extract the archive: " + sourceFile.toAbsolutePath(), e);
        }
    } catch (ArchiveException e) {
        throw new ArchiveException("Unable to extract the archive: " + sourceFile.toAbsolutePath(), e);
    }
}

From source file:ee.ria.xroad.confproxy.util.OutputBuilder.java

/**
 * Moves the signed global configuration to the location where it is
 * accessible to clients and cleans up any remaining temporary files.
 * @throws Exception in case of unsuccessful file operations
 *///from ww w . j  av a  2 s. co  m
public final void moveAndCleanup() throws Exception {
    String path = conf.getConfigurationTargetPath();
    Path targetPath = Paths.get(path, timestamp);
    Path targetConf = Paths.get(path, String.format("%s-v%d", SIGNED_DIRECTORY_NAME, version));
    Files.createDirectories(targetPath.getParent());

    log.debug("Moving '{}' to '{}'", tempDirPath, targetPath);

    Files.move(tempDirPath, targetPath);

    log.debug("Moving '{}' to '{}'", tempConfPath, targetConf);

    Files.move(tempConfPath, targetConf, StandardCopyOption.ATOMIC_MOVE);
    FileUtils.deleteDirectory(tempDirPath.toFile());
}