Example usage for java.io Writer toString

List of usage examples for java.io Writer toString

Introduction

In this page you can find the example usage for java.io Writer toString.

Prototype

public String toString() 

Source Link

Document

Returns a string representation of the object.

Usage

From source file:org.auraframework.integration.test.def.LibraryDefTest.java

public void testSerializationWithAuraProdCompression() throws Exception {
    DefDescriptor<LibraryDef> libDesc = getAuraTestingUtil().createStringSourceDescriptor(null,
            LibraryDef.class, null);
    DefDescriptor<IncludeDef> includeDesc = getAuraTestingUtil().createStringSourceDescriptor("uncompressed",
            IncludeDef.class, libDesc);
    addSourceAutoCleanup(libDesc,//from  ww w.  jav  a2  s .  com
            String.format("<aura:library><aura:include name='%s'/></aura:library>", includeDesc.getName()));
    addSourceAutoCleanup(includeDesc,
            "function(){\n\tvar renamed = 'truth';\n\tif(window.blah)\n\t\t{renamed+=' hurts'}\n\treturn renamed}");

    Aura.getContextService().endContext();
    Aura.getContextService().startContext(Mode.PROD, Format.JSON, Authentication.AUTHENTICATED);

    Set<DefDescriptor<?>> descs = ImmutableSet.<DefDescriptor<?>>of(libDesc);
    Writer writer = new StringWriter();
    Aura.getServerService().writeDefinitions(descs, writer);
    String actual = writer.toString();
    String expected = "function(){var a=\"truth\";window.blah&&(a+=\" hurts\");return a}";
    if (!actual.contains(expected)) {
        fail(String.format("library code was not compressed - expected <%s> but got <%s>", expected, actual));
    }
}

From source file:com.sharksharding.util.web.http.QueryViewServlet.java

@Override
protected void service(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    /* ? *//*from w w  w . j ava  2  s.  co m*/
    request.setCharacterEncoding("utf-8");
    response.setCharacterEncoding("utf-8");
    response.setContentType("text/html;charset=utf-8");
    /* Ioc */
    WebApplicationContext context = WebApplicationContextUtils
            .getWebApplicationContext(request.getSession().getServletContext());
    ShardRule shardRule = (ShardRule) context.getBean("shardRule");
    JdbcTemplate jdbcTemplate = (JdbcTemplate) context.getBean("jdbcTemplate");
    if (null != shardRule) {
        byte[] viewData = null;
        byte[] responseData = null;
        /* 1???2??? */
        final String TYPE = request.getParameter("type");
        if (null == TYPE) {
            viewData = initView(PATH + "index.html");
            if (null != viewData) {
                write(response, viewData);
            }
        } else {
            switch (Integer.parseInt(TYPE)) {
            case 1:
                String page = request.getParameter("page");
                if (page.equals("index")) {
                    viewData = initView(PATH + "index.html");
                } else if (page.equals("query")) {
                    viewData = initView(PATH + "query.html");
                }
                if (null != viewData) {
                    write(response, viewData);
                }
                break;
            case 2:
                final String SQL = request.getParameter("sql");
                if (null != SQL && 0 < SQL.trim().length()) {
                    JSONObject jsonObj = new JSONObject();
                    ExecuteSql exeSql = new ExecuteSql(jdbcTemplate);
                    try {
                        Map<String, Object> datas = exeSql.queryData(SQL);
                        if (!datas.isEmpty()) {
                            StringBuffer strBuffer = new StringBuffer();
                            Set<String> keys = datas.keySet();
                            for (String key : keys) {
                                strBuffer.append(datas.get(key) + ",");
                            }
                            jsonObj.put("sqlResult", strBuffer.toString());
                            responseData = jsonObj.toJSONString().getBytes();
                        }
                    } catch (Exception e) {
                        Writer write = new StringWriter();
                        e.printStackTrace(new PrintWriter(write));
                        jsonObj.put("error", write.toString());
                        responseData = jsonObj.toString().getBytes("utf-8");
                    }
                } else {
                    responseData = GetIndexData.getData(shardRule).getBytes("utf-8");
                }
                if (null != responseData) {
                    write(response, responseData);
                }
            }
        }
    }
}

From source file:de.tudarmstadt.ukp.experiments.dip.wp1.data.QueryResultContainer.java

public String toXML() throws IOException {
    Writer out = new StringWriter();
    out.write("<?xml version=\"1.0\" encoding=\"utf-8\"?>\n");

    XStream xStream = initializeXStream();

    xStream.toXML(this, out);
    IOUtils.closeQuietly(out);/*from   w  ww  .  j a  va2 s . c om*/

    return out.toString();
}

From source file:com.glaf.jbpm.web.rest.MxJbpmProcessViewResource.java

@GET
@POST/*www  .  j  ava 2 s . c om*/
@Path("detail/{processInstanceId}")
@Produces({ MediaType.APPLICATION_OCTET_STREAM })
@ResponseBody
public byte[] detail(@javax.ws.rs.core.Context HttpServletRequest request,
        @PathParam("processInstanceId") String pid) {
    if (StringUtils.isNotEmpty(pid)) {
        processInstanceId = Long.parseLong(pid);
        JbpmContext jbpmContext = null;
        try {
            contextPath = request.getContextPath();
            jbpmContext = ProcessContainer.getContainer().createJbpmContext();
            initialize(jbpmContext);
            if (processInstance != null && processDefinition != null) {
                retrieveByteArrays();
                if (gpdBytes != null && imageBytes != null) {
                    Writer writer = writeTable();
                    return writer.toString().getBytes("UTF-8");
                }
            }
        } catch (Exception ex) {
            throw new RuntimeException("table couldn't be displayed", ex);
        } finally {
            release();
            Context.close(jbpmContext);
        }
    }
    return null;
}

From source file:ca.nrc.cadc.xml.JsonOutputterTest.java

private void doit(String tname, Document document, JSONObject expected) throws IOException, JSONException {
    final JsonOutputter jsonOut = new JsonOutputter();
    jsonOut.getListElementNames().add("items");
    jsonOut.getStringElementNames().add("item");

    JsonInputter jsonIn = new JsonInputter();
    jsonIn.getListElementMap().put("items", "item");

    final Writer writer = new StringWriter();

    jsonOut.output(document, writer);/*  w  ww . jav  a  2s.  c  om*/
    String actual = writer.toString();
    log.debug(tname + ":\n" + actual);

    // verify expected json format
    final JSONObject result = new JSONObject(actual);
    JSONAssert.assertEquals(expected, result, true);

    // verify round-trip through outputter and inputter

    // JsonInputter does not handle namespaces correctly so disable this
    //Document doc2 = jsonIn.input(actual);
    //Writer writer2 = new StringWriter();
    //jsonOut.output(doc2, writer2);
    //String actual2 = writer2.toString();
    //log.debug(tname + ": (round-trip)\n" + actual2);

    //final JSONObject result2 = new JSONObject(actual2);
    //JSONAssert.assertEquals(expected, result2, true);
}

From source file:org.intellij.xquery.runner.rt.vendor.exist.ExistRunnerApp.java

private String prettyPrint(Element node, DOMImplementation domImplementation)
        throws InstantiationException, IllegalAccessException, ClassNotFoundException {
    DOMImplementationRegistry domImplementationRegistry = DOMImplementationRegistry.newInstance();
    DOMImplementationLS domImplementationLS = (DOMImplementationLS) domImplementationRegistry
            .getDOMImplementation("LS");
    LSOutput lsOutput = domImplementationLS.createLSOutput();
    LSSerializer lsSerializer = domImplementationLS.createLSSerializer();
    lsOutput.setEncoding("UTF-8");
    Writer stringWriter = new StringWriter();
    lsOutput.setCharacterStream(stringWriter);
    lsSerializer.write(node, lsOutput);//from   w  w  w .j a v  a  2s .  c om
    String result = stringWriter.toString();
    return result;
}

From source file:nl.cyso.vsphere.client.docs.ManPage.java

private String getSynopsisSection() {
    StringBuilder section = new StringBuilder();
    section.append(".SH SYNOPSIS\n");

    HelpFormatter help = new HelpFormatter();
    help.setSyntaxPrefix("");

    Writer str = new StringWriter();
    PrintWriter pw = new PrintWriter(str);

    help.printUsage(pw, 1000, Version.getVersion().getProjectName(), ConfigModes.getMode("ROOT"));
    section.append(str.toString() + "\n");

    for (String m : ConfigModes.getModes().keySet()) {
        if (m == "ROOT") {
            continue;
        }//from w ww  .j  av a2  s .  c om
        section.append(String.format(".B %s\n", m.toString()));
        str = new StringWriter();
        pw = new PrintWriter(str);
        help.printUsage(pw, 1000, Version.getVersion().getProjectName(), ConfigModes.getMode(m));
        section.append(".RS 4\n");
        section.append(str.toString() + "\n");
        section.append(".RE\n");
    }
    return section.toString().replace("-", "\\-");
}

From source file:org.csploit.android.core.System.java

public static synchronized void errorLogging(Throwable e) {
    String message = "Unknown error.", trace = "Unknown trace.",
            filename = (new File(Environment.getExternalStorageDirectory().toString(), ERROR_LOG_FILENAME))
                    .getAbsolutePath();/*  w ww  .  j a va2s  . co m*/

    if (e != null) {
        if (e.getMessage() != null && !e.getMessage().isEmpty())
            message = e.getMessage();

        else if (e.toString() != null)
            message = e.toString();

        if (message.equals(mLastError))
            return;

        Writer sWriter = new StringWriter();
        PrintWriter pWriter = new PrintWriter(sWriter);

        e.printStackTrace(pWriter);

        trace = sWriter.toString();

        if (mContext != null && getSettings().getBoolean("PREF_DEBUG_ERROR_LOGGING", false)) {
            try {
                FileWriter fWriter = new FileWriter(filename, true);
                BufferedWriter bWriter = new BufferedWriter(fWriter);

                bWriter.write(trace);

                bWriter.close();
            } catch (IOException ioe) {
                Logger.error(ioe.toString());
            }
        }
    }

    setLastError(message);
    Logger.error(message);
    Logger.error(trace);
}

From source file:org.openmrs.module.dhisreport.api.dxf2.DataValueSetTest.java

@Test
public void marshallDataValueSet() throws Exception {
    DataValueSet dvset = new DataValueSet();
    dvset.setDataSet("ANC");
    dvset.setOrgUnit("OU1");
    dvset.setPeriod("2012-09");
    List<DataValue> dataValues = dvset.getDataValues();
    dataValues.add(new DataValue("DE1", "45"));
    dataValues.add(new DataValue("DE2", "45"));
    dataValues.add(new DataValue("DE3", "r543efdgty2", "53"));

    Writer xmlWriter = new StringWriter();
    JAXBContext jaxbContext = JAXBContext.newInstance(DataValueSet.class);

    Marshaller jaxbmarshaller = jaxbContext.createMarshaller();
    jaxbmarshaller.marshal(dvset, xmlWriter);
    String xml = xmlWriter.toString();

    //System.out.println( xml );
    assertEquals("3", xpathTest("count(//d:dataValue)", xml));
    assertEquals("53", xpathTest("//d:dataValue[3]/@value", xml));
    assertEquals("r543efdgty2", xpathTest("//d:dataValue[3]/@categoryOptionCombo", xml));

}

From source file:com.morphoss.acal.service.connector.AcalRequestor.java

public static String convertStreamToString(InputStream in) throws IOException {
    if (in == null)
        return null;
    Writer writer = new StringWriter();
    char[] buffer = new char[1024];
    Reader reader = new BufferedReader(new InputStreamReader(in, "UTF-8"));
    int n;//  w  w w.j  a  va2s.  c om
    while ((n = reader.read(buffer)) != -1) {
        writer.write(buffer, 0, n);
    }
    in.close();
    return writer.toString();
}