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:fr.gael.dhus.datastore.FileSystemDataStore.java

/**
 * Moves product download zip into the given destination.
 * <p><b>Note:</b> generates the zip of product if necessary.</p>
 *
 * @param product     product to move./*from www .j a  va2s .com*/
 * @param destination destination of product
 */
private void moveProduct(Product product, String destination) {

    if (destination == null || destination.trim().isEmpty()) {
        return;
    }

    Path zip_destination = Paths.get(destination);
    String download_path = product.getDownloadablePath();
    try {
        if (download_path != null) {
            File product_zip_file = Paths.get(download_path).toFile();
            FileUtils.moveFileToDirectory(product_zip_file, zip_destination.toFile(), true);
        } else {
            Path product_path = Paths.get(product.getPath().getPath());
            if (UnZip.supported(product_path.toAbsolutePath().toString())) {
                FileUtils.moveFileToDirectory(product_path.toFile(), zip_destination.toFile(), true);
            } else {
                zip_destination.resolve(product_path.getFileName());
                generateZip(product_path.toFile(), zip_destination.toFile());
            }
        }
    } catch (IOException e) {
        LOGGER.error("Cannot move product: " + product.getPath() + " into " + destination, e);
    }
}

From source file:com.liferay.sync.engine.document.library.handler.GetSyncDLObjectUpdateHandler.java

protected boolean processFilePathChange(SyncFile sourceSyncFile, SyncFile targetSyncFile) throws Exception {

    String sourceSyncFileName = FileUtil.getSanitizedFileName(sourceSyncFile.getName(),
            sourceSyncFile.getExtension());

    String targetSyncFileName = FileUtil.getSanitizedFileName(targetSyncFile.getName(),
            targetSyncFile.getExtension());

    if ((sourceSyncFile.getParentFolderId() != targetSyncFile.getParentFolderId())
            || !sourceSyncFileName.equals(targetSyncFileName)) {

        SyncFile targetParentSyncFile = SyncFileService.fetchSyncFile(targetSyncFile.getRepositoryId(),
                getSyncAccountId(), targetSyncFile.getParentFolderId());

        Path targetParentFilePath = Paths.get(targetParentSyncFile.getFilePathName());

        Path targetFilePath = targetParentFilePath.resolve(targetSyncFileName);

        Path sourceFilePath = Paths.get(sourceSyncFile.getFilePathName());

        sourceSyncFile.setUiEvent(SyncFile.UI_EVENT_NONE);

        SyncFileService.updateSyncFile(targetFilePath, targetSyncFile.getParentFolderId(), sourceSyncFile);

        if (FileUtil.exists(sourceFilePath)) {
            Watcher watcher = WatcherManager.getWatcher(getSyncAccountId());

            watcher.addMovedFilePathName(targetSyncFile.getFilePathName());

            FileUtil.moveFile(sourceFilePath, targetFilePath);
        }//from www . java2s  .co m

        return true;
    }

    return false;
}

From source file:eu.itesla_project.modules.validation.OfflineValidationTool.java

private static void writeCsv(Map<String, Map<RuleId, ValidationStatus>> statusPerRulePerCase,
        Map<String, Map<RuleId, Map<HistoDbAttributeId, Object>>> valuesPerRulePerCase, Path outputDir)
        throws IOException {
    Set<RuleId> rulesIds = new TreeSet<>();
    statusPerRulePerCase.values().stream().forEach(e -> rulesIds.addAll(e.keySet()));

    writeComparisonFiles(rulesIds, statusPerRulePerCase, outputDir);
    writeAttributesFiles(rulesIds, valuesPerRulePerCase, outputDir);

    List<String> categories = Arrays.asList(toCategory(OK_S, OK_R), toCategory(OK_S, NOK_R),
            toCategory(NOK_S, OK_R), toCategory(NOK_S, NOK_R), toCategory(OK_S, UNDEF_R),
            toCategory(NOK_S, UNDEF_R), toCategory(UNDEF_S, OK_R), toCategory(UNDEF_S, NOK_R),
            toCategory(UNDEF_S, UNDEF_R));

    Map<RuleId, Map<String, AtomicInteger>> synthesisPerRule = new HashMap<>();
    for (RuleId ruleId : rulesIds) {
        synthesisPerRule.put(ruleId,/* ww  w. j  a v a 2s  .  c  om*/
                categories.stream().collect(Collectors.toMap(Function.identity(), e -> new AtomicInteger())));
    }
    for (Map.Entry<String, Map<RuleId, ValidationStatus>> e : statusPerRulePerCase.entrySet()) {
        Map<RuleId, ValidationStatus> statusPerRule = e.getValue();
        for (RuleId ruleId : rulesIds) {
            ValidationStatus status = statusPerRule.get(ruleId);
            String category = toCategory(status.isSimulationOkToStr(), status.isRuleOkToStr());
            synthesisPerRule.get(ruleId).get(category).incrementAndGet();
        }
    }

    writeSynthesisFile(synthesisPerRule, categories, outputDir.resolve("synthesis.csv"));
}

From source file:info.novatec.inspectit.rcp.storage.util.DataRetriever.java

/**
 * Downloads and saves locally wanted files associated with given {@link StorageData}. Files
 * will be saved in passed directory. The caller can specify the type of the files to download
 * by passing the proper {@link StorageFileType}s to the method.
 * /*ww  w  .  j  av a  2 s  . co  m*/
 * @param cmrRepositoryDefinition
 *            {@link CmrRepositoryDefinition}.
 * @param storageData
 *            {@link StorageData}.
 * @param directory
 *            Directory to save objects. compressBefore Should data files be compressed on the
 *            fly before sent.
 * @param compressBefore
 *            Should data files be compressed on the fly before sent.
 * @param decompressContent
 *            If the useGzipCompression is <code>true</code>, this parameter will define if the
 *            received content will be de-compressed. If false is passed content will be saved
 *            to file in the same format as received, but the path of the file will be altered
 *            with additional '.gzip' extension at the end.
 * @param subMonitor
 *            {@link SubMonitor} for process reporting.
 * @param fileTypes
 *            Files that should be downloaded.
 * @throws BusinessException
 *             If directory to save does not exists. If files wanted can not be found on the
 *             server.
 * @throws IOException
 *             If {@link IOException} occurs.
 */
public void downloadAndSaveStorageFiles(CmrRepositoryDefinition cmrRepositoryDefinition,
        StorageData storageData, final Path directory, boolean compressBefore, boolean decompressContent,
        SubMonitor subMonitor, StorageFileType... fileTypes) throws BusinessException, IOException {
    if (!Files.isDirectory(directory)) {
        throw new BusinessException("Download and save storage files for storage " + storageData
                + " to the path " + directory.toString() + ".", StorageErrorCodeEnum.FILE_DOES_NOT_EXIST);
    }

    Map<String, Long> allFiles = getFilesFromCmr(cmrRepositoryDefinition, storageData, fileTypes);

    if (MapUtils.isNotEmpty(allFiles)) {
        PostDownloadRunnable postDownloadRunnable = new PostDownloadRunnable() {
            @Override
            public void process(InputStream content, String fileName) throws IOException {
                String[] splittedFileName = fileName.split("/");
                Path writePath = directory;
                // first part is empty, second is storage id, we don't need it
                for (int i = 2; i < splittedFileName.length; i++) {
                    writePath = writePath.resolve(splittedFileName[i]);
                }
                // ensure all dirs are created
                if (Files.notExists(writePath.getParent())) {
                    Files.createDirectories(writePath.getParent());
                }
                Files.copy(content, writePath, StandardCopyOption.REPLACE_EXISTING);
            }
        };
        this.downloadAndSaveObjects(cmrRepositoryDefinition, allFiles, postDownloadRunnable, compressBefore,
                decompressContent, subMonitor);
    }
}

From source file:com.databasepreservation.visualization.utils.SolrUtils.java

public static void setupSolrCloudConfigsets(String zkHost) {
    // before anything else, try to get a zookeeper client
    CloudSolrClient zkClient = new CloudSolrClient(zkHost);

    // get resources and copy them to a temporary directory
    Path databaseDir = null;/*from ww  w.  ja  v  a  2s  .com*/
    Path tableDir = null;
    Path savedSearchesDir = null;
    try {
        final File jarFile = new File(
                SolrManager.class.getProtectionDomain().getCodeSource().getLocation().toURI());

        // if it is a directory the application in being run from an IDE
        // in that case do not setup (assuming setup is done)
        if (!jarFile.isDirectory()) {
            databaseDir = Files.createTempDirectory("dbv_db_");
            tableDir = Files.createTempDirectory("dbv_tab_");
            savedSearchesDir = Files.createTempDirectory("dbv_tab_");
            final JarFile jar = new JarFile(jarFile);
            final Enumeration<JarEntry> entries = jar.entries();

            while (entries.hasMoreElements()) {
                JarEntry entry = entries.nextElement();
                String name = entry.getName();

                String nameWithoutOriginPart = null;
                Path destination = null;
                if (name.startsWith(ViewerSafeConstants.SOLR_CONFIGSET_DATABASE_RESOURCE + "/")) {
                    nameWithoutOriginPart = name
                            .substring(ViewerSafeConstants.SOLR_CONFIGSET_DATABASE_RESOURCE.length() + 1);
                    destination = databaseDir;
                } else if (name.startsWith(ViewerSafeConstants.SOLR_CONFIGSET_TABLE_RESOURCE + "/")) {
                    nameWithoutOriginPart = name
                            .substring(ViewerSafeConstants.SOLR_CONFIGSET_TABLE_RESOURCE.length() + 1);
                    destination = tableDir;
                } else if (name.startsWith(ViewerSafeConstants.SOLR_CONFIGSET_SEARCHES_RESOURCE + "/")) {
                    nameWithoutOriginPart = name
                            .substring(ViewerSafeConstants.SOLR_CONFIGSET_SEARCHES_RESOURCE.length() + 1);
                    destination = savedSearchesDir;
                } else {
                    continue;
                }

                Path output = destination.resolve(nameWithoutOriginPart);
                if (name.endsWith("/")) {
                    Files.createDirectories(output);
                } else {
                    InputStream inputStream = SolrManager.class.getResourceAsStream("/" + name);
                    output = Files.createFile(output);
                    OutputStream outputStream = Files.newOutputStream(output, StandardOpenOption.CREATE,
                            StandardOpenOption.WRITE);
                    IOUtils.copy(inputStream, outputStream);
                    inputStream.close();
                    outputStream.close();
                }
            }
            jar.close();
        }
    } catch (IOException | URISyntaxException e) {
        LOGGER.error("Could not extract Solr configset", e);
        if (databaseDir != null) {
            try {
                FileUtils.deleteDirectoryRecursive(databaseDir);
            } catch (IOException e1) {
                LOGGER.debug("IO error deleting temporary folder: " + databaseDir, e1);
            }
        }
        if (tableDir != null) {
            try {
                FileUtils.deleteDirectoryRecursive(tableDir);
            } catch (IOException e1) {
                LOGGER.debug("IO error deleting temporary folder: " + tableDir, e1);
            }
        }
        databaseDir = null;
        tableDir = null;
    }

    // copy configurations to solr
    if (databaseDir != null && tableDir != null) {
        try {
            zkClient.uploadConfig(databaseDir, ViewerSafeConstants.SOLR_CONFIGSET_DATABASE);
        } catch (IOException e) {
            LOGGER.debug("IO error uploading database config to solr cloud", e);
        }
        try {
            zkClient.uploadConfig(tableDir, ViewerSafeConstants.SOLR_CONFIGSET_TABLE);
        } catch (IOException e) {
            LOGGER.debug("IO error uploading table config to solr cloud", e);
        }
        try {
            zkClient.uploadConfig(savedSearchesDir, ViewerSafeConstants.SOLR_CONFIGSET_SEARCHES);
        } catch (IOException e) {
            LOGGER.debug("IO error uploading saved searches config to solr cloud", e);
        }

        try {
            FileUtils.deleteDirectoryRecursive(databaseDir);
        } catch (IOException e1) {
            LOGGER.debug("IO error deleting temporary folder: " + databaseDir, e1);
        }
        try {
            FileUtils.deleteDirectoryRecursive(tableDir);
        } catch (IOException e1) {
            LOGGER.debug("IO error deleting temporary folder: " + tableDir, e1);
        }
        try {
            FileUtils.deleteDirectoryRecursive(savedSearchesDir);
        } catch (IOException e1) {
            LOGGER.debug("IO error deleting temporary folder: " + savedSearchesDir, e1);
        }
    }

    try {
        zkClient.close();
    } catch (IOException e) {
        LOGGER.debug("IO error closing connection to solr cloud", e);
    }
}

From source file:com.google.cloud.tools.managedcloudsdk.install.ZipExtractorProvider.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();

    // Use ZipFile instead of ZipArchiveInputStream so that we can obtain file permissions
    // on unix-like systems via getUnixMode(). ZipArchiveInputStream doesn't have access to
    // all the zip file data and will return "0" for any call to getUnixMode().
    try (ZipFile zipFile = new ZipFile(archive.toFile())) {
        // TextProgressBar progressBar = textBarFactory.newProgressBar(messageListener, count);
        Enumeration<ZipArchiveEntry> zipEntries = zipFile.getEntries();
        while (zipEntries.hasMoreElements()) {
            ZipArchiveEntry entry = zipEntries.nextElement();
            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());
            }/*w  w w  .  j av a2  s  .  com*/

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

            if (entry.isDirectory()) {
                if (!Files.exists(entryTarget)) {
                    Files.createDirectories(entryTarget);
                }
            } else {
                if (!Files.exists(entryTarget.getParent())) {
                    Files.createDirectories(entryTarget.getParent());
                }
                try (OutputStream out = new BufferedOutputStream(Files.newOutputStream(entryTarget))) {
                    try (InputStream in = zipFile.getInputStream(entry)) {
                        IOUtils.copy(in, out);
                        PosixFileAttributeView attributeView = Files.getFileAttributeView(entryTarget,
                                PosixFileAttributeView.class);
                        if (attributeView != null) {
                            attributeView
                                    .setPermissions(PosixUtil.getPosixFilePermissions(entry.getUnixMode()));
                        }
                    }
                }
            }
        }
    }
    progressListener.done();
}

From source file:bjerne.gallery.service.impl.GalleryRootDirConfigJob.java

private void watchForChanges() {
    Path dir = configFile.getParentFile().toPath();
    try {/*from w  w w .  ja  v  a2s.  c  om*/
        WatchKey key = dir.register(watcher, ENTRY_CREATE, ENTRY_DELETE, ENTRY_MODIFY);
        for (;;) {
            try {
                key = watcher.take();
            } catch (InterruptedException | ClosedWatchServiceException e) {
                LOG.info("Interrupted during watcher.take(). Exiting watch loop.");
                return;
            }
            for (WatchEvent<?> event : key.pollEvents()) {
                WatchEvent.Kind<?> kind = event.kind();
                if (kind == OVERFLOW) {
                    continue;
                }

                @SuppressWarnings("unchecked")
                WatchEvent<Path> ev = (WatchEvent<Path>) event;
                Path filename = ev.context();

                Path child = dir.resolve(filename);
                if (child.equals(configFile.toPath())) {
                    LOG.debug("File was changed.");
                    updateConfigFromFile();
                }
            }
            boolean valid = key.reset();
            if (!valid) {
                break;
            }
        }
    } catch (IOException ioe) {
        LOG.error("Exception in filewatcher loop. Exiting.", ioe);
    }
}

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

@Test
public void runSmokeTestInlineExplicitMapping() throws IOException, CodeGenerationException {
    // XXX: only really checks #resolve()
    URI rootUri = URI.create("http://example.com/");

    Path outputDirectory = fs.getPath("output");
    generator.setOutputDirectory(outputDirectory);

    SchemaLoader schemas = loadSchema(rootUri, "/schemas/inline.json");
    generator.setSchemaLoader(schemas);//  w  ww.  j av a2 s . c om

    Mapping rootMapping = new Mapping(URI.create("http://example.com/schemas/inline.json#"),
            new ClassName("com.example.test.schemas", "WithInline"));
    generator.addMapping(rootMapping.getTarget(), rootMapping);

    Mapping inlineMapping = new Mapping(URI.create("http://example.com/schemas/inline.json#/properties/inline"),
            new ClassName("com.example.test.schemas", "Inline"));
    generator.addMapping(inlineMapping.getTarget(), inlineMapping);

    generator.generate(rootMapping.getTarget());
    generator.generate(inlineMapping.getTarget());

    Path generatedTypeFile = outputDirectory.resolve("com/example/test/schemas/WithInline.java");
    assertTrue(Files.exists(generatedTypeFile));
    System.out.println(new String(Files.readAllBytes(generatedTypeFile), StandardCharsets.UTF_8));
    Path generatedInlineTypeFile = outputDirectory.resolve("com/example/test/schemas/Inline.java");
    assertTrue(Files.exists(generatedInlineTypeFile));
}

From source file:com.liferay.sync.engine.SyncSystemTest.java

protected void addFolder(Path testFilePath, JsonNode stepJsonNode) throws Exception {

    SyncSite syncSite = getSyncSite(stepJsonNode);

    String dependency = getString(stepJsonNode, "dependency");

    final Path dependencyFilePath = getDependencyFilePath(testFilePath, dependency);

    FileSystem fileSystem = FileSystems.getDefault();

    final Path targetFilePath = Paths.get(FileUtil.getFilePathName(syncSite.getFilePathName(),
            dependency.replace("common" + fileSystem.getSeparator(), "")));

    Files.walkFileTree(dependencyFilePath, new SimpleFileVisitor<Path>() {

        @Override/*from w  ww .  java  2  s.  c  o m*/
        public FileVisitResult preVisitDirectory(Path filePath, BasicFileAttributes basicFileAttributes)
                throws IOException {

            Path relativeFilePath = dependencyFilePath.relativize(filePath);

            Files.createDirectories(targetFilePath.resolve(relativeFilePath));

            return FileVisitResult.CONTINUE;
        }

        @Override
        public FileVisitResult visitFile(Path filePath, BasicFileAttributes basicFileAttributes)
                throws IOException {

            Path relativeFilePath = dependencyFilePath.relativize(filePath);

            Files.copy(filePath, targetFilePath.resolve(relativeFilePath));

            return FileVisitResult.CONTINUE;
        }

    });
}