Example usage for java.nio.file Path relativize

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

Introduction

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

Prototype

Path relativize(Path other);

Source Link

Document

Constructs a relative path between this path and a given path.

Usage

From source file:org.bonitasoft.web.designer.controller.export.ZipperTest.java

private void expectSameDirContent(final Path actual, final Path expected) throws IOException {
    Files.walkFileTree(actual, new SimpleFileVisitor<Path>() {

        @Override// ww w  .  java  2  s.  c  o  m
        public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
            Path expectedFile = expected.resolve(actual.relativize(file));
            assertThat(expectedFile.toFile()).exists();
            assertThat(expectedFile.toFile()).hasContent(new String(Files.readAllBytes(expectedFile)));
            return FileVisitResult.CONTINUE;
        }

        @Override
        public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException {
            Path expectedDir = expected.resolve(actual.relativize(dir));
            assertThat(expectedDir.toFile()).exists();
            return FileVisitResult.CONTINUE;
        }

    });
}

From source file:com.streamsets.datacollector.bundles.content.SdcInfoContentGenerator.java

private void printFile(Path path, Path prefix, String type, BundleWriter writer) throws IOException {
    writer.write(type);/*from w w  w.j av a2 s . c  o m*/
    writer.write(";");
    writer.write(getOrWriteError(() -> prefix.relativize(path).toString()));
    writer.write(";");
    writer.write(getOrWriteError(() -> Files.getOwner(path).getName()));
    writer.write(";");
    if ("F".equals(type)) {
        writer.write(getOrWriteError(() -> String.valueOf(Files.size(path))));
    }
    writer.write(";");
    writer.write(getOrWriteError(() -> StringUtils.join(Files.getPosixFilePermissions(path), ",")));
    writer.write("\n");
}

From source file:org.dataconservancy.packaging.tool.impl.GeneralPackageDescriptionCreator.java

private void populate(FileContext cxt, Rule rule, Map<String, PackageArtifact> artifacts) {

    List<Mapping> mappings = rule.getMappings(cxt);

    for (Mapping mapping : mappings) {

        /* We are using file URI as artifact IDs, unless multiple mappings */
        URIBuilder urib = new URIBuilder(cxt.getFile().toURI());
        //String id = cxt.getFile().toURI().toString();

        /*/* ww  w .j  av a2  s  . co m*/
         * If multiple mappings implicated by this file, then make sure
         * they're differentiated
         */
        if (mappings.size() > 1) {
            String specifier = mapping.getSpecifier();
            if (specifier != null) {
                urib.setFragment(specifier);
            }
        }

        URI uri = null;
        try {
            uri = urib.build();
        } catch (URISyntaxException e) {

        }
        String id = uri.toString();

        PackageArtifact artifact = new PackageArtifact();
        artifacts.put(id, artifact);
        artifact.setId(id);
        artifact.setIgnored(cxt.isIgnored());
        //we need to relativize against the content root if one exists, not the supplied root artifact dir
        if (cxt.getRoot().getParentFile() != null) {
            Path rootPath = Paths.get(cxt.getRoot().getParentFile().getPath());
            Path filePath = Paths.get(cxt.getFile().getPath());
            artifact.setArtifactRef(String.valueOf(rootPath.relativize(filePath)));
        } else {
            Path filePath = Paths.get(cxt.getFile().getPath());
            artifact.setArtifactRef(String.valueOf(filePath));
        }

        if (uri.getFragment() != null) {
            artifact.getArtifactRef().setFragment(uri.getFragment());
        }
        /*
         * if file is a normal file, set the isByteStream flag to true on
         * PackageArtifact
         */

        if (cxt.getFile().isFile()) {
            artifact.setByteStream(true);
        }

        artifact.setType(mapping.getType().getValue());

        if (mapping.getType().isByteStream() != null) {
            artifact.setByteStream(mapping.getType().isByteStream());
        } else {
            artifact.setByteStream(cxt.getFile().isFile());
        }

        for (Map.Entry<String, List<String>> entry : mapping.getProperties().entrySet()) {
            Set<String> valueSet = new HashSet<>(entry.getValue());
            artifact.setSimplePropertyValues(entry.getKey(), valueSet);
        }
        /*
         * Since we use file URI as artifact IDs (with optional specifier as
         * URI fragment), we just need to use the relationship's target
         * file's URI as the relationship target, and we're done!.
         */
        List<PackageRelationship> rels = new ArrayList<>();

        for (Map.Entry<String, Set<URI>> rel : mapping.getRelationships().entrySet()) {
            Set<String> relTargets = new HashSet<>();
            for (URI target : rel.getValue()) {
                relTargets.add(target.toString());
            }

            rels.add(new PackageRelationship(rel.getKey(), true, relTargets));

        }
        artifact.setRelationships(rels);
    }
}

From source file:at.tfr.securefs.xnio.MessageHandlerImpl.java

@Override
public void handleMessage(String json, MessageSender messageSender) throws IOException {

    log.debug("handleMessage: " + json);
    final Message message = objectMapper.readValue(json, Message.class);

    Path path = configuration.getBasePath().resolve(message.getPath());
    if (!path.relativize(configuration.getBasePath()).toString().equals("..")) {
        throw new SecurityException("invalid path spec: " + message.getPath());
    }/*from w w  w .  j ava  2 s. c o m*/

    try {
        final String uniqueKey = message.getUniqueKey();
        // find the Channel for this data stream:
        StreamInfo<ChannelPipe<StreamSourceChannel, StreamSinkChannel>> info = activeStreams.getStreams()
                .get(uniqueKey);

        if (message.getType() == MessageType.OPEN && info != null) {
            log.warn("illegal state on Open stream: " + message);
            IoUtils.safeClose(info.getStream().getRightSide());
            messageSender.send(new Message(MessageType.ERROR, message.getPath()).key(uniqueKey));
        }

        switch (message.getType()) {
        case ERROR:
            log.info("error from Client: " + json);
        case CLOSE: {
            if (info != null) {
                IoUtils.safeClose(info.getStream().getRightSide());
            }
        }
            break;

        case OPEN: {
            switch (message.getSubType()) {
            case READ: {
                final InputStream is = Files.newInputStream(path, StandardOpenOption.READ);
                final InputStream cis = new CipherInputStream(is, getCipher(message, Cipher.DECRYPT_MODE));

                final ChannelPipe<StreamSourceChannel, StreamSinkChannel> pipe = xnioWorker
                        .createHalfDuplexPipe();
                pipe.getLeftSide().getReadSetter().set(new SecureChannelWriterBase(message) {
                    @Override
                    protected void write(Message message) {
                        try {
                            messageSender.send(message);
                        } catch (Exception e) {
                            log.warn("cannot write message=" + message + " : " + e, e);
                        }
                    }
                });
                pipe.getLeftSide().getCloseSetter().set(new ChannelListener<StreamSourceChannel>() {

                    @Override
                    public void handleEvent(StreamSourceChannel channel) {
                        activeStreams.getStreams().remove(uniqueKey);
                        messageSender.send(new Message(MessageType.CLOSE, message.getPath()).key(uniqueKey));
                    }
                });
                pipe.getRightSide().getWriteSetter().set(new ChannelListener<StreamSinkChannel>() {
                    private byte[] bytes = new byte[Constants.BUFFER_SIZE];

                    @Override
                    public void handleEvent(StreamSinkChannel channel) {
                        try {
                            int count = 0;
                            while ((count = cis.read(bytes, 0, bytes.length)) > 0) {
                                if (count > 0) {
                                    Channels.writeBlocking(pipe.getRightSide(),
                                            ByteBuffer.wrap(bytes, 0, count));
                                }
                                if (count < 0) {
                                    pipe.getRightSide().close();
                                } else {
                                    channel.resumeWrites();
                                }
                            }
                        } catch (Exception e) {
                            log.warn("cannot read from cypher: " + e, e);
                            IoUtils.safeClose(channel);
                        }
                    }
                });

                activeStreams.getStreams().put(uniqueKey,
                        new StreamInfo<ChannelPipe<StreamSourceChannel, StreamSinkChannel>>(pipe,
                                message.getPath()));

                // start sending data:
                pipe.getLeftSide().resumeReads();
                pipe.getRightSide().resumeWrites();
            }
                break;

            case WRITE: {
                Files.createDirectories(path.getParent());
                OutputStream os = Files.newOutputStream(path, StandardOpenOption.CREATE,
                        StandardOpenOption.TRUNCATE_EXISTING, StandardOpenOption.WRITE);
                OutputStream cos = new CipherOutputStream(os, getCipher(message, Cipher.ENCRYPT_MODE));

                ChannelPipe<StreamSourceChannel, StreamSinkChannel> pipe = xnioWorker.createHalfDuplexPipe();

                pipe.getLeftSide().getReadSetter().set(new SecureChannelReaderBase() {

                    @Override
                    public void handleEvent(StreamSourceChannel channel) {
                        readChannel(message, cos, pipe, channel);
                    }
                });

                pipe.getLeftSide().getCloseSetter().set(new SecureChannelReaderBase() {
                    @Override
                    public void handleEvent(StreamSourceChannel channel) {
                        try {
                            cos.close();
                            activeStreams.getStreams().remove(pipe.toString());
                            messageSender
                                    .send(new Message(MessageType.CLOSE, message.getPath()).key(uniqueKey));
                            log.info("closed channel: " + pipe.toString());
                        } catch (IOException e) {
                            log.warn("cannot close stream: message=" + message + " : " + e, e);
                        }
                    }
                });
                activeStreams.getStreams().put(uniqueKey,
                        new StreamInfo<ChannelPipe<StreamSourceChannel, StreamSinkChannel>>(pipe,
                                message.getPath()));

                // start receiving data:
                pipe.getLeftSide().resumeReads();
            }
                break;

            default:
                messageSender.send(new Message(MessageType.ERROR, message.getPath()).key(uniqueKey));
                break;

            }
        }
            break;

        case DATA: {
            if (info != null) {
                Channels.writeBlocking(info.getStream().getRightSide(), ByteBuffer.wrap(message.getBytes()));
            } else {
                messageSender.send(new Message(MessageType.ERROR, message.getPath()).key(uniqueKey));
            }
        }
            break;
        }

    } catch (IOException e) {
        log.warn("cannot handle message: " + message + " : " + e, e);
        throw e;
    } catch (Exception e) {
        log.warn("cannot handle message: " + message + " : " + e, e);
        throw new IOException("cannot handle message: " + message + " : " + e, e);
    }
}

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

protected void compressFile(Path root, Path file, ArchiveOutputStream archiveOutputStream) throws IOException {
    try (InputStream inputStream = newInputStream(file)) {
        final long size = size(file);
        final byte[] content = new byte[(int) size];
        final String relativePath = root.relativize(file).toString();

        logger.debug("writting " + relativePath + " path in the archive output stream");

        ArchiveEntry entry = createArchiveEntry(relativePath, size, content);
        archiveOutputStream.putArchiveEntry(entry);
        IOUtils.copy(inputStream, archiveOutputStream); //archiveOutputStream.write(content);
        archiveOutputStream.closeArchiveEntry();
    }/* ww w  . j a v a2 s  .c o m*/
}

From source file:de.fu_berlin.inf.dpp.netbeans.ListenerForDocumentSwap.java

private void addListenerToCurrentlySelectedDocument(DataObject a) {

    DataObject thisDataObj = a;/*ww w  .  j a  v a  2  s .  com*/
    EditorCookie thisCurrentEditorCookie = thisDataObj.getLookup().lookup(EditorCookie.class);

    if (thisCurrentEditorCookie == null) {

        return;

    }
    Document thisCDoc = thisCurrentEditorCookie.getDocument();

    if (thisCDoc == null) {
        return;
    }

    thisCurrentFileObject = thisDataObj.getPrimaryFile();
    String fileObjectLocation = thisCurrentFileObject.getPath();
    currentProject = FileOwnerQuery.getOwner(thisCurrentFileObject);

    newDocument = thisCDoc;

    /*
     * Remove the DocumentListener from the old file and/or
     * set a listener on the new one
     */
    if (oldDocument != null && !(oldDocument.equals(newDocument))) {

        oldDocument.removeDocumentListener(currentListenerForOutgoingDocumentModification);
        currentListenerForOutgoingDocumentModification = null;
        oldDocument = newDocument;
    } else {
        if (oldDocument == null) {

            oldDocument = newDocument;

        } else {

            removeInitialPropertyChangedListener();
            return;
        }
    }
    removeInitialPropertyChangedListener();
    addDocumentFilterAndListener();

    /*
     * Get the relative and absolut path of the current file
     * Get the absolute path of the filecontaining project
     */
    FileObject root = currentProject.getProjectDirectory();
    String pathOfBase = root.getPath();
    Path absolutePathOfFile = Paths.get(fileObjectLocation);
    Path pathBase = Paths.get(pathOfBase);
    relativePathToFile = pathBase.relativize(absolutePathOfFile);
    editorManager.setRelativePathOfCurrentFile(relativePathToFile);
    editorManager.setAbsolutePathForCurrentProject(pathBase);
    editorManager.setCurrentProject(currentProject);
}

From source file:org.cryptomator.ui.model.Vault.java

public Binding<String> displayablePath() {
    Path homeDir = Paths.get(SystemUtils.USER_HOME);
    return EasyBind.map(path, p -> {
        if (p.startsWith(homeDir)) {
            Path relativePath = homeDir.relativize(p);
            String homePrefix = SystemUtils.IS_OS_WINDOWS ? "~\\" : "~/";
            return homePrefix + relativePath.toString();
        } else {// w w  w. j a  v  a  2 s . c  o  m
            return path.getValue().toString();
        }
    });
}

From source file:org.eclipse.che.selenium.core.client.TestGitHubRepository.java

/**
 * Creates file in GitHub repository in the specified {@code branch}.
 *
 * @param pathToRootContentDirectory path to the root directory of file locally
 * @param pathToFile path to file locally
 * @param branch name of the target branch
 * @throws IOException//  w  w  w .ja v  a 2s  . c o m
 */
private void createFile(Path pathToRootContentDirectory, Path pathToFile, String branch) throws IOException {
    byte[] contentBytes = Files.readAllBytes(pathToFile);
    String relativePath = pathToRootContentDirectory.relativize(pathToFile).toString();
    String commitMessage = String.format("Add file %s", relativePath);

    try {
        ghRepo.createContent(contentBytes, commitMessage, relativePath, branch);
    } catch (GHFileNotFoundException e) {
        // try to create content once again
        LOG.warn("Error of creation of {} occurred. Is trying to create it once again...",
                ghRepo.getHtmlUrl() + "/" + relativePath);
        sleepQuietly(GITHUB_OPERATION_TIMEOUT_SEC);
        ghRepo.createContent(contentBytes, commitMessage, relativePath);
    }
}

From source file:acromusashi.kafka.log.producer.WinApacheLogProducer.java

/**
 * tail??/*from   w ww. j  a  va2 s.  co m*/
 *
 * @param targetPath ?
 */
public void tailRun(File targetPath) {
    try (WatchService watcher = FileSystems.getDefault().newWatchService()) {
        Path targetDir = targetPath.toPath();
        targetDir.register(watcher, ENTRY_MODIFY);
        targetDir.relativize(targetPath.toPath());
        List<String> targetFileNames = getTargetLogFiles(Lists.newArrayList(targetDir.toFile().list()));
        Collections.sort(targetFileNames);
        int logFileNameSize = targetFileNames.size();
        this.targetFile = new File(targetDir + "/" + targetFileNames.get(logFileNameSize - 1));

        while (true) {
            WatchKey key = watcher.take();
            for (WatchEvent<?> event : key.pollEvents()) {
                WatchEvent.Kind<?> kind = event.kind();
                if (kind == OVERFLOW) {
                    logger.warn("OVERFLOW");
                    continue;
                }
                byte[] tail = null;
                boolean noRetry = false;
                for (int retryCount = 0; retryCount < this.retryNum; retryCount++) {
                    try {
                        tail = getTail(this.targetFile);
                        break;
                    } catch (IOException ex) {
                        if (retryCount == this.retryNum - 1) {
                            noRetry = true;
                        }
                    }
                }
                // ?????????????????
                if (noRetry) {
                    break;
                }
                List<String> allFileName = getTargetLogFiles(Arrays.asList(targetDir.toFile().list()));
                Collections.sort(allFileName);
                int allFileNameSize = allFileName.size();
                if (tail.length > 0) {
                    String inputStr = new String(tail, this.encoding);
                    if (!allFileName.equals(targetFileNames)) {
                        this.newFileName.add(allFileName.get(allFileNameSize - 1));
                        targetFileNames = allFileName;
                    }

                    List<String> eachStr = Arrays.asList(inputStr.split(System.getProperty("line.separator")));
                    List<KeyedMessage<String, String>> list = getKeyedMessage(eachStr);
                    this.producer.send(list);
                } else {
                    if (!allFileName.equals(targetFileNames)) {
                        this.newFileName.add(allFileName.get(allFileNameSize - 1));
                        targetFileNames = allFileName;
                    }
                    if (this.newFileName.size() > 0) {
                        this.targetFile = new File(targetDir + "/" + this.newFileName.get(0));
                        this.newFileName.remove(0);
                        targetFileNames = allFileName;
                    }
                }
            }

            boolean valid = key.reset();
            if (!valid) {
                break;
            }
        }
    } catch (Exception ex) {
        // FindBugs?Java7????????FindBugs?????????
        logger.error("Failed start producer. ", ex);
    }
}

From source file:org.tinymediamanager.core.Utils.java

/**
 * returns the relative path of 2 absolute file paths<br>
 * "/a/b & /a/b/c/d -> c/d//from ww  w  . ja v  a 2 s . co  m
 * 
 * @param parent
 *          the directory
 * @param child
 *          the subdirectory
 * @return relative path
 */
public static String relPath(Path parent, Path child) {
    return parent.relativize(child).toString();
}