Example usage for java.nio.file Path resolve

List of usage examples for java.nio.file Path resolve

Introduction

In this page you can find the example usage for java.nio.file Path resolve.

Prototype

default Path resolve(String other) 

Source Link

Document

Converts a given path string to a Path and resolves it against this Path in exactly the manner specified by the #resolve(Path) resolve method.

Usage

From source file:com.spectralogic.ds3client.helpers.FileObjectPutter_Test.java

@Test
public void testRelativeSymlink() throws IOException, URISyntaxException {
    assumeFalse(Platform.isWindows());// w ww.  j  a  v a2 s.c om
    final Path tempDir = Files.createTempDirectory("ds3_file_object_rel_test_");
    final Path tempPath = Files.createTempFile(tempDir, "temp_", ".txt");

    try {
        try (final SeekableByteChannel channel = Files.newByteChannel(tempPath, StandardOpenOption.CREATE,
                StandardOpenOption.TRUNCATE_EXISTING, StandardOpenOption.WRITE)) {
            channel.write(ByteBuffer.wrap(testData));
        }

        final Path symLinkPath = tempDir.resolve("sym_" + tempPath.getFileName().toString());
        final Path relPath = Paths.get("..", getParentDir(tempPath), tempPath.getFileName().toString());

        LOG.info("Creating symlink from " + symLinkPath.toString() + " to " + relPath.toString());

        Files.createSymbolicLink(symLinkPath, relPath);
        getFileWithPutter(tempDir, symLinkPath);

    } finally {
        Files.deleteIfExists(tempPath);
        Files.deleteIfExists(tempDir);
    }
}

From source file:org.opentestsystem.ap.ivs.service.ValidationUtility.java

/**
 * Map an item's local glossary to the validation structure.  The glossary lives in the 'Items' folder.  It sits
 * sibling to other glossaries and items.  Stimulus live in the 'Stimuli' folder.  The item context passed in can be
 * either an item or a stimulus.  The glossary for it is what gets mapped to the validation structure.
 *
 * @param itemContext  An item or stimulus context.
 * @param validationRootChild The root folder of the validation structure.
 * @return/*from  ww w  . j  a v  a  2s  .  co m*/
 */
public Path mapGlossaryToValidationStructure(final ItemContext itemContext, final Path validationRootChild) {
    Path glossaryValidationRepoPath = null;

    if (itemContext != null) {
        final Path itemGlossaryFilePath = itemContext.getLocalGlossaryFilePath();

        if (itemGlossaryFilePath.toFile().exists()) {

            final String glossaryId = RepositoryUtil.getGlossaryId(itemContext.getItemId());

            final String baseName = mapItemFolderName(glossaryId);

            final Path itemsPath = validationRootChild.resolve(ITEMS_DIR);
            glossaryValidationRepoPath = itemsPath.resolve(baseName);

            final Path glossaryValidationFilePath = glossaryValidationRepoPath.resolve(mapFileName(glossaryId));
            final Path glossaryValidationAdjustedFilePath = glossaryValidationRepoPath
                    .resolve(mapFileName(baseName));

            try {
                // copy the item's glossary folder to the local glossary repository folder
                FileUtils.copyDirectory(itemContext.getLocalGlossaryFolderPath().toFile(),
                        glossaryValidationRepoPath.toFile());

                // confirm the glossary's SAAIF file exists
                if (glossaryValidationFilePath.toFile().exists()) {
                    glossaryValidationFilePath.toFile().renameTo(glossaryValidationAdjustedFilePath.toFile());
                }
            } catch (IOException e) {
                throw new SystemException(
                        "Error mapping glossary " + glossaryId + " to the validation structure", e);
            }
        }
    }

    return glossaryValidationRepoPath;
}

From source file:com.yahoo.maven.visitor.VisitorGenerator.java

public void generate() throws IOException {
    for (Visitor visitor : getVisitors()) {
        String name = visitor.getVisitedName();
        int packageTail = name.lastIndexOf(".");
        String aPackage = packageTail == -1 ? null : name.substring(0, packageTail);
        String disjunctName = packageTail == -1 ? name : name.substring(packageTail + 1, name.length());
        String className = capitalizer.capitalize(disjunctName);
        String dir = aPackage == null ? ""
                : StringUtils.replace(aPackage, ".", FileSystems.getDefault().getSeparator());
        List<TypeParameterContext> typeParameterContexts = new ArrayList<>();
        Set<String> typeParameterNames = new LinkedHashSet<>();
        if (visitor.getTypeParameters() != null) {
            typeParameterContexts.addAll(Arrays.asList(visitor.getTypeParameters()));
            for (TypeParameter typeParameter : visitor.getTypeParameters()) {
                typeParameterNames.add(typeParameter.getName());
            }/* w  ww . java  2 s.co m*/
        }
        List<DisjunctContext> disjuncts = new ArrayList<>();
        for (Disjunction disjunction : visitor.getDisjunctions()) {
            List<ParameterContext> parameterContexts = new ArrayList<>();
            if (disjunction.parameters != null) {
                for (Parameter parameter : disjunction.parameters) {
                    parameterContexts.add(new ParameterContext() {
                        @Override
                        public String getType() {
                            return parameter.type;
                        }

                        @Override
                        public String getName() {
                            return parameter.name;
                        }

                        @Override
                        public String getHashExpression() {
                            switch (getType()) {
                            case "boolean":
                                return "(" + getName() + " ? 1 : 0)";
                            case "char":
                            case "byte":
                            case "short":
                                return "(int) " + getName();
                            case "int":
                                return getName();
                            case "long":
                                return "(int) (" + getName() + " ^ (" + getName() + " >>> 32))";
                            case "float":
                                return "(" + getName() + " != +0.0f ? Float.floatToIntBits(" + getName()
                                        + ") : 0)";
                            case "double":
                                return "(int) (Double.doubleToLongBits(" + getName()
                                        + ") ^ (Double.doubleToLongBits(" + getName() + ") >>> 32))";
                            default:
                                return "(" + getName() + " != null ? " + getName() + ".hashCode() : 0)";
                            }
                        }
                    });
                }
            }
            disjuncts.add(new DisjunctContext() {
                @Override
                public String getMethodName() {
                    return disjunction.name;
                }

                @Override
                public List<ParameterContext> getParameters() {
                    return parameterContexts.isEmpty() ? null : parameterContexts;
                }

                @Override
                public boolean hasAsMethod() {
                    return parameterContexts.size() == 1
                            && !primitives.contains(parameterContexts.get(0).getType());
                }
            });
        }
        class AbstractBaseContext implements BaseContext {
            @Override
            public String getPackage() {
                return aPackage;
            }

            @Override
            public String getVisitedClassName() {
                return className;
            }

            @Override
            public List<TypeParameterContext> getTypeParameters() {
                return typeParameterContexts.isEmpty() ? null : typeParameterContexts;
            }

            @Override
            public List<DisjunctContext> getDisjuncts() {
                return disjuncts.isEmpty() ? null : disjuncts;
            }
        }
        Path outputFolder = getOutputDirectory().resolve(dir);
        File outputFolderAsFile = outputFolder.toFile();
        if (!outputFolderAsFile.mkdirs() && !outputFolderAsFile.exists()) {
            throw new IOException("Unable to make directory: " + outputFolderAsFile.getAbsolutePath());
        }
        try (Writer visitedWriter = Files.newBufferedWriter(outputFolder.resolve(className + ".java"))) {
            class ThisVisitedContext extends AbstractBaseContext implements VisitedContext {
            }
            visitedTemplate.merge(visitedWriter, new ThisVisitedContext());
        }
        try (Writer visitorWriter = Files.newBufferedWriter(outputFolder.resolve(className + "Visitor.java"))) {
            class ThisVisitorContext extends AbstractBaseContext implements VisitorContext {
            }
            visitorTemplate.merge(visitorWriter, new ThisVisitorContext());
        }
        try (Writer visitorWriter = Files
                .newBufferedWriter(outputFolder.resolve("Defaulting" + className + "Visitor.java"))) {
            class ThisDefaultingVisitorContext extends AbstractBaseContext implements DefaultingVisitorContext {
            }
            defaultingVisitorTemplate.merge(visitorWriter, new ThisDefaultingVisitorContext());
        }
        try (Writer visitorWriter = Files
                .newBufferedWriter(outputFolder.resolve("Identity" + className + "Visitor.java"))) {
            class ThisIdentityVisitorContext extends AbstractBaseContext implements IdentityVisitorContext {
            }
            identityVisitorTemplate.merge(visitorWriter, new ThisIdentityVisitorContext());
        }
        try (Writer visitorWriter = Files
                .newBufferedWriter(outputFolder.resolve("DefaultingIdentity" + className + "Visitor.java"))) {
            class ThisIdentityVisitorContext extends AbstractBaseContext
                    implements IdentityVisitorContext, DefaultingVisitorContext {
            }
            defaultingIdentityVisitorTemplate.merge(visitorWriter, new ThisIdentityVisitorContext());
        }
    }
}

From source file:codes.writeonce.maven.plugins.soy.CompileMojo.java

private void generateJs(List<Path> soyFiles, SoyFileSet soyFileSet, SoyMsgBundle soyMsgBundle, Path outputPath)
        throws IOException {

    final List<String> compiledSources = soyFileSet
            .compileToJsSrc(firstNonNull(jsSrcOptions, new SoyJsSrcOptions()), soyMsgBundle);

    final Iterator<Path> soyFilePathIt = soyFiles.iterator();

    for (final String compiledSource : compiledSources) {

        final Path targetPath = outputPath
                .resolve(Utils.changeSuffix(soyFilePathIt.next(), SOY_EXTENSION, JS_EXTENSION));

        Files.createDirectories(targetPath.getParent());

        try (FileOutputStream out = new FileOutputStream(targetPath.toFile());
                OutputStreamWriter writer = new OutputStreamWriter(out, jsOutputCharsetName)) {
            writer.write(compiledSource);
        }/* w  ww. j a va2s . c o  m*/
    }
}

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

private Path getTestFilePath(String extension) {
    Path testDataDirectory = TestDataHelper.getTestDataDirectory(this.getClass());
    return testDataDirectory.resolve("output" + extension);
}

From source file:com.google.cloud.tools.managedcloudsdk.install.TarGzExtractorProvider.java

@Override
public void extract(Path archive, Path destination, ProgressListener progressListener) throws IOException {

    progressListener.start("Extracting archive: " + archive.getFileName(), ProgressListener.UNKNOWN);

    String canonicalDestination = destination.toFile().getCanonicalPath();

    GzipCompressorInputStream gzipIn = new GzipCompressorInputStream(Files.newInputStream(archive));
    try (TarArchiveInputStream in = new TarArchiveInputStream(gzipIn)) {
        TarArchiveEntry entry;/* w w w.jav  a2 s . com*/
        while ((entry = in.getNextTarEntry()) != null) {
            Path entryTarget = destination.resolve(entry.getName());

            String canonicalTarget = entryTarget.toFile().getCanonicalPath();
            if (!canonicalTarget.startsWith(canonicalDestination + File.separator)) {
                throw new IOException("Blocked unzipping files outside destination: " + entry.getName());
            }

            progressListener.update(1);
            logger.fine(entryTarget.toString());

            if (entry.isDirectory()) {
                if (!Files.exists(entryTarget)) {
                    Files.createDirectories(entryTarget);
                }
            } else if (entry.isFile()) {
                if (!Files.exists(entryTarget.getParent())) {
                    Files.createDirectories(entryTarget.getParent());
                }
                try (OutputStream out = new BufferedOutputStream(Files.newOutputStream(entryTarget))) {
                    IOUtils.copy(in, out);
                    PosixFileAttributeView attributeView = Files.getFileAttributeView(entryTarget,
                            PosixFileAttributeView.class);
                    if (attributeView != null) {
                        attributeView.setPermissions(PosixUtil.getPosixFilePermissions(entry.getMode()));
                    }
                }
            } else {
                // we don't know what kind of entry this is (we only process directories and files).
                logger.warning("Skipping entry (unknown type): " + entry.getName());
            }
        }
        progressListener.done();
    }
}

From source file:de.prozesskraft.pkraft.Manager.java

/**
 * erstellt fuer jeden running step einen watchkey
 * es soll jedes stepverzeichnis mit dem status 'working' observiert werden bis das file ".exit" erscheint
 * @param process/*  w  w w  .  ja va  2 s  .co  m*/
 * @throws IOException 
 */
private static void createWatchKeysForAllRunningSteps(Process process) throws IOException {
    // diesen Thread ablegen, damit er vom zyklischen thread gekillt werden kann
    watcherThread = Thread.currentThread();

    // einen neuen map erzeugen fuer die watchKeys
    keys = new HashMap<WatchKey, Path>();

    WatchService watcher = FileSystems.getDefault().newWatchService();

    // Anlegen des WatchKeys fuer den Prozess (falls er gestoppt wird, erfolgt die Komunikation mit diesem manager ueber das binaerfile)
    Path processDir = Paths.get(process.getRootdir());
    System.err.println("info: creating a watchkey for the process path " + process.getRootdir());
    WatchKey keyProcess = processDir.register(watcher, ENTRY_MODIFY);
    keys.put(keyProcess, processDir);

    // Anlegen der WatchKeys fuer jeden laufenden Step
    for (Step actStep : process.getStep()) {
        if (actStep.getStatus().equals("working")) {
            Path stepDir = Paths.get(actStep.getAbsdir());
            try {
                System.err.println("info: step " + actStep.getName()
                        + " is working -> creating a watchkey for its path " + actStep.getAbsdir());
                System.err.println("debug: creating...");
                WatchKey key = stepDir.register(watcher, ENTRY_CREATE);
                System.err.println("debug: creating...done. putting to the map");
                keys.put(key, stepDir);
                System.err.println("debug: creating...done. putting to the map...done");
            } catch (IOException e) {
                System.err.println(e);
            } catch (Exception e) {
                System.err.println(e);
            }

            java.io.File stepDirExitFile = new java.io.File(actStep.getAbsdir() + "/.exit");
            java.io.File stepDirStatusFile = new java.io.File(actStep.getAbsdir() + "/.status");

            // falls die datei bereits existiert, wird sofort erneut der Prozess weitergeschoben
            // dies ist dann der fall, wenn ein step gestartet wurde, und danach der manager neu gestartet wurde
            if (stepDirExitFile.exists()) {
                System.err.println("info: .exit file already exists -> shortcutting to pushing the process");

                // alle keys loeschen
                keys = null;

                // den prozess weiter pushen
                pushProcessAsFarAsPossible(process.getRootdir() + "/process.pmb", false);
            }
            // falls der step ein process ist, bibts dort kein .exit file sondern ein .status file
            else if (stepDirStatusFile.exists()) {
                System.err.println("info: .status file already exists.");
                try {
                    java.util.List<String> statusInhalt = Files.readAllLines(stepDirStatusFile.toPath(),
                            Charset.defaultCharset());
                    if (statusInhalt.size() > 0) {
                        String firstLine = statusInhalt.get(0);
                        System.err.println("info: status changed to: " + firstLine);

                        System.err.println("info: .status file contains status " + firstLine);
                        // wenn ein finaler status, dann soll manager aufgeweckt werden
                        if (firstLine.equals("error") || firstLine.equals("finished")) {
                            System.err.println("info: --> shortcutting to pushing process");
                            // alle keys loeschen
                            keys = null;

                            // den prozess weiter pushen
                            pushProcessAsFarAsPossible(process.getRootdir() + "/process.pmb", false);
                        }
                    }
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    System.err.println(
                            "IOException: trying to read file: " + stepDirStatusFile.getAbsolutePath());
                    e.printStackTrace();
                } catch (ExceptionInInitializerError e) {
                    System.err.println("ExceptionInInitializerError: trying to read file: "
                            + stepDirStatusFile.getAbsolutePath());
                    e.printStackTrace();
                }
            }

        }
    }

    process.log("info", "now into the watchloop");

    // warten auf ein Signal von einem WatchKey
    for (;;) {

        WatchKey key;
        try {
            key = watcher.take();
        } catch (InterruptedException e) {
            System.err.println(new Timestamp(System.currentTimeMillis())
                    + ": ---- watcher thread: interrupted! returning to alternativer Thread");
            return;
        }

        Path dir = keys.get(key);
        if (dir == null) {
            System.err.println("WatchKey not recognized!!");
            continue;
        }

        for (WatchEvent<?> event : key.pollEvents()) {
            //            System.err.println("debug: poll event " + event);

            WatchEvent.Kind kind = event.kind();

            WatchEvent<Path> ev = (WatchEvent<Path>) event;
            Path name = ev.context();
            // dieses logging fuehrt zur aenderung von stderr.txt und .log, was wiederum ein ENTRY_MODIFY ausloest etc. endlosschleife bis platte volllaeuft
            //            System.err.println("debug: poll context " + name);
            Path child = dir.resolve(name);
            //            System.err.println("debug: poll child " + child);

            if (kind == ENTRY_CREATE) {
                if (child.endsWith(".exit")) {
                    System.err.println("info: waking up, because file created: " + child.toString());

                    // alle keys loeschen
                    keys = null;

                    // den prozess weiter pushen
                    pushProcessAsFarAsPossible(process.getRootdir() + "/process.pmb", false);
                }
            }
            if ((kind == ENTRY_MODIFY) && (child.endsWith("process.pmb"))) {
                //               System.err.println("info: waking up, because process binary file has been modified: " + child.toString());

                // alle keys loeschen
                keys = null;

                // den prozess weiter pushen
                pushProcessAsFarAsPossible(process.getRootdir() + "/process.pmb", false);
            }
            if (kind == ENTRY_CREATE || kind == ENTRY_MODIFY) {
                if (child.endsWith(".status")) {
                    try {
                        java.util.List<String> statusInhalt = Files.readAllLines(child,
                                Charset.defaultCharset());
                        if (statusInhalt.size() > 0) {
                            String firstLine = statusInhalt.get(0);
                            System.err.println("info: status changed to: " + firstLine);

                            // wenn ein finaler status, dann soll manager aufgeweckt werden
                            if (firstLine.equals("error") || firstLine.equals("finished")) {
                                System.err.println("info: waking up, because status changed to: " + firstLine);
                                // alle keys loeschen
                                keys = null;

                                // den prozess weiter pushen
                                pushProcessAsFarAsPossible(process.getRootdir() + "/process.pmb", false);
                            }
                        }
                    } catch (IOException e) {
                        // TODO Auto-generated catch block
                        System.err.println("IOException: trying to read file: " + child.toString());
                        e.printStackTrace();
                    } catch (ExceptionInInitializerError e) {
                        System.err.println(
                                "ExceptionInInitializerError: trying to read file: " + child.toString());
                        e.printStackTrace();
                    }

                }
            }

            // reset the triggered key
            key.reset();
        }
    }
}

From source file:dk.dma.msinm.common.repo.RepositoryService.java

/**
 * Creates two levels of sub-folders within the {@code rootFolder} based on
 * a MD5 hash of the {@code target}./*from   w ww. j  ava 2s .com*/
 * If the sub-folder does not exist, it is created.
 *
 * @param rootFolder the root folder within the repository root
 * @param target the target name used for the hash
 * @param includeTarget whether to create a sub-folder for the target or not
 * @return the sub-folder associated with the target
 */
public Path getHashedSubfolder(String rootFolder, String target, boolean includeTarget) throws IOException {
    byte[] bytes = target.getBytes("utf-8");

    // MD5 hash the ID
    MessageDigest md = null;
    try {
        md = MessageDigest.getInstance("MD5");
    } catch (NoSuchAlgorithmException e) {
        throw new IOException("This should never happen");
    }
    md.update(bytes);
    bytes = md.digest();
    String hash = String.valueOf(Integer.toHexString(bytes[0] & 0xff));
    while (hash.length() < 2) {
        hash = "0" + hash;
    }

    Path folder = getRepoRoot();

    // Add the root folder
    if (StringUtils.isNotBlank(rootFolder)) {
        folder = folder.resolve(rootFolder);
    }

    // Add two hashed sub-folder levels
    folder = folder.resolve(hash.substring(0, 1)).resolve(hash.substring(0, 2));

    // Check if we should create a sub-folder for the target as well
    if (includeTarget) {
        folder = folder.resolve(target);
    }

    // Create the folder if it does not exist
    if (!Files.exists(folder)) {
        Files.createDirectories(folder);
    }
    return folder;
}

From source file:edu.cornell.mannlib.vitro.webapp.servlet.setup.UpdateKnowledgeBase.java

private Path createDirectory(Path parent, String... children) throws IOException {
    Path dir = parent;
    for (String child : children) {
        dir = dir.resolve(child);
    }/*from   w  w  w.ja va2 s. c  o m*/
    Files.createDirectories(dir);
    return dir;
}

From source file:edu.cornell.mannlib.vitro.webapp.servlet.setup.UpdateKnowledgeBase.java

private Path getFilePath(Path parent, String... children) throws IOException {
    Path path = parent;
    for (String child : children) {
        path = path.resolve(child);
    }//from  ww  w. jav  a  2  s  . c om
    return path;
}