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:com.spectralogic.ds3client.helpers.FileObjectPutter_Test.java

@Test
public void testRelativeSymlink() throws IOException, URISyntaxException {
    assumeFalse(Platform.isWindows());//from  w  w w  .j a  va2 s  . co m
    final Path tempDir = Files.createTempDirectory("ds3_file_object_rel_test_");
    final Path tempPath = Files.createTempFile(tempDir, "temp_", ".txt");

    try {
        try (final SeekableByteChannel channel = Files.newByteChannel(tempPath, StandardOpenOption.CREATE,
                StandardOpenOption.TRUNCATE_EXISTING, StandardOpenOption.WRITE)) {
            channel.write(ByteBuffer.wrap(testData));
        }

        final Path symLinkPath = tempDir.resolve("sym_" + tempPath.getFileName().toString());
        final Path relPath = Paths.get("..", getParentDir(tempPath), tempPath.getFileName().toString());

        LOG.info("Creating symlink from " + symLinkPath.toString() + " to " + relPath.toString());

        Files.createSymbolicLink(symLinkPath, relPath);
        getFileWithPutter(tempDir, symLinkPath);

    } finally {
        Files.deleteIfExists(tempPath);
        Files.deleteIfExists(tempDir);
    }
}

From source file:com.vns.pdf.impl.PdfDocument.java

private PdfDocument(String pdfFileName) throws IOException {
    this.pdfFileName = pdfFileName;
    setWorkingDir();//from  ww  w  .  ja v a 2s. co m
    Path filePath = Paths.get(pdfFileName);
    PosixFileAttributes attrs = Files.getFileAttributeView(filePath, PosixFileAttributeView.class)
            .readAttributes();
    String textAreaFileName = filePath.getFileName().toString() + "_" + filePath.toAbsolutePath().hashCode()
            + "_" + attrs.size() + "_" + attrs.lastModifiedTime().toString().replace(":", "_") + ".xml";
    textAreaFilePath = Paths.get(workingDir.toAbsolutePath().toString(), textAreaFileName);
    pdfTextStripper = new CustomPDFTextStripper();
    document = PDDocument.load(new File(pdfFileName));
    pdfRenderer = new PDFRenderer(document);

    if (Files.notExists(textAreaFilePath, LinkOption.NOFOLLOW_LINKS)) {
        pdfTextStripper.setSortByPosition(false);
        pdfTextStripper.setStartPage(0);
        pdfTextStripper.setEndPage(document.getNumberOfPages());

        this.doc = new Doc(new ArrayList<>(), new ArrayList<>());
        for (int i = 0; i < document.getNumberOfPages(); i++) {
            PDPage pdPage = document.getPage(i);
            PDRectangle box = pdPage.getMediaBox();
            this.doc.getPages().add(new Page(new ArrayList<>(), new ArrayList<>(), (int) box.getWidth(),
                    (int) box.getHeight()));
        }

        Writer dummy = new OutputStreamWriter(new ByteArrayOutputStream());
        try {
            pdfTextStripper.writeText(document, dummy);
        } catch (Exception ex) {
            LOGGER.error(ex.getMessage(), ex);
        }
        parseBookmarksAnnotation();
        createTextAreaFile();
        //document.save(pdfFileName + ".pdf");
    } else {
        loadTextAreaFile();
    }
}

From source file:hudson.plugins.report.jck.parsers.JtregReportParser.java

private String suiteName(Path path) {
    for (Entry<String, ArchiveFactory> factory : SUPPORTED_ARCHIVE_TYPES_MAP.entrySet()) {
        String pathName = path.getFileName().toString();
        if (pathName.toLowerCase().endsWith(factory.getKey())) {
            return pathName.substring(0, pathName.length() - factory.getKey().length());
        }//  ww  w . j  a va 2s. c  o m
    }
    return path.getFileName().toString();
}

From source file:io.stallion.dataAccess.file.FilePersisterBase.java

@Override
public List<T> fetchAll() {
    File target = new File(Settings.instance().getTargetFolder());
    if (!target.isDirectory()) {
        if (getItemController().isWritable()) {
            target.mkdirs();/* w w  w. j  a v  a 2  s.  com*/
        } else {
            throw new ConfigException(String.format(
                    "The JSON bucket %s (path %s) is read-only, but does not exist in the file system. Either create the folder, make it writable, or remove it from the configuration.",
                    getItemController().getBucket(), getBucketFolderPath()));
        }
    }
    TreeVisitor visitor = new TreeVisitor();
    Path folderPath = FileSystems.getDefault().getPath(getBucketFolderPath());
    try {
        Files.walkFileTree(folderPath, visitor);
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
    List<T> objects = new ArrayList<>();
    for (Path path : visitor.getPaths()) {
        if (!matchesExtension(path.toString())) {
            continue;
        }

        if (path.toString().contains(".#")) {
            continue;
        }
        if (path.getFileName().startsWith(".")) {
            continue;
        }
        T o = fetchOne(path.toString());
        if (o != null) {
            objects.add(o);
        }

    }
    objects.sort(new PropertyComparator<T>(sortField));
    if (sortDirection.toLowerCase().equals("desc")) {
        Collections.reverse(objects);
    }

    return objects;
}

From source file:com.aol.advertising.qiao.injector.file.watcher.QiaoFileManager.java

private Path renameToTmpFilePath(Path sourceFilePath) throws IOException {
    String tmp_name = UUID.randomUUID() + "_" + sourceFilePath.getFileName().toString();
    Path new_path = sourceFilePath.resolveSibling(tmp_name);
    Files.move(sourceFilePath, new_path, StandardCopyOption.ATOMIC_MOVE);

    return new_path;
}

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

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

    Path first = createZip(zipup.resolve("first.zip"), "dir/file1.txt", "dir/file2.txt",
            "com/example/Main.class");

    JarDirectoryStep step = new JarDirectoryStep(new ProjectFilesystem(zipup), Paths.get("output.jar"),
            ImmutableSet.of(first.getFileName()), "com.example.Main", /* manifest file */ null,
            /* merge manifests */ true, /* blacklist */ ImmutableSet.of(".*2.*"));

    ExecutionContext context = TestExecutionContext.newInstance();

    int returnCode = step.execute(context);

    assertEquals(0, returnCode);/*from   w w w .j a  v a2 s. c  o m*/

    Path zip = zipup.resolve("output.jar");

    // file1.txt, Main.class, plus the manifest.
    assertZipFileCountIs(3, zip);
    assertZipContains(zip, "dir/file1.txt");
    assertZipDoesNotContain(zip, "dir/file2.txt");
}

From source file:hudson.plugins.report.jck.parsers.JtregReportParser.java

private ArchiveInputStream streamPath(Path path) throws IOException {
    for (Entry<String, ArchiveFactory> factory : SUPPORTED_ARCHIVE_TYPES_MAP.entrySet()) {
        String pathName = path.getFileName().toString().toLowerCase();
        if (pathName.endsWith(factory.getKey())) {
            InputStream stream = new BufferedInputStream(Files.newInputStream(path));
            return factory.getValue().create(stream);
        }/*from   w  w  w.ja v a  2s.  c  o  m*/
    }
    throw new IOException("Unsupported archive format: " + path.getFileName());
}

From source file:joachimeichborn.geotag.ui.parts.PicturesView.java

@Inject
public void setSelection(
        @Named(IServiceConstants.ACTIVE_SELECTION) @Optional final PictureSelection aPictureSelection) {
    final MPart activePart = partService.getActivePart();
    if (activePart != null && activePart.getElementId().equals(PICTURES_PART_ID)) {
        if (nameLabel != null && aPictureSelection != null) {
            final List<Picture> pictures = aPictureSelection.getSelection();
            selectedPicturesLabel.setText(String.format(SELECTED_PICTURES, pictures.size()));
            if (pictures.size() == 1) {
                final Picture picture = pictures.get(0);
                final Path file = picture.getFile();
                lastKey = new PreviewKey(file.toString(), 160, 120);
                preview.setImage(previewRepo.getPreview(lastKey, true, this));
                previewContainer.setVisible(true);
                previewLabel.repaint();/*  w  ww  .ja va2  s . c  o m*/
                nameLabel.setText(file.getFileName().toString());
                pathLabel.setText(file.getParent().toString());
                fillGeocodingDetails(picture.getGeocoding());
            } else {
                nameLabel.setText("");
                pathLabel.setText("");
                previewContainer.setVisible(false);
                fillGeocodingDetails(null);
            }
        }
    }
}

From source file:ch.bender.evacuate.Runner.java

/**
 * run//from w  ww.ja va2 s .c om
 * <p>
 * @throws Exception 
 */
public void run() throws Exception {
    checkDirectories();
    initExcludeMatchers();

    myEvacuateCandidates = new TreeMap<>();
    myFailedChainPreparations = Collections.synchronizedMap(new HashMap<>());
    myFutures = new HashSet<>();
    myExclusionDirCount = 0;
    myEvacuationDirCount = 0;
    myExclusionFileCount = 0;
    myEvacuationFileCount = 0;

    Files.walkFileTree(myBackupDir, new SimpleFileVisitor<Path>() {
        /**
         * @see java.nio.file.SimpleFileVisitor#visitFileFailed(java.lang.Object, java.io.IOException)
         */
        @Override
        public FileVisitResult visitFileFailed(Path aFile, IOException aExc) throws IOException {
            if ("System Volume Information".equals((aFile.getFileName().toString()))) {
                return FileVisitResult.SKIP_SUBTREE;
            }

            throw aExc;
        }

        @Override
        public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
            return Runner.this.visitFile(file, attrs);
        }

        @Override
        public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException {
            if ("System Volume Information".equals((dir.getFileName()))) {
                return FileVisitResult.SKIP_SUBTREE;
            }

            return Runner.this.preVisitDirectory(dir, attrs);
        }

    });

    if (myEvacuateCandidates.size() == 0) {
        myLog.info("No candidates for evacuation found");
    } else {
        StringBuilder sb = new StringBuilder("\nFound candidates for evacuation:");
        myEvacuateCandidates.keySet().forEach(p -> sb.append("\n    " + p.toString()));
        myLog.info(sb.toString());
    }

    if (myDryRun) {
        myLog.debug("DryRun flag is set. Doing nothing");
        return;
    }

    if (myFutures.size() > 0) {
        myLog.debug("Waiting for all async tasks to complete");
        CompletableFuture.allOf(myFutures.toArray(new CompletableFuture[myFutures.size()])).get();
    }

    if (myFailedChainPreparations.size() > 0) {
        for (Path path : myFailedChainPreparations.keySet()) {
            myLog.error("exception occured", myFailedChainPreparations.get(path));
        }

        throw new Exception("chain preparation failed. See above error messages");
    }

    for (Path src : myEvacuateCandidates.keySet()) {
        Path dst = myEvacuateCandidates.get(src);
        Path dstParent = dst.getParent();

        if (Files.notExists(dstParent)) {
            Files.createDirectories(dstParent); // FUTURE: overtake file attributes from src
        }

        if (myMove) {
            try {
                myLog.debug(
                        "Moving file system object \"" + src.toString() + "\" to \"" + dst.toString() + "\"");
                Files.move(src, dst, StandardCopyOption.ATOMIC_MOVE);
            } catch (AtomicMoveNotSupportedException e) {
                myLog.warn("Atomic move not supported. Try copy and then delete");

                if (Files.isDirectory(src)) {
                    myLog.debug("Copying folder \"" + src.toString() + "\" to \"" + dst.toString() + "\"");
                    FileUtils.copyDirectory(src.toFile(), dst.toFile());
                    myLog.debug("Delete folder \"" + src.toString() + "\"");
                    FileUtils.deleteDirectory(src.toFile());
                } else {
                    myLog.debug("Copy file \"" + src.toString() + "\" to \"" + dst.toString() + "\"");
                    FileUtils.copyFile(src.toFile(), dst.toFile());
                    myLog.debug("Delete file \"" + src.toString() + "\"");
                    Files.delete(src);
                }
            }

        } else {
            if (Files.isDirectory(src)) {
                myLog.debug("Copying folder \"" + src.toString() + "\" to \"" + dst.toString() + "\"");
                FileUtils.copyDirectory(src.toFile(), dst.toFile());
            } else {
                myLog.debug("Copy file \"" + src.toString() + "\" to \"" + dst.toString() + "\"");
                FileUtils.copyFile(src.toFile(), dst.toFile());
            }
        }
    }

    myLog.info("\nSuccessfully terminated." + "\n             Evacuated  Skipped" + "\n    Files  : "
            + StringUtils.leftPad("" + myEvacuationDirCount, 9)
            + StringUtils.leftPad("" + myExclusionDirCount, 9) + "\n    Folders: "
            + StringUtils.leftPad("" + myEvacuationFileCount, 9)
            + StringUtils.leftPad("" + myExclusionFileCount, 9));
}

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

/**
 * Returns the associated content type if supported
 * @param path the file to check//from w w w .j  a va2  s .c o  m
 * @return the associated content type if supported
 */
private ContentType getSupportedContentType(Path path) {
    String type = getContentType(path);
    if (type != null) {
        Set<ContentType> supportedTypes = mimeTypeLookup.get(type);
        if (supportedTypes != null) {
            // Take the first match
            return supportedTypes.iterator().next();
        }
    } else {
        // Check if the file extension matches
        String ext = FilenameUtils.getExtension(path.getFileName().toString());
        if (ext != null && ext.length() > 0) {
            return fileExtensionLookup.get(ext.toLowerCase());
        }
    }
    return null;
}