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.dataconservancy.packaging.tool.impl.IPMServiceImpl.java

@Override
public void remapNode(Node node, Path newPath) throws IOException {

    Path oldPath = null;//from  ww w . j  av a 2s .co  m
    if (node.getFileInfo().getLocation() != null) {
        oldPath = Paths.get(node.getFileInfo().getLocation());
    }
    node.setFileInfo(new FileInfo(newPath));

    //If we have an old path try to remap children
    if (oldPath != null && node.getChildren() != null) {
        //If this path can't be relativized we won't automatically remap
        final Path finalOldPath = oldPath;
        node.getChildren().stream().filter(child -> child.getFileInfo() != null).forEach(child -> {
            try {
                Path oldRelativePath = finalOldPath.relativize(Paths.get(child.getFileInfo().getLocation()));
                Path newChildPath = newPath.resolve(oldRelativePath);
                if (newChildPath.toFile().exists()) {
                    remapNode(child, newChildPath);
                }
            } catch (IllegalArgumentException | IOException e) {
                //If this path can't be relativized we won't automatically remap
            }
        });
    }
}

From source file:com.collaborne.jsonschema.generator.pojo.PojoGeneratorSmokeTest.java

@After
public void tearDown() throws IOException {
    // Dump the contents of the file system
    Path dumpStart = fs.getPath("/");
    Files.walkFileTree(dumpStart, new SimpleFileVisitor<Path>() {
        @Override//  w  w w.j  a v  a  2  s  . c  om
        public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
            System.out.println("> " + file);
            System.out.println(new String(Files.readAllBytes(file), StandardCharsets.UTF_8));

            // Copy the file if wanted
            if (DUMP_DIRECTORY != null) {
                Path dumpTarget = Paths.get(DUMP_DIRECTORY, name.getMethodName());
                Path target = dumpTarget.resolve(dumpStart.relativize(file).toString());
                Files.createDirectories(target.getParent());
                Files.copy(file, target, StandardCopyOption.REPLACE_EXISTING);
            }
            return FileVisitResult.CONTINUE;
        }
    });
}

From source file:ffx.potential.utils.PotentialsFileOpener.java

public PotentialsFileOpener(File file) {
    if (!file.exists() || !file.isFile()) {
        throw new IllegalArgumentException(
                String.format(" File %s either did not exist or was not a file.", file.getName()));
    }//from   w  ww .  j ava 2 s  .co  m
    this.file = file;
    Path pwdPath;
    Path absPath;
    try {
        pwdPath = Paths.get(new File("").getCanonicalPath());
    } catch (IOException ex) {
        pwdPath = Paths.get(new File("").getAbsolutePath());
    }
    try {
        absPath = Paths.get(file.getCanonicalPath());
    } catch (IOException ex) {
        absPath = Paths.get(file.getAbsolutePath());
    }
    filepath = pwdPath.relativize(absPath);
    allFiles = new File[1];
    allFiles[0] = this.file;
    allPaths = new Path[1];
    allPaths[0] = this.filepath;
    assemblies = new ArrayList<>();
    propertyList = new ArrayList<>();
}

From source file:fr.gael.dhus.olingo.v1.entity.Product.java

@Override
public Map<String, Object> toEntityResponse(String root_url) {
    // superclass node response is not required. Only Item response is
    // necessary.
    Map<String, Object> res = super.itemToEntityResponse(root_url);

    res.put(NodeEntitySet.CHILDREN_NUMBER, getChildrenNumber());

    LinkedHashMap<String, Date> dates = new LinkedHashMap<String, Date>();
    dates.put(V1Model.TIME_RANGE_START, getContentStart());
    dates.put(V1Model.TIME_RANGE_END, getContentEnd());
    res.put(ProductEntitySet.CONTENT_DATE, dates);

    HashMap<String, String> checksum = new LinkedHashMap<String, String>();
    checksum.put(V1Model.ALGORITHM, getChecksumAlgorithm());
    checksum.put(V1Model.VALUE, getChecksumValue());
    res.put(ProductEntitySet.CHECKSUM, checksum);

    res.put(ProductEntitySet.INGESTION_DATE, getIngestionDate());
    res.put(ProductEntitySet.CREATION_DATE, getCreationDate());
    res.put(ProductEntitySet.EVICTION_DATE, getEvictionDate());
    res.put(ProductEntitySet.CONTENT_GEOMETRY, getGeometry());

    Path incoming_path = Paths.get(CONFIG_MGR.getArchiveConfiguration().getIncomingConfiguration().getPath());
    String prod_path = this.getDownloadablePath();
    if (prod_path != null) // Can happen with not yet ingested products
    {//from   www  . j  ava 2 s  . co  m
        Path prod_path_path = Paths.get(prod_path);
        if (prod_path_path.startsWith(incoming_path)) {
            prod_path = incoming_path.relativize(prod_path_path).toString();
        } else {
            prod_path = null;
        }
    } else {
        prod_path = null;
    }
    res.put(ProductEntitySet.LOCAL_PATH, prod_path);

    try {
        String url = root_url + V1Model.PRODUCT.getName() + "('" + getId() + "')/$value";
        MetalinkBuilder mb = new MetalinkBuilder();
        mb.addFile(getName() + ".zip").addUrl(url, null, 0);

        StringWriter sw = new StringWriter();
        Document doc = mb.build();
        Transformer transformer = TransformerFactory.newInstance().newTransformer();
        transformer.transform(new DOMSource(doc), new StreamResult(sw));

        res.put(ProductEntitySet.METALINK, sw.toString());
    } catch (ParserConfigurationException e) {
        LOGGER.error("Error when creating Product EntityResponse", e);
    } catch (TransformerException e) {
        LOGGER.error("Error when creating Product EntityResponse", e);
    }
    return res;
}

From source file:org.roda.core.plugins.plugins.characterization.ExifToolPlugin.java

private void processAIP(IndexService index, ModelService model, StorageService storage, Report report,
        SimpleJobPluginInfo jobPluginInfo, Job job, AIP aip) {
    LOGGER.debug("Processing AIP {}", aip.getId());
    boolean inotify = false;
    Report reportItem = PluginHelper.initPluginReportItem(this, aip.getId(), AIP.class,
            AIPState.INGEST_PROCESSING);
    PluginHelper.updatePartialJobReport(this, model, reportItem, false, job);
    PluginState reportState = PluginState.SUCCESS;
    ValidationReport validationReport = new ValidationReport();
    List<LinkingIdentifier> sources = new ArrayList<>();

    for (Representation representation : aip.getRepresentations()) {
        LOGGER.debug("Processing representation {} from AIP {}", representation.getId(), aip.getId());

        DirectResourceAccess directAccess = null;
        try {/*from   www .j av a  2  s  .  c  om*/
            StoragePath representationDataPath = ModelUtils.getRepresentationDataStoragePath(aip.getId(),
                    representation.getId());
            directAccess = storage.getDirectAccess(representationDataPath);

            sources.add(PluginHelper.getLinkingIdentifier(aip.getId(), representation.getId(),
                    RodaConstants.PRESERVATION_LINKING_OBJECT_SOURCE));

            CloseableIterable<OptionalWithCause<org.roda.core.data.v2.ip.File>> allFiles = model
                    .listFilesUnder(aip.getId(), representation.getId(), true);

            if (!CloseableIterables.isEmpty(allFiles)) {
                Path metadata = Files.createTempDirectory("metadata");
                ExifToolPluginUtils.runExifToolOnPath(directAccess.getPath(), metadata);

                try (DirectoryStream<Path> directoryStream = Files.newDirectoryStream(metadata)) {
                    for (Path path : directoryStream) {
                        ContentPayload payload = new FSPathContentPayload(path);
                        List<String> fileDirectoryPath = new ArrayList<>();

                        Path relativePath = metadata.relativize(path);
                        for (int i = 0; i < relativePath.getNameCount() - 2; i++) {
                            fileDirectoryPath.add(relativePath.getName(i).toString());
                        }

                        String fileId = path.getFileName().toString();
                        model.createOrUpdateOtherMetadata(aip.getId(), representation.getId(),
                                fileDirectoryPath, fileId, ".xml", RodaConstants.OTHER_METADATA_TYPE_EXIFTOOL,
                                payload, inotify);
                    }
                }

                FSUtils.deletePath(metadata);
            }
        } catch (RODAException | IOException e) {
            LOGGER.error("Error processing AIP {}: {}", aip.getId(), e.getMessage());
            reportState = PluginState.FAILURE;
            validationReport.addIssue(new ValidationIssue(e.getMessage()));
        } finally {
            IOUtils.closeQuietly(directAccess);
        }
    }

    try {
        model.notifyAipUpdated(aip.getId());
    } catch (RequestNotValidException | GenericException | NotFoundException | AuthorizationDeniedException e) {
        LOGGER.error("Error notifying of AIP update", e);
    }

    if (reportState.equals(PluginState.SUCCESS)) {
        jobPluginInfo.incrementObjectsProcessedWithSuccess();
        reportItem.setPluginState(PluginState.SUCCESS);
    } else {
        jobPluginInfo.incrementObjectsProcessedWithFailure();
        reportItem.setHtmlPluginDetails(true).setPluginState(PluginState.FAILURE);
        reportItem.setPluginDetails(validationReport.toHtml(false, false, false, "Error list"));
    }

    try {
        PluginHelper.createPluginEvent(this, aip.getId(), model, index, sources, null,
                reportItem.getPluginState(), "", true);
    } catch (ValidationException | RequestNotValidException | NotFoundException | GenericException
            | AuthorizationDeniedException | AlreadyExistsException e) {
        LOGGER.error("Error creating event: {}", e.getMessage(), e);
    }

    report.addReport(reportItem);
    PluginHelper.updatePartialJobReport(this, model, reportItem, true, job);
}

From source file:org.metaeffekt.dcc.controller.execution.RemoteExecutor.java

private void addDirectoryContentsToZipFile(Path rootDirectory, Path directory, ZipOutputStream zipFile,
        Set<String> includes) throws IOException {
    try (DirectoryStream<Path> directoryStream = Files.newDirectoryStream(directory)) {
        for (Path path : directoryStream) {
            Path relativePath = rootDirectory.relativize(path);
            if (CollectionUtils.isEmpty(includes) || includes.contains(relativePath.toString())) {
                if (Files.isDirectory(path)) {
                    String name = relativePath.toString();
                    name = name.endsWith("/") ? name : name + "/";
                    zipFile.putNextEntry(new ZipEntry(replaceWindowsPathSeparator(name)));
                    addDirectoryContentsToZipFile(rootDirectory, path, zipFile, null);
                } else {
                    String name = relativePath.toString();
                    zipFile.putNextEntry(new ZipEntry(replaceWindowsPathSeparator(name)));
                    try (InputStream fileToBeZipped = new BufferedInputStream(Files.newInputStream(path))) {
                        IOUtils.copy(fileToBeZipped, zipFile);
                    }/*  www  .j a  v  a 2  s . c  om*/
                }
            }
        }
    }
}

From source file:com.liferay.blade.cli.CreateCommand.java

public void execute() throws Exception {
    if (_options.listtemplates()) {
        listTemplates();//from   w  w w.  j av  a 2 s. co m
        return;
    }

    List<String> args = _options._arguments();

    String template = _options.template();

    if (template == null) {
        template = "mvcportlet";
    } else if (!isExistingTemplate(template)) {
        addError("Create", "the template " + template + " is not in the list");
        return;
    }

    String name = args.remove(0);
    final File dir = _options.dir() != null ? _options.dir() : getDefaultDir();
    final File workDir = Processor.getFile(dir, name);

    if (!checkDir(workDir)) {
        addError("Create",
                name + " is not empty or it is a file." + " Please clean or delete it then run again");
        return;
    }

    final boolean isWorkspace = Util.isWorkspace(dir);

    name = workDir.getName();

    final Pattern glob = Pattern.compile("^standalone/" + template + "/.*|\\...+/.*");

    final Map<String, String> subs = new HashMap<>();
    subs.put("templates/standalone/" + template + "/", "");
    subs.put("_project_path_", workDir.getAbsolutePath());
    subs.put("_name_", getPackageName(name));
    subs.put("_NAME_", name);

    final String packageName = _options.packagename();

    if (isEmpty(packageName)) {
        subs.put("_package_path_", getPackageName(name).replaceAll("\\.", "/"));
        subs.put("_package_", getPackageName(name));
    } else {
        subs.put("_package_path_", packageName.replaceAll("\\.", "/"));
        subs.put("_package_", packageName);
    }

    String classname = _options.classname();

    if (isEmpty(classname)) {
        classname = getClassName(name);
    }

    String service = _options.service();

    if ("service".equals(template)) {
        if (isEmpty(service)) {
            addError("Create",
                    "The service template requires the fully qualified name "
                            + "of service must be specified after the service "
                            + "argument.\nFor example: blade create -t service -s "
                            + "com.liferay.portal.kernel.events.LifecycleAction " + "customPreAction");
            return;
        }

        subs.put("_SERVICE_FULL_", service);
        subs.put("_SERVICE_SHORT_", service.substring(service.lastIndexOf('.') + 1));
    }

    if ("servicewrapper".equals(template)) {
        if (isEmpty(service)) {
            addError("Create",
                    "The servicewrapper template requires the fully qualified"
                            + " name of service must be specified after the service"
                            + " argument.\nFor example: blade create -t " + "servicewrapper -s "
                            + "com.liferay.portal.service.UserLocalServiceWrapper " + "customServiceWrapper");
            return;
        }

        subs.put("_SERVICE_FULL_", service);
        subs.put("_SERVICE_SHORT_", service.substring(service.lastIndexOf('.') + 1));
    }

    if ("servicebuilder".equals(template)) {
        if (isEmpty(packageName)) {
            addError("Create",
                    "The servicebuilder template requires the name of the "
                            + "root package within which to create service builder "
                            + "classes must be specified.\nFor example: blade " + "create -t servicebuilder -p "
                            + "com.liferay.guestbook guestbook");
            return;
        }

        if (name.indexOf(".") > -1) {
            subs.put("_api_", packageName + ".api");
            subs.put("_service_", packageName + ".svc");
            subs.put("_web_", packageName + ".web");
        } else {
            subs.put("_api_", name + "-api");
            subs.put("_service_", name + "-service");
            subs.put("_web_", name + "-web");
        }

        if (isWorkspace) {
            final Path workspacePath = Util.getWorkspaceDir(dir).getAbsoluteFile().toPath();

            final Path dirPath = dir.getAbsoluteFile().toPath();

            final String relativePath = workspacePath.relativize(dirPath).toString();

            final String apiPath = ":" + relativePath.replaceAll("\\\\", "/").replaceAll("\\/", ":") + ":"
                    + name;

            subs.put("_api_path_", apiPath);
        } else {
            subs.put("_api_path_", "");
        }

        subs.put("_portlet_", packageName + ".portlet");
        subs.put("_portletpackage_", packageName.replaceAll("\\.", "/") + "/portlet");
    } else if ("activator".equals(template)) {
        if (!classname.contains("Activator")) {
            classname += "Activator";
        }
    }

    if ("portlet".equals(template) || "mvcportlet".equals(template)) {
        if (classname.endsWith("Portlet")) {
            classname = classname.replaceAll("Portlet$", "");
        }
    }

    final String hostbundlebsn = _options.hostbundlebsn();

    final String hostbundleversion = _options.hostbundleversion();

    if ("fragment".equals(template)) {
        if (isEmpty(hostbundlebsn) || isEmpty(hostbundleversion)) {
            addError("Create", "The fragment template requires the bundle symbolic name "
                    + "of the hostbundle and version must be specified.\n"
                    + "For example: blade create -t fragment -h " + "com.liferay.login.web -H 1.0.0 name");
            return;
        }

        subs.put("_HOST_BUNDLE_BSN_", hostbundlebsn);
        subs.put("_HOST_BUNDLE_VERSION_", hostbundleversion);
    }

    subs.put("_CLASS_", classname);

    String unNormalizedPortletFqn = name.toLowerCase().replaceAll("-", ".") + "_" + classname;

    subs.put("_portlet_fqn_", unNormalizedPortletFqn.replaceAll("\\.", "_"));

    File moduleTemplatesZip = getGradleTemplatesZip();

    InputStream in = new FileInputStream(moduleTemplatesZip);

    copy("standalone", template, workDir, in, glob, true, subs);

    in.close();

    if (isWorkspace) {
        final Pattern buildGlob = Pattern.compile("^workspace/" + template + "/.*|\\...+/.*");

        in = new FileInputStream(moduleTemplatesZip);

        copy("workspace", template, workDir, in, buildGlob, true, subs);

        in.close();

        File settingsFile = new File(workDir, "settings.gradle");

        if (settingsFile.exists()) {
            settingsFile.delete();
        }

        IO.delete(new File(workDir, "gradlew"));
        IO.delete(new File(workDir, "gradlew.bat"));
        IO.delete(new File(workDir, "gradle"));
    } else {
        File gradlew = new File(workDir, "gradlew");

        if (gradlew.exists()) {
            gradlew.setExecutable(true);
        }
    }

    _blade.out().println("Created the project " + name + " using the " + template + " template in " + workDir);
}

From source file:facs.utils.Billing.java

/**
 * Helper method. copies files and directories from source to target source and target can be
 * created via the command: FileSystems.getDefault().getPath(String path, ... String more) or
 * Paths.get(String path, ... String more) Note: overrides existing folders
 * /*  w w w . j  a  va2 s  . c  om*/
 * @param source
 * @param target
 * @return true if copying was successful
 */
public boolean copy(final Path source, final Path target) {
    try {
        Files.walkFileTree(source, EnumSet.of(FileVisitOption.FOLLOW_LINKS), Integer.MAX_VALUE,
                new SimpleFileVisitor<Path>() {

                    @Override
                    public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs)
                            throws IOException {
                        Path targetdir = target.resolve(source.relativize(dir));
                        try {
                            Files.copy(dir, targetdir, java.nio.file.StandardCopyOption.REPLACE_EXISTING);
                        } catch (FileAlreadyExistsException e) {
                            if (!Files.isDirectory(targetdir)) {
                                throw e;
                            }
                        }

                        return FileVisitResult.CONTINUE;
                    }

                    @Override
                    public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
                        Files.copy(file, target.resolve(source.relativize(file)));
                        return FileVisitResult.CONTINUE;

                    }

                });
    } catch (IOException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
        return false;
    }
    return true;
}

From source file:org.apache.uima.ruta.descriptor.RutaDescriptorBuilder.java

private String getRelativeLocation(URI target, String base) {
    if (base == null) {
        return null;
    }//from   w  w  w. j  a  v  a2  s .  c om
    Path basePath = Paths.get(base);
    if (!basePath.toFile().isDirectory()) {
        basePath = basePath.getParent();
    }
    Path targetPath = null;
    try {
        targetPath = Paths.get(target);
    } catch (Exception e) {
        return null;
    }
    Path relativePath = null;
    try {
        relativePath = basePath.relativize(targetPath);
    } catch (Exception e) {
        return null;
    }
    // HOTFIX: avoid windows paths. No generic solution to access a portable string found yet for
    // Path
    String result = relativePath.toString().replaceAll("\\\\", "/");
    return result;
}