Example usage for java.nio.file Files newBufferedReader

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

Introduction

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

Prototype

public static BufferedReader newBufferedReader(Path path, Charset cs) throws IOException 

Source Link

Document

Opens a file for reading, returning a BufferedReader that may be used to read text from the file in an efficient manner.

Usage

From source file:com.netflix.metacat.usermetadata.mysql.MysqlUserMetadataService.java

private void initProperties() throws Exception {
    final String configLocation = System.getProperty(METACAT_USERMETADATA_CONFIG_LOCATION,
            "usermetadata.properties");
    final URL url = Thread.currentThread().getContextClassLoader().getResource(configLocation);
    final Path filePath;
    if (url != null) {
        filePath = Paths.get(url.toURI());
    } else {/*ww  w . ja va 2s .  c o  m*/
        filePath = FileSystems.getDefault().getPath(configLocation);
    }
    Preconditions.checkState(filePath != null, "Unable to read from user metadata config file '%s'",
            configLocation);

    connectionProperties = new Properties();
    try (Reader reader = Files.newBufferedReader(filePath, Charsets.UTF_8)) {
        connectionProperties.load(reader);
    }
}

From source file:br.com.blackhubos.eventozero.util.Framework.java

public static java.util.Vector<String> parseLines(final Path path, final Charset cs) throws IOException {
    try (BufferedReader reader = Files.newBufferedReader(path, cs)) {
        final java.util.Vector<String> result = new java.util.Vector<String>();
        for (; true;) {
            final String line = reader.readLine();
            if (line == null) {
                break;
            }/*w  w  w  .  ja  va2s . co m*/
            if (!Framework.isCommentary(line)) {
                result.add(line);
            }
        }
        return result;
    }
}

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

/**
 * Load the specified JavaScript library into the global scope of the Nashorn engine
 * @param lib   Path to the JavaScript library.
 *//* w w w. j  av  a 2s  .co m*/
protected boolean loadScriptLibrary(Path lib) {
    try (Reader r = Files.newBufferedReader(lib, Charset.forName("utf-8"))) {
        Nashorn.eval(r, Nashorn.getBindings(ScriptContext.GLOBAL_SCOPE));
    } catch (Exception e) {
        Logger.error("Unable to load JavaScript library " + lib.toAbsolutePath().toString(), e);
        return false;
    }
    return true;
}

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

/**
 * This is where Nashorn compiles the script, evals it into global scope to get an endpoint, and invokes the setup method of the endpoint.
 * @param rootPath   The root script directory path to assist in building a relative uri type path to discovered scripts.
 * @param f   The javascript file.//  www.j  a  v  a 2  s .c  om
 * @param uriKey   A "pass-back-by-reference" construct to w
 * @return
 */
private static void MakeJavaScriptEndPointDescriptor(Path rootPath, Path f,
        HierarchicalConfiguration scriptConfig, EndpointSetupCompleteCallback cb) {
    CompiledScript compiledScript;
    try (Reader r = Files.newBufferedReader(f, Charset.forName("utf-8"))) {
        compiledScript = ((Compilable) Nashorn).compile(r);
    } catch (Throwable e) {
        cb.setupFailed(f, "Unable to load and compile script at " + f.toAbsolutePath().toString(), e);
        return;
    }
    ScriptObjectMirror obj;
    try {
        obj = (ScriptObjectMirror) compiledScript.eval(Nashorn.getBindings(ScriptContext.GLOBAL_SCOPE));
    } catch (Throwable e) {
        cb.setupFailed(f, "Unable to eval the script at " + f.toAbsolutePath().toString(), e);
        return;
    }
    assert f.startsWith(rootPath);
    String uriKey = FileToUriKey(rootPath, f);
    final JavaScriptEndPoint retVal = new JavaScriptEndPoint(uriKey, obj);

    try {
        if (obj.hasMember("setup")) {
            obj.callMember("setup", uriKey, scriptConfig, ScriptHelper.ScriptLogger,
                    new SetupCompleteCallback() {
                        @Override
                        public void setupComplete() {
                            cb.setupComplete(retVal);
                        }

                        @Override
                        public void setupFailed(String msg) {
                            cb.setupFailed(f, msg, null);
                        }
                    });
        } else {
            cb.setupComplete(retVal);
        }
    } catch (Throwable e) {
        cb.setupFailed(f, "The script at " + f.toAbsolutePath().toString()
                + " did not expose the expected 'setup' method", e);
        return;
    }
}

From source file:org.tinymediamanager.core.entities.MediaFile.java

License:asdf

private long getMediaInfoSnapshotFromISO() {
    // check if we have a snapshot xml
    Path xmlFile = Paths.get(this.path, this.filename.replaceFirst("\\.iso$", "-mediainfo.xml"));
    if (Files.exists(xmlFile)) {
        try {/*  w  w  w  .java2 s  .c o m*/
            LOGGER.info("ISO: try to parse " + xmlFile);

            JAXBContext context = JAXBContext.newInstance(MediaInfoXMLParser.class);
            Unmarshaller um = context.createUnmarshaller();
            MediaInfoXMLParser xml = new MediaInfoXMLParser();

            Reader in = Files.newBufferedReader(xmlFile, StandardCharsets.UTF_8);
            xml = (MediaInfoXMLParser) um.unmarshal(in);
            in.close();
            xml.snapshot();

            // get snapshot from biggest file
            setMiSnapshot(xml.getBiggestFile().snapshot);
            setDuration(xml.getDuration()); // accumulated duration
            return xml.getFilesize();
        } catch (Exception e) {
            LOGGER.warn("ISO: Unable to parse " + xmlFile, e);
        }
    }

    if (miSnapshot == null) {
        int BUFFER_SIZE = 64 * 1024;
        Iso9660FileSystem image = null;
        try {
            LOGGER.trace("ISO: Open");
            image = new Iso9660FileSystem(getFileAsPath().toFile(), true);
            int dur = 0;
            long siz = 0L; // accumulated filesize
            long biggest = 0L;

            for (Iso9660FileEntry entry : image) {
                LOGGER.trace("ISO: got entry " + entry.getName() + " size:" + entry.getSize());
                siz += entry.getSize();

                if (entry.getSize() <= 5000) { // small files and "." entries
                    continue;
                }

                MediaFile mf = new MediaFile(Paths.get(getFileAsPath().toString(), entry.getPath())); // set ISO as MF path
                // mf.setMediaInfo(fileMI); // we need set the inner MI
                if (mf.getType() == MediaFileType.VIDEO && mf.isDiscFile()) { // would not count video_ts.bup for ex (and not .dat files or other types)
                    mf.setFilesize(entry.getSize());

                    MediaInfo fileMI = new MediaInfo();
                    try {
                        // mediaInfo.option("File_IsSeekable", "0");
                        byte[] From_Buffer = new byte[BUFFER_SIZE];
                        int From_Buffer_Size; // The size of the read file buffer

                        // Preparing to fill MediaInfo with a buffer
                        fileMI.openBufferInit(entry.getSize(), 0);

                        long pos = 0L;
                        // The parsing loop
                        do {
                            // Reading data somewhere, do what you want for this.
                            From_Buffer_Size = image.readBytes(entry, pos, From_Buffer, 0, BUFFER_SIZE);
                            pos += From_Buffer_Size; // add bytes read to file position

                            // Sending the buffer to MediaInfo
                            int Result = fileMI.openBufferContinue(From_Buffer, From_Buffer_Size);
                            if ((Result & 8) == 8) { // Status.Finalized
                                break;
                            }

                            // Testing if MediaInfo request to go elsewhere
                            if (fileMI.openBufferContinueGoToGet() != -1) {
                                pos = fileMI.openBufferContinueGoToGet();
                                LOGGER.trace("ISO: Seek to " + pos);
                                // From_Buffer_Size = image.readBytes(entry, newPos, From_Buffer, 0, BUFFER_SIZE);
                                // pos = newPos + From_Buffer_Size; // add bytes read to file position
                                fileMI.openBufferInit(entry.getSize(), pos); // Informing MediaInfo we have seek
                            }

                        } while (From_Buffer_Size > 0);

                        LOGGER.trace("ISO: finalize");
                        // Finalizing
                        fileMI.openBufferFinalize(); // This is the end of the stream, MediaInfo must finish some work
                        Map<StreamKind, List<Map<String, String>>> tempSnapshot = fileMI.snapshot();
                        fileMI.close();

                        mf.setMiSnapshot(tempSnapshot); // set ours to MI for standard gathering
                        mf.gatherMediaInformation(); // normal gather from snapshots

                        // set ISO snapshot ONCE from biggest video file, so we copy all the resolutions & co
                        if (entry.getSize() > biggest) {
                            biggest = entry.getSize();
                            miSnapshot = tempSnapshot;
                        }

                        // accumulate durations from every MF
                        dur += mf.getDuration();
                        LOGGER.trace("ISO: file duration:" + mf.getDurationHHMMSS() + "  accumulated min:"
                                + dur / 60);
                    }
                    // sometimes also an error is thrown
                    catch (Exception | Error e) {
                        LOGGER.error("Mediainfo could not open file STREAM", e);
                        fileMI.close();
                    }
                } // end VIDEO
            } // end entry
            setDuration(dur); // set it here, and ignore duration parsing for ISO in gatherMI method...
            LOGGER.trace("ISO: final duration:" + getDurationHHMMSS());
            image.close();
            return siz;
        } catch (Exception e) {
            LOGGER.error("Mediainfo could not open STREAM - trying fallback", e);
            try {
                if (image != null) {
                    image.close();
                    image = null;
                }
            } catch (IOException e1) {
                LOGGER.warn("Uh-oh. Cannot close disc image :(", e);
            }
            closeMediaInfo();
            getMediaInfoSnapshot();
        }
    }
    return 0;
}

From source file:org.structr.web.maintenance.DeployCommand.java

private List<Map<String, Object>> readConfigList(final Path conf) {

    try (final Reader reader = Files.newBufferedReader(conf, Charset.forName("utf-8"))) {

        return getGson().fromJson(reader, List.class);

    } catch (IOException ioex) {
        logger.warn("", ioex);
    }//from w  ww .j  a v a 2s .c om

    return Collections.emptyList();
}

From source file:eus.ixa.ixa.pipe.convert.AbsaSemEval.java

public static void getYelpText(String fileName) throws IOException {
    JSONParser parser = new JSONParser();
    Path filePath = Paths.get(fileName);
    BufferedReader breader = new BufferedReader(Files.newBufferedReader(filePath, StandardCharsets.UTF_8));
    String line;//  ww w  .j  a v a 2  s .  co  m
    while ((line = breader.readLine()) != null) {
        try {
            Object obj = parser.parse(line);
            JSONObject jsonObject = (JSONObject) obj;
            String text = (String) jsonObject.get("text");
            System.out.println(text);
        } catch (ParseException e) {
            e.printStackTrace();
        }
    }
    breader.close();
}

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

/**
 * Read a SPARQL query from a file into a String and create a Query object
 * from that. If a resource was specified all occurrences of $URI$
 * placeholder in the read query will be replaced with the URI of the
 * resource. If a model URI is specified, GRAPH lines will be added to the
 * query using the placeholders $S_MOD$ and $E_MOD$.
 *
 * @param pFileName File name of the SPARQL file. The file must exist and be
 *            located in 'res/sparql'/*from www .  j a v a 2s.  co  m*/
 * @param pRes Optional resource object, will be used to replace the $URI$
 *            placeholder. Can be set to null if not required.
 * @param pMod Optional model URI, will be used to add GRAPH lines to the
 *            query. If set to null the query will be executed on the
 *            default model of the dataset.
 * @return A Query object containing the read SPARQL query, null if the
 *         input file cannot be read
 */
private Query readSPARQL(String pFileName, Resource pRes, String pMod) {
    try {
        // Open the SPARQL file for reading
        Path inFile = Paths.get("res/sparql", pFileName);
        BufferedReader br = Files.newBufferedReader(inFile, StandardCharsets.UTF_8);

        // Read all lines and concatenate them using a StringBuilder
        StringBuilder rv = new StringBuilder();
        String line = br.readLine();
        while (line != null) {
            rv.append(line);
            rv.append(System.lineSeparator());

            line = br.readLine();
        }
        br.close();

        // Get the String from the StringBuilder and, if required, replace
        // the $URI$ placeholder
        String rvStr = rv.toString();
        if (pRes != null) {
            rvStr = rvStr.replaceAll("\\$URI\\$", pRes.getURI());
        }

        if (pMod != null && !pMod.isEmpty()) {
            StringBuilder graphLine = new StringBuilder("GRAPH <");
            graphLine.append(pMod);
            graphLine.append("> {");

            rvStr = rvStr.replaceAll("\\$S_MOD\\$", graphLine.toString()).replaceAll("\\$E_MOD\\$", "}");
        } else {
            rvStr = rvStr.replaceAll("\\$S_MOD\\$", "").replaceAll("\\$E_MOD\\$", "");
        }

        // Build a Query object and return it
        return QueryFactory.create(rvStr);
    } catch (IOException ex) {
        StringBuilder sb = new StringBuilder("Caught: [");
        sb.append(ex.getClass().getSimpleName());
        sb.append("] ");
        sb.append(ex.getMessage());
        log.error(sb.toString());

        if (log.isDebugEnabled()) {
            for (StackTraceElement ste : ex.getStackTrace()) {
                log.debug(ste.toString());
            }
        }

        return null;
    }
}