List of usage examples for java.io StringWriter getBuffer
public StringBuffer getBuffer()
From source file:org.apache.webdav.lib.methods.LockMethod.java
/** * DAV requests that contain a body must override this function to * generate that body.//from w w w. jav a2s . c o m * * <p>The default behavior simply returns an empty body.</p> */ protected String generateRequestBody() { String result = ""; if (!isRefresh()) { if (this.owner == null || this.owner.equals("")) { throw new IllegalStateException("The owner property has not been set"); } try { DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder builder = factory.newDocumentBuilder(); Document document = builder.newDocument(); Element lockinfo = document.createElement("DAV:lockinfo"); document.appendChild(lockinfo); lockinfo.setAttribute("xmlns:DAV", "DAV:"); Element lockscope = document.createElement("DAV:lockscope"); lockinfo.appendChild(lockscope); if (this.scope == SCOPE_EXCLUSIVE) { Element exclusive = document.createElement("DAV:exclusive"); lockscope.appendChild(exclusive); } else { Element shared = document.createElement("DAV:shared"); lockscope.appendChild(shared); } Element locktype = document.createElement("DAV:locktype"); lockinfo.appendChild(locktype); if (typeTransaction) { Element transaction = document.createElement("DAV:transaction"); locktype.appendChild(transaction); } else { Element write = document.createElement("DAV:write"); locktype.appendChild(write); } Element owner = document.createElement("DAV:owner"); lockinfo.appendChild(owner); Text text = document.createTextNode(this.owner); owner.appendChild(text); StringWriter stringWriter = new StringWriter(); DOMWriter domWriter = new DOMWriter(stringWriter, false); domWriter.print(document); result = stringWriter.getBuffer().toString(); } catch (DOMException e) { } catch (ParserConfigurationException e) { } } return result; }
From source file:com.tela.pms.PatientController.java
@ExceptionHandler(Exception.class) public ModelAndView exceptionFramework(Exception e) { ModelAndView modelAndView = new ModelAndView("error"); final StringWriter sw = new StringWriter(); final PrintWriter pw = new PrintWriter(sw, true); e.printStackTrace(pw);//from ww w . j a va 2s . c o m logger.error("error " + sw.getBuffer().toString() + e); //modelAndView.addObject("exception", e + " " + sw.getBuffer().toString()); return modelAndView; }
From source file:com.vmware.gemfire.tools.pulse.tests.junit.ClusterSelectedRegionsMemberServiceTest.java
/** * * Tests that response is for same region * * *//*from ww w . j av a 2 s. c om*/ @Test public void testResponseRegionOnMemberInfoMatches() { System.out.println( "ClusterSelectedRegionsMemberServiceTest :: ------TESTCASE BEGIN : MEMBER INFO RESPONSE CHECK FOR CLUSTER REGION MEMBERS------"); if (httpclient != null) { try { HttpUriRequest pulseupdate = RequestBuilder.post().setUri(new URI(PULSE_UPDATE_URL)) .addParameter(PULSE_UPDATE_PARAM, PULSE_UPDATE_3_VALUE).build(); CloseableHttpResponse response = httpclient.execute(pulseupdate); try { HttpEntity entity = response.getEntity(); System.out.println("ClusterSelectedRegionsMemberServiceTest :: HTTP request status : " + response.getStatusLine()); BufferedReader respReader = new BufferedReader(new InputStreamReader(entity.getContent())); StringWriter sw = new StringWriter(); PrintWriter pw = new PrintWriter(sw); String sz = null; while ((sz = respReader.readLine()) != null) { pw.print(sz); } String jsonResp = sw.getBuffer().toString(); System.out.println( "ClusterSelectedRegionsMemberServiceTest :: JSON response returned : " + jsonResp); EntityUtils.consume(entity); JSONObject jsonObj = new JSONObject(jsonResp); JSONObject clusterSelectedRegionObj = jsonObj.getJSONObject("ClusterSelectedRegionsMember"); Assert.assertNotNull( "ClusterSelectedRegionsMemberServiceTest :: Server returned null response for ClusterSelectedRegionsMember", clusterSelectedRegionObj); JSONObject jsonObjRegion = clusterSelectedRegionObj.getJSONObject("selectedRegionsMembers"); Assert.assertNotNull( "ClusterSelectedRegionsMemberServiceTest :: Server returned null response for selectedRegionsMembers", jsonObjRegion); Iterator<String> itrMemberNames = jsonObjRegion.keys(); Assert.assertNotNull( "ClusterSelectedRegionsMemberServiceTest :: Server returned null region on member info", itrMemberNames); while (itrMemberNames.hasNext()) { String szMemberName = itrMemberNames.next(); Assert.assertNotNull( "ClusterSelectedRegionsMemberServiceTest :: Server returned null member name", szMemberName); Assert.assertTrue("Server did not return member details", jsonObjRegion.has(szMemberName)); JSONObject jsonMemberObj = jsonObjRegion.getJSONObject(szMemberName); Assert.assertTrue( "ClusterSelectedRegionsMemberServiceTest :: Server did not return 'regionFullPath' of region on member", jsonMemberObj.has("regionFullPath")); String szPath = jsonMemberObj.getString("regionFullPath"); Assert.assertEquals( "ClusterSelectedRegionsMemberServiceTest :: Server returned wrong region path for region on member", szPath, "/GlobalVilage_2/GlobalVilage_9"); } } finally { response.close(); } } catch (Exception failed) { logException(failed); Assert.fail("Exception ! "); } } else { Assert.fail("ClusterSelectedRegionsMemberServiceTest :: No Http connection was established."); } System.out.println( "ClusterSelectedRegionsMemberServiceTest :: ------TESTCASE END : MEMBER INFO RESPONSE CHECK FOR CLUSTER REGION MEMBERS------"); }
From source file:com.vmware.gemfire.tools.pulse.tests.junit.ClusterSelectedRegionsMemberServiceTest.java
/** * * Tests that response is for same region * * *//* w w w .ja va 2 s . c o m*/ @Test public void testResponseRegionOnMemberAccessor() { System.out.println( "ClusterSelectedRegionsMemberServiceTest :: ------TESTCASE BEGIN : ACCESSOR RESPONSE CHECK FOR CLUSTER REGION MEMBERS------"); if (httpclient != null) { try { HttpUriRequest pulseupdate = RequestBuilder.post().setUri(new URI(PULSE_UPDATE_URL)) .addParameter(PULSE_UPDATE_PARAM, PULSE_UPDATE_3_VALUE).build(); CloseableHttpResponse response = httpclient.execute(pulseupdate); try { HttpEntity entity = response.getEntity(); System.out.println("ClusterSelectedRegionsMemberServiceTest :: HTTP request status : " + response.getStatusLine()); BufferedReader respReader = new BufferedReader(new InputStreamReader(entity.getContent())); StringWriter sw = new StringWriter(); PrintWriter pw = new PrintWriter(sw); String sz = null; while ((sz = respReader.readLine()) != null) { pw.print(sz); } String jsonResp = sw.getBuffer().toString(); System.out.println( "ClusterSelectedRegionsMemberServiceTest :: JSON response returned : " + jsonResp); EntityUtils.consume(entity); JSONObject jsonObj = new JSONObject(jsonResp); JSONObject clusterSelectedRegionObj = jsonObj.getJSONObject("ClusterSelectedRegionsMember"); Assert.assertNotNull( "ClusterSelectedRegionsMemberServiceTest :: Server returned null response for ClusterSelectedRegionsMember", clusterSelectedRegionObj); JSONObject jsonObjRegion = clusterSelectedRegionObj.getJSONObject("selectedRegionsMembers"); Assert.assertNotNull( "ClusterSelectedRegionsMemberServiceTest :: Server returned null response for selectedRegionsMembers", jsonObjRegion); Iterator<String> itrMemberNames = jsonObjRegion.keys(); Assert.assertNotNull( "ClusterSelectedRegionsMemberServiceTest :: Server returned null region on member info", itrMemberNames); while (itrMemberNames.hasNext()) { String szMemberName = itrMemberNames.next(); Assert.assertNotNull( "ClusterSelectedRegionsMemberServiceTest :: Server returned null member name", szMemberName); Assert.assertTrue("Server did not return member details", jsonObjRegion.has(szMemberName)); JSONObject jsonMemberObj = jsonObjRegion.getJSONObject(szMemberName); Assert.assertTrue( "ClusterSelectedRegionsMemberServiceTest :: Server did not return 'accessor' of region on member", jsonMemberObj.has("accessor")); String szAccessor = jsonMemberObj.getString("accessor"); Assert.assertTrue( "ClusterSelectedRegionsMemberServiceTest :: Server returned non-boolean value for accessor attribute", ((szAccessor.equalsIgnoreCase("True")) || (szAccessor.equalsIgnoreCase("False")))); } } finally { response.close(); } } catch (Exception failed) { logException(failed); Assert.fail("Exception ! "); } } else { Assert.fail("ClusterSelectedRegionsMemberServiceTest :: No Http connection was established."); } System.out.println( "ClusterSelectedRegionsMemberServiceTest :: ------TESTCASE END : ACCESSOR RESPONSE CHECK FOR CLUSTER REGION MEMBERS------"); }
From source file:cn.com.sinosoft.util.exception.NestableDelegate.java
/** * Captures the stack trace associated with the specified * <code>Throwable</code> object, decomposing it into a list of * stack frames./*from w w w .ja v a 2s.co m*/ * * @param t The <code>Throwable</code>. * @return An array of strings describing each stack frame. * @since 2.0 */ protected String[] getStackFrames(Throwable t) { StringWriter sw = new StringWriter(); PrintWriter pw = new PrintWriter(sw, true); // Avoid infinite loop between decompose() and printStackTrace(). if (t instanceof Nestable) { ((Nestable) t).printPartialStackTrace(pw); } else { t.printStackTrace(pw); } return ExceptionUtils.getStackFrames(sw.getBuffer().toString()); }
From source file:de.haber.xmind2latex.XMindToLatexExporter.java
private String processTemplate(String template, int level, String text) { Map<String, String> data = new HashMap<String, String>(); int maxLevel = getMaxLevel() != -1 ? getMaxLevel() + 1 : templates.size(); int inner = level - maxLevel; data.put("text", text); data.put("level", "" + level); data.put("innerLevel", "" + inner); StringBuilder currentIndent = new StringBuilder(); currentIndent.append(getIndention(inner)); data.put("indent", currentIndent.toString()); StringWriter writer = new StringWriter(); try {//from w w w .jav a2 s.c o m Template t = templateConfig.getTemplate(template); t.process(data, writer); } catch (Exception e) { throw new TemplateNotExistsException(template); } return writer.getBuffer().toString(); }
From source file:org.apereo.portal.rest.ImportExportController.java
@RequestMapping(value = "/entity/{entityType}/{entityId}", method = RequestMethod.GET) public void exportEntity(@PathVariable("entityId") String entityId, @PathVariable("entityType") String entityType, @RequestParam(value = "download", required = false) boolean download, @RequestParam(value = "format", defaultValue = "XML", required = false) String formatType, HttpServletRequest request, HttpServletResponse response) throws IOException, JSONException { final IPerson person = personManager.getPerson(request); final EntityIdentifier ei = person.getEntityIdentifier(); final IAuthorizationPrincipal ap = AuthorizationService.instance().newPrincipal(ei.getKey(), ei.getType()); // if the current user does not have permission to delete this database // object type, return a 401 error code if (!ap.hasPermission(IPermission.PORTAL_SYSTEM, IPermission.EXPORT_ACTIVITY, entityType)) { response.setStatus(HttpServletResponse.SC_UNAUTHORIZED); return;// w ww . j a va 2 s. co m } //Export the data into a string buffer final StringWriter exportBuffer = new StringWriter(); final String fileName = portalDataHandlerService.exportData(entityType, entityId, new StreamResult(exportBuffer)); final PrintWriter responseWriter = response.getWriter(); if (download) { response.setHeader("Content-Disposition", "attachment; filename=\"" + fileName + "." + entityType + "." + formatType.toLowerCase() + "\""); } if ("XML".equalsIgnoreCase(formatType)) { responseWriter.print(exportBuffer.getBuffer()); } else if ("JSON".equalsIgnoreCase(formatType)) { JSONObject json = XML.toJSONObject(exportBuffer.getBuffer().toString()); responseWriter.print(json); } else { response.setStatus(HttpServletResponse.SC_BAD_REQUEST); return; } }
From source file:com.free.exception.NestableDelegate.java
/** * Captures the stack trace associated with the specified * <code>Throwable</code> object, decomposing it into a list of stack frames. * //from www .ja v a2s . co m * @param t * The <code>Throwable</code>. * @return An array of strings describing each stack frame. * @since 2.0 */ protected String[] getStackFrames(Throwable t) { StringWriter sw = new StringWriter(); PrintWriter pw = new PrintWriter(sw, true); // Avoid infinite loop between decompose() and printStackTrace(). if (t instanceof Nestable) { ((Nestable) t).printPartialStackTrace(pw); } else { t.printStackTrace(pw); } return ExceptionHelper.getStackFrames(sw.getBuffer().toString()); }
From source file:org.alfresco.extension.pdftoolkit.repo.action.executer.PDFWatermarkActionExecuter.java
/** * Applies a text watermark (current date, user name, etc, depending on * options)/* w ww. j ava 2 s. c o m*/ * * @param reader * @param writer * @param options */ private void textAction(Action ruleAction, NodeRef actionedUponNodeRef, ContentReader actionedUponContentReader, Map<String, Object> options) { PdfStamper stamp = null; File tempDir = null; ContentWriter writer = null; String watermarkText; StringTokenizer st; Vector<String> tokens = new Vector<String>(); try { // get a temp file to stash the watermarked PDF in before moving to // repo File alfTempDir = TempFileProvider.getTempDir(); tempDir = new File(alfTempDir.getPath() + File.separatorChar + actionedUponNodeRef.getId()); tempDir.mkdir(); File file = new File(tempDir, serviceRegistry.getFileFolderService().getFileInfo(actionedUponNodeRef).getName()); // get the PDF input stream and create a reader for iText PdfReader reader = new PdfReader(actionedUponContentReader.getContentInputStream()); stamp = new PdfStamper(reader, new FileOutputStream(file)); PdfContentByte pcb; // get the PDF pages and position String pages = (String) options.get(PARAM_PAGE); String position = (String) options.get(PARAM_POSITION); String depth = (String) options.get(PARAM_WATERMARK_DEPTH); // create the base font for the text stamp BaseFont bf = BaseFont.createFont((String) options.get(PARAM_WATERMARK_FONT), BaseFont.CP1250, BaseFont.EMBEDDED); // get watermark text and process template with model String templateText = (String) options.get(PARAM_WATERMARK_TEXT); Map<String, Object> model = buildWatermarkTemplateModel(actionedUponNodeRef); StringWriter watermarkWriter = new StringWriter(); freemarkerProcessor.processString(templateText, model, watermarkWriter); watermarkText = watermarkWriter.getBuffer().toString(); // tokenize watermark text to support multiple lines and copy tokens // to vector for re-use st = new StringTokenizer(watermarkText, "\r\n", false); while (st.hasMoreTokens()) { tokens.add(st.nextToken()); } // stamp each page int numpages = reader.getNumberOfPages(); for (int i = 1; i <= numpages; i++) { Rectangle r = reader.getPageSizeWithRotation(i); // if this is an under-text stamp, use getUnderContent. // if this is an over-text stamp, use getOverContent. if (depth.equals(DEPTH_OVER)) { pcb = stamp.getOverContent(i); } else { pcb = stamp.getUnderContent(i); } // set the font and size float size = Float.parseFloat((String) options.get(PARAM_WATERMARK_SIZE)); pcb.setFontAndSize(bf, size); // only apply stamp to requested pages if (checkPage(pages, i, numpages)) { writeAlignedText(pcb, r, tokens, size, position); } } stamp.close(); // Get a writer and prep it for putting it back into the repo //can't use BasePDFActionExecuter.getWriter here need the nodeRef of the destination NodeRef destinationNode = createDestinationNode(file.getName(), (NodeRef) ruleAction.getParameterValue(PARAM_DESTINATION_FOLDER), actionedUponNodeRef); writer = serviceRegistry.getContentService().getWriter(destinationNode, ContentModel.PROP_CONTENT, true); writer.setEncoding(actionedUponContentReader.getEncoding()); writer.setMimetype(FILE_MIMETYPE); // Put it in the repo writer.putContent(file); // delete the temp file file.delete(); } catch (IOException e) { throw new AlfrescoRuntimeException(e.getMessage(), e); } catch (DocumentException e) { throw new AlfrescoRuntimeException(e.getMessage(), e); } finally { if (tempDir != null) { try { tempDir.delete(); } catch (Exception ex) { throw new AlfrescoRuntimeException(ex.getMessage(), ex); } } if (stamp != null) { try { stamp.close(); } catch (Exception ex) { throw new AlfrescoRuntimeException(ex.getMessage(), ex); } } } }
From source file:hermes.impl.DefaultXMLHelper.java
@Override public String toXML(Collection messages) throws JMSException { try {//ww w. j a va 2 s.c o m StringWriter writer = new StringWriter(); MessageSet messageSet = toMessageSet(messages); saveContent(messageSet, writer); return writer.getBuffer().toString(); } catch (Exception ex) { log.error(ex.getMessage(), ex); throw new HermesException(ex); } }