Example usage for java.io StringWriter write

List of usage examples for java.io StringWriter write

Introduction

In this page you can find the example usage for java.io StringWriter write.

Prototype

public void write(String str) 

Source Link

Document

Write a string.

Usage

From source file:eu.interedition.collatex.tools.CollationPipe.java

public static void start(CommandLine commandLine) throws Exception {
    List<SimpleWitness> witnesses = null;
    Function<String, Stream<String>> tokenizer = SimplePatternTokenizer.BY_WS_OR_PUNCT;
    Function<String, String> normalizer = SimpleTokenNormalizers.LC_TRIM_WS;
    Comparator<Token> comparator = new EqualityTokenComparator();
    CollationAlgorithm collationAlgorithm = null;
    boolean joined = true;

    final String[] witnessSpecs = commandLine.getArgs();
    final InputStream[] inputStreams = new InputStream[witnessSpecs.length];
    for (int wc = 0, wl = witnessSpecs.length; wc < wl; wc++) {
        try {//from  w  ww  .  j  a  v a  2 s.c  om
            inputStreams[wc] = argumentToInputStream(witnessSpecs[wc]);
        } catch (MalformedURLException urlEx) {
            throw new ParseException("Invalid resource: " + witnessSpecs[wc]);
        }
    }

    if (inputStreams.length < 1) {
        throw new ParseException("No input resource(s) given");
    } else if (inputStreams.length < 2) {
        try (InputStream inputStream = inputStreams[0]) {
            final SimpleCollation collation = JsonProcessor.read(inputStream);
            witnesses = collation.getWitnesses();
            collationAlgorithm = collation.getAlgorithm();
            joined = collation.isJoined();
        }
    }

    final String script = commandLine.getOptionValue("s");
    try {
        final PluginScript pluginScript = (script == null
                ? PluginScript.read("<internal>", new StringReader(""))
                : PluginScript.read(argumentToInput(script)));

        tokenizer = Optional.ofNullable(pluginScript.tokenizer()).orElse(tokenizer);
        normalizer = Optional.ofNullable(pluginScript.normalizer()).orElse(normalizer);
        comparator = Optional.ofNullable(pluginScript.comparator()).orElse(comparator);
    } catch (IOException e) {
        throw new ParseException("Failed to read script '" + script + "' - " + e.getMessage());
    }

    switch (commandLine.getOptionValue("a", "").toLowerCase()) {
    case "needleman-wunsch":
        collationAlgorithm = CollationAlgorithmFactory.needlemanWunsch(comparator);
        break;
    case "medite":
        collationAlgorithm = CollationAlgorithmFactory.medite(comparator, SimpleToken.TOKEN_MATCH_EVALUATOR);
        break;
    case "gst":
        collationAlgorithm = CollationAlgorithmFactory.greedyStringTiling(comparator, 2);
        break;
    default:
        collationAlgorithm = Optional.ofNullable(collationAlgorithm)
                .orElse(CollationAlgorithmFactory.dekker(comparator));
        break;
    }

    if (witnesses == null) {
        final Charset inputCharset = Charset
                .forName(commandLine.getOptionValue("ie", StandardCharsets.UTF_8.name()));
        final boolean xmlMode = commandLine.hasOption("xml");
        final XPathExpression tokenXPath = XPathFactory.newInstance().newXPath()
                .compile(commandLine.getOptionValue("xp", "//text()"));

        witnesses = new ArrayList<>(inputStreams.length);
        for (int wc = 0, wl = inputStreams.length; wc < wl; wc++) {
            try (InputStream stream = inputStreams[wc]) {
                final String sigil = "w" + (wc + 1);
                if (!xmlMode) {
                    final BufferedReader reader = new BufferedReader(
                            new InputStreamReader(stream, inputCharset));
                    final StringWriter writer = new StringWriter();
                    final char[] buf = new char[1024];
                    while (reader.read(buf) != -1) {
                        writer.write(buf);
                    }
                    witnesses.add(new SimpleWitness(sigil, writer.toString(), tokenizer, normalizer));
                } else {
                    final DocumentBuilder documentBuilder = DocumentBuilderFactory.newInstance()
                            .newDocumentBuilder();
                    final Document document = documentBuilder.parse(stream);
                    document.normalizeDocument();

                    final SimpleWitness witness = new SimpleWitness(sigil);
                    final NodeList tokenNodes = (NodeList) tokenXPath.evaluate(document,
                            XPathConstants.NODESET);
                    final List<Token> tokens = new ArrayList<>(tokenNodes.getLength());
                    for (int nc = 0; nc < tokenNodes.getLength(); nc++) {
                        final String tokenText = tokenNodes.item(nc).getTextContent();
                        tokens.add(new SimpleToken(witness, tokenText, normalizer.apply(tokenText)));
                    }
                    witness.setTokens(tokens);
                    witnesses.add(witness);
                }
            }
        }
    }

    final VariantGraph variantGraph = new VariantGraph();
    collationAlgorithm.collate(variantGraph, witnesses);

    if (joined && !commandLine.hasOption("t")) {
        VariantGraph.JOIN.apply(variantGraph);
    }

    final String output = commandLine.getOptionValue("o", "-");
    final Charset outputCharset = Charset
            .forName(commandLine.getOptionValue("oe", StandardCharsets.UTF_8.name()));
    final String outputFormat = commandLine.getOptionValue("f", "json").toLowerCase();

    try (PrintWriter out = argumentToOutput(output, outputCharset)) {
        final SimpleVariantGraphSerializer serializer = new SimpleVariantGraphSerializer(variantGraph);
        if ("csv".equals(outputFormat)) {
            serializer.toCsv(out);
        } else if ("dot".equals(outputFormat)) {
            serializer.toDot(out);
        } else if ("graphml".equals(outputFormat) || "tei".equals(outputFormat)) {
            XMLStreamWriter xml = null;
            try {
                xml = XMLOutputFactory.newInstance().createXMLStreamWriter(out);
                xml.writeStartDocument(outputCharset.name(), "1.0");
                if ("graphml".equals(outputFormat)) {
                    serializer.toGraphML(xml);
                } else {
                    serializer.toTEI(xml);
                }
                xml.writeEndDocument();
            } catch (XMLStreamException e) {
                throw new IOException(e);
            } finally {
                if (xml != null) {
                    try {
                        xml.close();
                    } catch (XMLStreamException e) {
                        // ignored
                    }
                }
            }
        } else {
            JsonProcessor.write(variantGraph, out);
        }
    }
}

From source file:com.github.gekoh.yagen.hibernate.PatchHibernateMappingClasses.java

public static String[] addHeaderAndFooter(String[] createSQL, Dialect dialect) {
    DDLGenerator.Profile profile;//from w w w. java 2 s  .c o m

    if (dialect instanceof DDLEnhancer) {
        DDLEnhancer ddlEnhancer = (DDLEnhancer) dialect;
        profile = ddlEnhancer.getDDLEnhancer().getProfile();
    } else {
        LOG.warn("{} was not patched, generator enhancements not working", Dialect.class.getName());
        return createSQL;
    }

    int idx = 0;
    List<String> ddlList = new ArrayList(Arrays.asList(createSQL));

    StringWriter sw = new StringWriter();

    sw.write("-- auto generated by " + DDLGenerator.class.getName() + " at " + new DateTime() + "\n");
    sw.write("-- DO NOT EDIT MANUALLY!");

    ddlList.add(idx++, sw.toString());

    for (DDLGenerator.AddDDLEntry addDdlFile : profile.getHeaderDdls()) {
        sw = new StringWriter();

        sw.write("-- " + addDdlFile + "\n");
        sw.write("-- DO NOT EDIT!\n");
        sw.write(addDdlFile.getDdlText(dialect));
        sw.write("\n");

        ddlList.add(idx++, sw.toString());
    }

    for (DDLGenerator.AddDDLEntry addDdlFile : profile.getAddDdls()) {
        sw = new StringWriter();

        sw.write("-- " + addDdlFile + "\n");
        sw.write("-- DO NOT EDIT!\n");
        sw.write(addDdlFile.getDdlText(dialect));
        sw.write("\n");

        ddlList.add(sw.toString());
    }

    return ddlList.toArray(new String[ddlList.size()]);
}

From source file:org.openlaszlo.sc.ScriptCompiler.java

/** Compiles the specified script into bytecode
 *
 * @param script a script/*from  w  w  w .  ja  v a 2s .co  m*/
 * @return an array containing the bytecode
 */
public static byte[] compileToByteArray(String script, Properties properties) {

    writeIntermediateFile(script);

    // We only want to keep off the properties that affect the
    // compilation.  Currently, "filename" is the only property
    // that tends to change and that the script compiler ignores,
    // so make a copy of properties that neutralizes that.
    properties = (Properties) properties.clone();
    properties.setProperty("filename", "");
    // Check the cache.  clearCache may clear the cache at any
    // time, so use a copy of it so that it doesn't change state
    // between a test that it's null and a method call on it.
    Item item = null;
    byte[] code = null;
    try {
        if (mScriptCache == null) {
            return _compileToByteArray(script, properties);
        } else {
            // The key is a string representation of the arguments:
            // properties, and the script.
            StringWriter writer = new StringWriter();
            writer.write(sortedPropertiesList(properties));
            writer.getBuffer().append(script);
            String key = writer.toString();
            synchronized (mScriptCache) {
                item = mScriptCache.findItem(key, null, false);
            }
        }

        if (item.getInfo().getSize() != 0) {
            code = item.getRawByteArray();
        } else {
            code = _compileToByteArray(script, properties);
            // Another thread might already have set this since we
            // called get.  That's okay --- it's the same value.
            synchronized (mScriptCache) {
                item.update(new ByteArrayInputStream(code), null);
                item.updateInfo();
                item.markClean();
            }
        }

        mScriptCache.updateCache(item);

        return (byte[]) code;
    } catch (IOException e) {
        throw new CompilationError(e, "IOException in compilation/script-cache");
    }
}

From source file:com.apporiented.hermesftp.utils.IOUtils.java

/**
 * Reads an arbitrary text resource from the class path.
 * //w w  w  .  j  a  v  a2s .  c  om
 * @param name The name of the resource.
 * @param encoding The text encoding.
 * @return The text.
 * @throws IOException Error on accessing the resource.
 */
public static String loadTextResource(String name, String encoding) throws IOException {
    String result = null;
    StringWriter sw = null;
    InputStreamReader isr = null;
    if (encoding == null) {
        encoding = "UTF-8";
    }
    try {
        InputStream is = IOUtils.class.getResourceAsStream(name);
        isr = new InputStreamReader(is, encoding);
        sw = new StringWriter();
        int c;
        while ((c = isr.read()) != -1) {
            sw.write(c);
        }
        result = sw.getBuffer().toString();
    } finally {
        closeGracefully(isr);
        closeGracefully(sw);
    }
    return result;
}

From source file:org.opensextant.xtext.collectors.web.WebClient.java

/**
 * Reads a data stream as text as the default encoding.
 * TODO: test reading website content with different charset encodings to see if the resulting String
 * is properly decoded.//w w  w  . j a  v a  2s.c  o m
 *
 * @param io
 *            IO stream
 * @return content of the stream
 * @throws IOException
 *             I/O error
 */
public static String readTextStream(InputStream io) throws IOException {
    Reader reader = new InputStreamReader(io);
    StringWriter buf = new StringWriter();

    int ch;
    while ((ch = reader.read()) >= 0) {
        buf.write(ch);
    }
    reader.close();
    io.close();

    return buf.toString();
}

From source file:org.occiware.clouddesigner.occi.docker.connector.dockermachine.util.DockerUtil.java

public static String asString(final InputStream response) {
    final StringWriter logwriter = new StringWriter();
    try {/*from   w  w w  .  j ava2  s. c o m*/
        final LineIterator itr = IOUtils.lineIterator(response, "UTF-8");
        while (itr.hasNext()) {
            {
                String line = itr.next();
                boolean _hasNext = itr.hasNext();
                if (_hasNext) {
                    logwriter.write((line + "\n"));
                } else {
                    logwriter.write((line + ""));
                }
            }
        }
        response.close();
        return logwriter.toString();
    } catch (final Throwable _t) {
        if (_t instanceof IOException) {
            final IOException e = (IOException) _t;
            throw new RuntimeException(e);
        } else {
            throw Exceptions.sneakyThrow(_t);
        }
    } finally {
        IOUtils.closeQuietly(response);
    }
}

From source file:gdv.xport.util.XmlFormatter.java

/**
 * Wandelt den uebergebenen Satz in einen XML-String um.
 *
 * @param satz/*from www. ja  va  2s  .  c om*/
 *            ein Satz
 *
 * @return Satz als XML-String
 */
public static String toString(final Satz satz) {
    StringWriter swriter = new StringWriter();
    XmlFormatter formatter = new XmlFormatter(swriter);
    try {
        formatter.write(satz, 0);
    } catch (XMLStreamException ex) {
        LOG.warn("cannot format " + satz, ex);
        swriter.write("<!-- " + satz + " -->");
    }
    IOUtils.closeQuietly(swriter);
    return swriter.toString();
}

From source file:org.apache.geode.management.internal.beans.QueryDataFunction.java

private static String wrapResult(final String str) {
    StringWriter w = new StringWriter();
    synchronized (w.getBuffer()) {
        w.write("{\"result\":");
        w.write(str);/* ww  w .j ava  2  s.  c  om*/
        w.write("}");
        return w.toString();
    }
}

From source file:it.tidalwave.northernwind.core.impl.filter.HtmlCleanupFilter.java

/*******************************************************************************************************************
 *
 ******************************************************************************************************************/
public static String formatHtml(final @Nonnull String text) throws IOException {
    final StringWriter sw = new StringWriter();
    final BufferedReader br = new BufferedReader(new StringReader(text));

    boolean inBody = false;

    for (;;) {/*  w  ww .jav  a  2s  .  c  om*/
        final String s = br.readLine();

        if (s == null) {
            break;
        }

        if (s.contains("<!-- @nw.HtmlCleanupFilter.enabled=false")) {
            return text;
        }

        if ("</body>".equals(s.trim())) {
            break;
        }

        if (inBody) {
            sw.write(s + "\n");
        }

        if ("<body>".equals(s.trim())) {
            inBody = true;
        }
    }

    sw.close();
    br.close();

    return inBody ? sw.getBuffer().toString() : text;
}

From source file:org.solmix.commons.io.SlxFile.java

public static String canonicalizePath(String path) {
    if (path == null)
        return null;
    path = path.trim();// w ww .  ja  v a 2 s. co  m
    StringWriter sw = new StringWriter();
    int copiedFrom = 0;
    int length = path.length();
    for (int ii = 0; ii < length; ii++) {
        char currChar = path.charAt(ii);
        if (currChar != '\\' && currChar != '/')
            continue;
        sw.write(path.substring(copiedFrom, ii));
        sw.write(47);
        for (; ii + 1 < length; ii++) {
            char nextChar = path.charAt(ii + 1);
            if (nextChar != '/' && nextChar != '\\')
                break;
            if (ii - 1 >= 0 && path.charAt(ii - 1) == ':')
                sw.write(47);
        }

        copiedFrom = ii + 1;
    }

    sw.write(path.substring(copiedFrom, length));
    path = sw.getBuffer().toString();
    length = path.length();
    if (length > 1) {
        char lastChar = path.charAt(length - 1);
        if (lastChar == '/' || lastChar == '\\')
            path = path.substring(0, length - 1);
    }
    return path;
}