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.fizzed.stork.deploy.Archive.java

public Path unpack(Path unpackDir) throws IOException {
    Files.createDirectories(unpackDir);

    log.info("Unpacking {} to {}", file, unpackDir);

    // we need to know the top-level dir(s) created by unpack
    final Set<Path> firstLevelPaths = new LinkedHashSet<>();
    final AtomicInteger count = new AtomicInteger();

    try (ArchiveInputStream ais = newArchiveInputStream(file)) {
        ArchiveEntry entry;// w  w w .j ava  2  s. c o m
        while ((entry = ais.getNextEntry()) != null) {
            try {
                Path entryFile = Paths.get(entry.getName());
                Path resolvedFile = unpackDir.resolve(entryFile);

                firstLevelPaths.add(entryFile.getName(0));

                log.debug("{}", resolvedFile);

                if (entry.isDirectory()) {
                    Files.createDirectories(resolvedFile);
                } else {
                    unpackEntry(ais, resolvedFile);
                    count.incrementAndGet();
                }
            } catch (IOException | IllegalStateException | IllegalArgumentException e) {
                log.error("", e);
                throw new RuntimeException(e);
            }
        }
    }

    if (firstLevelPaths.size() != 1) {
        throw new IOException("Only archives with a single top-level directory are supported!");
    }

    Path assemblyDir = unpackDir.resolve(firstLevelPaths.iterator().next());

    log.info("Unpacked {} files to {}", count, assemblyDir);

    return assemblyDir;
}

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

public void testLocalPluginInstallWithBinAndConfig() throws Exception {
    String pluginName = "fake-plugin";
    Path pluginDir = createTempDir().resolve(pluginName);
    // create bin/tool and config/file
    Files.createDirectories(pluginDir.resolve("bin"));
    Files.createFile(pluginDir.resolve("bin").resolve("tool"));
    Files.createDirectories(pluginDir.resolve("config"));
    Files.createFile(pluginDir.resolve("config").resolve("file"));

    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 binDir = environment.binFile();
    Path pluginBinDir = binDir.resolve(pluginName);

    Path pluginConfigDir = environment.configFile().resolve(pluginName);
    assertStatusOk("install " + pluginUrl + " --verbose");

    terminal.getTerminalOutput().clear();
    assertStatusOk("list");
    assertThat(terminal.getTerminalOutput(), hasItem(containsString(pluginName)));

    assertDirectoryExists(pluginBinDir);
    assertDirectoryExists(pluginConfigDir);
    Path toolFile = pluginBinDir.resolve("tool");
    assertFileExists(toolFile);//w  w  w.jav a  2s .  co  m

    // check that the file is marked executable, without actually checking that we can execute it.
    PosixFileAttributeView view = Files.getFileAttributeView(toolFile, PosixFileAttributeView.class);
    // the view might be null, on e.g. windows, there is nothing to check there!
    if (view != null) {
        PosixFileAttributes attributes = view.readAttributes();
        assertThat(attributes.permissions(), hasItem(PosixFilePermission.OWNER_EXECUTE));
        assertThat(attributes.permissions(), hasItem(PosixFilePermission.OWNER_READ));
    }
}

From source file:org.balloon_project.overflight.task.importer.ImporterFileListener.java

@Override
public void run() {
    // TODO initial import start
    // initial import of existing file
    logger.info("Scanning for files to import");
    File importDir = new File(configuration.getDatabaseImportDirectory());
    if (importDir.exists() && importDir.isDirectory()) {
        for (File file : importDir.listFiles()) {
            if (file.isFile() && file.getPath().endsWith(IndexingTask.N_TRIPLES_EXTENSION)) {
                logger.info("File event: Adding " + file.toString() + " to importer queue");
                importer.startImporting(file);
            }//w  w  w.j ava 2 s  . co m
        }
    }

    // starting file watch service for future files
    try {
        String path = configuration.getDatabaseImportDirectory();
        logger.info("Starting import file listener for path " + path);
        Path tmpPath = Paths.get(path);
        WatchService watchService = FileSystems.getDefault().newWatchService();
        tmpPath.register(watchService, StandardWatchEventKinds.ENTRY_CREATE);

        for (;;) {
            WatchKey key = watchService.take();

            for (WatchEvent event : key.pollEvents()) {
                if (event.kind().name() == "OVERFLOW") {
                    continue;
                } else {
                    WatchEvent<Path> ev = (WatchEvent<Path>) event;
                    Path filename = ev.context();
                    logger.info("File event: Adding " + filename.toString() + " to importer queue");
                    importer.startImporting(tmpPath.resolve(filename).toFile());
                }
            }

            // Reset the key -- this step is critical if you want to
            // receive further watch events.  If the key is no longer valid,
            // the directory is inaccessible so exit the loop.
            boolean valid = key.reset();
            if (!valid) {
                break;
            }

        }
    } catch (IOException | InterruptedException e) {
        e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
    } finally {
        logger.debug("Stopping import file listener");
    }
}

From source file:org.pentaho.marketplace.domain.services.BaPluginService.java

private void writeResourceToFolder(URL resourceUrl, Path destinationFolder) {
    try {//from  www  .  ja va  2s.com
        InputStream inputStream = resourceUrl.openConnection().getInputStream();
        String fileName = FilenameUtils.getName(resourceUrl.toString());
        Path destinationFile = destinationFolder.resolve(fileName);
        Files.copy(inputStream, destinationFile, StandardCopyOption.REPLACE_EXISTING);
    } catch (IOException e) {
        this.getLogger().error(
                "Error copying " + resourceUrl.toString() + " to destination folder " + destinationFolder, e);
    }
}

From source file:com.netflix.nicobar.core.persistence.PathArchiveRepository.java

@Override
public void insertArchive(JarScriptArchive jarScriptArchive) throws IOException {
    Objects.requireNonNull(jarScriptArchive, "jarScriptArchive");
    ScriptModuleSpec moduleSpec = jarScriptArchive.getModuleSpec();
    ModuleId moduleId = moduleSpec.getModuleId();
    Path moduleDir = rootDir.resolve(moduleId.toString());
    if (Files.exists(moduleDir)) {
        FileUtils.deleteDirectory(moduleDir.toFile());
    }/* w w  w.  java 2s  .  c  om*/
    JarFile jarFile;
    try {
        jarFile = new JarFile(jarScriptArchive.getRootUrl().toURI().getPath());
    } catch (URISyntaxException e) {
        throw new IOException(e);
    }
    try {
        Enumeration<JarEntry> entries = jarFile.entries();
        while (entries.hasMoreElements()) {
            JarEntry jarEntry = entries.nextElement();
            Path entryName = moduleDir.resolve(jarEntry.getName());
            if (jarEntry.isDirectory()) {
                Files.createDirectories(entryName);
            } else {
                InputStream inputStream = jarFile.getInputStream(jarEntry);
                try {
                    Files.copy(inputStream, entryName);
                } finally {
                    IOUtils.closeQuietly(inputStream);
                }
            }
        }
    } finally {
        IOUtils.closeQuietly(jarFile);
    }
    // write the module spec
    String serialized = moduleSpecSerializer.serialize(moduleSpec);
    Files.write(moduleDir.resolve(moduleSpecSerializer.getModuleSpecFileName()),
            serialized.getBytes(Charsets.UTF_8));

    // update the timestamp on the module directory to indicate that the module has been updated
    Files.setLastModifiedTime(moduleDir, FileTime.fromMillis(jarScriptArchive.getCreateTime()));
}

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

private Path findLocDir(String lang, Path baseLoc) throws IOException {
    Path locDir = baseLoc.resolve(lang);
    if (!Files.exists(locDir)) {
        locDir = baseLoc.resolve(Geonet.DEFAULT_LANGUAGE);
    }/*from   ww w.  j ava 2s.c  om*/
    if (!Files.exists(locDir) && Files.exists(baseLoc)) {
        try (DirectoryStream<Path> paths = Files.newDirectoryStream(baseLoc)) {
            final Iterator<Path> pathIterator = paths.iterator();
            if (pathIterator.hasNext()) {
                locDir = pathIterator.next();
            }
        }
    }
    return locDir;
}

From source file:eu.itesla_project.eurostag.EurostagImpactAnalysis.java

private Command before(SimulationState state, Set<String> contingencyIds, Path workingDir,
        List<Contingency> contingencies) throws IOException {
    // dump state info for debugging
    if (config.isDebug()) {
        Networks.dumpStateId(workingDir, state.getName());
    }//from   w  w w  .j  a v a  2s.  c  om

    try (OutputStream os = Files.newOutputStream(workingDir.resolve(PRE_FAULT_SAC_GZ_FILE_NAME))) {
        os.write(((EurostagState) state).getSacGz());
    }

    Supplier<Domain> domain = Suppliers.memoize(ShrinkWrap::createDomain);
    if (!config.isUseBroadcast()) {
        Files.write(workingDir.resolve(DDB_DICT_GENS_CSV), ((EurostagState) state).getDictGensCsv());

        try (OutputStream os = Files.newOutputStream(workingDir.resolve(LIMITS_ZIP_FILE_NAME))) {
            writeLimits(domain.get(), os);
        }
    }

    Command cmd;
    if (contingencyIds == null) {
        // take all contingencies
        contingencies.addAll(allContingencies);
        cmd = allCmd;

        if (config.isUseBroadcast()) {
            // all scenarios zip file has already been sent in the common dir
        } else {
            try (OutputStream os = Files.newOutputStream(workingDir.resolve(ALL_SCENARIOS_ZIP_FILE_NAME))) {
                writeAllScenarios(domain.get(), os);
            }
            try (OutputStream os = Files.newOutputStream(workingDir.resolve(WP43_ALL_CONFIGS_ZIP_FILE_NAME))) {
                writeAllWp43Configs(domain.get(), os);
            } catch (ConfigurationException e) {
                throw new RuntimeException(e);
            }
        }
    } else {
        // filter contingencies
        for (Contingency c : contingenciesProvider.getContingencies(network)) {
            if (contingencyIds.contains(c.getId())) {
                contingencies.add(c);
            }
        }
        cmd = subsetCmd;

        // write scenarios subset in the working dir
        try (OutputStream os = Files.newOutputStream(workingDir.resolve(PARTIAL_SCENARIOS_ZIP_FILE_NAME))) {
            writeScenarios(domain.get(), contingencies, os);
        }
        try (OutputStream os = Files.newOutputStream(workingDir.resolve(WP43_PARTIAL_CONFIGS_ZIP_FILE_NAME))) {
            writeWp43Configs(domain.get(), contingencies, os);
        } catch (ConfigurationException e) {
            throw new RuntimeException(e);
        }
    }

    return cmd;
}

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

/**
 * @deprecated support for this is not going to stick around, seriously.
 *//*w  w w  .j a  v  a 2s .com*/
@Deprecated
public void testAlreadyInstalledNotIsolated() throws Exception {
    String pluginName = "fake-plugin";
    Path pluginDir = createTempDir().resolve(pluginName);
    Files.createDirectories(pluginDir);
    // create a jar file in the plugin
    Path pluginJar = pluginDir.resolve("fake-plugin.jar");
    try (ZipOutputStream out = new JarOutputStream(
            Files.newOutputStream(pluginJar, StandardOpenOption.CREATE))) {
        out.putNextEntry(new ZipEntry("foo.class"));
        out.closeEntry();
    }
    String pluginUrl = createPlugin(pluginDir, "description", "fake desc", "name", pluginName, "version", "1.0",
            "elasticsearch.version", Version.CURRENT.toString(), "java.version",
            System.getProperty("java.specification.version"), "isolated", "false", "jvm", "true", "classname",
            "FakePlugin");

    // install
    ExitStatus status = new PluginManagerCliParser(terminal).execute(args("install " + pluginUrl));
    assertEquals("unexpected exit status: output: " + terminal.getTerminalOutput(), ExitStatus.OK, status);

    // install again
    status = new PluginManagerCliParser(terminal).execute(args("install " + pluginUrl));
    List<String> output = terminal.getTerminalOutput();
    assertEquals("unexpected exit status: output: " + output, ExitStatus.IO_ERROR, status);
    boolean foundExpectedMessage = false;
    for (String line : output) {
        foundExpectedMessage |= line.contains("already exists");
    }
    assertTrue(foundExpectedMessage);
}

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

Element getStrings(Path appPath, String lang) throws IOException, JDOMException {
    Path baseLoc = appPath.resolve("loc");
    Path locDir = findLocDir(lang, baseLoc);
    if (Files.exists(locDir)) {
        return Xml.loadFile(locDir.resolve("xml").resolve("strings.xml"));
    }/* w  ww.  j a va2s .co  m*/
    return new Element("strings");
}

From source file:desktopsearch.WatchDir.java

/**
 * Process all events for keys queued to the watcher
 */// w w  w .j  a  va2 s  . c om
void processEvents() {
    for (;;) {

        // wait for key to be signalled
        WatchKey key;
        try {
            key = watcher.take();
        } catch (InterruptedException x) {
            return;
        }

        Path dir = keys.get(key);
        if (dir == null) {
            System.err.println("WatchKey not recognized!!");
            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);

            // 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 (Exception x) {
                    // ignore to keep sample readbale
                }
            }

            // print out event
            //System.out.format("%s: %s\n", event.kind().name(), child);
            try {
                UpdateDB(event.kind().name(), child);
            } catch (Exception e) {
                e.printStackTrace();
            }

        }

        // 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;
            }
        }
    }
}