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.codice.ddf.catalog.content.impl.FileSystemStorageProvider.java

@SuppressFBWarnings
public void setBaseContentDirectory(final String baseDirectory) throws IOException {

    Path directory;//ww w . j av  a2s.c o  m
    if (!baseDirectory.isEmpty()) {
        String path = FilenameUtils.normalize(baseDirectory);
        try {
            directory = Paths.get(path, DEFAULT_CONTENT_REPOSITORY, DEFAULT_CONTENT_STORE);
        } catch (InvalidPathException e) {
            path = System.getProperty(KARAF_HOME);
            directory = Paths.get(path, DEFAULT_CONTENT_REPOSITORY, DEFAULT_CONTENT_STORE);
        }
    } else {
        String path = System.getProperty("karaf.home");
        directory = Paths.get(path, DEFAULT_CONTENT_REPOSITORY, DEFAULT_CONTENT_STORE);
    }

    Path directories;
    if (!Files.exists(directory)) {
        directories = Files.createDirectories(directory);
        LOGGER.debug("Setting base content directory to: {}", directories.toAbsolutePath().toString());
    } else {
        directories = directory;
    }

    Path tmpDirectories;
    Path tmpDirectory = Paths.get(directories.toAbsolutePath().toString(), DEFAULT_TMP);
    if (!Files.exists(tmpDirectory)) {
        tmpDirectories = Files.createDirectories(tmpDirectory);
        LOGGER.debug("Setting base content directory to: {}", tmpDirectory.toAbsolutePath().toString());
    } else {
        tmpDirectories = tmpDirectory;
    }

    this.baseContentDirectory = directories;
    this.baseContentTmpDirectory = tmpDirectories;
}

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

/**
 * Converts a single input file from LaTeX to Mobi
 *
 * @return Path of the resulting File/*from   w w w. j a v a  2s  . com*/
 * @throws FileNotFoundException when there's no file at the inputPath location
 */
public Path convert() throws FileNotFoundException {
    // Currently only the first input path will be evaluated
    File inputFile = inputPaths.get(0).toFile();

    final String fullFilePath = inputFile.toPath().toAbsolutePath().toString();

    if (Files.exists(inputPaths.get(0))) {
        logger.debug("Input file found: " + fullFilePath);

    } else {
        throw new FileNotFoundException("Input file could not be found at: " + fullFilePath);
    }

    // set default title
    if (title == null) {
        title = inputFile.getName();
    }

    // Main Document conversion to HTML, without formulas
    logger.debug("Converting main document to HTML...");
    Document document = latexToHtmlConverter.convert(inputFile, title);

    logger.info("Parsing LaTeX formulas from resulting HTML...");

    Map<Integer, Formula> formulaMap = new HashMap<>();

    formulaConverter.setGenerateDebugMarkup(debugMarkupOutput);

    Map<Integer, String> latexFormulas = formulaConverter.extractFormulas(document);

    if (latexFormulas.isEmpty() == false) {
        Iterator<Integer> it = latexFormulas.keySet().iterator();
        while (it.hasNext()) {
            Integer id = it.next();
            String latexFormula = latexFormulas.get(id);

            Formula formula = formulaConverter.parse(id, latexFormula);

            if (formula != null) {
                formulaMap.put(id, formula);
            }
        }
        document = formulaConverter.replaceFormulas(document, formulaMap);
    }

    // Persisting markup
    File htmlFile = saveHtmlFile(document);

    Path markupDir = null;

    // markup is requested or implicit output
    if (exportMarkup || noMobiConversion) {
        markupDir = exportMarkup(htmlFile.toPath());
    }

    if (noMobiConversion) {
        // no mobi file will be generated in any way, just the markup
        return markupDir.toAbsolutePath();
    } else {
        // Convert to MOBI format
        logger.info("Converting completed HTML to MOBI format...");
        File mobiFile = htmlToMobiConverter.convertToMobi(htmlFile);

        // Save file
        Path resultFilepath = null;
        try {
            // Don't overwrite files
            Path outputFilepath;
            int i = 1;
            String replaceFilename = filename + FILE_EXTENSION;
            while (true) {
                outputFilepath = outputPath.resolve(replaceFilename);
                if (Files.exists(outputFilepath) == false) {
                    break;
                }
                replaceFilename = filename + " (" + i + ")" + FILE_EXTENSION;
                i++;
            }

            resultFilepath = Files.move(mobiFile.toPath(), outputFilepath);
            logger.debug("Mobi file moved to: " + resultFilepath.toAbsolutePath().toString());
            return resultFilepath.toAbsolutePath();

        } catch (IOException e) {
            logger.error("Error writing or moving output file");
            logger.error(e.getMessage(), e);
            return null;
        }
    }
}

From source file:org.holodeckb2b.deliverymethod.file.AbstractFileDeliverer.java

/**
 * Helper method to copy a the payload content to <i>delivery directory</i>.
 * //from ww w.j  a  v a  2  s . c  om
 * @param p         The payload for which the content must be copied
 * @param msgId     The message-id of the message that contains the payload, used for name the file
 * @return          The path where the payload content is now stored
 * @throws IOException  When the payload content could not be copied to the <i>delivery directory</i>
 */
private Path copyPayloadFile(IPayload p, String msgId) throws IOException {
    // If payload was external to message, it is not processed by Holodeck B2B, so no content to move
    if (IPayload.Containment.EXTERNAL == p.getContainment())
        return null;

    // Compose a file name for the payload file, based on msgId and href 
    String plRef = p.getPayloadURI();
    plRef = (plRef == null || plRef.isEmpty() ? "body" : plRef);
    // If this was a attachment the reference is a a MIME Content-id. As these are also quite lengthy we shorten 
    // it to the left part
    if (plRef.indexOf("@") > 0)
        plRef = plRef.substring(0, plRef.indexOf("@"));

    Path sourcePath = Paths.get(p.getContentLocation());
    // Try to set nice extension based on MIME Type of payload
    String mimeType = p.getMimeType();
    if (mimeType == null || mimeType.isEmpty()) {
        // No MIME type given in message, try to detect from content
        try {
            mimeType = Utils.detectMimeType(sourcePath.toFile());
        } catch (IOException ex) {
            mimeType = null;
        } // Unable to detect the MIME Type                        
    }
    String ext = Utils.getExtension(mimeType);

    Path targetPath = Paths.get(Utils.preventDuplicateFileName(directory + "pl-"
            + (msgId + "-" + plRef).replaceAll("[^a-zA-Z0-9.-]", "_") + (ext != null ? ext : "")));

    try {
        Files.copy(sourcePath, targetPath, StandardCopyOption.REPLACE_EXISTING);
    } catch (Exception ex) {
        // Can not move payload file -> delivery not possible
        throw new IOException("Unable to deliver message because payload file [" + p.getContentLocation()
                + "] can not be moved!", ex);
    }

    return targetPath.toAbsolutePath();
}

From source file:modules.NativeProcessIterativeDaemonModule.java

protected String extractNative(String command, String options, Path path) throws NativeExecutionException {
    if (command == null || command.equals("")) {
        System.err.println("command null at GeneralNativeCommandModule.extractNative()");
        return null;
    }/*from   w w w . ja  v  a 2 s.co m*/
    CommandLine commandLine = new CommandLine(command);

    if (options != null && !options.equals("")) {
        String[] args = options.split(" ");
        commandLine.addArguments(args);
    }

    if (path != null) {
        commandLine.addArgument(path.toAbsolutePath().toString(), false);
    }
    DefaultExecutor executor = new DefaultExecutor();
    ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
    PumpStreamHandler streamHandler = new PumpStreamHandler(outputStream);
    executor.setStreamHandler(streamHandler);
    GeneralExecutableModuleConfig generalExecutableModuleConfig = getConfig();
    executor.setWatchdog(new ExecuteWatchdog(generalExecutableModuleConfig.timeout));
    if (getConfig().workingDirectory != null && getConfig().workingDirectory.exists()) {
        executor.setWorkingDirectory(getConfig().workingDirectory);
    }
    try {

        // System.out.println("Now execute " + commandLine);
        executor.execute(commandLine);
    } catch (ExecuteException xs) {
        NativeExecutionException n = new NativeExecutionException();
        n.initCause(xs);
        if (path != null) {
            n.path = path.toAbsolutePath().toString();
        }
        n.executionResult = outputStream.toString();
        n.exitCode = xs.getExitValue();
        throw n;
    } catch (IOException xs) {
        NativeExecutionException n = new NativeExecutionException();
        n.initCause(xs);
        if (path != null) {
            n.path = path.toAbsolutePath().toString();
        }
        n.executionResult = outputStream.toString();
        throw n;
    }
    return outputStream.toString().trim();
}

From source file:org.ng200.openolympus.cerberus.compilers.GNUCompiler.java

@Override
public void compile(final List<Path> inputFiles, final Path outputFile,
        final Map<String, Object> additionalParameters) throws CompilationException {
    GNUCompiler.logger.debug("Compiling {} to {} using GCC", inputFiles, outputFile);

    final CommandLine commandLine = new CommandLine("g++");
    commandLine.setSubstitutionMap(additionalParameters);

    this.arguments.forEach((arg) -> commandLine.addArgument(arg));

    commandLine.addArgument("-w"); // Prohibit warnings because they screw
    // up error detection

    commandLine.addArgument("-o");
    commandLine.addArgument(MessageFormat.format("\"{0}\"", outputFile.toAbsolutePath().toString())); // Set outuput file

    inputFiles.forEach((file) -> commandLine
            .addArguments(MessageFormat.format("\"{0}\"", file.toAbsolutePath().toString()))); // Add
    // input//from  ww  w  .  j a v  a  2s. c  o  m
    // files

    GNUCompiler.logger.debug("Running GCC with arguments: {}", Arrays.asList(commandLine.getArguments()));

    final DefaultExecutor executor = new DefaultExecutor();
    executor.setExitValues(new int[] { 0, 1 });

    final ByteArrayOutputStream errorStream = new ByteArrayOutputStream();
    executor.setStreamHandler(new PumpStreamHandler(null, errorStream, null));

    executor.setWatchdog(new ExecuteWatchdog(20000));// 20 seconds to
    // compile
    int result;
    try {
        result = executor.execute(commandLine);
    } catch (final IOException e) {
        GNUCompiler.logger.error("Could not execute GCC: {}", e);
        throw new CompilationException("Could not execute GCC", e);
    }

    switch (result) {
    case 0:
        return;
    case 1:
        try {
            String errorString = errorStream.toString(StandardCharsets.UTF_8.name());

            final Pattern pattern = Pattern.compile(
                    "^(" + inputFiles.stream().map(file -> Pattern.quote(file.toAbsolutePath().toString()))
                            .collect(Collectors.joining("|")) + "):",
                    Pattern.MULTILINE);
            errorString = pattern.matcher(errorString).replaceAll("");

            GNUCompiler.logger.debug("Compilation error: {}", errorString);
            throw new CompilerError("gcc.wrote.stderr", errorString);
        } catch (final UnsupportedEncodingException e) {
            throw new CompilationException("Unsupported encoding! The compiler should output UTF-8!", e);
        }
    }
}

From source file:io.undertow.server.handlers.file.FileHandlerSymlinksTestCase.java

@Test
public void testExplicitAccessSymlinkDeniedUsingSpecificFilters() throws IOException, URISyntaxException {
    TestHttpClient client = new TestHttpClient();
    Path rootPath = Paths.get(getClass().getResource("page.html").toURI()).getParent();
    Path newSymlink = rootPath.resolve("newSymlink");

    try {/*from w w w .ja va2 s .co m*/
        DefaultServer.setRootHandler(new CanonicalPathHandler().setNext(new PathHandler().addPrefixPath("/path",
                new ResourceHandler(new PathResourceManager(newSymlink, 10485760, true,
                        rootPath.toAbsolutePath().toString().concat("/otherDir")))
                                .setDirectoryListingEnabled(false).addWelcomeFiles("page.html"))));
        /**
         * This request should return a 404 code as rootPath + "/otherDir" doesnt match in rootPath + "/path/innerSymlink/page.html"
         */
        HttpGet get = new HttpGet(DefaultServer.getDefaultServerURL() + "/path/innerSymlink/page.html");
        HttpResponse result = client.execute(get);
        Assert.assertEquals(StatusCodes.NOT_FOUND, result.getStatusLine().getStatusCode());
    } finally {
        client.getConnectionManager().shutdown();
    }
}

From source file:io.undertow.server.handlers.file.FileHandlerSymlinksTestCase.java

@Test
public void testExplicitAccessSymlinkDeniedUsingSameSymlinkName() throws IOException, URISyntaxException {
    TestHttpClient client = new TestHttpClient();
    Path rootPath = Paths.get(getClass().getResource("page.html").toURI()).getParent();
    Path newSymlink = rootPath.resolve("newSymlink");

    try {/*  w w w  . j a va2  s  .  c  om*/
        DefaultServer.setRootHandler(new CanonicalPathHandler().setNext(new PathHandler().addPrefixPath("/path",
                new ResourceHandler(new PathResourceManager(newSymlink, 10485760, true,
                        rootPath.toAbsolutePath().toString().concat("/innerSymlink")))
                                .setDirectoryListingEnabled(false).addWelcomeFiles("page.html"))));
        /**
         * This request should return a 404 code as rootPath + "/innerSymlink" in safePaths will not match with canonical "/innerSymlink"
         */
        HttpGet get = new HttpGet(DefaultServer.getDefaultServerURL() + "/path/innerSymlink/page.html");
        HttpResponse result = client.execute(get);
        Assert.assertEquals(StatusCodes.NOT_FOUND, result.getStatusLine().getStatusCode());
    } finally {
        client.getConnectionManager().shutdown();
    }
}

From source file:org.opennms.test.FileAnticipator.java

/**
 * Delete expected files, throwing an AssertionFailedError if any of
 * the expected files don't exist./*  w w w. j ava  2s .  c o  m*/
 *
 * @param ignoreNonExistantFiles if true, non-existant files will be
 *      ignored and will not throw an AssertionFailedError
 * @throws AssertionFailedError if ignoreNonExistantFiles is false
 *      and an expected file does not exist, or if a file cannot be deleted
 */
public void deleteExpected(boolean ignoreNonExistantFiles) {
    assertInitialized();

    Collections.sort(m_expecting, new Comparator<File>() {
        @Override
        public int compare(File a, File b) {
            return a.getAbsolutePath().compareTo(b.getAbsolutePath());
        }
    });

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

    for (ListIterator<File> i = m_expectingPrefixes.listIterator(m_expectingPrefixes.size()); i
            .hasPrevious();) {
        File f = i.previous();
        List<Path> matches = getMatches(f);
        if (matches.size() < 1 && !ignoreNonExistantFiles) {
            errors.add("Expected prefix that needs to be deleted does not exist: " + f.getAbsolutePath());
        }
        for (Path match : matches) {
            if (!match.toFile().delete())
                errors.add("Could not delete expected file: " + match.toAbsolutePath());
        }
        i.remove();
    }

    for (ListIterator<File> i = m_expecting.listIterator(m_expecting.size()); i.hasPrevious();) {
        File f = i.previous();
        if (!f.exists()) {
            if (!ignoreNonExistantFiles) {
                errors.add("Expected file that needs to be deleted does not exist: " + f.getAbsolutePath());
            }
        } else {
            if (f.isDirectory()) {
                String[] files = f.list();
                if (files.length > 0) {
                    StringBuffer fileList = new StringBuffer("{ ");
                    fileList.append(files[0]);
                    for (int j = 1; j < files.length; j++) {
                        fileList.append(", ").append(files[j]);
                    }
                    fileList.append(" }");
                    errors.add("Directory was not empty: " + f.getAbsolutePath() + ": " + fileList.toString());
                } else {
                    if (!f.delete())
                        errors.add("Could not delete directory: " + f.getAbsolutePath());
                }
            } else {
                if (!f.delete())
                    errors.add("Could not delete expected file: " + f.getAbsolutePath());
            }
        }
        i.remove();
    }
    assertEquals("No expected files left over", m_expecting.size(), 0);
    if (errors.size() > 0) {
        StringBuffer errorString = new StringBuffer();
        for (String error : errors) {
            errorString.append(error).append("\n");
        }
        fail("Errors occurred inside FileAnticipator:\n" + errorString.toString().trim());
    }
}

From source file:io.undertow.server.handlers.file.FileHandlerSymlinksTestCase.java

@Test
public void testExplicitAccessSymlinkGrantedUsingSpecificFilters() throws IOException, URISyntaxException {
    TestHttpClient client = new TestHttpClient();
    Path rootPath = Paths.get(getClass().getResource("page.html").toURI()).getParent();
    Path newSymlink = rootPath.resolve("newSymlink");

    try {/*  w  ww.j a  va 2s.c  om*/
        DefaultServer.setRootHandler(new CanonicalPathHandler().setNext(new PathHandler().addPrefixPath("/path",
                new ResourceHandler(new PathResourceManager(newSymlink, 10485760, true,
                        rootPath.toAbsolutePath().toString().concat("/newDir")))
                                .setDirectoryListingEnabled(false).addWelcomeFiles("page.html"))));
        /**
         * This request should return a 200 code as rootPath + "/newDir" is used in the safePaths
         */
        HttpGet get = new HttpGet(DefaultServer.getDefaultServerURL() + "/path/innerSymlink/page.html");
        HttpResponse result = client.execute(get);
        Assert.assertEquals(StatusCodes.OK, result.getStatusLine().getStatusCode());
        final String response = HttpClientUtils.readResponse(result);
        Header[] headers = result.getHeaders("Content-Type");
        Assert.assertEquals("text/html", headers[0].getValue());
        Assert.assertTrue(response, response.contains("A web page"));
    } finally {
        client.getConnectionManager().shutdown();
    }
}

From source file:org.opencb.hpg.bigdata.app.cli.local.VariantCommandExecutor.java

private void convertToProtoBuf(Path inputPath, OutputStream outputStream) throws Exception {
    // Creating reader
    VcfBlockIterator iterator = (StringUtils.equals("-", inputPath.toAbsolutePath().toString()))
            ? new VcfBlockIterator(new BufferedInputStream(System.in), new FullVcfCodec())
            : new VcfBlockIterator(inputPath.toFile(), new FullVcfCodec());

    LocalCliOptionsParser.ConvertVariantCommandOptions cliOptions = variantCommandOptions.convertVariantCommandOptions;
    int numTasks = Math.max(cliOptions.numThreads, 1);
    int batchSize = Integer.parseInt(cliOptions.options.getOrDefault("batch.size", "50"));
    int bufferSize = Integer.parseInt(cliOptions.options.getOrDefault("buffer.size", "100000"));
    int capacity = numTasks + 1;
    ParallelTaskRunner.Config config = new ParallelTaskRunner.Config(numTasks, batchSize, capacity, true,
            false);/*from   w  ww  .  ja  v a2  s .c  om*/

    ParallelTaskRunner<CharSequence, ByteBuffer> runner = new ParallelTaskRunner<>(iterator.toLineDataReader(),
            () -> { //Task supplier. Will supply a task instance for each thread.

                //VCFCodec is not thread safe. MUST exist one instance per thread
                VCFCodec codec = new FullVcfCodec(iterator.getHeader(), iterator.getVersion());
                VariantContextBlockIterator blockIterator = new VariantContextBlockIterator(codec);
                Converter<VariantContext, VariantProto.Variant> converter = new VariantContextToVariantProtoConverter();
                return new ProtoEncoderTask<>(
                        charBuffer -> converter.convert(blockIterator.convert(charBuffer)), bufferSize);
            }, batch -> {
                batch.forEach(byteBuffer -> {
                    try {
                        outputStream.write(byteBuffer.array(), byteBuffer.arrayOffset(), byteBuffer.limit());
                    } catch (IOException e) {
                        throw new RuntimeException(e);
                    }
                });
                return true;
            }, config);
    runner.run();
    outputStream.close();

    //        InputStream inputStream = new FileInputStream(variantCommandOptions.convertVariantCommandOptions.output);
    //        if (outputStream instanceof GZIPOutputStream) {
    //            inputStream = new GZIPInputStream(inputStream);
    //        }
    //        VariantProto.Variant variant;
    //        int i = 0;
    //        try {
    //            while ((variant = VariantProto.Variant.parseDelimitedFrom(inputStream)) != null) {
    //                i++;
    //            System.out.println(variant.getChromosome() + ":" + variant.getStart()
    //                    + ":" + variant.getReference() + ":" + variant.getAlternate());
    ////            System.out.println("variant = " + variant.toString());
    //            }
    //        } finally {
    //            System.out.println("Num variants = " + i);
    //            inputStream.close();
    //        }
}