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.apache.jasper.compiler.JspReader.java

/**
 * Push a file (and its associated Stream) on the file stack.  THe
 * current position in the current file is remembered.
 *//*from w  w  w  . j  a  va  2s .  co  m*/
private void pushFile(String file, String encoding, InputStreamReader reader)
        throws JasperException, FileNotFoundException {

    // Register the file
    String longName = file;

    int fileid = registerSourceFile(longName);

    if (fileid == -1) {
        err.jspError("jsp.error.file.already.registered", file);
    }

    currFileId = fileid;

    try {
        CharArrayWriter caw = new CharArrayWriter();
        char buf[] = new char[1024];
        for (int i = 0; (i = reader.read(buf)) != -1;)
            caw.write(buf, 0, i);
        caw.close();
        if (current == null) {
            current = new Mark(this, caw.toCharArray(), fileid, getFile(fileid), master, encoding);
        } else {
            current.pushStream(caw.toCharArray(), fileid, getFile(fileid), longName, encoding);
        }
    } catch (Throwable ex) {
        log.error("Exception parsing file ", ex);
        // Pop state being constructed:
        popFile();
        err.jspError("jsp.error.file.cannot.read", file);
    } finally {
        if (reader != null) {
            try {
                reader.close();
            } catch (Exception any) {
            }
        }
    }
}

From source file:com.alvermont.terraj.stargen.ui.SystemFrame.java

private void detailsMenuItemActionPerformed(java.awt.event.ActionEvent evt)//GEN-FIRST:event_detailsMenuItemActionPerformed
{//GEN-HEADEREND:event_detailsMenuItemActionPerformed

    try {//ww w .  j  a  v a  2  s.  c  o m
        Configuration cfg = new Configuration();
        // Specify the data source where the template files come from.
        cfg.setClassForTemplateLoading(TemplateTest.class, "/com/alvermont/terraj/stargen/templates/");

        // Specify how templates will see the data model. This is an advanced topic...
        // but just use this:
        cfg.setObjectWrapper(new DefaultObjectWrapper());

        DetailsFromTemplate dft = new DetailsFromTemplate();

        List<PlanetDetailsPanel> panels = new ArrayList<PlanetDetailsPanel>();

        // first the star

        Template temp = cfg.getTemplate("starmain_html.ftl");

        CharArrayWriter out = new CharArrayWriter();

        dft.processTemplate(temp, star, out);
        out.flush();

        BufferedImage image = UIUtils.getImage("Sun");

        image = UIUtils.scaleImage(image, 32, 64);

        PlanetDetailsPanel panel = new PlanetDetailsPanel(image, "Star", out.toString());

        panel.setName("Star");

        panels.add(panel);

        // now do the planets

        temp = cfg.getTemplate("planetmain_html.ftl");

        for (Planet planet : this.planets) {
            out = new CharArrayWriter();

            dft.processTemplate(temp, planet, this.star, out);
            out.flush();

            image = UIUtils.getImage(planet.getType().getPrintText(planet.getType()));

            image = UIUtils.scaleImage(image, 64, 64);

            panel = new PlanetDetailsPanel(image, planet.getType().getPrintText(planet.getType()),
                    out.toString());

            panel.setName("#" + planet.getNumber());

            panels.add(panel);
        }

        DetailsFrame details = new DetailsFrame(this.star, this.planets, panels);

        details.setVisible(true);
    } catch (Exception ex) {
        log.error("Error getting details from template", ex);

        JOptionPane.showMessageDialog(this, "Error: " + ex.getMessage() + "\nCheck log file for full details",
                "Template Error", JOptionPane.ERROR_MESSAGE);
    }

}

From source file:nl.architolk.ldt.processors.HttpClientProcessor.java

public void generateData(PipelineContext context, ContentHandler contentHandler) throws SAXException {

    try {/*from  w  w w .j  a va 2  s .  c o  m*/
        CloseableHttpClient httpclient = HttpClientProperties.createHttpClient();

        try {
            // Read content of config pipe
            Document configDocument = readInputAsDOM4J(context, INPUT_CONFIG);
            Node configNode = configDocument.selectSingleNode("//config");

            URL theURL = new URL(configNode.valueOf("url"));

            if (configNode.valueOf("auth-method").equals("basic")) {
                HttpHost targetHost = new HttpHost(theURL.getHost(), theURL.getPort(), theURL.getProtocol());
                //Authentication support
                CredentialsProvider credsProvider = new BasicCredentialsProvider();
                credsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(
                        configNode.valueOf("username"), configNode.valueOf("password")));
                // logger.info("Credentials: "+configNode.valueOf("username")+"/"+configNode.valueOf("password"));
                // Create AuthCache instance
                AuthCache authCache = new BasicAuthCache();
                authCache.put(targetHost, new BasicScheme());

                // Add AuthCache to the execution context
                httpContext = HttpClientContext.create();
                httpContext.setCredentialsProvider(credsProvider);
                httpContext.setAuthCache(authCache);
            } else if (configNode.valueOf("auth-method").equals("form")) {
                //Sign in. Cookie will be remembered bij httpclient
                HttpPost authpost = new HttpPost(configNode.valueOf("auth-url"));
                List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
                nameValuePairs.add(new BasicNameValuePair("userName", configNode.valueOf("username")));
                nameValuePairs.add(new BasicNameValuePair("password", configNode.valueOf("password")));
                authpost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
                CloseableHttpResponse httpResponse = httpclient.execute(authpost);
                // logger.info("Signin response:"+Integer.toString(httpResponse.getStatusLine().getStatusCode()));
            }

            CloseableHttpResponse response;
            if (configNode.valueOf("method").equals("post")) {
                // POST
                HttpPost httpRequest = new HttpPost(configNode.valueOf("url"));
                setBody(httpRequest, context, configNode);
                response = executeRequest(httpRequest, httpclient);
            } else if (configNode.valueOf("method").equals("put")) {
                // PUT
                HttpPut httpRequest = new HttpPut(configNode.valueOf("url"));
                setBody(httpRequest, context, configNode);
                response = executeRequest(httpRequest, httpclient);
            } else if (configNode.valueOf("method").equals("delete")) {
                //DELETE
                HttpDelete httpRequest = new HttpDelete(configNode.valueOf("url"));
                response = executeRequest(httpRequest, httpclient);
            } else if (configNode.valueOf("method").equals("head")) {
                //HEAD
                HttpHead httpRequest = new HttpHead(configNode.valueOf("url"));
                response = executeRequest(httpRequest, httpclient);
            } else if (configNode.valueOf("method").equals("options")) {
                //OPTIONS
                HttpOptions httpRequest = new HttpOptions(configNode.valueOf("url"));
                response = executeRequest(httpRequest, httpclient);
            } else {
                //Default = GET
                HttpGet httpRequest = new HttpGet(configNode.valueOf("url"));
                String acceptHeader = configNode.valueOf("accept");
                if (!acceptHeader.isEmpty()) {
                    httpRequest.addHeader("accept", configNode.valueOf("accept"));
                }
                //Add proxy route if needed
                HttpClientProperties.setProxy(httpRequest, theURL.getHost());
                response = executeRequest(httpRequest, httpclient);
            }

            try {
                contentHandler.startDocument();

                int status = response.getStatusLine().getStatusCode();
                AttributesImpl statusAttr = new AttributesImpl();
                statusAttr.addAttribute("", "status", "status", "CDATA", Integer.toString(status));
                contentHandler.startElement("", "response", "response", statusAttr);
                if (status >= 200 && status < 300) {
                    HttpEntity entity = response.getEntity();
                    Header contentType = response.getFirstHeader("Content-Type");
                    if (entity != null && contentType != null) {
                        //logger.info("Contenttype: " + contentType.getValue());
                        //Read content into inputstream
                        InputStream inStream = entity.getContent();

                        // output-type = json means: response is json, convert to xml
                        if (configNode.valueOf("output-type").equals("json")) {
                            //TODO: net.sf.json.JSONObject might nog be the correct JSONObject. javax.json.JsonObject might be better!!!
                            //javax.json contains readers to read from an inputstream
                            StringWriter writer = new StringWriter();
                            IOUtils.copy(inStream, writer, "UTF-8");
                            JSONObject json = JSONObject.fromObject(writer.toString());
                            parseJSONObject(contentHandler, json);
                            // output-type = xml means: response is xml, keep it
                        } else if (configNode.valueOf("output-type").equals("xml")) {
                            try {
                                XMLReader saxParser = XMLParsing
                                        .newXMLReader(new XMLParsing.ParserConfiguration(false, false, false));
                                saxParser.setContentHandler(new ParseHandler(contentHandler));
                                saxParser.parse(new InputSource(inStream));
                            } catch (Exception e) {
                                throw new OXFException(e);
                            }
                            // output-type = jsonld means: reponse is json-ld, (a) convert to nquads; (b) convert to xml
                        } else if (configNode.valueOf("output-type").equals("jsonld")) {
                            try {
                                Object jsonObject = JsonUtils.fromInputStream(inStream, "UTF-8"); //TODO: UTF-8 should be read from response!
                                Object nquads = JsonLdProcessor.toRDF(jsonObject, new NQuadTripleCallback());

                                Any23 runner = new Any23();
                                DocumentSource source = new StringDocumentSource((String) nquads,
                                        configNode.valueOf("url"));
                                ByteArrayOutputStream out = new ByteArrayOutputStream();
                                TripleHandler handler = new RDFXMLWriter(out);
                                try {
                                    runner.extract(source, handler);
                                } finally {
                                    handler.close();
                                }
                                ByteArrayInputStream inJsonStream = new ByteArrayInputStream(out.toByteArray());
                                XMLReader saxParser = XMLParsing
                                        .newXMLReader(new XMLParsing.ParserConfiguration(false, false, false));
                                saxParser.setContentHandler(new ParseHandler(contentHandler));
                                saxParser.parse(new InputSource(inJsonStream));
                            } catch (Exception e) {
                                throw new OXFException(e);
                            }
                            // output-type = rdf means: response is some kind of rdf (except json-ld...), convert to xml
                        } else if (configNode.valueOf("output-type").equals("rdf")) {
                            try {
                                Any23 runner = new Any23();

                                DocumentSource source;
                                //If contentType = text/html than convert from html to xhtml to handle non-xml style html!
                                logger.info("Contenttype: " + contentType.getValue());
                                if (configNode.valueOf("tidy").equals("yes")
                                        && contentType.getValue().startsWith("text/html")) {
                                    org.jsoup.nodes.Document doc = Jsoup.parse(inStream, "UTF-8",
                                            configNode.valueOf("url")); //TODO UTF-8 should be read from response!

                                    RDFCleaner cleaner = new RDFCleaner();
                                    org.jsoup.nodes.Document cleandoc = cleaner.clean(doc);
                                    cleandoc.outputSettings().escapeMode(Entities.EscapeMode.xhtml);
                                    cleandoc.outputSettings()
                                            .syntax(org.jsoup.nodes.Document.OutputSettings.Syntax.xml);
                                    cleandoc.outputSettings().charset("UTF-8");

                                    source = new StringDocumentSource(cleandoc.html(),
                                            configNode.valueOf("url"), contentType.getValue());
                                } else {
                                    source = new ByteArrayDocumentSource(inStream, configNode.valueOf("url"),
                                            contentType.getValue());
                                }

                                ByteArrayOutputStream out = new ByteArrayOutputStream();
                                TripleHandler handler = new RDFXMLWriter(out);
                                try {
                                    runner.extract(source, handler);
                                } finally {
                                    handler.close();
                                }
                                ByteArrayInputStream inAnyStream = new ByteArrayInputStream(out.toByteArray());
                                XMLReader saxParser = XMLParsing
                                        .newXMLReader(new XMLParsing.ParserConfiguration(false, false, false));
                                saxParser.setContentHandler(new ParseHandler(contentHandler));
                                saxParser.parse(new InputSource(inAnyStream));

                            } catch (Exception e) {
                                throw new OXFException(e);
                            }
                        } else {
                            CharArrayWriter writer = new CharArrayWriter();
                            IOUtils.copy(inStream, writer, "UTF-8");
                            contentHandler.characters(writer.toCharArray(), 0, writer.size());
                        }
                    }
                }
                contentHandler.endElement("", "response", "response");

                contentHandler.endDocument();
            } finally {
                response.close();
            }
        } finally {
            httpclient.close();
        }
    } catch (Exception e) {
        throw new OXFException(e);
    }

}

From source file:org.apache.taverna.scufl2.translator.t2flow.T2FlowParser.java

public static String elementToXML(Element element) {
    try {//www .jav  a2s  .  c om
        Transformer transformer = getTransformer();
        CharArrayWriter writer = new CharArrayWriter();
        transformer.transform(new DOMSource(element), new StreamResult(writer));
        return writer.toString();
    } catch (TransformerException e) {
        throw new IllegalStateException("Can't write XML", e);
    }
}

From source file:org.theospi.portfolio.portal.web.XsltPortal.java

private Element createSitesTabArea(Session session, String siteId, Document doc, HttpServletRequest req)
        throws IOException, SAXException {
    Element siteTabs = doc.createElement("siteTabs");
    CharArrayWriter writer = new CharArrayWriter();
    PrintWriter printWriter = new PrintWriter(writer);
    printWriter.write("<div id=\"blank\">");
    includeTabs(printWriter, req, session, siteId, "site", false);
    Document tabs = getDocumentBuilder().parse(new InputSource(new CharArrayReader(writer.toCharArray())));
    siteTabs.appendChild(doc.importNode(tabs.getDocumentElement(), true));
    return siteTabs;
}

From source file:com.aliyun.odps.rodps.ROdps.java

public boolean setLogPath(String log_path) throws IOException {
    String fileName = ROdps.class.getClassLoader().getResource("log4j.properties").getPath();
    String mode = "loghome";
    File file = new File(fileName);
    BufferedReader reader = null;
    try {/*from   www  . ja va2s  .c om*/
        reader = new BufferedReader(new FileReader(file));
        CharArrayWriter tempStream = new CharArrayWriter();
        String tempString = null;
        int line = 1;
        while ((tempString = reader.readLine()) != null) {
            if (tempString.contains(mode) && (!tempString.contains("${" + mode + "}"))) {
                tempString = tempString.substring(0, tempString.indexOf('=') + 1) + log_path;
            }
            tempStream.write(tempString);
            tempStream.append(System.getProperty("line.separator"));
        }
        reader.close();
        FileWriter out = new FileWriter(fileName);
        tempStream.writeTo(out);
        out.close();

    } catch (IOException e) {
        e.printStackTrace();
        return false;
    } finally {
        if (reader != null) {
            try {
                reader.close();
            } catch (IOException e1) {
            }
        }
    }
    return true;
}

From source file:org.ireland.jnetty.webapp.ErrorPageManager.java

/**
 * Escapes HTML symbols in a stack trace.
 *///from  w ww. jav a 2s. co  m
private void printStackTrace(PrintWriter out, String lineMessage, Throwable e, Throwable rootExn,
        LineMap lineMap) {
    CharArrayWriter writer = new CharArrayWriter();
    PrintWriter pw = new PrintWriter(writer);

    if (lineMessage != null)
        pw.println(lineMessage);

    if (lineMap != null)
        lineMap.printStackTrace(e, pw);
    else
        ScriptStackTrace.printStackTrace(e, pw);

    pw.close();

    char[] array = writer.toCharArray();
    out.print(escapeHtml(new String(array)));
}

From source file:com.rc.droid_stalker.components.NetworkStats.java

@Override
public String toString() {
    final CharArrayWriter writer = new CharArrayWriter();
    dump("", new PrintWriter(writer));
    return writer.toString();
}

From source file:com.android.providers.downloads.DownloadInfo.java

@Override
public String toString() {
    final CharArrayWriter writer = new CharArrayWriter();
    dump(new IndentingPrintWriter(writer, "  "));
    return writer.toString();
}

From source file:launcher.net.CustomIOUtils.java

/**
 * Get the contents of an <code>InputStream</code> as a character array
 * using the specified character encoding.
 * <p>//from  w ww  .j  a  va 2s .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
 * @param encoding  the encoding to use, null means platform default
 * @return the requested character array
 * @throws NullPointerException if the input is null
 * @throws IOException if an I/O error occurs
 * @since 2.3
 */
public static char[] toCharArray(InputStream is, Charset encoding) throws IOException {
    CharArrayWriter output = new CharArrayWriter();
    copy(is, output, encoding);
    return output.toCharArray();
}