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.github.harti2006.neo4j.StartNeo4jServerMojo.java

private void installNeo4jServer() throws MojoExecutionException {
    final Path serverLocation = getServerLocation();
    if (!exists(serverLocation)) {
        final Path downloadDestination = Paths.get(System.getProperty("java.io.tmpdir"),
                "neo4j-server-maven-plugin", "downloads", "server", version, "neo4j-server" + urlSuffix);

        if (!exists(downloadDestination)) {
            try {
                final URL source = new URL(BASE_URL + version + urlSuffix);
                createDirectories(downloadDestination.getParent());

                getLog().info(format("Downloading Neo4j Server from %s", source));
                getLog().debug(format("...and saving it to '%s'", downloadDestination));

                copyURLToFile(source, downloadDestination.toFile());
            } catch (IOException e) {
                throw new MojoExecutionException("Error downloading server artifact", e);
            }/* w  ww . j  a v  a  2 s  .co m*/
        }

        try {
            getLog().info(format("Extracting %s", downloadDestination));
            createArchiver("tar", "gz").extract(downloadDestination.toFile(),
                    serverLocation.getParent().toFile());
        } catch (IOException e) {
            throw new MojoExecutionException("Error extracting server archive", e);
        }
    }
}

From source file:org.roda.core.common.monitor.TransferredResourcesScanner.java

public String renameTransferredResource(TransferredResource resource, String newName, boolean replaceExisting,
        boolean reindexResources)
        throws AlreadyExistsException, GenericException, IsStillUpdatingException, NotFoundException {

    if (FSUtils.exists(Paths.get(resource.getFullPath()))) {
        Path resourcePath = Paths.get(resource.getFullPath());
        Path newPath = resourcePath.getParent().resolve(newName);
        FSUtils.move(resourcePath, newPath, replaceExisting);

        if (reindexResources) {
            if (resource.getParentUUID() != null) {
                try {
                    TransferredResource parent = index.retrieve(TransferredResource.class,
                            resource.getParentUUID(), fieldsToReturn);
                    if (parent != null) {
                        updateTransferredResources(Optional.of(parent.getRelativePath()), true);
                    } else {
                        updateTransferredResources(Optional.empty(), true);
                    }/*  w w  w .  java  2s . c  o m*/
                } catch (GenericException | NotFoundException e) {
                    LOGGER.error("Could not reindex transferred resources after renaming");
                }
            } else {
                updateTransferredResources(Optional.empty(), true);
            }
        }

        Path relativeToBase = basePath.relativize(resourcePath.getParent().resolve(newName));
        return IdUtils.createUUID(relativeToBase.toString());
    } else {
        throw new NotFoundException("Transferred resource was moved or does not exist");
    }
}

From source file:de.tudarmstadt.ukp.dkpro.core.api.datasets.internal.actions.Explode.java

private void extract7z(ActionDescription aAction, Path aCachedFile, Path aTarget)
        throws IOException, RarException {
    // We always extract archives into a subfolder. Figure out the name of the folder.
    String base = getBase(aCachedFile.getFileName().toString());

    Map<String, Object> cfg = aAction.getConfiguration();
    int strip = cfg.containsKey("strip") ? (int) cfg.get("strip") : 0;

    AntFileFilter filter = new AntFileFilter(coerceToList(cfg.get("includes")),
            coerceToList(cfg.get("excludes")));

    try (SevenZFile archive = new SevenZFile(aCachedFile.toFile())) {
        SevenZArchiveEntry entry = archive.getNextEntry();
        while (entry != null) {
            String name = stripLeadingFolders(entry.getName(), strip);

            if (name == null) {
                // Stripped to null - nothing left to extract - continue;
                continue;
            }//from   www  .j av  a2 s  .  c o  m

            if (filter.accept(name)) {
                Path out = aTarget.resolve(base).resolve(name);
                if (entry.isDirectory()) {
                    Files.createDirectories(out);
                } else {
                    Files.createDirectories(out.getParent());
                    try (OutputStream os = Files.newOutputStream(out)) {
                        InputStream is = new SevenZEntryInputStream(archive, entry);
                        IOUtils.copyLarge(is, os);
                    }
                }
            }

            entry = archive.getNextEntry();
        }
    }
}

From source file:org.nuxeo.ecm.core.api.impl.blob.FileBlob.java

/**
 * Moves this blob's temporary file to a new non-temporary location.
 * <p>/*from   ww  w .j ava  2 s .c om*/
 * The move is done as atomically as possible.
 *
 * @since 7.2
 */
public void moveTo(File dest) throws IOException {
    if (!isTemporary) {
        throw new IOException("Cannot move non-temporary file: " + file);
    }
    Path path = file.toPath();
    Path destPath = dest.toPath();
    try {
        Files.move(path, destPath, ATOMIC_MOVE);
        file = dest;
    } catch (AtomicMoveNotSupportedException e) {
        // Do a copy through a tmp file on the same filesystem then atomic rename
        Path tmp = Files.createTempFile(destPath.getParent(), null, null);
        try {
            Files.copy(path, tmp, REPLACE_EXISTING);
            Files.delete(path);
            Files.move(tmp, destPath, ATOMIC_MOVE);
            file = dest;
        } catch (IOException ioe) {
            // don't leave tmp file in case of error
            Files.deleteIfExists(tmp);
            throw ioe;
        }
    }
    isTemporary = false;
}

From source file:org.codice.ddf.catalog.plugin.metacard.backup.storage.filestorage.MetacardBackupFileStorage.java

private void deleteBackupIfPresent(String filename) throws MetacardBackupException {
    Path metacardPath = getMetacardDirectory(filename);
    if (metacardPath == null) {
        LOGGER.debug("Unable to delete backup for: {}", filename);
        throw new MetacardBackupException("Unable to delete backup");
    }//  w ww.j a v  a2  s .  com

    try {
        Files.deleteIfExists(metacardPath);
        while (metacardPath.getParent() != null
                && !metacardPath.getParent().toString().equals(outputDirectory)) {
            metacardPath = metacardPath.getParent();
            if (isDirectoryEmpty(metacardPath)) {
                FileUtils.deleteDirectory(metacardPath.toFile());
            }
        }
    } catch (IOException e) {
        LOGGER.debug("Unable to delete backup file {}", metacardPath, e);
        throw new MetacardBackupException("Unable to delete backup file", e);
    }
}

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

public void delete(TagDto tag) throws IOException {

    Path tagPath = Paths.get(settingDao.getSetting("tags.directory") + tag.getLocalPath());

    rrwl.writeLock().lock();//from w w w.j  a v a  2s . c  o m
    try {
        Files.delete(tagPath);

        FileUtils.rmdir(tagPath.getParent(), new DirectoryStream.Filter<Path>() {
            @Override
            public boolean accept(Path path) throws IOException {
                return !tagPathStringPattern.matcher(path.toString()).find();
            }
        });

        FileUtils.rmdir(tagPath.getParent().getParent(), new DirectoryStream.Filter<Path>() {
            @Override
            public boolean accept(Path path) throws IOException {
                return (!tagMonthPattern.matcher(path.toString()).find()) || (!Files.isDirectory(path));
            }
        });

        FileUtils.rmdir(tagPath.getParent().getParent().getParent(), new DirectoryStream.Filter<Path>() {
            @Override
            public boolean accept(Path path) throws IOException {
                return (!tagYearPattern.matcher(path.toString()).find()) || (!Files.isDirectory(path));
            }
        });
    } finally {
        rrwl.writeLock().unlock();
    }
}

From source file:org.codice.ddf.catalog.plugin.metacard.backup.storage.filestorage.MetacardBackupFileStorage.java

@Override
public void store(String id, byte[] data) throws IOException, MetacardBackupException {
    if (StringUtils.isEmpty(outputDirectory)) {
        throw new MetacardBackupException("Unable to store data; no output directory specified.");
    }//w ww. j  a  v  a 2s. co m

    if (data == null) {
        throw new MetacardBackupException("No data to store");
    }

    Path metacardPath = getMetacardDirectory(id);
    if (metacardPath == null) {
        String message = String.format("Unable to create metacard path directory for %s", id);
        LOGGER.debug(message);
        throw new MetacardBackupException(message);
    }

    try {
        Path parent = metacardPath.getParent();
        if (parent != null) {
            Files.createDirectories(parent);
        }
        Files.createFile(metacardPath);
    } catch (IOException e) {
        LOGGER.trace("Unable to create empty backup file {}.  File may already exist.", metacardPath, e);
    }

    try (OutputStream outputStream = new FileOutputStream(metacardPath.toFile())) {
        IOUtils.write(data, outputStream);
    }
}

From source file:org.apache.storm.localizer.LocallyCachedTopologyBlob.java

protected void extractDirFromJar(String jarpath, String dir, Path dest) throws IOException {
    LOG.debug("EXTRACTING {} from {} and placing it at {}", dir, jarpath, dest);
    try (JarFile jarFile = new JarFile(jarpath)) {
        String toRemove = dir + '/';
        Enumeration<JarEntry> jarEnums = jarFile.entries();
        while (jarEnums.hasMoreElements()) {
            JarEntry entry = jarEnums.nextElement();
            String name = entry.getName();
            if (!entry.isDirectory() && name.startsWith(toRemove)) {
                String shortenedName = name.replace(toRemove, "");
                Path aFile = dest.resolve(shortenedName);
                LOG.debug("EXTRACTING {} SHORTENED to {} into {}", name, shortenedName, aFile);
                fsOps.forceMkdir(aFile.getParent());
                try (FileOutputStream out = new FileOutputStream(aFile.toFile());
                        InputStream in = jarFile.getInputStream(entry)) {
                    IOUtils.copy(in, out);
                }/*w  w w. j av  a  2 s . c  o m*/
            }
        }
    }
}

From source file:org.ligoj.app.resource.plugin.LigojPluginListener.java

/**
 * Get a file reference for a specific subscription. This file will use the
 * subscription as a context to isolate it, and using the related node and
 * the subscription's identifier. The parent directory is created as needed.
 *
 * @param subscription//from w  w  w  .j  av  a  2  s  . com
 *            The subscription used a context of the file to create.
 * @param fragments
 *            The file fragments.
 * @return The file reference.
 * @throws IOException
 *             When the file creation failed.
 */
public File toFile(final Subscription subscription, final String... fragments) throws IOException {
    java.nio.file.Path parent = toPath(getPluginClassLoader().getHomeDirectory(), subscription.getNode());
    parent = parent.resolve(String.valueOf(subscription.getId()));

    // Ensure the t
    for (int i = 0; i < fragments.length; i++) {
        parent = parent.resolve(fragments[i]);
    }
    FileUtils.forceMkdir(parent.getParent().toFile());
    return parent.toFile();
}

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

/**
 * Writes out a single symlink, and any symlinks that may recursively need to exist before writing
 *
 * <p>That is, if foo1/bar should point to foo2/bar, but foo2/bar is also in the map pointing to
 * foo3/bar, then foo2/bar will be writtten first, then foo1/bar
 *
 * @param creator Creator with the right filesystem to create symlinks
 * @param windowsSymlinkMap The map of paths to their target. NOTE: This method modifies the map
 *     as it traverses, removing files that have been written out
 * @param linkFilePath The link file that will actually be created
 * @param target What the link should point to
 * @throws IOException//from ww  w  .j  a v a 2  s  .com
 */
private void writeWindowsSymlink(DirectoryCreator creator, Map<Path, Path> windowsSymlinkMap, Path linkFilePath,
        Path target) throws IOException {
    if (windowsSymlinkMap.containsKey(target)) {
        writeWindowsSymlink(creator, windowsSymlinkMap, target, windowsSymlinkMap.get(target));
    }
    Path relativeTargetPath = linkFilePath.getParent().relativize(target);
    creator.getFilesystem().createSymLink(linkFilePath, relativeTargetPath, true);
    windowsSymlinkMap.remove(linkFilePath);
}