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.att.research.xacml.admin.model.GitRepositoryContainer.java

/**
 * Returns <code>false</code> when moving files around in the filesystem is
 * not supported./* w w w .  ja va  2 s . co  m*/
 * 
 * @param itemId
 *            the ID of the item.
 * @param newParentId
 *            the ID of the Item that's to be the new parent of the Item
 *            identified with itemId.
 * @return <code>true</code> if the operation is successful otherwise
 *         <code>false</code>.
 * @throws UnsupportedOperationException
 *             if the setParent is not supported.
 */
@Override
public boolean setParent(Object itemId, Object newParentId) throws UnsupportedOperationException {
    if (logger.isTraceEnabled()) {
        logger.trace("setParent: " + ((File) itemId).hashCode() + " " + ((File) itemId).getName() + " to: "
                + ((File) newParentId).hashCode() + " " + ((File) newParentId).getName());
    }

    Path path = Paths.get(((File) itemId).getAbsolutePath());
    Path parent = Paths.get(((File) newParentId).getAbsolutePath());
    boolean ok = (path.getParent() == parent);

    if (ok) {
        fireItemSetChange();
    }
    return ok;
}

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

/**
 * Assert that a symlink exists inside of the temp directory with given contents and that links to
 * the right file//from  w  ww  .j  a  va 2 s.  c o m
 */
private void assertOutputSymlinkExists(Path symlinkPath, Path expectedLinkedToPath, String expectedContents)
        throws IOException {
    Path fullPath = tmpFolder.getRoot().resolve(symlinkPath);
    if (Platform.detect() != Platform.WINDOWS) {
        Assert.assertTrue(String.format("Expected %s to be a symlink", fullPath),
                Files.isSymbolicLink(fullPath));
        Path linkedToPath = Files.readSymbolicLink(fullPath);
        Assert.assertEquals(String.format("Expected symlink at %s to point to %s, not %s", symlinkPath,
                expectedLinkedToPath, linkedToPath), expectedLinkedToPath, linkedToPath);
    }

    Path realExpectedLinkedToPath = filesystem.getRootPath()
            .resolve(symlinkPath.getParent().resolve(expectedLinkedToPath).normalize());
    Assert.assertTrue(
            String.format("Expected link %s to be the same file as %s", fullPath, realExpectedLinkedToPath),
            Files.isSameFile(fullPath, realExpectedLinkedToPath));

    String contents = Joiner.on('\n').join(Files.readAllLines(fullPath));
    Assert.assertEquals(expectedContents, contents);
}

From source file:org.apache.openaz.xacml.admin.model.GitRepositoryContainer.java

/**
 * Returns <code>false</code> when moving files around in the filesystem is
 * not supported.//from   w  ww.  ja  va 2 s  .  com
 * 
 * @param itemId
 *            the ID of the item.
 * @param newParentId
 *            the ID of the Item that's to be the new parent of the Item
 *            identified with itemId.
 * @return <code>true</code> if the operation is successful otherwise
 *         <code>false</code>.
 * @throws UnsupportedOperationException
 *             if the setParent is not supported.
 */
@Override
public boolean setParent(Object itemId, Object newParentId) throws UnsupportedOperationException {
    if (logger.isTraceEnabled()) {
        logger.trace("setParent: " + ((File) itemId).hashCode() + " " + ((File) itemId).getName() + " to: "
                + ((File) newParentId).hashCode() + " " + ((File) newParentId).getName());
    }

    Path path = Paths.get(((File) itemId).getAbsolutePath());
    Path parent = Paths.get(((File) newParentId).getAbsolutePath());
    boolean ok = path.getParent() == parent;

    if (ok) {
        fireItemSetChange();
    }
    return ok;
}

From source file:org.apache.taverna.databundle.TestDataBundles.java

@Test
public void getInputs() throws Exception {
    Path inputs = DataBundles.getInputs(dataBundle);
    assertTrue(Files.isDirectory(inputs));
    // Second time should not fail because it alreadresolvy exists
    inputs = DataBundles.getInputs(dataBundle);
    assertTrue(Files.isDirectory(inputs));
    assertEquals(dataBundle.getRoot(), inputs.getParent());
}

From source file:org.apache.taverna.databundle.TestDataBundles.java

@Test
public void getOutputs() throws Exception {
    Path outputs = DataBundles.getOutputs(dataBundle);
    assertTrue(Files.isDirectory(outputs));
    // Second time should not fail because it already exists
    outputs = DataBundles.getOutputs(dataBundle);
    assertTrue(Files.isDirectory(outputs));
    assertEquals(dataBundle.getRoot(), outputs.getParent());
}

From source file:com.searchcode.app.jobs.IndexGitRepoJob.java

/**
 * Indexes all the documents in the path provided. Will also remove anything from the index if not on disk
 * Generally this is a slow update used only for the inital clone of a repository
 * NB this can be used for updates but it will be much slower as it needs to to walk the contents of the disk
 *///w w w  .j a v  a 2 s .  c  o  m
public void indexDocsByPath(Path path, String repoName, String repoLocations, String repoRemoteLocation,
        boolean existingRepo) {
    SearchcodeLib scl = Singleton.getSearchCodeLib(); // Should have data object by this point
    List<String> fileLocations = new ArrayList<>();
    Queue<CodeIndexDocument> codeIndexDocumentQueue = Singleton.getCodeIndexQueue();

    // Convert once outside the main loop
    String fileRepoLocations = FilenameUtils.separatorsToUnix(repoLocations);
    boolean lowMemory = this.LOWMEMORY;
    boolean useSystemGit = this.USESYSTEMGIT;

    try {
        Files.walkFileTree(path, new SimpleFileVisitor<Path>() {
            @Override
            public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {

                while (CodeIndexer.shouldPauseAdding()) {
                    Singleton.getLogger().info("Pausing parser.");
                    try {
                        Thread.sleep(SLEEPTIME);
                    } catch (InterruptedException ex) {
                    }
                }

                // Convert Path file to unix style that way everything is easier to reason about
                String fileParent = FilenameUtils.separatorsToUnix(file.getParent().toString());
                String fileToString = FilenameUtils.separatorsToUnix(file.toString());
                String fileName = file.getFileName().toString();
                String md5Hash = Values.EMPTYSTRING;

                if (fileParent.endsWith("/.git") || fileParent.contains("/.git/")) {
                    return FileVisitResult.CONTINUE;
                }

                List<String> codeLines;
                try {
                    codeLines = Helpers.readFileLines(fileToString, MAXFILELINEDEPTH);
                } catch (IOException ex) {
                    return FileVisitResult.CONTINUE;
                }

                try {
                    FileInputStream fis = new FileInputStream(new File(fileToString));
                    md5Hash = org.apache.commons.codec.digest.DigestUtils.md5Hex(fis);
                    fis.close();
                } catch (IOException ex) {
                    Singleton.getLogger().warning("Unable to generate MD5 for " + fileToString);
                }

                // is the file minified?
                if (scl.isMinified(codeLines)) {
                    Singleton.getLogger().info("Appears to be minified will not index  " + fileToString);
                    return FileVisitResult.CONTINUE;
                }

                String languageName = scl.languageGuesser(fileName, codeLines);
                String fileLocation = fileToString.replace(fileRepoLocations, Values.EMPTYSTRING)
                        .replace(fileName, Values.EMPTYSTRING);
                String fileLocationFilename = fileToString.replace(fileRepoLocations, Values.EMPTYSTRING);
                String repoLocationRepoNameLocationFilename = fileToString;

                String newString = getBlameFilePath(fileLocationFilename);
                List<CodeOwner> owners;
                if (useSystemGit) {
                    owners = getBlameInfoExternal(codeLines.size(), repoName, fileRepoLocations, newString);
                } else {
                    owners = getBlameInfo(codeLines.size(), repoName, fileRepoLocations, newString);
                }

                String codeOwner = scl.codeOwner(owners);

                // If low memory don't add to the queue, just index it directly
                if (lowMemory) {
                    CodeIndexer.indexDocument(new CodeIndexDocument(repoLocationRepoNameLocationFilename,
                            repoName, fileName, fileLocation, fileLocationFilename, md5Hash, languageName,
                            codeLines.size(), StringUtils.join(codeLines, " "), repoRemoteLocation, codeOwner));
                } else {
                    Singleton.incrementCodeIndexLinesCount(codeLines.size());
                    codeIndexDocumentQueue.add(new CodeIndexDocument(repoLocationRepoNameLocationFilename,
                            repoName, fileName, fileLocation, fileLocationFilename, md5Hash, languageName,
                            codeLines.size(), StringUtils.join(codeLines, " "), repoRemoteLocation, codeOwner));
                }

                fileLocations.add(fileLocationFilename);
                return FileVisitResult.CONTINUE;
            }
        });
    } catch (IOException ex) {
        Singleton.getLogger().warning("ERROR - caught a " + ex.getClass() + " in " + this.getClass()
                + "\n with message: " + ex.getMessage());
    }

    if (existingRepo) {
        CodeSearcher cs = new CodeSearcher();
        List<String> indexLocations = cs.getRepoDocuments(repoName);

        for (String file : indexLocations) {
            if (!fileLocations.contains(file)) {
                Singleton.getLogger().info("Missing from disk, removing from index " + file);
                try {
                    CodeIndexer.deleteByFileLocationFilename(file);
                } catch (IOException ex) {
                    Singleton.getLogger().warning("ERROR - caught a " + ex.getClass() + " in " + this.getClass()
                            + "\n with message: " + ex.getMessage());
                }
            }
        }
    }
}

From source file:org.opencb.cellbase.app.transform.GeneParser.java

public GeneParser(Path geneDirectoryPath, Path genomeSequenceFastaFile, Species species,
        boolean flexibleGTFParsing, CellBaseSerializer serializer) {
    this(null, geneDirectoryPath.resolve("description.txt"), geneDirectoryPath.resolve("xrefs.txt"),
            geneDirectoryPath.resolve("idmapping_selected.tab.gz"),
            geneDirectoryPath.resolve("MotifFeatures.gff.gz"), geneDirectoryPath.resolve("mirna.txt"),
            geneDirectoryPath.getParent().getParent()
                    .resolve("common/expression/allgenes_updown_in_organism_part.tab.gz"),
            geneDirectoryPath.resolve("geneDrug/dgidb.tsv"),
            geneDirectoryPath.resolve("ALL_SOURCES_ALL_FREQUENCIES_diseases_to_genes_to_phenotypes.txt"),
            geneDirectoryPath.resolve("all_gene_disease_associations.txt.gz"), genomeSequenceFastaFile, species,
            flexibleGTFParsing, serializer);
    getGtfFileFromGeneDirectoryPath(geneDirectoryPath);
    getProteinFastaFileFromGeneDirectoryPath(geneDirectoryPath);
    getCDnaFastaFileFromGeneDirectoryPath(geneDirectoryPath);
}

From source file:org.roda.core.storage.fs.FileStorageService.java

@Override
public BinaryVersion createBinaryVersion(StoragePath storagePath, Map<String, String> properties)
        throws RequestNotValidException, NotFoundException, GenericException {
    Path binPath = FSUtils.getEntityPath(basePath, storagePath);

    String id = IdUtils.createUUID();
    Path dataPath = FSUtils.getEntityPath(historyDataPath, storagePath, id);
    Path metadataPath = FSUtils.getBinaryHistoryMetadataPath(historyDataPath, historyMetadataPath, dataPath);

    if (!FSUtils.exists(binPath)) {
        throw new NotFoundException("Binary does not exist: " + binPath);
    }/*w w w  . j av  a  2s.  c  o  m*/

    if (!FSUtils.isFile(binPath)) {
        throw new RequestNotValidException("Not a regular file: " + binPath);
    }

    if (FSUtils.exists(dataPath)) {
        throw new GenericException("Binary version id collided: " + dataPath);
    }

    try {
        // ensuring parent exists
        Path parent = dataPath.getParent();
        if (!FSUtils.exists(parent)) {
            Files.createDirectories(parent);
        }

        // writing file
        Files.copy(binPath, dataPath);

        // Creating metadata
        DefaultBinaryVersion b = new DefaultBinaryVersion();
        b.setId(id);
        b.setProperties(properties);
        b.setCreatedDate(new Date());
        Files.createDirectories(metadataPath.getParent());
        JsonUtils.writeObjectToFile(b, metadataPath);

        return FSUtils.convertPathToBinaryVersion(historyDataPath, historyMetadataPath, dataPath);
    } catch (IOException e) {
        throw new GenericException("Could not create binary", e);
    }

}

From source file:org.eclipse.winery.repository.importing.CSARImporter.java

/**
 * Reads the CSAR from the given inputstream
 * //from   w w w  . ja  v  a 2 s . co  m
 * @param in the inputstream to read from
 * @param errorList the list of errors during the import. Has to be non-null
 * @param overwrite if true: contents of the repo are overwritten
 * 
 * @throws InvalidCSARException if the CSAR is invalid
 */
public void readCSAR(InputStream in, List<String> errors, boolean overwrite, final boolean asyncWPDParsing)
        throws IOException {
    // we have to extract the file to a temporary directory as
    // the .definitions file does not necessarily have to be the first entry in the archive
    Path csarDir = Files.createTempDirectory("winery");

    try (ZipInputStream zis = new ZipInputStream(in)) {
        ZipEntry entry;
        while ((entry = zis.getNextEntry()) != null) {
            if (!entry.isDirectory()) {
                Path targetPath = csarDir.resolve(entry.getName());
                Files.createDirectories(targetPath.getParent());
                Files.copy(zis, targetPath, StandardCopyOption.REPLACE_EXISTING);
            }
        }

        this.importFromDir(csarDir, errors, overwrite, asyncWPDParsing);
        this.importCustomFile(csarDir);
    } catch (Exception e) {
        CSARImporter.logger.debug("Could not import CSAR", e);
        throw e;
    } finally {
        // cleanup: delete all contents of the temporary directory
        FileUtils.forceDelete(csarDir);
    }
}

From source file:de.teamgrit.grit.checking.compile.GccCompileChecker.java

@Override
public CompilerOutput checkProgram(Path pathToProgramFile, Path outputFolder, String compilerName,
        List<String> compilerFlags)
        throws FileNotFoundException, BadCompilerSpecifiedException, BadFlagException {

    // First we build the command to invoke the compiler. This consists of
    // the compiler executable, the path of the
    // file to compile and compiler flags. So for example we call:
    List<String> compilerInvocation = createCompilerInvocation(pathToProgramFile, compilerName, compilerFlags);
    // Now we build a launchable process from the given parameters and set
    // the working directory.
    Process compilerProcess = null;

    try {//from  w w  w . j av  a 2  s .  com
        ProcessBuilder compilerProcessBuilder = new ProcessBuilder(compilerInvocation);
        // make sure the compiler stays in its directory.
        if (Files.isDirectory(pathToProgramFile)) {
            compilerProcessBuilder.directory(pathToProgramFile.toFile());
        } else {
            compilerProcessBuilder.directory(pathToProgramFile.getParent().toFile());
        }
        compilerProcess = compilerProcessBuilder.start();
    } catch (IOException e) {
        // If we cannot call the compiler we return a CompilerOutput
        // initialized with false, false, indicating
        // that the compiler wasn't invoked properly and that there was no
        // clean Compile.
        CompilerOutput compilerInvokeError = new CompilerOutput();
        compilerInvokeError.setClean(false);
        compilerInvokeError.setCompilerInvoked(false);
        LOGGER.severe("Couldn't launch GCC. Check whether it's in the system's PATH");
        return compilerInvokeError;
    }

    // Now we read compiler output. If everything is ok gcc reports
    // nothing at all.
    InputStream compilerOutputStream = compilerProcess.getErrorStream();
    InputStreamReader compilerStreamReader = new InputStreamReader(compilerOutputStream);
    BufferedReader compilerOutputBuffer = new BufferedReader(compilerStreamReader);
    String line;

    CompilerOutput compilerOutput = new CompilerOutput();
    compilerOutput.setCompilerInvoked(true);

    List<String> compilerOutputLines = new LinkedList<>();

    try {
        while ((line = compilerOutputBuffer.readLine()) != null) {
            compilerOutputLines.add(line);
        }

        compilerOutputStream.close();
        compilerStreamReader.close();
        compilerOutputBuffer.close();
        compilerProcess.destroy();
    } catch (IOException e) {
        // Reading might go wrong here if gcc should unexpectedly terminate
        LOGGER.severe("Error while reading from compiler stream.");
        compilerOutput.setClean(false);
        compilerOutput.setCompileStreamBroken(true);
        return compilerOutput;
    }

    if (compilerOutputLines.size() == 0) {
        compilerOutput.setClean(true);
    }

    compilerOutput = splitCompilerOutput(compilerOutputLines, compilerOutput);

    // delete all .o and .exe files
    // these are output files generated by gcc which we won't need
    // anymore
    File[] candidateToplevelFiles = pathToProgramFile.toFile().listFiles();
    for (File candidateFile : candidateToplevelFiles) {
        if (!candidateFile.isDirectory()) {
            String extension = FilenameUtils.getExtension(candidateFile.toString());
            if (extension.matches("([Oo]|([Ee][Xx][Ee]))")) {
                // We only pass the filename, since gcc will be
                // confined to the dir the file is located in.
                candidateFile.delete();
            }
        }

    }

    return compilerOutput;
}