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.google.javascript.jscomp.deps.ClosureBundler.java

/** Append the contents of the string to the supplied appendable. */
public void appendTo(Appendable out, DependencyInfo info, String content) throws IOException {
    appendTo(out, info, CharSource.wrap(content));
}

From source file:de.monticore.parsing.Parser.java

/**
 * Parses the given {@link CharSequence}.
 * /*from   w ww . j a v a  2 s.c  om*/
 * @return the ast of the resulting model.
 */
public final ASTNode parse(CharSequence model) {
    return parse(CharSource.wrap(Log.errorIfNull(model)));
}

From source file:org.metaservice.core.nvd.cve.CVEParser.java

@Override
public List<VulnerabilityType> parse(final Reader source, ArchiveAddress archiveParameters) {
    final List<VulnerabilityType> result = new ArrayList<>();
    List<Future<List<VulnerabilityType>>> futures = new ArrayList<>();

    try {/*from  w w  w. j  av  a2  s. c o  m*/
        final String s = IOUtils.toString(source);
        final JAXBContext jaxbContext = JAXBContext.newInstance(Nvd.class);

        final CharSource header = CharSource.wrap(new CharSequenceSegment(s, 0, s.indexOf("<entry") - 1));
        final CharSource end = CharSource.wrap(s.substring(s.lastIndexOf("</entry>") + 9));

        int i = 0;
        //
        int index = 0;
        while (index < s.length()) {
            final int start = s.indexOf("<entry ", index);
            if (start == -1) {
                break;
            }
            index = start;
            int e = start;
            for (int j = 0; j < 500; j++) {
                e = s.indexOf("</entry>", index);
                if (e == -1) {
                    e = s.lastIndexOf("</entry>") + 8;
                    break;
                }
                e += 8;
                index = e;
            }
            final int finalE = e;
            Future<List<VulnerabilityType>> future = executorService
                    .submit(new Callable<List<VulnerabilityType>>() {
                        @Override
                        public List<VulnerabilityType> call() {
                            Unmarshaller unmarshaller = null;
                            try {
                                unmarshaller = jaxbContext.createUnmarshaller();
                                Nvd nvd = (Nvd) unmarshaller
                                        .unmarshal(CharSource
                                                .concat(header,
                                                        CharSource.wrap(
                                                                new CharSequenceSegment(s, start, finalE)),
                                                        end)
                                                .openStream());
                                return nvd.getEntries();
                            } catch (JAXBException | IOException e1) {
                                throw new RuntimeException(e1);
                            }
                        }
                    });
            futures.add(future);

            //   System.err.println(new CharSequenceSegment(s,start,e).toString().substring(0,40));
            /*
                            if(i++ % 100 == 0)
            System.err.println(i);*/
        }

    } catch (JAXBException | IOException e) {
        e.printStackTrace();
    }
    for (Future<List<VulnerabilityType>> future : futures) {
        try {
            result.addAll(future.get());
        } catch (InterruptedException | ExecutionException e) {
            e.printStackTrace();
        }
    }
    return result;
}

From source file:com.google.errorprone.apply.SourceFile.java

/**
 * Returns a copy of code as a list of lines.
 *//* ww  w. j av a 2  s.  c  o  m*/
public List<String> getLines() {
    try {
        return CharSource.wrap(sourceBuilder).readLines();
    } catch (IOException e) {
        throw new AssertionError("IOException not possible, as the string is in-memory");
    }
}

From source file:com.google.googlejavaformat.java.filer.FormattingJavaFileObject.java

@Override
public Writer openWriter() throws IOException {
    final StringBuilder stringBuilder = new StringBuilder(DEFAULT_FILE_SIZE);
    return new Writer() {
        @Override/*from  ww w  .  j  a  v a  2  s  .  c o m*/
        public void write(char[] chars, int start, int end) throws IOException {
            stringBuilder.append(chars, start, end - start);
        }

        @Override
        public void write(String string) throws IOException {
            stringBuilder.append(string);
        }

        @Override
        public void flush() throws IOException {
        }

        @Override
        public void close() throws IOException {
            try {
                formatter.formatSource(CharSource.wrap(stringBuilder), new CharSink() {
                    @Override
                    public Writer openStream() throws IOException {
                        return fileObject.openWriter();
                    }
                });
            } catch (FormatterException e) {
                // An exception will happen when the code being formatted has an error. It's better to
                // log the exception and emit unformatted code so the developer can view the code which
                // caused a problem.
                try (Writer writer = fileObject.openWriter()) {
                    writer.append(stringBuilder.toString());
                }
                if (messager != null) {
                    messager.printMessage(Diagnostic.Kind.NOTE, "Error formatting " + getName());
                }
            }
        }
    };
}

From source file:org.apache.isis.applib.value.Clob.java

public void writeCharsTo(final Writer wr) throws IOException {
    CharSource.wrap(chars).copyTo(wr);
}

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

private String prettyPrintXml(CharSource inputXml) {
    try {/*from   w w w.j av  a  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();
        }
    }
}

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

/**
 * Desserializes a {@link NativeRequest} from a JSON string, provided as a {@link CharSequence}.
 *//*w  w  w  . j  a va  2s. c om*/
public NativeRequest readNativeRequest(CharSequence chars) throws IOException {
    return readNativeRequest(CharSource.wrap(chars).openStream());
}

From source file:works.chatterbox.chatterbox.hooks.HookManager.java

/**
 * Creates a ConfigurationNode from a YAML string.
 *
 * @param string String of YAML//from   www  .j ava2  s. c o  m
 * @return ConfigurationNode
 * @throws IOException If any IOException occurs
 */
@NotNull
private ConfigurationNode loadYAML(@NotNull final String string) throws IOException {
    Preconditions.checkNotNull(string, "string was null");
    return YAMLConfigurationLoader.builder().setSource(CharSource.wrap(string)).build().load();
}

From source file:dagger.internal.codegen.JavaPoetSourceFileGenerator.java

/** Generates a source file to be compiled for {@code T}. */
void generate(T input) throws SourceFileGenerationException {
    ClassName generatedTypeName = nameGeneratedType(input);
    try {/*w ww .  j  a v  a2  s .  co  m*/
        Optional<TypeSpec.Builder> type = write(generatedTypeName, input);
        if (!type.isPresent()) {
            return;
        }
        JavaFile javaFile = buildJavaFile(generatedTypeName, type.get());

        final JavaFileObject sourceFile = filer.createSourceFile(generatedTypeName.toString(),
                Iterables.toArray(javaFile.typeSpec.originatingElements, Element.class));
        try {
            new Formatter().formatSource(CharSource.wrap(javaFile.toString()), new CharSink() {
                @Override
                public Writer openStream() throws IOException {
                    return sourceFile.openWriter();
                }
            });
        } catch (FormatterException e) {
            throw new SourceFileGenerationException(Optional.of(generatedTypeName), e,
                    getElementForErrorReporting(input));
        }
    } catch (Exception e) {
        // if the code above threw a SFGE, use that
        Throwables.propagateIfPossible(e, SourceFileGenerationException.class);
        // otherwise, throw a new one
        throw new SourceFileGenerationException(Optional.<ClassName>absent(), e,
                getElementForErrorReporting(input));
    }
}