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:fr.gael.dhus.datastore.FileSystemDataStore.java

/**
 * Moves product download zip into the given destination.
 * <p><b>Note:</b> generates the zip of product if necessary.</p>
 *
 * @param product     product to move./*w w  w. j  av  a2s.  c om*/
 * @param destination destination of product
 */
private void moveProduct(Product product, String destination) {

    if (destination == null || destination.trim().isEmpty()) {
        return;
    }

    Path zip_destination = Paths.get(destination);
    String download_path = product.getDownloadablePath();
    try {
        if (download_path != null) {
            File product_zip_file = Paths.get(download_path).toFile();
            FileUtils.moveFileToDirectory(product_zip_file, zip_destination.toFile(), true);
        } else {
            Path product_path = Paths.get(product.getPath().getPath());
            if (UnZip.supported(product_path.toAbsolutePath().toString())) {
                FileUtils.moveFileToDirectory(product_path.toFile(), zip_destination.toFile(), true);
            } else {
                zip_destination.resolve(product_path.getFileName());
                generateZip(product_path.toFile(), zip_destination.toFile());
            }
        }
    } catch (IOException e) {
        LOGGER.error("Cannot move product: " + product.getPath() + " into " + destination, e);
    }
}

From source file:net.rptools.tokentool.controller.ManageOverlays_Controller.java

public void displayTreeView() {
    TreeItem<Path> root = new OverlayTreeItem(AppConstants.OVERLAY_DIR);
    root.setExpanded(true);/*from www  .  j av  a  2s  .com*/
    overlayTreeView.setRoot(root);

    overlayTreeView.setCellFactory(treeView -> new TreeCell<Path>() {
        @Override
        public void updateItem(Path path, boolean empty) {
            super.updateItem(path, empty);
            if (empty) {
                setText(null);
            } else {
                setText(path.getFileName().toString());
            }
        }
    });
}

From source file:edu.cornell.mannlib.vitro.webapp.servlet.setup.FileGraphSetup.java

private boolean readGraphs(Set<Path> pathSet, RDFService rdfService, String type, OntModel baseModel) {

    int count = 0;

    boolean modelChanged = false;

    // For each file graph in the target directory update or add that graph to
    // the Jena SDB, and attach the graph as a submodel of the base model
    for (Path p : pathSet) {

        count++; // note this will count the empty files too
        try {/* w  ww  . ja v  a 2 s. c o m*/
            FileInputStream fis = new FileInputStream(p.toFile());
            try {
                OntModel model = ModelFactory.createOntologyModel(OntModelSpec.OWL_MEM);
                String fn = p.getFileName().toString().toLowerCase();
                if (fn.endsWith(".n3") || fn.endsWith(".ttl")) {
                    model.read(fis, null, "N3");
                } else if (fn.endsWith(".owl") || fn.endsWith(".rdf") || fn.endsWith(".xml")) {
                    model.read(fis, null, "RDF/XML");
                } else if (fn.endsWith(".md")) {
                    // Ignore markdown files - documentation.
                } else {
                    log.warn("Ignoring " + type + " file graph " + p
                            + " because the file extension is unrecognized.");
                }

                if (!model.isEmpty() && baseModel != null) {
                    baseModel.addSubModel(model);
                    log.debug("Attached file graph as " + type + " submodel " + p.getFileName());
                }

                modelChanged = modelChanged | updateGraphInDB(rdfService, model, type, p);

            } catch (Exception ioe) {
                log.error("Unable to process file graph " + p, ioe);
                System.out.println("Unable to process file graph " + p);
                ioe.printStackTrace();
            } finally {
                fis.close();
            }
        } catch (FileNotFoundException fnfe) {
            log.warn(p + " not found. Unable to process file graph"
                    + ((fnfe.getLocalizedMessage() != null) ? fnfe.getLocalizedMessage() : ""));
        } catch (IOException ioe) {
            // this is for the fis.close() above.
            log.warn("Exception while trying to close file graph file: " + p, ioe);
        }
    } // end - for

    log.info("Read " + count + " " + type + " file graph" + ((count == 1) ? "" : "s"));

    return modelChanged;
}

From source file:com.bc.fiduceo.post.PostProcessingTool.java

void computeFiles(List<Path> mmdFiles) {
    final PostProcessingConfig processingConfig = context.getProcessingConfig();

    final List<PostProcessing> processings = new ArrayList<>();
    final PostProcessingFactory factory = PostProcessingFactory.get();
    for (Element processing : processingConfig.getPostProcessingElements()) {
        final PostProcessing postProcessing = factory.getPostProcessing(processing);
        postProcessing.setContext(context);
        processings.add(postProcessing);
    }//from  w w w  . ja  v a  2s. c o m

    final SourceTargetManager manager = new SourceTargetManager(processingConfig);
    for (Path mmdFile : mmdFiles) {
        Exception ex = null;
        try {
            computeFile(mmdFile, manager, processings);
        } catch (Exception e) {
            ex = e;
            logger.severe(
                    "Unable to execute post processing for matchup '" + mmdFile.getFileName().toString() + "'");
            logger.severe("Cause: " + e.getMessage());
            e.printStackTrace();
        } finally {
            manager.processingDone(mmdFile, ex);
        }
    }
}

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

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

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

    JarDirectoryStep step = new JarDirectoryStep(new ProjectFilesystem(zipup), Paths.get("output.jar"),
            ImmutableSet.of(first.getFileName(), second.getFileName()), "com.example.Main",
            /* manifest file */ null);
    ExecutionContext context = TestExecutionContext.newInstance();

    int returnCode = step.execute(context);

    assertEquals(0, returnCode);//  w w w.  j  av a2  s.c om

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

    // "example.txt" "Main.class" and the MANIFEST.MF.
    assertZipFileCountIs(3, zip);
    assertZipContains(zip, "example.txt");
}

From source file:com.evolveum.midpoint.tools.schemadist.SchemaDistMojo.java

public void execute() throws MojoExecutionException, MojoFailureException {
    getLog().info("SchemaDist plugin started");

    try {//from w w  w  . j  ava2s  .c  o m
        processArtifactItems();
    } catch (InvalidVersionSpecificationException e) {
        handleFailure(e);
    }
    final File outDir = initializeOutDir(outputDirectory);

    CatalogManager catalogManager = new CatalogManager();
    catalogManager.setVerbosity(999);

    for (ArtifactItem artifactItem : artifactItems) {
        Artifact artifact = artifactItem.getArtifact();
        getLog().info("SchemaDist unpacking artifact " + artifact);
        File workDir = new File(workDirectory, artifact.getArtifactId());
        initializeOutDir(workDir);
        artifactItem.setWorkDir(workDir);
        unpack(artifactItem, workDir);

        if (translateSchemaLocation) {
            String catalogPath = artifactItem.getCatalog();
            File catalogFile = new File(workDir, catalogPath);
            if (!catalogFile.exists()) {
                throw new MojoExecutionException("No catalog file " + catalogPath + " in artifact " + artifact);
            }
            Catalog catalog = new Catalog(catalogManager);
            catalog.setupReaders();
            try {
                // UGLY HACK. On Windows, file names like d:\abc\def\catalog.xml eventually get treated very strangely
                // (resulting in names like "file:<current-working-dir>d:\abc\def\catalog.xml" that are obviously wrong)
                // Prefixing such names with "file:/" helps.
                String prefix;
                if (catalogFile.isAbsolute() && !catalogFile.getPath().startsWith("/")) {
                    prefix = "/";
                } else {
                    prefix = "";
                }
                String fileName = "file:" + prefix + catalogFile.getPath();
                getLog().debug("Calling parseCatalog with: " + fileName);
                catalog.parseCatalog(fileName);
            } catch (MalformedURLException e) {
                throw new MojoExecutionException(
                        "Error parsing catalog file " + catalogPath + " in artifact " + artifact, e);
            } catch (IOException e) {
                throw new MojoExecutionException(
                        "Error parsing catalog file " + catalogPath + " in artifact " + artifact, e);
            }
            artifactItem.setResolveCatalog(catalog);
        }
    }

    for (ArtifactItem artifactItem : artifactItems) {
        Artifact artifact = artifactItem.getArtifact();
        getLog().info("SchemaDist processing artifact " + artifact);
        final File workDir = artifactItem.getWorkDir();
        FileVisitor<Path> fileVisitor = new FileVisitor<Path>() {
            @Override
            public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException {
                // nothing to do
                return FileVisitResult.CONTINUE;
            }

            @Override
            public FileVisitResult visitFile(Path filePath, BasicFileAttributes attrs) throws IOException {
                String fileName = filePath.getFileName().toString();
                if (fileName.endsWith(".xsd")) {
                    getLog().debug("Processing file " + filePath);
                    try {
                        processXsd(filePath, workDir, outDir);
                    } catch (MojoExecutionException | MojoFailureException e) {
                        throw new RuntimeException(e.getMessage(), e);
                    }
                } else if (fileName.endsWith(".wsdl")) {
                    getLog().debug("Processing file " + filePath);
                    try {
                        processWsdl(filePath, workDir, outDir);
                    } catch (MojoExecutionException | MojoFailureException e) {
                        throw new RuntimeException(e.getMessage(), e);
                    }
                } else {
                    getLog().debug("Skipping file " + filePath);
                }
                return FileVisitResult.CONTINUE;
            }

            @Override
            public FileVisitResult visitFileFailed(Path file, IOException exc) throws IOException {
                return FileVisitResult.TERMINATE;
            }

            @Override
            public FileVisitResult postVisitDirectory(Path dir, IOException exc) throws IOException {
                // nothing to do
                return FileVisitResult.CONTINUE;
            }
        };
        try {
            Files.walkFileTree(workDir.toPath(), fileVisitor);
        } catch (IOException e) {
            throw new MojoExecutionException("Error processing files of artifact " + artifact, e);
        }

    }
    getLog().info("SchemaDist plugin finished");
}

From source file:com.google.pubsub.flic.controllers.GCEController.java

/**
 * Uploads a given file to Google Storage.
 *//*from   w w  w  .  j a  va 2  s. co  m*/
private void uploadFile(Path filePath) throws IOException {
    try {
        byte[] md5hash = Base64.decodeBase64(
                storage.objects().get(projectName + "-cloud-pubsub-loadtest", filePath.getFileName().toString())
                        .execute().getMd5Hash());
        try (InputStream inputStream = Files.newInputStream(filePath, StandardOpenOption.READ)) {
            if (Arrays.equals(md5hash, DigestUtils.md5(inputStream))) {
                log.info("File " + filePath.getFileName() + " is current, reusing.");
                return;
            }
        }
        log.info("File " + filePath.getFileName() + " is out of date, uploading new version.");
        storage.objects().delete(projectName + "-cloud-pubsub-loadtest", filePath.getFileName().toString())
                .execute();
    } catch (GoogleJsonResponseException e) {
        if (e.getStatusCode() != NOT_FOUND) {
            throw e;
        }
    }
    try (InputStream inputStream = Files.newInputStream(filePath, StandardOpenOption.READ)) {
        storage.objects()
                .insert(projectName + "-cloud-pubsub-loadtest", null,
                        new InputStreamContent("application/octet-stream", inputStream))
                .setName(filePath.getFileName().toString()).execute();
        log.info("File " + filePath.getFileName() + " created.");
    }
}

From source file:io.github.swagger2markup.markup.builder.internal.AbstractMarkupDocBuilder.java

@Override
public void writeToFile(Path file, Charset charset, OpenOption... options) {
    writeToFileWithoutExtension(file.resolveSibling(addFileExtension(file.getFileName().toString())), charset,
            options);/*from   www . ja v a 2 s  .c  om*/
}

From source file:de.qucosa.webapi.v1.DocumentResourceFileTest.java

@Test
public void addsMimeTypeElement() throws Exception {
    Path src = new File(this.getClass().getResource("/blank.pdf").toURI()).toPath();
    Path dest = tempFolder.getRoot().toPath().resolve(src.getFileName());
    Files.copy(src, dest, StandardCopyOption.REPLACE_EXISTING);

    mockMvc.perform(post("/document").accept(new MediaType("application", "vnd.slub.qucosa-v1+xml"))
            .contentType(new MediaType("application", "vnd.slub.qucosa-v1+xml"))
            .content("<Opus version=\"2.0\">" + "<Opus_Document>" + "   <DocumentId>815</DocumentId>"
                    + "       <PersonAuthor>" + "           <LastName>Shakespear</LastName>"
                    + "           <FirstName>William</FirstName>" + "       </PersonAuthor>" + "   <TitleMain>"
                    + "       <Value>Macbeth</Value>" + "   </TitleMain>" + "   <IdentifierUrn>"
                    + "       <Value>urn:nbn:foo-4711</Value>" + "   </IdentifierUrn>" + "   <File>"
                    + "       <PathName>1057131155078-6506.pdf</PathName>"
                    + "       <Label>Volltextdokument (PDF)</Label>" + "       <TempFile>blank.pdf</TempFile>"
                    + "       <OaiExport>1</OaiExport>" + "       <FrontdoorVisible>1</FrontdoorVisible>"
                    + "   </File>" + "</Opus_Document>" + "</Opus>"))
            .andExpect(status().isCreated());

    ArgumentCaptor<InputStream> argCapt = ArgumentCaptor.forClass(InputStream.class);
    verify(fedoraRepository).modifyDatastreamContent(eq("qucosa:815"), eq("QUCOSA-XML"), anyString(),
            argCapt.capture());// w  ww  .j  av a  2 s. co  m
    Document control = XMLUnit.buildControlDocument(new InputSource(argCapt.getValue()));

    assertXpathExists("/Opus/Opus_Document/File[MimeType='application/pdf']", control);
}

From source file:de.qucosa.webapi.v1.DocumentResourceFileTest.java

@Test
public void addsFileSize() throws Exception {
    Path src = new File(this.getClass().getResource("/blank.pdf").toURI()).toPath();
    Path dest = tempFolder.getRoot().toPath().resolve(src.getFileName());
    Files.copy(src, dest, StandardCopyOption.REPLACE_EXISTING);

    mockMvc.perform(post("/document").accept(new MediaType("application", "vnd.slub.qucosa-v1+xml"))
            .contentType(new MediaType("application", "vnd.slub.qucosa-v1+xml"))
            .content("<Opus version=\"2.0\">" + "<Opus_Document>" + "   <DocumentId>815</DocumentId>"
                    + "       <PersonAuthor>" + "           <LastName>Shakespear</LastName>"
                    + "           <FirstName>William</FirstName>" + "       </PersonAuthor>" + "   <TitleMain>"
                    + "       <Value>Macbeth</Value>" + "   </TitleMain>" + "   <IdentifierUrn>"
                    + "       <Value>urn:nbn:foo-4711</Value>" + "   </IdentifierUrn>" + "   <File>"
                    + "       <PathName>1057131155078-6506.pdf</PathName>"
                    + "       <Label>Volltextdokument (PDF)</Label>" + "       <TempFile>blank.pdf</TempFile>"
                    + "       <OaiExport>1</OaiExport>" + "       <FrontdoorVisible>1</FrontdoorVisible>"
                    + "   </File>" + "</Opus_Document>" + "</Opus>"))
            .andExpect(status().isCreated());

    ArgumentCaptor<InputStream> argCapt = ArgumentCaptor.forClass(InputStream.class);
    verify(fedoraRepository).modifyDatastreamContent(eq("qucosa:815"), eq("QUCOSA-XML"), anyString(),
            argCapt.capture());//from w w  w  . j  a va 2s.co m
    Document control = XMLUnit.buildControlDocument(new InputSource(argCapt.getValue()));

    assertXpathExists("/Opus/Opus_Document/File[FileSize='11112']", control);
}