Example usage for java.nio.file Path getParent

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

Introduction

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

Prototype

Path getParent();

Source Link

Document

Returns the parent path, or null if this path does not have a parent.

Usage

From source file:io.cloudslang.content.vmware.services.DeployOvfTemplateService.java

private ITransferVmdkFrom getTransferVmdK(final String templateFilePathStr, final String vmdkName)
        throws IOException {
    final Path templateFilePath = Paths.get(templateFilePathStr);
    if (isOva(templateFilePath)) {
        final TarArchiveInputStream tar = new TarArchiveInputStream(new FileInputStream(templateFilePathStr));
        TarArchiveEntry entry;/*from w w w  .  j  a  v a 2  s . com*/
        while ((entry = tar.getNextTarEntry()) != null) {
            if (new File(entry.getName()).getName().startsWith(vmdkName)) {
                return new TransferVmdkFromInputStream(tar, entry.getSize());
            }
        }
    } else if (isOvf(templateFilePath)) {
        final Path vmdkPath = templateFilePath.getParent().resolve(vmdkName);
        return new TransferVmdkFromFile(vmdkPath.toFile());
    }
    throw new RuntimeException(NOT_OVA_OR_OVF);
}

From source file:org.codice.ddf.platform.migratable.impl.PlatformMigratableTest.java

private void setup(String ddfHomeStr, String tag, String productVersion) throws IOException {
    ddfHome = tempDir.newFolder(ddfHomeStr).toPath().toRealPath();
    Path binDir = ddfHome.resolve("bin");
    Files.createDirectory(binDir);
    System.setProperty(DDF_HOME_SYSTEM_PROP_KEY, ddfHome.toRealPath().toString());
    setupBrandingFile(SUPPORTED_BRANDING);
    setupVersionFile(productVersion);//w  w w. ja va  2 s .c  o  m
    setupMigrationProperties(SUPPORTED_VERSION);
    setupKeystores(tag);
    for (Path path : REQUIRED_SYSTEM_FILES) {
        Path p = ddfHome.resolve(path);
        Files.createDirectories(p.getParent());
        Files.createFile(p);
        FileUtils.writeStringToFile(p.toFile(), String.format("#%s&%s", p.toRealPath().toString(), tag),
                StandardCharsets.UTF_8);
    }
    for (Path path : OPTIONAL_SYSTEM_FILES) {
        Path p = ddfHome.resolve(path);
        Files.createDirectories(p.getParent());
        Files.createFile(p);
        FileUtils.writeStringToFile(p.toFile(), String.format("#%s&%s", p.toRealPath().toString(), tag),
                StandardCharsets.UTF_8);
    }
    setupWsSecurity(tag);
    setupServiceWrapper(tag);
}

From source file:org.apache.taverna.robundle.TestBundles.java

@Test
public void withExtension() throws Exception {
    Path testDir = Files.createTempDirectory("test");
    testDir.toFile().deleteOnExit();/*w  ww .j  a va2s.com*/
    Path fileTxt = testDir.resolve("file.txt");
    fileTxt.toFile().deleteOnExit();
    assertEquals("file.txt", fileTxt.getFileName().toString()); // better
    // be!

    Path fileHtml = Bundles.withExtension(fileTxt, ".html");
    assertEquals(fileTxt.getParent(), fileHtml.getParent());
    assertEquals("file.html", fileHtml.getFileName().toString());

    Path fileDot = Bundles.withExtension(fileTxt, ".");
    assertEquals("file.", fileDot.getFileName().toString());

    Path fileEmpty = Bundles.withExtension(fileTxt, "");
    assertEquals("file", fileEmpty.getFileName().toString());

    Path fileDoc = Bundles.withExtension(fileEmpty, ".doc");
    assertEquals("file.doc", fileDoc.getFileName().toString());

    Path fileManyPdf = Bundles.withExtension(fileTxt, ".test.many.pdf");
    assertEquals("file.test.many.pdf", fileManyPdf.getFileName().toString());

    Path fileManyTxt = Bundles.withExtension(fileManyPdf, ".txt");
    assertEquals("file.test.many.txt", fileManyTxt.getFileName().toString());
}

From source file:org.alfresco.repo.bulkimport.impl.DirectoryAnalyserImpl.java

private Path getParentOfMetadatafile(Path metadataFile) {
    Path result = null;/*from  w w w.  j a v  a 2  s .c  om*/

    if (!isMetadataFile(metadataFile)) {
        throw new IllegalStateException(FileUtils.getFileName(metadataFile) + " is not a metadata file.");
    }

    String name = metadataFile.getFileName().toString();
    String contentName = name.substring(0, name.length()
            - (MetadataLoader.METADATA_SUFFIX + metadataLoader.getMetadataFileExtension()).length());

    result = metadataFile.getParent().resolve(contentName);

    return (result);
}

From source file:org.auscope.portal.server.web.service.TemplateLintService.java

private List<LintResult> pylint(String template) throws PortalServiceException {
    List<LintResult> lints = new ArrayList<LintResult>();

    // Save template as a temporary python file
    Path f;
    try {// w  w w .j  a va 2s.  c  o m
        f = Files.createTempFile("contemplate", ".py");
        BufferedWriter writer = Files.newBufferedWriter(f);
        writer.write(template);
        writer.close();
    } catch (Exception ex) {
        throw new PortalServiceException("Failed to write template to temporary file.", ex);
    }

    // Run pylint in the temp file's directory
    String results;
    String errors;
    ArrayList<String> cmd = new ArrayList<String>(this.pylintCommand);
    cmd.add(f.getFileName().toString());
    try {
        ProcessBuilder pb = new ProcessBuilder(cmd).directory(f.getParent().toFile());

        // Start the process, and consume the results immediately so Windows is happy.
        Process p = pb.start();
        BufferedReader stdout = new BufferedReader(new InputStreamReader(p.getInputStream()));
        results = stdout.lines().collect(Collectors.joining("\n"));
        BufferedReader stderr = new BufferedReader(new InputStreamReader(p.getErrorStream()));
        errors = stderr.lines().collect(Collectors.joining("\n"));

        if (!p.waitFor(DEFAULT_TIMEOUT, TimeUnit.SECONDS)) {
            // Timed out
            throw new PortalServiceException(String.format(
                    "pylint process failed to complete before {} second timeout elapsed", DEFAULT_TIMEOUT));
        }

        // Finished successfully? pylint returns 0 on success *with no
        // issues*, 1 on failure to run properly, 2/4/8/16 for successful
        // completion with python convention/refactor/warning/error (codes
        // 2-16 bit-ORd into final result) or 32 on usage error.
        int rv = p.exitValue();
        if (rv == 1 || rv == 32) {
            logger.error("pylint failed");
            logger.debug("\npylint stderr:\n" + errors);
            logger.debug("\npylint stdout:\n" + results);
            throw new PortalServiceException(
                    String.format("pylint process returned non-zero exit value: {}", rv));
        } else if (rv != 0) {
            logger.info("pylint found issues");
        }
    } catch (PortalServiceException pse) {
        throw pse;
    } catch (Exception ex) {
        throw new PortalServiceException("Failed to run pylint on template", ex);
    }

    // Parse results into LintResult objects
    lints = parsePylintResults(results);

    // Clean up
    try {
        Files.delete(f);
    } catch (Exception ex) {
        throw new PortalServiceException("Failed to delete temporary template file.", ex);
    }

    return lints;
}

From source file:org.corehunter.services.simple.FileBasedDatasetServices.java

private void copyOrMoveFile(Path source, Path target) throws IOException {

    Files.createDirectories(target.getParent());

    Files.copy(source, target);/*from ww w.ja  v  a2s .c om*/
}

From source file:org.artifactory.storage.binstore.service.providers.DoubleFileBinaryProviderImpl.java

@Override
@Nonnull/*  w  w  w.j  av a 2 s.com*/
public BinaryInfo addStream(InputStream in) throws IOException {
    ProviderAndTempFile[] providerAndTempFiles = null;
    Sha1Md5ChecksumInputStream checksumStream = null;
    try {
        // first save to a temp file and calculate checksums while saving
        if (in instanceof Sha1Md5ChecksumInputStream) {
            checksumStream = (Sha1Md5ChecksumInputStream) in;
        } else {
            checksumStream = new Sha1Md5ChecksumInputStream(in);
        }
        providerAndTempFiles = writeToTempFile(checksumStream);
        BinaryInfo bd = new BinaryInfoImpl(checksumStream);
        log.trace("Inserting {} in file binary provider", bd);

        String sha1 = bd.getSha1();
        boolean oneGoodMove = false;
        for (ProviderAndTempFile providerAndTempFile : providerAndTempFiles) {
            File tempFile = providerAndTempFile.tempFile;
            if (tempFile != null && providerAndTempFile.somethingWrong == null) {
                try {
                    long fileLength = tempFile.length();
                    if (fileLength != checksumStream.getTotalBytesRead()) {
                        throw new IOException("File length is " + fileLength + " while total bytes read on"
                                + " stream is " + checksumStream.getTotalBytesRead());
                    }
                    File file = providerAndTempFile.provider.getFile(sha1);
                    Path target = file.toPath();
                    if (!java.nio.file.Files.exists(target)) {
                        // move the file from the pre-filestore to the filestore
                        java.nio.file.Files.createDirectories(target.getParent());
                        try {
                            log.trace("Moving {} to {}", tempFile.getAbsolutePath(), target);
                            java.nio.file.Files.move(tempFile.toPath(), target, StandardCopyOption.ATOMIC_MOVE);
                            log.trace("Moved  {} to {}", tempFile.getAbsolutePath(), target);
                        } catch (FileAlreadyExistsException ignore) {
                            // May happen in heavy concurrency cases
                            log.trace("Failed moving {} to {}. File already exist", tempFile.getAbsolutePath(),
                                    target);
                        }
                        providerAndTempFile.tempFile = null;
                        oneGoodMove = true;
                    } else {
                        log.trace("File {} already exist in the file store. Deleting temp file: {}", target,
                                tempFile.getAbsolutePath());
                    }
                } catch (IOException e) {
                    providerAndTempFile.somethingWrong = e;
                    providerAndTempFile.provider.markInactive(e);
                }
            }
        }
        if (!oneGoodMove) {
            StringBuilder msg = new StringBuilder("Could not move checksum file ").append(sha1)
                    .append(" to any filestore:\n");
            IOException oneEx = null;
            for (ProviderAndTempFile providerAndTempFile : providerAndTempFiles) {
                DynamicFileBinaryProviderImpl provider = providerAndTempFile.provider;
                msg.append("\t'").append(provider.getBinariesDir().getAbsolutePath()).append("' actif=")
                        .append(provider.isActive()).append("\n");
                if (providerAndTempFile.somethingWrong != null) {
                    oneEx = providerAndTempFile.somethingWrong;
                    msg.append("\t\tWith Exception:").append(providerAndTempFile.somethingWrong.getMessage());
                }
                msg.append("\n");
            }
            if (oneEx != null) {
                throw new IOException(msg.toString(), oneEx);
            } else {
                throw new IOException(msg.toString());
            }
        }
        return bd;
    } finally {
        IOUtils.closeQuietly(checksumStream);
        if (providerAndTempFiles != null) {
            for (ProviderAndTempFile providerAndTempFile : providerAndTempFiles) {
                File file = providerAndTempFile.tempFile;
                if (file != null && file.exists()) {
                    if (!file.delete()) {
                        log.error("Could not delete temp file {}", file.getAbsolutePath());
                    }
                }
            }
        }
    }
}

From source file:io.warp10.worf.WorfInteractive.java

public String runTemplate(Properties config, String warp10Configuration) throws WorfException {
    try {//from   w  w w. jav  a  2s. co m
        out.println("The configuration file is a template");
        WorfTemplate template = new WorfTemplate(config, warp10Configuration);

        out.println("Generating crypto keys...");
        for (String cryptoKey : template.getCryptoKeys()) {
            String keySize = template.generateCryptoKey(cryptoKey);
            if (keySize != null) {
                out.println(keySize + " bits secured key for " + cryptoKey + "  generated");
            } else {
                out.println("Unable to generate " + cryptoKey + ", template error");
            }
        }

        out.println("Crypto keys generated");

        Stack<Pair<String, String[]>> fieldsStack = template.getFieldsStack();

        if (fieldsStack.size() > 0) {
            out.println("Update configuration...");
        }

        while (!fieldsStack.isEmpty()) {
            Pair<String, String[]> templateValues = fieldsStack.peek();
            String replaceValue = null;
            // get user input
            switch (templateValues.getValue()[0]) {
            case "path":
                replaceValue = readInputPath(reader, out, templateValues.getValue()[2]);
                break;
            case "host":
                replaceValue = readHost(reader, out, templateValues.getValue()[2]);
                break;
            case "int":
                replaceValue = readInteger(reader, out, templateValues.getValue()[2]);
                break;
            }

            if (replaceValue == null) {
                out.println("Unable to update " + templateValues.getValue()[1] + " key, enter a valid "
                        + templateValues.getValue()[0]);
                continue;
            }

            // replace template value
            template.updateField(templateValues.getKey(), replaceValue);

            // field updated pop
            fieldsStack.pop();
        }

        out.println("Configuration updated.");

        // save file
        Path warp10ConfigurationPath = Paths.get(warp10Configuration);
        String outputFileName = warp10ConfigurationPath.getFileName().toString();
        outputFileName = outputFileName.replace("template", "conf");
        String outputPath = readInputPath(reader, out, "save config:output path",
                warp10ConfigurationPath.getParent().toString());
        String outputFilename = readInputString(reader, out, "save config:output filename", outputFileName);

        if (Strings.isNullOrEmpty(outputPath) || Strings.isNullOrEmpty(outputFilename)) {
            throw new Exception("Path or filename empty, unable to save configuration file!");
        }

        StringBuilder sb = new StringBuilder();
        sb.append(outputPath);
        if (!outputPath.endsWith(File.separator)) {
            sb.append(File.separator);
        }
        sb.append(outputFilename);

        warp10Configuration = sb.toString();
        template.saveConfig(warp10Configuration);

        out.println("Configuration saved. filepath=" + warp10Configuration);
        out.println("Reading warp10 configuration " + warp10Configuration);
        return warp10Configuration;
    } catch (Exception exp) {
        throw new WorfException("Unexpected Worf error:" + exp.getMessage());
    }
}

From source file:org.fao.geonet.api.records.formatters.FormatterApiIntegrationTest.java

@Test(expected = AssertionError.class)
public void testGroovyUseEnvDuringConfigStage() throws Exception {
    MockHttpServletRequest r = new MockHttpServletRequest();
    r.getSession();//from   www. j  a va2s.c  o  m
    final ServletWebRequest webRequest = new ServletWebRequest(r, new MockHttpServletResponse());
    final FormatterParams fparams = new FormatterParams();
    fparams.context = this.serviceContext;
    fparams.webRequest = webRequest;
    // make sure context is cleared
    EnvironmentProxy.setCurrentEnvironment(fparams);

    final String formatterName = "groovy-illegal-env-access-formatter";
    final URL testFormatterViewFile = FormatterApiIntegrationTest.class
            .getResource(formatterName + "/view.groovy");
    final Path testFormatter = IO.toPath(testFormatterViewFile.toURI()).getParent();
    final Path formatterDir = this.dataDirectory.getFormatterDir();
    IO.copyDirectoryOrFile(testFormatter, formatterDir.resolve(formatterName), false);
    final String functionsXslName = "functions.xsl";
    Files.deleteIfExists(formatterDir.resolve(functionsXslName));
    IO.copyDirectoryOrFile(testFormatter.getParent().resolve(functionsXslName),
            formatterDir.resolve(functionsXslName), false);

    formatService.exec("eng", "html", "" + id, null, formatterName, null, null, _100, webRequest);
}