Example usage for java.nio.file Path toAbsolutePath

List of usage examples for java.nio.file Path toAbsolutePath

Introduction

In this page you can find the example usage for java.nio.file Path toAbsolutePath.

Prototype

Path toAbsolutePath();

Source Link

Document

Returns a Path object representing the absolute path of this path.

Usage

From source file:au.org.ands.vocabs.toolkit.provider.importer.SesameImporterProvider.java

/** Upload the RDF data into the Sesame repository.
 * @param taskInfo The TaskInfo object describing the entire task.
 * @param subtask The details of the subtask
 * @param results HashMap representing the result of the task.
 * @return True, iff the upload succeeded.
 *///from  ww w .ja v a 2 s. c  o  m
public final boolean uploadRDF(final TaskInfo taskInfo, final JsonNode subtask,
        final HashMap<String, String> results) {
    RepositoryManager manager = null;
    try {
        manager = RepositoryProvider.getRepositoryManager(sesameServer);

        String repositoryID = ToolkitFileUtils.getSesameRepositoryId(taskInfo);

        Repository repository = manager.getRepository(repositoryID);
        if (repository == null) {
            // Repository is missing. This is bad.
            logger.error("Sesame uploadRDF, repository missing");
            return false;
        }

        RepositoryConnection con = null;
        try {
            con = repository.getConnection();
            // If required, remove all existing triples
            if (subtask.get("clear") != null && subtask.get("clear").booleanValue()) {
                con.clear();
            }
            Path dir = Paths.get(ToolkitFileUtils.getTaskHarvestOutputPath(taskInfo));
            try (DirectoryStream<Path> stream = Files.newDirectoryStream(dir)) {
                for (Path entry : stream) {
                    File file = new File(entry.toString());
                    logger.debug("Full path:" + entry.toAbsolutePath().toString());
                    con.add(file, "", Rio.getParserFormatForFileName(entry.toString()));
                }
            } catch (DirectoryIteratorException | IOException ex) {
                // I/O error encountered during the iteration,
                // the cause is an IOException
                results.put(TaskStatus.EXCEPTION, "Exception in Sesame uploadRDF");
                logger.error("Exception in Sesame uploadRDF:", ex);
                return false;
            }
        } catch (RDFParseException e) {
            results.put(TaskStatus.EXCEPTION, "Exception in Sesame uploadRDF");
            logger.error("Sesame uploadRDF, error parsing RDF: ", e);
            return false;
        } finally {
            if (con != null) {
                con.close();
            }
        }

        return true;
    } catch (RepositoryConfigException | RepositoryException e) {
        results.put(TaskStatus.EXCEPTION, "Exception in Sesame uploadRDF");
        logger.error("Exception in Sesame uploadRDF()", e);
    }
    return false;
}

From source file:net.daboross.bukkitdev.skywars.world.WorldUnzipper.java

public void doWorldUnzip(Logger logger) throws StartupFailedException {
    Validate.notNull(logger, "Logger cannot be null");
    Path outputDir = Bukkit.getWorldContainer().toPath().resolve(Statics.BASE_WORLD_NAME);
    if (Files.exists(outputDir)) {
        return;//from  www  . java2s  .c  om
    }
    try {
        Files.createDirectories(outputDir);
    } catch (IOException e) {
        throw new StartupFailedException("Couldn't create directory " + outputDir.toAbsolutePath() + ".");
    }

    InputStream fis = WorldUnzipper.class.getResourceAsStream(Statics.ZIP_FILE_PATH);
    if (fis == null) {
        throw new StartupFailedException("Couldn't get resource.\nError creating world. Please delete "
                + Statics.BASE_WORLD_NAME + " and restart server.");
    }
    try {
        try (ZipInputStream zis = new ZipInputStream(fis)) {
            ZipEntry ze = zis.getNextEntry();
            while (ze != null) {
                String fileName = ze.getName();
                Path newFile = outputDir.resolve(fileName);
                Path parent = newFile.getParent();
                if (parent != null) {
                    Files.createDirectories(parent);
                }
                if (ze.isDirectory()) {
                    logger.log(Level.FINER, "Making dir {0}", newFile);
                    Files.createDirectories(newFile);
                } else if (Files.exists(newFile)) {
                    logger.log(Level.FINER, "Already exists {0}", newFile);
                } else {
                    logger.log(Level.FINER, "Copying {0}", newFile);
                    try (FileOutputStream fos = new FileOutputStream(newFile.toFile())) {
                        try {
                            int next;
                            while ((next = zis.read()) != -1) {
                                fos.write(next);
                            }
                            fos.flush();
                        } catch (IOException ex) {
                            logger.log(Level.WARNING, "Error copying file from zip", ex);
                            throw new StartupFailedException("Error creating world. Please delete "
                                    + Statics.BASE_WORLD_NAME + " and restart server.");
                        }
                        fos.close();
                    }
                }
                try {
                    ze = zis.getNextEntry();
                } catch (IOException ex) {
                    throw new StartupFailedException(
                            "Error getting next zip entry\nError creating world. Please delete "
                                    + Statics.BASE_WORLD_NAME + " and restart server.",
                            ex);
                }
            }
        }
    } catch (IOException | RuntimeException ex) {
        throw new StartupFailedException(
                "\nError unzipping world. Please delete " + Statics.BASE_WORLD_NAME + " and restart server.",
                ex);
    }
}

From source file:edu.si.sidora.tabularmetadata.webapp.integration.OperationIT.java

@Test
public void testUrlOperationWithHeaderDeclaration() throws IOException, SAXException {
    final Path dataFileLocation = createTempFile("testUrlOperationWithHeaderDeclaration", "-" + randomUUID());
    final List<String> lines = asList("1,2,3", "Kirk,Admiral,002", "McCoy,Doctor,567");
    write(dataFileLocation, lines, UTF_8);
    log.debug("Parsing file: {}", dataFileLocation);
    final Response r = client.resetQuery().query("url", "file://" + dataFileLocation.toAbsolutePath())
            .query("hasHeaders", "true").get();
    assertEquals(OK.getStatusCode(), r.getStatus());
    final String text = r.readEntity(String.class);
    log.trace("Got response: {}", text);
    assertXMLEqual(properResponse2, text);
    dataFileLocation.toFile().delete();//w  w w  .  j a  v  a 2  s  . com
}

From source file:org.craftercms.studio.impl.v1.deployment.EnvironmentStoreGitBranchDeployer.java

private void createPatch(Repository repository, String site, String path) {
    StringBuffer output = new StringBuffer();

    String tempPath = System.getProperty("java.io.tmpdir");
    if (tempPath == null) {
        tempPath = "temp";
    }/*from  www .ja v a2s.  c  o  m*/
    Path patchPath = Paths.get(tempPath, "patch" + site + ".bin");

    String gitPath = getGitPath(path);
    Process p = null;
    File file = patchPath.toAbsolutePath().normalize().toFile();
    try {
        ProcessBuilder pb = new ProcessBuilder();
        pb.command("git", "diff", "--binary", environment, "master", "--", gitPath);

        pb.redirectOutput(file);
        pb.directory(repository.getDirectory().getParentFile());
        p = pb.start();
        p.waitFor();
    } catch (Exception e) {
        logger.error("Error while creating patch for site: " + site + " path: " + path, e);
    }
}

From source file:org.sonarsource.scanner.cli.ConfTest.java

@Test
public void shouldLoadModuleConfiguration() throws Exception {
    Path projectHome = Paths
            .get(getClass().getResource("ConfTest/shouldLoadModuleConfiguration/project").toURI());
    args.setProperty("project.home", projectHome.toAbsolutePath().toString());

    Properties properties = conf.properties();

    assertThat(properties.getProperty("module1.sonar.projectName")).isEqualTo("Module 1");
    assertThat(properties.getProperty("module2.sonar.projectName")).isEqualTo("Module 2");
    assertThat(properties.getProperty("sonar.projectBaseDir")).isEqualTo(projectHome.toString());
}

From source file:de.hopmann.msc.slave.util.RCMDBuilder.java

public RCMDOutputReader start() throws IOException {

    List<String> commands = new ArrayList<String>();
    commands.add(rExecutablePath.toAbsolutePath().toString());
    commands.add("CMD");

    processCommands(commands);//from   w  w  w  .ja  va2 s .c  o  m

    if (targetLibraryPath != null) {
        commands.add("--library=" + targetLibraryPath.toAbsolutePath().toString());
    }

    commands.add(packagePath.toAbsolutePath().toString());

    ProcessBuilder cmdProcessBuilder = new ProcessBuilder(commands)
            .directory(workingDirectoryPath.toAbsolutePath().toFile()).redirectErrorStream(true);

    if (!sourceLibraryPaths.isEmpty()) {
        StringBuilder rlibs = new StringBuilder();

        for (Path libPath : sourceLibraryPaths) {
            if (rlibs.length() != 0) {
                // Add separator char
                rlibs.append(SystemUtils.IS_OS_WINDOWS ? ";" : ":");
            }
            rlibs.append(libPath.toAbsolutePath().toString());
        }
        Map<String, String> processEnvironment = cmdProcessBuilder.environment();
        processEnvironment.put(R_LIBS_ENVIR, rlibs.toString());
        processEnvironment.put(R_LANGUAGE_ENVIR, "en");
        processEnvironment.put(LC_ALL, "English");
        processEnvironment.put(CYQWIN_ENVIR, "nodosfilewarning");
        for (Entry<String, String> envirEntry : customEnvironment.entrySet()) {
            processEnvironment.put(envirEntry.getKey(), envirEntry.getValue());
        }
    }

    processEnvironment(cmdProcessBuilder.environment());

    final Process cmdProcess = cmdProcessBuilder.start();

    // BufferedReader processOut = new BufferedReader(
    // new InputStreamReader(installProcess.getInputStream()));
    // while (processOut.readLine() != null) { }

    // IOUtils.copy(installProcess.getInputStream(), System.out);

    return new RCMDOutputReader(cmdProcess, logPrintStream) {
        @Override
        public void close() throws IOException {
            try {
                cmdProcess.waitFor();// XXX or .destroy()?
            } catch (InterruptedException e) {

            }
            super.close();
        }
    };

}

From source file:org.codice.ddf.configuration.migration.SystemConfigurationMigration.java

private void copyDirectory(Path source, Path destination) throws MigrationException {
    try {// w  w w.j  a  v  a  2  s.  c o m
        FileUtils.copyDirectory(source.toFile(), destination.toFile());
    } catch (IOException e) {
        String message = String.format("Unable to copy [%s] to [%s].", source.toAbsolutePath().toString(),
                source.toAbsolutePath().toString());
        LOGGER.error(message, e);
        throw new MigrationException(message, e);
    }
}

From source file:dk.dma.ais.track.AisTrackServiceConfiguration.java

private InputStream aisBusConfiguration() throws IOException {
    InputStream is = null;//from  w w  w  . ja v  a  2 s.co  m

    if (!StringUtils.isBlank(aisBusXmlFileName)) {
        LOG.debug("Application properties say that aisbus.xml can be found in " + aisBusXmlFileName);

        Path aisBusXmlFile = Paths.get(aisBusXmlFileName);
        if (Files.exists(aisBusXmlFile) && Files.isReadable(aisBusXmlFile)
                && Files.isRegularFile(aisBusXmlFile)) {
            LOG.debug(aisBusXmlFileName
                    + " exists, is readable and regular. Using that for AisBus configuration.");
            LOG.info("Using " + aisBusXmlFile.toAbsolutePath().toString());
            is = Files.newInputStream(aisBusXmlFile);
        } else {
            LOG.debug(
                    "Application properties points to a file which does not exist or is not readable or regular.");
        }
    } else {
        LOG.debug("No location of aisbus.xml given in application properties.");
    }

    if (is == null) {
        LOG.info("Falling back to built-in default AisBus configuration.");
        is = ClassLoader.getSystemResourceAsStream("aisbus.xml");
    }

    return is;
}

From source file:org.apache.nifi.processors.standard.TestPutSFTP.java

@Test
public void testPutSFTPFile() throws IOException {
    emptyTestDirectory();/*from   w  w  w.j  a  v  a  2  s .  co  m*/

    Map<String, String> attributes = new HashMap<>();
    attributes.put("filename", "testfile.txt");

    putSFTPRunner.enqueue(Paths.get(testFile), attributes);
    putSFTPRunner.run();

    putSFTPRunner.assertTransferCount(PutSFTP.REL_SUCCESS, 1);

    //verify directory exists
    Path newDirectory = Paths.get(sshTestServer.getVirtualFileSystemPath() + "nifi_test/");
    Path newFile = Paths.get(sshTestServer.getVirtualFileSystemPath() + "nifi_test/testfile.txt");
    Assert.assertTrue("New directory not created.", newDirectory.toAbsolutePath().toFile().exists());
    Assert.assertTrue("New File not created.", newFile.toAbsolutePath().toFile().exists());
    putSFTPRunner.clearTransferState();
}

From source file:org.craftercms.studio.impl.v1.deployment.EnvironmentStoreGitDeployer.java

private void fetchFromRemote(String site, Repository repository) {
    try (Git git = new Git(repository)) {
        Path siteRepoPath = Paths.get(rootPath, "sites", site, ".git");
        Collection<Ref> refs = Git.lsRemoteRepository().setHeads(true).setTags(true)
                .setRemote(siteRepoPath.toAbsolutePath().toString()).call();
        FetchResult result = git.fetch().setRemote("work-area").setCheckFetchedObjects(true).call();

    } catch (GitAPIException e) {
        logger.error(/*  w w  w  .j  a va2 s.  c  o  m*/
                "Error while fetching updates for repository: " + repository.getDirectory().getAbsolutePath(),
                e);
    }
}