Example usage for java.nio.file Path getFileName

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

Introduction

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

Prototype

Path getFileName();

Source Link

Document

Returns the name of the file or directory denoted by this path as a Path object.

Usage

From source file:codes.thischwa.c5c.impl.LocalConnector.java

@Override
public void replace(String backendPath, InputStream in) throws C5CException {
    Path file = buildRealPath(backendPath);
    try {//  w  ww  . j a v  a 2 s  .  co  m
        Files.copy(in, file, StandardCopyOption.REPLACE_EXISTING);
    } catch (IOException e) {
        throw new FilemanagerException(FilemanagerAction.REPLACE, FilemanagerException.Key.InvalidFileUpload,
                file.getFileName().toString());
    }
}

From source file:objective.taskboard.utils.ZipUtilsTest.java

@Test
public void whenZipAndUnzipFile_BothShouldBeGenerated() throws IOException, URISyntaxException {
    Path source = Paths.get(getClass().getResource("zipUtilsTest.json").toURI());
    Path destiny = Paths.get("zipAndUnzipFile.zip");
    Path assertDir = Paths.get("zipAndUnzipFile");

    try {/*www.ja va 2s  .  c  o  m*/
        zip(source, destiny);

        assertTrue("Zip file should be generated", exists(destiny));
        assertThat(size(destiny), greaterThan(0L));

        unzip(destiny.toFile(), assertDir);

        File file = assertDir.resolve(source.getFileName()).toFile();
        assertTrue("JSON file should be generated", file.exists());

        String actual = IOUtils.toString(asResource(file).getInputStream(), ENCODE_UTF_8);
        String expected = IOUtils.toString(asResource(source).getInputStream(), ENCODE_UTF_8);

        assertEquals("JSON", expected, actual);
    } finally {
        deleteQuietly(destiny.toFile());
        deleteQuietly(assertDir.toFile());
    }
}

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

public String runTemplate(Properties config, String warp10Configuration) throws WorfException {
    try {//from ww  w  . j a  v  a2s . c o  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:de.elomagic.carafile.client.CaraCloud.java

private void createFile(final Path path) throws IOException, GeneralSecurityException {
    LOG.debug("Creating file \"" + path + "\" file at " + client.getRegistryURI());

    URI uri;/*  w w w.ja va2  s  .  c o m*/

    if (Files.isDirectory(path)) {
        registerDefaultWatch(path);
        uri = CaraFileUtils.buildURI(client.getRegistryURI(), "cloud", "create", getSubPath(path));
    } else {
        MetaData md = client.uploadFile(path, path.getFileName().toString());
        uri = CaraFileUtils.buildURI(client.getRegistryURI(), "cloud", "create", getSubPath(path), md.getId());
    }

    HttpResponse response = client.executeRequest(Request.Post(uri)).returnResponse();

    if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
        throw new IOException();
    }
}

From source file:com.facebook.buck.jvm.java.JarDirectoryStepTest.java

@Test
public void shouldFailIfMainClassMissing() throws IOException {
    Path zipup = folder.newFolder("zipup");

    Path zip = createZip(zipup.resolve("a.zip"), "com/example/Main.class");

    JarDirectoryStep step = new JarDirectoryStep(new ProjectFilesystem(zipup), Paths.get("output.jar"),
            ImmutableSortedSet.of(zip.getFileName()), "com.example.MissingMain", /* manifest file */ null);
    TestConsole console = new TestConsole();
    ExecutionContext context = TestExecutionContext.newBuilder().setConsole(console).build();

    int returnCode = step.execute(context).getExitCode();

    assertEquals(1, returnCode);//from  www. jav  a  2s  .c  o  m
    assertEquals("ERROR: Main class com.example.MissingMain does not exist.\n",
            console.getTextWrittenToStdErr());
}

From source file:grakn.core.console.ConsoleSession.java

void load(Path filePath) throws IOException {
    consoleReader.println("Loading: " + filePath.toString());
    consoleReader.println("...");
    consoleReader.flush();/*from  w w w  .  ja v a  2 s .c om*/

    tx = session.transaction().write();

    try {
        String queries = readFile(filePath);
        executeQuery(queries, false);
        commit();
        consoleReader.println("Successful commit: " + filePath.getFileName().toString());
    } catch (GraknException e) {
        String error = "Failed to load file: " + filePath.getFileName().toString();
        throw new GraknConsoleException(error, e);
    } finally {
        consoleReader.flush();
    }
}

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

private int getVersionNumber(Path versionFile) {
    int result = -1;

    if (!isVersionFile(versionFile)) {
        throw new IllegalStateException(FileUtils.getFileName(versionFile) + " is not a version file.");
    }/*from  ww w .  ja v a 2  s.  c om*/

    Matcher matcher = VERSION_SUFFIX_PATTERN.matcher(versionFile.getFileName().toString());
    String versionStr = null;

    if (matcher.matches()) {
        versionStr = matcher.group(1);
    } else {
        throw new IllegalStateException(""); // ####TODO!!!!
    }

    result = Integer.parseInt(versionStr);

    return (result);
}

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

public int execute(String[] args) {
    try {//from ww w .  j  av a 2 s  .  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.ow2.authzforce.pap.dao.flatfile.FlatFileDAORefPolicyProviderModule.java

private FlatFileDAORefPolicyProviderModule(final Path policyParentDirectory, final String suffix,
        final XACMLParserFactory xacmlParserFactory, final ExpressionFactory expressionFactory,
        final CombiningAlgRegistry combiningAlgRegistry, final int maxPolicySetRefDepth)
        throws IllegalArgumentException {
    assert policyParentDirectory != null;
    assert xacmlParserFactory != null;
    assert expressionFactory != null;
    assert combiningAlgRegistry != null;

    FlatFileDAOUtils.checkFile("RefPolicyProvider's policy directory", policyParentDirectory, true, false);
    final Map<String, Map<PolicyVersion, PolicyEvaluatorSupplier>> updatablePolicyMap = HashObjObjMaps
            .newUpdatableMap();/*from  w  w w  .  ja  va2  s . c o m*/
    // filter matching specifc file suffix for policy files
    final Filter<? super Path> policyFilenameSuffixMatchingDirStreamFilter = new SuffixMatchingDirectoryStreamFilter(
            suffix);
    try (final DirectoryStream<Path> policyParentDirStream = Files.newDirectoryStream(policyParentDirectory,
            FlatFileDAOUtils.SUB_DIRECTORY_STREAM_FILTER)) {
        // Browse directories of policies, one for each policy ID
        for (final Path policyVersionsDir : policyParentDirStream) {
            /*
             * FindBugs considers there is a potential NullPointerException
             * here since getFileName() may be null
             */
            final Path lastPathSegment = policyVersionsDir.getFileName();
            if (lastPathSegment == null) {
                throw new IllegalArgumentException(
                        "Invalid policy directory: no filename (root of filesystem?): " + policyVersionsDir);
            }

            final String policyDirName = lastPathSegment.toString();
            final String policyId;
            try {
                policyId = FlatFileDAOUtils.base64UrlDecode(policyDirName);
            } catch (final IllegalArgumentException e) {
                throw new IllegalArgumentException(
                        "Invalid policy directory: bad filename (not Base64URL-encoded): " + policyDirName, e);
            }

            final Map<PolicyVersion, PolicyEvaluatorSupplier> policySetSuppliersByVersion = HashObjObjMaps
                    .newUpdatableMap();
            // Browse policy versions, one policy file for each version of
            // the current policy
            try (final DirectoryStream<Path> policyVersionsDirStream = Files
                    .newDirectoryStream(policyVersionsDir, policyFilenameSuffixMatchingDirStreamFilter)) {
                for (final Path policyVersionFile : policyVersionsDirStream) {
                    /*
                     * The PolicyEvaluator supplier (from file) allows to
                     * instantiate the Evaluator only if needed, because the
                     * instantiation of a PolicyEvaluator from a file is
                     * expensive.
                     */
                    policySetSuppliersByVersion.put(
                            new PolicyVersion(FlatFileDAOUtils.getPrefix(policyVersionFile, suffix.length())),
                            new PolicyEvaluatorSupplier(policyVersionFile));
                }
            } catch (final IOException e) {
                throw new IllegalArgumentException("Error listing files of each version of policy '" + policyId
                        + "' in directory: " + policyParentDirectory, e);
            }

            updatablePolicyMap.put(policyId, policySetSuppliersByVersion);
        }
    } catch (final IOException e) {
        throw new IllegalArgumentException(
                "Error listing files in policies parent directory '" + policyParentDirectory, e);
    }

    this.policyCache = new PolicyMap<>(updatablePolicyMap);
    this.xacmlParserFactory = xacmlParserFactory;
    this.expressionFactory = expressionFactory;
    this.combiningAlgRegistry = combiningAlgRegistry;
    this.maxPolicyRefDepth = maxPolicySetRefDepth;
}

From source file:de.alexkamp.sandbox.ChrootSandboxFactory.java

@Override
public void deleteSandbox(final SandboxData sandbox) {
    File copyDir = sandbox.getBaseDir();

    try {/*from   w  ww. j  a v  a2  s .c  om*/
        final AtomicInteger depth = new AtomicInteger(0);
        Files.walkFileTree(copyDir.toPath(), new FileVisitor<Path>() {
            @Override
            public FileVisitResult preVisitDirectory(Path path, BasicFileAttributes basicFileAttributes)
                    throws IOException {
                int d = depth.getAndIncrement();

                // see whether the mounts are gone
                if (1 == d) {
                    for (Mount m : sandbox) {
                        if (path.endsWith(m.getMountPoint().substring(1))) {
                            if (0 != path.toFile().listFiles().length) {
                                throw new IllegalArgumentException(
                                        path.getFileName() + " has not been unmounted.");
                            }
                        }
                    }
                }

                return FileVisitResult.CONTINUE;
            }

            @Override
            public FileVisitResult visitFile(Path path, BasicFileAttributes basicFileAttributes)
                    throws IOException {
                Files.delete(path);
                return FileVisitResult.CONTINUE;
            }

            @Override
            public FileVisitResult visitFileFailed(Path path, IOException e) throws IOException {
                return FileVisitResult.CONTINUE;
            }

            @Override
            public FileVisitResult postVisitDirectory(Path path, IOException e) throws IOException {
                Files.delete(path);
                depth.decrementAndGet();
                return FileVisitResult.CONTINUE;
            }
        });
    } catch (IOException e) {
        throw new SandboxException(e);
    }
}