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.eclipse.winery.repository.backend.filebased.FilebasedRepository.java

@Override
public <T extends TOSCAComponentId> SortedSet<T> getAllTOSCAComponentIds(Class<T> idClass) {
    SortedSet<T> res = new TreeSet<T>();
    String rootPathFragment = Util.getRootPathFragment(idClass);
    Path dir = this.repositoryRoot.resolve(rootPathFragment);
    if (!Files.exists(dir)) {
        // return empty list if no ids are available
        return res;
    }//w w w .  j av  a2  s.c o  m
    assert (Files.isDirectory(dir));

    final OnlyNonHiddenDirectories onhdf = new OnlyNonHiddenDirectories();

    // list all directories contained in this directory
    try (DirectoryStream<Path> ds = Files.newDirectoryStream(dir, onhdf)) {
        for (Path nsP : ds) {
            // the current path is the namespace
            Namespace ns = new Namespace(nsP.getFileName().toString(), true);
            try (DirectoryStream<Path> idDS = Files.newDirectoryStream(nsP, onhdf)) {
                for (Path idP : idDS) {
                    XMLId xmlId = new XMLId(idP.getFileName().toString(), true);
                    Constructor<T> constructor;
                    try {
                        constructor = idClass.getConstructor(Namespace.class, XMLId.class);
                    } catch (Exception e) {
                        FilebasedRepository.logger.debug("Internal error at determining id constructor", e);
                        // abort everything, return invalid result
                        return res;
                    }
                    T id;
                    try {
                        id = constructor.newInstance(ns, xmlId);
                    } catch (InstantiationException | IllegalAccessException | IllegalArgumentException
                            | InvocationTargetException e) {
                        FilebasedRepository.logger.debug("Internal error at invocation of id constructor", e);
                        // abort everything, return invalid result
                        return res;
                    }
                    res.add(id);
                }
            }
        }
    } catch (IOException e) {
        FilebasedRepository.logger.debug("Cannot close ds", e);
    }

    return res;
}

From source file:ch.admin.suis.msghandler.util.FileUtils.java

/**
 * Reads all files from a directory. Will throw an UnhandledException if the directory doesn't exist or an IO
 * exception occurred. Use this method instead of File.listFiles(...)
 *
 * @param directory The directory to list the files from
 * @param filter    The file filter//  w  ww . java2s . c o  m
 * @return A stream of files
 */
public static DirectoryStream<Path> listFiles(File directory, DirectoryStream.Filter<Path> filter) {
    Path folder = Paths.get(directory.getAbsolutePath());

    try {
        return Files.newDirectoryStream(folder, filter);
    } catch (IOException e) {
        throw new UnhandledException(
                new IOException("This pathname does not denote a directory, or an I/O error occured: "
                        + directory.getAbsolutePath()));
    }
}

From source file:dk.dma.ais.downloader.QueryService.java

/**
 * Returns a list of files in the folder specified by the clientId
 * @return the list of files in the folder specified by the path
 *//*  ww  w.  j  av a2  s  .c  om*/
@RequestMapping(value = "/list/{clientId:.*}", method = RequestMethod.GET, produces = "application/json;charset=UTF-8")
@ResponseBody
public List<RepoFile> listFiles(@PathVariable("clientId") String clientId) throws IOException {

    List<RepoFile> result = new ArrayList<>();
    Path folder = repoRoot.resolve(clientId);

    if (Files.exists(folder) && Files.isDirectory(folder)) {

        // Filter out directories and hidden files
        DirectoryStream.Filter<Path> filter = file -> Files.isRegularFile(file)
                && !file.getFileName().toString().startsWith(".");

        try (DirectoryStream<Path> stream = Files.newDirectoryStream(folder, filter)) {
            stream.forEach(f -> {
                RepoFile vo = new RepoFile();
                vo.setName(f.getFileName().toString());
                vo.setPath(clientId + "/" + f.getFileName().toString());
                try {
                    vo.setUpdated(new Date(Files.getLastModifiedTime(f).toMillis()));
                    vo.setSize(Files.size(f));
                } catch (Exception e) {
                    log.finer("Error reading file attribute for " + f);
                }
                vo.setComplete(!f.getFileName().toString().endsWith(DOWNLOAD_SUFFIX));
                result.add(vo);
            });
        }
    }
    Collections.sort(result);
    return result;
}

From source file:org.apache.jena.fuseki.build.FusekiConfig.java

/** Read service descriptions in the given directory */
public static List<DataAccessPoint> readConfigurationDirectory(String dir) {
    Path pDir = Paths.get(dir).normalize();
    File dirFile = pDir.toFile();
    if (!dirFile.exists()) {
        log.warn("Not found: directory for assembler files for services: '" + dir + "'");
        return Collections.emptyList();
    }// www  .ja v  a  2  s . c  om
    if (!dirFile.isDirectory()) {
        log.warn("Not a directory: '" + dir + "'");
        return Collections.emptyList();
    }
    // Files that are not hidden.
    DirectoryStream.Filter<Path> filter = (entry) -> {
        File f = entry.toFile();
        final Lang lang = filenameToLang(f.getName());
        return !f.isHidden() && f.isFile() && lang != null && isRegistered(lang);
    };

    List<DataAccessPoint> dataServiceRef = new ArrayList<>();
    try (DirectoryStream<Path> stream = Files.newDirectoryStream(pDir, filter)) {
        for (Path p : stream) {
            DatasetDescriptionMap dsDescMap = new DatasetDescriptionMap();
            String fn = IRILib.filenameToIRI(p.toString());
            log.info("Load configuration: " + fn);
            Model m = readAssemblerFile(fn);
            readConfiguration(m, dsDescMap, dataServiceRef);
        }
    } catch (IOException ex) {
        log.warn("IOException:" + ex.getMessage(), ex);
    }
    return dataServiceRef;
}

From source file:org.apache.gobblin.cluster.GobblinClusterKillTest.java

/**
 * Get a file that matches the glob pattern in the base directory
 * @param base directory to check/*from w  w w  .  ja  va  2s . co m*/
 * @param glob the glob pattern to match
 * @return a {@link File} if found, otherwise null
 */
private File getFileFromGlob(String base, String glob) {
    try (DirectoryStream<java.nio.file.Path> dirStream = Files.newDirectoryStream(Paths.get(base), glob)) {

        Iterator<java.nio.file.Path> iter = dirStream.iterator();
        if (iter.hasNext()) {
            java.nio.file.Path path = iter.next();
            return path.toFile();
        } else {
            return null;
        }
    } catch (IOException e) {
        return null;
    }
}

From source file:ezbake.common.properties.EzProperties.java

/**
 * This will glob properties files form a directory and merge them into our properties files.
 * {@see  mergeProperties(Properties, boolean)}
 *
 * @param directory the path of the directory to read from
 * @param globPattern a pattern of wild card characters for the filenames to match against
 * @param shouldOverride whether or not we should just override, if false then we will check for collisions
 *
 * @throws DuplicatePropertyException if we are checking for collisions and we actually have collisions this will
 * contain all the "keys" which collide.
 * @throws IllegalArgumentException if the directory was null or is not a directory
 * @throws IOException if there are any problems with talking to the file system or if the directory doesn't exist
 *//*from   www . java  2  s.  c  om*/
public void loadFromDirectory(Path directory, String globPattern, boolean shouldOverride)
        throws IOException, DuplicatePropertyException {
    if (directory == null || !Files.isDirectory(directory)) {
        String dir = (directory == null) ? "null" : directory.toString();
        throw new IllegalArgumentException("The directory " + dir + " is null or does not exist!");
    }

    DirectoryStream<Path> ds = null;
    try {
        ds = Files.newDirectoryStream(directory, globPattern);
        for (Path p : ds) {
            Properties pro = new Properties();
            File propFile = p.toFile();
            if (propFile.canRead()) {
                pro.load(new FileReader(propFile));
            } else {

                // This is expected to happen sometimes with our
                // configuration, but it's probably helpful to
                // know, so let's stick with info-level here.

                logger.info("I am skipping the properties file {} "
                        + "because I do not have permission to read it.", p);

            }
            mergeProperties(pro, shouldOverride);
        }
    } finally {
        if (ds != null) {
            Closeables.close(ds, true);
        }
    }
}

From source file:org.openhab.binding.fems.FEMSCore.java

/**
 * Checks if modbus connection to storage system is working
 * @param ess "dess" or "cess"// www  .j a  v a2s .c  o m
 * @return
 */
public static boolean isModbusWorking(Log log, String ess) {
    // remove old lock file
    try {
        if (Files.deleteIfExists(Paths.get("/var/lock/LCK..ttyUSB0"))) {
            log.info("Deleted old lock file");
        }
    } catch (IOException e) {
        log.error("Error deleting old lock file: " + e.getMessage());
        e.printStackTrace();
    }

    // find first matching device
    String modbusDevice = "ttyUSB*";
    String portName = "/dev/ttyUSB0"; // if no file found: use default
    try (DirectoryStream<Path> files = Files.newDirectoryStream(Paths.get("/dev"), modbusDevice)) {
        for (Path file : files) {
            portName = file.toAbsolutePath().toString();
            log.info("Set modbus portname: " + portName);
        }
    } catch (Exception e) {
        log.info("Error trying to find " + modbusDevice + ": " + e.getMessage());
        e.printStackTrace();
    }

    // default: DESS 
    int baudRate = 9600;
    int socAddress = 10143;
    int unit = 4;
    if (ess.compareTo("cess") == 0) {
        baudRate = 19200;
        socAddress = 0x1402;
        unit = 100;
    }
    SerialParameters params = new SerialParameters();
    params.setPortName(portName);
    params.setBaudRate(baudRate);
    params.setDatabits(8);
    params.setParity("None");
    params.setStopbits(1);
    params.setEncoding(Modbus.SERIAL_ENCODING_RTU);
    params.setEcho(false);
    params.setReceiveTimeout(Constants.MODBUS_TIMEOUT);
    SerialConnection serialConnection = new SerialConnection(params);
    try {
        serialConnection.open();
    } catch (Exception e) {
        log.error("Modbus connection error: " + e.getMessage());
        serialConnection.close();
        return false;
    }
    ModbusSerialTransaction modbusSerialTransaction = null;
    ReadMultipleRegistersRequest req = new ReadMultipleRegistersRequest(socAddress, 1);
    req.setUnitID(unit);
    req.setHeadless();
    modbusSerialTransaction = new ModbusSerialTransaction(serialConnection);
    modbusSerialTransaction.setRequest(req);
    modbusSerialTransaction.setRetries(1);
    try {
        modbusSerialTransaction.execute();
    } catch (ModbusException e) {
        log.error("Modbus execution error: " + e.getMessage());
        serialConnection.close();
        return false;
    }
    ModbusResponse res = modbusSerialTransaction.getResponse();
    serialConnection.close();

    if (res instanceof ReadMultipleRegistersResponse) {
        return true;
    } else if (res instanceof ExceptionResponse) {
        log.error("Modbus read error: " + ((ExceptionResponse) res).getExceptionCode());
    } else {
        log.error("Modbus read undefined response");
    }
    return false;
}

From source file:org.eclipse.winery.repository.backend.filebased.FilebasedRepository.java

@Override
public SortedSet<RepositoryFileReference> getContainedFiles(GenericId id) {
    Path dir = this.id2AbsolutePath(id);
    SortedSet<RepositoryFileReference> res = new TreeSet<RepositoryFileReference>();
    if (!Files.exists(dir)) {
        return res;
    }/*from ww w.  j  a  v a 2  s .co  m*/
    assert (Files.isDirectory(dir));
    // list all directories contained in this directory
    try (DirectoryStream<Path> ds = Files.newDirectoryStream(dir, new OnlyNonHiddenFiles())) {
        for (Path p : ds) {
            RepositoryFileReference ref = new RepositoryFileReference(id, p.getFileName().toString());
            res.add(ref);
        }
    } catch (IOException e) {
        FilebasedRepository.logger.debug("Cannot close ds", e);
    }
    return res;
}

From source file:com.puppycrawl.tools.checkstyle.AllChecksTest.java

/**
 * Gets xdocs documentation file paths./* w w w.j a  v a 2 s. co  m*/
 * @param xdocsDirectoryPath xdocs directory path.
 * @return a list of xdocs file paths.
 * @throws IOException if an I/O error occurs.
 */
private static Set<Path> getXdocsFilePaths(String xdocsDirectoryPath) throws IOException {

    final Path directory = Paths.get(xdocsDirectoryPath);
    final Set<Path> xdocs = new HashSet<>();
    try (DirectoryStream<Path> stream = Files.newDirectoryStream(directory, "*.xml")) {
        for (Path entry : stream) {
            final String fileName = entry.getFileName().toString();
            if (fileName.startsWith("config_")) {
                xdocs.add(entry);
            }
        }
        return xdocs;
    }
}

From source file:gov.usgs.cida.coastalhazards.rest.data.util.MetadataUtilTest.java

@Test
public void testFilePathBuilder() throws FactoryException, IOException {
    final String TEMP_FILE_SUBDIRECTORY_PATH = "cch-temp";
    //java.nio.file.Path TEMP_FILE_SUBDIRECTORY =Files.createDirectory(Paths.get(TEMP_FILE_SUBDIRECTORY_PATH));
    //  TEMP_FILE_SUBDIRECTORY = Files.createDirectory(Paths.get(TEMP_FILE_SUBDIRECTORY_PATH));
    String tempPath = FileUtils.getTempDirectoryPath() + TEMP_FILE_SUBDIRECTORY_PATH;
    java.nio.file.Path TEMP_FILE_SUBDIRECTORY = Paths.get(tempPath);

    String fileDir = TEMP_FILE_SUBDIRECTORY.toFile().toString();
    System.out.println("getTempFileUtils: " + fileDir);

    String tempDir = System.getProperty("java.io.tmpdir") + "cch-temp";
    System.out.println("get System temp file: " + tempDir);

    java.nio.file.Path path = Paths.get(System.getProperty("java.io.tmpdir"));
    try (DirectoryStream<java.nio.file.Path> newDirectoryStream = Files.newDirectoryStream(path,
            TEMP_FILE_SUBDIRECTORY_PATH + "*")) {
        for (final java.nio.file.Path newDirectoryStreamItem : newDirectoryStream) {
            System.out.println("DIR that would be DELETED: " + newDirectoryStreamItem.getFileName());
            // Files.delete(newDirectoryStreamItem);
        }/*w  ww  .  j av  a 2  s  .  c om*/
    } catch (final Exception e) { // empty
        System.out.println(e);
    }

    assertEquals(fileDir, tempDir);
}