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.warp10.worf.WorfCLI.java

public int execute(String[] args) {
    try {/*from   ww w .java 2s.c  o  m*/
        CommandLineParser parser = new BasicParser();
        CommandLine cmd = parser.parse(options, args);

        String inputFile = null;
        boolean interactive = false;
        boolean token = false;
        String outputFile = null;
        String keyStoreFile = null;

        String producerUID = null;
        String ownerUID = null;
        String appName = null;
        long ttl = 0L;

        PrintWriter out = new PrintWriter(System.out);

        if (cmd.hasOption(HELP)) {
            help();
            return 0;
        }

        if (cmd.hasOption(VERSION)) {
            version(out);
            return 0;
        }

        if (cmd.hasOption(VERBOSE)) {
            verbose = true;
        }

        if (cmd.hasOption(INTERACTIVE)) {
            interactive = true;
        }

        if (cmd.hasOption(OUTPUT)) {
            outputFile = cmd.getOptionValue(OUTPUT);
        }

        if (cmd.hasOption(KEYSTORE)) {
            keyStoreFile = cmd.getOptionValue(KEYSTORE);
        }

        if (cmd.hasOption(TOKEN)) {
            token = true;
            // PRODUCER UUID OPTION (mandatory)
            // --------------------------------------------------------------------
            if (cmd.hasOption(UUIDGEN_PRODUCER)) {
                producerUID = UUID.randomUUID().toString();
            } else if (cmd.hasOption(P_UUID)) {
                producerUID = cmd.getOptionValue(P_UUID);
                UUID.fromString(producerUID);
            }

            // OWNER UUID OPTION (mandatory)
            // --------------------------------------------------------------------
            if (cmd.hasOption(UUIDGEN_OWNER)) {
                ownerUID = UUID.randomUUID().toString();
            } else if (cmd.hasOption(O_UUID)) {
                ownerUID = cmd.getOptionValue(O_UUID);
                UUID.fromString(ownerUID);
            } else {
                ownerUID = producerUID;
            }

            if (cmd.hasOption(APPNAME)) {
                appName = cmd.getOptionValue(APPNAME);
            }

            if (cmd.hasOption(TTL)) {
                ttl = Long.parseLong(cmd.getOptionValue(TTL));
                long ttlMax = Long.MAX_VALUE - System.currentTimeMillis();

                if (ttl >= ttlMax) {
                    throw new WorfException("TTL can not be upper than " + ttlMax + " ms");
                }

            } else {
                throw new WorfException("The option 'ttl' is missing ");
            }
        }

        // get the input file name
        switch (cmd.getArgs().length) {
        case 0:
            throw new WorfException("Config or template file missing.");

        case 1:
            inputFile = cmd.getArgs()[0];
            break;

        default:
            throw new WorfException("Too many arguments, only one config or template file expected.");
        }

        // load the interactive mode
        if (interactive) {
            return runInteractive(inputFile);
        }

        Properties config = Worf.readConfig(inputFile, out);

        //
        // TEMPLATE CONFIGURATION
        //
        if (WorfTemplate.isTemplate(config)) {

            // load keystore if needed
            WorfKeyMaster templateKeyMaster = null;
            if (!Strings.isNullOrEmpty(keyStoreFile)) {
                // read config
                Properties keyStoreConfig = Worf.readConfig(keyStoreFile, out);
                // load key master
                templateKeyMaster = new WorfKeyMaster(keyStoreConfig);

                if (!templateKeyMaster.loadKeyStore()) {
                    throw new WorfException("Template Keystore not loaded");
                }
            }

            WorfTemplate tpl = new WorfTemplate(config, inputFile);

            // GENERATE CRYPTO KEYS
            for (String cryptoKey : tpl.getCryptoKeys()) {
                String keySize = tpl.generateCryptoKey(cryptoKey);
                if (keySize != null) {
                    out.println(keySize + " bits secured key for " + cryptoKey + "  generated");
                } else {
                    throw new WorfException("Unable to generate " + cryptoKey + ", template error");
                }
            }

            // read defaults
            if (token) {
                Properties defaultProperties = Worf.readDefault(inputFile, out);
                appName = Worf.getDefault(defaultProperties, out, appName, APPNAME);
                producerUID = Worf.getDefault(defaultProperties, out, producerUID, P_UUID);
                ownerUID = Worf.getDefault(defaultProperties, out, ownerUID, O_UUID);
            }
            // GENERATE TOKENS
            for (String tokenKey : tpl.getTokenKeys()) {
                if (!token) {
                    throw new WorfException("Unable to generate template tokens missing -t option");
                }
                if (templateKeyMaster == null) {
                    throw new WorfException("Unable to generate template tokens missing -ks option");
                }

                String tokenIdent = tpl.generateTokenKey(tokenKey, appName, ownerUID, producerUID, ttl,
                        templateKeyMaster);
                out.println("Token generated key=" + tokenKey + "  ident=" + tokenIdent);
            }

            // GET INTERACTIVE CONFIGURATION
            if (tpl.getFieldsStack().size() > 0) {
                throw new WorfException("Unable the update template, you are not in interactive mode");
            }

            // save the template
            if (Strings.isNullOrEmpty(outputFile)) {
                Path inputConfigurationPath = Paths.get(inputFile);
                String outputFileName = inputConfigurationPath.getFileName().toString();
                outputFileName = outputFileName.replace("template", "conf");

                StringBuilder sb = new StringBuilder();
                sb.append(inputConfigurationPath.getParent().toString());
                if (!inputConfigurationPath.endsWith(File.separator)) {
                    sb.append(File.separator);
                }
                sb.append(outputFileName);

                outputFile = sb.toString();
            }
            tpl.saveConfig(outputFile);
            out.println("Warp configuration saved (" + outputFile + ")");
            out.flush();
            inputFile = outputFile;

            // Keystore is given as input
            //end of the job
            if (!Strings.isNullOrEmpty(keyStoreFile)) {
                out.println("Warp configuration file used for tokens generation in templates");
                out.println("For generate tokens, reload Worf without 'ks' option");
                out.flush();
                System.exit(0);
            }
        }

        //
        // GENERATE TOKEN
        //
        if (token) {
            // read config
            config = Worf.readConfig(inputFile, out);
            // load key master
            WorfKeyMaster keyMaster = new WorfKeyMaster(config);

            if (!keyMaster.loadKeyStore()) {
                throw new WorfException("Keystore not loaded");
            }

            Properties defaultProperties = Worf.readDefault(inputFile, out);
            appName = Worf.getDefault(defaultProperties, out, appName, APPNAME);
            producerUID = Worf.getDefault(defaultProperties, out, producerUID, P_UUID);
            ownerUID = Worf.getDefault(defaultProperties, out, ownerUID, O_UUID);

            // save default
            if (defaultProperties == null) {
                Worf.saveDefault(inputFile, appName, producerUID, ownerUID);
            }

            // deliver token
            String readToken = keyMaster.deliverReadToken(appName, producerUID, ownerUID, ttl);
            String writeToken = keyMaster.deliverWriteToken(appName, producerUID, ownerUID, ttl);

            // write outputformat
            JSONObject jsonOutput = new JSONObject();
            JSONObject jsonToken = new JSONObject();
            jsonToken.put("token", readToken);
            jsonToken.put("tokenIdent", keyMaster.getTokenIdent(readToken));
            jsonToken.put("ttl", ttl);
            jsonToken.put("application", appName);
            jsonToken.put("owner", ownerUID);
            jsonToken.put("producer", producerUID);

            jsonOutput.put("read", jsonToken);

            jsonToken = new JSONObject();
            jsonToken.put("token", writeToken);
            jsonToken.put("tokenIdent", keyMaster.getTokenIdent(writeToken));
            jsonToken.put("ttl", ttl);
            jsonToken.put("application", appName);
            jsonToken.put("owner", ownerUID);
            jsonToken.put("producer", producerUID);

            jsonOutput.put("write", jsonToken);

            System.out.println(jsonOutput.toString());
        }

    } catch (Exception we) {
        if (verbose) {
            we.printStackTrace();
        } else {
            System.out.println(we.getMessage() + "\n");
        }
        help();
        return -1;
    }
    return 0;
}

From source file:org.mitre.mpf.wfm.util.PropertiesUtil.java

public File createArtifactFile(long jobId, long mediaId, int stageIndex, String name) throws IOException {
    Path path = Paths.get(artifactsDirectory.toURI())
            .resolve(String.format("%d/%d/%d/%s", jobId, mediaId, stageIndex, name)).normalize()
            .toAbsolutePath();/*from  w  w w. j  av  a2  s .c  o m*/
    Files.createDirectories(path.getParent());
    return path.toFile();
}

From source file:com.liferay.sync.engine.document.library.handler.GetSyncDLObjectUpdateHandler.java

protected boolean isParentUnsynced(SyncFile syncFile) {
    Path filePath = Paths.get(syncFile.getFilePathName());

    if (FileUtil.isUnsynced(filePath.getParent())) {
        return true;
    }/*  w  w  w  . ja  v a2s.co  m*/

    return false;
}

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

@Test
public void testLoggingNullPointerBug() throws Exception {
    final org.apache.log4j.Logger logger = org.apache.log4j.Logger.getLogger(Geonet.FORMATTER);
    Level level = logger.getLevel();
    logger.setLevel(Level.ALL);//from  w w w .  j  a v a 2  s. c o m
    try {
        MockHttpServletRequest webRequest = new MockHttpServletRequest();
        webRequest.getSession();
        final ServletWebRequest request = new ServletWebRequest(webRequest, new MockHttpServletResponse());
        final FormatterParams fparams = new FormatterParams();
        fparams.context = this.serviceContext;
        fparams.webRequest = request;
        // make sure context is cleared
        EnvironmentProxy.setCurrentEnvironment(fparams);

        final String formatterName = "logging-null-pointer";
        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, request);

        // no Error is success
    } finally {
        logger.setLevel(level);
    }
}

From source file:de.teamgrit.grit.checking.compile.JavaCompileChecker.java

/**
 * Runs a command specified by a compiler invocation.
 *
 * @param compilerInvocation//from   w  w  w  . j  a  v  a 2s .c  om
 *            specifies what program with which flags is being executed
 * @param pathToSourceFolder
 *            the path to the source folder of the submission
 * @return CompilerOutput with fields initialized according to the outcome
 *         of the process
 * @throws BadFlagException
 *             if a flag is not known to javac
 */
private CompilerOutput runJavacProcess(List<String> compilerInvocation, Path pathToSourceFolder, boolean junit)
        throws BadFlagException {
    Process compilerProcess = null;
    try {
        ProcessBuilder compilerProcessBuilder = new ProcessBuilder(compilerInvocation);
        // make sure the compiler stays in its directory.
        if (Files.isDirectory(pathToSourceFolder, LinkOption.NOFOLLOW_LINKS)) {
            compilerProcessBuilder.directory(pathToSourceFolder.toFile());
        } else {
            compilerProcessBuilder.directory(pathToSourceFolder.getParent().toFile());
        }
        compilerProcess = compilerProcessBuilder.start();
    } catch (IOException e) {
        // If we cannot call the compiler we return a CompilerOutput
        // which is
        // initialized with false, false, indicating
        // that the compiler wasn't invoked properly and that there was no
        // clean Compile.
        CompilerOutput compilerInvokeError = new CompilerOutput();
        compilerInvokeError.setClean(false);
        compilerInvokeError.setCompilerInvoked(false);
        return compilerInvokeError;
    }

    // Now we read compiler output. If everything is ok javac reports
    // nothing at all.
    InputStream compilerOutputStream = compilerProcess.getErrorStream();
    InputStreamReader compilerStreamReader = new InputStreamReader(compilerOutputStream);
    BufferedReader compilerOutputBuffer = new BufferedReader(compilerStreamReader);
    String line;

    CompilerOutput compilerOutput = new CompilerOutput();
    compilerOutput.setCompilerInvoked(true);

    List<String> compilerOutputLines = new LinkedList<>();

    try {
        while ((line = compilerOutputBuffer.readLine()) != null) {
            compilerOutputLines.add(line);
        }

        compilerOutputStream.close();
        compilerStreamReader.close();
        compilerOutputBuffer.close();
        compilerProcess.destroy();
    } catch (IOException e) {
        // Reading might go wrong here if javac should unexpectedly
        // terminate
        LOGGER.severe("Could not read compiler ourput from its output stream." + " Aborting compile of: "
                + pathToSourceFolder.toString() + " Got message: " + e.getMessage());
        compilerOutput.setClean(false);
        compilerOutput.setCompileStreamBroken(true);
        return compilerOutput;
    }

    splitCompilerOutput(compilerOutputLines, compilerOutput);

    if (compilerOutputLines.size() == 0) {
        compilerOutput.setClean(true);
    }

    return compilerOutput;
}

From source file:org.mitre.mpf.wfm.util.PropertiesUtil.java

public Path createMarkupPath(long jobId, long mediaId, String extension) throws IOException {
    Path path = Paths.get(markupDirectory.toURI()).resolve(
            String.format("%d/%d/%s%s", jobId, mediaId, UUID.randomUUID(), TextUtils.trimToEmpty(extension)))
            .normalize().toAbsolutePath();
    Files.createDirectories(path.getParent());
    return Files.createFile(path);
}

From source file:org.opencb.opencga.server.rest.OpenCGAWSServer.java

private void init() {
    logger = LoggerFactory.getLogger("org.opencb.opencga.server.rest.OpenCGAWSServer");
    logger.info("========================================================================");
    logger.info("| Starting OpenCGA REST server, initializing OpenCGAWSServer");
    logger.info("| This message must appear only once.");

    // We must load the configuration files and init catalogManager, storageManagerFactory and Logger only the first time.
    // We first read 'config-dir' parameter passed
    ServletContext context = httpServletRequest.getServletContext();
    String configDirString = context.getInitParameter("config-dir");
    if (StringUtils.isEmpty(configDirString)) {
        // If not environment variable then we check web.xml parameter
        if (StringUtils.isNotEmpty(context.getInitParameter("OPENCGA_HOME"))) {
            configDirString = context.getInitParameter("OPENCGA_HOME") + "/conf";
        } else if (StringUtils.isNotEmpty(System.getenv("OPENCGA_HOME"))) {
            // If not exists then we try the environment variable OPENCGA_HOME
            configDirString = System.getenv("OPENCGA_HOME") + "/conf";
        } else {//from  w w w  .  j  a v  a  2  s  . c  om
            logger.error("No valid configuration directory provided!");
        }
    }

    // Check and execute the init methods
    java.nio.file.Path configDirPath = Paths.get(configDirString);
    if (configDirPath != null && Files.exists(configDirPath) && Files.isDirectory(configDirPath)) {
        logger.info("|  * Configuration folder: '{}'", configDirPath.toString());
        initOpenCGAObjects(configDirPath);

        // Required for reading the analysis.properties file.
        // TODO: Remove when analysis.properties is totally migrated to configuration.yml
        Config.setOpenCGAHome(configDirPath.getParent().toString());

        // TODO use configuration.yml for getting the server.log, for now is hardcoded
        logger.info("|  * Server logfile: " + configDirPath.getParent().resolve("logs").resolve("server.log"));
        initLogger(configDirPath.getParent().resolve("logs"));
    } else {
        logger.error("No valid configuration directory provided: '{}'", configDirPath.toString());
    }

    logger.info("========================================================================\n");
}

From source file:org.opencastproject.staticfiles.impl.StaticFileServiceImpl.java

@Override
public String storeFile(String filename, InputStream inputStream) throws IOException {
    notNull(filename, "filename");
    notNull(inputStream, "inputStream");
    final String uuid = UUID.randomUUID().toString();
    final String org = securityService.getOrganization().getId();

    Path file = getTemporaryStorageDir(org).resolve(Paths.get(uuid, filename));
    try (ProgressInputStream progressInputStream = new ProgressInputStream(inputStream)) {
        progressInputStream.addPropertyChangeListener(new PropertyChangeListener() {
            @Override/*  w  w w  .j  a  va  2  s  .com*/
            public void propertyChange(PropertyChangeEvent evt) {
                long totalNumBytesRead = (Long) evt.getNewValue();
                long oldTotalNumBytesRead = (Long) evt.getOldValue();
                staticFileStatistics.add(totalNumBytesRead - oldTotalNumBytesRead);
            }
        });

        Files.createDirectories(file.getParent());
        Files.copy(progressInputStream, file);
    } catch (IOException e) {
        logger.error("Unable to save file '{}' to {} because: {}",
                new Object[] { filename, file, ExceptionUtils.getStackTrace(e) });
        throw e;
    }

    return uuid;
}

From source file:org.apache.taverna.prov.W3ProvenanceExport.java

private Path saveValue(T2Reference t2Ref, Path file) throws IOException {
    Path parent = file.getParent();

    switch (t2Ref.getReferenceType()) {

    case IdentifiedList:
        DataBundles.createList(file);/*  www .  ja  v  a2s. c o m*/
        IdentifiedList<T2Reference> list = saver.getReferenceService().getListService().getList(t2Ref);
        long position = 0;
        for (T2Reference ref : list) {
            saveValue(ref, DataBundles.getListItem(file, position++));
        }
        break;
    case ErrorDocument:
        Files.createDirectories(parent);
        file = saveError(t2Ref, file);
        break;
    case ReferenceSet:
        Files.createDirectories(parent);
        file = saver.saveReference(t2Ref, file);
    }
    seenReference(t2Ref, file);
    return file;
}

From source file:de.teamgrit.grit.checking.compile.GccCompileChecker.java

/**
 * This Method generates the command required to start the compiler. It
 * generates a list of strings that can be passed to a process builder.
 * /*from   w w  w. ja v  a2 s  .co m*/
 * @param pathToProgramFile
 *            Where to look for the main file that will be compiled.
 * @param compilerName
 *            Which compiler to call
 * @param compilerFlags
 *            User supplied flags to be passed
 * @throws BadCompilerSpecifiedException
 *             When no compiler is given.
 * @throws FileNotFoundException
 *             When the file to be compiled does not exist
 * @return List of string with the command for the process builder.
 */
private List<String> createCompilerInvocation(Path pathToProgramFile, String compilerName,
        List<String> compilerFlags) throws BadCompilerSpecifiedException, FileNotFoundException {

    List<String> compilerInvocation = new LinkedList<>();
    // We need a compiler name. Without it we cannot compile anything and
    // abort.
    if (("".equals(compilerName)) || (compilerName == null)) {
        throw new BadCompilerSpecifiedException("No compiler specified.");
    } else {
        // search for a makefile
        Path programDirectory = null;
        if (!Files.isDirectory(pathToProgramFile)) {
            programDirectory = pathToProgramFile.getParent();
        } else {
            programDirectory = pathToProgramFile;
        }
        Collection<File> fileList = FileUtils.listFiles(programDirectory.toFile(),
                FileFilterUtils.fileFileFilter(), null);

        boolean hasMakefile = false;
        for (File f : fileList) {
            if (f.getName().matches("[Mm][Aa][Kk][Ee][Ff][Ii][Ll][Ee]")) {
                hasMakefile = true;
            }
        }

        if (hasMakefile) {
            // add the necessary flags for make and return the invocation -
            // we don't need more flags or parameters
            LOGGER.info("Found make-file. Compiling c-code with make.");
            compilerInvocation.add("make");
            compilerInvocation.add("-k");
            compilerInvocation.add("-s");
            return compilerInvocation;
        } else {
            compilerInvocation.add(compilerName);
            LOGGER.info("Compiling c-code with " + compilerName);
        }
    }

    // If compiler flags are passed, append them after the compiler name.
    // If we didn't get any we append nothing.
    if ((compilerFlags != null) && !(compilerFlags.isEmpty())) {
        if (!compilerFlags.contains("-c")) {
            compilerFlags.add("-c");
        }
        compilerInvocation.addAll(compilerFlags);
    }

    // Check for the existance of the program file we are trying to
    // compile.
    if ((pathToProgramFile == null) || (pathToProgramFile.compareTo(Paths.get("")) == 0)) {
        throw new FileNotFoundException("No file to compile specified");
    } else {

        if (Files.isDirectory(pathToProgramFile, LinkOption.NOFOLLOW_LINKS)) {
            // we have to be able to compile several .c files at the same
            // time so we need to find them
            RegexDirectoryWalker dirWalker = new RegexDirectoryWalker(".+\\.[Cc][Pp]?[Pp]?");
            try {
                Files.walkFileTree(pathToProgramFile, dirWalker);
            } catch (IOException e) {
                LOGGER.severe("Could not walk submission " + pathToProgramFile.toString()
                        + " while building compiler invocation: " + e.getMessage());
            }
            for (Path matchedFile : dirWalker.getFoundFiles()) {
                compilerInvocation
                        .add(matchedFile.toString().substring(pathToProgramFile.toString().length() + 1));
            }
        } else {
            throw new FileNotFoundException("Program file that should be compiled does not exist."
                    + "Filename : \"" + pathToProgramFile.toString() + "\"");
        }
    }
    return compilerInvocation;
}