Example usage for java.io StringWriter append

List of usage examples for java.io StringWriter append

Introduction

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

Prototype

public StringWriter append(char c) 

Source Link

Document

Appends the specified character to this writer.

Usage

From source file:org.sakaiproject.sgs2.server.GroovyShellServiceImpl.java

public ScriptExecutionResult run(String name, String sourceCode, String secureToken)
        throws RpcSecurityException, Server500Exception {

    isSecure(secureToken);/*from   ww  w . j  av a 2s .  c o m*/

    StringWriter output = new StringWriter();
    Binding binding = new Binding();
    binding.setVariable("out", new PrintWriter(output));

    StringWriter stackTrace = new StringWriter();
    PrintWriter errorWriter = new PrintWriter(stackTrace);

    GroovyShell groovyShell = new GroovyShell(binding);
    Object result = null;
    long start = 0;
    long end = 0;

    try {

        start = System.currentTimeMillis();
        result = groovyShell.evaluate(sourceCode);
        end = System.currentTimeMillis();

    } catch (MultipleCompilationErrorsException e) {

        stackTrace.append(e.getMessage());

    } catch (Throwable t) {

        t.printStackTrace(errorWriter);
    }

    long executionTimeInMillis = 0;

    if (0 != start && 0 != end) {
        executionTimeInMillis = end - start;
    }

    // Persisting script information
    Script script = new Script();
    // Getting userEid. If we cannot find the userId from the userEid, we just log the userEid
    String userEid = userDirectoryService.getCurrentUser().getEid();
    try {
        script.setUserId(userDirectoryService.getUserId(userEid));
    } catch (UserNotDefinedException e1) {
        LOG.error("Was not able to get userId from userEid : userEid = " + userEid);
        script.setUserId(userEid);
    }
    script.setName(name);
    script.setScript(sourceCode);
    script.setOutput((null == output || "".equals(output.toString())) ? null
            : "[" + executionTimeInMillis + "ms] " + output.toString());
    script.setResult((null == result || "".equals(result.toString())) ? null
            : "[" + executionTimeInMillis + "ms] " + result.toString());
    script.setStackTrace(
            (null == stackTrace || "".equals(stackTrace.toString())) ? null : stackTrace.toString());
    script.setActionType(ActionType.SCRIPT_EXECUTION.name);
    script.setActionDate(new Date());

    try {

        groovyShellManager.save(script);
    } catch (Exception e) {
        e.printStackTrace();
        stackTrace.append(e.getMessage());
        LOG.error("Was not able to save script object");
    }

    // Sending result back to the client
    ScriptExecutionResult scriptExecutionResult = new ScriptExecutionResult();
    scriptExecutionResult.setOutput((null == output || "".equals(output.toString())) ? null
            : "[" + executionTimeInMillis + "ms] " + output.toString());
    scriptExecutionResult.setResult((null == result || "".equals(result.toString())) ? null
            : "[" + executionTimeInMillis + "ms] " + result.toString());
    scriptExecutionResult.setStackTrace(
            (null == stackTrace || "".equals(stackTrace.toString())) ? null : stackTrace.toString());

    return scriptExecutionResult;
}

From source file:dk.statsbiblioteket.util.LineReaderTest.java

public void testMonkeyBinarySearch() throws Exception {
    File testFile = File.createTempFile("binarySearch", ".tmp");
    testFile.deleteOnExit();/*  w ww .j  a va2s .co m*/
    Random random = new Random(87);

    int LINES = 50;
    int MINWORDLENGTH = 1;
    int MAXWORDLENGTH = 10;
    int MINCHAR = 32;
    int MAXCHAR = 14200;
    Set<String> lineSet = new HashSet<String>(LINES);
    for (int line = 0; line < LINES; line++) {
        int wordLength = random.nextInt(MAXWORDLENGTH - MINWORDLENGTH) + MINWORDLENGTH;
        StringWriter word = new StringWriter(wordLength);
        for (int i = 0; i < wordLength; i++) {
            word.append((char) (random.nextInt(MAXCHAR - MINCHAR) + MINCHAR));
        }
        lineSet.add(word.toString());
    }

    List<String> lines = new ArrayList<String>(lineSet);
    Collections.sort(lines);
    log.info("Created content: " + Strings.join(lines, "  "));
    StringWriter sw = new StringWriter(MAXWORDLENGTH * LINES);
    for (String word : lines) {
        sw.append(word);
        sw.append("\n");
    }
    String content = sw.toString();
    Files.saveString(content, testFile);

    LineReader reader = new LineReader(testFile, "r");
    int pos = 0;
    for (String word : lines) {
        assertPos(reader, pos, word);
        pos += word.getBytes("utf-8").length + 1;
    }
    reader.close();
}

From source file:com.offbynull.portmapper.upnpigd.UpnpIgdController.java

private Map<String, String> parseResponseXml(String expectedTagName, byte[] data) {
    try {//from ww w  . ja va 2 s.co  m
        MessageFactory factory = MessageFactory.newInstance();
        SOAPMessage soapMessage = factory.createMessage(new MimeHeaders(), new ByteArrayInputStream(data));

        if (soapMessage.getSOAPBody().hasFault()) {
            StringWriter writer = new StringWriter();
            try {
                Transformer transformer = TransformerFactory.newInstance().newTransformer();
                transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
                transformer.transform(new DOMSource(soapMessage.getSOAPPart()), new StreamResult(writer));
            } catch (IllegalArgumentException | TransformerException | TransformerFactoryConfigurationError e) {
                writer.append("Failed to dump fault: " + e);
            }

            throw new ResponseException(writer.toString());
        }

        Iterator<SOAPBodyElement> responseBlockIt = soapMessage.getSOAPBody()
                .getChildElements(new QName(serviceType, expectedTagName));
        if (!responseBlockIt.hasNext()) {
            throw new ResponseException(expectedTagName + " tag missing");
        }

        Map<String, String> ret = new HashMap<>();

        SOAPBodyElement responseNode = responseBlockIt.next();
        Iterator<SOAPBodyElement> responseChildrenIt = responseNode.getChildElements();
        while (responseChildrenIt.hasNext()) {
            SOAPBodyElement param = responseChildrenIt.next();
            String name = StringUtils.trim(param.getLocalName().trim());
            String value = StringUtils.trim(param.getValue().trim());

            ret.put(name, value);
        }

        return ret;
    } catch (IllegalArgumentException | IOException | SOAPException | DOMException e) {
        throw new IllegalStateException(e); // should never happen
    }
}

From source file:org.apache.synapse.mediators.bsf.CommonScriptMessageContext.java

private String serializeJSON(Object obj) {
    StringWriter json = new StringWriter();
    if (obj instanceof Wrapper) {
        obj = ((Wrapper) obj).unwrap();
    }/*from   w w w  .j a v a 2s. c o  m*/

    if (obj instanceof NativeObject) {
        json.append("{");
        NativeObject o = (NativeObject) obj;
        Object[] ids = o.getIds();
        boolean first = true;
        for (Object id : ids) {
            String key = (String) id;
            Object value = o.get((String) id, o);
            if (!first) {
                json.append(", ");
            } else {
                first = false;
            }
            json.append("\"").append(key).append("\" : ").append(serializeJSON(value));
        }
        json.append("}");
    } else if (obj instanceof NativeArray) {
        json.append("[");
        NativeArray o = (NativeArray) obj;
        Object[] ids = o.getIds();
        boolean first = true;
        for (Object id : ids) {
            Object value = o.get((Integer) id, o);
            if (!first) {
                json.append(", ");
            } else {
                first = false;
            }
            json.append(serializeJSON(value));
        }
        json.append("]");
    } else if (obj instanceof Object[]) {
        json.append("[");
        boolean first = true;
        for (Object value : (Object[]) obj) {
            if (!first) {
                json.append(", ");
            } else {
                first = false;
            }
            json.append(serializeJSON(value));
        }
        json.append("]");

    } else if (obj instanceof String) {
        json.append("\"").append(obj.toString()).append("\"");
    } else if (obj instanceof Integer || obj instanceof Long || obj instanceof Float || obj instanceof Double
            || obj instanceof Short || obj instanceof BigInteger || obj instanceof BigDecimal
            || obj instanceof Boolean) {
        json.append(obj.toString());
    } else {
        json.append("{}");
    }
    return json.toString();
}

From source file:com.aurel.track.admin.customize.category.report.execute.ReportBeansToLaTeXConverter.java

/**
 * This method renders inline items based on a macro included in the main
 * template. In the template file the macro must be marked like this: <code>
 * % %%ITP ${Description} ${IssueNo}//from ww  w  .j  a v  a  2s. com
 * </code> The inline macro buffer passed here has the comment part removed.
 *
 * @param context
 * @param inlineMacroBuffer
 */
private static String createProcessedInlineItems(Map<String, Object> context, StringBuilder inlineMacroBuffer) {
    if (inlineMacroBuffer == null || "".equals(inlineMacroBuffer)) {
        return null;
    }

    Template freemarkerTemplate = null;

    StringWriter texWriter = new StringWriter();
    StringBuffer debugMessages = new StringBuffer();
    try {
        debugMessages.append("Creating Freemarker template..." + CRLF);
        Configuration freemarkerConfig = new Configuration();
        freemarkerConfig.setTemplateExceptionHandler(new LaTeXFreemarkerExceptionHandler());
        freemarkerTemplate = new Template("InlineItems", new StringReader(inlineMacroBuffer.toString()),
                freemarkerConfig);
        debugMessages.append("Processing the Freemarker LaTeX template..." + CRLF);
        freemarkerTemplate.process(context, texWriter);
        debugMessages.append("Freemarker LaTeX template processed." + CRLF);
    } catch (Exception e) {
        LOGGER.error("Problem processing template: " + CRLF + debugMessages.toString());
        String st = ExceptionUtils.getStackTrace(e);
        LOGGER.debug(st, e);
        texWriter = new StringWriter();
        texWriter.append(inlineMacroBuffer.toString());

    }

    texWriter.flush();

    return texWriter.toString();
}

From source file:burlov.ultracipher.swing.SwingGuiApplication.java

public void showError(String msg, Throwable e) {
    StringWriter swriter = new StringWriter();
    PrintWriter pwriter = new PrintWriter(swriter, true);
    pwriter.println("<pre>");
    e.printStackTrace(pwriter);/*from   w ww. j a va 2  s .co  m*/

    swriter.append("\n\n======== System properties =======\n");
    swriter.append(createSystemInfo());
    pwriter.println("</pre>");
    pwriter.flush();
    ErrorInfo info = new ErrorInfo("Error", msg, swriter.toString(), null, e, null, null);
    JXErrorPane.showDialog(getMainFrame(), info);
}

From source file:org.dataconservancy.dcs.access.server.RegistryServiceImpl.java

@Override
public String getRO(String roId, String roUrl) throws IOException {
    String orePath = handleNestedRO(roId, roUrl);
    System.out.println(orePath);//from  w w w.  j  av  a 2 s . c o m

    String temp = new java.io.File(orePath).getAbsolutePath();
    String dir = temp.substring(0, temp.lastIndexOf('/'));
    //Convert ORE to SIP

    String sipPath = sipConversion(orePath, dir, roId.substring(roId.lastIndexOf('/') + 1));
    String tempSipPath = sipPath.replace("_sip.xml", "_0.xml");
    IOUtils.copy(new FileInputStream(sipPath), new FileOutputStream(tempSipPath));
    System.out.println(sipPath);
    ResearchObject sip;
    StringWriter tempWriter = new StringWriter();

    try {
        sip = new SeadXstreamStaxModelBuilder().buildSip(new FileInputStream(sipPath));
        new BagUploadServlet().siptoJsonConverter().toXML(new BagUploadServlet().toQueryResult(sip),
                tempWriter);
        tempWriter.append(";" + tempSipPath);
    } catch (InvalidXmlException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    return tempWriter.toString();

}

From source file:org.apache.juddi.adminconsole.hub.UddiAdminHub.java

private String invoke_SyncSubscription(HttpServletRequest parameters) {
    StringBuilder ret = new StringBuilder();
    SyncSubscription sb = new SyncSubscription();

    SyncSubscriptionDetail d = null;//from  w w  w .j  av  a  2  s.c om
    try {
        StringReader sr = new StringReader(parameters.getParameter("invokeSyncSubscriptionXML").trim());
        sb = (JAXB.unmarshal(sr, SyncSubscription.class));
        sb.setAuthInfo(GetToken());
        d = juddi.invokeSyncSubscription(sb);
    } catch (Exception ex) {
        if (isExceptionExpiration(ex)) {
            token = null;
            sb.setAuthInfo(GetToken());
            try {
                d = juddi.invokeSyncSubscription(sb);
            } catch (Exception ex1) {
                return HandleException(ex);
            }

        } else {
            return HandleException(ex);
        }
    }
    if (d != null) {
        ret.append("<pre>");
        StringWriter sw = new StringWriter();
        JAXB.marshal(d, sw);
        sw.append(PrettyPrintXML(sw.toString()));
        ret.append("</pre>");
    } else {
        ret.append("No data returned");
    }
    return ret.toString();
}

From source file:org.dataconservancy.dcs.access.server.RegistryServiceImpl.java

@Override
public String getSip(String roId, String roUrl) throws IOException {
    WebResource webResource = Client.create().resource(roUrl);

    ClientResponse response = webResource.path("resource").path("getsip").path(URLEncoder.encode(roId))
            .get(ClientResponse.class);

    String id = UUID.randomUUID().toString();
    String sipPath = id + "_sip.xml";
    IOUtils.copy(response.getEntityInputStream(), new FileOutputStream(sipPath));

    ResearchObject sip;//from w  w  w  .  j a  v  a 2 s  .com
    StringWriter tempWriter = new StringWriter();

    try {
        sip = new SeadXstreamStaxModelBuilder().buildSip(new FileInputStream(sipPath));
        new BagUploadServlet().siptoJsonConverter().toXML(new BagUploadServlet().toQueryResultNoManifest(sip),
                tempWriter);
        tempWriter.append(";" + sipPath);
    } catch (InvalidXmlException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    return tempWriter.toString();

}

From source file:org.apache.juddi.adminconsole.hub.UddiAdminHub.java

private String save_ClientSubscriptionInfo(HttpServletRequest parameters) {
    StringBuilder ret = new StringBuilder();
    SaveClientSubscriptionInfo sb = new SaveClientSubscriptionInfo();

    if (parameters.getParameter("ClientSubscriptionInfoDetailXML") == null)
        return "No input!";
    ClientSubscriptionInfoDetail d = null;
    try {/*from ww  w  .ja  v a  2s .c o m*/
        StringReader sr = new StringReader(parameters.getParameter("ClientSubscriptionInfoDetailXML").trim());
        sb = (JAXB.unmarshal(sr, SaveClientSubscriptionInfo.class));
        sb.setAuthInfo(GetToken());
        d = juddi.saveClientSubscriptionInfo(sb);
    } catch (Exception ex) {
        if (ex instanceof DispositionReportFaultMessage) {
            DispositionReportFaultMessage f = (DispositionReportFaultMessage) ex;
            if (f.getFaultInfo().countainsErrorCode(DispositionReport.E_AUTH_TOKEN_EXPIRED)) {
                token = null;
                sb.setAuthInfo(GetToken());
                try {
                    d = juddi.saveClientSubscriptionInfo(sb);
                } catch (Exception ex1) {
                    return HandleException(ex);
                }
            }
        } else {
            return HandleException(ex);
        }
    }
    if (d != null) {
        ret.append("<pre>");
        StringWriter sw = new StringWriter();
        JAXB.marshal(d, sw);
        sw.append(PrettyPrintXML(sw.toString()));
        ret.append("</pre>");
    } else {
        ret.append("No data returned");
    }
    return ret.toString();
}