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:duthientan.mmanm.com.CipherRSA.java

@Override
public void encrypt(String filePath) {
    try {//from  w  ww  .ja va  2 s .  com
        Cipher ecipher = Cipher.getInstance("RSA");
        ecipher.init(Cipher.ENCRYPT_MODE, publicKey);
        Path path = Paths.get(filePath);
        String encryptFilePath = path.getParent().toString() + "/" + "RSA" + "_"
                + path.getFileName().toString();
        byte[] data = Files.readAllBytes(path);
        byte[] textEncrypted = null;
        int chunkSize = 245;
        if (data.length < 245) {
            textEncrypted = ecipher.doFinal(data);
        } else {
            for (int i = 0; i < data.length; i += chunkSize) {
                byte[] segment = Arrays.copyOfRange(data, i,
                        i + chunkSize > data.length ? data.length : i + chunkSize);
                byte[] segmentEncrypted = ecipher.doFinal(segment);
                textEncrypted = ArrayUtils.addAll(textEncrypted, segmentEncrypted);
            }
        }
        FileOutputStream fos = new FileOutputStream(encryptFilePath);
        fos.write(textEncrypted);
        fos.close();
    } catch (NoSuchAlgorithmException ex) {
        Logger.getLogger(CipherRSA.class.getName()).log(Level.SEVERE, null, ex);
    } catch (NoSuchPaddingException ex) {
        Logger.getLogger(CipherRSA.class.getName()).log(Level.SEVERE, null, ex);
    } catch (InvalidKeyException ex) {
        Logger.getLogger(CipherRSA.class.getName()).log(Level.SEVERE, null, ex);
    } catch (IOException ex) {
        Logger.getLogger(CipherRSA.class.getName()).log(Level.SEVERE, null, ex);
    } catch (IllegalBlockSizeException ex) {
        Logger.getLogger(CipherRSA.class.getName()).log(Level.SEVERE, null, ex);
    } catch (BadPaddingException ex) {
        Logger.getLogger(CipherRSA.class.getName()).log(Level.SEVERE, null, ex);
    }
}

From source file:nl.mpi.lamus.filesystem.implementation.LamusWorkspaceDirectoryHandler.java

/**
 * @see WorkspaceDirectoryHandler#ensurePathIsAllowed(String)
 *///from   w w  w  .  j a  v a 2 s.c  o m
@Override
public void ensurePathIsAllowed(String path) throws DisallowedPathException {

    Path pathToCheck = Paths.get("", path);

    Iterator<Path> pathIterator = pathToCheck.iterator();
    while (pathIterator.hasNext()) {
        Path currentPathItem = pathIterator.next();
        String nameToMatch = currentPathItem.getFileName().toString();
        for (String regex : disallowedFolderNamesWorkspace) {
            if (Pattern.matches(regex, nameToMatch)) {
                String message = "The path [" + path + "] contains a disallowed file/folder name ("
                        + nameToMatch + ")";
                throw new DisallowedPathException(path, message);
            }
        }
    }
}

From source file:com.c4om.autoconf.ulysses.configanalyzer.configurationextractor.LocalCopyConfigurationsExtractor.java

/**
 * This method performs the extraction. 
 * The context must contain: //  w w  w .j av  a  2s  .c o m
 * <ul>
 * <li>One or more {@link ConfigureAppsTarget} returned by {@link ConfigurationAnalysisContext#getInputTargets()}. 
 * All the referenced {@link Application} must return "file://" URIs at {@link Application#getConfigurationURIs()}.</li>
 * <li>An {@link Environment} object returned by {@link ConfigurationAnalysisContext#getInputEnvironment()}, from which 
 * the configuration of the runtime where all the referenced applications are run.</li>
 * </ul>
 * @see com.c4om.autoconf.ulysses.interfaces.configanalyzer.configurationextractor.ConfigurationsExtractor#extractConfigurations(com.c4om.autoconf.ulysses.interfaces.configanalyzer.core.datastructures.ConfigurationAnalysisContext)
 */
@Override
public void extractConfigurations(ConfigurationAnalysisContext context)
        throws ConfigurationExtractionException {
    try {
        Path tempFolderPath = Files.createTempDirectory("ConfigurationAnalyzer");
        for (Target currentTarget : context.getInputTargets().values()) {
            if (!(currentTarget instanceof ConfigureAppsTarget)) {
                continue;
            }
            Properties configurationAnalyzerSettings = context.getConfigurationAnalyzerSettings();
            String runtimeConfigurationDirName = configurationAnalyzerSettings
                    .getProperty(PROPERTY_KEY_RUNTIME_CONFIGURATION_FILENAME);
            if (runtimeConfigurationDirName == null) {
                throw new ConfigurationExtractionException(
                        "Property '" + PROPERTY_KEY_RUNTIME_CONFIGURATION_FILENAME + "' not found");
            }
            ConfigureAppsTarget currentConfigureAppsTarget = (ConfigureAppsTarget) currentTarget;
            for (String appId : currentConfigureAppsTarget.getParameters().keySet()) {
                Path subfolderForApp = tempFolderPath.resolve(Paths.get(appId));
                List<File> copiedFiles = new ArrayList<>();
                Files.createDirectory(subfolderForApp);
                //We copy the application configuration files to the root of the directory.
                //We also copy the runtime configuration.
                Application currentApplication = (Application) currentConfigureAppsTarget.getParameters()
                        .get(appId);
                for (URI configurationURI : currentApplication.getConfigurationURIs()) {
                    //TODO: Let other configuration URIs live, specially, SVN-based ones, which should be extracted by other extractors. This would require some refactoring. 
                    if (!configurationURI.getScheme().equalsIgnoreCase("file")) {
                        throw new ConfigurationExtractionException(
                                "URI '" + configurationURI.toString() + "' does not have a 'file' scheme");
                    }
                    Path configurationPath = Paths.get(configurationURI);
                    Path configurationPathName = configurationPath.getFileName();
                    if (configurationPathName.toString().equals(runtimeConfigurationDirName)) {
                        throw new ConfigurationExtractionException(
                                "One of the application configuration files has the same name than the runtime configuration folder ('"
                                        + runtimeConfigurationDirName + "')");
                    }

                    Path destinationConfigurationPath = Files.copy(configurationPath,
                            subfolderForApp.resolve(configurationPathName), REPLACE_EXISTING);
                    File destinationConfigurationFile = destinationConfigurationPath.toFile();
                    copiedFiles.add(destinationConfigurationFile);

                }

                File runtimeConfigurationDirectory = new File(
                        context.getInputEnvironment().getApplicationConfigurations().get(appId));
                File destinationRuntimeConfigurationDirectory = subfolderForApp
                        .resolve(runtimeConfigurationDirName).toFile();
                FileUtils.copyDirectory(runtimeConfigurationDirectory,
                        destinationRuntimeConfigurationDirectory);
                copiedFiles.add(destinationRuntimeConfigurationDirectory);

                ExtractedConfiguration<File> extractedConfiguration = new FileExtractedConfiguration(appId,
                        currentTarget, copiedFiles);
                context.getExtractedConfigurations().add(extractedConfiguration);
            }
        }
    } catch (IOException e) {
        throw new ConfigurationExtractionException(e);
    }

}

From source file:com.bc.fiduceo.ingest.IngestionToolTest.java

@Test
public void testGetMatcher() {
    final Path path = mock(Path.class);
    final Path fileName = mock(Path.class);
    when(fileName.toString()).thenReturn("2345.nc");
    when(path.getFileName()).thenReturn(fileName);

    Pattern pattern = Pattern.compile("[0-9]{4}.nc");
    Matcher matcher = IngestionTool.getMatcher(path, pattern);
    assertTrue(matcher.matches());/* www .ja v a2  s . c  o m*/

    pattern = Pattern.compile("\\d.nc");
    matcher = IngestionTool.getMatcher(path, pattern);
    assertFalse(matcher.matches());
}

From source file:audiomanagershell.commands.PlayCommand.java

@Override
public void execute() throws CommandException, IOException {
    String OS = System.getProperty("os.name").toLowerCase();
    Path file;
    if (OS.equals("windows"))
        file = Paths.get(this.pathRef.toString() + "\\" + this.arg);
    else/*  w  w w  .ja v a  2 s .c o m*/
        file = Paths.get(this.pathRef.toString() + "/" + this.arg);
    String fileName = file.getFileName().toString();
    List<String> acceptedExtensions = Arrays.asList("wav", "mp3", "flac", "mp4");
    //Get the extension of the file
    String extension = FilenameUtils.getExtension(fileName);
    if (Files.isRegularFile(file) && Files.isReadable(file)) {
        if (acceptedExtensions.contains(extension)) {
            Desktop desktop = Desktop.getDesktop();
            desktop.open(file.toFile());
            System.out.printf("The file %s will open shortly...\n", fileName);
        } else {
            throw new NotAudioFileException(fileName);
        }
    } else {
        throw new CommandException(file.toString() + " not a file or can't read");
    }
}

From source file:com.marklogic.entityservices.examples.ExamplesBase.java

private void importOrDescend(Path directory, WriteHostBatcher batcher, String collection, Format format) {
    try (DirectoryStream<Path> stream = Files.newDirectoryStream(directory)) {
        for (Path entry : stream) {
            if (entry.toFile().isDirectory()) {
                logger.info("Reading subdirectory " + entry.getFileName().toString());
                importOrDescend(entry, batcher, collection, format);
            } else {
                logger.debug("Adding " + entry.getFileName().toString());
                String uri = entry.toUri().toString();
                if (collection != null) {
                    DocumentMetadataHandle metadata = new DocumentMetadataHandle().withCollections(collection) //
                            .withPermission("race-reader", Capability.READ) //
                            .withPermission("race-writer", Capability.INSERT, Capability.UPDATE);
                    batcher.add(uri, metadata, new FileHandle(entry.toFile()).withFormat(format));
                } else {
                    batcher.add(uri, new FileHandle(entry.toFile()).withFormat(format));
                }/*from   w ww  . ja  v a2s . c  o  m*/
                logger.debug("Inserted " + format.toString() + " document " + uri);
            }
        }

    } catch (IOException e) {
        e.printStackTrace();
    }
}

From source file:com.sqs.tq.fdc.Main.java

public void analyzeSingleFile(Path file, Reporter r) throws Exception {
    Collector fc = new FileCollector();
    List<FileData> data = fc.collect(file);

    Analyser a = new FileVariantAnalyser();
    ObjectNode reportData = a.analyse(data);
    reportData.put("name", file.getFileName().toString());

    r.report(reportData);//from  w w w. j a  v  a2  s  .co m
}

From source file:com.marklogic.entityservices.e2e.ExamplesBase.java

private void importOrDescend(Path directory, WriteHostBatcher batcher, String collection, Format format) {
    try (DirectoryStream<Path> stream = Files.newDirectoryStream(directory)) {
        for (Path entry : stream) {
            if (entry.toFile().isDirectory()) {
                logger.info("Reading subdirectory " + entry.getFileName().toString());
                importOrDescend(entry, batcher, collection, format);
            } else {
                logger.debug("Adding " + entry.getFileName().toString());
                String uri = entry.toUri().toString();
                if (collection != null) {
                    DocumentMetadataHandle metadata = new DocumentMetadataHandle().withCollections(collection) //
                            .withPermission("nwind-reader", Capability.READ) //
                            .withPermission("nwind-writer", Capability.INSERT, Capability.UPDATE);
                    batcher.add(uri, metadata, new FileHandle(entry.toFile()).withFormat(format));
                } else {
                    batcher.add(uri, new FileHandle(entry.toFile()).withFormat(format));
                }//from  w  w w  .ja va 2 s.  c  o  m
                logger.debug("Inserted " + format.toString() + " document " + uri);
            }
        }

    } catch (IOException e) {
        e.printStackTrace();
    }
}

From source file:codes.thischwa.c5c.requestcycle.impl.FilemanagerIconResolver.java

protected void collectIcons(String iconPath, java.nio.file.Path iconFolder, PathBuilder urlPath) {
    Map<String, String> iconsPerType = new HashMap<>();
    try {/*from   w  ww .  j ava2s . c  o  m*/
        for (java.nio.file.Path icon : Files.newDirectoryStream(iconFolder,
                new DirectoryStream.Filter<java.nio.file.Path>() {
                    @Override
                    public boolean accept(java.nio.file.Path entry) throws IOException {
                        if (Files.isDirectory(entry))
                            return false;
                        String name = entry.getFileName().toString();
                        return !name.contains("_") && name.endsWith("png");
                    }
                })) {
            String name = icon.getFileName().toString();
            String knownExtension = FilenameUtils.getBaseName(name);
            iconsPerType.put(knownExtension, urlPath.addFile(name));
        }
    } catch (IOException e) {
        throw new RuntimeException("Couldn't read the icon files!", e);
    }

    iconsPerType.put(IconResolver.key_directory, urlPath.addFile(directoryIcon));
    iconsPerType.put(IconResolver.key_default, urlPath.addFile(defaultIcon));
    iconsPerType.put(IconResolver.key_directory_lock, urlPath.addFile("locked_" + directoryIcon));
    iconsPerType.put(IconResolver.key_default_lock, urlPath.addFile("locked_" + defaultIcon));

    iconCache.put(iconPath, new IconRequestResolver(iconsPerType));
}

From source file:jsonbrowse.JsonBrowse.java

@Override
public void run() {
    try {/*  ww  w  . java 2 s  . c o  m*/
        WatchKey key = watcher.take();
        while (key != null) {

            if (watching) {
                for (WatchEvent event : key.pollEvents()) {
                    if (event.context() instanceof Path) {
                        Path path = (Path) (event.context());
                        if (path.getFileName().equals(jsonFilePath.getFileName())) {
                            if (path.toFile().length() > 0)
                                updateModel();
                        }
                    }
                }
            }
            key.reset();
            key = watcher.take();
        }
    } catch (InterruptedException | IOException ex) {
        Logger.getLogger(JsonBrowse.class.getName()).log(Level.SEVERE, null, ex);
    }
    System.out.println("Stopping thread.");
}