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.ambraproject.service.xml.XMLServiceImpl.java

/**
 * Given an XML Document as input, will return an XML string representing the document after
 * transformation.//w ww .ja  va  2s.c  om
 *
 * @param doc
 * @return XML String of transformed document
 * @throws org.ambraproject.ApplicationException
 */
@Override
public String getTransformedDocument(Document doc) throws ApplicationException {
    String transformedString;
    try {
        if (log.isDebugEnabled())
            log.debug("Applying XSLT transform to the document...");

        final DOMSource domSource = new DOMSource(doc);
        final Transformer transformer = getTranslet(doc);
        final Writer writer = new StringWriter(1000);

        transformer.transform(domSource, new StreamResult(writer));
        transformedString = writer.toString();
    } catch (Exception e) {
        throw new ApplicationException(e);
    }
    return transformedString;
}

From source file:com.quinsoft.zeidon.SerializeOi.java

public void toAttribute(AttributeInstance attribute) {
    Writer writer = toStringWriter();
    write(writer);
    attribute.setValue(writer.toString());
}

From source file:com.liferay.petra.doulos.processor.BaseShellDoulosRequestProcessor.java

protected void execute(ShellStatus shellStatus) throws Exception {
    shellStatus.status = "executing";

    List<String> shellCommandsList = getShellCommands(shellStatus);

    shellCommandsList.add(0, "/bin/bash");
    shellCommandsList.add(1, "-x");
    shellCommandsList.add(2, "-c");

    String[] shellCommands = shellCommandsList.toArray(new String[shellCommandsList.size()]);

    shellStatus.shellCommands = StringUtils.join(shellCommands, "\n");

    ProcessBuilder processBuilder = new ProcessBuilder(shellCommands);

    processBuilder.redirectErrorStream(true);

    Process process = processBuilder.start();

    StringBuilder sb = new StringBuilder();

    String line = null;/*  w w w.  j  a  v  a2  s  .c  o  m*/

    BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(process.getInputStream()));

    while ((line = bufferedReader.readLine()) != null) {
        sb.append(line);
        sb.append("\n");
    }

    bufferedReader.close();

    try {
        if (_log.isDebugEnabled()) {
            _log.debug("Wait for process to finish");
        }

        process.waitFor();

        shellStatus.exitValue = String.valueOf(process.exitValue());
        shellStatus.output = sb.toString();
        shellStatus.status = "finished";
    } catch (Exception e) {
        Writer writer = new StringWriter();

        PrintWriter printWriter = new PrintWriter(writer);

        e.printStackTrace(printWriter);

        shellStatus.exception = writer.toString();

        shellStatus.status = "exception";
    }
}

From source file:eu.learnpad.core.impl.cw.XwikiBridgeInterfaceRestResource.java

@Override
public void notifyRecommendations(String modelSetId, String simulationid, String userId, Recommendations rec)
        throws LpRestException {
    String contentType = "application/xml";

    HttpClient httpClient = this.getClient();
    String uri = String.format("%s/learnpad/cw/bridge/notify/%s", DefaultRestResource.REST_URI, modelSetId);

    PutMethod putMethod = new PutMethod(uri);
    putMethod.addRequestHeader("Accept", contentType);

    NameValuePair[] queryString = new NameValuePair[2];
    queryString[0] = new NameValuePair("simulationid", simulationid);
    queryString[1] = new NameValuePair("userid", userId);
    putMethod.setQueryString(queryString);

    try {//  ww  w.  j  av a 2 s  . c  o m
        JAXBContext jc = JAXBContext.newInstance(Recommendations.class);
        Writer recWriter = new StringWriter();

        Marshaller marshaller = jc.createMarshaller();
        marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
        marshaller.marshal(rec, recWriter);

        RequestEntity requestEntity = new StringRequestEntity(recWriter.toString(), contentType, "UTF-8");
        putMethod.setRequestEntity(requestEntity);

        httpClient.executeMethod(putMethod);
    } catch (JAXBException | IOException e) {
        throw new LpRestExceptionXWikiImpl(e.getMessage(), e.getCause());
    }
}

From source file:com.oneops.boo.ClientConfigInterpolator.java

/**
 * Take key/value pairs of configuration and interpolate a Boo YAML template in straing format
 * with them./*w  ww  .ja v  a  2  s  .  co  m*/
 * 
 * @see ClientConfigInterpolator#interpolate(File, File, String)
 * @param booYaml the template string
 * @param config the key/value pairs
 */
public String interpolate(String booYaml, Map<String, String> config) throws IOException {
    Map<String, Object> mustacheMap = Maps.newHashMap();
    for (Map.Entry<String, String> e : config.entrySet()) {
        String key = e.getKey();
        String value = e.getValue();
        Object mustacheValue;
        if (value.startsWith("\"") && value.endsWith("\"")) {
            mustacheValue = deliteral(value);
        } else if (value.contains(",")) {
            mustacheValue = splitter.split(value);
        } else {
            mustacheValue = value;
        }
        mustacheMap.put(key, mustacheValue);
    }
    Writer writer = new StringWriter();
    NoEncodingMustacheFactory mustacheFactory = new NoEncodingMustacheFactory();
    mustacheFactory.setObjectHandler(new BooReflectionObjectHandler());
    Mustache mustache = mustacheFactory.compile(new StringReader(booYaml), "boo");
    mustache.execute(writer, mustacheMap).flush();
    return writer.toString();
}

From source file:es.upm.dit.gsi.noticiastvi.gtv.item.SetRemoveFavoriteThread.java

public String convertStreamToString(InputStream is) throws IOException {
    /*//  w ww  .  ja  v  a 2 s  .  c om
     * To convert the InputStream to String we use the
     * Reader.read(char[] buffer) method. We iterate until the
     * Reader return -1 which means there's no more data to
     * read. We use the StringWriter class to produce the string.
     */
    if (is != null) {
        Writer writer = new StringWriter();

        char[] buffer = new char[1024];
        try {
            Reader reader = new BufferedReader(new InputStreamReader(is, "UTF-8"));
            int n;
            while ((n = reader.read(buffer)) != -1) {
                writer.write(buffer, 0, n);
            }
        } finally {
            is.close();
        }
        return writer.toString();
    } else {
        return "";
    }
}

From source file:com.murati.oszk.audiobook.model.OfflineJSONSource.java

private JSONObject fetchJSON(String urlString) throws JSONException {
    BufferedReader reader = null;
    try {//w w w. ja v  a 2s  .  c o m
        InputStream is = getContext().getResources().openRawResource(R.raw.offline_catalog);
        Writer writer = new StringWriter();
        char[] buffer = new char[1024];
        try {
            reader = new BufferedReader(new InputStreamReader(is, "UTF-8"));
            int n;
            while ((n = reader.read(buffer)) != -1) {
                writer.write(buffer, 0, n);
            }
        } finally {
            is.close();
        }
        return new JSONObject(writer.toString());
    } catch (JSONException e) {
        throw e;
    } catch (Exception e) {
        LogHelper.e(TAG, "Failed to parse the json for media list", e);
        return null;
    } finally {
        if (reader != null) {
            try {
                reader.close();
            } catch (IOException e) {
                // ignore
            }
        }
    }
}

From source file:eu.learnpad.core.impl.cw.XwikiBridgeInterfaceRestResource.java

@Override
public void notifyScoreUpdate(ScoreRecord record) throws LpRestException {
    String contentType = "application/xml";
    HttpClient httpClient = this.getClient();
    String uri = String.format("%s/learnpad/cw/bridge/scores", DefaultRestResource.REST_URI);
    PostMethod postMethod = new PostMethod(uri);
    postMethod.addRequestHeader(HttpHeaders.CONTENT_TYPE, contentType);

    try {/*from  w w  w . ja  va 2 s  . co  m*/
        JAXBContext jc = JAXBContext.newInstance(ScoreRecord.class);
        Writer marshalledRecord = new StringWriter();

        Marshaller marshaller = jc.createMarshaller();
        marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
        marshaller.marshal(record, marshalledRecord);

        postMethod.setRequestEntity(new StringRequestEntity(marshalledRecord.toString(), contentType, "UTF-8"));

        httpClient.executeMethod(postMethod);
    } catch (JAXBException e1) {
        e1.printStackTrace();
    } catch (UnsupportedEncodingException e1) {
        e1.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

}

From source file:com.polyvi.xface.extension.XExtensionManager.java

/**
 * ???umeng?// w  ww.j  ava 2s . c  o m
 * 
 * @param e
 */
public void reportError(Exception e) {
    try {
        // ?Writer
        Writer writer = new StringWriter();
        PrintWriter printWriter = new PrintWriter(writer);
        e.printStackTrace(printWriter);
        printWriter.flush();
        writer.flush();
        String stackTrackInfo = writer.toString();
        printWriter.close();
        writer.close();
        MobclickAgent.reportError(mExtensionContext.getSystemContext().getContext(), stackTrackInfo);
    } catch (IOException ioE) {
        XLog.e(CLASS_NAME, ioE.getMessage());
    } catch (Exception genericE) {
        XLog.e(CLASS_NAME, genericE.getMessage());
    }
}

From source file:com.glaf.jbpm.web.springmvc.MxJbpmStartProcessController.java

@RequestMapping
public ModelAndView startProcess(HttpServletRequest request, HttpServletResponse response) throws Exception {
    Map<String, Object> paramMap = RequestUtils.getParameterMap(request);
    logger.debug(paramMap);/*from   ww  w  .j  a  v a  2 s  . co m*/
    String json = RequestUtils.getStringValue(request, "json");
    String rowId = RequestUtils.getStringValue(request, "rowId");
    String processName = RequestUtils.getStringValue(request, "processName");
    String actorId = RequestUtils.getActorId(request);
    ProcessContainer container = ProcessContainer.getContainer();
    Long processInstanceId = null;

    if (StringUtils.isNotEmpty(rowId) && StringUtils.isNotEmpty(processName)
            && StringUtils.isNotEmpty(actorId)) {
        ProcessContext ctx = new ProcessContext();
        ctx.setRowId(rowId);
        ctx.setActorId(actorId);
        ctx.setTitle("???" + rowId);
        ctx.setProcessName(processName);

        /**
         * ??json?.<br>
         * {money:100000,day:5,pass:true,deptId:"123", roleId:"R001"}
         */
        if (StringUtils.isNotEmpty(json)) {
            Map<String, Object> jsonMap = JsonUtils.decode(json);
            if (jsonMap != null && jsonMap.size() > 0) {
                Set<Entry<String, Object>> entrySet = jsonMap.entrySet();
                for (Entry<String, Object> entry : entrySet) {
                    String name = entry.getKey();
                    Object value = entry.getValue();
                    if (name != null && value != null) {
                        if (name != null && value != null) {
                            DataField dataField = new DataField();
                            dataField.setName(name);
                            dataField.setValue(value);
                            ctx.addDataField(dataField);
                        }
                    }
                }
            }
        }
        try {
            processInstanceId = container.startProcess(ctx);
            if (processInstanceId != null) {
                request.setAttribute("processInstanceId", processInstanceId);
                request.setAttribute("statusCode", 200);
                request.setAttribute("message", ViewProperties.getString("res_submit_ok"));
            } else {
                request.setAttribute("statusCode", 500);
                request.setAttribute("message", ViewProperties.getString("res_submit_error"));
            }

            logger.debug("processInstanceId:" + processInstanceId);
        } catch (Exception ex) {
            request.setAttribute("statusCode", 500);
            request.setAttribute("message", ViewProperties.getString("res_submit_error"));
            if (LogUtils.isDebug()) {
                ex.printStackTrace();
                logger.debug(ex);
            }
        }
    }

    /**
     * ??jsonxml???<br>
     * 200-? <br>
     * 500-<br>
     */
    String responseDataType = RequestUtils.getStringValue(request, "responseDataType");
    if (StringUtils.equals(responseDataType, "json")) {
        String encoding = request.getParameter("encoding");
        if (encoding == null) {
            encoding = "UTF-8";
        }
        request.setCharacterEncoding(encoding);
        response.setCharacterEncoding(encoding);
        response.setContentType("text/plain;charset=" + encoding);
        Map<String, Object> jsonMap = new java.util.HashMap<String, Object>();
        if (processInstanceId != null) {
            jsonMap.put("statusCode", 200);
            jsonMap.put("success", "true");
            jsonMap.put("data", ViewProperties.getString("res_submit_ok"));
            jsonMap.put("message", ViewProperties.getString("res_submit_ok"));
        } else {
            jsonMap.put("statusCode", 500);
            jsonMap.put("success", "false");
            jsonMap.put("data", ViewProperties.getString("res_submit_error"));
            jsonMap.put("message", ViewProperties.getString("res_submit_error"));
        }
        JSONObject object = new JSONObject(jsonMap);
        response.getWriter().write(object.toString());
        return null;
    } else if (StringUtils.equals(responseDataType, "xml")) {
        String encoding = request.getParameter("encoding");
        if (encoding == null) {
            encoding = "UTF-8";
        }
        request.setCharacterEncoding(encoding);
        response.setCharacterEncoding(encoding);
        response.setContentType("text/xml;charset=" + encoding);
        StringBuffer buffer = new StringBuffer();
        buffer.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
        buffer.append("<response>");
        if (processInstanceId != null) {
            buffer.append("\n    <statusCode>200</statusCode>");
            buffer.append("\n    <message>").append(ViewProperties.getString("res_submit_ok"))
                    .append("</message>");
        } else {
            buffer.append("\n    <statusCode>500</statusCode>");
            buffer.append("\n    <message>").append(ViewProperties.getString("res_submit_error"))
                    .append("</message>");
        }
        buffer.append("\n</response>");
        response.getWriter().write(buffer.toString());
        return null;
    }

    /**
     * ?????<br>
     * ?????_start_template??jbpm_start_template
     * WEB-INF\conf\extension??
     */
    String templateId = RequestUtils.getStringValue(request, "x_templateId");

    if (StringUtils.isEmpty(templateId)) {
        templateId = CustomProperties.getString(processName + "_start_template");
    }
    if (StringUtils.isEmpty(templateId)) {
        templateId = CustomProperties.getString("jbpm_start_template");
    }
    if (StringUtils.isNotEmpty(templateId)) {

        Map<String, Object> context = new java.util.HashMap<String, Object>();
        context.putAll(paramMap);
        context.put("actorId", actorId);
        context.put("processInstanceId", processInstanceId);
        context.put("contextPath", request.getContextPath());

        if (processInstanceId != null) {
            context.put("statusCode", 200);
            context.put("message", ViewProperties.getString("res_submit_ok"));
        } else {
            context.put("statusCode", 500);
            context.put("message", ViewProperties.getString("res_submit_error"));
        }
        try {
            logger.debug(context);
            Writer writer = new StringWriter();
            TemplateUtils.evaluate(templateId, context, writer);
            request.setAttribute("templateScript", writer.toString());
            String encoding = request.getParameter("encoding");
            if (encoding == null) {
                encoding = "UTF-8";
            }
            request.setCharacterEncoding(encoding);
            response.setCharacterEncoding(encoding);
            response.setContentType("text/html;charset=" + encoding);
            response.getWriter().write(writer.toString());
            return null;
        } catch (Exception ex) {
            if (LogUtils.isDebug()) {
                ex.printStackTrace();
                logger.debug(ex);
            }
        }
    }

    String view = request.getParameter("view");
    if (StringUtils.isNotEmpty(view)) {
        return new ModelAndView(view);
    }

    String x_view = ViewProperties.getString("jbpm_start.startProcess");
    if (StringUtils.isNotEmpty(x_view)) {
        return new ModelAndView(x_view);
    }

    return new ModelAndView("/jbpm/start");
}