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.eclipse.che.api.fs.server.impl.FsOperations.java

void moveWithParents(Path srcFsPath, Path dstFsPath) throws ServerException {
    try {/*from  www  . j a  v a  2s .c o m*/
        Files.createDirectories(dstFsPath.getParent());

        if (Files.isDirectory(srcFsPath)) {
            FileUtils.moveDirectory(srcFsPath.toFile(), dstFsPath.toFile());
        } else {
            FileUtils.moveFile(srcFsPath.toFile(), dstFsPath.toFile());
        }
    } catch (IOException e) {
        throw new ServerException("Failed to move item " + srcFsPath + " to " + dstFsPath, e);
    }
}

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

@Before
public void setup() throws Exception {
    final Path path = createFile(createDirectory(DIRS), FILENAME);

    propertiesPath = createFile(path.getParent(), PROPERTIES_FILENAME);
    absoluteFilePath = ddfHome.resolve(UNIX_NAME).toRealPath(LinkOption.NOFOLLOW_LINKS);

    Mockito.when(context.getPathUtils()).thenReturn(new PathUtils());
    Mockito.when(context.getReport()).thenReturn(report);
    Mockito.when(context.getId()).thenReturn(MIGRATABLE_ID);

    entry = new ExportMigrationJavaPropertyReferencedEntryImpl(context, propertiesPath, PROPERTY, UNIX_NAME);
}

From source file:com.cyc.corpus.nlmpaper.AIMedOpenAccessPaper.java

private Optional<Path> getZipArchive(boolean cached) {
    try {// w  w  w .  j a  v a2 s. co  m
        Path cachedFilePath = cachedArchivePath();
        Path parentDirectoryPath = cachedFilePath.getParent();

        // create the parent directory it doesn't already exist
        if (Files.notExists(parentDirectoryPath, LinkOption.NOFOLLOW_LINKS)) {
            Files.createDirectory(parentDirectoryPath);
        }

        // if cached file already exist - return it, no download necessary
        if (cached && Files.exists(cachedFilePath, LinkOption.NOFOLLOW_LINKS)) {
            return Optional.of(cachedFilePath.toAbsolutePath());
        }

        // otherwise, download the file
        URL url = new URL(PROTEINS_URL);
        Files.copy(url.openStream(), cachedFilePath, StandardCopyOption.REPLACE_EXISTING);
        return Optional.of(cachedFilePath.toAbsolutePath());

    } catch (MalformedURLException ex) {
        LOG.log(Level.SEVERE, ex.getMessage(), ex);
    } catch (IOException ex) {
        LOG.log(Level.SEVERE, ex.getMessage(), ex);
    }

    return Optional.empty();
}

From source file:br.com.thiaguten.archive.AbstractArchive.java

/**
 * Generic compress implementation/* w w w  .  j a v a2  s.co m*/
 */
@Override
public Path compress(Path... paths) throws IOException {
    Path compress = null;
    ArchiveOutputStream archiveOutputStream = null;

    for (Path path : paths) {
        // get path infos
        final Path parent = path.getParent();
        final String name = path.getFileName().toString();
        final boolean isDirectory = isDirectory(path);

        if (compress == null) {
            // create compress file
            String compressName = (paths.length == 1 ? name : getName());
            compress = Paths.get(parent.toString(), compressName + getExtension());

            // creates a new compress file to not override if already exists
            // if you do not want this behavior, just comment this line
            compress = createFile(ArchiveAction.COMPRESS, parent, compress);

            // open compress file stream
            archiveOutputStream = createArchiveOutputStream(
                    new BufferedOutputStream(newOutputStream(compress)));

            logger.debug("creating the archive file " + compressName);
        }

        logger.debug("reading path " + path);

        if (isDirectory) {
            compressDirectory(parent, path, archiveOutputStream);
        } else {
            compressFile(parent, path, archiveOutputStream);
        }
    }

    // closing streams
    if (archiveOutputStream != null) {
        archiveOutputStream.finish();
        archiveOutputStream.close();
    }

    logger.debug("finishing the archive file: " + compress);

    return compress;
}

From source file:com.facebook.buck.cxx.ArchiveStepIntegrationTest.java

@Test
public void thinArchives() throws IOException, InterruptedException {
    assumeTrue(Platform.detect() == Platform.MACOS || Platform.detect() == Platform.LINUX);
    ProjectFilesystem filesystem = new ProjectFilesystem(tmp.getRoot());
    CxxPlatform platform = CxxPlatformUtils.build(new CxxBuckConfig(FakeBuckConfig.builder().build()));
    assumeTrue(platform.getAr().supportsThinArchives());

    // Build up the paths to various files the archive step will use.
    SourcePathResolver sourcePathResolver = new SourcePathResolver(new SourcePathRuleFinder(
            new BuildRuleResolver(TargetGraph.EMPTY, new DefaultTargetNodeToBuildRuleTransformer())));
    Archiver archiver = platform.getAr();

    Path output = filesystem.getPath("foo/libthin.a");
    filesystem.mkdirs(output.getParent());

    // Create a really large input file so it's obvious that the archive is thin.
    Path input = filesystem.getPath("bar/blah.dat");
    filesystem.mkdirs(input.getParent());
    byte[] largeInputFile = new byte[1024 * 1024];
    byte[] fillerToRepeat = "hello\n".getBytes(StandardCharsets.UTF_8);
    for (int i = 0; i < largeInputFile.length; i++) {
        largeInputFile[i] = fillerToRepeat[i % fillerToRepeat.length];
    }// ww  w.  jav  a  2  s . c  om
    filesystem.writeBytesToPath(largeInputFile, input);

    // Build an archive step.
    ArchiveStep archiveStep = new ArchiveStep(filesystem, archiver.getEnvironment(),
            archiver.getCommandPrefix(sourcePathResolver), ImmutableList.of(), getArchiveOptions(true), output,
            ImmutableList.of(input), archiver);

    // Execute the archive step and verify it ran successfully.
    ExecutionContext executionContext = TestExecutionContext.newInstance();
    TestConsole console = (TestConsole) executionContext.getConsole();
    int exitCode = archiveStep.execute(executionContext).getExitCode();
    assertEquals("archive step failed: " + console.getTextWrittenToStdErr(), 0, exitCode);

    // Verify that the thin header is present.
    assertThat(filesystem.readFirstLine(output), Matchers.equalTo(Optional.of("!<thin>")));

    // Verify that even though the archived contents is really big, the archive is still small.
    assertThat(filesystem.getFileSize(output), Matchers.lessThan(1000L));

    // NOTE: Replace the thin header with a normal header just so the commons compress parser
    // can parse the archive contents.
    try (OutputStream outputStream = Files.newOutputStream(filesystem.resolve(output),
            StandardOpenOption.WRITE)) {
        outputStream.write(ObjectFileScrubbers.GLOBAL_HEADER);
    }

    // Now read the archive entries and verify that the timestamp, UID, and GID fields are
    // zero'd out.
    try (ArArchiveInputStream stream = new ArArchiveInputStream(
            new FileInputStream(filesystem.resolve(output).toFile()))) {
        ArArchiveEntry entry = stream.getNextArEntry();

        // Verify that the input names are relative paths from the outputs parent dir.
        assertThat(entry.getName(), Matchers.equalTo(output.getParent().relativize(input).toString()));
    }
}

From source file:com.ttech.cordovabuild.domain.application.source.ApplicationSourceFactoryImpl.java

private boolean isSubPath(Path path, Path parent) {
    if (path == null)
        return false;
    if (path.equals(parent))
        return true;
    else/*  w w w.  jav  a 2 s .  c o  m*/
        return isSubPath(path.getParent(), parent);
}

From source file:com.kumarvv.setl.Setl.java

/**
 * init csv paths/*from   w w w. j  a  v  a 2s . c om*/
 *
 * @param def
 * @param defPath
 */
protected void initCsvPaths(final Def def, Path defPath) {
    if (def.getExtract().getCsv() != null && StringUtils.isNotEmpty(def.getExtract().getCsv().getFile())) {
        Path csvPath = defPath.getParent().resolve(def.getExtract().getCsv().getFile()).normalize();
        def.getExtract().getCsv().setFilePath(csvPath.toAbsolutePath().toString());
    }

    for (Load load : def.getLoads()) {
        if (load.getPre() != null && load.getPre().getCsv() != null
                && StringUtils.isNotEmpty(load.getPre().getCsv().getFile())) {
            Path csvPath = defPath.getParent().resolve(load.getPre().getCsv().getFile()).normalize();
            load.getPre().getCsv().setFilePath(csvPath.toAbsolutePath().toString());
        }
        if (load.getPost() != null && load.getPost().getCsv() != null
                && StringUtils.isNotEmpty(load.getPost().getCsv().getFile())) {
            Path csvPath = defPath.getParent().resolve(load.getPost().getCsv().getFile()).normalize();
            load.getPost().getCsv().setFilePath(csvPath.toAbsolutePath().toString());
        }
    }
}

From source file:de.flashpixx.rrd_antlr4.engine.template.IBaseTemplate.java

/**
 * copies files from the directory of the template to the output directory
 *
 * @param p_templatefile file within the template directory
 * @param p_output output directory//  ww  w  . ja v  a2s .c om
 * @throws IOException on IO error
 * @throws URISyntaxException on URL syntax error
 */
protected final void copy(final String p_templatefile, final Path p_output)
        throws IOException, URISyntaxException {
    final Path l_target = Paths.get(p_output.toString(), p_templatefile);
    Files.createDirectories(l_target.getParent());
    Files.copy(CCommon.resourceurl(MessageFormat.format("{0}{1}{2}{3}", "de/flashpixx/rrd_antlr4/template/",
            m_name, "/", p_templatefile)).openStream(), l_target, StandardCopyOption.REPLACE_EXISTING);
}

From source file:org.bonitasoft.web.designer.repository.JsonFileBasedPersister.java

/**
 * Save an identifiable object in a json file
 * @throws IOException/*from w  ww .  j  a va2s .co  m*/
 */
public void save(Path directory, String id, T content) throws IOException {
    content.setDesignerVersionIfEmpty(version);
    validator.validate(content);
    try {
        write(jsonFile(directory, id), objectMapper.toPrettyJson(content, JsonViewPersistence.class));
        forceMkdir(directory.getParent().resolve(".metadata").toFile());
        write(jsonFile(directory.getParent().resolve(".metadata"), id),
                objectMapper.toJson(content, JsonViewMetadata.class));
    } catch (RuntimeException e) {
        //Jackson can sent Runtime exception. We change this one to IO because this exception is caught higher
        throw new IOException(e);
    }
}

From source file:org.canova.image.recordreader.ImageRecordReader.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() && containsFormat(iter.getAbsolutePath()))
                        allFiles.add(iter);
                    if (appendLabel) {
                        File parentDir = iter.getParentFile();
                        String name = parentDir.getName();
                        if (!labels.contains(name))
                            labels.add(name);

                    }/*  w w  w . ja v a2s .com*/

                }

                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();
    }

}