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:onl.area51.filesystem.ftp.client.FTPClient.java

/**
 * Retrieve a remote file/* w w w .ja  v a2 s .  c om*/
 * <p>
 * @param target  file to create. Name will also be the remote name in the current directory
 * @param options CopyOptions to use
 * <p>
 * @throws IOException
 */
default void retrieve(Path target, CopyOption... options) throws IOException {
    retrieve(target.getFileName().toString(), target, options);
}

From source file:com.facebook.buck.jvm.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"),
            ImmutableSortedSet.of(first.getFileName()), "com.example.Main", /* manifest file */ null,
            /* merge manifests */ true, /* blacklist */ ImmutableSet.of(Pattern.compile(".*2.*")));

    assertEquals(0, step.execute(TestExecutionContext.newInstance()).getExitCode());

    Path zip = zipup.resolve("output.jar");
    // 3 files in total: file1.txt, & com/example/Main.class & the manifest.
    assertZipFileCountIs(3, zip);/*from   w  w w . ja va  2s .co m*/
    assertZipContains(zip, "dir/file1.txt");
    assertZipDoesNotContain(zip, "dir/file2.txt");
}

From source file:ru.histone.staticrender.StaticRender.java

public void renderSite(final Path srcDir, final Path dstDir) {
    log.info("Running StaticRender for srcDir={}, dstDir={}", srcDir.toString(), dstDir.toString());
    Path contentDir = srcDir.resolve("content/");
    final Path layoutDir = srcDir.resolve("layouts/");

    FileVisitor<Path> layoutVisitor = new SimpleFileVisitor<Path>() {
        @Override/*from   ww  w .  j ava  2s.co  m*/
        public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
            if (file.toString().endsWith("." + TEMPLATE_FILE_EXTENSION)) {
                ArrayNode ast = null;
                try {
                    ast = histone.parseTemplateToAST(new FileReader(file.toFile()));
                } catch (HistoneException e) {
                    throw new RuntimeException("Error parsing histone template:" + e.getMessage(), e);
                }

                final String fileName = file.getFileName().toString();
                String layoutId = fileName.substring(0,
                        fileName.length() - TEMPLATE_FILE_EXTENSION.length() - 1);
                layouts.put(layoutId, ast);
                if (log.isDebugEnabled()) {
                    log.debug("Layout found id='{}', file={}", layoutId, file);
                } else {
                    log.info("Layout found id='{}'", layoutId);
                }
            } else {
                final Path relativeFileName = srcDir.resolve("layouts").relativize(Paths.get(file.toUri()));
                final Path resolvedFile = dstDir.resolve(relativeFileName);
                if (!resolvedFile.getParent().toFile().exists()) {
                    Files.createDirectories(resolvedFile.getParent());
                }
                Files.copy(Paths.get(file.toUri()), resolvedFile, StandardCopyOption.REPLACE_EXISTING,
                        LinkOption.NOFOLLOW_LINKS);
            }
            return FileVisitResult.CONTINUE;
        }
    };

    FileVisitor<Path> contentVisitor = new SimpleFileVisitor<Path>() {
        @Override
        public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {

            Scanner scanner = new Scanner(file, "UTF-8");
            scanner.useDelimiter("-----");

            String meta = null;
            StringBuilder content = new StringBuilder();

            if (!scanner.hasNext()) {
                throw new RuntimeException("Wrong format #1:" + file.toString());
            }

            if (scanner.hasNext()) {
                meta = scanner.next();
            }

            if (scanner.hasNext()) {
                content.append(scanner.next());
                scanner.useDelimiter("\n");
            }

            while (scanner.hasNext()) {
                final String next = scanner.next();
                content.append(next);

                if (scanner.hasNext()) {
                    content.append("\n");
                }
            }

            Map<String, String> metaYaml = (Map<String, String>) yaml.load(meta);

            String layoutId = metaYaml.get("layout");

            if (!layouts.containsKey(layoutId)) {
                throw new RuntimeException(MessageFormat.format("No layout with id='{0}' found", layoutId));
            }

            final Path relativeFileName = srcDir.resolve("content").relativize(Paths.get(file.toUri()));
            final Path resolvedFile = dstDir.resolve(relativeFileName);
            if (!resolvedFile.getParent().toFile().exists()) {
                Files.createDirectories(resolvedFile.getParent());
            }
            Writer output = new FileWriter(resolvedFile.toFile());
            ObjectNode context = jackson.createObjectNode();
            ObjectNode metaNode = jackson.createObjectNode();
            context.put("content", content.toString());
            context.put("meta", metaNode);
            for (String key : metaYaml.keySet()) {
                if (!key.equalsIgnoreCase("content")) {
                    metaNode.put(key, metaYaml.get(key));
                }
            }

            try {
                histone.evaluateAST(layoutDir.toUri().toString(), layouts.get(layoutId), context, output);
                output.flush();
            } catch (HistoneException e) {
                throw new RuntimeException("Error evaluating content: " + e.getMessage(), e);
            } finally {
                output.close();
            }

            return FileVisitResult.CONTINUE;
        }
    };

    try {
        Files.walkFileTree(layoutDir, layoutVisitor);
        Files.walkFileTree(contentDir, contentVisitor);
    } catch (Exception e) {
        throw new RuntimeException("Error during site render", e);
    }
}

From source file:io.undertow.server.handlers.file.FileHandlerSymlinksTestCase.java

@Before
public void createSymlinksScenario() throws IOException, URISyntaxException {
    Assume.assumeFalse(System.getProperty("os.name").toLowerCase().contains("windows"));

    /**//from   w  ww  . j a v  a 2s.  c  om
     * Creating following structure for test:
     *
     * $ROOT_PATH/newDir
     * $ROOT_PATH/newDir/page.html
     * $ROOT_PATH/newDir/innerDir/
     * $ROOT_PATH/newDir/innerDir/page.html
     * $ROOT_PATH/newSymlink -> $ROOT_PATH/newDir
     * $ROOT_PATH/newDir/innerSymlink -> $ROOT_PATH/newDir/innerDir/
     *
     */
    Path filePath = Paths.get(getClass().getResource("page.html").toURI());
    Path rootPath = filePath.getParent();

    Path newDir = rootPath.resolve("newDir");
    Files.createDirectories(newDir);

    Path innerDir = newDir.resolve("innerDir");
    Files.createDirectories(innerDir);

    Files.copy(filePath, newDir.resolve(filePath.getFileName()));
    Files.copy(filePath, innerDir.resolve(filePath.getFileName()));

    Path newSymlink = rootPath.resolve("newSymlink");

    Files.createSymbolicLink(newSymlink, newDir);

    Path innerSymlink = newDir.resolve("innerSymlink");

    Files.createSymbolicLink(innerSymlink, innerDir);
}

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

@Test
public void shouldNotIncludeFilesInClassesToRemoveFromJar() throws IOException {
    Path zipup = folder.newFolder();
    Path first = createZip(zipup.resolve("first.zip"), "com/example/A.class", "com/example/B.class",
            "com/example/C.class");

    JarDirectoryStep step = new JarDirectoryStep(new ProjectFilesystem(zipup), Paths.get("output.jar"),
            ImmutableSortedSet.of(first.getFileName()), "com.example.A", /* manifest file */ null,
            /* merge manifests */ true, /* blacklist */ ImmutableSet.of(Pattern.compile("com.example.B"),
                    Pattern.compile("com.example.C")));

    assertEquals(0, step.execute(TestExecutionContext.newInstance()).getExitCode());

    Path zip = zipup.resolve("output.jar");
    // 2 files in total: com/example/A/class & the manifest.
    assertZipFileCountIs(2, zip);//  w ww  . j  a  v a  2 s .  c o m
    assertZipContains(zip, "com/example/A.class");
    assertZipDoesNotContain(zip, "com/example/B.class");
    assertZipDoesNotContain(zip, "com/example/C.class");
}

From source file:de.tu_dortmund.ub.data.dswarm.Init.java

private Optional<String> enhanceInputDataResource(final String inputDataResourceFile,
        final JsonObject configurationJSON) throws Exception {

    final JsonObject parameters = configurationJSON.getJsonObject(DswarmBackendStatics.PARAMETERS_IDENTIFIER);

    if (parameters == null) {

        LOG.debug("could not find parameters in configuration '{}'", configurationJSON.toString());

        return Optional.empty();
    }/*w w  w . j av  a2s  . c om*/

    final String storageType = parameters.getString(DswarmBackendStatics.STORAGE_TYPE_IDENTIFIER);

    if (storageType == null || storageType.trim().isEmpty()) {

        LOG.debug("could not find storage in parameters of configuration '{}'", configurationJSON.toString());

        return Optional.empty();
    }

    switch (storageType) {

    case DswarmBackendStatics.XML_STORAGE_TYPE:
    case DswarmBackendStatics.MABXML_STORAGE_TYPE:
    case DswarmBackendStatics.MARCXML_STORAGE_TYPE:
    case DswarmBackendStatics.PNX_STORAGE_TYPE:
    case DswarmBackendStatics.OAI_PMH_DC_ELEMENTS_STORAGE_TYPE:
    case DswarmBackendStatics.OAI_PMH_DCE_AND_EDM_ELEMENTS_STORAGE_TYPE:
    case DswarmBackendStatics.OAIPMH_DC_TERMS_STORAGE_TYPE:
    case DswarmBackendStatics.OAIPMH_MARCXML_STORAGE_TYPE:

        // only XML is supported right now

        break;
    default:

        LOG.debug("storage type '{}' is currently not supported for input data resource enhancement",
                storageType);

        return Optional.empty();
    }

    final Path inputDataResourcePath = Paths.get(inputDataResourceFile);

    final Path inputDataResourceFileNamePath = inputDataResourcePath.getFileName();
    final String inputDataResourceFileName = inputDataResourceFileNamePath.toString();
    final String newInputDataResourcePath = OS_TEMP_DIR + File.separator + inputDataResourceFileName;

    LOG.debug("try to enhance input data resource '{}'", inputDataResourceFile);

    XMLEnhancer.enhanceXML(inputDataResourceFile, newInputDataResourcePath);

    LOG.debug("enhanced input data resource for '{}' can be found at ''{}", inputDataResourceFile,
            newInputDataResourcePath);

    return Optional.of(newInputDataResourcePath);
}

From source file:com.facebook.buck.io.filesystem.impl.DefaultProjectFilesystemTest.java

@Test
public void testWalkFileTreeWhenProjectRootIsWorkingDir() throws IOException {
    ProjectFilesystem projectFilesystem = TestProjectFilesystems
            .createProjectFilesystem(Paths.get(".").toAbsolutePath());
    ImmutableList.Builder<String> fileNames = ImmutableList.builder();

    Path pathRelativeToProjectRoot = Paths
            .get("test/com/facebook/buck/io/testdata/directory_traversal_ignore_paths");
    projectFilesystem.walkRelativeFileTree(pathRelativeToProjectRoot, new SimpleFileVisitor<Path>() {
        @Override//  w  ww  .  j av a2 s . c  o m
        public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) {
            fileNames.add(file.getFileName().toString());
            return FileVisitResult.CONTINUE;
        }
    });

    assertThat(fileNames.build(), containsInAnyOrder("file", "a_file", "b_file", "b_c_file", "b_d_file"));
}

From source file:com.facebook.buck.io.filesystem.impl.DefaultProjectFilesystemTest.java

@Test
public void testWalkFileTreeWhenProjectRootIsNotWorkingDir() throws IOException {
    tmp.newFolder("dir");
    tmp.newFile("dir/file.txt");
    tmp.newFolder("dir/dir2");
    tmp.newFile("dir/dir2/file2.txt");

    ImmutableList.Builder<String> fileNames = ImmutableList.builder();

    filesystem.walkRelativeFileTree(Paths.get("dir"), new SimpleFileVisitor<Path>() {
        @Override//from  ww  w  . ja va 2s.  com
        public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) {
            fileNames.add(file.getFileName().toString());
            return FileVisitResult.CONTINUE;
        }
    });

    assertThat(fileNames.build(), containsInAnyOrder("file.txt", "file2.txt"));
}

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

/**
 * Construct file info./*from ww  w .java 2 s. com*/
 * 
 * @param path the file
 * @param needSize the need size
 * @return the file info
 * @throws C5CException the connector exception
 */
private FileProperties constructFileInfo(Path path, boolean needSize) throws C5CException {
    InputStream imageIn = null;
    try {
        FileProperties fileProperties;
        Date lastModified = new Date(Files.getLastModifiedTime(path).toMillis());
        // 'needsize' isn't implemented in the filemanager yet, so the dimension is set if we have an image.
        String fileName = path.getFileName().toString();
        String ext = FilenameUtils.getExtension(fileName.toString());
        long size = Files.size(path);
        boolean isProtected = isProtected(path);
        if (isImageExtension(ext)) {
            imageIn = new BufferedInputStream(Files.newInputStream(path));
            Dimension dim = UserObjectProxy.getDimension(imageIn);
            fileProperties = buildForImage(fileName, isProtected, dim.width, dim.height, size, lastModified);
        } else {
            fileProperties = (Files.isDirectory(path)) ? buildForDirectory(fileName, isProtected, lastModified)
                    : buildForFile(fileName, isProtected, size, lastModified);
        }
        return fileProperties;
    } catch (FileNotFoundException e) {
        throw new C5CException(String.format("File not found: %s", path.getFileName().toString()));
    } catch (SecurityException | IOException e) {
        logger.warn("Error while analyzing an image!", e);
        throw new C5CException(String.format("Error while getting the dimension of the image %s: %s",
                path.getFileName().toString(), e.getMessage()));
    } finally {
        IOUtils.closeQuietly(imageIn);
    }
}

From source file:com.liferay.sync.engine.SyncSystemTest.java

protected Path getDependencyFilePath(Path testFilePath, String dependency) throws Exception {

    String filePathName = null;//ww  w.  ja v  a2s. co m

    if (dependency.contains("common")) {
        filePathName = FileUtil.getFilePathName("tests", "dependencies", dependency);
    } else {
        Path testFileNameFilePath = testFilePath.getFileName();

        String testFileName = testFileNameFilePath.toString();

        filePathName = FileUtil.getFilePathName("tests", "dependencies",
                FilenameUtils.removeExtension(testFileName), dependency);
    }

    return getResourceFilePath(filePathName);
}