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:de.tiqsolutions.hdfs.HadoopFileSystemPath.java

@Override
public Path getName(int index) {
    int c = getNameCount();
    if (index >= c || index < 0)
        return null;
    Path p = this;
    for (int i = 0; i < c - index - 1; i++) {
        p = p.getParent();
    }/*from   w  w  w  . ja  v a 2s.  c o m*/
    return p.getFileName();
}

From source file:com.cloudbees.clickstack.util.Files2.java

/**
 * Copy the given {@code zipSubFilePath} of the given {@code zipFile} into the {@code destDir} if this sub file exists.
 *
 * @param zipFile        the source zip file (e.g. {@code path/to/app.war}
 * @param zipSubFilePath sub file path in the zip file (e.g. {@code /WEB-INF/web.xml}
 * @param destDir//ww  w  .  j a v  a  2 s .com
 * @param trimSourcePath indicates if the source path should be trimmed creating the dest file (e.g. should {@code WEB-INF/web.xml} be copied as
 *                       {@code dest-dir/WEB-INF/web.xml} or as {@code dest-dir/web.xml})
 * @throws RuntimeIOException
 */
@Nullable
public static Path unzipSubFileIfExists(@Nonnull Path zipFile, @Nonnull String zipSubFilePath,
        @Nonnull final Path destDir, boolean trimSourcePath) throws RuntimeIOException {
    try {
        //if the destination doesn't exist, create it
        if (Files.notExists(destDir)) {
            logger.trace("Create dir: {}", destDir);
            Files.createDirectories(destDir);
        }

        try (FileSystem zipFileSystem = createZipFileSystem(zipFile, false)) {
            final Path root = zipFileSystem.getPath("/");

            Path subFile = root.resolve(zipSubFilePath);
            if (Files.exists(subFile)) {
                // make file path relative
                Path destFile;
                if (trimSourcePath) {
                    destFile = destDir.resolve(subFile.getFileName().toString());
                } else {
                    if (Strings2.beginWith(zipSubFilePath, "/")) {
                        destFile = destDir.resolve("." + zipSubFilePath);
                    } else {
                        destFile = destDir.resolve(zipSubFilePath);
                    }
                }
                // create parent dirs if needed
                Files.createDirectories(destFile.getParent());
                // copy
                return Files.copy(subFile, destFile, StandardCopyOption.REPLACE_EXISTING,
                        StandardCopyOption.COPY_ATTRIBUTES);
            } else {
                return null;
            }
        }
    } catch (IOException e) {
        throw new RuntimeIOException("Exception expanding " + zipFile + ":" + zipSubFilePath + " to " + destDir,
                e);
    }
}

From source file:FTP.FileUploading.java

private String getPATH(String File) {
    Path F = Paths.get(File, "");
    String fname = F.getParent().toString();
    return fname;
}

From source file:fr.duminy.jbackup.core.archive.CompressorTest.java

@Theory
public void testCompress(Data data, boolean useListener, EntryType entryType) throws Throwable {
    // preparation of archiver & mocks
    boolean relativeEntries = EntryType.RELATIVE.equals(entryType);
    ErrorType errorType = ErrorType.NO_ERROR;
    ArchiveOutputStream mockOutput = mock(ArchiveOutputStream.class);
    ArgumentCaptor<String> pathArgument = ArgumentCaptor.forClass(String.class);
    doAnswer(new Answer() {
        @Override/*  w  ww  .j a v a 2s  .  c om*/
        public Object answer(InvocationOnMock invocation) throws Throwable {
            InputStream input = (InputStream) invocation.getArguments()[1];
            IOUtils.copy(input, new ByteArrayOutputStream());
            return null;
        }
    }).when(mockOutput).addEntry(pathArgument.capture(), any(InputStream.class));

    ArchiveFactory mockFactory = createMockArchiveFactory(mockOutput);
    Path baseDirectory = createBaseDirectory();
    TaskListener listener = useListener ? mock(TaskListener.class) : null;

    final ArchiveParameters archiveParameters = new ArchiveParameters(createArchivePath(), relativeEntries);
    Map<Path, List<Path>> expectedFilesBySource = data.createFiles(baseDirectory, archiveParameters);
    List<Path> expectedFiles = mergeFiles(expectedFilesBySource);
    Map<String, Path> expectedEntryToFile = new HashMap<>();

    try {
        errorType.setUp(expectedFiles);

        // test compression
        compress(mockFactory, archiveParameters, listener, null);

        // assertions
        verify(mockFactory, times(1)).create(any(OutputStream.class));
        verifyNoMoreInteractions(mockFactory);

        for (Map.Entry<Path, List<Path>> sourceEntry : expectedFilesBySource.entrySet()) {
            for (Path file : sourceEntry.getValue()) {
                assertTrue("test self-check:  files must be absolute", file.isAbsolute());
                final String expectedEntry;
                if (relativeEntries) {
                    Path source = sourceEntry.getKey();
                    if (Files.isDirectory(source)) {
                        expectedEntry = source.getParent().relativize(file).toString();
                    } else {
                        expectedEntry = file.getFileName().toString();
                    }
                } else {
                    expectedEntry = file.toString();
                }
                expectedEntryToFile.put(expectedEntry, file);
                verify(mockOutput, times(1)).addEntry(eq(expectedEntry), any(InputStream.class));
            }
        }
        verify(mockOutput, times(1)).close();
        verifyNoMoreInteractions(mockOutput);
    } catch (Throwable t) {
        errorType.verifyExpected(t);
    } finally {
        errorType.tearDown(expectedFiles);
    }

    assertThatNotificationsAreValid(listener, pathArgument.getAllValues(), expectedEntryToFile, errorType);
}

From source file:org.apache.nifi.minifi.c2.integration.test.AbstractTestSecure.java

public static SSLContext initCertificates(Path certificatesDirectory, List<String> serverHostnames)
        throws Exception {
    List<String> toolkitCommandLine = new ArrayList<>(Arrays.asList("-O", "-o",
            certificatesDirectory.toFile().getAbsolutePath(), "-C", "CN=user1", "-C", "CN=user2", "-C",
            "CN=user3", "-C", "CN=user4", "-S", "badKeystorePass", "-K", "badKeyPass", "-P", "badTrustPass"));
    for (String serverHostname : serverHostnames) {
        toolkitCommandLine.add("-n");
        toolkitCommandLine.add(serverHostname);
    }/* w  ww . j a v  a 2s .c  o m*/
    Files.createDirectories(certificatesDirectory);
    TlsToolkitStandaloneCommandLine tlsToolkitStandaloneCommandLine = new TlsToolkitStandaloneCommandLine();
    tlsToolkitStandaloneCommandLine.parse(toolkitCommandLine.toArray(new String[toolkitCommandLine.size()]));
    new TlsToolkitStandalone()
            .createNifiKeystoresAndTrustStores(tlsToolkitStandaloneCommandLine.createConfig());

    tlsToolkitStandaloneCommandLine = new TlsToolkitStandaloneCommandLine();
    tlsToolkitStandaloneCommandLine.parse(new String[] { "-O", "-o",
            certificatesDirectory.getParent().resolve("badCert").toFile().getAbsolutePath(), "-C",
            "CN=user3" });
    new TlsToolkitStandalone()
            .createNifiKeystoresAndTrustStores(tlsToolkitStandaloneCommandLine.createConfig());

    final KeyStore trustStore = KeyStoreUtils.getTrustStore("jks");
    try (final InputStream trustStoreStream = new FileInputStream(
            certificatesDirectory.resolve("c2").resolve("truststore.jks").toFile().getAbsolutePath())) {
        trustStore.load(trustStoreStream, "badTrustPass".toCharArray());
    }
    final TrustManagerFactory trustManagerFactory = TrustManagerFactory
            .getInstance(TrustManagerFactory.getDefaultAlgorithm());
    trustManagerFactory.init(trustStore);

    return SslContextFactory.createTrustSslContext(
            certificatesDirectory.resolve("c2").resolve("truststore.jks").toFile().getAbsolutePath(),
            "badTrustPass".toCharArray(), "jks", "TLS");
}

From source file:dk.dma.msinm.web.OsmStaticMap.java

public void writeTileToCache(String url, BufferedImage image) {
    try {/*from w w  w . ja va 2  s.com*/
        String filename = tileUrlToFilename(url);
        Path path = repositoryService.getRepoRoot().resolve(filename);
        Files.createDirectories(path.getParent());
        ImageIO.write(image, "png", path.toFile());
    } catch (IOException e) {
        log.warn("Failed saving cached tile for url " + url);
    }
}

From source file:org.eclipse.cdt.arduino.core.internal.board.Platform.java

public IStatus install(IProgressMonitor monitor) throws CoreException {
    try {//w ww .j a v  a 2  s .  c o m
        try (CloseableHttpClient client = HttpClients.createDefault()) {
            HttpGet get = new HttpGet(url);
            try (CloseableHttpResponse response = client.execute(get)) {
                if (response.getStatusLine().getStatusCode() >= 400) {
                    return new Status(IStatus.ERROR, Activator.getId(),
                            response.getStatusLine().getReasonPhrase());
                } else {
                    HttpEntity entity = response.getEntity();
                    if (entity == null) {
                        return new Status(IStatus.ERROR, Activator.getId(), Messages.ArduinoBoardManager_1);
                    }
                    // the archive has the version number as the root
                    // directory
                    Path installPath = getInstallPath().getParent();
                    Files.createDirectories(installPath);
                    Path archivePath = installPath.resolve(archiveFileName);
                    Files.copy(entity.getContent(), archivePath, StandardCopyOption.REPLACE_EXISTING);

                    // extract
                    ArchiveInputStream archiveIn = null;
                    try {
                        String compressor = null;
                        String archiver = null;
                        if (archiveFileName.endsWith("tar.bz2")) { //$NON-NLS-1$
                            compressor = CompressorStreamFactory.BZIP2;
                            archiver = ArchiveStreamFactory.TAR;
                        } else if (archiveFileName.endsWith(".tar.gz") || archiveFileName.endsWith(".tgz")) { //$NON-NLS-1$ //$NON-NLS-2$
                            compressor = CompressorStreamFactory.GZIP;
                            archiver = ArchiveStreamFactory.TAR;
                        } else if (archiveFileName.endsWith(".tar.xz")) { //$NON-NLS-1$
                            compressor = CompressorStreamFactory.XZ;
                            archiver = ArchiveStreamFactory.TAR;
                        } else if (archiveFileName.endsWith(".zip")) { //$NON-NLS-1$
                            archiver = ArchiveStreamFactory.ZIP;
                        }

                        InputStream in = new BufferedInputStream(new FileInputStream(archivePath.toFile()));
                        if (compressor != null) {
                            in = new CompressorStreamFactory().createCompressorInputStream(compressor, in);
                        }
                        archiveIn = new ArchiveStreamFactory().createArchiveInputStream(archiver, in);

                        for (ArchiveEntry entry = archiveIn.getNextEntry(); entry != null; entry = archiveIn
                                .getNextEntry()) {
                            if (entry.isDirectory()) {
                                continue;
                            }

                            // TODO check for soft links in tar files.
                            Path entryPath = installPath.resolve(entry.getName());
                            Files.createDirectories(entryPath.getParent());
                            Files.copy(archiveIn, entryPath, StandardCopyOption.REPLACE_EXISTING);
                        }
                    } finally {
                        if (archiveIn != null) {
                            archiveIn.close();
                        }
                    }
                }
            }
        }
        return Status.OK_STATUS;
    } catch (IOException | CompressorException | ArchiveException e) {
        throw new CoreException(new Status(IStatus.ERROR, Activator.getId(), "Installing Platform", e));
    }
}

From source file:org.eclipse.tycho.plugins.tar.TarGzArchiver.java

private Path getRelativeSymLinkTarget(File source, File baseDir) throws IOException {
    Path sourcePath = source.toPath();
    Path linkTarget = Files.readSymbolicLink(sourcePath);
    // link target may be relative, so we resolve it first
    Path resolvedLinkTarget = sourcePath.getParent().resolve(linkTarget);
    Path relative = baseDir.toPath().relativize(resolvedLinkTarget);
    Path normalizedSymLinkPath = relative.normalize();
    log.debug("Computed symlink target path " + slashify(normalizedSymLinkPath) + " for symlink " + source
            + " relative to " + baseDir);
    return normalizedSymLinkPath;
}

From source file:org.eclipse.cdt.arduino.core.internal.board.ArduinoManager.java

public static void downloadAndInstall(String url, String archiveFileName, Path installPath,
        IProgressMonitor monitor) throws IOException {
    Exception error = null;//from ww  w  .j  av a2s . c  om
    for (int retries = 3; retries > 0 && !monitor.isCanceled(); --retries) {
        try {
            URL dl = new URL(url);
            Path dlDir = ArduinoPreferences.getArduinoHome().resolve("downloads"); //$NON-NLS-1$
            Files.createDirectories(dlDir);
            Path archivePath = dlDir.resolve(archiveFileName);
            URLConnection conn = dl.openConnection();
            conn.setConnectTimeout(10000);
            conn.setReadTimeout(10000);
            Files.copy(conn.getInputStream(), archivePath, StandardCopyOption.REPLACE_EXISTING);

            boolean isWin = Platform.getOS().equals(Platform.OS_WIN32);

            // extract
            ArchiveInputStream archiveIn = null;
            try {
                String compressor = null;
                String archiver = null;
                if (archiveFileName.endsWith("tar.bz2")) { //$NON-NLS-1$
                    compressor = CompressorStreamFactory.BZIP2;
                    archiver = ArchiveStreamFactory.TAR;
                } else if (archiveFileName.endsWith(".tar.gz") || archiveFileName.endsWith(".tgz")) { //$NON-NLS-1$ //$NON-NLS-2$
                    compressor = CompressorStreamFactory.GZIP;
                    archiver = ArchiveStreamFactory.TAR;
                } else if (archiveFileName.endsWith(".tar.xz")) { //$NON-NLS-1$
                    compressor = CompressorStreamFactory.XZ;
                    archiver = ArchiveStreamFactory.TAR;
                } else if (archiveFileName.endsWith(".zip")) { //$NON-NLS-1$
                    archiver = ArchiveStreamFactory.ZIP;
                }

                InputStream in = new BufferedInputStream(new FileInputStream(archivePath.toFile()));
                if (compressor != null) {
                    in = new CompressorStreamFactory().createCompressorInputStream(compressor, in);
                }
                archiveIn = new ArchiveStreamFactory().createArchiveInputStream(archiver, in);

                for (ArchiveEntry entry = archiveIn.getNextEntry(); entry != null; entry = archiveIn
                        .getNextEntry()) {
                    if (entry.isDirectory()) {
                        continue;
                    }

                    // Magic file for git tarballs
                    Path path = Paths.get(entry.getName());
                    if (path.endsWith("pax_global_header")) { //$NON-NLS-1$
                        continue;
                    }

                    // Strip the first directory of the path
                    Path entryPath;
                    switch (path.getName(0).toString()) {
                    case "i586":
                    case "i686":
                        // Cheat for Intel
                        entryPath = installPath.resolve(path);
                        break;
                    default:
                        entryPath = installPath.resolve(path.subpath(1, path.getNameCount()));
                    }

                    Files.createDirectories(entryPath.getParent());

                    if (entry instanceof TarArchiveEntry) {
                        TarArchiveEntry tarEntry = (TarArchiveEntry) entry;
                        if (tarEntry.isLink()) {
                            Path linkPath = Paths.get(tarEntry.getLinkName());
                            linkPath = installPath.resolve(linkPath.subpath(1, linkPath.getNameCount()));
                            Files.deleteIfExists(entryPath);
                            Files.createSymbolicLink(entryPath, entryPath.getParent().relativize(linkPath));
                        } else if (tarEntry.isSymbolicLink()) {
                            Path linkPath = Paths.get(tarEntry.getLinkName());
                            Files.deleteIfExists(entryPath);
                            Files.createSymbolicLink(entryPath, linkPath);
                        } else {
                            Files.copy(archiveIn, entryPath, StandardCopyOption.REPLACE_EXISTING);
                        }
                        if (!isWin && !tarEntry.isSymbolicLink()) {
                            int mode = tarEntry.getMode();
                            Files.setPosixFilePermissions(entryPath, toPerms(mode));
                        }
                    } else {
                        Files.copy(archiveIn, entryPath, StandardCopyOption.REPLACE_EXISTING);
                    }
                }
            } finally {
                if (archiveIn != null) {
                    archiveIn.close();
                }
            }
            return;
        } catch (IOException | CompressorException | ArchiveException e) {
            error = e;
            // retry
        }
    }

    // out of retries
    if (error instanceof IOException) {
        throw (IOException) error;
    } else {
        throw new IOException(error);
    }
}

From source file:org.opencb.opencga.storage.hadoop.variant.HadoopDirectVariantStoragePipeline.java

/**
 * Read from VCF file, group by slice and insert into HBase table.
 *
 * @param inputUri {@link URI}/*from w w w  .jav  a2 s  .  co m*/
 * @throws StorageEngineException if the load fails
 */
protected void loadArch(URI inputUri) throws StorageEngineException {
    Path input = Paths.get(inputUri.getPath());
    String table = archiveTableCredentials.getTable();
    String fileName = input.getFileName().toString();
    Path sourcePath = input.getParent().resolve(VariantReaderUtils.getMetaFromTransformedFile(fileName));

    if (!VariantReaderUtils.isProto(fileName)) {
        throw new NotImplementedException("Direct loading only available for PROTO files.");
    }

    StudyConfiguration studyConfiguration = getStudyConfiguration();
    Integer fileId;
    if (options.getBoolean(Options.ISOLATE_FILE_FROM_STUDY_CONFIGURATION.key(),
            Options.ISOLATE_FILE_FROM_STUDY_CONFIGURATION.defaultValue())) {
        fileId = Options.FILE_ID.defaultValue();
    } else {
        fileId = options.getInt(Options.FILE_ID.key());
    }
    int studyId = getStudyId();

    VariantSource source = VariantReaderUtils.readVariantSource(sourcePath, null);
    source.setFileId(fileId.toString());
    source.setStudyId(Integer.toString(studyId));
    VcfMeta meta = new VcfMeta(source);
    ArchiveHelper helper = new ArchiveHelper(dbAdaptor.getGenomeHelper(), meta);

    ProgressLogger progressLogger = new ProgressLogger("Loaded slices:",
            source.getStats() != null ? source.getStats().getNumRecords() : 0);
    VariantHbasePutTask hbaseWriter = new VariantHbasePutTask(helper, table);
    long counter = 0;
    long start = System.currentTimeMillis();
    try (InputStream in = new BufferedInputStream(new GZIPInputStream(new FileInputStream(input.toFile())))) {
        hbaseWriter.open();
        hbaseWriter.pre();
        VcfSlice slice = VcfSlice.parseDelimitedFrom(in);
        while (null != slice) {
            ++counter;
            hbaseWriter.write(slice);
            progressLogger.increment(slice.getRecordsCount());
            slice = VcfSlice.parseDelimitedFrom(in);
        }
        hbaseWriter.post();
    } catch (IOException e) {
        throw new StorageEngineException("Problems reading " + input, e);
    } finally {
        hbaseWriter.close();
    }
    long end = System.currentTimeMillis();
    logger.info("Read {} slices", counter);
    logger.info("end - start = " + (end - start) / 1000.0 + "s");

    HadoopVariantSourceDBAdaptor manager = dbAdaptor.getVariantSourceDBAdaptor();
    try {
        manager.updateVariantSource(source);
        manager.updateLoadedFilesSummary(studyId, Collections.singletonList(fileId));
    } catch (IOException e) {
        throw new StorageEngineException("Not able to store Variant Source for file!!!", e);
    }
}