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:fll.web.FullTournamentTest.java

/**
 * Load the teams from testDataConnection.
 * /*  w w  w .  ja  v  a 2  s . c  o  m*/
 * @param testDataConnection where to get the teams from
 * @param outputDirectory where to write the teams file, may be null in which
 *          case a temp file will be used
 * @throws IOException
 * @throws SQLException
 * @throws InterruptedException 
 */
private void loadTeams(final Connection testDataConnection, final Tournament sourceTournament,
        final Path outputDirectory) throws IOException, SQLException, InterruptedException {

    final Path teamsFile = outputDirectory.resolve(sanitizeFilename(sourceTournament.getName()) + "_teams.csv");
    // write the teams out to a file
    try (final Writer writer = new FileWriter(teamsFile.toFile())) {
        try (final CSVWriter csvWriter = new CSVWriter(writer)) {
            csvWriter.writeNext(new String[] { "team_name", "team_number", "affiliation", "award_group",
                    "judging_group", "tournament" });
            final Map<Integer, TournamentTeam> sourceTeams = Queries.getTournamentTeams(testDataConnection,
                    sourceTournament.getTournamentID());
            for (final Map.Entry<Integer, TournamentTeam> entry : sourceTeams.entrySet()) {
                final TournamentTeam team = entry.getValue();

                csvWriter.writeNext(new String[] { team.getTeamName(), Integer.toString(team.getTeamNumber()),
                        team.getOrganization(), team.getAwardGroup(), team.getJudgingGroup(),
                        sourceTournament.getName() });
            }
        }
    }

    IntegrationTestUtils.loadPage(selenium, TestUtils.URL_ROOT + "admin/");

    selenium.findElement(By.id("teams_file")).sendKeys(teamsFile.toAbsolutePath().toString());

    selenium.findElement(By.id("upload_teams")).click();

    IntegrationTestUtils.assertNoException(selenium);

    // skip past the filter page
    selenium.findElement(By.id("next")).click();
    IntegrationTestUtils.assertNoException(selenium);

    // team column selection
    new Select(selenium.findElement(By.name("TeamNumber"))).selectByValue("team_number");
    new Select(selenium.findElement(By.name("TeamName"))).selectByValue("team_name");
    new Select(selenium.findElement(By.name("Organization"))).selectByValue("affiliation");
    new Select(selenium.findElement(By.name("tournament"))).selectByValue("tournament");
    new Select(selenium.findElement(By.name("event_division"))).selectByValue("award_group");
    new Select(selenium.findElement(By.name("judging_station"))).selectByValue("judging_group");
    selenium.findElement(By.id("next")).click();
    IntegrationTestUtils.assertNoException(selenium);
    Assert.assertTrue(IntegrationTestUtils.isElementPresent(selenium, By.id("success")));
}

From source file:com.boundlessgeo.geoserver.AppIntegrationTest.java

@Test
public void testWorkspaceExport() throws Exception {
    MockHttpServletResponse response = doWorkspaceExport("sf");

    assertEquals("application/zip", response.getContentType());
    assertEquals("attachment; filename=\"sf.zip\"", response.getHeader("Content-Disposition"));

    Path tmp = Files.createTempDirectory(Paths.get("target"), "export");
    org.geoserver.data.util.IOUtils.decompress(new ByteArrayInputStream(response.getContentAsByteArray()),
            tmp.toFile());//from   w w  w .  ja v a  2s  .  c  om

    assertTrue(tmp.resolve("bundle.json").toFile().exists());
}

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

private void extract7z(ActionDescription aAction, Path aCachedFile, Path aTarget)
        throws IOException, RarException {
    // We always extract archives into a subfolder. Figure out the name of the folder.
    String base = getBase(aCachedFile.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")));

    try (SevenZFile archive = new SevenZFile(aCachedFile.toFile())) {
        SevenZArchiveEntry entry = archive.getNextEntry();
        while (entry != null) {
            String name = stripLeadingFolders(entry.getName(), strip);

            if (name == null) {
                // Stripped to null - nothing left to extract - continue;
                continue;
            }/*from  w  ww  .  java 2s.c  o m*/

            if (filter.accept(name)) {
                Path out = aTarget.resolve(base).resolve(name);
                if (entry.isDirectory()) {
                    Files.createDirectories(out);
                } else {
                    Files.createDirectories(out.getParent());
                    try (OutputStream os = Files.newOutputStream(out)) {
                        InputStream is = new SevenZEntryInputStream(archive, entry);
                        IOUtils.copyLarge(is, os);
                    }
                }
            }

            entry = archive.getNextEntry();
        }
    }
}

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

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

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

    //Then
    String[] files = outputDirectory.toFile().list();
    expectedFiles.add("operations");
    assertThat(files).hasSize(5).containsAll(expectedFiles);

    Path pathsDirectory = outputDirectory.resolve("operations");
    String[] paths = pathsDirectory.toFile().list();
    assertThat(paths).hasSize(18);
}

From source file:codes.writeonce.maven.plugins.soy.CompileMojo.java

private void generateJs(List<Path> soyFiles, List<Path> xliffFiles, byte[] sourceDigestBytes)
        throws IOException, NoSuchAlgorithmException {

    final Path outputRootPath = jsOutputDirectory.toPath();

    FileUtils.deleteDirectory(jsOutputDirectory);
    Files.createDirectories(outputRootPath);

    FileUtils.deleteDirectory(javaOutputDirectory);

    final Path javaSourceOutputPath = getJavaSourceOutputPath();
    Files.createDirectories(javaSourceOutputPath);

    final SoyFileSet soyFileSet = getSoyFileSet(soyFiles);

    if (xliffFiles.isEmpty()) {
        getLog().info("No translations detected. Using default messages.");
        generateJs(soyFiles, soyFileSet, null, outputRootPath);
    } else {//from ww w.j  a  v  a  2s .com
        final SoyMsgBundleHandler smbh = new SoyMsgBundleHandler(new XliffMsgPlugin());
        for (final Path xliffFilePath : xliffFiles) {
            final SoyMsgBundle smb = smbh.createFromFile(translations.toPath().resolve(xliffFilePath).toFile());
            final Path outputPath = Utils.removeSuffix(outputRootPath.resolve(xliffFilePath), XLIFF_EXTENSION);
            generateJs(soyFiles, soyFileSet, smb, outputPath);
        }
    }

    final ImmutableMap<String, String> parseInfo = SoyFileSetAccessor.generateParseInfo(soyFileSet, javaPackage,
            javaClassNameSource.getValue());

    final Charset classSourceCharset;
    if (StringUtils.isEmpty(javaOutputCharsetName)) {
        classSourceCharset = Charset.defaultCharset();
        getLog().warn("Using platform encoding (" + classSourceCharset.displayName()
                + " actually) to generate SOY sources, i.e. build is platform dependent!");
    } else {
        classSourceCharset = Charset.forName(javaOutputCharsetName);
    }

    for (final Map.Entry<String, String> entry : parseInfo.entrySet()) {
        final String classFileName = entry.getKey();
        final String classSource = entry.getValue();
        try (FileOutputStream out = new FileOutputStream(javaSourceOutputPath.resolve(classFileName).toFile());
                OutputStreamWriter writer = new OutputStreamWriter(out, classSourceCharset)) {
            writer.write(classSource);
        }
    }

    final byte[] targetDigestBytes = getGeneratedFilesDigest();

    final Path statusFilePath = getStatusFilePath();
    Files.createDirectories(statusFilePath.getParent());
    try (FileOutputStream out = new FileOutputStream(statusFilePath.toFile());
            OutputStreamWriter outputStreamWriter = new OutputStreamWriter(out, TEXT_DIGEST_CHARSET);
            BufferedWriter writer = new BufferedWriter(outputStreamWriter)) {
        writer.write(Hex.encodeHex(sourceDigestBytes));
        writer.newLine();
        writer.write(Hex.encodeHex(targetDigestBytes));
        writer.newLine();
    }
}

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

private void extractRar(ActionDescription aAction, Path aCachedFile, Path aTarget)
        throws IOException, RarException {
    // We always extract archives into a subfolder. Figure out the name of the folder.
    String base = getBase(aCachedFile.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")));

    try (Archive archive = new Archive(new FileVolumeManager(aCachedFile.toFile()))) {
        FileHeader fh = archive.nextFileHeader();
        while (fh != null) {
            String name = stripLeadingFolders(fh.getFileNameString(), strip);

            if (name == null) {
                // Stripped to null - nothing left to extract - continue;
                continue;
            }//from www.ja  v  a2s  . c  om

            if (filter.accept(name)) {
                Path out = aTarget.resolve(base).resolve(name);
                if (fh.isDirectory()) {
                    Files.createDirectories(out);
                } else {
                    Files.createDirectories(out.getParent());
                    try (OutputStream os = Files.newOutputStream(out)) {
                        archive.extractFile(fh, os);
                    }
                }
            }

            fh = archive.nextFileHeader();
        }
    }
}

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

@Test
public void testWithSeparatedDefinitions() throws IOException, URISyntaxException {
    //Given//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/generated");
    FileUtils.deleteQuietly(outputDirectory.toFile());

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

    //Then
    String[] files = outputDirectory.toFile().list();
    expectedFiles.add("definitions");
    assertThat(files).hasSize(5).containsAll(expectedFiles);

    Path definitionsDirectory = outputDirectory.resolve("definitions");
    String[] definitions = definitionsDirectory.toFile().list();
    assertThat(definitions).hasSize(5)
            .containsAll(asList("Category.adoc", "Order.adoc", "Pet.adoc", "Tag.adoc", "User.adoc"));
}

From source file:io.gravitee.gateway.services.localregistry.LocalApiDefinitionRegistry.java

@Override
protected void doStart() throws Exception {
    if (enabled) {
        super.doStart();

        this.init();

        executor = Executors.newSingleThreadExecutor(r -> new Thread(r, "registry-monitor"));
        executor.execute(() -> {//from   ww w.  ja v a2s  .c  om
            Path registry = Paths.get(registryPath);
            LOGGER.info("Start local registry monitor for directory {}", registry);

            try {
                WatchService watcher = registry.getFileSystem().newWatchService();
                registry.register(watcher, StandardWatchEventKinds.ENTRY_CREATE,
                        StandardWatchEventKinds.ENTRY_DELETE, StandardWatchEventKinds.ENTRY_MODIFY);

                while (true) {
                    WatchKey key;
                    try {
                        key = watcher.take();
                    } catch (InterruptedException ex) {
                        return;
                    }

                    for (WatchEvent<?> event : key.pollEvents()) {
                        WatchEvent.Kind<?> kind = event.kind();

                        @SuppressWarnings("unchecked")
                        WatchEvent<Path> ev = (WatchEvent<Path>) event;
                        Path fileName = registry.resolve(ev.context().getFileName());

                        LOGGER.info("An event occurs for file {}: {}", fileName, kind.name());

                        if (kind == StandardWatchEventKinds.ENTRY_MODIFY) {
                            Api loadedDefinition = loadDefinition(fileName.toFile());
                            Api existingDefinition = definitions.get(fileName);
                            if (existingDefinition != null) {
                                if (apiManager.get(existingDefinition.getId()) != null) {
                                    apiManager.update(loadedDefinition);
                                } else {
                                    apiManager.undeploy(existingDefinition.getId());
                                    definitions.remove(fileName);
                                    apiManager.deploy(loadedDefinition);
                                    definitions.put(fileName, loadedDefinition);
                                }
                            }
                        } else if (kind == StandardWatchEventKinds.ENTRY_CREATE) {
                            Api loadedDefinition = loadDefinition(fileName.toFile());
                            Api existingDefinition = apiManager.get(loadedDefinition.getId());
                            if (existingDefinition != null) {
                                apiManager.update(loadedDefinition);
                            } else {
                                apiManager.deploy(loadedDefinition);
                                definitions.put(fileName, loadedDefinition);
                            }
                        } else if (kind == StandardWatchEventKinds.ENTRY_DELETE) {
                            Api existingDefinition = definitions.get(fileName);
                            if (existingDefinition != null
                                    && apiManager.get(existingDefinition.getId()) != null) {
                                apiManager.undeploy(existingDefinition.getId());
                                definitions.remove(fileName);
                            }
                        }

                        boolean valid = key.reset();
                        if (!valid) {
                            break;
                        }
                    }
                }
            } catch (IOException ioe) {
                LOGGER.error("Unexpected error while looking for PI definitions from filesystem", ioe);
            }
        });
    }
}

From source file:nextflow.fs.dx.DxFileSystemProvider.java

/**
 * Implements the *copy* operation using the DnaNexus API *clone*
 *
 *
 * <p>/*  w  w  w. jav  a 2s .co m*/
 * See clone https://wiki.dnanexus.com/API-Specification-v1.0.0/Cloning#API-method%3A-%2Fclass-xxxx%2Fclone
 *
 * @param source
 * @param target
 * @param options
 * @throws IOException
 */

@Override
public void copy(Path source, Path target, CopyOption... options) throws IOException {

    List<CopyOption> opts = Arrays.asList(options);
    boolean targetExists = Files.exists(target);

    if (targetExists) {
        if (Files.isRegularFile(target)) {
            if (opts.contains(StandardCopyOption.REPLACE_EXISTING)) {
                Files.delete(target);
            } else {
                throw new FileAlreadyExistsException("Copy failed -- target file already exists: " + target);
            }

        } else if (Files.isDirectory(target)) {
            target = target.resolve(source.getFileName());
        } else {
            throw new UnsupportedOperationException();
        }
    }

    String name1 = source.getFileName().toString();
    String name2 = target.getFileName().toString();
    if (!name1.equals(name2)) {
        throw new UnsupportedOperationException(
                "Copy to a file with a different name is not supported: " + source.toString());
    }

    final DxPath dxSource = toDxPath(source);
    final DxFileSystem dxFileSystem = dxSource.getFileSystem();
    dxFileSystem.fileCopy(dxSource, toDxPath(target));
}

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

private void readSecurityIndexes(List<Contingency> contingencies, Path workingDir, ImpactAnalysisResult result)
        throws IOException {
    long start = System.currentTimeMillis();
    int files = 0;
    //TODO TSO INDEXES HANDLING
    for (int i = 0; i < contingencies.size(); i++) {
        Contingency contingency = contingencies.get(i);
        String prefixFile = DymolaUtil.DYMOLA_SIM_MAT_OUTPUT_PREFIX + "_" + i;
        for (String securityIndexFileName : Arrays.asList(
                prefixFile + WP43_SMALLSIGNAL_SECURITY_INDEX_FILE_NAME,
                prefixFile + WP43_TRANSIENT_SECURITY_INDEX_FILE_NAME,
                prefixFile + WP43_OVERLOAD_SECURITY_INDEX_FILE_NAME,
                prefixFile + WP43_UNDEROVERVOLTAGE_SECURITY_INDEX_FILE_NAME)) {
            Path file = workingDir.resolve(
                    securityIndexFileName.replace(Command.EXECUTION_NUMBER_PATTERN, Integer.toString(i)));
            LOGGER.info("reading indexes output from file  {} ", file);
            if (Files.exists(file)) {
                try (BufferedReader reader = Files.newBufferedReader(file, StandardCharsets.UTF_8)) {
                    for (SecurityIndex index : SecurityIndexParser.fromXml(contingency.getId(), reader)) {
                        result.addSecurityIndex(index);
                    }//from   www .  jav a2 s. co  m
                }
                files++;
            }
        }
        //TODO
        // also scan errors in output
        //EurostagUtil.searchErrorMessage(workingDir.resolve(FAULT_OUT_GZ_FILE_NAME.replace(Command.EXECUTION_NUMBER_PATTERN, Integer.toString(i))), result.getMetrics(), i);
    }
    LOGGER.trace("{} security indexes files read in {} ms", files, (System.currentTimeMillis() - start));
}