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.qwazr.server.InFileSessionPersistenceManager.java

private void writeSession(final Path deploymentDir, final String sessionId,
        final PersistentSession persistentSession) {
    final Date expDate = persistentSession.getExpiration();
    if (expDate == null)
        return; // No expiry date? no serialization
    final Map<String, Object> sessionData = persistentSession.getSessionData();
    if (sessionData == null)
        return; // No sessionData? no serialization
    final File sessionFile = deploymentDir.resolve(sessionId).toFile();
    try (final ObjectOutputStream draftOutputStream = new ObjectOutputStream(new NullOutputStream())) {
        try (final ObjectOutputStream sessionOutputStream = new ObjectOutputStream(
                new FileOutputStream(sessionFile))) {
            sessionOutputStream.writeLong(expDate.getTime()); // The date is stored as long
            sessionData.forEach((attribute, object) -> writeSessionAttribute(draftOutputStream,
                    sessionOutputStream, attribute, object));
        }// w  w w .  j a v  a 2  s  .  c  o  m
    } catch (IOException | CancellationException e) {
        LOGGER.log(Level.SEVERE, e, () -> "Cannot save sessions in " + sessionFile);
    }
}

From source file:io.redlink.solrlib.embedded.EmbeddedCoreContainer.java

@Override
@SuppressWarnings({ "squid:S3725", "squid:S3776" })
protected synchronized void init(ExecutorService executorService) throws IOException {
    Preconditions.checkState(Objects.isNull(coreContainer), "Already initialized!");

    if (solrHome == null) {
        solrHome = Files.createTempDirectory("solr-home");
        log.debug("No solr-home set, using temp directory {}", solrHome);
        deleteOnShutdown = true;//  www  .  ja v a 2  s.  c o  m
    }

    final Path absoluteSolrHome = this.solrHome.toAbsolutePath();
    if (Files.isDirectory(absoluteSolrHome)) {
        log.trace("solr-home exists: {}", absoluteSolrHome);
    } else {
        Files.createDirectories(absoluteSolrHome);
        log.debug("Created solr-home: {}", absoluteSolrHome);
    }
    final Path lib = absoluteSolrHome.resolve("lib");
    if (Files.isDirectory(lib)) {
        log.trace("lib-directory exists: {}", lib);
    } else {
        Files.createDirectories(lib);
        log.debug("Created solr-lib directory: {}", lib);
    }

    final Path solrXml = absoluteSolrHome.resolve("solr.xml");
    if (!Files.exists(solrXml)) {
        log.info("no solr.xml found, creating new at {}", solrXml);
        try (PrintStream writer = new PrintStream(Files.newOutputStream(solrXml, StandardOpenOption.CREATE))) {
            writer.printf("<!-- Generated by %s on %tF %<tT -->%n", getClass().getSimpleName(), new Date());
            writer.println("<solr>");
            writer.printf("  <str name=\"%s\">%s</str>%n", "sharedLib", absoluteSolrHome.relativize(lib));
            writer.println("</solr>");
        }
    } else {
        log.trace("found solr.xml: {}", solrXml);
    }

    for (SolrCoreDescriptor coreDescriptor : coreDescriptors) {
        final String coreName = coreDescriptor.getCoreName();
        if (availableCores.containsKey(coreName)) {
            log.warn("CoreName-Clash: {} already initialized. Skipping {}", coreName,
                    coreDescriptor.getClass());
            continue;
        }
        final Path coreDir = absoluteSolrHome.resolve(coreName);
        Files.createDirectories(coreDir);
        coreDescriptor.initCoreDirectory(coreDir, lib);

        final Properties coreProperties = new Properties();
        final Path corePropertiesFile = coreDir.resolve("core.properties");
        if (Files.exists(corePropertiesFile)) {
            try (InputStream inStream = Files.newInputStream(corePropertiesFile, StandardOpenOption.CREATE)) {
                coreProperties.load(inStream);
            }
            log.debug("core.properties for {} found, updating", coreName);
        } else {
            log.debug("Creating new core {} in {}", coreName, coreDir);
        }
        coreProperties.setProperty("name", coreName);
        try (OutputStream outputStream = Files.newOutputStream(corePropertiesFile)) {
            coreProperties.store(outputStream, null);
        }

        if (coreDescriptor.getNumShards() > 1 || coreDescriptor.getReplicationFactor() > 1) {
            log.warn("Deploying {} to EmbeddedCoreContainer, ignoring config of shards={},replication={}",
                    coreName, coreDescriptor.getNumShards(), coreDescriptor.getReplicationFactor());
        }

        availableCores.put(coreName, coreDescriptor);
    }

    log.info("Starting {} in solr-home '{}'", getClass().getSimpleName(), absoluteSolrHome);
    coreContainer = CoreContainer.createAndLoad(absoluteSolrHome, solrXml);

    availableCores.values().forEach(coreDescriptor -> {
        final String coreName = coreDescriptor.getCoreName();
        try (SolrClient solrClient = createSolrClient(coreName)) {
            final NamedList<Object> coreStatus = CoreAdminRequest.getStatus(coreName, solrClient)
                    .getCoreStatus(coreName);
            final NamedList<Object> indexStatus = coreStatus == null ? null
                    : (NamedList<Object>) coreStatus.get("index");
            final Object lastModified = indexStatus == null ? null : indexStatus.get("lastModified");
            // lastModified is null if there was never a update
            scheduleCoreInit(executorService, coreDescriptor, lastModified == null);
        } catch (SolrServerException | IOException e) {
            if (log.isDebugEnabled()) {
                log.error("Error initializing core {}", coreName, e);
            }
            //noinspection ThrowableResultOfMethodCallIgnored
            coreInitExceptions.put(coreName, e);
        }
    });
}

From source file:io.mangoo.build.Watcher.java

@SuppressWarnings("all")
private void handleEvents(WatchKey watchKey, Path path) {
    for (WatchEvent<?> watchEvent : watchKey.pollEvents()) {
        WatchEvent.Kind<?> watchEventKind = watchEvent.kind();
        if (OVERFLOW.equals(watchEventKind)) {
            continue;
        }/*  ww w.  j  a v a 2  s . c o m*/

        WatchEvent<Path> ev = (WatchEvent<Path>) watchEvent;
        Path name = ev.context();
        Path child = path.resolve(name);

        if (ENTRY_MODIFY.equals(watchEventKind) && !child.toFile().isDirectory()) {
            handleNewOrModifiedFile(child);
        }

        if (ENTRY_CREATE.equals(watchEventKind)) {
            if (!child.toFile().isDirectory()) {
                handleNewOrModifiedFile(child);
            }
            try {
                if (Files.isDirectory(child, NOFOLLOW_LINKS)) {
                    registerAll(child);
                }
            } catch (IOException e) {
                LOG.error("Something fishy happened. Unable to register new dir for watching", e);
            }
        }
    }
}

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

@Test
public void testLoggingNullPointerBug() throws Exception {
    final org.apache.log4j.Logger logger = org.apache.log4j.Logger.getLogger(Geonet.FORMATTER);
    Level level = logger.getLevel();
    logger.setLevel(Level.ALL);/*from   ww w . j a va  2 s. c  om*/
    try {
        MockHttpServletRequest webRequest = new MockHttpServletRequest();
        webRequest.getSession();
        final ServletWebRequest request = new ServletWebRequest(webRequest, new MockHttpServletResponse());
        final FormatterParams fparams = new FormatterParams();
        fparams.context = this.serviceContext;
        fparams.webRequest = request;
        // make sure context is cleared
        EnvironmentProxy.setCurrentEnvironment(fparams);

        final String formatterName = "logging-null-pointer";
        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, request);

        // no Error is success
    } finally {
        logger.setLevel(level);
    }
}

From source file:com.facebook.buck.zip.UnzipTest.java

@Test
public void testExtractZipFilePreservesExecutePermissionsAndModificationTime() throws IOException {

    // getFakeTime returs time with some non-zero millis. By doing division and multiplication by
    // 1000 we get rid of that.
    final 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);/* w ww  .  j a  va2  s .c  o  m*/
        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 = Unzip.extractZipFile(zipFile.toAbsolutePath(), extractFolder.toAbsolutePath(),
            Unzip.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.gitpitch.services.OfflineService.java

private int processMarkdown(PitchParams pp, Path zipRoot, Optional<SlideshowModel> ssmo) {

    int status = STATUS_UNDEF;

    String consumed = null;//from  w w w  .ja v  a  2s  .c  o m
    Path mdOnlinePath = zipRoot.resolve(PITCHME_ONLINE_PATH);
    File mdOnlineFile = mdOnlinePath.toFile();

    if (mdOnlineFile.exists()) {

        GRSService grsService = grsManager.getService(grsManager.get(pp));

        MarkdownRenderer mrndr = MarkdownRenderer.build(pp, ssmo, grsService, diskService);

        MarkdownModel markdownModel = (MarkdownModel) markdownModelFactory.create(mrndr);

        try (Stream<String> stream = Files.lines(mdOnlinePath)) {

            consumed = stream.map(md -> {
                return markdownModel.offline(md);
            }).collect(Collectors.joining("\n"));

            Path mdOfflinePath = zipRoot.resolve(PITCHME_OFFLINE_PATH);
            Files.write(mdOfflinePath, consumed.getBytes());

            fetchOnlineAssets(pp, zipRoot);

            status = STATUS_OK;

        } catch (Exception mex) {
            log.warn("processMarkdown: ex={}", mex);
        }

    } else {
        log.warn("processMarkdown: mdOnline not found={}", mdOnlineFile);
    }

    log.debug("processMarkdown: returning status={}", status);
    return status;
}

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

@Test
public void entriesFromTheGivenManifestShouldOverrideThoseInTheJars() throws IOException {
    String expected = "1.4";
    // Write the manifest, setting the implementation version
    Path tmp = folder.newFolder();

    Manifest manifest = new Manifest();
    manifest.getMainAttributes().putValue(MANIFEST_VERSION.toString(), "1.0");
    manifest.getMainAttributes().putValue(IMPLEMENTATION_VERSION.toString(), expected);
    Path manifestFile = tmp.resolve("manifest");
    try (OutputStream fos = Files.newOutputStream(manifestFile)) {
        manifest.write(fos);/*from   ww w  . jav  a 2  s .c  om*/
    }

    // Write another manifest, setting the implementation version to something else
    manifest = new Manifest();
    manifest.getMainAttributes().putValue(MANIFEST_VERSION.toString(), "1.0");
    manifest.getMainAttributes().putValue(IMPLEMENTATION_VERSION.toString(), "1.0");

    Path input = tmp.resolve("input.jar");
    try (CustomZipOutputStream out = ZipOutputStreams.newOutputStream(input)) {
        ZipEntry entry = new ZipEntry("META-INF/MANIFEST.MF");
        out.putNextEntry(entry);
        manifest.write(out);
    }

    Path output = tmp.resolve("output.jar");
    JarDirectoryStep step = new JarDirectoryStep(new ProjectFilesystem(tmp), Paths.get("output.jar"),
            ImmutableSet.of(Paths.get("input.jar")), /* main class */ null, Paths.get("manifest"),
            /* merge manifest */ true, /* blacklist */ ImmutableSet.<String>of());
    ExecutionContext context = TestExecutionContext.newInstance();
    assertEquals(0, step.execute(context));

    try (Zip zip = new Zip(output, false)) {
        byte[] rawManifest = zip.readFully("META-INF/MANIFEST.MF");
        manifest = new Manifest(new ByteArrayInputStream(rawManifest));
        String version = manifest.getMainAttributes().getValue(IMPLEMENTATION_VERSION);

        assertEquals(expected, version);
    }
}

From source file:com.facebook.buck.io.ProjectFilesystemTest.java

@Test
public void testIsSymLinkReturnsTrueForSymLink() throws IOException {
    Path rootPath = tmp.getRoot();
    Files.createSymbolicLink(rootPath.resolve("foo"), rootPath.resolve("bar"));
    assertTrue(filesystem.isSymLink(Paths.get("foo")));
}

From source file:com.facebook.buck.zip.ZipStepTest.java

@Test
public void zipEntryOrderingIsFilesystemAgnostic() throws IOException {
    Path output = Paths.get("output");
    Path zipdir = Paths.get("zipdir");

    // Run the zip step on a filesystem with a particular ordering.
    FakeProjectFilesystem filesystem = new FakeProjectFilesystem();
    ExecutionContext context = TestExecutionContext.newInstance();
    filesystem.mkdirs(zipdir);//from w  ww .j  a  va 2 s.  c o  m
    filesystem.touch(zipdir.resolve("file1"));
    filesystem.touch(zipdir.resolve("file2"));
    ZipStep step = new ZipStep(filesystem, output, ImmutableSet.of(), false,
            ZipCompressionLevel.MIN_COMPRESSION_LEVEL, zipdir);
    assertEquals(0, step.execute(context).getExitCode());
    ImmutableList<String> entries1 = getEntries(filesystem, output);

    // Run the zip step on a filesystem with a different ordering.
    filesystem = new FakeProjectFilesystem();
    context = TestExecutionContext.newInstance();
    filesystem.mkdirs(zipdir);
    filesystem.touch(zipdir.resolve("file2"));
    filesystem.touch(zipdir.resolve("file1"));
    step = new ZipStep(filesystem, output, ImmutableSet.of(), false, ZipCompressionLevel.MIN_COMPRESSION_LEVEL,
            zipdir);
    assertEquals(0, step.execute(context).getExitCode());
    ImmutableList<String> entries2 = getEntries(filesystem, output);

    assertEquals(entries1, entries2);
}

From source file:com.spectralogic.ds3client.helpers.FileObjectPutter_Test.java

/**
 * This test cannot run on Windows without extra privileges
 *//*  w  w w. ja v a 2  s  .  c  o  m*/
@Test
public void testSymlink() throws IOException {
    assumeFalse(Platform.isWindows());
    final Path tempDir = Files.createTempDirectory("ds3_file_object_putter_");
    final Path tempPath = Files.createTempFile(tempDir, "temp_", ".txt");

    try {
        try (final SeekableByteChannel channel = Files.newByteChannel(tempPath, StandardOpenOption.CREATE,
                StandardOpenOption.TRUNCATE_EXISTING, StandardOpenOption.WRITE)) {
            channel.write(ByteBuffer.wrap(testData));
        }

        final Path symLinkPath = tempDir.resolve("sym_" + tempPath.getFileName().toString());
        Files.createSymbolicLink(symLinkPath, tempPath);

        getFileWithPutter(tempDir, symLinkPath);
    } finally {
        Files.deleteIfExists(tempPath);
        Files.deleteIfExists(tempDir);
    }
}