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.AsciidocConverterTest.java

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

    //When
    Swagger2MarkupConverter.from(file).build().toFolder(outputDirectory);

    //Then
    String[] files = outputDirectory.toFile().list();
    assertThat(files).hasSize(4).containsAll(expectedFiles);

    assertThat(new String(Files.readAllBytes(outputDirectory.resolve("overview.adoc"))))
            .doesNotContain("=== URI scheme");
}

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

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

    //When
    Swagger2MarkupConverter.from(file).build().toFolder(outputDirectory);

    //Then
    String[] files = outputDirectory.toFile().list();
    assertThat(files).hasSize(4).containsAll(expectedFiles);

    assertThat(new String(Files.readAllBytes(outputDirectory.resolve("overview.adoc"))))
            .contains("=== URI scheme");
}

From source file:eu.itesla_project.dymola.DymolaImpactAnalysis.java

private List<String> writeDymolaInputs(Path workingDir, List<Contingency> contingencies) throws IOException {
    LOGGER.info(" Start writing dymola inputs");

    List<String> retList = new ArrayList<>();

    DdbConfig ddbConfig = DdbConfig.load();
    String jbossHost = ddbConfig.getJbossHost();
    String jbossPort = ddbConfig.getJbossPort();
    String jbossUser = ddbConfig.getJbossUser();
    String jbossPassword = ddbConfig.getJbossPassword();

    Path dymolaExportPath = workingDir.resolve(MO_EXPORT_DIRECTORY);
    if (!Files.exists(dymolaExportPath)) {
        Files.createDirectory(dymolaExportPath);
    }//from  w ww  .j ava 2 s  . com

    //retrieve modelica export parameters from configuration
    String modelicaVersion = config.getModelicaVersion();
    String sourceEngine = config.getSourceEngine();
    String sourceVersion = config.getSourceEngineVersion();
    Path modelicaPowerSystemLibraryPath = Paths.get(config.getModelicaPowerSystemLibraryFile());

    //write the modelica events file, to feed the modelica exporter
    Path eventsPath = workingDir.resolve(MODELICA_EVENTS_CSV_FILENAME);
    writeModelicaExporterContingenciesFile(eventsPath, contingencies);

    //these are only optional params needed if the source is eurostag
    Path modelicaLibPath = null;

    String slackId = config.getSlackId();
    if ("".equals(slackId)) {
        slackId = null; // null when not specified ()
    }

    LoadFlowFactory loadFlowFactory;
    try {
        loadFlowFactory = config.getLoadFlowFactoryClass().newInstance();
    } catch (InstantiationException | IllegalAccessException e) {
        throw new RuntimeException(e);
    }

    LOGGER.info("Exporting modelica data for network {}, working state-id {} ", network,
            network.getStateManager().getWorkingStateId());
    ModelicaMainExporter exporter = new ModelicaMainExporter(network, slackId, jbossHost, jbossPort, jbossUser,
            jbossPassword, modelicaVersion, sourceEngine, sourceVersion, modelicaLibPath, loadFlowFactory);
    exporter.export(dymolaExportPath);
    ModEventsExport eventsExporter = new ModEventsExport(
            dymolaExportPath.resolve(network.getId() + ".mo").toFile(), eventsPath.toFile());
    eventsExporter.export(dymolaExportPath);
    LOGGER.info(" modelica data exported.");

    // now assemble the input files to feed dymola
    //  one .zip per contingency; in the zip, the .mo file and the powersystem library
    //TODO here it is assumed that contingencies ids in csv file start from 0 (i.e. 0 is the first contingency); id should be decoupled from the implementation
    try (final Stream<Path> pathStream = Files.walk(dymolaExportPath)) {
        pathStream.filter((p) -> !p.toFile().isDirectory() && p.toFile().getAbsolutePath().contains("events_")
                && p.toFile().getAbsolutePath().endsWith(".mo")).forEach(p -> {
                    GenericArchive archive = ShrinkWrap.createDomain().getArchiveFactory()
                            .create(GenericArchive.class);
                    try (FileSystem fileSystem = ShrinkWrapFileSystems.newFileSystem(archive)) {
                        Path rootDir = fileSystem.getPath("/");
                        Files.copy(modelicaPowerSystemLibraryPath,
                                rootDir.resolve(modelicaPowerSystemLibraryPath.getFileName()));
                        Files.copy(Paths.get(p.toString()),
                                rootDir.resolve(DymolaUtil.DYMOLA_SIM_MODEL_INPUT_PREFIX + ".mo"));

                        String[] c = p.getFileName().toString().replace(".mo", "").split("_");
                        try (OutputStream os = Files.newOutputStream(dymolaExportPath.getParent().resolve(
                                DymolaUtil.DYMOLAINPUTZIPFILENAMEPREFIX + "_" + c[c.length - 1] + ".zip"))) {
                            archive.as(ZipExporter.class).exportTo(os);
                            retList.add(new String(c[c.length - 1]));
                        } catch (IOException e) {
                            //e.printStackTrace();
                            throw new RuntimeException(e);
                        }

                    } catch (IOException e) {
                        throw new RuntimeException(e);
                    }

                });
    }
    retList.sort(Comparator.<String>naturalOrder());

    //prepare param inputs for indexes from indexes properties file
    LOGGER.info("writing input indexes parameters in  .mat format - start ");
    try {
        Path baseWp43ConfigFile = PlatformConfig.CONFIG_DIR.resolve(WP43_CONFIG_FILE_NAME);
        HierarchicalINIConfiguration configuration = new HierarchicalINIConfiguration(
                baseWp43ConfigFile.toFile());

        //fix params for smallsignal index (cfr EurostagImpactAnalysis sources)
        SubnodeConfiguration node = configuration.getSection("smallsignal");
        node.setProperty("f_instant", Double.toString(parameters.getFaultEventInstant()));
        for (int i = 0; i < contingencies.size(); i++) {
            Contingency contingency = contingencies.get(i);
            if (contingency.getElements().isEmpty()) {
                throw new AssertionError("Empty contingency " + contingency.getId());
            }
            Iterator<ContingencyElement> it = contingency.getElements().iterator();
            // compute the maximum fault duration
            double maxDuration = getFaultDuration(it.next());
            while (it.hasNext()) {
                maxDuration = Math.max(maxDuration, getFaultDuration(it.next()));
            }
            node.setProperty("f_duration", Double.toString(maxDuration));
        }

        DymolaAdaptersMatParamsWriter writer = new DymolaAdaptersMatParamsWriter(configuration);
        for (String cId : retList) {
            String parFileNamePrefix = DymolaUtil.DYMOLA_SIM_MAT_OUTPUT_PREFIX + "_" + cId + "_wp43_";
            String parFileNameSuffix = "_pars.mat";
            String zippedParFileNameSuffix = "_pars.zip";

            try (OutputStream os = Files.newOutputStream(dymolaExportPath.getParent()
                    .resolve(DymolaUtil.DYMOLAINPUTZIPFILENAMEPREFIX + "_" + cId + zippedParFileNameSuffix))) {
                JavaArchive archive = ShrinkWrap.create(JavaArchive.class);
                Path sfile1 = ShrinkWrapFileSystems.newFileSystem(archive).getPath("/");

                Arrays.asList(config.getIndexesNames()).forEach(indexName -> writer.write(indexName,
                        sfile1.resolve(parFileNamePrefix + indexName + parFileNameSuffix)));

                archive.as(ZipExporter.class).exportTo(os);
            } catch (Exception e) {
                throw new RuntimeException(e);
            }

        }

    } catch (ConfigurationException exc) {
        throw new RuntimeException(exc);
    }

    LOGGER.info("writing input indexes parameters in  .mat format - end - {}", retList);
    return retList;
}

From source file:SecurityWatch.java

public void watchVideoCamera(Path path) throws IOException, InterruptedException {

    watchService = FileSystems.getDefault().newWatchService();
    register(path, StandardWatchEventKinds.ENTRY_CREATE);

    OUTERMOST: while (true) {

        final WatchKey key = watchService.poll(11, TimeUnit.SECONDS);

        if (key == null) {
            System.out.println("The video camera is jammed - security watch system is canceled!");
            break;
        } else {/*from w ww  .  j a  va 2 s.co m*/

            for (WatchEvent<?> watchEvent : key.pollEvents()) {

                final Kind<?> kind = watchEvent.kind();

                if (kind == StandardWatchEventKinds.OVERFLOW) {
                    continue;
                }

                if (kind == StandardWatchEventKinds.ENTRY_CREATE) {

                    //get the filename for the event
                    final WatchEvent<Path> watchEventPath = (WatchEvent<Path>) watchEvent;
                    final Path filename = watchEventPath.context();
                    final Path child = path.resolve(filename);

                    if (Files.probeContentType(child).equals("image/jpeg")) {

                        //print it out the video capture time
                        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MMM-dd HH:mm:ss");
                        System.out.println("Video capture successfully at: " + dateFormat.format(new Date()));
                    } else {
                        System.out.println("The video camera capture format failed! This could be a virus!");
                        break OUTERMOST;
                    }
                }
            }

            boolean valid = key.reset();
            if (!valid) {
                break;
            }
        }
    }

    watchService.close();
}

From source file:de.tudarmstadt.ukp.dkpro.core.api.datasets.internal.actions.Explode.java

private void extract(ActionDescription aAction, Path aArchive, ArchiveInputStream aAStream, Path aTarget)
        throws IOException {
    // We always extract archives into a subfolder. Figure out the name of the folder.
    String base = getBase(aArchive.getFileName().toString());

    Map<String, Object> cfg = aAction.getConfiguration();
    int strip = cfg.containsKey("strip") ? (int) cfg.get("strip") : 0;

    AntFileFilter filter = new AntFileFilter(coerceToList(cfg.get("includes")),
            coerceToList(cfg.get("excludes")));

    ArchiveEntry entry = null;/*from ww w. ja va  2  s . c o  m*/
    while ((entry = aAStream.getNextEntry()) != null) {
        String name = stripLeadingFolders(entry.getName(), strip);

        if (name == null) {
            // Stripped to null - nothing left to extract - continue;
            continue;
        }

        if (filter.accept(name)) {
            Path out = aTarget.resolve(base).resolve(name);
            if (entry.isDirectory()) {
                Files.createDirectories(out);
            } else {
                Files.createDirectories(out.getParent());
                Files.copy(aAStream, out);
            }
        }
    }
}

From source file:io.github.swagger2markup.extensions.DynamicDocumentExtensionTest.java

@Test
public void testSwagger2AsciiDocExtensions() throws IOException, URISyntaxException {
    //Given/*from  w w w  . j a v a 2  s .  com*/
    Path file = Paths
            .get(DynamicDocumentExtensionTest.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(DynamicDocumentExtensionTest.class.getResourceAsStream("/config/asciidoc/config.properties"));
    Swagger2MarkupConfig config = new Swagger2MarkupConfigBuilder(properties).build();
    Swagger2MarkupExtensionRegistry registry = new Swagger2MarkupExtensionRegistryBuilder()
            //.withDefinitionsDocumentExtension(new DynamicDefinitionsDocumentExtension(Paths.get("src/test/resources/docs/asciidoc/extensions")))
            //.withPathsDocumentExtension(new DynamicPathsDocumentExtension(Paths.get("src/test/resources/docs/asciidoc/extensions")))
            .build();
    Swagger2MarkupConverter.from(file).withConfig(config).withExtensionRegistry(registry).build()
            .toFolder(outputDirectory);

    //Then
    assertThat(new String(Files.readAllBytes(outputDirectory.resolve("paths.adoc"))))
            .contains("Pet update request extension");
    assertThat(new String(Files.readAllBytes(outputDirectory.resolve("definitions.adoc"))))
            .contains("Pet extension");

}

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

private void testWithOutputLanguage(Language language, String outputFilename, String expected)
        throws IOException, URISyntaxException {
    //Given//from w  w  w .  j  a v a  2 s.c  om
    Path file = Paths.get(AsciidocConverterTest.class.getResource("/yaml/swagger_petstore.yaml").toURI());
    Path outputDirectory = Paths.get("build/test/asciidoc/language");
    FileUtils.deleteQuietly(outputDirectory.toFile());

    //When
    Swagger2MarkupConfig config = new Swagger2MarkupConfigBuilder().withOutputLanguage(language).build();
    Swagger2MarkupConverter.from(file).withConfig(config).build().toFolder(outputDirectory);

    //Then
    assertThat(
            new String(Files.readAllBytes(outputDirectory.resolve(outputFilename)), Charset.forName("UTF-8")))
                    .contains(expected);
}

From source file:com.fizzed.rocker.compiler.JavaGenerator.java

public File generate(TemplateModel model) throws GeneratorException, IOException {
    if (configuration.getOutputDirectory() == null) {
        throw new NullPointerException("Output dir was null");
    }/*from  w  w w  .  j a  va 2  s. c  o m*/

    if (model == null) {
        throw new NullPointerException("Model was null");
    }

    Path outputPath = configuration.getOutputDirectory().toPath();

    // append package path
    Path packagePath = RockerUtil.packageNameToPath(model.getPackageName());
    if (packagePath != null) {
        outputPath = outputPath.resolve(packagePath);
    }

    File buildDir = outputPath.toFile();
    if (!buildDir.exists()) {
        buildDir.mkdirs();
    }

    File outputFile = new File(buildDir, model.getName() + ".java");
    try (Writer w = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(outputFile), "UTF-8"))) {
        createSourceTemplate(model, w);
        w.flush();
    }

    return outputFile;
}

From source file:com.fizzed.blaze.ssh.impl.JschSftpSession.java

@Override
public List<SshFile> ls(Path path) throws SshException {
    try {//from  w w w  . j  a va 2  s.  c  o  m
        @SuppressWarnings("UseOfObsoleteCollectionType")
        java.util.Vector<Object> fileObjects = this.channel.ls(PathHelper.toString(path));

        List<SshFile> files = new ArrayList<>();

        for (Object fileObject : fileObjects) {
            LsEntry entry = (LsEntry) fileObject;

            // seems like filtering these out is useful
            if (entry.getFilename().equals(".") || entry.getFilename().equals("..")) {
                continue;
            }

            // workingDir + path + fileName
            Path entryPath = path.resolve(entry.getFilename()).normalize();

            files.add(new SshFile(entryPath, new JschFileAttributes(entry.getAttrs())));
        }

        return files;
    } catch (SftpException e) {
        throw convertSftpException(e);
    }
}

From source file:it.greenvulcano.configuration.BaseConfigurationManager.java

@Override
public void deploy(String name) throws XMLConfigException, FileNotFoundException {

    Path configurationArchivePath = getConfigurationPath(name);

    Path current = Paths.get(XMLConfig.getBaseConfigPath());
    Path staging = current.getParent().resolve("deploy");
    Path destination = current.getParent().resolve(name);

    if (LOCK.tryLock()) {

        if (Files.exists(configurationArchivePath) && !Files.isDirectory(configurationArchivePath)) {

            try {

                ZipInputStream configurationArchive = new ZipInputStream(
                        Files.newInputStream(configurationArchivePath, StandardOpenOption.READ));

                LOG.debug("Starting deploy of configuration " + name);
                ZipEntry zipEntry = null;

                for (Path cfgFile : Files.walk(current).collect(Collectors.toSet())) {

                    if (!Files.isDirectory(cfgFile)) {

                        Path target = staging.resolve(current.relativize(cfgFile));
                        Files.createDirectories(target);

                        Files.copy(cfgFile, target, StandardCopyOption.REPLACE_EXISTING);
                    }//from   w  w w.  j a v a  2s . com

                }

                LOG.debug("Staging new config " + name);

                while ((zipEntry = configurationArchive.getNextEntry()) != null) {

                    Path entryPath = staging.resolve(zipEntry.getName());

                    LOG.debug("Adding resource: " + entryPath);
                    if (zipEntry.isDirectory()) {
                        entryPath.toFile().mkdirs();
                    } else {

                        Path parent = entryPath.getParent();
                        if (!Files.exists(parent)) {
                            Files.createDirectories(parent);
                        }

                        Files.copy(configurationArchive, entryPath, StandardCopyOption.REPLACE_EXISTING);
                    }

                }

                //**** Deleting old config dir
                LOG.debug("Removing old config: " + current);
                Files.walk(current, FileVisitOption.FOLLOW_LINKS).sorted(Comparator.reverseOrder())
                        .map(java.nio.file.Path::toFile).forEach(File::delete);

                LOG.debug("Deploy new config " + name + " in path " + destination);
                Files.move(staging, destination, StandardCopyOption.ATOMIC_MOVE);

                setXMLConfigBasePath(destination.toString());
                LOG.debug("Deploy complete");
                deployListeners.forEach(l -> l.onDeploy(destination));

            } catch (Exception e) {

                if (Objects.nonNull(staging) && Files.exists(staging)) {
                    LOG.error("Deploy failed, rollback to previous configuration", e);
                    try {
                        Files.walk(staging, FileVisitOption.FOLLOW_LINKS).sorted(Comparator.reverseOrder())
                                .map(java.nio.file.Path::toFile).forEach(File::delete);

                        setXMLConfigBasePath(current.toString());
                    } catch (IOException | InvalidSyntaxException rollbackException) {
                        LOG.error("Failed to delete old configuration", e);
                    }
                } else {
                    LOG.error("Deploy failed", e);
                }

                throw new XMLConfigException("Deploy failed", e);
            } finally {
                LOCK.unlock();
            }
        } else {
            throw new FileNotFoundException(configurationArchivePath.toString());
        }
    } else {
        throw new IllegalStateException("A deploy is already in progress");
    }

}