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

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

Introduction

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

Prototype

public static CharSource wrap(CharSequence charSequence) 

Source Link

Document

Returns a view of the given character sequence as a CharSource .

Usage

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  ww.  j ava2  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:com.opengamma.strata.collect.io.ArrayByteSource.java

/**
 * Returns a {@code CharSource} for the same bytes, converted to UTF-8 using a Byte-Order Mark if available.
 * //ww w. j a v a  2 s  .co m
 * @return the equivalent {@code CharSource}
 */
public CharSource asCharSourceUtf8UsingBom() {
    return CharSource.wrap(readUtf8UsingBom());
}

From source file:com.gradleware.tooling.toolingutils.distribution.PublishedGradleVersions.java

private static void storeCacheVersionFile(String json) {
    //noinspection ResultOfMethodCallIgnored
    CACHE_FILE.getParentFile().mkdirs();

    try {//from   w w w .j  a va2s . c o m
        CharSource.wrap(json).copyTo(Files.asCharSink(CACHE_FILE, Charsets.UTF_8));
    } catch (IOException e) {
        LOG.error("Cannot write Gradle version information cache file.", e);
        // do not throw an exception if cache file cannot be written to be more robust against file system problems
    }
}

From source file:dagger.internal.codegen.writer.JavaWriter.java

public void file(Filer filer, CharSequence name, Iterable<? extends Element> originatingElements)
        throws IOException {
    final JavaFileObject sourceFile = filer.createSourceFile(name,
            Iterables.toArray(originatingElements, Element.class));
    try {/*ww w  .  ja  va  2  s  .co  m*/
        new Formatter().formatSource(CharSource.wrap(write(new StringBuilder())), new CharSink() {
            @Override
            public Writer openStream() throws IOException {
                return sourceFile.openWriter();
            }
        });
    } catch (FormatterException e) {
        throw new IllegalStateException("The writer produced code that could not be parsed by the formatter",
                e);
    }
}

From source file:org.onosproject.odtn.cli.impl.OdtnManualTestCommand.java

void doTheMagic(List<CharSequence> nodes) {

    Document doc;/*from w ww  .  j  a v  a  2 s  .  com*/
    try {
        doc = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument();
    } catch (ParserConfigurationException e) {
        printlog("Unexpected error", e);
        throw new IllegalStateException(e);
    }

    // netconf rpc boilerplate part without message-id
    Element rpc = doc.createElementNS("urn:ietf:params:xml:ns:netconf:base:1.0", "rpc");
    doc.appendChild(rpc);
    Element editConfig = doc.createElement("edit-config");
    rpc.appendChild(editConfig);
    Element target = doc.createElement("target");
    editConfig.appendChild(target);
    target.appendChild(doc.createElement("running"));

    Element config = doc.createElement("config");
    config.setAttributeNS("http://www.w3.org/2000/xmlns/", "xmlns:xc",
            "urn:ietf:params:xml:ns:netconf:base:1.0");
    editConfig.appendChild(config);

    for (CharSequence node : nodes) {
        Document ldoc = toDocument(CharSource.wrap(node));
        Element cfgRoot = ldoc.getDocumentElement();

        // is everything as merge, ok?
        cfgRoot.setAttribute("xc:operation", "merge");

        // move (or copy) node to another Document
        config.appendChild(
                Optional.ofNullable(doc.adoptNode(cfgRoot)).orElseGet(() -> doc.importNode(cfgRoot, true)));

        // don't have good use for JSON for now
        //JsonNode json = toJsonNode(toJsonCompositeStream(toCompositeData(toResourceData(resourceId, node))));
        //printlog("JSON:\n{}", toCharSequence(json));
    }

    printlog("XML:\n{}", XmlString.prettifyXml(toCharSequence(doc)));

    // TODO if deviceId is given send it out to the device
    if (uri != null) {
        DeviceId deviceId = DeviceId.deviceId(uri);
        NetconfController ctr = get(NetconfController.class);
        Optional.ofNullable(ctr.getNetconfDevice(deviceId)).map(NetconfDevice::getSession)
                .ifPresent(session -> {
                    try {
                        session.rpc(toCharSequence(doc, false).toString()).join();
                    } catch (NetconfException e) {
                        log.error("Exception thrown", e);
                    }
                });
    }
}

From source file:org.apache.druid.cli.validate.DruidJsonValidator.java

@Override
public void run() {
    File file = new File(jsonFile);
    if (!file.exists()) {
        LOG.info("File[%s] does not exist.%n", file);
    }/* w w w .j a v a 2  s  . c  om*/

    final Injector injector = makeInjector();
    final ObjectMapper jsonMapper = injector.getInstance(ObjectMapper.class);

    registerModules(jsonMapper,
            Iterables.concat(
                    Initialization.getFromExtensions(injector.getInstance(ExtensionsConfig.class),
                            DruidModule.class),
                    Arrays.asList(new FirehoseModule(), new IndexingHadoopModule(),
                            new IndexingServiceFirehoseModule(), new LocalDataStorageDruidModule())));

    final ClassLoader loader;
    if (Thread.currentThread().getContextClassLoader() != null) {
        loader = Thread.currentThread().getContextClassLoader();
    } else {
        loader = DruidJsonValidator.class.getClassLoader();
    }

    if (toLogger) {
        logWriter = new NullWriter() {
            private final Logger logger = new Logger(DruidJsonValidator.class);

            @Override
            public void write(char[] cbuf, int off, int len) {
                logger.info(new String(cbuf, off, len));
            }
        };
    }

    try {
        if ("query".equalsIgnoreCase(type)) {
            jsonMapper.readValue(file, Query.class);
        } else if ("hadoopConfig".equalsIgnoreCase(type)) {
            jsonMapper.readValue(file, HadoopDruidIndexerConfig.class);
        } else if ("task".equalsIgnoreCase(type)) {
            jsonMapper.readValue(file, Task.class);
        } else if ("parse".equalsIgnoreCase(type)) {
            final StringInputRowParser parser;
            if (file.isFile()) {
                logWriter.write("loading parse spec from file '" + file + "'");
                parser = jsonMapper.readValue(file, StringInputRowParser.class);
            } else if (loader.getResource(jsonFile) != null) {
                logWriter.write("loading parse spec from resource '" + jsonFile + "'");
                parser = jsonMapper.readValue(loader.getResource(jsonFile), StringInputRowParser.class);
            } else {
                logWriter.write("cannot find proper spec from 'file'.. regarding it as a json spec");
                parser = jsonMapper.readValue(jsonFile, StringInputRowParser.class);
            }
            parser.initializeParser();
            if (resource != null) {
                final CharSource source;
                if (new File(resource).isFile()) {
                    logWriter.write("loading data from file '" + resource + "'");
                    source = Resources.asByteSource(new File(resource).toURI().toURL())
                            .asCharSource(Charset.forName(parser.getEncoding()));
                } else if (loader.getResource(resource) != null) {
                    logWriter.write("loading data from resource '" + resource + "'");
                    source = Resources.asByteSource(loader.getResource(resource))
                            .asCharSource(Charset.forName(parser.getEncoding()));
                } else {
                    logWriter.write("cannot find proper data from 'resource'.. regarding it as data string");
                    source = CharSource.wrap(resource);
                }
                readData(parser, source);
            }
        } else {
            throw new UOE("Unknown type[%s]", type);
        }
    } catch (Exception e) {
        LOG.error(e, "INVALID JSON!");
        throw Throwables.propagate(e);
    }
}

From source file:io.reactivesocket.cli.Main.java

private Publisher<Payload> inputPublisher() {
    CharSource is;//from w  w w . ja va  2  s .c o m

    if (input == null) {
        is = SystemInCharSource.INSTANCE;
    } else if (input.startsWith("@")) {
        is = Files.asCharSource(inputFile(), Charsets.UTF_8);
    } else {
        is = CharSource.wrap(input);
    }

    return ObservableIO.lines(is);
}

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

private List<CharSource> getProfiles(String transactionType, @Nullable String transactionName, long from,
        long to) throws Exception {
    List<AggregateIntervalCollector> orderedIntervalCollectors = getOrderedIntervalCollectorsInRange(from, to);
    if (orderedIntervalCollectors.isEmpty()) {
        return getProfilesFromDao(transactionType, transactionName, from, to);
    }// w ww  . j  a v a 2 s  .c  o  m
    long revisedTo = getRevisedTo(to, orderedIntervalCollectors);
    List<CharSource> profiles = getProfilesFromDao(transactionType, transactionName, from, revisedTo);
    profiles = Lists.newArrayList(profiles);
    for (AggregateIntervalCollector intervalCollector : orderedIntervalCollectors) {
        String profile = intervalCollector.getLiveProfileJson(transactionType, transactionName);
        if (profile != null) {
            profiles.add(CharSource.wrap(profile));
        }
    }
    return profiles;
}

From source file:com.google.errorprone.DiagnosticTestHelper.java

/**
 * Asserts that the diagnostics contain a diagnostic on each line of the source file that
 * matches our bug marker pattern.  Parses the bug marker pattern for the specific string to
 * look for in the diagnostic./*from  ww  w  .  java 2 s.c  om*/
 * @param source File in which to find matching lines
 *
 * TODO(eaftan): Switch to use assertThat instead of assertTrue.
 */
public void assertHasDiagnosticOnAllMatchingLines(JavaFileObject source,
        LookForCheckNameInDiagnostic lookForCheckNameInDiagnostic) throws IOException {
    final List<Diagnostic<? extends JavaFileObject>> diagnostics = getDiagnostics();
    final LineNumberReader reader = new LineNumberReader(
            CharSource.wrap(source.getCharContent(false)).openStream());
    do {
        String line = reader.readLine();
        if (line == null) {
            break;
        }

        List<Predicate<? super String>> predicates = null;
        if (line.contains(BUG_MARKER_COMMENT_INLINE)) {
            // Diagnostic must contain all patterns from the bug marker comment.
            List<String> patterns = extractPatterns(line, reader, BUG_MARKER_COMMENT_INLINE);
            predicates = new ArrayList<>(patterns.size());
            for (String pattern : patterns) {
                predicates.add(new SimpleStringContains(pattern));
            }
        } else if (line.contains(BUG_MARKER_COMMENT_LOOKUP)) {
            int markerLineNumber = reader.getLineNumber();
            List<String> lookupKeys = extractPatterns(line, reader, BUG_MARKER_COMMENT_LOOKUP);
            predicates = new ArrayList<>(lookupKeys.size());
            for (String lookupKey : lookupKeys) {
                assertTrue(
                        "No expected error message with key [" + lookupKey + "] as expected from line ["
                                + markerLineNumber + "] with diagnostic [" + line.trim() + "]",
                        expectedErrorMsgs.containsKey(lookupKey));
                predicates.add(expectedErrorMsgs.get(lookupKey));
                usedLookupKeys.add(lookupKey);
            }
        }

        if (predicates != null) {
            int lineNumber = reader.getLineNumber();
            for (Predicate<? super String> predicate : predicates) {
                Matcher<? super Iterable<Diagnostic<? extends JavaFileObject>>> patternMatcher = hasItem(
                        diagnosticOnLine(source.toUri(), lineNumber, predicate));
                assertTrue("Did not see an error on line " + lineNumber + " matching " + predicate
                        + ". All errors:\n" + diagnostics, patternMatcher.matches(diagnostics));
            }

            if (checkName != null && lookForCheckNameInDiagnostic == LookForCheckNameInDiagnostic.YES) {
                // Diagnostic must contain check name.
                Matcher<? super Iterable<Diagnostic<? extends JavaFileObject>>> checkNameMatcher = hasItem(
                        diagnosticOnLine(source.toUri(), lineNumber,
                                new SimpleStringContains("[" + checkName + "]")));
                assertTrue("Did not see an error on line " + lineNumber + " containing [" + checkName
                        + "]. All errors:\n" + diagnostics, checkNameMatcher.matches(diagnostics));
            }

        } else {
            int lineNumber = reader.getLineNumber();
            Matcher<? super Iterable<Diagnostic<? extends JavaFileObject>>> matcher = hasItem(
                    diagnosticOnLine(source.toUri(), lineNumber));
            if (matcher.matches(diagnostics)) {
                fail("Saw unexpected error on line " + lineNumber + ". All errors:\n" + diagnostics);
            }
        }
    } while (true);
    reader.close();
}

From source file:com.google.openrtb.json.OpenRtbNativeJsonReader.java

/**
 * Desserializes a {@link NativeResponse} from a JSON string, provided as a {@link CharSequence}.
 *///from  w  w w.j  ava 2  s  . c o  m
public NativeResponse readNativeResponse(CharSequence chars) throws IOException {
    return readNativeResponse(CharSource.wrap(chars).openStream());
}