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.databundle.TestDataBundles.java

@Test
public void getIntermediate() throws Exception {
    UUID uuid = UUID.randomUUID();
    Path inter = DataBundles.getIntermediate(dataBundle, uuid);
    assertFalse(Files.exists(inter));
    DataBundles.setStringValue(inter, "intermediate");
    Path parent = inter.getParent();
    assertEquals(dataBundle.getRoot().resolve("intermediates"), parent.getParent());
    String parentName = parent.getFileName().toString();
    assertEquals(2, parentName.length());
    assertTrue(uuid.toString().startsWith(parentName));
    // Filename is a valid string
    String interFileName = inter.getFileName().toString();
    assertTrue(interFileName.startsWith(parentName));
    assertEquals(uuid, UUID.fromString(interFileName));
}

From source file:org.apache.openaz.xacml.pdp.test.TestBase.java

@Override
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
    ////from  w w w  . j  a  va2  s . com
    // Sanity check the file name
    //
    Matcher matcher = this.pattern.matcher(file.getFileName().toString());
    if (matcher.matches()) {
        //
        // if user has limited which files to use, check that here
        //
        if (testNumbersArray != null) {
            String fileNameString = file.getFileName().toString();
            boolean found = false;
            for (String numberString : testNumbersArray) {
                if (fileNameString.contains(numberString)) {
                    found = true;
                    break;
                }
            }
            if (!found) {
                //
                // this test is not in the list to be run, so skip it
                //
                return super.visitFile(file, attrs);
            }
        }
        try {
            //
            // Pull what this request is supposed to be
            //
            String group = null;
            int count = matcher.groupCount();
            if (count >= 1) {
                group = matcher.group(count - 1);
            }
            //
            // Send it
            //
            this.sendRequest(file, group);
        } catch (Exception e) {
            logger.error(e);
            e.printStackTrace();
        }
    }
    return super.visitFile(file, attrs);
}

From source file:de.elomagic.carafile.client.CaraFileClient.java

/**
 * Uploads a file (Multi chunk upload).// www  . j a  v  a  2s. c  om
 * <p/>
 * Multi chunk upload means that the file will be devived in one or more chunks and each chunk can be downloaded to a different peer.
 *
 * @param path Must be a file and not a directory. File will not be deleted
 * @param filename Name of the file. If null then name of the parameter path will be used
 * @return Returns the {@link MetaData} of the uploaded stream
 * @throws IOException Thrown when unable to call REST services
 * @throws java.security.GeneralSecurityException Thrown when unable to determine SHA-1 of the file
 * @see CaraFileClient#uploadFile(java.net.URI, java.io.InputStream, java.lang.String, long)
 */
public MetaData uploadFile(final Path path, final String filename)
        throws IOException, GeneralSecurityException {
    if (registryURI == null) {
        throw new IllegalArgumentException("Parameter 'registryURI' must not be null!");
    }

    if (path == null) {
        throw new IllegalArgumentException("Parameter 'path' must not be null!");
    }

    if (Files.notExists(path)) {
        throw new FileNotFoundException("File \"" + path + "\" doesn't exists!");
    }

    if (Files.isDirectory(path)) {
        throw new IOException("Parameter 'path' is not a file!");
    }

    String fn = filename == null ? path.getFileName().toString() : filename;

    MetaData md = CaraFileUtils.createMetaData(path, fn);
    md.setRegistryURI(registryURI);

    String json = JsonUtil.write(md);

    LOG.debug("Register " + md.getId() + " file at " + registryURI.toString());
    URI uri = CaraFileUtils.buildURI(registryURI, "registry", "register");
    HttpResponse response = executeRequest(Request.Post(uri).bodyString(json, ContentType.APPLICATION_JSON))
            .returnResponse();

    if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
        throw new IOException("Unable to register file. " + response.getStatusLine().getReasonPhrase());
    }

    Set<PeerData> peerDataSet = downloadPeerSet();

    byte[] buffer = new byte[md.getChunkSize()];
    try (InputStream in = Files.newInputStream(path, StandardOpenOption.READ);
            BufferedInputStream bis = new BufferedInputStream(in, md.getChunkSize())) {
        int bytesRead;
        int chunkIndex = 0;
        while ((bytesRead = bis.read(buffer)) > 0) {
            String chunkId = md.getChunk(chunkIndex).getId();

            URI peerURI = peerSelector.getURI(peerDataSet, chunkIndex);
            URI seedChunkUri = CaraFileUtils.buildURI(peerURI, "peer", "seedChunk", chunkId);

            LOG.debug("Uploading chunk " + chunkId + " to peer " + seedChunkUri.toString() + ";Index="
                    + chunkIndex + ";Length=" + bytesRead);
            response = executeRequest(Request.Post(seedChunkUri).bodyStream(
                    new ByteArrayInputStream(buffer, 0, bytesRead), ContentType.APPLICATION_OCTET_STREAM))
                            .returnResponse();

            if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
                throw new IOException("Unable to upload file. " + response.getStatusLine().getStatusCode() + " "
                        + response.getStatusLine().getReasonPhrase());
            }

            chunkIndex++;
        }
    }

    return md;
}

From source file:au.edu.uq.cmm.paul.servlet.WebUIController.java

private ArrayList<BuildInfo> loadBuildInfo(ServletContext servletContext) {
    final ArrayList<BuildInfo> res = new ArrayList<>();
    res.add(BuildInfo.readBuildInfo("au.edu.uq.cmm", "aclslib"));
    res.add(BuildInfo.readBuildInfo("au.edu.uq.cmm", "eccles"));
    try {/*  w w w  .  ja  v  a  2  s  .co  m*/
        Path start = FileSystems.getDefault().getPath(servletContext.getRealPath("/META-INF/maven"));
        Files.walkFileTree(start, new SimpleFileVisitor<Path>() {
            @Override
            public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
                if (file.getFileName().toString().equals("pom.properties")) {
                    try (InputStream is = new FileInputStream(file.toFile())) {
                        res.add(BuildInfo.readBuildInfo(is));
                    }
                }
                return FileVisitResult.CONTINUE;
            }
        });
    } catch (IOException ex) {
        LOG.error("Problem loading build info");
    }
    return res;
}

From source file:nextflow.fs.dx.DxFileSystemProvider.java

/**
 * Implements the *copy* operation using the DnaNexus API *clone*
 *
 *
 * <p>//  w w  w.  jav  a2 s.c  o  m
 * See clone https://wiki.dnanexus.com/API-Specification-v1.0.0/Cloning#API-method%3A-%2Fclass-xxxx%2Fclone
 *
 * @param source
 * @param target
 * @param options
 * @throws IOException
 */

@Override
public void copy(Path source, Path target, CopyOption... options) throws IOException {

    List<CopyOption> opts = Arrays.asList(options);
    boolean targetExists = Files.exists(target);

    if (targetExists) {
        if (Files.isRegularFile(target)) {
            if (opts.contains(StandardCopyOption.REPLACE_EXISTING)) {
                Files.delete(target);
            } else {
                throw new FileAlreadyExistsException("Copy failed -- target file already exists: " + target);
            }

        } else if (Files.isDirectory(target)) {
            target = target.resolve(source.getFileName());
        } else {
            throw new UnsupportedOperationException();
        }
    }

    String name1 = source.getFileName().toString();
    String name2 = target.getFileName().toString();
    if (!name1.equals(name2)) {
        throw new UnsupportedOperationException(
                "Copy to a file with a different name is not supported: " + source.toString());
    }

    final DxPath dxSource = toDxPath(source);
    final DxFileSystem dxFileSystem = dxSource.getFileSystem();
    dxFileSystem.fileCopy(dxSource, toDxPath(target));
}

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

private Callable<Integer> importGenBankSubTask(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//w  w w.j  a va  2s.c om
        public Integer call() throws Exception {
            setStatus("Finding missing sequences between GenBank and the local collection");
            // filter out the sequence 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(GENBANK)) {
                            result = filters.get(i).filterById(id);
                        }
                    }
                    return result;
                }
            }).filter(notNull()).toSet().asList();
            if (ids2.size() > 0) {
                setStatus("Fetching sequences from GenBank");
                // update progress
                int pendingCount = pending.addAndGet(ids2.size());
                setProgress(100.0d * fetched.get() / pendingCount);
                // fetch sequence files
                final Path tmpDir2 = createTempDirectory(tmpDir.toPath(), "fetch_seq_task_");
                entrez.efetch(ids2, 0, MAX_RECORDS_FETCHED, tmpDir2.toFile(), format);
                // import sequence files to the database
                for (final String id : ids2) {
                    setStatus("Importing GenBank sequences into local collection");
                    final Path source = tmpDir2.resolve(id + "." + extension);
                    try {
                        // insert sequence in the database
                        final GBSeq gbSeq = GBSEQ_XMLB.typeFromFile(source.toFile());
                        final T sequence = parseSequence(gbSeq, builder);
                        dao.insert(sequence);
                        efetchCount++;
                        LOGGER.info("New GBSeqXML file stored: " + source.toString());
                        // update progress
                        int fetchedCount = fetched.incrementAndGet();
                        setProgress(100.0d * fetchedCount / pending.get());
                        // extract references from the sequence
                        pmids.addAll(getPubMedIds(gbSeq));
                    } catch (Exception e) {
                        LOGGER.warn("Failed to import sequence from file: " + source.getFileName(), e);
                    }
                }
            }
            checkState(ids2.size() == efetchCount, "No all sequences were imported");
            return efetchCount;
        }
    };
}

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

/**
 * Creates a thumbnail for the image file using plain old java
 * @param file the image file//from  w w  w  .ja va2s.  c  om
 * @param thumbFile the resulting thumbnail file
 * @param size the size of the thumbnail
 */
private void createThumbnailUsingJava(Path file, Path thumbFile, IconSize size) throws IOException {

    try {
        BufferedImage image = ImageIO.read(file.toFile());

        int w = image.getWidth();
        int h = image.getHeight();

        // Never scale up
        if (w <= size.getSize() && h <= size.getSize()) {
            FileUtils.copyFile(file.toFile(), thumbFile.toFile());

        } else {
            // Compute the scale factor
            double dx = (double) size.getSize() / (double) w;
            double dy = (double) size.getSize() / (double) h;
            double d = Math.min(dx, dy);

            // Create the thumbnail
            BufferedImage thumbImage = new BufferedImage((int) Math.round(w * d), (int) Math.round(h * d),
                    BufferedImage.TYPE_INT_RGB);
            Graphics2D g2d = thumbImage.createGraphics();
            AffineTransform at = AffineTransform.getScaleInstance(d, d);
            g2d.drawRenderedImage(image, at);
            g2d.dispose();

            // Save the thumbnail
            String fileName = thumbFile.getFileName().toString();
            ImageIO.write(thumbImage, FilenameUtils.getExtension(fileName), thumbFile.toFile());

            // Releas resources
            image.flush();
            thumbImage.flush();
        }

        // Update the timestamp of the thumbnail file to match the change date of the image file
        Files.setLastModifiedTime(thumbFile, Files.getLastModifiedTime(file));

    } catch (Exception e) {
        log.error("Error creating thumbnail for image " + file, e);
        throw new IOException(e);
    }
}

From source file:com.ejie.uda.jsonI18nEditor.Editor.java

public void importResources(Path dir) {

    Stream<Path> filter;

    try {/*from   w  ww .  ja v a 2 s . c om*/
        if (!closeCurrentSession()) {
            return;
        }
        if (Files.isDirectory(dir, LinkOption.NOFOLLOW_LINKS)) {
            reset();
            resourcesDir = dir;
            filter = Files.walk(resourcesDir, 1).filter(path -> Resources.isResource(path));

        } else {
            reset();
            // Se ha arrastrado un fichero de 18n individual, se debe de obtener los recursos relacionados con el bundle al que pertenece.
            Pattern.matches(BUNDLE_REGEX, dir.getFileName().toString());
            Pattern regex = Pattern.compile(BUNDLE_REGEX);
            resourcesDir = dir.getParent();
            inputFile = dir;
            Matcher regexMatcher = regex.matcher(dir.getFileName().toString());
            if (regexMatcher.find()) {
                this.bundle = regexMatcher.group(1);
                filter = Files.walk(resourcesDir, 1).filter(path -> Resources.isResource(path, this.bundle));
            } else {
                showError(MessageBundle.get("resources.open.error.multiple"));
                return;
            }
            //         Pattern.matches("BUNDLE_REGEX", dir.getFileName().toString());
            //         showError(MessageBundle.get("resources.open.error.multiple"));
            //         return;
        }

        filter.forEach(path -> {
            try {
                Resource resource = Resources.read(path);
                setupResource(resource);
            } catch (Exception e) {
                e.printStackTrace();
                showError(MessageBundle.get("resources.open.error.single", path.toString()));
            }
        });

        List<String> recentDirs = settings.getListProperty("history");
        recentDirs.remove(dir);
        recentDirs.add(dir.toString());
        if (recentDirs.size() > 5) {
            recentDirs.remove(0);
        }
        settings.setProperty("history", recentDirs);
        editorMenu.setRecentItems(Lists.reverse(recentDirs));

        Map<String, String> keys = Maps.newTreeMap();
        resources.forEach(resource -> keys.putAll(resource.getTranslations()));
        //         resources.forEach(resource -> {
        //            
        //            
        //            
        //         });
        List<String> keyList = Lists.newArrayList(keys.keySet());
        translationTree.setModel(new TranslationTreeModel(keyList));

        updateUI();
        //         for (String key : keyList) {
        //            boolean anyEmpty = false;
        //            
        //            for (Resource resource : resources) {
        //               if (StringUtils.isBlank(resource.getTranslation(key))){
        //                  anyEmpty = true;
        //               }
        //            }
        //            
        //            TranslationTreeModel model = (TranslationTreeModel) translationTree.getModel();
        //            TranslationTreeNode node = model.getNodeByKey(key);
        //            
        //            node
        //         }
        //         keyList.stream().filter(key -> {
        //            
        //            resources.stream().filter(resource -> {
        //               return StringUtils.isNotBlank(resource.getTranslation(key));
        //            });
        //            return true;
        //         });
    } catch (IOException e) {
        e.printStackTrace();
        showError(MessageBundle.get("resources.open.error.multiple"));
    }
}

From source file:com.streamsets.datacollector.antennadoctor.storage.AntennaDoctorStorage.java

private List<AntennaDoctorRuleBean> loadRules() {
    Path database = repositoryDirectory.resolve(overrideRunnable == null ? AntennaDoctorConstants.FILE_DATABASE
            : AntennaDoctorConstants.FILE_OVERRIDE);
    LOG.trace("Loading rules from: {}", database);

    try (InputStream inputStream = Files.newInputStream(database)) {
        AntennaDoctorStorageBean storageBean = ObjectMapperFactory.get().readValue(inputStream,
                AntennaDoctorStorageBean.class);

        // Version protection
        if (storageBean.getSchemaVersion() != AntennaDoctorStorageBean.CURRENT_SCHEMA_VERSION) {
            LOG.error(/*from w  w  w  .j  av a2 s  .  c o  m*/
                    "Ignoring the knowledge base file since it has incompatible schema version ({} versus expected {})",
                    storageBean.getSchemaVersion(), AntennaDoctorStorageBean.CURRENT_SCHEMA_VERSION);
            return Collections.emptyList();
        }

        return storageBean.getRules();
    } catch (Throwable e) {
        LOG.error("Can't load knowledge base from {}: ", database.getFileName().toString(), e);
        return Collections.emptyList();
    }
}

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

private Path setUpACrossCell(String cellName, Path crossCellContents) throws IOException {
    File crossCellsRoot = tmp2.getRoot().resolve("cross_cells").toFile();
    crossCellsRoot.mkdirs();/*from  w  w w.j a  va  2 s .com*/

    Path newCellLocation = crossCellsRoot.toPath().resolve(crossCellContents.getFileName());
    Files.move(crossCellContents, newCellLocation);
    workspace.addBuckConfigLocalOption("repositories", cellName, newCellLocation.toString());
    return newCellLocation;
}