Example usage for com.google.common.io CharSource openStream

List of usage examples for com.google.common.io CharSource openStream

Introduction

In this page you can find the example usage for com.google.common.io CharSource openStream.

Prototype

public abstract Reader openStream() throws IOException;

Source Link

Document

Opens a new Reader for reading from this source.

Usage

From source file:com.google.javascript.jscomp.WhitelistWarningsGuard.java

/**
 * Loads legacy warnings list from the file.
 * @return The lines of the file.//from w w  w. j a va 2s.c o m
 */
protected static Set<String> loadWhitelistedJsWarnings(CharSource supplier) {
    try {
        return loadWhitelistedJsWarnings(supplier.openStream());
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}

From source file:org.glowroot.ui.ChunkSource.java

static ChunkSource create(final CharSource charSource) {
    return new ChunkSource() {
        @Override//from   w  w w  .j a  v  a 2 s . c o  m
        public ChunkCopier getCopier(Writer writer) throws IOException {
            return new ReaderChunkCopier(charSource.openStream(), writer);
        }
    };
}

From source file:com.opengamma.strata.examples.marketdata.credit.markit.MarkitSingleNameCreditCurveDataParser.java

/**
 * Parses the specified sources.//from   www  . j  ava 2s .  c  om
 * 
 * @param builder  the market data builder that the resulting curve and recovery rate items should be loaded into
 * @param curveSource  the source of curve data to parse
 * @param staticDataSource  the source of static data to parse
 */
public static void parse(ImmutableMarketDataBuilder builder, CharSource curveSource,
        CharSource staticDataSource) {

    Map<MarkitRedCode, CdsConvention> conventions = parseStaticData(staticDataSource);
    try (Scanner scanner = new Scanner(curveSource.openStream())) {
        while (scanner.hasNextLine()) {

            String line = scanner.nextLine();
            // skip over header rows
            if (line.startsWith("V5 CDS Composites by Convention") || line.trim().isEmpty()
                    || line.startsWith("\"Date\",")) {
                continue;
            }
            String[] columns = line.split(",");
            for (int i = 0; i < columns.length; i++) {
                // get rid of quotes and trim the string
                columns[i] = columns[i].replaceFirst("^\"", "").replaceFirst("\"$", "").trim();
            }

            LocalDate valuationDate = LocalDate.parse(columns[DATE], DATE_FORMAT);

            MarkitRedCode redCode = MarkitRedCode.of(columns[RED_CODE]);
            SeniorityLevel seniorityLevel = MarkitSeniorityLevel.valueOf(columns[TIER]).translate();
            Currency currency = Currency.parse(columns[CURRENCY]);
            RestructuringClause restructuringClause = MarkitRestructuringClause.valueOf(columns[DOCS_CLAUSE])
                    .translate();

            double recoveryRate = parseRate(columns[RECOVERY]);

            SingleNameReferenceInformation referenceInformation = SingleNameReferenceInformation
                    .of(redCode.toStandardId(), seniorityLevel, currency, restructuringClause);

            IsdaSingleNameCreditCurveInputsId curveId = IsdaSingleNameCreditCurveInputsId
                    .of(referenceInformation);

            List<Period> periodsList = Lists.newArrayList();
            List<Double> ratesList = Lists.newArrayList();
            for (int i = 0; i < TENORS.size(); i++) {
                String rateString = columns[FIRST_SPREAD_COLUMN + i];
                if (rateString.isEmpty()) {
                    // no data at this point
                    continue;
                }
                periodsList.add(TENORS.get(i).getPeriod());
                ratesList.add(parseRate(rateString));
            }

            String creditCurveName = curveId.toString();

            CdsConvention cdsConvention = conventions.get(redCode);

            Period[] periods = periodsList.stream().toArray(Period[]::new);
            LocalDate[] endDates = Lists.newArrayList(periods).stream()
                    .map(p -> cdsConvention.calculateUnadjustedMaturityDateFromValuationDate(valuationDate, p))
                    .toArray(LocalDate[]::new);

            double[] rates = ratesList.stream().mapToDouble(s -> s).toArray();
            double unitScalingFactor = 1d; // for single name, we don't do any scaling (no index factor)

            IsdaCreditCurveInputs curveInputs = IsdaCreditCurveInputs.of(CurveName.of(creditCurveName), periods,
                    endDates, rates, cdsConvention, unitScalingFactor);

            builder.addValue(curveId, curveInputs);

            IsdaSingleNameRecoveryRateId recoveryRateId = IsdaSingleNameRecoveryRateId.of(referenceInformation);
            CdsRecoveryRate cdsRecoveryRate = CdsRecoveryRate.of(recoveryRate);

            builder.addValue(recoveryRateId, cdsRecoveryRate);

        }
    } catch (IOException ex) {
        throw new UncheckedIOException(ex);
    }
}

From source file:org.onosproject.odtn.utils.YangToolUtil.java

/**
 * Converts XML source into XML Document.
 *
 * @param xmlInput to convert/*  ww w.  ja  va  2s  .  co  m*/
 * @return Document
 */
public static Document toDocument(CharSource xmlInput) {
    try {
        return DocumentBuilderFactory.newInstance().newDocumentBuilder()
                .parse(new InputSource(xmlInput.openStream()));
    } catch (ParserConfigurationException | SAXException | IOException e) {
        log.error("Exception thrown", e);
        return null;
    }
}

From source file:com.google.template.soy.SoyUtils.java

/**
 * Parses a globals file in the format created by {@link #generateCompileTimeGlobalsFile} into a
 * map from global name to primitive value.
 * @param inputSource A source that returns a reader for the globals file.
 * @return The parsed globals map.//from  ww w.j  a  v a2s  .c  om
 * @throws IOException If an error occurs while reading the globals file.
 * @throws java.lang.IllegalStateException If the globals file is not in the correct format.
 */
public static ImmutableMap<String, PrimitiveData> parseCompileTimeGlobals(CharSource inputSource)
        throws IOException {
    ImmutableMap.Builder<String, PrimitiveData> compileTimeGlobalsBuilder = ImmutableMap.builder();
    ErrorReporter errorReporter = ExplodingErrorReporter.get();

    try (BufferedReader reader = new BufferedReader(inputSource.openStream())) {
        int lineNum = 1;
        for (String line = reader.readLine(); line != null; line = reader.readLine(), ++lineNum) {

            if (line.startsWith("//") || line.trim().length() == 0) {
                continue;
            }

            SourceLocation sourceLocation = new SourceLocation("globals", lineNum, 1, lineNum, 1);

            Matcher matcher = COMPILE_TIME_GLOBAL_LINE.matcher(line);
            if (!matcher.matches()) {
                errorReporter.report(sourceLocation, CompileTimeGlobalsFileErrors.INVALID_FORMAT, line);
                continue;
            }
            String name = matcher.group(1);
            String valueText = matcher.group(2).trim();

            ExprNode valueExpr = new ExpressionParser(valueText, sourceLocation, errorReporter)
                    .parseExpression();

            // Handle negative numbers as a special case.
            // TODO: Consider changing parser to actually parse negative numbers as primitives.
            if (valueExpr instanceof NegativeOpNode) {
                ExprNode childExpr = ((NegativeOpNode) valueExpr).getChild(0);
                if (childExpr instanceof IntegerNode) {
                    compileTimeGlobalsBuilder.put(name,
                            IntegerData.forValue(-((IntegerNode) childExpr).getValue()));
                    continue;
                } else if (childExpr instanceof FloatNode) {
                    compileTimeGlobalsBuilder.put(name,
                            FloatData.forValue(-((FloatNode) childExpr).getValue()));
                    continue;
                }
            }

            // Record error for non-primitives.
            // TODO: Consider allowing non-primitives (e.g. list/map literals).
            if (!(valueExpr instanceof PrimitiveNode)) {
                if (valueExpr instanceof GlobalNode || valueExpr instanceof VarRefNode) {
                    errorReporter.report(sourceLocation, CompileTimeGlobalsFileErrors.INVALID_VALUE, line);
                } else {
                    errorReporter.report(sourceLocation, CompileTimeGlobalsFileErrors.NON_PRIMITIVE_VALUE,
                            line);
                }
                continue;
            }

            // Default case.
            compileTimeGlobalsBuilder.put(name,
                    InternalValueUtils.convertPrimitiveExprToData((PrimitiveNode) valueExpr));
        }
    }
    return compileTimeGlobalsBuilder.build();
}

From source file:org.apache.aurora.common.args.apt.Configuration.java

private static Configuration load(int nextIndex, List<URL> configs) throws ConfigurationException, IOException {
    CharSource input = CharSource.concat(Iterables.transform(configs, URL_TO_SOURCE));
    try (Reader reader = input.openStream()) {
        return CharStreams.readLines(reader, new ConfigurationParser(nextIndex));
    }//ww  w  .  ja va 2 s.  co  m
}

From source file:to.lean.tools.gmail.importer.gmail.Authorizer.java

private GoogleClientSecrets loadGoogleClientSecrets(JsonFactory jsonFactory) throws IOException {
    URL url = Resources.getResource("client_secret.json");
    CharSource inputSupplier = Resources.asCharSource(url, Charsets.UTF_8);
    return GoogleClientSecrets.load(jsonFactory, inputSupplier.openStream());
}

From source file:org.glowroot.local.ui.TraceExportHttpService.java

private ChunkedInput<HttpContent> getExportChunkedInput(TraceExport export) throws IOException {
    CharSource charSource = render(export);
    return ChunkedInputs.fromReaderToZipFileDownload(charSource.openStream(), getFilename(export.trace()));
}

From source file:com.googlecode.blaisemath.svg.SVGTool.java

private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton3ActionPerformed
    if (pathTB.isSelected()) {
        gsvg.setElement(new SVGPath(text.getText()));
    } else {//w  w  w.  j a  v a 2 s. co  m
        try {
            String svg = text.getText();
            CharSource cs = CharSource.wrap(svg);
            SVGRoot root = SVGRoot.load(cs.openStream());
            gsvg.setElement(root);
        } catch (IOException ex) {
            Logger.getLogger(SVGTool.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
}

From source file:org.onlab.util.XmlString.java

private String prettyPrintXml(CharSource inputXml) {
    try {/*from w  w w .  ja va 2  s  . co m*/
        Document document;
        boolean wasFragment = false;

        DocumentBuilder docBuilder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
        // do not print error to stderr
        docBuilder.setErrorHandler(new DefaultHandler());

        try {
            document = docBuilder.parse(new InputSource(inputXml.openStream()));
        } catch (SAXException e) {
            log.debug("will retry assuming input is XML fragment", e);
            // attempt to parse XML fragments, adding virtual root
            try {
                document = docBuilder.parse(new InputSource(
                        CharSource.concat(CharSource.wrap("<vroot>"), inputXml, CharSource.wrap("</vroot>"))
                                .openStream()));
                wasFragment = true;
            } catch (SAXException e1) {
                log.debug("SAXException after retry", e1);
                // Probably wasn't fragment issue, throwing original
                throw e;
            }
        }

        document.normalize();

        XPath xPath = XPathFactory.newInstance().newXPath();
        NodeList nodeList = (NodeList) xPath.evaluate("//text()[normalize-space()='']", document,
                XPathConstants.NODESET);

        for (int i = 0; i < nodeList.getLength(); ++i) {
            Node node = nodeList.item(i);
            node.getParentNode().removeChild(node);
        }

        // Setup pretty print options
        Transformer t = TransformerFactory.newInstance().newTransformer();
        t.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
        t.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
        t.setOutputProperty(OutputKeys.INDENT, "yes");
        t.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");

        // Return pretty print xml string
        StringWriter strWriter = new StringWriter();
        if (wasFragment) {
            // print everything but virtual root node added
            NodeList children = document.getDocumentElement().getChildNodes();
            for (int i = 0; i < children.getLength(); ++i) {
                t.transform(new DOMSource(children.item(i)), new StreamResult(strWriter));
            }
        } else {
            t.transform(new DOMSource(document), new StreamResult(strWriter));
        }
        return strWriter.toString();
    } catch (Exception e) {
        log.warn("Pretty printing failed", e);
        try {
            String rawInput = inputXml.read();
            log.debug("  failed input: \n{}", rawInput);
            return rawInput;
        } catch (IOException e1) {
            log.error("Failed to read from input", e1);
            return inputXml.toString();
        }
    }
}