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:org.sakaiproject.sitestats.impl.parser.DigesterUtil.java

public static String convertReportParamsToXml(ReportParams reportParams) throws Exception {
    String xml = null;// ww  w  . j a  va  2s.  com
    StringWriter outputWriter = null;
    try {
        outputWriter = new StringWriter();
        outputWriter.write("<?xml version='1.0' ?>");
        BeanWriter beanWriter = getBeanWriter(outputWriter);
        beanWriter.write("ReportParams", reportParams);
        xml = outputWriter.toString();
    } finally {
        outputWriter.close();
    }
    return xml;
}

From source file:org.sakaiproject.sitestats.impl.parser.DigesterUtil.java

public static String convertReportDefsToXml(List<ReportDef> reportDef) throws Exception {
    String xml = null;//from w  ww  .ja v a 2  s.com
    StringWriter outputWriter = null;
    try {
        outputWriter = new StringWriter();
        outputWriter.write("<?xml version='1.0' ?>");
        BeanWriter beanWriter = getBeanWriter(outputWriter);
        beanWriter.write("List", reportDef);
        xml = outputWriter.toString();
    } finally {
        outputWriter.close();
    }
    return xml;
}

From source file:nl.b3p.catalog.arcgis.ArcObjectsSynchronizerForker.java

public static Document synchronize(ServletContext context, /* HttpServletResponse response,*/ String dataset,
        String type, String sdeConnectionString, String metadata) throws Exception {

    String workingDir = context.getRealPath("/WEB-INF");

    String cp = buildClasspath(context);
    String mainClass = ArcObjectsSynchronizerMain.class.getName();

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

    args.addAll(Arrays.asList("java", "-classpath", cp, mainClass, "-type", type, "-dataset", dataset));
    if (metadata != null && !"".equals(metadata)) {
        args.add("-stdin");
    }/*from   w w  w . java2 s . co m*/

    if ("sde".equals(type)) {
        if (sdeConnectionString == null) {
            throw new IllegalArgumentException("SDE connection string is required");
        }
        args.add("-sde");
        args.add(sdeConnectionString);
    }

    final StringWriter output = new StringWriter();
    final StringWriter errors = new StringWriter(); // response.getWriter();
    errors.write(String.format("Werkdirectory: %s\nUitvoeren synchronizer proces: %s\n\n", workingDir,
            StringUtils.join(args, ' ')));
    //errors.flush();
    int result;

    try {
        Process p = Runtime.getRuntime().exec(args.toArray(new String[] {}), null, new File(workingDir));

        final BufferedReader stderr = new BufferedReader(new InputStreamReader(p.getErrorStream()));
        final BufferedReader stdout = new BufferedReader(new InputStreamReader(p.getInputStream()));

        if (metadata != null && !"".equals(metadata)) {
            try {
                p.getOutputStream().write(metadata.getBytes("UTF-8"));
                p.getOutputStream().flush();
                p.getOutputStream().close();
            } catch (Exception e) {
                errors.write("Fout tijdens schrijven metadata XML met alle elementen naar stdin: "
                        + e.getClass() + ": " + e.getMessage() + "\n");
            }
        }

        // Threads vereist omdat streams blocken en pas verder gaan nadat je uit
        // de andere stream hebt gelezen

        Thread stderrReader = new Thread() {
            @Override
            public void run() {
                String line;
                try {
                    while ((line = stderr.readLine()) != null) {
                        errors.write(line + "\r\n");
                        //errors.flush();
                    }
                    stderr.close();
                } catch (Exception e) {
                    throw new Error(e);
                }
            }
        };

        Thread stdoutReader = new Thread() {
            @Override
            public void run() {
                String line;
                try {
                    while ((line = stdout.readLine()) != null) {
                        output.write(line + "\r\n");
                    }
                    stdout.close();
                } catch (Exception e) {
                    throw new Error(e);
                }
            }
        };

        stderrReader.start();
        stdoutReader.start();

        result = p.waitFor();

        stderrReader.join();
        stdoutReader.join();

        errors.write("Resultaat: " + (result == 0 ? "succesvol gesynchroniseerd" : "fout opgetreden") + "\n\n");
    } catch (Exception e) {
        throw new Exception(
                "Fout tijdens aanroepen extern proces voor synchroniseren, output: \n" + errors.toString(), e);
    }

    if (log.isDebugEnabled()) {
        log.debug("Synchroniseren via apart proces succesvol; output: " + errors.toString());
    }
    if (result == 0) {
        return DocumentHelper.getMetadataDocument(output.toString());
    } else {
        throw new Exception("Synchroniseren via apart process geeft error code " + result + "; output: \n"
                + errors.toString());
    }
}

From source file:org.localmatters.serializer.util.EscapeUtils.java

/**
  * Escapes the characters in a <code>String</code> using JSON String rules.
  * Deals correctly with quotes and control-chars (tab, backslash, cr, ff, 
  * etc.). So a tab becomes the characters <code>'\\'</code> and 
  * <code>'t'</code>.//from w  w  w  .  ja v a2 s. c  o m
  * @param str The string to escape
  * @return The escaped string
  */
public static String escapeJson(String str) {
    if (str == null) {
        return null;
    }
    StringWriter writer = new StringWriter(str.length() * 2);
    int sz;
    sz = str.length();
    for (int i = 0; i < sz; i++) {
        char ch = str.charAt(i);
        switch (ch) {
        case '\b':
            writer.write('\\');
            writer.write('b');
            break;
        case '\n':
            writer.write('\\');
            writer.write('n');
            break;
        case '\t':
            writer.write('\\');
            writer.write('t');
            break;
        case '\f':
            writer.write('\\');
            writer.write('f');
            break;
        case '\r':
            writer.write('\\');
            writer.write('r');
            break;
        case '"':
            writer.write('\\');
            writer.write('"');
            break;
        case '\\':
            writer.write('\\');
            writer.write('\\');
            break;
        default:
            writer.write(ch);
            break;
        }
    }
    return writer.toString();
}

From source file:bin.spider.frame.uri.TextUtils.java

/**
 * @param message Message to put at top of the string returned. May be
 * null.//w  w w . ja  va 2s  . c  o  m
 * @param e Exception to write into a string.
 * @return Return formatted string made of passed message and stack trace
 * of passed exception.
 */
public static String exceptionToString(String message, Throwable e) {
    StringWriter sw = new StringWriter();
    if (message == null || message.length() == 0) {
        sw.write(message);
        sw.write("\n");
    }
    e.printStackTrace(new PrintWriter(sw));
    return sw.toString();
}

From source file:com.espertech.esper.event.bean.PropertyHelper.java

private static String getGetterSetterMethodName(String propertyName, String operation) {
    StringWriter writer = new StringWriter();
    writer.write(operation);
    writer.write(Character.toUpperCase(propertyName.charAt(0)));
    writer.write(propertyName.substring(1));
    return writer.toString();
}

From source file:com.futureplatforms.kirin.internal.JSONUtils.java

/**
 * Based on Apache Common Lang 2.6 implementation of StringEscapeUtls.escapeJavaScript.
 * /*from w  w  w .ja v  a  2 s.  c  om*/
 * Future: Use JSONStringer?
 * 
 * @param str The string to escape
 * @return Escaped string
 * @throws IOException
 */
public static String escapeJavaScript(String str) {
    if (str == null) {
        return null;
    }

    int size = str.length();
    StringWriter out = new StringWriter(size * 2);

    for (int i = 0; i < size; i++) {
        char ch = str.charAt(i);

        // handle unicode
        if (ch > 0xfff) {
            out.write("\\u" + hex(ch));
        } else if (ch > 0xff) {
            out.write("\\u0" + hex(ch));
        } else if (ch > 0x7f) {
            out.write("\\u00" + hex(ch));
        } else if (ch < 32) {
            switch (ch) {
            case '\b':
                out.write('\\');
                out.write('b');
                break;
            case '\n':
                out.write('\\');
                out.write('n');
                break;
            case '\t':
                out.write('\\');
                out.write('t');
                break;
            case '\f':
                out.write('\\');
                out.write('f');
                break;
            case '\r':
                out.write('\\');
                out.write('r');
                break;
            default:
                if (ch > 0xf) {
                    out.write("\\u00" + hex(ch));
                } else {
                    out.write("\\u000" + hex(ch));
                }
                break;
            }
        } else {
            switch (ch) {
            case '\'':
                out.write('\\');
                out.write('\'');
                break;
            case '"':
                out.write('\\');
                out.write('"');
                break;
            case '\\':
                out.write('\\');
                out.write('\\');
                break;
            case '/':
                out.write('\\');
                out.write('/');
                break;
            default:
                out.write(ch);
                break;
            }
        }
    }

    return out.toString();
}

From source file:org.apache.oozie.action.hadoop.LauncherMain.java

/**
 * Write to STDOUT (the task log) the Configuration/Properties values. All properties that contain
 * any of the strings in the maskSet will be masked when writting it to STDOUT.
 *
 * @param header message for the beginning of the Configuration/Properties dump.
 * @param maskSet set with substrings of property names to mask.
 * @param conf Configuration/Properties object to dump to STDOUT
 * @throws IOException thrown if an IO error ocurred.
 *///from   w w  w . j  a  v a 2 s .  c  om
@SuppressWarnings("unchecked")
protected static void logMasking(String header, Collection<String> maskSet, Iterable conf) throws IOException {
    StringWriter writer = new StringWriter();
    writer.write(header + "\n");
    writer.write("--------------------\n");
    for (Map.Entry entry : (Iterable<Map.Entry>) conf) {
        String name = (String) entry.getKey();
        String value = (String) entry.getValue();
        for (String mask : maskSet) {
            if (name.contains(mask)) {
                value = "*MASKED*";
            }
        }
        writer.write(" " + name + " : " + value + "\n");
    }
    writer.write("--------------------\n");
    writer.close();
    System.out.println(writer.toString());
    System.out.flush();
}

From source file:dk.statsbiblioteket.hadoop.archeaderextractor.ARCHeaderExtractor.java

private static String extractHeader(ArcRecordBase arcRecord, String timeStamp) throws IOException {
    StringWriter headerString = new StringWriter();

    HttpHeader httpHeader = null;/*from w  ww  . j  a  v  a  2s .c o  m*/
    if (hasPayload(arcRecord)) {
        httpHeader = arcRecord.getHttpHeader();
        if (httpHeader != null) {

            headerString.write("Offset: " + arcRecord.getStartOffset() + "\n");

            String URLHash = DigestUtils.md5Hex(arcRecord.getUrlStr());

            headerString.write("KEY: " + URLHash + "-" + timeStamp + "\n");
            headerString.write("URL: " + arcRecord.getUrlStr() + "\n");

            headerString.write("IP:  " + arcRecord.getIpAddress() + "\n");

            headerString.write("ProtocolVersion: " + httpHeader.getProtocolVersion() + "\n");
            headerString.write("ProtocolStatusCode: " + httpHeader.getProtocolStatusCodeStr() + "\n");
            headerString.write("ProtocolContentType: " + httpHeader.getProtocolContentType() + "\n");
            headerString.write("TotalLength: " + httpHeader.getTotalLength() + "\n");

            for (HeaderLine hl : httpHeader.getHeaderList()) {
                headerString.write(hl.name + ": " + hl.value + "\n");
            }
        }
    }
    if (httpHeader != null) {
        httpHeader.close();
    }
    arcRecord.close();
    return headerString.toString();
}

From source file:com.facebook.fresco.sample.urlsfetcher.ImageUrlsFetcher.java

/** Reads an InputStream and converts it to a String. */
private static String readAsString(InputStream stream) throws IOException {
    StringWriter writer = new StringWriter();
    Reader reader = new BufferedReader(new InputStreamReader(stream, "UTF-8"));
    while (true) {
        int c = reader.read();
        if (c < 0) {
            break;
        }/* ww w. ja v  a  2 s. c o  m*/
        writer.write(c);
    }
    return writer.toString();
}