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:org.apache.taverna.robundle.manifest.Manifest.java

/**
 * Guess media type based on extension/*from w w  w  .ja  v  a  2  s.  c  o m*/
 * 
 * @see http://wf4ever.github.io/ro/bundle/#media-types
 * 
 * @param file
 *            A Path to a file
 * @return media-type, e.g. <code>application/xml</code> or
 *         <code>text/plain; charset="utf-8"</code>
 */
public String guessMediaType(Path file) {
    if (file.getFileName() == null)
        return null;
    String filename = file.getFileName().toString().toLowerCase(Locale.ENGLISH);
    if (filename.endsWith(".txt"))
        return "text/plain; charset=\"utf-8\"";
    if (filename.endsWith(".ttl"))
        return "text/turtle; charset=\"utf-8\"";
    if (filename.endsWith(".rdf") || filename.endsWith(".owl"))
        return "application/rdf+xml";
    if (filename.endsWith(".json"))
        return "application/json";
    if (filename.endsWith(".jsonld"))
        return "application/ld+json";
    if (filename.endsWith(".xml"))
        return "application/xml";

    // A few extra, common ones

    if (filename.endsWith(".png"))
        return "image/png";
    if (filename.endsWith(".svg"))
        return "image/svg+xml";
    if (filename.endsWith(".jpg") || filename.endsWith(".jpeg"))
        return "image/jpeg";
    if (filename.endsWith(".pdf"))
        return "application/pdf";
    return "application/octet-stream";
}

From source file:net.minecrell.ice.launch.transformers.DeobfuscationTransformer.java

public DeobfuscationTransformer() throws Exception {
    Path path = (Path) Launch.blackboard.get("ice.deobf-srg");
    String name = path.getFileName().toString();
    boolean gzip = name.endsWith(".gz");

    ImmutableBiMap.Builder<String, String> classes = ImmutableBiMap.builder();
    ImmutableTable.Builder<String, String, String> fields = ImmutableTable.builder();
    ImmutableTable.Builder<String, String, String> methods = ImmutableTable.builder();

    try (BufferedReader reader = new BufferedReader(new InputStreamReader(
            gzip ? new GZIPInputStream(Files.newInputStream(path)) : Files.newInputStream(path),
            StandardCharsets.UTF_8))) {
        String line;// w  w  w. j a va2 s.c o m
        while ((line = reader.readLine()) != null) {
            if ((line = line.trim()).isEmpty())
                continue;

            String[] parts = StringUtils.split(line, ' ');
            if (parts.length < 3) {
                System.out.println("Invalid line: " + line);
                continue;
            }

            MappingType type = MappingType.of(parts[0]);
            if (type == null) {
                System.out.println("Invalid mapping: " + line);
                continue;
            }

            String[] source, dest;
            switch (type) {
            case CLASS:
                classes.put(parts[1], parts[2]);
                break;
            case FIELD:
                source = getSignature(parts[1]);
                dest = getSignature(parts[2]);
                String fieldType = getFieldType(source[0], source[1]);
                fields.put(source[0], source[1] + ':' + fieldType, dest[1]);
                if (fieldType != null)
                    fields.put(source[0], source[1] + ":null", dest[1]);
                break;
            case METHOD:
                source = getSignature(parts[1]);
                dest = getSignature(parts[3]);
                methods.put(source[0], source[1] + parts[2], dest[1]);
                break;
            }
        }
    }

    this.classes = classes.build();
    this.rawFields = fields.build();
    this.rawMethods = methods.build();

    this.fields = Maps.newHashMapWithExpectedSize(rawFields.size());
    this.methods = Maps.newHashMapWithExpectedSize(rawMethods.size());
}

From source file:com.dancorder.Archiverify.SynchingVisitor.java

@Override
public void visitFile(Path relativeFilePath, FileExistence existence) {
    try {/* w  w  w.ja  v a  2  s. c om*/
        if (isNotInErrorPath(relativeFilePath) && !fileHashStoreFactory.isHashFile(relativeFilePath)) {
            Path file1 = root1.resolve(relativeFilePath);
            Path file2 = root2.resolve(relativeFilePath);

            visitedFilesByDirectory.get(currentRelativeDirectoryPath).add(relativeFilePath.getFileName());

            Pair<FileHashStore, FileHashStore> hashStorePair = hashStoresByDirectory
                    .get(currentRelativeDirectoryPath);
            List<Action> newActions = syncLogic.compareFiles(file1, hashStorePair.getLeft(), file2,
                    hashStorePair.getRight());
            actions.addAll(newActions);
        }
    } catch (Exception e) {
        actions.add(new WarningAction(String.format(
                "Error caught visiting file %s this file will not be synched. %s", relativeFilePath, e)));
    }
}

From source file:au.org.ands.vocabs.toolkit.provider.harvest.FileHarvestProvider.java

/** Do a harvest. Update the message parameter with the result
 * of the harvest.//from  w ww.j  a v a 2s.c  o  m
 * NB: if delete is true, Tomcat must have write access, in order
 * to be able to delete the file successfully. However, a failed
 * deletion will not per se cause the subtask to fail.
 * @param version The version to which access points are to be added.
 * @param format The format of the file(s) to be harvested.
 * @param filePath The path to the file or directory to be harvested.
 * @param outputPath The directory in which to store output files.
 * @param delete True, if successfully harvested files are to be deleted.
 * @param results HashMap representing the result of the harvest.
 * @return True, iff the harvest succeeded.
 */
public final boolean getHarvestFiles(final Version version, final String format, final String filePath,
        final String outputPath, final boolean delete, final HashMap<String, String> results) {
    ToolkitFileUtils.requireDirectory(outputPath);
    Path filePathPath = Paths.get(filePath);
    Path outputPathPath = Paths.get(outputPath);
    if (Files.isDirectory(filePathPath)) {
        logger.debug("Harvesting file(s) from directory " + filePath);
        try (DirectoryStream<Path> stream = Files.newDirectoryStream(filePathPath)) {
            for (Path entry : stream) {
                // Only harvest files. E.g., no recursive
                // directory searching.
                if (Files.isRegularFile(entry)) {
                    logger.debug("Harvesting file:" + entry.toString());
                    Path target = outputPathPath.resolve(entry.getFileName());
                    Files.copy(entry, target, StandardCopyOption.REPLACE_EXISTING);
                    AccessPointUtils.createFileAccessPoint(version, format, target);
                    if (delete) {
                        logger.debug("Deleting file: " + entry.toString());
                        try {
                            Files.delete(entry);
                        } catch (AccessDeniedException e) {
                            logger.error("Unable to delete file: " + entry.toString(), e);
                        }
                    }
                }
            }
        } catch (DirectoryIteratorException | IOException ex) {
            results.put(TaskStatus.EXCEPTION, "Exception in getHarvestFiles while copying file");
            logger.error("Exception in getHarvestFiles while copying file:", ex);
            return false;
        }
    } else {
        logger.debug("Harvesting file: " + filePath);
        try {
            Path target = outputPathPath.resolve(filePathPath.getFileName());
            Files.copy(filePathPath, target, StandardCopyOption.REPLACE_EXISTING);
            AccessPointUtils.createFileAccessPoint(version, format, target);
            if (delete) {
                logger.debug("Deleting file: " + filePathPath.toString());
                try {
                    Files.delete(filePathPath);
                } catch (AccessDeniedException e) {
                    logger.error("Unable to delete file: " + filePathPath.toString(), e);
                }
            }
        } catch (IOException e) {
            results.put(TaskStatus.EXCEPTION, "Exception in getHarvestFiles while copying file");
            logger.error("Exception in getHarvestFiles while copying file:", e);
            return false;
        }
    }
    // If we reached here, success, so return true.
    return true;
}

From source file:com.splicemachine.derby.stream.control.ControlDataSetProcessor.java

private InputStream newInputStream(DistributedFileSystem dfs, @Nonnull Path p, OpenOption... options)
        throws IOException {
    InputStream value = dfs.newInputStream(p, options);
    String s = p.getFileName().toString();
    assert s != null;
    if (s.endsWith("gz")) {
        //need to open up a decompressing inputStream
        value = new GZIPInputStream(value);
    }//from w  w  w.  jav a2 s.c  o m
    return value;
}

From source file:acromusashi.stream.ml.common.spout.WatchTextBatchSpout.java

/**
 * ???????????????????/*from  w  w w . j a  v a 2s . c  om*/
 * 
 * @param collector Collector
 * @throws IOException 
 * @throws InterruptedException ?
 */
@SuppressWarnings({ "rawtypes" })
protected void checkDataFile(TridentCollector collector) throws IOException, InterruptedException {
    // ?????????????????
    if (this.isInitialReaded == false) {
        List<String> fileContents = FileUtils.readLines(this.targetFile);
        emitTuples(fileContents, collector);
        this.isInitialReaded = true;

        // 
        Path dirPath = new File(this.dataFileDir).toPath();
        FileSystem fileSystem = dirPath.getFileSystem();
        this.watcherService = fileSystem.newWatchService();
        this.watchKey = dirPath.register(this.watcherService,
                new Kind[] { StandardWatchEventKinds.ENTRY_CREATE, StandardWatchEventKinds.ENTRY_MODIFY });

        return;
    }

    // ????????
    WatchKey detectedKey = this.watcherService.poll(1, TimeUnit.SECONDS);

    // ???????????????????????
    if (detectedKey == null || detectedKey.equals(this.watchKey) == false) {
        return;
    }

    try {
        // ???????????????
        for (WatchEvent event : detectedKey.pollEvents()) {

            Path filePath = (Path) event.context();

            // ?????????????
            if (filePath == null
                    || this.targetFile.toPath().getFileName().equals(filePath.getFileName()) == false) {
                continue;
            }

            List<String> fileContents = FileUtils.readLines(this.targetFile);
            emitTuples(fileContents, collector);
        }
    } finally {
        detectedKey.reset();
    }
}

From source file:ch.cyberduck.core.Local.java

public AttributedList<Local> list(final Filter<String> filter) throws AccessDeniedException {
    final AttributedList<Local> children = new AttributedList<Local>();
    try (DirectoryStream<Path> stream = Files.newDirectoryStream(Paths.get(path),
            new DirectoryStream.Filter<Path>() {
                @Override//from   w w w.  j  a  v a2s.  co  m
                public boolean accept(final Path entry) throws IOException {
                    if (null == entry.getFileName()) {
                        return false;
                    }
                    return filter.accept(entry.getFileName().toString());
                }
            })) {
        for (Path entry : stream) {
            children.add(LocalFactory.get(entry.toString()));
        }
    } catch (IOException e) {
        throw new LocalAccessDeniedException(String.format("Error listing files in directory %s", path), e);
    }
    return children;
}

From source file:com.eqbridges.vertx.VerticleModuleMojo.java

@Override
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
    Path to = toPath.resolve(fromPath.relativize(file));
    Files.copy(file, to, copyOption);
    log.info(format("Copied file [%s] -> [%s]", file.getFileName(), to.normalize()));
    return FileVisitResult.CONTINUE;
}

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

/**
 * Construct from dir request.//w w w .  ja v  a  2 s  .  c o m
 * @param dir the dir
 * @param needSize the need size
 * @return the folder info
 * @throws C5CException the connector exception
 */
private Set<FileProperties> constructFromDirRequest(Path dir, boolean needSize) throws C5CException {
    Set<FileProperties> props = new HashSet<>();

    // add dirs
    try {
        for (Path d : Files.newDirectoryStream(dir, new DirectoryStream.Filter<Path>() {
            @Override
            public boolean accept(Path entry) throws IOException {
                return Files.isDirectory(entry) && checkFolderName(entry.getFileName().toString());
            }
        })) {
            boolean isProtected = isProtected(d);
            FileProperties fp = buildForDirectory(d.getFileName().toString(), isProtected,
                    new Date(Files.getLastModifiedTime(d).toMillis()));
            props.add(fp);
        }
    } catch (IOException | SecurityException e) {
        throw new C5CException(String.format("Error while fetching sub-directories from [%s]: %s",
                dir.toAbsolutePath().toString(), e.getMessage()));
    }

    // add files
    try {
        for (Path f : Files.newDirectoryStream(dir, new DirectoryStream.Filter<Path>() {
            @Override
            public boolean accept(Path entry) throws IOException {
                return Files.isRegularFile(entry) && checkFilename(entry.getFileName().toString());
            }
        })) {
            props.add(constructFileInfo(f, needSize));
        }
    } catch (IOException | SecurityException e) {
        throw new C5CException(String.format("Error while fetching files from [%s]: %s",
                dir.toAbsolutePath().toString(), e.getMessage()));
    }

    return props;
}

From source file:dk.dma.msiproxy.common.repo.ThumbnailService.java

/**
 * Returns or creates the a thumbnail for the given file if it is an image.
 * Otherwise, null is returned/*from   w w  w  .j a v  a2  s.c  o  m*/
 *
 * @param file the file to create a thumbnail for
 * @param type the type of image
 * @param size the size of the thumbnail
 * @return the thumbnail file or null if none was found or created
 */
public Path createThumbnail(Path file, String type, IconSize size) {

    try {
        // Construct the thumbnail name by appending "_thumb_size" to the file name
        String thumbName = String.format("%s_thumb_%d.%s",
                FilenameUtils.removeExtension(file.getFileName().toString()), size.getSize(),
                FilenameUtils.getExtension(file.getFileName().toString()));

        // Check if the thumbnail already exists
        Path thumbFile = file.getParent().resolve(thumbName);
        if (Files.isRegularFile(thumbFile) && Files.getLastModifiedTime(thumbFile).toMillis() >= Files
                .getLastModifiedTime(file).toMillis()) {
            return thumbFile;
        }

        // Check whether to use VIPS or java
        if (StringUtils.isNotBlank(vipsCmd) && vipsFileTypes.contains(type.toLowerCase())) {
            // Use VIPS
            createThumbnailUsingVips(file, thumbFile, size);

        } else {
            // Use java APIs
            createThumbnailUsingJava(file, thumbFile, size);
        }

        return thumbFile;

    } catch (Throwable e) {
        // Alas, no thumbnail
        return null;
    }
}