List of usage examples for java.io CharArrayWriter toString
public String toString()
From source file:onl.area51.httpd.action.Response.java
static Response create(Request request) { class State { private final String tag; private final boolean disableMini; private boolean body; public State(String tag, boolean disableMini) { this.tag = tag; this.disableMini = disableMini; }/*from w w w .jav a 2 s.co m*/ @Override public String toString() { return tag; } } CharArrayWriter writer = new CharArrayWriter(); return new Response() { private ContentType contentType = ContentType.TEXT_HTML; private Deque<State> deque = new ArrayDeque<>(); private State state; @Override public Response exec(Action a) throws IOException, HttpException { if (a != null) { // Ensure we have finished the current tag startBody(); // Now preserve the stack & start a new one. // This means one action cannot affect the state of this one final Deque<State> orig = deque; deque = new ArrayDeque<>(); try { a.apply(request); } finally { endAll(); deque = orig; } } return this; } @Override public Response setContentType(ContentType contentType) { this.contentType = contentType; return this; } @Override public HttpEntity getEntity() throws IOException { while (!deque.isEmpty()) { end(); } return new StringEntity(writer.toString(), contentType); } private void startBody() { if (state != null && !state.body) { state.body = true; writer.append('>'); } } private void tagOnly() { if (state == null || state.body) { throw new IllegalStateException("Not in tag"); } } @Override public Response write(CharSequence seq, int s, int e) throws IOException { startBody(); writer.append(seq, s, e); return this; } @Override public Response write(char[] v, int s, int l) throws IOException { startBody(); writer.write(v, s, l); return this; } @Override public Response write(char v) throws IOException { startBody(); writer.write(v); return this; } @Override public Response begin(String t, boolean disableMini) throws IOException { startBody(); if (state != null) { deque.addLast(state); } state = new State(t, disableMini); writer.append('<'); writer.write(state.tag); return this; } @Override public Response end() throws IOException { if (state == null) { throw new IllegalStateException("end() called outside of tag"); } // elements like script mustn't be minified, i.e. <script/> is invalid must be <script></script> if (state.disableMini) { startBody(); } if (state.body) { writer.append('<'); writer.append('/'); writer.append(state.tag); writer.append('>'); } else { writer.append('/'); writer.append('>'); } state = deque.pollLast(); return this; } @Override public Response endAll() throws IOException { while (!deque.isEmpty()) { end(); } return this; } @Override public Response attr(String n, CharSequence seq) throws IOException { tagOnly(); writer.append(' '); writer.append(n); writer.append('='); writer.append('"'); writer.append(seq); writer.append('"'); return this; } @Override public Response attr(String n, CharSequence seq, int s, int e) throws IOException { tagOnly(); writer.append(' '); writer.append(n); writer.append('='); writer.append('"'); writer.append(seq, s, e); writer.append('"'); return this; } @Override public Response attr(String n, char[] v) throws IOException { tagOnly(); writer.append(' '); writer.append(n); writer.append('='); writer.append('"'); writer.write(v); writer.append('"'); return this; } @Override public Response attr(String n, char[] v, int s, int l) throws IOException { tagOnly(); writer.append(' '); writer.append(n); writer.append('='); writer.append('"'); writer.write(v, s, l); writer.append('"'); return this; } }; }
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 {/*from ww w .ja v a2 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:org.pentaho.platform.engine.services.MessageFormatter.java
public void formatExceptionMessage(String mimeType, ActionSequenceException exception, StringBuffer messageBuffer) { if ("text/html".equals(mimeType)) { //$NON-NLS-1$ String templateFile = null; String templatePath = "system/ui/templates/viewActionErrorTemplate.html"; //$NON-NLS-1$ try {/*from w ww .jav a 2s . c om*/ byte[] bytes = IOUtils .toByteArray(ActionSequenceResource.getInputStream(templatePath, LocaleHelper.getLocale())); templateFile = new String(bytes, LocaleHelper.getSystemEncoding()); } catch (IOException e) { messageBuffer.append(Messages.getInstance() .getErrorString("MessageFormatter.RESPONSE_ERROR_HEADING", templatePath)); //$NON-NLS-1$ e.printStackTrace(); } // NOTE: StringUtils.replace is used here instead of String.replaceAll because since the latter uses regex, // the // replacment // text can cause exceptions if '$' or other special characters are present. We cannot guarantee that the // replacement // text does not have these characters, so a non-regex replacer was used. // TODO: there is a bit of extraneous String object creation here. If performance becomes an issue, there are // more // efficient // ways of doing mass replacements of text, such as using StringBuilder.replace // %ERROR_HEADING% templateFile = StringUtils.replace(templateFile, "%ERROR_HEADING%", Messages.getInstance() //$NON-NLS-1$ .getString("MessageFormatter.RESPONSE_ERROR_HEADING")); //$NON-NLS-1$ // %EXCEPTION_MSG% templateFile = StringUtils.replace(templateFile, "%EXCEPTION_MSG%", //$NON-NLS-1$ StringEscapeUtils.escapeHtml(exception.getMessage() == null ? "" : exception.getMessage())); //$NON-NLS-1$ templateFile = StringUtils.replace(templateFile, "%EXCEPTION_MSG_LABEL%", Messages.getInstance() //$NON-NLS-1$ .getString("MessageFormatter.RESPONSE_EXCEPTION_MSG_LABEL")); //$NON-NLS-1$ // %EXCEPTION_TIME% templateFile = StringUtils.replace(templateFile, "%EXCEPTION_TIME%", //$NON-NLS-1$ StringEscapeUtils.escapeHtml(dateFormat.format(exception.getDate()))); templateFile = StringUtils.replace(templateFile, "%EXCEPTION_TIME_LABEL%", Messages.getInstance() //$NON-NLS-1$ .getString("MessageFormatter.RESPONSE_EXCEPTION_TIME_LABEL")); //$NON-NLS-1$ // %EXCEPTION_TYPE% templateFile = StringUtils.replace(templateFile, "%EXCEPTION_TYPE%", //$NON-NLS-1$ StringEscapeUtils.escapeHtml(exception.getClass().getSimpleName())); templateFile = StringUtils.replace(templateFile, "%EXCEPTION_TYPE_LABEL%", Messages.getInstance() //$NON-NLS-1$ .getString("MessageFormatter.RESPONSE_EXCEPTION_TYPE_LABEL")); //$NON-NLS-1$ // %SESSION_ID% templateFile = StringUtils.replace(templateFile, "%SESSION_ID%", StringEscapeUtils.escapeHtml(exception //$NON-NLS-1$ .getSessionId() == null ? "" : exception.getSessionId())); //$NON-NLS-1$ templateFile = StringUtils.replace(templateFile, "%SESSION_ID_LABEL%", Messages.getInstance() //$NON-NLS-1$ .getString("MessageFormatter.RESPONSE_EXCEPTION_SESSION_ID_LABEL")); //$NON-NLS-1$ // %INSTANCE_ID% templateFile = StringUtils.replace(templateFile, "%INSTANCE_ID%", StringEscapeUtils.escapeHtml(exception //$NON-NLS-1$ .getInstanceId() == null ? "" : exception.getInstanceId())); //$NON-NLS-1$ templateFile = StringUtils.replace(templateFile, "%INSTANCE_ID_LABEL%", Messages.getInstance() //$NON-NLS-1$ .getString("MessageFormatter.RESPONSE_EXCEPTION_INSTANCE_ID_LABEL")); //$NON-NLS-1$ // %ACTION_SEQUENCE% templateFile = StringUtils.replace(templateFile, "%ACTION_SEQUENCE%", //$NON-NLS-1$ StringEscapeUtils.escapeHtml(exception.getActionSequenceName() == null ? "" : exception.getActionSequenceName())); //$NON-NLS-1$ templateFile = StringUtils.replace(templateFile, "%ACTION_SEQUENCE_LABEL%", Messages.getInstance() //$NON-NLS-1$ .getString("MessageFormatter.RESPONSE_EXCEPTION_ACTION_SEQUENCE_LABEL")); //$NON-NLS-1$ // %ACTION_SEQUENCE_EXECUTION_STACK% CharArrayWriter charWriter = new CharArrayWriter(); PrintWriter printWriter = new PrintWriter(charWriter); exception.printActionExecutionStack(printWriter); templateFile = StringUtils.replace(templateFile, "%ACTION_SEQUENCE_EXECUTION_STACK%", //$NON-NLS-1$ StringEscapeUtils.escapeHtml(charWriter.toString())); templateFile = StringUtils.replace(templateFile, "%ACTION_SEQUENCE_EXECUTION_STACK_LABEL%", //$NON-NLS-1$ Messages.getInstance().getString( "MessageFormatter.RESPONSE_EXCEPTION_ACTION_SEQUENCE_EXECUTION_STACK_LABEL")); //$NON-NLS-1$ // %ACTION_CLASS% templateFile = StringUtils.replace(templateFile, "%ACTION_CLASS%", //$NON-NLS-1$ StringEscapeUtils.escapeHtml(exception.getActionClass() == null ? "" : exception.getActionClass())); //$NON-NLS-1$ templateFile = StringUtils.replace(templateFile, "%ACTION_CLASS_LABEL%", Messages.getInstance() //$NON-NLS-1$ .getString("MessageFormatter.RESPONSE_EXCEPTION_ACTION_CLASS_LABEL")); //$NON-NLS-1$ // %ACTION_DESC% templateFile = StringUtils.replace(templateFile, "%ACTION_DESC%", StringEscapeUtils.escapeHtml(exception //$NON-NLS-1$ .getStepDescription() == null ? "" : exception.getStepDescription())); //$NON-NLS-1$ templateFile = StringUtils.replace(templateFile, "%ACTION_DESC_LABEL%", Messages.getInstance() //$NON-NLS-1$ .getString("MessageFormatter.RESPONSE_EXCEPTION_ACTION_DESC_LABEL")); //$NON-NLS-1$ // %STEP_NUM% templateFile = StringUtils.replace(templateFile, "%STEP_NUM%", StringEscapeUtils.escapeHtml(exception //$NON-NLS-1$ .getStepNumber() == null ? Messages.getInstance().getString("MessageFormatter.EXCEPTION_FIELD_NOT_APPLICABLE") //$NON-NLS-1$ : exception.getStepNumber().toString())); templateFile = StringUtils.replace(templateFile, "%STEP_NUM_LABEL%", Messages.getInstance() //$NON-NLS-1$ .getString("MessageFormatter.RESPONSE_EXCEPTION_STEP_NUM_LABEL")); //$NON-NLS-1$ // %STEP_NUM% templateFile = StringUtils.replace(templateFile, "%LOOP_INDEX%", StringEscapeUtils.escapeHtml(exception //$NON-NLS-1$ .getLoopIndex() == null ? Messages.getInstance().getString("MessageFormatter.EXCEPTION_FIELD_NOT_APPLICABLE") //$NON-NLS-1$ : exception.getLoopIndex().toString())); templateFile = StringUtils.replace(templateFile, "%LOOP_INDEX_LABEL%", Messages.getInstance() //$NON-NLS-1$ .getString("MessageFormatter.RESPONSE_EXCEPTION_LOOP_INDEX_LABEL")); //$NON-NLS-1$ // %STACK_TRACE% charWriter = new CharArrayWriter(); printWriter = new PrintWriter(charWriter); exception.printStackTrace(printWriter); templateFile = StringUtils.replace(templateFile, "%STACK_TRACE%", //$NON-NLS-1$ StringEscapeUtils.escapeHtml(charWriter.toString())); templateFile = StringUtils.replace(templateFile, "%STACK_TRACE_LABEL%", Messages.getInstance() //$NON-NLS-1$ .getString("MessageFormatter.RESPONSE_EXCEPTION_STACK_TRACE_LABEL")); //$NON-NLS-1$ // %EXCEPTION_MESSAGES% Stack<String> causes = new Stack<String>(); buildCauses(causes, exception); charWriter = new CharArrayWriter(); printWriter = new PrintWriter(charWriter); while (!causes.empty()) { printWriter.println(causes.pop()); } templateFile = StringUtils.replace(templateFile, "%EXCEPTION_MESSAGES%", //$NON-NLS-1$ StringEscapeUtils.escapeHtml(charWriter.toString())); templateFile = StringUtils.replace(templateFile, "%EXCEPTION_MESSAGES_LABEL%", Messages.getInstance() //$NON-NLS-1$ .getString("MessageFormatter.RESPONSE_EXCEPTION_MESSAGES_LABEL")); //$NON-NLS-1$ // %SERVER_INFO% (if available) if (PentahoSystem.getObjectFactory().objectDefined(IVersionHelper.class.getSimpleName())) { IVersionHelper versionHelper = PentahoSystem.get(IVersionHelper.class); templateFile = StringUtils.replace(templateFile, "%SERVER_INFO%", Messages.getInstance().getString( //$NON-NLS-1$ "MessageFormatter.USER_SERVER_VERSION", //$NON-NLS-1$ versionHelper.getVersionInformation(PentahoSystem.class))); } messageBuffer.append(templateFile); } }
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//www . j av 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:jp.co.atware.solr.geta.GETAssocComponent.java
/** * GETAssoc??????//from w w w. ja v a2 s .c o m * * @param params * @param queryValue * @param queryType * @return * @throws FactoryConfigurationError * @throws IOException */ protected String convertRequest(SolrParams params, String queryValue, QueryType queryType) throws FactoryConfigurationError, IOException { String req; try { CharArrayWriter output = new CharArrayWriter(); XMLStreamWriter xml = XMLOutputFactory.newInstance().createXMLStreamWriter(output); xml.writeStartDocument(); xml.writeStartElement("gss"); if (config.settings.gss3version != null) { xml.writeAttribute("version", config.settings.gss3version); } xml.writeStartElement("assoc"); String target = params.get(PARAM_TARGET, config.defaults.target); if (target != null) { xml.writeAttribute("target", target); } convertRequestWriteStage1Param(xml, params); convertRequestWriteStage2Param(xml, params); convReqWriteQuery(xml, params, queryValue, queryType); xml.writeEndElement(); xml.writeEndElement(); xml.writeEndDocument(); xml.close(); req = output.toString(); } catch (XMLStreamException e) { throw new IOException(e); } LOG.debug(req); return req; }
From source file:org.opensingular.internal.lib.commons.xml.MElement.java
/** * Gera o XML to elemento conforme o funcionamento do mtodo printTabulado * (utilizar preferencialment printTabulado). Existe como convenincia * quando no houver um PrintWriter ou PrintStream disponvel. * * @return o XML com um tag por linha e alinhado conforme o nvel *//* ww w. ja va 2 s. c o m*/ @Override public String toString() { CharArrayWriter writer = new CharArrayWriter(); PrintWriter out = new PrintWriter(writer); printTabulado(out); out.flush(); return writer.toString(); }
From source file:org.opensingular.internal.lib.commons.xml.MElement.java
/** * Gera o XML do elemento conforme o funcionamento do mtodo print (utilizar * preferencialment printTabulado). Existe como convenincia quando no * houver um PrintWriter ou PrintStream disponvel. * * @return a String que feito parse, retorna o mesmo conteudo *//* w w w. ja v a 2s.co m*/ public final String toStringExato() { CharArrayWriter writer = new CharArrayWriter(); PrintWriter out = new PrintWriter(writer); print(out, true, true); out.flush(); return writer.toString(); }
From source file:grails.plugin.freemarker.TagLibToDirectiveAndFunction.java
@SuppressWarnings("serial") @Override/*from w w w . j a v a 2 s.c om*/ public Object exec(@SuppressWarnings("rawtypes") List arguments) throws TemplateModelException { if (log.isDebugEnabled()) { log.debug("exec(): @" + namespace + "." + tagName); } try { CharArrayWriter writer = new CharArrayWriter(); tagInstance.invokeMethod("pushOut", writer); Object args = null; Object body = null; if (arguments != null) { if (arguments.size() > 0) { args = arguments.get(0); } if (arguments.size() > 1) { body = arguments.get(1); } } Object result = null; args = args != null ? unwrapParams((TemplateHashModelEx) args, true) : unwrapParams(Collections.EMPTY_MAP, true); if (tagInstance.getMaximumNumberOfParameters() == 1) { result = tagInstance.call(args); } else { Closure bodyClosure = EMPTY_BODY; if (body != null || hasReturnValue) { final Object fBody = body; bodyClosure = new Closure(this) { @SuppressWarnings("unused") public Object doCall(Object it) throws IOException, TemplateException { return fBody; } }; } result = tagInstance.call(new Object[] { args, bodyClosure }); if (result == null) { // writer.flush(); result = writer.toString(); } } return result; } catch (RuntimeException e) { throw new TemplateModelException(e); } finally { tagInstance.invokeMethod("popOut", null); } }
From source file:org.opensingular.internal.lib.commons.xml.MElement.java
/** * Gera o XML do elemento conforme o funcionamento do mtodo print (utilizar * preferencialment printTabulado). Existe como convenincia quando no * houver um PrintWriter ou PrintStream disponvel. * * @param printHeader Indica se ser adiciona o identificado inicial de * arquivo XML. Se for false, no ser possvel fazer parse do * resultado sem a adio de informaes complementares. * @return a String que feito parse, retorna o mesmo conteudo *//*from ww w . j a v a 2 s . co m*/ public final String toStringExato(boolean printHeader) { CharArrayWriter writer = new CharArrayWriter(); PrintWriter out = new PrintWriter(writer); print(out, printHeader, true); out.flush(); return writer.toString(); }
From source file:com.google.acre.script.HostEnv.java
/** * This implies an internal problem in acreboot.js, since it should * be handling any user errors./* w ww. j a va 2 s .co m*/ */ private void reportDisaster(String message, Throwable exc) { // we hit a java exception. all // bare java exception should have been trapped // and hidden by now, so this is a serious internal // error. try { syslog(ERROR, "hostenv.internal.error", "Internal error in script boot: " + message); startErrorPage(); signalAcreError(message); CharArrayWriter cw = new CharArrayWriter(); PrintWriter pw = new PrintWriter(cw); exc.printStackTrace(pw); if (null != exc.getCause()) { pw.write("Caused by:\n"); pw.write(exc.getCause().getMessage() + "\n"); exc.getCause().printStackTrace(pw); } pw.flush(); String excdump = cw.toString(); syslog(ERROR, "hostenv.internal.error.msg", "ACRE INTERNAL ERROR: \n" + excdump); write("ACRE INTERNAL ERROR -- Please Report to irc://irc.freenode.net/#freebase\n"); write("Request Id: " + req._metaweb_tid + "\n\n"); write(excdump + "\n"); } catch (Throwable e) { syslog(ERROR, "hostenv.internal.error.fatal", "Dispatch: Acre Last chance error, giving up" + exc); syslog(ERROR, "hostenv.internal.error.fatal.failed_on", "Failed reporting the error above" + e); // XXX this should be replaced with an exception class that is unique to this case // and will never be caught. throw new AcreInternalError("Failed while reporting a disaster", e); } }