Example usage for java.io CharArrayWriter CharArrayWriter

List of usage examples for java.io CharArrayWriter CharArrayWriter

Introduction

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

Prototype

public CharArrayWriter() 

Source Link

Document

Creates a new CharArrayWriter.

Usage

From source file:edu.duke.cabig.c3pr.domain.scheduler.runtime.job.CCTSNotificationMessageJob.java

private String serialize(Notification notification) {
    try {/*from  w ww.  ja  va  2  s .c  o  m*/
        JAXBContext context = JAXBContext.newInstance(Notification.class);
        Marshaller m = context.createMarshaller();
        m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
        JAXBElement<Notification> jaxbElement = new JAXBElement<Notification>(
                new QName(CCTS_NOTIFICATIONS_NS, "notification"), Notification.class, notification);
        CharArrayWriter writer = new CharArrayWriter();
        m.marshal(jaxbElement, writer);
        return String.valueOf(writer.toCharArray());
    } catch (JAXBException e) {
        throw new RuntimeException(e);
    }

}

From source file:org.apache.solr.client.solrj.impl.BackupRequestLBHttpSolrServer.java

@Override
protected Exception addZombie(HttpSolrServer server, Exception e) {
    CharArrayWriter cw = new CharArrayWriter();
    PrintWriter pw = new PrintWriter(cw);
    e.printStackTrace(pw);//from   ww  w .j a  v  a 2 s  .c  o m
    pw.flush();
    String stack = cw.toString();
    log.info("Server :{} did not respond correctly or timed out, the server is zombied. {}", server.baseUrl,
            e.toString() + stack);
    return super.addZombie(server, e);
}

From source file:org.rhq.plugins.agent.AgentServerComponent.java

public OperationResult invokeOperation(String name, Configuration params) {
    OperationResult result = null;/*  w  w  w  . jav  a 2 s  .c o m*/

    // I know all operation names have identical MBean operations on the agent management MBean
    // I also know about all operations that have void and non-void parameters
    try {
        if ((params == null) || (params.getProperties().size() == 0)) {
            result = (OperationResult) getAgentBean().getOperation(name).invoke();
        } else {
            if (name.equals("retrievePluginInfo")) {
                String pluginToUpdate = params.getSimple("pluginName").getStringValue();
                result = (OperationResult) getAgentBean().getOperation(name).invoke(pluginToUpdate);
            } else if (name.equals("executeAvailabilityScan")) {
                Boolean changesOnly = params.getSimple("changesOnly").getBooleanValue();
                result = (OperationResult) getAgentBean().getOperation(name).invoke(changesOnly);
            } else if (name.equals("retrieveCurrentDateTime")) {
                String timeZone = params.getSimple("timeZone").getStringValue();
                result = new OperationResult();
                result.getComplexResults().put(
                        new PropertySimple("dateTime", getAgentBean().getOperation(name).invoke(timeZone)));
            } else if (name.equals("setDebugMode")) {
                Boolean enabled = params.getSimple("enabled").getBooleanValue();
                Boolean traceMessaging = params.getSimple("traceMessaging").getBooleanValue();
                result = new OperationResult();
                getAgentBean().getOperation(name).invoke(enabled, traceMessaging);
            } else if (name.equals("executePromptCommand")) {
                String command = params.getSimple("command").getStringValue();
                result = new OperationResult();
                try {
                    Object output = getAgentBean().getOperation(name).invoke(command);
                    result.getComplexResults().put(new PropertySimple("output", output));
                } catch (EmsInvocationException eie) {
                    if (eie.getCause() instanceof MBeanException
                            && eie.getCause().getCause() instanceof ExecutionException) {
                        // the prompt command threw the exception - in this case:
                        // the message is the prompt output and the cause is the actual prompt exception
                        ExecutionException ee = (ExecutionException) eie.getCause().getCause();
                        String output = ee.getMessage();
                        CharArrayWriter caw = new CharArrayWriter();
                        ee.getCause().printStackTrace(new PrintWriter(caw));
                        String error = caw.toString();
                        result.getComplexResults().put(new PropertySimple("output", output));
                        result.getComplexResults().put(new PropertySimple("error", error));
                    } else {
                        throw eie;
                    }
                }
            } else if (name.equals("switchToServer")) {
                String server = params.getSimpleValue("server", null);
                getAgentBean().getOperation(name).invoke(server);
            } else {
                // this should really never happen
                throw new IllegalArgumentException("Operation [" + name + "] does not support params");
            }
        }
    } catch (Exception e) {
        throw new RuntimeException("Failed to invoke operation [" + name + "]", e);
    }
    return result;
}

From source file:opendap.aws.glacier.BesMetadataExtractor.java

private static String runSysCommand(String sysCmd) throws IOException {

    Process p = null;//from ww w  .  j a v  a2 s . c o  m

    try {
        System.out.println("COMMAND: " + sysCmd);

        Runtime rt = Runtime.getRuntime();
        p = rt.exec(sysCmd.toString());
        InputStream in = p.getInputStream();
        OutputStream out = p.getOutputStream();
        InputStream err = p.getErrorStream();

        CharArrayWriter caw = new CharArrayWriter();

        IOUtils.copy(in, caw);
        IOUtils.copy(err, System.err);

        return caw.toString();
    } finally {
        if (p != null)
            p.destroy();
    }

}

From source file:org.apache.catalina.logger.LoggerBase.java

/**
 * Writes an explanatory message and a stack trace for a given
 * <code>Throwable</code> exception to the servlet log file.  The name
 * and type of the servlet log file is specific to the servlet container,
 * usually an event log.  This message will be logged unconditionally.
 *
 * @param msg A <code>String</code> that describes the error or
 *  exception//from  w  w  w .  ja v  a2  s.  co  m
 * @param throwable The <code>Throwable</code> error or exception
 */
public void log(String msg, Throwable throwable) {

    CharArrayWriter buf = new CharArrayWriter();
    PrintWriter writer = new PrintWriter(buf);
    writer.println(msg);
    throwable.printStackTrace(writer);
    Throwable rootCause = null;
    if (throwable instanceof LifecycleException)
        rootCause = ((LifecycleException) throwable).getThrowable();
    else if (throwable instanceof ServletException)
        rootCause = ((ServletException) throwable).getRootCause();
    if (rootCause != null) {
        writer.println("----- Root Cause -----");
        rootCause.printStackTrace(writer);
    }
    log(buf.toString());

}

From source file:org.couch4j.http.HttpConnectionManager.java

private JSONObject fromResponseStream(HttpEntity entity) throws IOException {
    InputStream is = entity.getContent();
    Reader reader = new InputStreamReader(is, EntityUtils.getContentCharSet(entity));
    CharArrayWriter w = new CharArrayWriter();
    StreamUtils.copy(reader, w);//from   w  ww .j a v a2 s  .com
    JSONObject json = JSONObject.fromObject(w.toString());
    StreamUtils.closeSilently(reader);
    StreamUtils.closeSilently(w);
    entity.consumeContent(); // finish
    return json;
}

From source file:org.roda.core.common.RodaUtils.java

public static Reader applyEventStylesheet(Binary binary, boolean onlyDetails, Map<String, String> translations,
        String path) throws GenericException {
    try (Reader descMetadataReader = new InputStreamReader(
            new BOMInputStream(binary.getContent().createInputStream()))) {

        XMLReader xmlReader = XMLReaderFactory.createXMLReader();
        xmlReader.setEntityResolver(new RodaEntityResolver());
        InputSource source = new InputSource(descMetadataReader);
        Source text = new SAXSource(xmlReader, source);

        XsltExecutable xsltExecutable = EVENT_CACHE.get(path);

        XsltTransformer transformer = xsltExecutable.load();
        CharArrayWriter transformerResult = new CharArrayWriter();

        transformer.setSource(text);//  w w w.  j a v a  2  s  .  c o  m
        transformer.setDestination(PROCESSOR.newSerializer(transformerResult));

        // send param to filter stylesheet work
        transformer.setParameter(new QName("onlyDetails"), new XdmAtomicValue(Boolean.toString(onlyDetails)));

        for (Entry<String, String> parameter : translations.entrySet()) {
            QName qName = new QName(parameter.getKey());
            XdmValue xdmValue = new XdmAtomicValue(parameter.getValue());
            transformer.setParameter(qName, xdmValue);
        }

        transformer.transform();
        return new CharArrayReader(transformerResult.toCharArray());
    } catch (IOException | SAXException | ExecutionException | SaxonApiException e) {
        LOGGER.error(e.getMessage(), e);
        throw new GenericException("Could not process event binary " + binary.getStoragePath(), e);
    }
}

From source file:phex.common.log.PhexLogger.java

/**
 * Gets the stack trace of an exception as string.
 * @param       aThrowable  the Throwable
 * @return      the stack trace of the exception
 *//*from  www .  j av a  2s.c  o m*/
private static String getStackTrace(Throwable aThrowable) {
    CharArrayWriter buffer = new CharArrayWriter();
    PrintWriter printWriter = new PrintWriter(buffer);

    // recursively print nested exceptions to a String
    while (aThrowable != null) {
        aThrowable.printStackTrace(printWriter);

        if (aThrowable instanceof InvocationTargetException) {
            aThrowable = ((InvocationTargetException) aThrowable).getTargetException();
        } else {
            aThrowable = null;
        }
    }
    return buffer.toString();
}

From source file:org.couch4j.http.HttpConnectionManager.java

private JSONArray arrayFromResponseStream(HttpEntity entity) throws IOException {
    InputStream is = entity.getContent();
    Reader reader = new InputStreamReader(is, EntityUtils.getContentCharSet(entity));
    CharArrayWriter w = new CharArrayWriter();
    StreamUtils.copy(reader, w);/*from  w ww . ja v a2 s.co m*/
    JSONArray json = JSONArray.fromObject(w.toString());
    StreamUtils.closeSilently(reader);
    StreamUtils.closeSilently(w);
    entity.consumeContent(); // finish
    return json;
}

From source file:com.jigsforjava.string.StringUtils.java

/**
 * Converts a camel case string into a lower-case, delimiter-separated
 * string. For example, a call of toSeparatedString("ACamelCaseString, '_')
 * returns a_camel_case_string./*from  w  ww.ja v  a2 s.  c  o m*/
 * 
 * @param camelCaseString
 *            a String in camel case to delimit.
 * @param delimiter
 *            the character used to separate the string.
 * @return a String where capitals in the original are prefixed with the
 *         given delimiter.
 */
public static String toSeparatedString(String camelCaseString, char delimiter) {
    CharArrayWriter result = new CharArrayWriter();
    char[] chars = camelCaseString.toCharArray();

    for (int i = 0; i < chars.length; ++i) {
        if (chars[i] != delimiter && Character.isUpperCase(chars[i]) && i > 0) {
            if ((i < chars.length - 1) && (!Character.isUpperCase(chars[i + 1]) && chars[i + 1] != delimiter)
                    && chars[i - 1] != delimiter)
                result.write(delimiter);
            else if (!Character.isUpperCase(chars[i - 1]) && chars[i - 1] != delimiter)
                result.write(delimiter);
        }

        result.write(chars[i]);
    }

    return result.toString().toLowerCase();
}