Example usage for java.nio.file Files newDirectoryStream

List of usage examples for java.nio.file Files newDirectoryStream

Introduction

In this page you can find the example usage for java.nio.file Files newDirectoryStream.

Prototype

public static DirectoryStream<Path> newDirectoryStream(Path dir, DirectoryStream.Filter<? super Path> filter)
        throws IOException 

Source Link

Document

Opens a directory, returning a DirectoryStream to iterate over the entries in the directory.

Usage

From source file:org.fao.geonet.api.records.attachments.FilesystemStore.java

@Override
public Path getResource(ServiceContext context, String metadataUuid, String resourceId) throws Exception {
    // Those characters should not be allowed by URL structure
    if (resourceId.contains("..") || resourceId.startsWith("/") || resourceId.startsWith("file:/")) {
        throw new SecurityException(String.format("Invalid resource identifier '%s'.", resourceId));
    }//from w ww  . j av a  2 s  . c  om
    ApplicationContext _appContext = ApplicationContextHolder.get();
    AccessManager accessManager = _appContext.getBean(AccessManager.class);
    GeonetworkDataDirectory dataDirectory = _appContext.getBean(GeonetworkDataDirectory.class);
    String metadataId = getAndCheckMetadataId(metadataUuid);
    Path metadataDir = Lib.resource.getMetadataDir(dataDirectory, metadataId);

    Path resourceFile = null;

    boolean canDownload = accessManager.canDownload(context, metadataId);
    for (MetadataResourceVisibility r : MetadataResourceVisibility.values()) {
        try (DirectoryStream<Path> directoryStream = Files.newDirectoryStream(metadataDir.resolve(r.toString()),
                resourceId)) {
            for (Path path : directoryStream) {
                if (Files.isRegularFile(path)) {
                    resourceFile = path;
                }
            }
        } catch (IOException ignored) {
        }
    }

    if (resourceFile != null && Files.exists(resourceFile)) {
        if (resourceFile.getParent().getFileName().toString()
                .equals(MetadataResourceVisibility.PRIVATE.toString()) && !canDownload) {
            throw new SecurityException(String.format(
                    "Current user can't download resources for metadata '%s' and as such can't access the requested resource '%s'.",
                    metadataUuid, resourceId));
        }
        return resourceFile;
    } else {
        throw new ResourceNotFoundException(
                String.format("Metadata resource '%s' not found for metadata '%s'", resourceId, metadataUuid));
    }
}

From source file:io.ecarf.core.utils.LogParser.java

/**
 * @throws Exception /*from w  w w  .  j  a  v a 2s .  co m*/
 * 
 */
public LogParser(String folder) throws Exception {
    super();

    boolean remote = folder.startsWith(GoogleMetaData.CLOUD_STORAGE_PREFIX);

    if (remote) {

        String bucket = StringUtils.remove(folder, GoogleMetaData.CLOUD_STORAGE_PREFIX);
        this.setUp();
        List<StorageObject> objects = this.service.listCloudStorageObjects(bucket);

        for (StorageObject object : objects) {
            String name = object.getName();
            if (name.endsWith(Constants.DOT_LOG)) {
                String localFile = FilenameUtils.getLocalFilePath(name);

                service.downloadObjectFromCloudStorage(name, localFile, bucket);

                this.files.add(localFile);
            }
        }

    } else {
        // local file
        DirectoryStream.Filter<Path> filter = new DirectoryStream.Filter<Path>() {
            public boolean accept(Path file) throws IOException {

                String filename = file.toString();
                return filename.endsWith(Constants.DOT_LOG) && filename.contains(PROCESSOR)
                        || filename.contains(COORDINATOR);
            }
        };

        Path dir = Paths.get(folder);
        try (DirectoryStream<Path> stream = Files.newDirectoryStream(dir, filter)) {
            for (Path path : stream) {
                this.files.add(path.toString());
            }
        }
    }

}

From source file:org.opencastproject.staticfiles.impl.StaticFileServiceImpl.java

@Override
public void persistFile(final String uuid) throws NotFoundException, IOException {
    final String org = securityService.getOrganization().getId();
    try (DirectoryStream<Path> folders = Files.newDirectoryStream(getTemporaryStorageDir(org),
            getDirsEqualsUuidFilter(uuid))) {
        for (Path folder : folders) {
            Files.move(folder, getDurableStorageDir(org).resolve(folder.getFileName()));
        }//w w  w .jav a 2  s.  c  om
    }
}

From source file:de.decoit.visa.rdf.RDFManager.java

/**
 * Construct a new RDFManager object. It will open and clear the TDB
 * database at the specified location if it exists. Otherwise a new database
 * will be created. The program must have read and write access to the
 * database location./* w  w  w  . ja  v  a  2 s .  c o  m*/
 *
 * @param pLocation The TDB database will be opened at this location
 * @throws IOException if the VSA template directory is not accessible
 * @throws ParserConfigurationException
 * @throws SAXException
 */
public RDFManager(String pLocation) throws IOException, ParserConfigurationException, SAXException {
    source = new ArrayList<>();
    vsaTemplates = new ArrayList<>();
    activeNamedModel = null;

    // Load a list of available VSA templates
    DirectoryStream<Path> dirStream = Files.newDirectoryStream(Paths.get("res/vsa"), "*.xml");
    DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
    for (Path p : dirStream) {
        DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
        Document doc = dBuilder.parse(Files.newInputStream(p, StandardOpenOption.READ));

        doc.getDocumentElement().normalize();

        vsaTemplates.add(doc);
    }

    // Create or load the TDB database at pLocation
    ds = TDBFactory.createDataset(pLocation);

    ds.begin(ReadWrite.WRITE);

    try {
        // Do some cleanup if last run didn't clear the database
        // Remove all named models from the database
        Iterator<String> itNames = ds.listNames();
        ArrayList<String> names = new ArrayList<>();

        while (itNames.hasNext()) {
            names.add(itNames.next());
        }

        for (String n : names) {
            ds.removeNamedModel(n);
        }

        // Clear the default model
        ds.getDefaultModel().removeAll();

        ds.commit();
    } catch (Throwable ex) {
        ds.abort();
    } finally {
        ds.end();

        // Sync changes to disk
        TDB.sync(ds);
    }
}

From source file:ch.cyberduck.core.Local.java

public AttributedList<Local> list(final Filter<String> filter) throws AccessDeniedException {
    final AttributedList<Local> children = new AttributedList<Local>();
    try (DirectoryStream<Path> stream = Files.newDirectoryStream(Paths.get(path),
            new DirectoryStream.Filter<Path>() {
                @Override//from   w  ww  .  j ava 2 s  . c om
                public boolean accept(final Path entry) throws IOException {
                    if (null == entry.getFileName()) {
                        return false;
                    }
                    return filter.accept(entry.getFileName().toString());
                }
            })) {
        for (Path entry : stream) {
            children.add(LocalFactory.get(entry.toString()));
        }
    } catch (IOException e) {
        throw new LocalAccessDeniedException(String.format("Error listing files in directory %s", path), e);
    }
    return children;
}

From source file:im.bci.gamesitekit.GameSiteKitMain.java

private List<ScreenshotMV> createScreenshotsMV(Path localeOutputDir) throws IOException {
    List<ScreenshotMV> screenshots = new ArrayList<>();
    try (DirectoryStream<Path> stream = Files.newDirectoryStream(screenshotThumbnailsOutputDir, IMAGE_GLOB)) {
        for (Path thumbnail : stream) {
            Path screenshot = screenshotsOutputDir.resolve(thumbnail.getFileName());
            if (Files.exists(screenshot)) {
                ScreenshotMV mv = new ScreenshotMV();
                mv.setFull(localeOutputDir.relativize(screenshot).toString().replace('\\', '/'));
                mv.setThumbnail(localeOutputDir.relativize(thumbnail).toString().replace('\\', '/'));
                screenshots.add(mv);/* ww w .j ava 2s .com*/
            }
        }
    }
    Collections.sort(screenshots, new Comparator<ScreenshotMV>() {

        @Override
        public int compare(ScreenshotMV o1, ScreenshotMV o2) {
            return o1.getFull().compareTo(o2.getFull());
        }

    });
    return screenshots;
}

From source file:ee.ria.xroad.confproxy.util.ConfProxyHelper.java

/**
 * Gets the list of subdirectory names in the given directory path.
 * @param dir path to the directory/*from  w  w  w  . ja v a 2 s .  co  m*/
 * @return list of subdirectory names
 * @throws IOException if opening the directory fails
 */
private static List<String> subDirectoryNames(final Path dir) throws IOException {
    List<String> subdirs = new ArrayList<>();
    try (DirectoryStream<Path> stream = Files.newDirectoryStream(dir, Files::isDirectory)) {
        for (Path subDir : stream) {
            String conf = subDir.getFileName().toString();
            subdirs.add(conf);
        }
        return subdirs;
    }
}

From source file:org.structr.javaparser.JavaParserModule.java

/**
 * Add compilation units of all jar files found in the given folder to the index.
 *
 * @param folderPath//w  w w.  ja va  2  s. c o m
 */
public void addJarsToIndex(final String folderPath) {

    logger.info("Starting adding jar files in " + folderPath);

    final CombinedTypeSolver typeSolver = new CombinedTypeSolver();
    typeSolver.add(new ReflectionTypeSolver());

    final AtomicLong count = new AtomicLong(0);

    try {
        Files.newDirectoryStream(Paths.get(folderPath), path -> path.toString().endsWith(".jar"))
                .forEach((file) -> {
                    try {
                        typeSolver.add(new JarTypeSolver(new FileInputStream(file.toFile())));
                        count.addAndGet(1L);

                    } catch (IOException ex) {
                    }
                });

    } catch (IOException ex) {
    }

    logger.info("Added " + count.toString() + " jar files to the type solver");

    typeSolver.add(structrTypeSolver);

    facade = JavaParserFacade.get(typeSolver);

    logger.info("Done with adding jar files in " + folderPath);
}

From source file:org.apache.solr.handler.TestRestoreCore.java

@Test
public void testFailedRestore() throws Exception {
    int nDocs = BackupRestoreUtils.indexDocs(masterClient, "collection1", docsSeed);

    String location = createTempDir().toFile().getAbsolutePath();
    String snapshotName = TestUtil.randomSimpleString(random(), 1, 5);
    String params = "&name=" + snapshotName + "&location=" + URLEncoder.encode(location, "UTF-8");
    String baseUrl = masterJetty.getBaseUrl().toString();

    TestReplicationHandlerBackup.runBackupCommand(masterJetty, ReplicationHandler.CMD_BACKUP, params);

    CheckBackupStatus checkBackupStatus = new CheckBackupStatus((HttpSolrClient) masterClient,
            DEFAULT_TEST_CORENAME, null);
    while (!checkBackupStatus.success) {
        checkBackupStatus.fetchStatus();
        Thread.sleep(1000);/*from  w  w  w . j a  v a  2 s .c  o m*/
    }

    //Remove the segments_n file so that the backup index is corrupted.
    //Restore should fail and it should automatically rollback to the original index.
    Path restoreIndexPath = Paths.get(location).resolve("snapshot." + snapshotName);
    try (DirectoryStream<Path> stream = Files.newDirectoryStream(restoreIndexPath,
            IndexFileNames.SEGMENTS + "*")) {
        Path segmentFileName = stream.iterator().next();
        Files.delete(segmentFileName);
    }

    TestReplicationHandlerBackup.runBackupCommand(masterJetty, ReplicationHandler.CMD_RESTORE, params);

    try {
        while (!fetchRestoreStatus(baseUrl, DEFAULT_TEST_CORENAME)) {
            Thread.sleep(1000);
        }
        fail("Should have thrown an error because restore could not have been successful");
    } catch (AssertionError e) {
        //supposed to happen
    }

    BackupRestoreUtils.verifyDocs(nDocs, masterClient, DEFAULT_TEST_CORENAME);

    //make sure we can write to the index again
    nDocs = BackupRestoreUtils.indexDocs(masterClient, "collection1", docsSeed);
    BackupRestoreUtils.verifyDocs(nDocs, masterClient, DEFAULT_TEST_CORENAME);

}

From source file:ee.ria.xroad.common.SystemPropertiesLoader.java

static List<Path> getFilePaths(Path dir, String glob) throws IOException {
    try (DirectoryStream<Path> dStream = Files.newDirectoryStream(dir, glob)) {
        List<Path> filePaths = new ArrayList<>();
        dStream.forEach(filePaths::add);
        return filePaths;
    }/*w  w w . j  a  va 2 s. c  o m*/
}