Example usage for com.google.common.io LineReader readLine

List of usage examples for com.google.common.io LineReader readLine

Introduction

In this page you can find the example usage for com.google.common.io LineReader readLine.

Prototype

public String readLine() throws IOException 

Source Link

Document

Reads a line of text.

Usage

From source file:com.github.nzyuzin.candiderl.game.map.MapFactory.java

private char[][] readMapFile() throws IOException {
    File mapFile = new File(GameConstants.MAP_FILENAME);
    LineReader lineReader = new LineReader(new FileReader(mapFile));
    ArrayList<char[]> result = new ArrayList<>();
    String line;/*from   w w  w  .j  av a  2 s .c o  m*/
    while ((line = lineReader.readLine()) != null) {
        if (line.length() == 0) {
            break;
        }
        result.add(line.toCharArray());
    }
    return result.toArray(new char[result.size()][]);
}

From source file:org.apache.gobblin.metastore.nameParser.GuidDatasetUrnStateStoreNameParser.java

public GuidDatasetUrnStateStoreNameParser(FileSystem fs, Path jobStatestoreRootDir) throws IOException {
    this.fs = fs;
    this.sanitizedNameToDatasetURNMap = Maps.synchronizedBiMap(HashBiMap.<String, String>create());
    this.versionIdentifier = new Path(jobStatestoreRootDir,
            StateStoreNameVersion.V1.getDatasetUrnNameMapFile());
    if (this.fs.exists(versionIdentifier)) {
        this.version = StateStoreNameVersion.V1;
        try (InputStream in = this.fs.open(versionIdentifier)) {
            LineReader lineReader = new LineReader(new InputStreamReader(in, Charsets.UTF_8));
            String shortenName = lineReader.readLine();
            while (shortenName != null) {
                String datasetUrn = lineReader.readLine();
                this.sanitizedNameToDatasetURNMap.put(shortenName, datasetUrn);
                shortenName = lineReader.readLine();
            }/*from   w  w  w .ja v a 2s.  c  o  m*/
        }
    } else {
        this.version = StateStoreNameVersion.V0;
    }
}

From source file:org.openqa.selenium.firefox.Preferences.java

private void readPreferences(Reader reader) throws IOException {
    LineReader allLines = new LineReader(reader);
    String line = allLines.readLine();
    while (line != null) {
        Matcher matcher = PREFERENCE_PATTERN.matcher(line);
        if (matcher.matches()) {
            allPrefs.put(matcher.group(1), preferenceAsValue(matcher.group(2)));
        }/* w  w  w .  java2s.  com*/
        line = allLines.readLine();
    }
}

From source file:com.sindicetech.siren.demo.ncpr.DatatypeConverter.java

public void process() throws IOException {
    final FileReader fileReader = new FileReader(new File(INPUT_FILE));
    final LineReader reader = new LineReader(fileReader);
    try {//from w  ww .  ja v  a  2 s .  c  o  m
        JsonNode obj;
        String line;
        while ((line = reader.readLine()) != null) {
            obj = mapper.readTree(line);
            this.convertRatedOutputCurrent(obj);
            this.convertRatedOutputVoltage(obj);
            this.convertRatedOutputkW(obj);
            this.convertLatitude(obj);
            this.convertLongitude(obj);
            this.convertTetheredCable(obj);
            this.convertChargeMode(obj);
            this.convertDeviceControllerWebsite(obj);
            this.convertDeviceOwnerWebsite(obj);
            generator.writeTree(obj);
            generator.writeRaw('\n');
        }
    } finally {
        fileReader.close();
    }
}

From source file:com.google.devtools.j2objc.gen.SourceBuilder.java

/**
 * Fix line indention, based on brace count.
 *//*from   w  w  w.  j  a  v  a  2  s. c  o  m*/
public String reindent(String code) {
    try {
        // Remove indention from each line.
        StringBuffer sb = new StringBuffer();
        LineReader lr = new LineReader(new StringReader(code));
        String line = lr.readLine();
        while (line != null) {
            sb.append(line.trim());
            line = lr.readLine();
            if (line != null) {
                sb.append('\n');
            }
        }
        String strippedCode = sb.toString();

        // Now indent it again.
        int indent = indention * DEFAULT_INDENTION;
        sb.setLength(0); // reset buffer
        lr = new LineReader(new StringReader(strippedCode));
        line = lr.readLine();
        while (line != null) {
            if (line.startsWith("}")) {
                indent -= DEFAULT_INDENTION;
            }
            if (!line.startsWith("#line")) {
                sb.append(pad(indent));
            }
            sb.append(line);
            if (line.endsWith("{")) {
                indent += DEFAULT_INDENTION;
            }
            line = lr.readLine();
            if (line != null) {
                sb.append('\n');
            }
        }
        return sb.toString();
    } catch (IOException e) {
        // Should never happen with string readers.
        throw new AssertionError(e);
    }
}

From source file:controllers.GrokPatternsController.java

@BodyParser.Of(BodyParser.MultipartFormData.class)
public Result upload() {
    String path = getRefererPath();
    Http.MultipartFormData body = request().body().asMultipartFormData();
    Http.MultipartFormData.FilePart patterns = body.getFile("patterns");
    final String[] replaceParam = body.asFormUrlEncoded().get("replace");
    boolean replace = replaceParam != null;

    if (patterns != null) {

        Collection<GrokPatternSummary> grokPatterns = Lists.newArrayList();
        try {/*ww w.java 2 s  .  c  o  m*/
            File file = patterns.getFile();
            String patternsContent = Files.toString(file, StandardCharsets.UTF_8);

            final LineReader lineReader = new LineReader(new StringReader(patternsContent));

            Pattern pattern = Pattern.compile("^([A-z0-9_]+)\\s+(.*)$");
            String line;
            while ((line = lineReader.readLine()) != null) {
                Matcher m = pattern.matcher(line);
                if (m.matches()) {
                    final GrokPatternSummary grokPattern = new GrokPatternSummary();
                    grokPattern.name = m.group(1);
                    grokPattern.pattern = m.group(2);
                    grokPatterns.add(grokPattern);
                }
            }
        } catch (IOException e) {
            Logger.error("Could not parse uploaded file: " + e);
            flash("error", "The uploaded pattern file could not be parsed: does it have the right format?");
            return redirect(path);
        }
        try {
            extractorService.bulkLoadGrokPatterns(grokPatterns, replace);
            flash("success", "Grok patterns added successfully.");
        } catch (APIException | IOException e) {
            flash("error", "There was an error adding the grok patterns, please check the file format.");
        }
    } else {
        flash("error", "You didn't upload any pattern file");
    }
    return redirect(path);
}

From source file:org.opencastproject.silencedetection.ffmpeg.FFmpegSilenceDetector.java

/**
 * Create nonsilent sequences detection pipeline.
 * Parse audio stream and store all positions, where the volume level fall under the threshold.
 *
 * @param properties/*w ww . ja  v a 2 s.  c o  m*/
 * @param track source track
 */
public FFmpegSilenceDetector(Properties properties, Track track, Workspace workspace)
        throws SilenceDetectionFailedException, MediaPackageException, IOException {

    long minSilenceLength = Long.parseLong(
            properties.getProperty(SilenceDetectionProperties.SILENCE_MIN_LENGTH, DEFAULT_SILENCE_MIN_LENGTH));
    long minVoiceLength = Long.parseLong(
            properties.getProperty(SilenceDetectionProperties.VOICE_MIN_LENGTH, DEFAULT_VOICE_MIN_LENGTH));
    long preSilenceLength = Long.parseLong(
            properties.getProperty(SilenceDetectionProperties.SILENCE_PRE_LENGTH, DEFAULT_SILENCE_PRE_LENGTH));
    String thresholdDB = properties.getProperty(SilenceDetectionProperties.SILENCE_THRESHOLD_DB,
            DEFAULT_THRESHOLD_DB);

    String binary = properties.getProperty(FFMPEG_BINARY_CONFIG, FFMPEG_BINARY_DEFAULT);

    trackId = track.getIdentifier();

    /* Make sure the element can be analyzed using this analysis implementation */
    if (!track.hasAudio()) {
        logger.warn("Track {} has no audio stream to run a silece detection on", trackId);
        throw new SilenceDetectionFailedException("Element has no audio stream");
    }

    /* Make sure we are not allowed to move the beginning of a segment into the last segment */
    if (preSilenceLength > minSilenceLength) {
        logger.error("Pre silence length ({}) is configured to be greater than minimun silence length ({})",
                preSilenceLength, minSilenceLength);
        throw new SilenceDetectionFailedException("preSilenceLength > minSilenceLength");
    }

    try {
        File mediaFile = workspace.get(track.getURI());
        filePath = mediaFile.getAbsolutePath();
    } catch (NotFoundException e) {
        throw new SilenceDetectionFailedException("Error finding the media file in workspace", e);
    } catch (IOException e) {
        throw new SilenceDetectionFailedException("Error reading media file in workspace", e);
    }

    if (track.getDuration() == null) {
        throw new MediaPackageException("Track " + trackId + " does not have a duration");
    }
    logger.info("Track {} loaded, duration is {} s", filePath, track.getDuration() / 1000);

    logger.info("Starting silence detection of {}", filePath);
    String mediaPath = filePath.replaceAll(" ", "\\ ");
    DecimalFormat decimalFmt = new DecimalFormat("0.000", new DecimalFormatSymbols(Locale.US));
    String minSilenceLengthInSeconds = decimalFmt.format((double) minSilenceLength / 1000.0);
    String filter = "silencedetect=noise=" + thresholdDB + ":duration=" + minSilenceLengthInSeconds;
    String[] command = new String[] { binary, "-nostats", "-i", mediaPath, "-filter:a", filter, "-f", "null",
            "-" };
    String commandline = StringUtils.join(command, " ");

    logger.info("Running {}", commandline);

    ProcessBuilder pbuilder = new ProcessBuilder(command);
    List<String> segmentsStrings = new LinkedList<String>();
    Process process = pbuilder.start();
    BufferedReader reader = new BufferedReader(new InputStreamReader(process.getErrorStream()));
    try {
        LineReader lr = new LineReader(reader);
        String line = lr.readLine();
        while (null != line) {
            /* We want only lines from the silence detection filter */
            logger.debug("FFmpeg output: {}", line);
            if (line.startsWith("[silencedetect ")) {
                segmentsStrings.add(line);
            }
            line = lr.readLine();
        }
    } catch (IOException e) {
        logger.error("Error executing ffmpeg: {}", e.getMessage());
    } finally {
        reader.close();
    }

    /**
     * Example output:
     * [silencedetect @ 0x2968e40] silence_start: 466.486
     * [silencedetect @ 0x2968e40] silence_end: 469.322 | silence_duration: 2.83592
     */

    LinkedList<MediaSegment> segmentsTmp = new LinkedList<MediaSegment>();
    if (segmentsStrings.size() == 0) {
        /* No silence found -> Add one segment for the whole track */
        logger.info("No silence found. Adding one large segment.");
        segmentsTmp.add(new MediaSegment(0, track.getDuration()));
    } else {
        long lastSilenceEnd = 0;
        long lastSilenceStart = 0;
        Pattern patternStart = Pattern.compile("silence_start\\:\\ \\d+\\.\\d+");
        Pattern patternEnd = Pattern.compile("silence_end\\:\\ \\d+\\.\\d+");
        for (String seginfo : segmentsStrings) {
            /* Match silence ends */
            Matcher matcher = patternEnd.matcher(seginfo);
            String time = "";
            while (matcher.find()) {
                time = matcher.group().substring(13);
            }
            if (!"".equals(time)) {
                long silenceEnd = (long) (Double.parseDouble(time) * 1000);
                if (silenceEnd > lastSilenceEnd) {
                    logger.debug("Found silence end at {}", silenceEnd);
                    lastSilenceEnd = silenceEnd;
                }
                continue;
            }

            /* Match silence start -> End of segments */
            matcher = patternStart.matcher(seginfo);
            time = "";
            while (matcher.find()) {
                time = matcher.group().substring(15);
            }
            if (!"".equals(time)) {
                lastSilenceStart = (long) (Double.parseDouble(time) * 1000);
                logger.debug("Found silence start at {}", lastSilenceStart);
                if (lastSilenceStart - lastSilenceEnd > minVoiceLength) {
                    /* Found a valid segment */
                    long segmentStart = java.lang.Math.max(0, lastSilenceEnd - preSilenceLength);
                    logger.info("Adding segment from {} to {}", segmentStart, lastSilenceStart);
                    segmentsTmp.add(new MediaSegment(segmentStart, lastSilenceStart));
                }
            }
        }
        /* Add last segment if it is no silence and the segment is long enough */
        if (lastSilenceStart < lastSilenceEnd && track.getDuration() - lastSilenceEnd > minVoiceLength) {
            long segmentStart = java.lang.Math.max(0, lastSilenceEnd - preSilenceLength);
            logger.info("Adding final segment from {} to {}", segmentStart, track.getDuration());
            segmentsTmp.add(new MediaSegment(segmentStart, track.getDuration()));
        }
    }

    logger.info("Segmentation of track {} yielded {} segments", trackId, segmentsTmp.size());
    segments = segmentsTmp;

}

From source file:org.eclipse.ocl.examples.build.utilities.BackportToXtext_2_3_1.java

private void convertFile(File file) {
    try {//w ww .  j a  v a 2  s  .  c  om
        Reader reader = new FileReader(file);
        LineReader lineReader = new LineReader(reader);
        StringBuilder s = new StringBuilder();
        try {
            for (String line; (line = lineReader.readLine()) != null;) {
                s.append(line);
                s.append("\n");
            }
        } catch (IOException e) {
            LOG.error("Failed to read '" + file + "'", e);
            return;
        }
        try {
            reader.close();
        } catch (IOException e) {
            LOG.error("Failed to close '" + file + "'", e);
            return;
        }
        String sFirst = s.toString();
        String s1 = sFirst.replaceAll(
                ResourceDescriptionsProvider.class.getName().replaceAll("\\.", "\\.")
                        + "\\.PERSISTED_DESCRIPTIONS",
                "\"" + ResourceDescriptionsProvider.PERSISTED_DESCRIPTIONS + "\"");
        String s2 = s1.replaceAll(
                org.eclipse.xtext.resource.impl.BinaryGrammarResourceFactoryImpl.class.getName()
                        .replaceAll("\\.", "\\."),
                org.eclipse.ocl.xtext.base.services.BinaryGrammarResourceFactoryImpl.class.getName());
        //
        // Bug 466354
        //
        String s3 = s2.replaceAll("import org\\.eclipse\\.xtext\\.ISetupExtension;", "");
        String s4 = s3.replaceAll("ISetup, ISetupExtension \\{", "ISetup \\{");
        String s5 = s4.replaceAll("@since 2\\.9\\s*\\*/\\s*@Override", "\\*/");
        String sLast = s5;
        if (!sLast.equals(sFirst)) {
            try {
                Writer writer = new FileWriter(file);
                try {
                    writer.write(sLast);
                    writer.flush();
                } catch (IOException e) {
                    LOG.error("Failed to write '" + file + "'", e);
                    return;
                } finally {
                    writer.close();
                }
            } catch (IOException e) {
                LOG.error("Failed to re-open '" + file + "'", e);
                return;
            }
            LOG.info("Backported " + file);
        }
    } catch (FileNotFoundException e) {
        LOG.error("Failed to open '" + file + "'", e);
        return;
    }
}

From source file:uk.ac.ebi.mdk.service.query.PubChemCompoundAdapter.java

/**
 * @inheritDoc//from w  w w  .  j a v  a  2  s.com
 */
@Override
public Collection<PubChemCompoundIdentifier> searchName(String name, boolean approximate) {

    List<PubChemCompoundIdentifier> cids = new ArrayList<PubChemCompoundIdentifier>(5);
    InputStream in = null;
    try {
        String address = new URI("http", "pubchem.ncbi.nlm.nih.gov",
                "/rest/pug/compound/name/" + name + "/cids/TXT/", null).toASCIIString();
        in = new URL(address).openStream();
        LineReader lines = new LineReader(new InputStreamReader(in));
        String line;
        while ((line = lines.readLine()) != null) {
            if (numeric.matcher(line).matches()) {
                cids.add(new PubChemCompoundIdentifier(line));
            }
        }
    } catch (IOException e) {
        LOGGER.error("could not complete search for " + name, e);
    } catch (URISyntaxException e) {
        System.out.println(e);
        LOGGER.error("could not encode URI for " + name, e);
    } finally {
        try {
            if (in != null) {
                in.close();
            }
        } catch (IOException e) {
            // ignore
        }
    }
    return cids;
}

From source file:uk.ac.ebi.mdk.service.query.PubChemCompoundAdapter.java

/**
 * @inheritDoc//  w  w  w  . j  a v a2  s.  c  o  m
 */
@Override
public Collection<String> getNames(PubChemCompoundIdentifier identifier) {

    List<String> synonyms = new ArrayList<String>();

    String address = prefix + identifier.getAccession() + "/synonyms/TXT/";
    InputStream in = null;

    try {
        in = new URL(address).openStream();
        LineReader reader = new LineReader(new InputStreamReader(in));
        String line = "";
        while ((line = reader.readLine()) != null) {
            synonyms.add(line);
        }
    } catch (IOException e) {
        LOGGER.error("could not open stream for " + identifier, e);
    } finally {
        try {
            if (in != null)
                in.close();
        } catch (IOException e) {
            // ignore
        }
    }
    return synonyms;
}