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.htmlhifive.visualeditor.persister.LocalFileContentsPersister.java

/**
 * ?????????????.//w w w  . j  a  v  a2 s .co  m
 * 
 * @param key ?
 * @return ????
 */
@Override
public UrlTreeMetaData<InputStream> generateMetaDataFromReal(String key, UrlTreeContext ctx)
        throws BadContentException {
    if (!this.canLoad(key, ctx)) {
        throw new IllegalArgumentException(
                "Cannot Load it. check before can it load with canLoad(key): " + key);
    }
    Path p = this.generateFileObj(key);
    File f = p.toFile();
    long lastModified = f.lastModified();

    logger.trace("[?]????lastModified: " + p.toString() + ":"
            + lastModified);

    UrlTreeMetaData<InputStream> md = new UrlTreeMetaData<>();
    md.setDirectory(Files.isDirectory(p, LinkOption.NOFOLLOW_LINKS));
    md.setFilename(key);
    md.setOwnerId(ctx.getUserName());
    md.setGroupId(ctx.getPrimaryGroup());
    md.setCreatedTime(lastModified);
    md.setUpdatedTime(lastModified);
    md.setPermission(ctx.getDefaultPermission());
    String contentType = new MimetypesFileTypeMap().getContentType(p.getFileName().toString());
    md.setContentType(contentType);

    return md;
}

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

@Override
public boolean rename(String oldBackendPath, String sanitizedName) throws C5CException {
    Path src = buildRealPath(oldBackendPath);
    boolean isDirectory = Files.isDirectory(src);
    if (!Files.exists(src)) {
        logger.error("Source file not found: {}", src.toString());
        FilemanagerException.Key key = (isDirectory) ? FilemanagerException.Key.DirectoryNotExist
                : FilemanagerException.Key.FileNotExists;
        throw new FilemanagerException(FilemanagerAction.RENAME, key, FilenameUtils.getName(oldBackendPath));
    }/*from  w w  w .  jav a2 s.  co  m*/

    Path dest = src.resolveSibling(sanitizedName);
    try {
        Files.move(src, dest);
    } catch (SecurityException | IOException e) {
        logger.warn(String.format("Error while renaming [%s] to [%s]", src.getFileName().toString(),
                dest.getFileName().toString()), e);
        FilemanagerException.Key key = (Files.isDirectory(src))
                ? FilemanagerException.Key.ErrorRenamingDirectory
                : FilemanagerException.Key.ErrorRenamingFile;
        throw new FilemanagerException(FilemanagerAction.RENAME, key, FilenameUtils.getName(oldBackendPath),
                sanitizedName);
    } catch (FileSystemAlreadyExistsException e) {
        logger.warn("Destination file already exists: {}", dest.toAbsolutePath());
        FilemanagerException.Key key = (Files.isDirectory(dest))
                ? FilemanagerException.Key.DirectoryAlreadyExists
                : FilemanagerException.Key.FileAlreadyExists;
        throw new FilemanagerException(FilemanagerAction.RENAME, key, sanitizedName);
    }
    return isDirectory;
}

From source file:org.apache.taverna.databundle.TestDataBundles.java

@Test
public void getListItem() throws Exception {
    Path inputs = DataBundles.getInputs(dataBundle);
    Path list = DataBundles.getPort(inputs, "in1");
    DataBundles.createList(list);/*  www. java 2 s.  c  o m*/
    for (int i = 0; i < 5; i++) {
        Path item = DataBundles.newListItem(list);
        DataBundles.setStringValue(item, "item " + i);
    }
    // set at next available position
    Path item5 = DataBundles.getListItem(list, 5);
    assertTrue(item5.getFileName().toString().contains("5"));
    DataBundles.setStringValue(item5, "item 5");

    // set somewhere later
    Path item8 = DataBundles.getListItem(list, 8);
    assertTrue(item8.getFileName().toString().contains("8"));
    DataBundles.setStringValue(item8, "item 8");

    Path item7 = DataBundles.getListItem(list, 7);
    assertFalse(Files.exists(item7));
    assertFalse(DataBundles.isList(item7));
    assertFalse(DataBundles.isError(item7));
    assertFalse(DataBundles.isValue(item7));
    // TODO: Is it really missing? item1337 is also missing..
    assertTrue(DataBundles.isMissing(item7));

    // overwrite #2
    Path item2 = DataBundles.getListItem(list, 2);
    DataBundles.setStringValue(item2, "replaced");

    List<Path> listItems = DataBundles.getList(list);
    assertEquals(9, listItems.size());
    assertEquals("item 0", DataBundles.getStringValue(listItems.get(0)));
    assertEquals("item 1", DataBundles.getStringValue(listItems.get(1)));
    assertEquals("replaced", DataBundles.getStringValue(listItems.get(2)));
    assertEquals("item 3", DataBundles.getStringValue(listItems.get(3)));
    assertEquals("item 4", DataBundles.getStringValue(listItems.get(4)));
    assertEquals("item 5", DataBundles.getStringValue(listItems.get(5)));
    assertNull(listItems.get(6));
    assertNull(listItems.get(7));
    assertEquals("item 8", DataBundles.getStringValue(listItems.get(8)));

}

From source file:com.bytelightning.opensource.pokerface.PokerFace.java

/**
 * If requested by the user, this method walks the script directory discovering, loading, compiling, and initialing an .js javascript files it finds in the specified directory or it's children.
 * @param baseScriptDirectory   The contents of this directory should be structured in the same layout as the url's we wish to interfere with.
 * @param watchScriptDirectory   If true, a watch will be placed on <code>baseScriptDirectory</code> and any javascript file modifications (cud) will be dynamically rebuilt and reflected in the running server. 
 * @return   True if all scripts were successfully loaded.
 *///from w  w w  .j  av  a  2s  . c  om
protected boolean configureScripts(final List<Path> jsLibs, final HierarchicalConfiguration scriptConfig,
        final Path baseScriptDirectory, boolean watchScriptDirectory) {
    // Our unit test has verified that CompiledScripts can produce objects (endpoints) that can be executed from ANY thread (and even concurrently execute immutable methods).
    // However we have not validated that Nashorn can compile *and* recompile scripts from multiple threads.
    //TODO: Write unit test to see if we can use all available processors to compile discovered javascript files.
    ScriptCompilationExecutor = Executors.newSingleThreadScheduledExecutor();
    // This is done to make sure the engine is allocated in the same thread that will be doing the compiling.
    Callable<Boolean> compileScriptsTask = new Callable<Boolean>() {
        @Override
        public Boolean call() {
            Nashorn = new ScriptEngineManager().getEngineByName("nashorn");

            if (jsLibs != null)
                for (Path lib : jsLibs)
                    if (!loadScriptLibrary(lib))
                        return false;

            // Recursively discover javascript files, compile, load, and setup any that are found.
            EnumSet<FileVisitOption> opts = EnumSet.of(FileVisitOption.FOLLOW_LINKS);
            try {
                Files.walkFileTree(baseScriptDirectory, opts, Integer.MAX_VALUE, new SimpleFileVisitor<Path>() {
                    @Override
                    public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs)
                            throws IOException {
                        if (Files.isDirectory(dir) && dir.getFileName().toString().startsWith("#"))
                            return FileVisitResult.SKIP_SUBTREE;
                        return super.preVisitDirectory(dir, attrs);
                    }

                    @Override
                    public FileVisitResult visitFile(Path path, BasicFileAttributes attrs) throws IOException {
                        if (Files.isRegularFile(path)) {
                            if (path.toString().toLowerCase().endsWith(".js")) {
                                MakeJavaScriptEndPointDescriptor(baseScriptDirectory, path, scriptConfig,
                                        new NewEndpointSetupCallback());
                            }
                        }
                        return FileVisitResult.CONTINUE;
                    }
                });
            } catch (IOException e) {
                Logger.error("Unable recursively load scripts", e);
                return false;
            }
            return true;
        }
    };
    // Walk the root directory recursively compiling all discovered javascript files (does not return until all endpoint files have been setup).
    try {
        if (!ScriptCompilationExecutor.submit(compileScriptsTask).get())
            return false;
    } catch (Throwable e) {
        Logger.error("Unable to compile scripts", e);
        return false;
    }
    if (watchScriptDirectory) {
        try {
            // Establish a watch on the root
            ScriptDirectoryWatcher.establishWatch(baseScriptDirectory, new DirectoryWatchEventListener() {
                // Internal Callable task to load, compile, and initialize a javascript file endpoint.
                final class CreateEndpointTask implements Callable<Void> {
                    public CreateEndpointTask(Path file, EndpointSetupCompleteCallback callback) {
                        this.file = file;
                        this.callback = callback;
                    }

                    private final Path file;
                    private final EndpointSetupCompleteCallback callback;

                    @Override
                    public Void call() {
                        MakeJavaScriptEndPointDescriptor(baseScriptDirectory, file, scriptConfig, callback);
                        return null;
                    }
                }

                // Internal Callable task that gives us the ability to schedule a delayed unload of a deleted or obsoleted endpoint.
                // By delaying for a period of time longer than twice the socket timeout, we can safely call the endpoint's teardown method.
                final class DecommisionEndpointTask implements Callable<Void> {
                    private DecommisionEndpointTask(ScriptObjectMirror endpoint) {
                        this.endpoint = endpoint;
                    }

                    private final ScriptObjectMirror endpoint;

                    @Override
                    public Void call() {
                        if (endpoint.hasMember("teardown"))
                            endpoint.callMember("teardown");
                        return null;
                    }
                }

                /**
                 * Called by the WatchService when the contents of the script directory have changed.
                 */
                @Override
                public void onWatchEvent(Path watchDir, final Path oldFile, final Path newFile,
                        FileChangeType change) {
                    if (change == FileChangeType.eRenamed) {
                        // If it was changed to something that does *not* end .js then it should no longer be considered an endpoint.
                        if (oldFile.toString().toLowerCase().endsWith(".js"))
                            if (!newFile.toString().toLowerCase().endsWith(".js"))
                                change = FileChangeType.eDeleted;
                    }
                    if (change == FileChangeType.eModified || change == FileChangeType.eRenamed) {
                        // Decommission the obsolete and load the update.
                        try {
                            assert newFile.toString().toLowerCase().endsWith(".js"); // Will be true because of the 'rename' check at the top of this method.
                            ScriptCompilationExecutor
                                    .submit(new CreateEndpointTask(newFile, new NewEndpointSetupCallback() {
                                        @Override
                                        public ScriptObjectMirror setupComplete(JavaScriptEndPoint endpoint) {
                                            ScriptObjectMirror old = super.setupComplete(endpoint);
                                            assert old != null;
                                            // Yeah, it's hincky, but it won't be in use this long after we remove it from the Map.
                                            ScriptCompilationExecutor.schedule(new DecommisionEndpointTask(old),
                                                    6, TimeUnit.MINUTES);
                                            return null;
                                        }
                                    }));
                        } catch (Throwable e) {
                            Logger.error("Unable to compile modified script found at "
                                    + newFile.toAbsolutePath().toString(), e);
                        }
                    } else if (change == FileChangeType.eCreated) {
                        // This is the easy one.  If a javascript file was created, load it.
                        if (newFile.toString().toLowerCase().endsWith(".js")) {
                            try {
                                ScriptCompilationExecutor.submit(
                                        new CreateEndpointTask(newFile, new NewEndpointSetupCallback()));
                            } catch (Throwable e) {
                                Logger.error("Unable to compile new script found at "
                                        + newFile.toAbsolutePath().toString(), e);
                            }
                        }
                    } else if (change == FileChangeType.eDeleted) {
                        // Endpoint should be decommisioned.
                        if (oldFile.toString().toLowerCase().endsWith(".js")) {
                            String uriKey = FileToUriKey(baseScriptDirectory, oldFile);
                            ScriptObjectMirror desc = scripts.remove(uriKey);
                            if (desc != null) {
                                // Yeah, it's hincky, but it won't be in use this long after we remove it from the Map.
                                ScriptCompilationExecutor.schedule(new DecommisionEndpointTask(desc), 6,
                                        TimeUnit.MINUTES);
                            }
                        }
                    }
                }
            });
        } catch (IOException e) {
            Logger.error("Unable to establish a real time watch on the script directory.", e);
        }
    } else // Not watching for changes, so we are done with the Executor.
        ScriptCompilationExecutor.shutdown();
    return true;
}

From source file:org.apache.taverna.databundle.TestDataBundles.java

@Test
public void setErrorObj() throws Exception {
    Path inputs = DataBundles.getInputs(dataBundle);

    Path portIn1 = DataBundles.getPort(inputs, "in1");
    Path cause1 = DataBundles.setError(portIn1, "a", "b");
    Path portIn2 = DataBundles.getPort(inputs, "in2");
    Path cause2 = DataBundles.setError(portIn2, "c", "d");

    Path outputs = DataBundles.getOutputs(dataBundle);
    Path portOut1 = DataBundles.getPort(outputs, "out1");

    ErrorDocument error = new ErrorDocument();
    error.getCausedBy().add(cause1);// w  ww.  j  av  a  2 s. c  o m
    error.getCausedBy().add(cause2);

    error.setMessage("Something did not work");
    error.setTrace("Here\nis\nwhy\n");

    Path errorPath = DataBundles.setError(portOut1, error);
    assertEquals("out1.err", errorPath.getFileName().toString());

    List<String> errLines = Files.readAllLines(errorPath, Charset.forName("UTF-8"));
    assertEquals(8, errLines.size());
    assertEquals("../inputs/in1.err", errLines.get(0));
    assertEquals("../inputs/in2.err", errLines.get(1));
    assertEquals("", errLines.get(2));
    assertEquals("Something did not work", errLines.get(3));
    assertEquals("Here", errLines.get(4));
    assertEquals("is", errLines.get(5));
    assertEquals("why", errLines.get(6));
    assertEquals("", errLines.get(7));
}

From source file:au.org.ands.vocabs.toolkit.db.AccessPointUtils.java

/** Create an access point for a version, for a file. Don't duplicate it,
 * if it already exists.//from   ww  w  .ja v a2s.c  om
 * @param version The version for which the access point is to be created.
 * @param format The format of the access point. If null, attempt
 * to deduce a format from the filename.
 * @param targetPath The path to the existing file.
 */
public static void createFileAccessPoint(final Version version, final String format, final Path targetPath) {
    String targetPathString;
    try {
        targetPathString = targetPath.toRealPath().toString();
    } catch (IOException e) {
        LOGGER.error("createFileAccessPoint failed calling " + "toRealPath() on file: " + targetPath.toString(),
                e);
        // Try toAbsolutePath() instead.
        targetPathString = targetPath.toAbsolutePath().toString();
    }
    List<AccessPoint> aps = getAccessPointsForVersionAndType(version, AccessPoint.FILE_TYPE);
    for (AccessPoint ap : aps) {
        if (targetPathString.equals(getToolkitPath(ap))) {
            // Already exists. Check the format.
            if (format != null && !format.equals(getFormat(ap))) {
                // Format changed.
                updateFormat(ap, format);
            }
            return;
        }
    }
    // No existing access point for this file, so create a new one.
    AccessPoint ap = new AccessPoint();
    ap.setVersionId(version.getId());
    ap.setType(AccessPoint.FILE_TYPE);
    JsonObjectBuilder jobPortal = Json.createObjectBuilder();
    JsonObjectBuilder jobToolkit = Json.createObjectBuilder();
    jobToolkit.add("path", targetPathString);
    // toolkitData is now done.
    ap.setToolkitData(jobToolkit.build().toString());
    ap.setPortalData("");
    // Persist what we have ...
    AccessPointUtils.saveAccessPoint(ap);
    // ... so that now we can get access to the
    // ID of the persisted object with ap.getId().
    String baseFilename = targetPath.getFileName().toString();
    jobPortal.add("uri", downloadPrefixProperty + ap.getId() + "/" + baseFilename);
    // Now work on the format. The following is messy. It's really very
    // much for the best if the portal provides the format.
    String deducedFormat;
    if (format == null) {
        // The format was not provided to us, so try to deduce it.
        // First, try the extension.
        String extension = FilenameUtils.getExtension(baseFilename);
        deducedFormat = EXTENSION_TO_FILE_FORMAT_MAP.get(extension);
        if (deducedFormat == null) {
            // No luck with the extension, so try probing.
            try {
                String mimeType = Files.probeContentType(targetPath);
                if (mimeType == null) {
                    // Give up.
                    deducedFormat = "Unknown";
                } else {
                    deducedFormat = MIMETYPE_TO_FILE_FORMAT_MAP.get(mimeType);
                    if (deducedFormat == null) {
                        // Give up.
                        deducedFormat = "Unknown";
                    }
                }
            } catch (IOException e) {
                LOGGER.error("createFileAccessPoint failed to get " + "MIME type of file: " + targetPathString,
                        e);
                // Give up.
                deducedFormat = "Unknown";
            }
        }
    } else {
        // The format was provided to us, so use that. Much easier.
        deducedFormat = format;
    }
    jobPortal.add("format", deducedFormat);
    // portalData is now complete.
    ap.setPortalData(jobPortal.build().toString());
    AccessPointUtils.updateAccessPoint(ap);
}

From source file:org.apache.taverna.databundle.TestDataBundles.java

@Test
public void newListItem() throws Exception {
    Path inputs = DataBundles.getInputs(dataBundle);
    Path list = DataBundles.getPort(inputs, "in1");
    DataBundles.createList(list);/*from   w ww  .  j  a  v a 2 s  . c o  m*/
    Path item0 = DataBundles.newListItem(list);
    assertEquals(list, item0.getParent());
    assertTrue(item0.getFileName().toString().contains("0"));
    assertFalse(Files.exists(item0));
    DataBundles.setStringValue(item0, "test");

    Path item1 = DataBundles.newListItem(list);
    assertTrue(item1.getFileName().toString().contains("1"));
    // Because we've not actually created item1 yet
    assertEquals(item1, DataBundles.newListItem(list));
    DataBundles.setStringValue(item1, "test");

    // Check that DataBundles.newListItem can deal with gaps
    Files.delete(item0);
    Path item2 = DataBundles.newListItem(list);
    assertTrue(item2.getFileName().toString().contains("2"));

    // Check that non-numbers don't interfere
    Path nonumber = list.resolve("nonumber");
    Files.createFile(nonumber);
    item2 = DataBundles.newListItem(list);
    assertTrue(item2.getFileName().toString().contains("2"));

    // Check that extension is stripped
    Path five = list.resolve("5.txt");
    Files.createFile(five);
    Path item6 = DataBundles.newListItem(list);
    assertTrue(item6.getFileName().toString().contains("6"));
}

From source file:org.apache.taverna.databundle.TestDataBundles.java

@Test
public void setErrorArgs() throws Exception {
    Path inputs = DataBundles.getInputs(dataBundle);
    Path portIn1 = DataBundles.getPort(inputs, "in1");
    Path errorPath = DataBundles.setError(portIn1, "Something did not work", "A very\n long\n error\n trace");
    assertEquals("in1.err", errorPath.getFileName().toString());

    List<String> errLines = Files.readAllLines(errorPath, Charset.forName("UTF-8"));
    assertEquals(6, errLines.size());// w  ww. j a  v a 2 s .c  o m
    assertEquals("", errLines.get(0));
    assertEquals("Something did not work", errLines.get(1));
    assertEquals("A very", errLines.get(2));
    assertEquals(" long", errLines.get(3));
    assertEquals(" error", errLines.get(4));
    assertEquals(" trace", errLines.get(5));
}

From source file:eu.eubrazilcc.lvl.service.io.ImportPublicationsTask.java

private Callable<Integer> importPubMedSubTask(final List<String> ids, final EntrezHelper entrez,
        final File tmpDir, final Format format, final String extension) {
    return new Callable<Integer>() {
        private int efetchCount = 0;

        @Override/*  ww  w.  j  a va2 s .c o m*/
        public Integer call() throws Exception {
            setStatus("Finding missing publications between PubMed and the local collection");
            // filter out the publications that are already stored in the database, creating a new set
            // with the identifiers that are missing from the database. Using a set ensures that 
            // duplicate identifiers are also removed from the original list
            final List<String> ids2 = from(ids).transform(new Function<String, String>() {
                @Override
                public String apply(final String id) {
                    String result = id;
                    for (int i = 0; i < filters.size() && result != null; i++) {
                        final RecordFilter filter = filters.get(i);
                        if (filter.canBeApplied(PUBMED)) {
                            result = filters.get(i).filterById(id);
                        }
                    }
                    return result;
                }
            }).filter(notNull()).toSet().asList();
            if (ids2.size() > 0) {
                setStatus("Fetching publications from PubMed");
                // update progress
                int pendingCount = pending.addAndGet(ids2.size());
                setProgress(100.0d * fetched.get() / pendingCount);
                // fetch sequence files
                final Path tmpDir2 = createTempDirectory(tmpDir.toPath(), "fetch_pub_task_");
                entrez.efetch(ids2, 0, MAX_RECORDS_FETCHED, tmpDir2.toFile(), format);
                // import publication files to the database
                for (final String id : ids2) {
                    setStatus("Importing PubMed publications into local collection");
                    final Path source = tmpDir2.resolve(id + "." + extension);
                    try {
                        // insert publication in the database
                        final PubmedArticle pmArticle = PUBMED_XMLB.typeFromFile(source.toFile());
                        final Reference reference = parseArticle(pmArticle);
                        REFERENCE_DAO.insert(reference, true);
                        efetchCount++;
                        LOGGER.info("New PubMed file stored: " + source.toString());
                        // update progress
                        int fetchedCount = fetched.incrementAndGet();
                        setProgress(100.0d * fetchedCount / pending.get());
                    } catch (Exception e) {
                        LOGGER.warn("Failed to import publication from file: " + source.getFileName(), e);
                    }
                }
            }
            checkState(ids2.size() == efetchCount, "No all publications were imported");
            return efetchCount;
        }
    };
}

From source file:at.tfr.securefs.client.SecurefsClient.java

public void run() {
    DateTime start = new DateTime();
    try (FileSystem fs = FileSystems.newFileSystem(new URI(baseDir), null)) {

        for (Path path : files) {

            Path sec = fs.getPath(path.toString() + (asyncTest ? "." + Thread.currentThread().getId() : ""));

            if (write) {
                if (!path.toFile().exists()) {
                    System.err.println(Thread.currentThread() + ": NoSuchFile: " + path + " currentWorkdir="
                            + Paths.get("./").toAbsolutePath());
                    continue;
                }/*from w ww. j  a va  2  s  . co  m*/

                if (path.getParent() != null) {
                    fs.provider().createDirectory(fs.getPath(path.getParent().toString()));
                }
                final OutputStream secOs = Files.newOutputStream(sec);

                System.out.println(Thread.currentThread() + ": Sending file: " + start + " : " + sec);

                IOUtils.copyLarge(Files.newInputStream(path), secOs, new byte[128 * 1024]);
                secOs.close();
            }

            Path out = path.resolveSibling(
                    path.getFileName() + (asyncTest ? "." + Thread.currentThread().getId() : "") + ".out");

            if (read) {
                System.out.println(Thread.currentThread() + ": Reading file: " + new DateTime() + " : " + out);
                if (out.getParent() != null) {
                    Files.createDirectories(out.getParent());
                }

                final InputStream secIs = Files.newInputStream(sec);
                IOUtils.copyLarge(secIs, Files.newOutputStream(out), new byte[128 * 1024]);
                secIs.close();
            }

            if (write && read) {
                long inputChk = FileUtils.checksumCRC32(path.toFile());
                long outputChk = FileUtils.checksumCRC32(out.toFile());

                if (inputChk != outputChk) {
                    throw new IOException(Thread.currentThread()
                            + ": Checksum Failed: failure to write/read: in=" + path + ", out=" + out);
                }
                System.out.println(Thread.currentThread() + ": Checked Checksums: " + new DateTime() + " : "
                        + inputChk + " / " + outputChk);
            }

            if (delete) {
                boolean deleted = fs.provider().deleteIfExists(sec);
                if (!deleted) {
                    throw new IOException(
                            Thread.currentThread() + ": Delete Failed: failure to delete: in=" + path);
                } else {
                    System.out.println(Thread.currentThread() + ": Deleted File: in=" + path);
                }
            }
        }
    } catch (Throwable t) {
        t.printStackTrace();
        throw new RuntimeException(t);
    }
}