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:org.niord.core.settings.SettingsService.java

public void setPath(String key, Path path) {
    set(key, path == null ? null : path.toAbsolutePath().toString());
}

From source file:com.liferay.blade.cli.command.CreateCommand.java

@Override
public void execute() throws Exception {
    CreateArgs createArgs = getArgs();/*from w  w w  . j  ava 2s.co m*/
    BladeCLI bladeCLI = getBladeCLI();

    if (createArgs.isListTemplates()) {
        _printTemplates();

        return;
    }

    String template = createArgs.getTemplate();

    if (template == null) {
        bladeCLI.error("The following option is required: [-t | --template]\n\n");
        bladeCLI.error("Availble project templates:\n\n");

        _printTemplates();

        return;
    } else if (template.equals("service")) {
        if (createArgs.getService() == null) {
            StringBuilder sb = new StringBuilder();

            sb.append("\"-t service <FQCN>\" parameter missing.");
            sb.append(System.lineSeparator());
            sb.append("Usage: blade create -t service -s <FQCN> <project name>");
            sb.append(System.lineSeparator());

            bladeCLI.error(sb.toString());

            return;
        }
    } else if (template.equals("fragment")) {
        boolean hasHostBundleBSN = false;

        if (createArgs.getHostBundleBSN() != null) {
            hasHostBundleBSN = true;
        }

        boolean hasHostBundleVersion = false;

        if (createArgs.getHostBundleVersion() != null) {
            hasHostBundleVersion = true;
        }

        if (!hasHostBundleBSN || !hasHostBundleVersion) {
            StringBuilder sb = new StringBuilder("\"-t fragment\" options missing:" + System.lineSeparator());

            if (!hasHostBundleBSN) {
                sb.append("Host Bundle BSN (\"-h\", \"--host-bundle-bsn\") is required.");
                sb.append(System.lineSeparator());
            }

            if (!hasHostBundleVersion) {
                sb.append("Host Bundle Version (\"-H\", \"--host-bundle-version\") is required.");
                sb.append(System.lineSeparator());
            }

            bladeCLI.printUsage("create", sb.toString());

            return;
        }
    } else if (template.equals("modules-ext")) {
        if ("maven".equals(createArgs.getProfileName())) {
            bladeCLI.error(
                    "Modules Ext projects are not supported with Maven build. Please use Gradle build instead.");

            return;
        }

        boolean hasOriginalModuleName = false;

        if (createArgs.getOriginalModuleName() != null) {
            hasOriginalModuleName = true;
        }

        if (!hasOriginalModuleName) {
            StringBuilder sb = new StringBuilder();

            sb.append("modules-ext options missing:");
            sb.append(System.lineSeparator());
            sb.append("\"-m\", \"--original-module-name\") is required.");
            sb.append(System.lineSeparator());
            sb.append(
                    "\"-M\", \"--original-module-version\") is required unless you have enabled target platform.");
            sb.append(System.lineSeparator());
            sb.append(System.lineSeparator());

            bladeCLI.printUsage("create", sb.toString());

            return;
        }
    }

    String name = createArgs.getName();

    if (BladeUtil.isEmpty(name)) {
        _addError("Create", "SYNOPSIS\n\t create [options] <[name]>");

        return;
    }

    if (!_isExistingTemplate(template)) {
        _addError("Create", "The template " + template + " is not in the list");

        return;
    }

    File dir;

    File argsDir = createArgs.getDir();

    if (argsDir != null) {
        dir = new File(argsDir.getAbsolutePath());
    } else if (template.startsWith("war") || template.equals("theme") || template.equals("layout-template")
            || template.equals("spring-mvc-portlet")) {

        dir = _getDefaultWarsDir();
    } else if (template.startsWith("modules-ext")) {
        dir = _getDefaultExtDir();
    } else {
        dir = _getDefaultModulesDir();
    }

    final File checkDir = new File(dir, name);

    if (!_checkDir(checkDir)) {
        _addError("Create", name + " is not empty or it is a file. Please clean or delete it then run again");

        return;
    }

    ProjectTemplatesArgs projectTemplatesArgs = getProjectTemplateArgs(createArgs, bladeCLI, template, name,
            dir);

    List<File> archetypesDirs = projectTemplatesArgs.getArchetypesDirs();

    Path customTemplatesPath = bladeCLI.getExtensionsPath();

    archetypesDirs.add(customTemplatesPath.toFile());

    execute(projectTemplatesArgs);

    Path path = dir.toPath();

    Path absolutePath = path.toAbsolutePath();

    absolutePath = absolutePath.normalize();

    bladeCLI.out("Successfully created project " + projectTemplatesArgs.getName() + " in " + absolutePath);
}

From source file:com.qwazr.library.archiver.ArchiverTool.java

public void extract_dir(final Path sourceDir, final String sourceExtension, final Path destDir,
        final Boolean logErrorAndContinue) throws IOException, ArchiveException {
    if (!Files.exists(sourceDir))
        throw new FileNotFoundException("The source directory does not exist: " + sourceDir.toAbsolutePath());
    if (!Files.exists(destDir))
        throw new FileNotFoundException(
                "The destination directory does not exist: " + destDir.toAbsolutePath());
    final Path[] sourceFiles;
    try (final Stream<Path> stream = Files.list(sourceDir)) {
        sourceFiles = stream.filter(p -> Files.isRegularFile(p)).toArray(Path[]::new);
    }/*from w  w  w .ja  v a2 s  .c om*/
    if (sourceFiles == null)
        return;
    for (final Path sourceFile : sourceFiles) {
        final String ext = FilenameUtils.getExtension(sourceFile.getFileName().toString());
        if (!sourceExtension.equals(ext))
            continue;
        try {
            extract(sourceFile, destDir);
        } catch (IOException | ArchiveException e) {
            if (logErrorAndContinue != null && logErrorAndContinue)
                LOGGER.log(Level.SEVERE, e, e::getMessage);
            else
                throw e;
        }
    }
}

From source file:org.apache.tika.eval.TikaEvalCLI.java

private void handleCompare(String[] subsetArgs) throws Exception {
    List<String> argList = new ArrayList(Arrays.asList(subsetArgs));

    boolean containsBC = false;
    String inputDir = null;/*from  w w  w  . ja  v  a 2 s  .co m*/
    String extractsA = null;
    String alterExtract = null;
    //confirm there's a batch-config file
    for (int i = 0; i < argList.size(); i++) {
        String arg = argList.get(i);
        if (arg.equals("-bc")) {
            containsBC = true;
        } else if (arg.equals("-inputDir")) {
            if (i + 1 >= argList.size()) {
                System.err.println("Must specify directory after -inputDir");
                ExtractComparer.USAGE();
                return;
            }
            inputDir = argList.get(i + 1);
            i++;
        } else if (arg.equals("-extractsA")) {
            if (i + 1 >= argList.size()) {
                System.err.println("Must specify directory after -extractsA");
                ExtractComparer.USAGE();
                return;
            }
            extractsA = argList.get(i + 1);
            i++;
        } else if (arg.equals("-alterExtract")) {
            if (i + 1 >= argList.size()) {
                System.err.println("Must specify type 'as_is', 'first_only' or "
                        + "'concatenate_content' after -alterExtract");
                ExtractComparer.USAGE();
                return;
            }
            alterExtract = argList.get(i + 1);
            i++;
        }
    }
    if (alterExtract != null && !alterExtract.equals("as_is") && !alterExtract.equals("concatenate_content")
            && !alterExtract.equals("first_only")) {
        System.out.println("Sorry, I don't understand:" + alterExtract
                + ". The values must be one of: as_is, first_only, concatenate_content");
        ExtractComparer.USAGE();
        return;
    }

    //need to specify each in the commandline that goes into tika-batch
    //if only extracts is passed to tika-batch,
    //the crawler will see no inputDir and start crawling "input".
    //if the user doesn't specify inputDir, crawl extractsA
    if (inputDir == null && extractsA != null) {
        argList.add("-inputDir");
        argList.add(extractsA);
    }

    Path tmpBCConfig = null;
    try {
        tmpBCConfig = Files.createTempFile("tika-eval", ".xml");
        if (!containsBC) {
            Files.copy(this.getClass().getResourceAsStream("/tika-eval-comparison-config.xml"), tmpBCConfig,
                    StandardCopyOption.REPLACE_EXISTING);
            argList.add("-bc");
            argList.add(tmpBCConfig.toAbsolutePath().toString());

        }
        String[] updatedArgs = argList.toArray(new String[argList.size()]);
        DefaultParser defaultCLIParser = new DefaultParser();
        try {
            CommandLine commandLine = defaultCLIParser.parse(ExtractComparer.OPTIONS, updatedArgs);
            if (commandLine.hasOption("db") && commandLine.hasOption("jdbc")) {
                System.out.println("Please specify either the default -db or the full -jdbc, not both");
                ExtractComparer.USAGE();
                return;
            }
        } catch (ParseException e) {
            System.out.println(e.getMessage() + "\n");
            ExtractComparer.USAGE();
            return;
        }

        FSBatchProcessCLI.main(updatedArgs);
    } finally {
        if (tmpBCConfig != null && Files.isRegularFile(tmpBCConfig)) {
            Files.delete(tmpBCConfig);
        }
    }
}

From source file:at.ac.tuwien.ims.latex2mobiformulaconv.converter.Converter.java

/**
 * Saves the html document to a file with .html extension
 *
 * @param document JDOM Document representing the HTML
 * @return written HTML File object/*  w ww.j  a  v  a2  s  .c om*/
 */
private File saveHtmlFile(Document document) {
    Path tempFilepath = null;

    Path tempDirPath = formulaConverter.getTempDirPath();

    ClassLoader classLoader = getClass().getClassLoader();
    InputStream mainCssIs = classLoader.getResourceAsStream(MAIN_CSS_FILENAME);

    logger.debug("Copying main.css file to temp dir: " + tempDirPath.toAbsolutePath().toString());
    try {
        Files.copy(mainCssIs, tempDirPath.resolve(MAIN_CSS_FILENAME));
    } catch (FileAlreadyExistsException e) {
        // do nothing
    } catch (IOException e) {
        logger.error("could not copy main.css file to temp dir!");
    }

    tempFilepath = tempDirPath.resolve("latex2mobi.html");

    logger.debug("tempFile created at: " + tempFilepath.toAbsolutePath().toString());
    try {
        Files.write(tempFilepath, new XMLOutputter().outputString(document).getBytes(Charset.forName("UTF-8")));

        if (debugMarkupOutput) {
            logger.info("Debug markup will be generated.");
        }

    } catch (IOException e) {
        logger.error("Error writing HTML to temp dir!");
        logger.error(e.getMessage(), e);
    }

    return tempFilepath.toFile();
}

From source file:org.apache.tika.eval.TikaEvalCLI.java

private void handleProfile(String[] subsetArgs) throws Exception {
    List<String> argList = new ArrayList(Arrays.asList(subsetArgs));

    boolean containsBC = false;
    String inputDir = null;//from  w  w w.jav  a  2  s .c  o  m
    String extracts = null;
    String alterExtract = null;
    //confirm there's a batch-config file
    for (int i = 0; i < argList.size(); i++) {
        String arg = argList.get(i);
        if (arg.equals("-bc")) {
            containsBC = true;
        } else if (arg.equals("-inputDir")) {
            if (i + 1 >= argList.size()) {
                System.err.println("Must specify directory after -inputDir");
                ExtractProfiler.USAGE();
                return;
            }
            inputDir = argList.get(i + 1);
            i++;
        } else if (arg.equals("-extracts")) {
            if (i + 1 >= argList.size()) {
                System.err.println("Must specify directory after -extracts");
                ExtractProfiler.USAGE();
                return;
            }
            extracts = argList.get(i + 1);
            i++;
        } else if (arg.equals("-alterExtract")) {
            if (i + 1 >= argList.size()) {
                System.err.println("Must specify type 'as_is', 'first_only' or "
                        + "'concatenate_content' after -alterExtract");
                ExtractComparer.USAGE();
                return;
            }
            alterExtract = argList.get(i + 1);
            i++;
        }
    }

    if (alterExtract != null && !alterExtract.equals("as_is") && !alterExtract.equals("concatenate_content")
            && !alterExtract.equals("first_only")) {
        System.out.println("Sorry, I don't understand:" + alterExtract
                + ". The values must be one of: as_is, first_only, concatenate_content");
        ExtractProfiler.USAGE();
        return;
    }

    //need to specify each in this commandline
    //if only extracts is passed to tika-batch,
    //the crawler will see no inputDir and start crawling "input".
    //this allows the user to specify either extracts or inputDir
    if (extracts == null && inputDir != null) {
        argList.add("-extracts");
        argList.add(inputDir);
    } else if (inputDir == null && extracts != null) {
        argList.add("-inputDir");
        argList.add(extracts);
    }

    Path tmpBCConfig = null;
    try {
        tmpBCConfig = Files.createTempFile("tika-eval-profiler", ".xml");
        if (!containsBC) {
            Files.copy(this.getClass().getResourceAsStream("/tika-eval-profiler-config.xml"), tmpBCConfig,
                    StandardCopyOption.REPLACE_EXISTING);
            argList.add("-bc");
            argList.add(tmpBCConfig.toAbsolutePath().toString());
        }

        String[] updatedArgs = argList.toArray(new String[argList.size()]);
        DefaultParser defaultCLIParser = new DefaultParser();
        try {
            CommandLine commandLine = defaultCLIParser.parse(ExtractProfiler.OPTIONS, updatedArgs);
            if (commandLine.hasOption("db") && commandLine.hasOption("jdbc")) {
                System.out.println("Please specify either the default -db or the full -jdbc, not both");
                ExtractProfiler.USAGE();
                return;
            }
        } catch (ParseException e) {
            System.out.println(e.getMessage() + "\n");
            ExtractProfiler.USAGE();
            return;
        }

        FSBatchProcessCLI.main(updatedArgs);
    } finally {
        if (tmpBCConfig != null && Files.isRegularFile(tmpBCConfig)) {
            Files.delete(tmpBCConfig);
        }
    }
}

From source file:org.apache.tika.eval.tokens.CommonTokenCountManager.java

private synchronized void tryToLoad(String langCode) {
    if (alreadyTriedToLoad.contains(langCode)) {
        return;//w w w  .ja  v a  2  s .  c o m
    }
    //check once more now that we're in a
    //synchronized block
    if (commonTokenMap.get(langCode) != null) {
        return;
    }
    InputStream is = null;
    Path p = null;
    if (commonTokensDir != null) {
        p = commonTokensDir.resolve(langCode);
    }

    try {
        if (p == null || !Files.isRegularFile(p)) {
            is = this.getClass().getResourceAsStream("/common_tokens/" + langCode);
        } else {
            is = Files.newInputStream(p);
        }

        if (is == null) {
            LOG.warn("Couldn't find common tokens file for: '" + langCode + "': " + p.toAbsolutePath());
            alreadyTriedToLoad.add(langCode);
            return;
        }

        Set<String> set = commonTokenMap.get(langCode);
        if (set == null) {
            set = new HashSet<>();
            commonTokenMap.put(langCode, set);
        }
        try (BufferedReader reader = new BufferedReader(new InputStreamReader(is, COMMON_TOKENS_CHARSET))) {
            alreadyTriedToLoad.add(langCode);
            String line = reader.readLine();
            while (line != null) {
                line = line.trim();
                if (line.startsWith("#")) {
                    line = reader.readLine();
                    continue;
                }
                //allow language models with, e.g. tab-delimited counts after the term
                String[] cols = line.split("\t");
                String t = cols[0].trim();
                if (t.length() > 0) {
                    set.add(t);
                }

                line = reader.readLine();
            }
        }
    } catch (IOException e) {
        LOG.warn("IOException trying to read: '" + langCode + "'");
    } finally {
        IOUtils.closeQuietly(is);
    }
}

From source file:com.facebook.buck.util.unarchive.UnzipTest.java

@Test
public void testExcludedEntriesNotExtracted() throws IOException {
    try (ZipArchive zipArchive = new ZipArchive(this.zipFile, true)) {
        zipArchive.add("1.bin", DUMMY_FILE_CONTENTS);
        zipArchive.add("subdir/2.bin", DUMMY_FILE_CONTENTS);
        zipArchive.addDir("emptydir");
    }//from w  w  w . j  av a  2s.  co  m

    ProjectFilesystem filesystem = TestProjectFilesystems.createProjectFilesystem(tmpFolder.getRoot());

    Path extractFolder = tmpFolder.newFolder();
    ImmutableSet<Path> result = ArchiveFormat.ZIP.getUnarchiver().extractArchive(zipFile.toAbsolutePath(),
            filesystem, extractFolder, Optional.empty(), new PatternsMatcher(ImmutableSet.of("subdir/2.bin")),
            ExistingFileMode.OVERWRITE);
    assertTrue(Files.exists(extractFolder.toAbsolutePath().resolve("1.bin")));
    assertTrue(Files.isDirectory(extractFolder.toAbsolutePath().resolve("emptydir")));
    assertEquals(ImmutableSet.of(extractFolder.resolve("1.bin")), result);
}

From source file:org.niord.core.repo.RepositoryService.java

/**
 * Resolves the relative repository path as a temporary repository path
 * and returns the full path to it./*w  w w .j av  a2 s  .c om*/
 * @param path the path to resolve and validate as a temporary repository path
 * @return the full path
 */
public Path validateTempRepoPath(String path) {
    // Validate that the path is a temporary repository folder path
    Path folder = getRepoRoot().resolve(path);
    if (!folder.toAbsolutePath().startsWith(getTempRepoRoot().toAbsolutePath())) {
        log.warn("Failed streaming file to temp root folder: " + folder);
        throw new WebApplicationException("Invalid upload folder: " + path, 403);
    }
    return folder;
}

From source file:ch.admin.suis.msghandler.common.MessageCollection.java

private List<File> directoryStreamToListOfFiles(DirectoryStream<Path> stream, long limit) {
    int processed = 0;
    List<File> envFiles = new ArrayList<>();
    for (Path path : stream) {
        processed++;//from w ww  .ja v a 2  s  . c  o  m
        if (processed > limit) {
            LOG.warn(
                    "This job has reached the maximum it could handle. Due to configuration, this job will be throttled. Configuration currently allows "
                            + Inbox.incomingMessageLimit + " messages.");
            break; // This allows to continue without breaking stuff
        }
        envFiles.add(new File(path.toAbsolutePath().toString()));
    }
    try {
        stream.close();
    } catch (IOException e) {
        LOG.error("Unable to close directory stream. " + e);
    }
    return new ArrayList<>(envFiles);
}