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.netflix.genie.common.internal.services.impl.JobArchiveServiceImpl.java

/**
 * {@inheritDoc}//w  ww.  jav  a 2s  .com
 */
@Override
public void archiveDirectory(final Path directory, final URI target) throws JobArchiveException {
    // TODO: This relies highly on convention. Might be nicer to better abstract with database
    //       record that points directly to where the manifest is or other solution?
    try {
        final JobDirectoryManifest manifest = new JobDirectoryManifest(directory);
        final Path manifestDirectoryPath = StringUtils.isBlank(JobArchiveService.MANIFEST_DIRECTORY) ? directory
                : directory.resolve(JobArchiveService.MANIFEST_DIRECTORY);
        if (Files.notExists(manifestDirectoryPath)) {
            Files.createDirectories(manifestDirectoryPath);
        } else if (!Files.isDirectory(manifestDirectoryPath)) {
            throw new JobArchiveException(manifestDirectoryPath
                    + " is not a directory. Unable to create job manifest. Unable to archive");
        }
        final Path manifestPath = manifestDirectoryPath.resolve(JobArchiveService.MANIFEST_NAME);
        Files.write(manifestPath, GenieObjectMapper.getMapper().writeValueAsBytes(manifest));
        log.debug("Wrote job directory manifest to {}", manifestPath);
    } catch (final IOException ioe) {
        throw new JobArchiveException("Unable to create job directory manifest. Unable to archive", ioe);
    }

    // Attempt to archive the job directory, now including the manifest file, using available implementations
    final String uriString = target.toString();
    for (final JobArchiver archiver : this.jobArchivers) {
        // TODO: Perhaps we should pass the manifest down to the archive implementations if they want to use it?
        if (archiver.archiveDirectory(directory, target)) {
            log.debug("Successfully archived job directory {} to {} using {}", directory.toString(), uriString,
                    archiver.getClass().getSimpleName());
            return;
        }
    }

    // For now archival is not considered critical so just log warning
    log.warn("Failed to archive job directory {} to {} using any of the available implementations",
            directory.toString(), uriString);
}

From source file:org.elasticsearch.xpack.core.ssl.SSLConfigurationReloaderTests.java

/**
 * Test the reloading of SSLContext whose trust config is backed by PEM certificate files.
 *///  www . ja  v a2s . co  m
public void testReloadingPEMTrustConfig() throws Exception {
    Path tempDir = createTempDir();
    Path clientCertPath = tempDir.resolve("testnode.crt");
    Path keyStorePath = tempDir.resolve("testnode.jks");
    Files.copy(getDataPath("/org/elasticsearch/xpack/security/transport/ssl/certs/simple/testnode.jks"),
            keyStorePath);
    //Our keystore contains two Certificates it can present. One build from the RSA keypair and one build from the EC keypair. EC is
    // used since it keyManager presents the first one in alias alphabetical order (and testnode_ec comes before testnode_rsa)
    Files.copy(getDataPath("/org/elasticsearch/xpack/security/transport/ssl/certs/simple/testnode_ec.crt"),
            clientCertPath);
    Settings settings = Settings.builder()
            .putList("xpack.ssl.certificate_authorities", clientCertPath.toString())
            .put("path.home", createTempDir()).build();
    Environment env = randomBoolean() ? null : TestEnvironment.newEnvironment(settings);
    // Create the MockWebServer once for both pre and post checks
    try (MockWebServer server = getSslServer(keyStorePath, "testnode")) {
        final Consumer<SSLContext> trustMaterialPreChecks = (context) -> {
            try (CloseableHttpClient client = HttpClients.custom().setSSLContext(context).build()) {
                privilegedConnect(
                        () -> client.execute(new HttpGet("https://localhost:" + server.getPort())).close());
            } catch (Exception e) {
                throw new RuntimeException("Exception connecting to the mock server", e);
            }
        };

        final Runnable modifier = () -> {
            try {
                Path updatedCert = tempDir.resolve("updated.crt");
                Files.copy(getDataPath(
                        "/org/elasticsearch/xpack/security/transport/ssl/certs/simple/testnode_updated.crt"),
                        updatedCert, StandardCopyOption.REPLACE_EXISTING);
                atomicMoveIfPossible(updatedCert, clientCertPath);
            } catch (Exception e) {
                throw new RuntimeException("failed to modify file", e);
            }
        };

        // Client doesn't trust the Server certificate anymore so SSLHandshake should fail
        final Consumer<SSLContext> trustMaterialPostChecks = (updatedContext) -> {
            try (CloseableHttpClient client = HttpClients.custom().setSSLContext(updatedContext).build()) {
                SSLHandshakeException sslException = expectThrows(SSLHandshakeException.class,
                        () -> privilegedConnect(() -> client
                                .execute(new HttpGet("https://localhost:" + server.getPort())).close()));
                assertThat(sslException.getCause().getMessage(), containsString("PKIX path building failed"));
            } catch (Exception e) {
                throw new RuntimeException("Error closing CloseableHttpClient", e);
            }
        };
        validateSSLConfigurationIsReloaded(settings, env, trustMaterialPreChecks, modifier,
                trustMaterialPostChecks);
    }
}

From source file:com.facebook.buck.jvm.java.JarDirectoryStepTest.java

@Test
public void timesAreSanitized() throws IOException {
    Path zipup = folder.newFolder("dir-zip");

    // Create a jar file with a file and a directory.
    Path subdir = zipup.resolve("dir");
    Files.createDirectories(subdir);
    Files.write(subdir.resolve("a.txt"), "cake".getBytes());
    Path outputJar = folder.getRoot().resolve("output.jar");
    JarDirectoryStep step = new JarDirectoryStep(new ProjectFilesystem(folder.getRoot()), outputJar,
            ImmutableSortedSet.of(zipup), /* main class */ null, /* manifest file */ null);
    ExecutionContext context = TestExecutionContext.newInstance();
    int returnCode = step.execute(context).getExitCode();
    assertEquals(0, returnCode);/*from w  w  w .ja  va2 s .c  o  m*/

    // Iterate over each of the entries, expecting to see all zeros in the time fields.
    assertTrue(Files.exists(outputJar));
    Date dosEpoch = new Date(ZipUtil.dosToJavaTime(ZipConstants.DOS_FAKE_TIME));
    try (ZipInputStream is = new ZipInputStream(new FileInputStream(outputJar.toFile()))) {
        for (ZipEntry entry = is.getNextEntry(); entry != null; entry = is.getNextEntry()) {
            assertEquals(entry.getName(), dosEpoch, new Date(entry.getTime()));
        }
    }
}

From source file:org.elasticsearch.xpack.core.ssl.SSLConfigurationReloaderTests.java

/**
 * Tests the reloading of SSLContext when a PEM key and certificate are used.
 *///w w  w  .  j a v  a 2  s  .  c  o m
public void testPEMKeyConfigReloading() throws Exception {
    Path tempDir = createTempDir();
    Path keyPath = tempDir.resolve("testnode.pem");
    Path updatedKeyPath = tempDir.resolve("testnode_updated.pem");
    Path certPath = tempDir.resolve("testnode.crt");
    Path updatedCertPath = tempDir.resolve("testnode_updated.crt");
    final Path clientTruststorePath = tempDir.resolve("testnode.jks");
    Files.copy(getDataPath("/org/elasticsearch/xpack/security/transport/ssl/certs/simple/testnode.pem"),
            keyPath);
    Files.copy(getDataPath("/org/elasticsearch/xpack/security/transport/ssl/certs/simple/testnode_updated.pem"),
            updatedKeyPath);
    Files.copy(getDataPath("/org/elasticsearch/xpack/security/transport/ssl/certs/simple/testnode_updated.crt"),
            updatedCertPath);
    Files.copy(getDataPath("/org/elasticsearch/xpack/security/transport/ssl/certs/simple/testnode.crt"),
            certPath);
    Files.copy(getDataPath("/org/elasticsearch/xpack/security/transport/ssl/certs/simple/testnode.jks"),
            clientTruststorePath);
    MockSecureSettings secureSettings = new MockSecureSettings();
    secureSettings.setString("xpack.ssl.secure_key_passphrase", "testnode");
    final Settings settings = Settings.builder().put("path.home", createTempDir()).put("xpack.ssl.key", keyPath)
            .put("xpack.ssl.certificate", certPath).setSecureSettings(secureSettings).build();
    final Environment env = randomBoolean() ? null
            : TestEnvironment.newEnvironment(Settings.builder().put("path.home", createTempDir()).build());
    // Load HTTPClient once. Client uses a keystore containing testnode key/cert as a truststore
    try (CloseableHttpClient client = getSSLClient(clientTruststorePath, "testnode")) {
        final Consumer<SSLContext> keyMaterialPreChecks = (context) -> {
            try (MockWebServer server = new MockWebServer(context, false)) {
                server.enqueue(new MockResponse().setResponseCode(200).setBody("body"));
                server.start();
                privilegedConnect(
                        () -> client.execute(new HttpGet("https://localhost:" + server.getPort())).close());
            } catch (Exception e) {
                throw new RuntimeException("Exception starting or connecting to the mock server", e);
            }
        };
        final Runnable modifier = () -> {
            try {
                atomicMoveIfPossible(updatedKeyPath, keyPath);
                atomicMoveIfPossible(updatedCertPath, certPath);
            } catch (Exception e) {
                throw new RuntimeException("failed to modify file", e);
            }
        };

        // The new server certificate is not in the client's truststore so SSLHandshake should fail
        final Consumer<SSLContext> keyMaterialPostChecks = (updatedContext) -> {
            try (MockWebServer server = new MockWebServer(updatedContext, false)) {
                server.enqueue(new MockResponse().setResponseCode(200).setBody("body"));
                server.start();
                SSLHandshakeException sslException = expectThrows(SSLHandshakeException.class,
                        () -> privilegedConnect(() -> client
                                .execute(new HttpGet("https://localhost:" + server.getPort())).close()));
                assertThat(sslException.getCause().getMessage(), containsString("PKIX path validation failed"));
            } catch (Exception e) {
                throw new RuntimeException("Exception starting or connecting to the mock server", e);
            }
        };
        validateSSLConfigurationIsReloaded(settings, env, keyMaterialPreChecks, modifier,
                keyMaterialPostChecks);
    }
}

From source file:io.github.swagger2markup.Swagger2MarkupConverter.java

/**
 * Converts the Swagger specification into the given {@code outputDirectory}.
 *
 * @param outputDirectory the output directory path
 *//*from  w ww . ja  v a  2s  .c  o m*/
public void toFolder(Path outputDirectory) {
    Validate.notNull(outputDirectory, "outputDirectory must not be null");

    context.setOutputPath(outputDirectory);

    applyOverviewDocument().writeToFile(outputDirectory.resolve(context.config.getOverviewDocument()),
            StandardCharsets.UTF_8);
    applyPathsDocument().writeToFile(outputDirectory.resolve(context.config.getPathsDocument()),
            StandardCharsets.UTF_8);
    applyDefinitionsDocument().writeToFile(outputDirectory.resolve(context.config.getDefinitionsDocument()),
            StandardCharsets.UTF_8);
    applySecurityDocument().writeToFile(outputDirectory.resolve(context.config.getSecurityDocument()),
            StandardCharsets.UTF_8);
}

From source file:org.elasticsearch.xpack.core.ssl.SSLConfigurationReloaderTests.java

/**
 * Tests reloading a keystore that is used in the KeyManager of SSLContext
 *///from  w w  w. j  a  va2  s  . c om
public void testReloadingKeyStore() throws Exception {
    final Path tempDir = createTempDir();
    final Path keystorePath = tempDir.resolve("testnode.jks");
    final Path updatedKeystorePath = tempDir.resolve("testnode_updated.jks");
    Files.copy(getDataPath("/org/elasticsearch/xpack/security/transport/ssl/certs/simple/testnode.jks"),
            keystorePath);
    Files.copy(getDataPath("/org/elasticsearch/xpack/security/transport/ssl/certs/simple/testnode_updated.jks"),
            updatedKeystorePath);
    MockSecureSettings secureSettings = new MockSecureSettings();
    secureSettings.setString("xpack.ssl.keystore.secure_password", "testnode");
    final Settings settings = Settings.builder().put("path.home", createTempDir())
            .put("xpack.ssl.keystore.path", keystorePath).setSecureSettings(secureSettings).build();
    final Environment env = randomBoolean() ? null : TestEnvironment.newEnvironment(settings);
    //Load HTTPClient only once. Client uses the same store as a truststore
    try (CloseableHttpClient client = getSSLClient(keystorePath, "testnode")) {
        final Consumer<SSLContext> keyMaterialPreChecks = (context) -> {
            try (MockWebServer server = new MockWebServer(context, true)) {
                server.enqueue(new MockResponse().setResponseCode(200).setBody("body"));
                server.start();
                privilegedConnect(
                        () -> client.execute(new HttpGet("https://localhost:" + server.getPort())).close());
            } catch (Exception e) {
                throw new RuntimeException("Exception starting or connecting to the mock server", e);
            }
        };

        final Runnable modifier = () -> {
            try {
                atomicMoveIfPossible(updatedKeystorePath, keystorePath);
            } catch (Exception e) {
                throw new RuntimeException("modification failed", e);
            }
        };

        // The new server certificate is not in the client's truststore so SSLHandshake should fail
        final Consumer<SSLContext> keyMaterialPostChecks = (updatedContext) -> {
            try (MockWebServer server = new MockWebServer(updatedContext, true)) {
                server.enqueue(new MockResponse().setResponseCode(200).setBody("body"));
                server.start();
                SSLHandshakeException sslException = expectThrows(SSLHandshakeException.class,
                        () -> privilegedConnect(() -> client
                                .execute(new HttpGet("https://localhost:" + server.getPort())).close()));
                assertThat(sslException.getCause().getMessage(), containsString("PKIX path validation failed"));
            } catch (Exception e) {
                throw new RuntimeException("Exception starting or connecting to the mock server", e);
            }
        };
        validateSSLConfigurationIsReloaded(settings, env, keyMaterialPreChecks, modifier,
                keyMaterialPostChecks);
    }
}

From source file:org.fao.geonet.api.records.formatters.FormatterApiIntegrationTest.java

@Test
public void testExecXslt() throws Exception {
    final ServletContext context = _applicationContext.getBean(ServletContext.class);
    MockHttpServletRequest request = new MockHttpServletRequest(context, "GET",
            "http://localhost:8080/geonetwork/srv/eng/md.formatter");
    request.getSession();//from  ww  w . j  av  a 2  s.c om
    request.setPathInfo("/eng/md.formatter");

    final String applicationContextAttributeKey = "srv";
    request.getServletContext().setAttribute(applicationContextAttributeKey, _applicationContext);
    ServletRequestAttributes requestAttributes = new ServletRequestAttributes(request);

    RequestContextHolder.setRequestAttributes(requestAttributes);
    final String formatterName = "xsl-test-formatter";
    final URL testFormatterViewFile = FormatterApiIntegrationTest.class
            .getResource(formatterName + "/view.xsl");
    final Path testFormatter = IO.toPath(testFormatterViewFile.toURI()).getParent();
    final Path formatterDir = this.dataDirectory.getFormatterDir();
    Files.deleteIfExists(formatterDir.resolve("functions.xsl"));
    IO.copyDirectoryOrFile(testFormatter, formatterDir.resolve(formatterName), false);
    IO.copyDirectoryOrFile(testFormatter.getParent().resolve("functions.xsl"), formatterDir, true);
    JeevesDelegatingFilterProxy.setApplicationContextAttributeKey(applicationContextAttributeKey);

    final MockHttpServletResponse response = new MockHttpServletResponse();
    formatService.exec("eng", "html", "" + id, null, formatterName, "true", false, _100,
            new ServletWebRequest(request, response));
    final String viewXml = response.getContentAsString();
    final Element view = Xml.loadString(viewXml, false);
    assertEqualsText("fromFunction", view, "*//p");
    assertEqualsText("Title", view, "*//div[@class='tr']");
}

From source file:org.fao.geonet.api.records.formatters.FormatterApiIntegrationTest.java

private String configureGroovyTestFormatter() throws URISyntaxException, IOException {
    final String formatterName = "groovy-test-formatter";
    final URL testFormatterViewFile = FormatterApiIntegrationTest.class
            .getResource(formatterName + "/view.groovy");
    final Path testFormatter = IO.toPath(testFormatterViewFile.toURI()).getParent();
    final Path formatterDir = this.dataDirectory.getFormatterDir();
    IO.copyDirectoryOrFile(testFormatter, formatterDir.resolve(formatterName), false);
    final String groovySharedClasses = "groovy";
    IO.copyDirectoryOrFile(testFormatter.getParent().resolve(groovySharedClasses),
            formatterDir.resolve(groovySharedClasses), false);

    final Path iso19139ConfigProperties = this.schemaManager.getSchemaDir("iso19139")
            .resolve("formatter/config.properties");
    Files.write(iso19139ConfigProperties, "dependsOn=dublin-core".getBytes("UTF-8"));

    final Path dublinCoreSchemaDir = this.schemaManager.getSchemaDir("dublin-core").resolve("formatter/groovy");
    Files.createDirectories(dublinCoreSchemaDir);
    IO.copyDirectoryOrFile(IO.toPath(//from www .  j a  v  a2  s .co  m
            FormatterApiIntegrationTest.class.getResource(formatterName + "/dublin-core-groovy").toURI()),
            dublinCoreSchemaDir.resolve("DCFunctions.groovy"), false);
    return formatterName;
}

From source file:org.bonitasoft.web.designer.repository.WidgetRepositoryTest.java

private Widget addToRepository(Widget widget) throws Exception {
    Path widgetDir = createDirectory(widgetDirectory.resolve(widget.getId()));
    writeWidgetMetadataInFile(widget, widgetDir.resolve(widget.getId() + ".json"));
    return getFromRepository(widget.getId());
}

From source file:org.fao.geonet.api.records.formatters.FormatterApiIntegrationTest.java

@Test(expected = AssertionError.class)
public void testGroovyUseEnvDuringConfigStage() throws Exception {
    MockHttpServletRequest r = new MockHttpServletRequest();
    r.getSession();//from w w w .j  a  v a 2  s  .co  m
    final ServletWebRequest webRequest = new ServletWebRequest(r, new MockHttpServletResponse());
    final FormatterParams fparams = new FormatterParams();
    fparams.context = this.serviceContext;
    fparams.webRequest = webRequest;
    // make sure context is cleared
    EnvironmentProxy.setCurrentEnvironment(fparams);

    final String formatterName = "groovy-illegal-env-access-formatter";
    final URL testFormatterViewFile = FormatterApiIntegrationTest.class
            .getResource(formatterName + "/view.groovy");
    final Path testFormatter = IO.toPath(testFormatterViewFile.toURI()).getParent();
    final Path formatterDir = this.dataDirectory.getFormatterDir();
    IO.copyDirectoryOrFile(testFormatter, formatterDir.resolve(formatterName), false);
    final String functionsXslName = "functions.xsl";
    Files.deleteIfExists(formatterDir.resolve(functionsXslName));
    IO.copyDirectoryOrFile(testFormatter.getParent().resolve(functionsXslName),
            formatterDir.resolve(functionsXslName), false);

    formatService.exec("eng", "html", "" + id, null, formatterName, null, null, _100, webRequest);
}