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:gr.upatras.ece.nam.baker.impl.InstalledBunLifecycleMgmt.java

public int extractPackage(Path targetPath) {
    String cmdStr = "tar --strip-components=1 -xvzf " + targetPath + " -C " + targetPath.getParent()
            + File.separator;//from   w w  w  .  ja  v  a 2s  .co  m
    return executeSystemCommand(cmdStr);
}

From source file:org.esa.s2tbx.dataio.gdal.GDALInstaller.java

private void installDistribution(Path gdalFolderPath, OSCategory osCategory, String mapLibraryName)
        throws IOException {
    // the library file does not exist on  the local disk among the folders from path environment
    String zipArchivePath = osCategory.getDirectory() + "/" + osCategory.getZipFileName();
    Path zipFilePathOnLocalDisk = gdalFolderPath.resolve(zipArchivePath);
    Path gdalDistributionRootFolderPath = zipFilePathOnLocalDisk.getParent();

    fixUpPermissions(gdalFolderPath);//w w w  . j  a v  a 2  s  .c o m

    if (!Files.exists(gdalDistributionRootFolderPath)) {
        Files.createDirectories(gdalDistributionRootFolderPath);
        try {
            String zipFilePathFromSources = SRC_PATH + "/" + zipArchivePath;
            URL zipFileURLFromSources = getClass().getClassLoader().getResource(zipFilePathFromSources);
            FileHelper.copyFile(zipFileURLFromSources, zipFilePathOnLocalDisk);
            FileHelper.unzip(zipFilePathOnLocalDisk, gdalDistributionRootFolderPath, true);
        } finally {
            try {
                Files.deleteIfExists(zipFilePathOnLocalDisk);
            } catch (IOException e) {
                logger.log(Level.SEVERE, "GDAL configuration error: failed to delete zip after decompression.",
                        e);
            }
        }
    }

    Path gdalBinFolderPath = gdalDistributionRootFolderPath.resolve(BIN_PATH);
    processInstalledDistribution(gdalFolderPath, gdalBinFolderPath, osCategory, mapLibraryName);
}

From source file:org.m1theo.apt.repo.builder.RepoBuilder.java

private RepoBuilder(String repoDir, boolean sign, String keyring, String keyId, String passphrase,
        File passphraseFile, String digest) throws AptRepoException {
    Path repoPath = Paths.get(repoDir);
    if (!Files.exists(repoPath)) {
        if (Files.isDirectory(repoPath.getParent())) {
            try {
                Files.createDirectory(repoPath);
            } catch (IOException e) {
                throw new AptRepoException("creating repo directory failed: " + repoDir, e);
            }/*from  ww  w.ja v  a 2  s .c om*/
        } else {
            throw new AptRepoException("repDir does not exist: " + repoDir);
        }
    }
    if (sign) {
        if (!Files.isRegularFile(Paths.get(keyring))) {
            throw new AptRepoException("keyring does not exist: " + keyring);
        }
        this.passphraseFile = passphraseFile;
        this.keyring = new File(keyring);
        this.keyId = keyId;
        this.passphrase = passphrase;
        this.digest = digest;
    } else {
        this.passphraseFile = null;
        this.keyring = null;
        this.keyId = null;
        this.passphrase = null;
        this.digest = null;
    }
    this.repoDir = new File(repoDir);
    this.sign = sign;
}

From source file:org.bonitasoft.platform.configuration.util.AllConfigurationResourceVisitor.java

@Override
public FileVisitResult visitFile(Path path, BasicFileAttributes basicFileAttributes) throws IOException {
    Objects.requireNonNull(path);
    Objects.requireNonNull(basicFileAttributes);
    final File file = path.toFile();
    if (isConfigurationFile(path)) {
        final Long tenantId = getTenantId(path.getParent());
        final String configurationType = getFolderName(path.getParent());
        try (FileInputStream fileInputStream = new FileInputStream(file)) {
            LOGGER.debug(buildMessage(file, tenantId, configurationType));
            fullBonitaConfigurations.add(new FullBonitaConfiguration(file.getName(),
                    IOUtils.toByteArray(fileInputStream), configurationType, tenantId));
        }//from w  w  w.  java 2s . c o m
    }
    return FileVisitResult.CONTINUE;
}

From source file:neembuu.uploader.zip.generator.NUZipFileGenerator.java

private void handleSmallModule(SmallModule moduleDescription, Class clzz, Path uploadersDirectory)
        throws IOException {
    Logger.getLogger(NUZipFileGenerator.class.getName()).log(Level.INFO, "Create zip for: {0}", clzz.getName());
    Path outputModulePath = outputDirectory.resolve("sm").resolve(moduleDescription.name() + ".zip");
    Files.createDirectories(outputModulePath.getParent());
    while (Files.exists(outputModulePath)) {
        try {/*from   w w  w  .ja v  a2 s.c  o m*/
            Files.deleteIfExists(outputModulePath);
        } catch (Exception a) {
            a.printStackTrace();
        }
    }

    Map<String, String> env = new HashMap<>();
    env.put("create", "true");
    boolean destroyZipIsCorrupt = false;
    URI uri = URI.create("jar:" + outputModulePath.toUri());
    try (FileSystem fs = FileSystems.newFileSystem(uri, env)) {
        smallModuleCreateZip(fs, moduleDescription, clzz, uploadersDirectory);
    } catch (Exception e) {
        e.printStackTrace();
        destroyZipIsCorrupt = true;
    }
    if (destroyZipIsCorrupt) {
        Files.delete(outputModulePath);
    } else {
        String hash = HashUtil.hashFile(outputModulePath.toFile(), index.getHashalgorithm());
        try {
            index.addSmallModule(moduleDescription, hash);
        } catch (Exception a) {
            a.printStackTrace();//ignore
        }
    }
}

From source file:nl.salp.warcraft4j.casc.cdn.util.CascFileExtractor.java

private Optional<Path> extractFile(Path destination, long filenameHash)
        throws CascExtractionException, DataReadingException, DataParsingException {
    Optional<Path> file;
    if (isWritableFile(destination)) {
        try {// w  ww  . j av  a2 s  .c om
            Files.createDirectories(destination.getParent());
            try (DataReader in = context.getFileDataReader(filenameHash);
                    OutputStream out = Files.newOutputStream(destination, StandardOpenOption.CREATE,
                            StandardOpenOption.TRUNCATE_EXISTING, StandardOpenOption.WRITE)) {
                while (in.hasRemaining()) {
                    int chunkSize = (int) Math.min(CHUNK_SIZE, in.remaining());
                    byte[] chunk = in.readNext(DataTypeFactory.getByteArray(chunkSize));
                    out.write(chunk);
                }
                out.flush();
                file = Optional.of(destination);
            } catch (CascEntryNotFoundException e) {
                file = Optional.empty();
            }
        } catch (IOException e) {
            throw new CascExtractionException(
                    format("Error while extraction CASC file to %s: %s", destination, e.getMessage()), e);
        }
    } else {
        throw new CascExtractionException(format(
                "Unable to extract a file to %s, the path already exists and is not a file or not writable.",
                destination));
    }
    return file;
}

From source file:org.artifactory.storage.db.binstore.service.FileBinaryProviderImpl.java

@Override
@Nonnull// w  w  w . ja  v a 2  s.  com
public BinaryInfo addStream(InputStream in) throws IOException {
    check();
    File preFileStoreFile = null;
    Sha1Md5ChecksumInputStream checksumStream = null;
    try {
        // first save to a temp file and calculate checksums while saving
        if (in instanceof Sha1Md5ChecksumInputStream) {
            checksumStream = (Sha1Md5ChecksumInputStream) in;
        } else {
            checksumStream = new Sha1Md5ChecksumInputStream(in);
        }
        preFileStoreFile = writeToTempFile(checksumStream);
        BinaryInfo bd = new BinaryInfoImpl(checksumStream);
        log.trace("Inserting {} in file binary provider", bd);

        String sha1 = bd.getSha1();
        long fileLength = preFileStoreFile.length();
        if (fileLength != checksumStream.getTotalBytesRead()) {
            throw new IOException("File length is " + fileLength + " while total bytes read on" + " stream is "
                    + checksumStream.getTotalBytesRead());
        }

        Path target = getFile(sha1).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 {}", preFileStoreFile.getAbsolutePath(), target);
                java.nio.file.Files.move(preFileStoreFile.toPath(), target, StandardCopyOption.ATOMIC_MOVE);
                log.trace("Moved  {} to {}", preFileStoreFile.getAbsolutePath(), target);
            } catch (FileAlreadyExistsException ignore) {
                // May happen in heavy concurrency cases
                log.trace("Failed moving {} to {}. File already exist", preFileStoreFile.getAbsolutePath(),
                        target);
            }
            preFileStoreFile = null;
        } else {
            log.trace("File {} already exist in the file store. Deleting temp file: {}", target,
                    preFileStoreFile.getAbsolutePath());
        }
        return bd;
    } finally {
        IOUtils.closeQuietly(checksumStream);
        if (preFileStoreFile != null && preFileStoreFile.exists()) {
            if (!preFileStoreFile.delete()) {
                log.error("Could not delete temp file {}", preFileStoreFile.getAbsolutePath());
            }
        }
    }
}

From source file:org.canova.image.recordreader.VideoRecordReader.java

@Override
public void initialize(InputSplit split) throws IOException, InterruptedException {
    if (split instanceof FileSplit) {
        URI[] locations = split.locations();
        if (locations != null && locations.length >= 1) {
            if (locations.length > 1) {
                List<File> allFiles = new ArrayList<>();
                for (URI location : locations) {
                    File iter = new File(location);
                    if (iter.isDirectory()) {
                        allFiles.add(iter);
                        if (appendLabel) {
                            File parentDir = iter.getParentFile();
                            String name = parentDir.getName();
                            if (!labels.contains(name))
                                labels.add(name);

                        }//from   ww w .j  ava  2  s.c o m
                    }

                    else {
                        File parent = iter.getParentFile();
                        if (!allFiles.contains(parent) && containsFormat(iter.getAbsolutePath())) {
                            allFiles.add(parent);
                            if (appendLabel) {
                                File parentDir = iter.getParentFile();
                                String name = parentDir.getName();
                                if (!labels.contains(name))
                                    labels.add(name);

                            }
                        }
                    }

                }

                iter = allFiles.iterator();
            } else {
                File curr = new File(locations[0]);
                if (!curr.exists())
                    throw new IllegalArgumentException("Path " + curr.getAbsolutePath() + " does not exist!");
                if (curr.isDirectory())
                    iter = FileUtils.iterateFiles(curr, null, true);
                else
                    iter = Collections.singletonList(curr).iterator();
            }
        }
    }

    else if (split instanceof InputStreamInputSplit) {
        InputStreamInputSplit split2 = (InputStreamInputSplit) split;
        InputStream is = split2.getIs();
        URI[] locations = split2.locations();
        INDArray load = imageLoader.asMatrix(is);
        record = RecordConverter.toRecord(load);
        if (appendLabel) {
            Path path = Paths.get(locations[0]);
            String parent = path.getParent().toString();
            record.add(new DoubleWritable(labels.indexOf(parent)));
        }

        is.close();
    }

}

From source file:org.apache.storm.daemon.logviewer.handler.LogviewerProfileHandlerTest.java

private LogviewerProfileHandler createHandlerTraversalTests(Path rootPath) throws IOException {
    Path daemonLogRoot = rootPath.resolve("logs");
    Path fileOutsideDaemonRoot = rootPath.resolve("evil.bin");
    Path workerLogRoot = daemonLogRoot.resolve("workers-artifacts");
    Path daemonFile = daemonLogRoot.resolve("daemon-dump.bin");
    Path topoA = workerLogRoot.resolve("topoA");
    Path file1 = topoA.resolve("1111").resolve("worker.jfr");
    Path file2 = topoA.resolve("2222").resolve("worker.bin");
    Path file3 = workerLogRoot.resolve("topoB").resolve("1111").resolve("worker.txt");

    Files.createDirectories(file1.getParent());
    Files.createDirectories(file2.getParent());
    Files.createDirectories(file3.getParent());
    Files.write(file1, "TopoA jfr".getBytes(StandardCharsets.UTF_8));
    Files.write(file3, "TopoB txt".getBytes(StandardCharsets.UTF_8));
    Files.createFile(file2);//w w w  .  ja v  a  2  s . c  om
    Files.createFile(fileOutsideDaemonRoot);
    Files.createFile(daemonFile);

    Map<String, Object> stormConf = Utils.readStormConfig();
    StormMetricsRegistry metricsRegistry = new StormMetricsRegistry();
    return new LogviewerProfileHandler(workerLogRoot.toString(), new ResourceAuthorizer(stormConf),
            metricsRegistry);
}

From source file:org.commonjava.indy.ftest.core.content.AuthoritativeIndexedContentInHostedTest.java

@Category(EventDependent.class)
@Test/*  w  ww.jav  a  2  s . c  o m*/
public void bypassNotIndexedContentWithAuthoritativeIndex() throws Exception {
    final String repoName = newName();
    HostedRepository repo = new HostedRepository(MAVEN_PKG_KEY, repoName);
    repo = client.stores().create(repo, name.getMethodName(), HostedRepository.class);

    client.content().store(repo.getKey(), CACHED_AFACT_PATH,
            new ByteArrayInputStream(CACHED_CONTENT.getBytes()));

    final Path nonCachedFile = Paths.get(fixture.getBootOptions().getIndyHome(), "var/lib/indy/storage",
            MAVEN_PKG_KEY, hosted.singularEndpointName() + "-" + repoName, NON_CACHED_AFACT_PATH);
    Files.createDirectories(nonCachedFile.getParent());
    Files.createFile(nonCachedFile);

    try (FileOutputStream stream = new FileOutputStream(nonCachedFile.toFile())) {
        stream.write(NON_CACHED_CONTENT.getBytes());
    }

    repo.setReadonly(true);
    assertThat(client.stores().update(repo, name.getMethodName()), equalTo(true));

    Thread.sleep(500);

    try (InputStream cached = client.content().get(repo.getKey(), CACHED_AFACT_PATH)) {
        assertThat(IOUtils.toString(cached), equalTo(CACHED_CONTENT));
    }

    try (InputStream cached = client.content().get(repo.getKey(), NON_CACHED_AFACT_PATH)) {
        assertThat(cached, equalTo(null));
    }

    repo.setReadonly(false);
    assertThat(client.stores().update(repo, name.getMethodName()), equalTo(true));

    Thread.sleep(500);

    try (InputStream cached = client.content().get(repo.getKey(), CACHED_AFACT_PATH)) {
        assertThat(IOUtils.toString(cached), equalTo(CACHED_CONTENT));
    }

    try (InputStream nonCached = client.content().get(repo.getKey(), NON_CACHED_AFACT_PATH)) {
        assertThat(IOUtils.toString(nonCached), equalTo(NON_CACHED_CONTENT));
    }

    repo.setReadonly(true);
    assertThat(client.stores().update(repo, name.getMethodName()), equalTo(true));

    Thread.sleep(500);

    try (InputStream cached = client.content().get(repo.getKey(), CACHED_AFACT_PATH)) {
        assertThat(IOUtils.toString(cached), equalTo(CACHED_CONTENT));
    }

    try (InputStream nonCached = client.content().get(repo.getKey(), NON_CACHED_AFACT_PATH)) {
        assertThat(IOUtils.toString(nonCached), equalTo(NON_CACHED_CONTENT));
    }

}