List of usage examples for java.io CharArrayWriter CharArrayWriter
public CharArrayWriter()
From source file:org.jabsorb.JSONRPCServlet.java
/** * Called when a JSON-RPC requests comes in. * Looks in the session for a JSONRPCBridge and if not found there, * uses the global bridge; then passes off the * JSON-PRC call to be handled by the JSONRPCBridge found. * * @param request servlet request from browser. * @param response servlet response to browser. * * @throws IOException if an IOException occurs during processing. *///from ww w . j a v a 2 s . c om public void service(HttpServletRequest request, HttpServletResponse response) throws IOException { // Use protected method in case someone wants to override it JSONRPCBridge json_bridge = findBridge(request); // Decode using the charset in the request if it exists otherwise // use UTF-8 as this is what all browser implementations use. // The JSON-RPC-Java JavaScript client is ASCII clean so it // although here we can correctly handle data from other clients // that do not escape non ASCII data String charset = request.getCharacterEncoding(); if (charset == null) { charset = "UTF-8"; } BufferedReader in = new BufferedReader(new InputStreamReader(request.getInputStream(), charset)); String receiveString = (String) request.getAttribute("_jabsorb_beenHere"); // if JSON data is found in a special request attribute, it means // that a continuation was used and this request is being retried // as a consequence of a Jetty continuation // see http://blogs.webtide.com/gregw/2007/11/18/1195421880000.html if (receiveString == null) { // Read the request CharArrayWriter data = new CharArrayWriter(); char buf[] = new char[buf_size]; int ret; while ((ret = in.read(buf, 0, buf_size)) != -1) { data.write(buf, 0, ret); } receiveString = data.toString(); int begin = receiveString.indexOf("{"); int end = receiveString.lastIndexOf("}") + 1; receiveString = receiveString.substring(begin, end); // save the json-rpc data in a special request attribute, in case a jetty // continuation exception (org.mortbay.jetty.RetryRequest) is thrown and this // request is retried by the container request.setAttribute("_jabsorb_beenHere", receiveString); } else { log.debug("jetty continuation resumed..."); } if (log.isDebugEnabled()) { log.debug("receive: " + receiveString); log.debug("receive: " + prettyPrintJson(receiveString)); } // Process the request JSONObject json_req; JSONRPCResult json_res; try { json_req = new JSONObject(receiveString); json_res = json_bridge.call(new Object[] { request, response }, json_req); } catch (JSONException e) { log.error("can't parse call" + receiveString, e); json_res = new JSONRPCResult(JSONRPCResult.CODE_ERR_PARSE, null, JSONRPCResult.MSG_ERR_PARSE); } String sendString = json_res.toString(); // dump the received string if (log.isDebugEnabled()) { log.debug("send: " + sendString); log.debug("send: " + prettyPrintJson(sendString)); } // Write the response byte[] bout = sendString.getBytes("UTF-8"); // handle gzipping of the response if it is turned on if (JSONRPCServlet.GZIP_THRESHOLD != -1) { // if the request header says that the browser can take gzip compressed output, then gzip the output // but only if the response is large enough to warrant it and if the resultant compressed output is // actually smaller. if (acceptsGzip(request)) { if (bout.length > JSONRPCServlet.GZIP_THRESHOLD) { byte[] gzippedOut = gzip(bout); log.debug( "gzipping! original size = " + bout.length + " gzipped size = " + gzippedOut.length); // if gzip didn't actually help, abort if (bout.length <= gzippedOut.length) { log.warn("gzipping resulted in a larger output size! " + "aborting (sending non-gzipped response)... " + "you may want to increase the gzip threshold if this happens a lot!" + " original size = " + bout.length + " gzipped size = " + gzippedOut.length); } else { // go with the gzipped output bout = gzippedOut; response.addHeader("Content-Encoding", "gzip"); } } else { log.debug("not gzipping because size is " + bout.length + " (less than the GZIP_THRESHOLD of " + JSONRPCServlet.GZIP_THRESHOLD + " bytes)"); } } else { // this should be rare with modern user agents log.debug("not gzipping because user agent doesn't accept gzip encoding..."); } } // Encode using UTF-8, although We are actually ASCII clean as // all unicode data is JSON escaped using backslash u. This is // less data efficient for foreign character sets but it is // needed to support naughty browsers such as Konqueror and Safari // which do not honour the charset set in the response response.setContentType("application/json;charset=utf-8"); OutputStream out = response.getOutputStream(); response.setIntHeader("Content-Length", bout.length); out.write(bout); out.flush(); out.close(); }
From source file:org.dd4t.mvc.utils.RenderUtils.java
/** * Dispatch a url to a request dispatcher while buffering the output in a string * (and not directly to the response's writer). *//*from w ww. j a v a 2 s .c o m*/ public static String dispatchBufferedRequest(final HttpServletRequest request, final HttpServletResponse response, final String url) throws ServletException, IOException { long time = System.currentTimeMillis(); final RequestDispatcher dispatcher = request.getServletContext().getRequestDispatcher(url); final HttpServletResponse responseWrapper = new HttpServletResponseWrapper(response) { private CharArrayWriter output = new CharArrayWriter(); @Override public String toString() { return output.toString(); } @Override public PrintWriter getWriter() { return new PrintWriter(output); } }; dispatcher.include(request, responseWrapper); time = System.currentTimeMillis() - time; LOG.debug("dispatchBufferedRequest {}, takes: {} ms.", url, time); return responseWrapper.toString(); }
From source file:com.aoindustries.website.signup.ServerConfirmationCompletedActionHelper.java
/** * Sends a summary email and returns <code>true</code> if successful. *//*from w w w.j a va2 s . c o m*/ private static boolean sendSummaryEmail(ActionServlet servlet, HttpServletRequest request, String pkey, String statusKey, String recipient, SiteSettings siteSettings, PackageDefinition packageDefinition, SignupCustomizeServerForm signupCustomizeServerForm, SignupCustomizeManagementForm signupCustomizeManagementForm, SignupBusinessForm signupBusinessForm, SignupTechnicalForm signupTechnicalForm, SignupBillingInformationForm signupBillingInformationForm) { try { Locale userLocale = ThreadLocale.get(); // Find the locale and related resource bundles String charset = Skin.getCharacterSet(userLocale); // Generate the email contents CharArrayWriter cout = new CharArrayWriter(); ChainWriter emailOut = new ChainWriter(cout); String htmlLang = getHtmlLang(userLocale); emailOut.print( "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Strict//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd\">\n" + "<html xmlns=\"http://www.w3.org/1999/xhtml\""); if (htmlLang != null) emailOut.print(" lang=\"").print(htmlLang).print("\" xml:lang=\"").print(htmlLang).print('"'); emailOut.print(">\n" + "<head>\n" + " <meta http-equiv='Content-Type' content='text/html; charset=") .print(charset).print("' />\n"); // Embed the text-only style sheet InputStream cssIn = servlet.getServletContext().getResourceAsStream("/textskin/global.css"); if (cssIn != null) { try { emailOut.print(" <style type=\"text/css\">\n" + " /* <![CDATA[ */\n"); Reader cssReader = new InputStreamReader(cssIn); try { char[] buff = new char[4096]; int ret; while ((ret = cssReader.read(buff, 0, 4096)) != -1) emailOut.write(buff, 0, ret); } finally { cssIn.close(); } emailOut.print(" /* ]]> */\n" + " </style>\n"); } finally { cssIn.close(); } } else { servlet.log("Warning: Unable to find resource: /global/textskin.css"); } emailOut.print( "</head>\n" + "<body>\n" + "<table style='border:0px' cellpadding=\"0\" cellspacing=\"0\">\n" + " <tr><td style='white-space:nowrap' colspan=\"3\">\n" + " ") .print(accessor.getMessage(statusKey, pkey)).print("<br />\n" + " <br />\n" + " ") .print(accessor.getMessage("serverConfirmationCompleted.belowIsSummary")) .print("<br />\n" + " <hr />\n" + " </td></tr>\n" + " <tr><th colspan=\"3\">") .print(accessor.getMessage("steps.selectServer.label")).print("</th></tr>\n"); SignupSelectServerActionHelper.printConfirmation(emailOut, packageDefinition); emailOut.print(" <tr><td colspan=\"3\"> </td></tr>\n" + " <tr><th colspan=\"3\">") .print(accessor.getMessage("steps.customizeServer.label")).print("</th></tr>\n"); AOServConnector rootConn = siteSettings.getRootAOServConnector(); SignupCustomizeServerActionHelper.printConfirmation(request, emailOut, rootConn, packageDefinition, signupCustomizeServerForm); if (signupCustomizeManagementForm != null) { emailOut.print(" <tr><td colspan=\"3\"> </td></tr>\n" + " <tr><th colspan=\"3\">") .print(accessor.getMessage("steps.customizeManagement.label")).print("</th></tr>\n"); SignupCustomizeManagementActionHelper.printConfirmation(request, emailOut, rootConn, signupCustomizeManagementForm); } emailOut.print(" <tr><td colspan=\"3\"> </td></tr>\n" + " <tr><th colspan=\"3\">") .print(accessor.getMessage("steps.businessInfo.label")).print("</th></tr>\n"); SignupBusinessActionHelper.printConfirmation(emailOut, rootConn, signupBusinessForm); emailOut.print(" <tr><td colspan=\"3\"> </td></tr>\n" + " <tr><th colspan=\"3\">") .print(accessor.getMessage("steps.technicalInfo.label")).print("</th></tr>\n"); SignupTechnicalActionHelper.printConfirmation(emailOut, rootConn, signupTechnicalForm); emailOut.print(" <tr><td colspan=\"3\"> </td></tr>\n" + " <tr><th colspan=\"3\">") .print(accessor.getMessage("steps.billingInformation.label")).print("</th></tr>\n"); SignupBillingInformationActionHelper.printConfirmation(emailOut, signupBillingInformationForm); emailOut.print("</table>\n" + "</body>\n" + "</html>\n"); emailOut.flush(); // Send the email Brand brand = siteSettings.getBrand(); Mailer.sendEmail( HostAddress.valueOf(brand.getSignupEmailAddress().getDomain().getAOServer().getHostname()), "text/html", charset, brand.getSignupEmailAddress().toString(), brand.getSignupEmailDisplay(), Collections.singletonList(recipient), accessor.getMessage("serverConfirmationCompleted.email.subject", pkey), cout.toString()); return true; } catch (RuntimeException err) { servlet.log("Unable to send sign up details to " + recipient, err); return false; } catch (IOException err) { servlet.log("Unable to send sign up details to " + recipient, err); return false; } catch (SQLException err) { servlet.log("Unable to send sign up details to " + recipient, err); return false; } catch (MessagingException err) { servlet.log("Unable to send sign up details to " + recipient, err); return false; } }
From source file:org.hippoecm.repository.PdfExtractionAndIndexingTest.java
private void createDocumentWithPdfAndHippoTextBinary(String name, boolean setHippoBinaryEmpty) 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 a v a2 s . c o m resource.setProperty("jcr:encoding", "UTF-8"); resource.setProperty("jcr:mimeType", "text/plain"); ByteArrayOutputStream data = new ByteArrayOutputStream(); OutputStreamWriter writer = new OutputStreamWriter(data, "UTF-8"); writer.write("The quick brown fox jumps over the lazy " + UNIQUE_WORD_IN_PLAIN_TEXT); writer.close(); resource.setProperty("jcr:data", new BinaryImpl(new ByteArrayInputStream(data.toByteArray()))); resource.setProperty("jcr:lastModified", Calendar.getInstance()); } if (setHippoBinaryEmpty) { final ByteArrayInputStream emptyByteArrayInputStream = new ByteArrayInputStream(new byte[0]); resource.setProperty("hippo:text", resource.getSession().getValueFactory().createBinary(emptyByteArrayInputStream)); } else { InputStream pdf = this.getClass().getResourceAsStream(UNITTEST_PDF_FILE_NAME); 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(); stripper.setLineSeparator("\n"); 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:jp.co.atware.solr.geta.GETAssocComponent.java
/** * GETAssoc??????//w w w . ja v a 2 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:com.allblacks.utils.web.HttpUtil.java
/** * Gets data from URL as char[] throws {@link RuntimeException} If anything * goes wrong/*from ww w.j av a2s . co m*/ * * @return The content of the URL as a char[] * @throws java.io.IOException */ public char[] postDataAsCharArray(String url, String contentType, String contentName, char[] content) throws IOException { URLConnection urlc = null; OutputStream os = null; InputStream is = null; CharArrayWriter dat = null; BufferedReader reader = null; String boundary = "" + new Date().getTime(); try { urlc = new URL(url).openConnection(); urlc.setDoOutput(true); urlc.setRequestProperty(HttpUtil.CONTENT_TYPE, "multipart/form-data; boundary=---------------------------" + boundary); String message1 = "-----------------------------" + boundary + HttpUtil.BNL; message1 += "Content-Disposition: form-data; name=\"nzbfile\"; filename=\"" + contentName + "\"" + HttpUtil.BNL; message1 += "Content-Type: " + contentType + HttpUtil.BNL; message1 += HttpUtil.BNL; String message2 = HttpUtil.BNL + "-----------------------------" + boundary + "--" + HttpUtil.BNL; os = urlc.getOutputStream(); BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(os, Charset.forName(HttpUtil.UTF_8))); writer.write(message1); writer.write(content); writer.write(message2); writer.flush(); dat = new CharArrayWriter(); if (urlc.getContentEncoding() != null && urlc.getContentEncoding().equalsIgnoreCase(HttpUtil.GZIP)) { is = new GZIPInputStream(urlc.getInputStream()); } else { is = urlc.getInputStream(); } reader = new BufferedReader(new InputStreamReader(is, Charset.forName(HttpUtil.UTF_8))); int c; while ((c = reader.read()) != -1) { dat.append((char) c); } } catch (IOException exception) { throw exception; } finally { try { reader.close(); os.close(); is.close(); } catch (Exception e) { // we do not care about this } } return dat.toCharArray(); }
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 www. ja v a 2 s. co m*/ 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.jabsorb.ng.JSONRPCServlet.java
/** * Called when a JSON-RPC requests comes in. Looks in the session for a * JSONRPCBridge and if not found there, uses the global bridge; then passes * off the JSON-PRC call to be handled by the JSONRPCBridge found. * //from w w w . j ava 2 s .c om * @param request * servlet request from browser. * @param response * servlet response to browser. * * @throws IOException * if an IOException occurs during processing. */ @Override public void service(final HttpServletRequest request, final HttpServletResponse response) throws IOException { // Use protected method in case someone wants to override it JSONRPCBridge json_bridge = findBridge(request); // Decode using the charset in the request if it exists otherwise // use UTF-8 as this is what all browser implementations use. // The JSON-RPC-Java JavaScript client is ASCII clean so it // although here we can correctly handle data from other clients // that do not escape non ASCII data String charset = request.getCharacterEncoding(); if (charset == null) { charset = "UTF-8"; } BufferedReader in = new BufferedReader(new InputStreamReader(request.getInputStream(), charset)); String receiveString = (String) request.getAttribute("_jabsorb_beenHere"); // if JSON data is found in a special request attribute, it means // that a continuation was used and this request is being retried // as a consequence of a Jetty continuation // see http://blogs.webtide.com/gregw/2007/11/18/1195421880000.html if (receiveString == null) { // Read the request CharArrayWriter data = new CharArrayWriter(); char buf[] = new char[buf_size]; int ret; while ((ret = in.read(buf, 0, buf_size)) != -1) { data.write(buf, 0, ret); } receiveString = data.toString(); // save the json-rpc data in a special request attribute, in case a // jetty // continuation exception (org.mortbay.jetty.RetryRequest) is thrown // and this // request is retried by the container request.setAttribute("_jabsorb_beenHere", receiveString); } else { log.debug("service", "jetty continuation resumed..."); } if (log.isDebugEnabled()) { log.debug("service", "receive: " + receiveString); log.debug("service", "receive: " + prettyPrintJson(receiveString)); } // Process the request JSONObject json_req; JSONRPCResult json_res; try { json_req = new JSONObject(receiveString); json_res = json_bridge.call(new Object[] { request, response }, json_req); } catch (JSONException e) { log.error("service", "can't parse call" + receiveString, e); json_res = new JSONRPCResult(JSONRPCResult.CODE_ERR_PARSE, null, JSONRPCResult.MSG_ERR_PARSE); } String sendString = json_res.toString(); // dump the received string if (log.isDebugEnabled()) { log.debug("service", "send: " + sendString); log.debug("service", "send: " + prettyPrintJson(sendString)); } // Write the response byte[] bout = sendString.getBytes("UTF-8"); // handle gzipping of the response if it is turned on if (JSONRPCServlet.GZIP_THRESHOLD != -1) { // if the request header says that the browser can take gzip // compressed output, then gzip the output // but only if the response is large enough to warrant it and if the // resultant compressed output is // actually smaller. if (acceptsGzip(request)) { if (bout.length > JSONRPCServlet.GZIP_THRESHOLD) { byte[] gzippedOut = gzip(bout); log.debug("service", "gzipping! original size = " + bout.length + " gzipped size = " + gzippedOut.length); // if gzip didn't actually help, abort if (bout.length <= gzippedOut.length) { log.warning("service", "gzipping resulted in a larger output size! " + "aborting (sending non-gzipped response)... " + "you may want to increase the gzip threshold if this happens a lot!" + " original size = " + bout.length + " gzipped size = " + gzippedOut.length); } else { // go with the gzipped output bout = gzippedOut; response.addHeader("Content-Encoding", "gzip"); } } else { log.debug("service", "not gzipping because size is " + bout.length + " (less than the GZIP_THRESHOLD of " + JSONRPCServlet.GZIP_THRESHOLD + " bytes)"); } } else { // this should be rare with modern user agents log.debug("service", "not gzipping because user agent doesn't accept gzip encoding..."); } } // Encode using UTF-8, although We are actually ASCII clean as // all unicode data is JSON escaped using backslash u. This is // less data efficient for foreign character sets but it is // needed to support naughty browsers such as Konqueror and Safari // which do not honour the charset set in the response response.setContentType("application/json;charset=utf-8"); OutputStream out = response.getOutputStream(); response.setIntHeader("Content-Length", bout.length); out.write(bout); out.flush(); out.close(); }
From source file:org.apache.solr.client.solrj.impl.BackupRequestLBHttpSolrClient.java
@Override protected Exception addZombie(HttpSolrClient server, Exception e) { CharArrayWriter cw = new CharArrayWriter(); PrintWriter pw = new PrintWriter(cw); e.printStackTrace(pw);// w w w .j a v a2 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.getBaseURL(), e.toString() + stack); return super.addZombie(server, e); }
From source file:org.apache.maven.doxia.DefaultConverter.java
/** * @param inputFile a not null existing file. * @param inputEncoding a not null supported encoding or {@link InputFileWrapper#AUTO_ENCODING} * @param inputFormat a not null supported format or {@link InputFileWrapper#AUTO_FORMAT} * @param output not null OutputFileWrapper object * @throws ConverterException if any//from w w w .j ava2 s . c om * @throws UnsupportedFormatException if any */ private void parse(File inputFile, String inputEncoding, String inputFormat, OutputFileWrapper output) throws ConverterException, UnsupportedFormatException { if (getLog().isDebugEnabled()) { getLog().debug("Parsing file from '" + inputFile.getAbsolutePath() + "' with the encoding '" + inputEncoding + "' to '" + output.getFile().getAbsolutePath() + "' with the encoding '" + output.getEncoding() + "'"); } if (inputEncoding.equals(InputFileWrapper.AUTO_ENCODING)) { inputEncoding = autoDetectEncoding(inputFile); if (getLog().isDebugEnabled()) { getLog().debug("Auto detect encoding: " + inputEncoding); } } if (inputFormat.equals(InputFileWrapper.AUTO_FORMAT)) { inputFormat = autoDetectFormat(inputFile, inputEncoding); if (getLog().isDebugEnabled()) { getLog().debug("Auto detect input format: " + inputFormat); } } Parser parser; try { parser = ConverterUtil.getParser(plexus, inputFormat, SUPPORTED_FROM_FORMAT); parser.enableLogging(log); } catch (ComponentLookupException e) { throw new ConverterException("ComponentLookupException: " + e.getMessage(), e); } File outputFile; if (output.getFile().exists() && output.getFile().isDirectory()) { outputFile = new File(output.getFile(), inputFile.getName() + "." + output.getFormat()); } else { if (!SelectorUtils.match("**.*", output.getFile().getName())) { // assume it is a directory output.getFile().mkdirs(); outputFile = new File(output.getFile(), inputFile.getName() + "." + output.getFormat()); } else { output.getFile().getParentFile().mkdirs(); outputFile = output.getFile(); } } Reader reader; try { if (inputEncoding != null) { if (parser.getType() == Parser.XML_TYPE) { reader = ReaderFactory.newXmlReader(inputFile); } else { reader = ReaderFactory.newReader(inputFile, inputEncoding); } } else { reader = ReaderFactory.newPlatformReader(inputFile); } } catch (IOException e) { throw new ConverterException("IOException: " + e.getMessage(), e); } SinkFactory sinkFactory; try { sinkFactory = ConverterUtil.getSinkFactory(plexus, output.getFormat(), SUPPORTED_TO_FORMAT); } catch (ComponentLookupException e) { throw new ConverterException("ComponentLookupException: " + e.getMessage(), e); } Sink sink; try { String outputEncoding; if (StringUtils.isEmpty(output.getEncoding()) || output.getEncoding().equals(OutputFileWrapper.AUTO_ENCODING)) { outputEncoding = inputEncoding; } else { outputEncoding = output.getEncoding(); } OutputStream out = new FileOutputStream(outputFile); sink = sinkFactory.createSink(out, outputEncoding); } catch (IOException e) { throw new ConverterException("IOException: " + e.getMessage(), e); } sink.enableLogging(log); if (getLog().isDebugEnabled()) { getLog().debug("Sink used: " + sink.getClass().getName()); } parse(parser, reader, sink); if (formatOutput && (output.getFormat().equals(DOCBOOK_SINK) || output.getFormat().equals(FO_SINK) || output.getFormat().equals(ITEXT_SINK) || output.getFormat().equals(XDOC_SINK) || output.getFormat().equals(XHTML_SINK))) { // format all xml files excluding docbook which is buggy // TODO Add doc book format if (output.getFormat().equals(DOCBOOK_SINK) || inputFormat.equals(DOCBOOK_PARSER)) { return; } Reader r = null; Writer w = null; try { r = ReaderFactory.newXmlReader(outputFile); CharArrayWriter caw = new CharArrayWriter(); XmlUtil.prettyFormat(r, caw); w = WriterFactory.newXmlWriter(outputFile); w.write(caw.toString()); } catch (IOException e) { throw new ConverterException("IOException: " + e.getMessage(), e); } finally { IOUtil.close(r); IOUtil.close(w); } } }