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:io.github.swagger2markup.extensions.SchemaExtensionTest.java

@Test
public void testSwagger2AsciiDocSchemaExtension() throws IOException, URISyntaxException {
    //Given//w  ww.  jav a  2 s .  c o  m
    Path file = Paths.get(SchemaExtensionTest.class.getResource("/yaml/swagger_petstore.yaml").toURI());
    Path outputDirectory = Paths.get("build/test/asciidoc/generated");
    FileUtils.deleteQuietly(outputDirectory.toFile());

    //When
    Properties properties = new Properties();
    properties.load(SchemaExtensionTest.class.getResourceAsStream("/config/config.properties"));
    Swagger2MarkupConfig config = new Swagger2MarkupConfigBuilder(properties).build();
    Swagger2MarkupExtensionRegistry registry = new Swagger2MarkupExtensionRegistryBuilder()
            //.withDefinitionsDocumentExtension(new SchemaExtension(Paths.get("src/test/resources/docs/asciidoc/extensions").toUri()))
            .build();
    Swagger2MarkupConverter.from(file).withConfig(config).withExtensionRegistry(registry).build()
            .toFolder(outputDirectory);

    //Then
    assertThat(new String(Files.readAllBytes(outputDirectory.resolve("definitions.adoc")))).contains("=== Pet");
    assertThat(new String(Files.readAllBytes(outputDirectory.resolve("definitions.adoc"))))
            .contains("==== XML Schema");
}

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

@Test
public void testExtractZipFilePreservesExecutePermissionsAndModificationTime()
        throws InterruptedException, IOException {

    // getFakeTime returs time with some non-zero millis. By doing division and multiplication by
    // 1000 we get rid of that.
    long time = ZipConstants.getFakeTime() / 1000 * 1000;

    // Create a simple zip archive using apache's commons-compress to store executable info.
    try (ZipArchiveOutputStream zip = new ZipArchiveOutputStream(zipFile.toFile())) {
        ZipArchiveEntry entry = new ZipArchiveEntry("test.exe");
        entry.setUnixMode((int) MorePosixFilePermissions.toMode(PosixFilePermissions.fromString("r-x------")));
        entry.setSize(DUMMY_FILE_CONTENTS.length);
        entry.setMethod(ZipEntry.STORED);
        entry.setTime(time);//from  w  w  w .  jav a2  s. c  om
        zip.putArchiveEntry(entry);
        zip.write(DUMMY_FILE_CONTENTS);
        zip.closeArchiveEntry();
    }

    // Now run `Unzip.extractZipFile` on our test zip and verify that the file is executable.
    Path extractFolder = tmpFolder.newFolder();
    ImmutableList<Path> result = ArchiveFormat.ZIP.getUnarchiver().extractArchive(
            new DefaultProjectFilesystemFactory(), zipFile.toAbsolutePath(), extractFolder.toAbsolutePath(),
            ExistingFileMode.OVERWRITE);
    Path exe = extractFolder.toAbsolutePath().resolve("test.exe");
    assertTrue(Files.exists(exe));
    assertThat(Files.getLastModifiedTime(exe).toMillis(), Matchers.equalTo(time));
    assertTrue(Files.isExecutable(exe));
    assertEquals(ImmutableList.of(extractFolder.resolve("test.exe")), result);
}

From source file:com.google.devtools.build.android.PackedResourceTarExpander.java

private void unTarPackedResources(final Path tarOut, final Path packedResources) throws IOException {
    LOGGER.fine(String.format("Found packed resources: %s", packedResources));
    try (InputStream inputStream = Files.newInputStream(packedResources);
            TarArchiveInputStream tarStream = new TarArchiveInputStream(inputStream)) {
        byte[] temp = new byte[4 * 1024];
        for (TarArchiveEntry entry = tarStream.getNextTarEntry(); entry != null; entry = tarStream
                .getNextTarEntry()) {//from  w w  w  . jav  a2  s.c o m
            if (!entry.isFile()) {
                continue;
            }
            int read = tarStream.read(temp);
            // packed tars can start with a ./. This can cause issues, so remove it.
            final Path entryPath = tarOut.resolve(entry.getName().replace("^\\./", ""));
            Files.createDirectories(entryPath.getParent());
            final OutputStream entryOutStream = Files.newOutputStream(entryPath);
            while (read > -1) {
                entryOutStream.write(temp, 0, read);
                read = tarStream.read(temp);
            }
            entryOutStream.flush();
            entryOutStream.close();
        }
    }
}

From source file:com.qwazr.library.archiver.ArchiverTool.java

public void extract(final Path sourceFile, final Path destDir) throws IOException, ArchiveException {
    try (final InputStream is = new BufferedInputStream(Files.newInputStream(sourceFile))) {
        try (final ArchiveInputStream in = new ArchiveStreamFactory().createArchiveInputStream(is)) {
            ArchiveEntry entry;// w  w w .  j a v  a 2 s. c  o  m
            while ((entry = in.getNextEntry()) != null) {
                if (!in.canReadEntryData(entry))
                    continue;
                if (entry.isDirectory()) {
                    final Path newDir = destDir.resolve(entry.getName());
                    if (!Files.exists(newDir))
                        Files.createDirectory(newDir);
                    continue;
                }
                if (entry instanceof ZipArchiveEntry)
                    if (((ZipArchiveEntry) entry).isUnixSymlink())
                        continue;
                final Path destFile = destDir.resolve(entry.getName());
                final Path parentDir = destFile.getParent();
                if (!Files.exists(parentDir))
                    Files.createDirectories(parentDir);
                final long entryLastModified = entry.getLastModifiedDate().getTime();
                if (Files.exists(destFile) && Files.isRegularFile(destFile)
                        && Files.getLastModifiedTime(destFile).toMillis() == entryLastModified
                        && entry.getSize() == Files.size(destFile))
                    continue;
                IOUtils.copy(in, destFile);
                Files.setLastModifiedTime(destFile, FileTime.fromMillis(entryLastModified));
            }
        } catch (IOException e) {
            throw new IOException("Unable to extract the archive: " + sourceFile.toAbsolutePath(), e);
        }
    } catch (ArchiveException e) {
        throw new ArchiveException("Unable to extract the archive: " + sourceFile.toAbsolutePath(), e);
    }
}

From source file:au.org.ands.vocabs.toolkit.provider.harvest.SesameHarvestProvider.java

/** Do a harvest. Update the message parameter with the result
 * of the harvest.//ww w  . jav a2 s. c  o  m
 * @param taskInfo The TaskInfo object describing the entire task.
 * @param subtask The details of the subtask
 * @param results HashMap representing the result of the harvest.
 * @return True, iff the harvest succeeded.
 */
@Override
public final boolean harvest(final TaskInfo taskInfo, final JsonNode subtask,
        final HashMap<String, String> results) {

    if (subtask.get("repository_base") == null) {
        TaskUtils.updateMessageAndTaskStatus(logger, taskInfo.getTask(), results, TaskStatus.ERROR,
                "No Sesame repository_base specified.");
        return false;
    }

    String remoteBase = subtask.get("repository_base").textValue();
    if (remoteBase.isEmpty()) {
        TaskUtils.updateMessageAndTaskStatus(logger, taskInfo.getTask(), results, TaskStatus.ERROR,
                "Blank Sesame repository_base specified.");
        return false;
    }

    if (subtask.get("repository_id") == null) {
        TaskUtils.updateMessageAndTaskStatus(logger, taskInfo.getTask(), results, TaskStatus.ERROR,
                "No Sesame repository_id specified.");
        return false;
    }

    String repositoryId = subtask.get("repository_id").textValue();
    if (repositoryId.isEmpty()) {
        TaskUtils.updateMessageAndTaskStatus(logger, taskInfo.getTask(), results, TaskStatus.ERROR,
                "Blank Sesame repository_id specified.");
        return false;
    }

    // Future work: support accessing via basic authentication.
    //        String username = PROPS.getProperty(
    //                PropertyConstants.POOLPARTYHARVESTER_USERNAME);
    //        String password = PROPS.getProperty(
    //                PropertyConstants.POOLPARTYHARVESTER_PASSWORD);

    logger.debug("Getting project from " + remoteBase + ", repository id " + repositoryId);

    RepositoryManager manager = null;
    try {
        manager = RepositoryProvider.getRepositoryManager(remoteBase);

        Repository repository = manager.getRepository(repositoryId);
        if (repository == null) {
            // Repository is missing. This is bad.
            logger.error("Sesame import, repository missing");
            return false;
        }

        RepositoryConnection con = null;
        try {
            con = repository.getConnection();

            Path dir = Paths.get(ToolkitFileUtils.getTaskHarvestOutputPath(taskInfo));
            ToolkitFileUtils.requireDirectory(dir.toString());

            // Future work: support getting just one context.
            //                String contextUri = null;
            //                Resource context;
            //                if (contextUri != null &&  !(contextUri.isEmpty())) {
            //                    context = repository.getValueFactory()
            //                            .createURI(contextUri);
            //                    results.put("contextUri", contextUri);
            //                }

            File outputFile = new File(dir.resolve(repositoryId + ".rdf").toString());
            OutputStream output = new FileOutputStream(outputFile);
            RDFXMLWriter rdfxmlfWriter = new RDFXMLWriter(output);
            con.export(rdfxmlfWriter);
            //                output.write('\n');

        } catch (FileNotFoundException e) {
            results.put(TaskStatus.EXCEPTION, "Sesame harvest, can't create output file");
            logger.error("Sesame harvest, can't create output file: ", e);
            return false;
        } catch (RDFHandlerException e) {
            results.put(TaskStatus.EXCEPTION, "Sesame harvest, can't serialize");
            logger.error("Sesame harvest, can't serialize: ", e);
            return false;
        } finally {
            if (con != null) {
                con.close();
            }
        }
    } catch (RepositoryConfigException | RepositoryException e) {
        results.put(TaskStatus.EXCEPTION, "Exception in Sesame harvest");
        logger.error("Exception in Sesame harvest", e);
        return false;
    }
    return true;
}

From source file:org.elasticsearch.plugins.PluginManagerIT.java

/**
 * Test for #7890//  ww  w . j av a  2  s.c  om
 */
public void testLocalPluginInstallWithBinAndConfigInAlreadyExistingConfigDir_7890() throws Exception {
    String pluginName = "fake-plugin";
    Path pluginDir = createTempDir().resolve(pluginName);
    // create config/test.txt with contents 'version1'
    Files.createDirectories(pluginDir.resolve("config"));
    Files.write(pluginDir.resolve("config").resolve("test.txt"), "version1".getBytes(StandardCharsets.UTF_8));

    String pluginUrl = createPlugin(pluginDir, "description", "fake desc", "name", pluginName, "version", "1.0",
            "elasticsearch.version", Version.CURRENT.toString(), "java.version",
            System.getProperty("java.specification.version"), "jvm", "true", "classname", "FakePlugin");

    Path pluginConfigDir = environment.configFile().resolve(pluginName);

    assertStatusOk(String.format(Locale.ROOT, "install %s --verbose", pluginUrl));

    /*
    First time, our plugin contains:
    - config/test.txt (version1)
     */
    assertFileContent(pluginConfigDir, "test.txt", "version1");

    // We now remove the plugin
    assertStatusOk("remove " + pluginName);

    // We should still have test.txt
    assertFileContent(pluginConfigDir, "test.txt", "version1");

    // Installing a new plugin version
    /*
    Second time, our plugin contains:
    - config/test.txt (version2)
    - config/dir/testdir.txt (version1)
    - config/dir/subdir/testsubdir.txt (version1)
     */
    Files.write(pluginDir.resolve("config").resolve("test.txt"), "version2".getBytes(StandardCharsets.UTF_8));
    Files.createDirectories(pluginDir.resolve("config").resolve("dir").resolve("subdir"));
    Files.write(pluginDir.resolve("config").resolve("dir").resolve("testdir.txt"),
            "version1".getBytes(StandardCharsets.UTF_8));
    Files.write(pluginDir.resolve("config").resolve("dir").resolve("subdir").resolve("testsubdir.txt"),
            "version1".getBytes(StandardCharsets.UTF_8));
    pluginUrl = createPlugin(pluginDir, "description", "fake desc", "name", pluginName, "version", "2.0",
            "elasticsearch.version", Version.CURRENT.toString(), "java.version",
            System.getProperty("java.specification.version"), "jvm", "true", "classname", "FakePlugin");

    assertStatusOk(String.format(Locale.ROOT, "install %s --verbose", pluginUrl));
    assertFileContent(pluginConfigDir, "test.txt", "version1");
    assertFileContent(pluginConfigDir, "test.txt.new", "version2");
    assertFileContent(pluginConfigDir, "dir/testdir.txt", "version1");
    assertFileContent(pluginConfigDir, "dir/subdir/testsubdir.txt", "version1");

    // Removing
    assertStatusOk("remove " + pluginName);
    assertFileContent(pluginConfigDir, "test.txt", "version1");
    assertFileContent(pluginConfigDir, "test.txt.new", "version2");
    assertFileContent(pluginConfigDir, "dir/testdir.txt", "version1");
    assertFileContent(pluginConfigDir, "dir/subdir/testsubdir.txt", "version1");

    // Installing a new plugin version
    /*
    Third time, our plugin contains:
    - config/test.txt (version3)
    - config/test2.txt (version1)
    - config/dir/testdir.txt (version2)
    - config/dir/testdir2.txt (version1)
    - config/dir/subdir/testsubdir.txt (version2)
     */
    Files.write(pluginDir.resolve("config").resolve("test.txt"), "version3".getBytes(StandardCharsets.UTF_8));
    Files.write(pluginDir.resolve("config").resolve("test2.txt"), "version1".getBytes(StandardCharsets.UTF_8));
    Files.write(pluginDir.resolve("config").resolve("dir").resolve("testdir.txt"),
            "version2".getBytes(StandardCharsets.UTF_8));
    Files.write(pluginDir.resolve("config").resolve("dir").resolve("testdir2.txt"),
            "version1".getBytes(StandardCharsets.UTF_8));
    Files.write(pluginDir.resolve("config").resolve("dir").resolve("subdir").resolve("testsubdir.txt"),
            "version2".getBytes(StandardCharsets.UTF_8));
    pluginUrl = createPlugin(pluginDir, "description", "fake desc", "name", pluginName, "version", "3.0",
            "elasticsearch.version", Version.CURRENT.toString(), "java.version",
            System.getProperty("java.specification.version"), "jvm", "true", "classname", "FakePlugin");

    assertStatusOk(String.format(Locale.ROOT, "install %s --verbose", pluginUrl));

    assertFileContent(pluginConfigDir, "test.txt", "version1");
    assertFileContent(pluginConfigDir, "test2.txt", "version1");
    assertFileContent(pluginConfigDir, "test.txt.new", "version3");
    assertFileContent(pluginConfigDir, "dir/testdir.txt", "version1");
    assertFileContent(pluginConfigDir, "dir/testdir.txt.new", "version2");
    assertFileContent(pluginConfigDir, "dir/testdir2.txt", "version1");
    assertFileContent(pluginConfigDir, "dir/subdir/testsubdir.txt", "version1");
    assertFileContent(pluginConfigDir, "dir/subdir/testsubdir.txt.new", "version2");
}

From source file:com.boundlessgeo.geoserver.bundle.BundleExporterTest.java

@Test
public void testSimple() throws Exception {
    new CatalogCreator(cat).workspace("foo").property("bar")
            .featureType("stuff", "geom:Point:srid=4326,name:String,id:Integer", stuff()).layer();

    exporter = new BundleExporter(cat, new ExportOpts(cat.getWorkspaceByName("foo")));
    Path root = exporter.run();

    assertPathExists(root, "workspace.xml");
    assertPathExists(root, "namespace.xml");
    assertPathExists(root, "bar");
    assertPathExists(root, "bar/datastore.xml");
    assertPathExists(root, "bar/stuff");
    assertPathExists(root, "bar/stuff/featuretype.xml");
    assertPathExists(root, "bar/stuff/layer.xml");
    assertPathExists(root, "styles");
    assertPathExists(root, "styles/stuff.xml");
    assertPathExists(root, "styles/stuff.sld");
    assertPathExists(root, "data/bar/stuff.properties");

    // ensure the exported store config points to the properties
    DataStoreInfo store = new XStreamPersisterFactory().createXMLPersister()
            .load(new FileInputStream(root.resolve("bar/datastore.xml").toFile()), DataStoreInfo.class);

    assertEquals("file:%WORKSPACE%/data" + File.separator + "bar",
            store.getConnectionParameters().get("directory"));
}

From source file:com.garyclayburg.filesystem.WatchDir.java

@Override
public void run() {
    try {//from   w w  w  .j  a v  a 2 s. c  om
        init(watchDir, recursive);
        for (;;) {

            log.debug("Listening for File Events...");
            // wait for key to be signalled
            WatchKey key;
            try {
                key = watcher.take();
            } catch (InterruptedException x) {
                return;
            }

            Path dir = keys.get(key);
            if (dir == null) {
                log.warn("WatchKey not recognized!! " + key);
                continue;
            }
            for (WatchEvent<?> event : key.pollEvents()) {
                WatchEvent.Kind kind = event.kind();

                // TBD - provide example of how OVERFLOW event is handled
                if (kind == OVERFLOW) {
                    continue;
                }

                // Context for directory entry event is the file name of entry
                WatchEvent<Path> ev = cast(event);
                Path name = ev.context();
                Path child = dir.resolve(name);

                // print out event
                log.info("{}: {}", event.kind().name(), child);
                if (kind == ENTRY_CREATE || kind == ENTRY_MODIFY) {
                    attributeService.reloadGroovyClass(child);
                } else if (kind == ENTRY_DELETE) {
                    attributeService.removeGroovyClass(child);
                }

                // if directory is created, and watching recursively, then
                // register it and its sub-directories
                if (recursive && (kind == ENTRY_CREATE)) {
                    try {
                        if (Files.isDirectory(child, NOFOLLOW_LINKS)) {
                            registerAll(child);
                        }
                    } catch (IOException x) {
                        log.warn("Cannot register possible new directory for groovy changes: {}", child);
                    }
                }
            }

            // reset key and remove from set if directory no longer accessible
            boolean valid = key.reset();
            if (!valid) {
                keys.remove(key);

                // all directories are inaccessible
                if (keys.isEmpty()) {
                    break;
                }
            }
        }
        log.info("Stopped listening for file events");
    } catch (IOException e) {
        log.warn("Could not start File Watch service", e);
    }
}

From source file:com.gitpitch.services.OfflineService.java

private void fetchYAMLDependencies(PitchParams pp, Path zipRoot) {

    GRSService grsService = grsManager.getService(grsManager.get(pp));
    YAMLOptions yOpts = YAMLOptions.build(pp, grsService, diskService);
    log.debug("fetchYAMLDependencies: yOpts={}", yOpts);

    try {//from  w w  w  . j av a2  s  .  c  o  m

        if (yOpts != null && yOpts.hasLogo()) {
            String logoUrl = yOpts.fetchLogo(pp);
            String logoName = FilenameUtils.getName(logoUrl);

            Path zipAssetsPath = diskService.ensure(zipRoot.resolve(ZIP_ASSETS_DIR));
            diskService.download(pp, zipAssetsPath, logoUrl, logoName, grsManager.get(pp).getHeaders());
            log.debug("fetchYAMLDependencies: downloaded logo={}", logoUrl);
        }

    } catch (Exception lex) {
        log.warn("fetchYAMLDependencies: logo ex={}", lex);
    }

    try {

        /*
         * If Math Slides not enabled within PITCHME.yaml, strip
         * Reveal.js math plugin file dependencies from zip.
         */
        if (yOpts == null || !yOpts.mathEnabled(pp)) {

            Path destPath = zipRoot.resolve(ZIP_ASSETS_DIR);
            String revealVersion = configuration.getString("gitpitch.dependency.revealjs");
            Path mathPluginPath = Paths.get(destPath.toString(), "reveal.js", revealVersion, "plugin/math");
            log.debug("fetchYAMLDependencies: removing mathPlugin={}", mathPluginPath);

            diskService.deepDelete(mathPluginPath.toFile());
        }

    } catch (Exception mex) {
        log.warn("fetchYAMLDependencies: math config assets ex={}", mex);
    }
}