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:org.jabsorb.JSONRPCResult.java

public String toString() {
    JSONObject o = new JSONObject();

    try {//www .  j  a  v  a 2 s . c  o m
        if (errorCode == CODE_SUCCESS) {
            o.put("id", id);
            o.put("result", result);
            if (fixUps != null && fixUps.size() > 0) {
                JSONArray fixups = new JSONArray();
                for (Iterator i = fixUps.iterator(); i.hasNext();) {
                    FixUp fixup = (FixUp) i.next();
                    fixups.put(fixup.toJSONArray());
                }
                o.put("fixups", fixups);
            }
        } else if (errorCode == CODE_REMOTE_EXCEPTION) {
            o.put("id", id);
            if (result instanceof Throwable) {
                Throwable e = (Throwable) result;
                CharArrayWriter caw = new CharArrayWriter();
                e.printStackTrace(new PrintWriter(caw));
                JSONObject err = new JSONObject();
                err.put("code", new Integer(errorCode));
                err.put("msg", e.getMessage());
                err.put("trace", caw.toString());
                o.put("error", err);
            } else {
                // When using a customized implementation of ExceptionTransformer
                // an error result may be something other than Throwable. In this
                // case, it has to be a JSON compatible object, we will just store it
                // to the 'error' property of the response. 
                o.put("error", result);
            }
        } else {
            JSONObject err = new JSONObject();
            err.put("code", new Integer(errorCode));
            err.put("msg", result);
            o.put("id", id);
            o.put("error", err);
        }
    } catch (JSONException e) {
        // this would have been a null pointer exception in the previous json.org library.
        throw (RuntimeException) new RuntimeException(e.getMessage()).initCause(e);
    }
    return o.toString();
}

From source file:org.apache.jasper.compiler.JspReader.java

String getText(Mark start, Mark stop) throws JasperException {
    Mark oldstart = mark();// w  ww  .j av  a  2 s.  co  m
    reset(start);
    CharArrayWriter caw = new CharArrayWriter();
    while (!stop.equals(mark()))
        caw.write(nextChar());
    caw.close();
    reset(oldstart);
    return caw.toString();
}

From source file:org.jabsorb.ng.JSONRPCResult.java

@Override
public String toString() {

    final JSONObject o = new JSONObject();

    try {// w  w w  . ja  v  a  2s. c  om
        if (errorCode == CODE_SUCCESS) {
            o.put("id", id);
            o.put("result", result);
            if (fixUps != null && fixUps.size() > 0) {
                final JSONArray fixups = new JSONArray();
                for (final Iterator<FixUp> i = fixUps.iterator(); i.hasNext();) {
                    final FixUp fixup = i.next();
                    fixups.put(fixup.toJSONArray());
                }
                o.put("fixups", fixups);
            }
        } else if (errorCode == CODE_REMOTE_EXCEPTION) {
            o.put("id", id);
            if (result instanceof Throwable) {
                final Throwable e = (Throwable) result;
                final CharArrayWriter caw = new CharArrayWriter();
                e.printStackTrace(new PrintWriter(caw));
                final JSONObject err = new JSONObject();
                err.put("code", new Integer(errorCode));
                err.put("message", e.getMessage());
                err.put("trace", caw.toString());

                // PATCH: Add the Java exception class hint
                err.put("javaClass", e.getClass().getName());

                o.put("error", err);
            } else {
                // When using a customized implementation of
                // ExceptionTransformer
                // an error result may be something other than Throwable. In
                // this
                // case, it has to be a JSON compatible object, we will just
                // store it
                // to the 'error' property of the response.
                o.put("error", result);
            }
        } else {
            final JSONObject err = new JSONObject();
            err.put("code", new Integer(errorCode));
            err.put("message", result);
            o.put("id", id);
            o.put("error", err);
        }
    } catch (final JSONException e) {
        // this would have been a null pointer exception in the previous
        // json.org library.
        throw (RuntimeException) new RuntimeException(e.getMessage()).initCause(e);
    }
    return o.toString();
}

From source file:hm.binkley.util.XProperties.java

/**
 * Note {@code XProperties} description for additional features over plain
 * properties loading. {@inheritDoc}//from  w  w w . ja v a  2  s  .  c  o m
 *
 * @throws IOException if the properties cannot be loaded or if included
 * resources cannot be read
 */
@Override
public synchronized void load(@Nonnull final Reader reader) throws IOException {
    final ResourcePatternResolver loader = new PathMatchingResourcePatternResolver();
    try (final CharArrayWriter writer = new CharArrayWriter()) {
        try (final BufferedReader lines = new BufferedReader(reader)) {
            for (String line = lines.readLine(); null != line; line = lines.readLine()) {
                writer.append(line).append('\n');
                final Matcher matcher = include.matcher(line);
                if (matcher.matches())
                    for (final String x : comma.split(substitutor.replace(matcher.group(1))))
                        for (final Resource resource : loader.getResources(x)) {
                            final URI uri = resource.getURI();
                            if (!included.add(uri))
                                throw new RecursiveIncludeException(uri, included);
                            try (final InputStream in = resource.getInputStream()) {
                                load(in);
                            }
                        }
            }
        }

        super.load(new CharArrayReader(writer.toCharArray()));
    }
    included.clear();
}

From source file:org.topazproject.ambra.auth.web.UsernameReplacementWithGuidFilter.java

public CharResponseWrapper(final HttpServletResponse response) {
    super(response);
    output = new CharArrayWriter();
}

From source file:org.hippoecm.repository.PdfExtractedTextWithLineBreaksAreIndexedCorrectlyTest.java

private void createDocumentWithPdf(String name, String lineSeparator) throws Exception {

    Node handle = testPath.addNode(name, HippoNodeType.NT_HANDLE);
    Node document = handle.addNode(name, NT_SEARCHDOCUMENT);

    Node compound = document.addNode("substructure", NT_COMPOUNDSTRUCTURE);
    Node resource = compound.addNode("hippo:testresource", "hippo:resource");

    {/*w  ww . j  av a2s  .  c  om*/
        resource.setProperty("jcr:encoding", "UTF-8");
        resource.setProperty("jcr:mimeType", "application/pdf");
        InputStream pdf = this.getClass().getResourceAsStream(WORDS_ON_NEW_LINE_WITHOUT_SPACES);
        resource.setProperty("jcr:data", new BinaryImpl(new BufferedInputStream(pdf)));
        resource.setProperty("jcr:lastModified", Calendar.getInstance());
    }
    {
        InputStream pdf = this.getClass().getResourceAsStream(WORDS_ON_NEW_LINE_WITHOUT_SPACES);
        try {
            PDFParser parser = new PDFParser(new BufferedInputStream(pdf));
            PDDocument pdDocument = null;
            try {
                parser.parse();
                pdDocument = parser.getPDDocument();
                CharArrayWriter writer = new CharArrayWriter();

                PDFTextStripper stripper = new PDFTextStripper();
                if (lineSeparator != null) {
                    stripper.setLineSeparator(lineSeparator);
                }
                stripper.writeText(pdDocument, writer);

                StringBuilder extracted = new StringBuilder();
                extracted.append(writer.toCharArray());
                // make sure to store it as UTF-8
                InputStream extractedStream = IOUtils.toInputStream(extracted.toString(), "UTF-8");
                resource.setProperty("hippo:text",
                        resource.getSession().getValueFactory().createBinary(extractedStream));
            } finally {
                try {
                    if (pdDocument != null) {
                        pdDocument.close();
                    }
                } catch (IOException e) {
                    // ignore
                }
            }
        } catch (Exception e) {
            // it may happen that PDFParser throws a runtime
            // exception when parsing certain pdf documents

            // we set empty text:
            final ByteArrayInputStream emptyByteArrayInputStream = new ByteArrayInputStream(new byte[0]);
            resource.setProperty("hippo:text",
                    resource.getSession().getValueFactory().createBinary(emptyByteArrayInputStream));

        } finally {
            pdf.close();
        }
    }
    testPath.getSession().save();
}

From source file:org.apache.struts2.views.freemarker.FreemarkerResult.java

/**
 * Execute this result, using the specified template locationArg.
 * <p/>/*from w  w w .  j  a v a  2 s .  com*/
 * The template locationArg has already been interoplated for any variable substitutions
 * <p/>
 * this method obtains the freemarker configuration and the object wrapper from the provided hooks.
 * It them implements the template processing workflow by calling the hooks for
 * preTemplateProcess and postTemplateProcess
 */
public void doExecute(String locationArg, ActionInvocation invocation) throws IOException, TemplateException {
    this.location = locationArg;
    this.invocation = invocation;
    this.configuration = getConfiguration();
    this.wrapper = getObjectWrapper();

    ActionContext ctx = invocation.getInvocationContext();
    HttpServletRequest req = (HttpServletRequest) ctx.get(ServletActionContext.HTTP_REQUEST);

    if (!locationArg.startsWith("/")) {
        String base = ResourceUtil.getResourceBase(req);
        locationArg = base + "/" + locationArg;
    }

    Template template = configuration.getTemplate(locationArg, deduceLocale());
    TemplateModel model = createModel();

    // Give subclasses a chance to hook into preprocessing
    if (preTemplateProcess(template, model)) {
        try {
            // Process the template
            Writer writer = getWriter();
            if (isWriteIfCompleted() || configuration
                    .getTemplateExceptionHandler() == TemplateExceptionHandler.RETHROW_HANDLER) {
                CharArrayWriter parentCharArrayWriter = (CharArrayWriter) req
                        .getAttribute(PARENT_TEMPLATE_WRITER);
                boolean isTopTemplate = false;
                if (isTopTemplate = (parentCharArrayWriter == null)) {
                    //this is the top template
                    parentCharArrayWriter = new CharArrayWriter();
                    //set it in the request because when the "action" tag is used a new VS and ActionContext is created
                    req.setAttribute(PARENT_TEMPLATE_WRITER, parentCharArrayWriter);
                }

                try {
                    template.process(model, parentCharArrayWriter);

                    if (isTopTemplate) {
                        parentCharArrayWriter.flush();
                        parentCharArrayWriter.writeTo(writer);
                    }
                } catch (TemplateException e) {
                    if (LOG.isErrorEnabled()) {
                        LOG.error("Error processing Freemarker result!", e);
                    }
                    throw e;
                } catch (IOException e) {
                    if (LOG.isErrorEnabled()) {
                        LOG.error("Error processing Freemarker result!", e);
                    }
                    throw e;
                } finally {
                    if (isTopTemplate && parentCharArrayWriter != null) {
                        req.removeAttribute(PARENT_TEMPLATE_WRITER);
                        parentCharArrayWriter.close();
                    }
                }
            } else {
                template.process(model, writer);
            }
        } finally {
            // Give subclasses a chance to hook into postprocessing
            postTemplateProcess(template, model);
        }
    }
}

From source file:IOUtils.java

/**
 * Get the contents of an <code>InputStream</code> as a character array
 * using the default character encoding of the platform.
 * <p>/*w  ww.  ja v a2  s  .c o  m*/
 * This method buffers the input internally, so there is no need to use a
 * <code>BufferedInputStream</code>.
 * 
 * @param is  the <code>InputStream</code> to read from
 * @return the requested character array
 * @throws NullPointerException if the input is null
 * @throws IOException if an I/O error occurs
 * @since Commons IO 1.1
 */
public static char[] toCharArray(InputStream is) throws IOException {
    CharArrayWriter output = new CharArrayWriter();
    copy(is, output);
    return output.toCharArray();
}

From source file:com.aoyetech.fee.commons.utils.IOUtils.java

/**
 * Get the contents of an <code>InputStream</code> as a character array
 * using the default character encoding of the platform.
 * <p>/*from   ww w.  ja va  2s.  c  om*/
 * This method buffers the input internally, so there is no need to use a
 * <code>BufferedInputStream</code>.
 * 
 * @param is the <code>InputStream</code> to read from
 * @return the requested character array
 * @throws NullPointerException if the input is null
 * @throws IOException if an I/O error occurs
 * @since Commons IO 1.1
 */
public static char[] toCharArray(final InputStream is) throws IOException {
    final CharArrayWriter output = new CharArrayWriter();
    copy(is, output);
    return output.toCharArray();
}

From source file:net.ontopia.topicmaps.nav2.servlets.DataIntegrationServlet.java

public TopicMapIF transformRequest(String transformId, InputStream xmlstream, LocatorIF base) throws Exception {

    InputStream xsltstream = StreamUtils.getInputStream("classpath:" + transformId + ".xsl");
    if (xsltstream == null)
        throw new ServletException("Could not find style sheet '" + transformId + ".xsl'");

    // set up source and target streams
    // Source xmlSource = new StreamSource(xmlstream);
    Source xmlSource = new StreamSource(xmlstream);
    Source xsltSource = new StreamSource(xsltstream);

    // the factory pattern supports different XSLT processors
    TransformerFactory transFact = TransformerFactory.newInstance();
    Transformer trans = transFact.newTransformer(xsltSource);

    CharArrayWriter cw = new CharArrayWriter();
    trans.transform(xmlSource, new StreamResult(cw));
    CharArrayReader cr = new CharArrayReader(cw.toCharArray());

    TopicMapStoreIF store = new InMemoryTopicMapStore();
    TopicMapIF topicmap = store.getTopicMap();
    store.setBaseAddress(base);//from  w  ww .  j  a v a2s .  co m
    XTMTopicMapReader xr = new XTMTopicMapReader(cr, base);
    xr.setValidation(false);
    xr.importInto(topicmap);

    return topicmap;
}