List of usage examples for java.io StringWriter getBuffer
public StringBuffer getBuffer()
From source file:Main.java
public static StringBuffer transformToString(Source xmlSource, Source xslSource) { StringWriter writer = new StringWriter(); Transformer transformer;//from w w w .ja v a 2 s.c o m try { if (xslSource == null) { transformer = TransformerFactory.newInstance().newTransformer(); } else { transformer = TransformerFactory.newInstance().newTransformer(xslSource); } transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes"); transformer.transform(xmlSource, new StreamResult(writer)); return writer.getBuffer(); } catch (Exception e) { e.printStackTrace(); return writer.getBuffer(); } finally { try { writer.close(); } catch (Exception e) { e.printStackTrace(); } } }
From source file:com.viettel.ws.client.JDBCUtil.java
/** * Convert a document to string/* w ww.j av a2 s. c o m*/ * * @param doc a input document * @return a string of document * @throws IOException If error when convert */ public static String serialize(Document doc) throws IOException { StringWriter writer = new StringWriter(); OutputFormat format = new OutputFormat(); format.setIndenting(true); XMLSerializer serializer = new XMLSerializer(writer, format); serializer.serialize(doc); return writer.getBuffer().toString(); }
From source file:com.isa.utiles.Utiles.java
public static String printDocument(Document doc) { try {/*from ww w .ja v a 2s.co m*/ TransformerFactory tf = TransformerFactory.newInstance(); Transformer transformer = tf.newTransformer(); transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "no"); StringWriter writer = new StringWriter(); transformer.transform(new DOMSource(doc), new StreamResult(writer)); String output = writer.getBuffer().toString(); return output; } catch (TransformerConfigurationException ex) { return ""; } catch (TransformerException ex) { return ""; } }
From source file:org.apache.geode.management.internal.beans.QueryDataFunction.java
private static String wrapResult(final String str) { StringWriter w = new StringWriter(); synchronized (w.getBuffer()) { w.write("{\"result\":"); w.write(str);/*from w w w. j a va2 s .c o m*/ w.write("}"); return w.toString(); } }
From source file:com.glaf.core.util.IOUtils.java
/** * read string./*from w w w . j a v a 2s. co m*/ * * @param reader * Reader instance. * @return String. * @throws IOException */ public static String read(Reader reader) throws IOException { StringWriter writer = new StringWriter(); try { write(reader, writer); return writer.getBuffer().toString(); } finally { writer.close(); } }
From source file:eu.sisob.uma.restserver.TaskManager.java
/** * /*from w ww.j a v a 2 s . co m*/ * Is possible that use thee locker of AuthorizationManager * @param user * @param pass * @param task_code * @param retrieveTiming * @param retrieveDataUrls * @param retrieveFeedback * @return */ public static OutputTaskStatus getTaskStatus(String user, String pass, String task_code, boolean retrieveTiming, boolean retrieveDataUrls, boolean retrieveFeedback) { boolean valid = true; OutputTaskStatus task_status = new OutputTaskStatus(); task_status.name = task_code; task_status.task_code = task_code; if (user != null && pass != null && task_code != null) { StringWriter message = new StringWriter(); if (AuthorizationManager.validateAccess(user, pass, message)) { message.getBuffer().setLength(0); String code_task_folder = TASKS_USERS_PATH + File.separator + user + File.separator + task_code; File file = new File(code_task_folder); if (file.exists()) { /* Retrieve data created*/ if (retrieveTiming) { task_status.date_created = (new SimpleDateFormat("yyyy.MM.dd G - HH:mm:ss")) .format(new Date(file.lastModified())); File kind_file = new File(code_task_folder + File.separator + kind_flag_file); if (kind_file.exists()) { try { task_status.kind = FileUtils.readFileToString(kind_file); } catch (FileNotFoundException ex) { ProjectLogger.LOGGER.error("Error, cant read " + kind_file.getAbsolutePath()); task_status.kind = "none"; } catch (IOException ex) { ProjectLogger.LOGGER.error("Error, cant read " + kind_file.getAbsolutePath()); task_status.kind = "none"; } } else { task_status.kind = "none"; } } File begin_file = new File(code_task_folder + File.separator + begin_flag_file); if (begin_file.exists()) { if (retrieveTiming) { task_status.date_started = (new SimpleDateFormat("yyyy.MM.dd G - HH:mm:ss")) .format(new Date(begin_file.lastModified())); } File end_file = new File(code_task_folder + File.separator + end_flag_file); if (end_file.exists()) { if (retrieveTiming) { task_status.date_finished = (new SimpleDateFormat("yyyy.MM.dd G - HH:mm:ss")) .format(new Date(end_file.lastModified())); } valid = true; task_status.status = (OutputTaskStatus.TASK_STATUS_EXECUTED); task_status.message = (TheResourceBundle.getString("Jsp Task Executed Msg")); if (task_status.status.equals(OutputTaskStatus.TASK_STATUS_EXECUTED)) { if (retrieveDataUrls) { task_status.result = ""; List<String> fresults = AuthorizationManager.getResultFiles(user, task_code); for (String fresult : fresults) { String file_url = AuthorizationManager.getGetFileUrl(user, pass, task_code, fresult, "results"); task_status.result += fresult + ";" + file_url + ";"; } task_status.source = ""; List<String> fsources = AuthorizationManager.getSourceFiles(user, task_code); for (String fsource : fsources) { String file_url = AuthorizationManager.getGetFileUrl(user, pass, task_code, fsource, ""); task_status.source += fsource + ";" + file_url + ";"; } //Also do method to build path task_status.verbose = ""; List<String> fverboses = AuthorizationManager.getVerboseFiles(user, task_code); for (String fverbose : fverboses) { String file_url = AuthorizationManager.getGetFileUrlToShow(user, pass, task_code, fverbose, "verbose"); task_status.verbose += fverbose + ";" + file_url + ";"; } File errors_file = new File( code_task_folder + File.separator + AuthorizationManager.results_dirname + File.separator + error_flag_file); if (errors_file.exists()) { try { task_status.errors = FileUtils.readFileToString(errors_file); } catch (IOException ex) { ProjectLogger.LOGGER .error("Error, cant read " + errors_file.getAbsolutePath()); task_status.errors = "Error, cant read " + errors_file.getName(); } } File params_file = new File( code_task_folder + File.separator + params_flag_file); task_status.params = ""; List<InputParameter> params_list = new ArrayList<InputParameter>(); if (params_file.exists()) { try { String params = FileUtils.readFileToString(params_file); if (!params.equals("")) { String[] lines = params.split("\r\n"); for (String line : lines) { String[] values = line.split("\\$"); if (values.length > 1) { if (!task_status.params.equals("")) task_status.params += ";"; task_status.params += values[0] + ";" + values[1]; } } task_status.params = task_status.params; } } catch (IOException ex) { ProjectLogger.LOGGER .error("Error, cant read " + params_file.getAbsolutePath()); task_status.errors = "Error, cant read " + params_file.getName(); } } } if (retrieveFeedback) { File feedback_file = new File( code_task_folder + File.separator + AuthorizationManager.results_dirname + File.separator + feedback_flag_file); String feedback = ""; if (feedback_file.exists()) { try { feedback = FileUtils.readFileToString(feedback_file); } catch (IOException ex) { ProjectLogger.LOGGER .error("Error, cant read " + feedback_file.getAbsolutePath()); } } task_status.feedback = feedback; } } } else { valid = true; task_status.status = (OutputTaskStatus.TASK_STATUS_EXECUTING); task_status.message = (TheResourceBundle.getString("Jsp Task Executing Msg")); } } else { valid = true; task_status.status = (OutputTaskStatus.TASK_STATUS_TO_EXECUTE); task_status.message = (TheResourceBundle.getString("Jsp Task To Execute Msg")); } } else { valid = false; task_status.status = (OutputTaskStatus.TASK_STATUS_NO_ACCESS); task_status.message = (TheResourceBundle.getString("Jsp Task Unknowed Msg")); } } else { valid = false; task_status.status = (OutputTaskStatus.TASK_STATUS_NO_AUTH); task_status.message = message.toString(); } } else { valid = false; task_status.status = (OutputTaskStatus.TASK_STATUS_NO_AUTH); task_status.message = (TheResourceBundle.getString("Jsp Params Invalid Msg")); } return task_status; }
From source file:com.apporiented.hermesftp.utils.IOUtils.java
/** * Reads an arbitrary text resource from the class path. * //from w w w .j a v a2 s . c o m * @param name The name of the resource. * @param encoding The text encoding. * @return The text. * @throws IOException Error on accessing the resource. */ public static String loadTextResource(String name, String encoding) throws IOException { String result = null; StringWriter sw = null; InputStreamReader isr = null; if (encoding == null) { encoding = "UTF-8"; } try { InputStream is = IOUtils.class.getResourceAsStream(name); isr = new InputStreamReader(is, encoding); sw = new StringWriter(); int c; while ((c = isr.read()) != -1) { sw.write(c); } result = sw.getBuffer().toString(); } finally { closeGracefully(isr); closeGracefully(sw); } return result; }
From source file:Main.java
/** * convert node object into String object. * @param node//ww w . java 2s .c o m * @param omitXmlDecl * @return */ public static String dom2String(Node node, boolean omitXmlDecl) { Source source = new DOMSource(node); StringWriter stringWriter = new StringWriter(); Result result = new StreamResult(stringWriter); try { TransformerFactory factory = TransformerFactory.newInstance(); Transformer transformer = factory.newTransformer(); if (omitXmlDecl) transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes"); transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8"); transformer.transform(source, result); } catch (Exception e) { throw new RuntimeException(e); } return stringWriter.getBuffer().toString(); }
From source file:gr.abiss.calipso.util.PdfUtils.java
public static byte[] getPdf(CalipsoService calipso, Item item, String template, Component callerComponent) { ByteArrayOutputStream os = new ByteArrayOutputStream(); String html = null;/*from w w w . j a v a 2 s . c om*/ try { Localizer localizer = callerComponent.getLocalizer(); if (template != null) { // template exists, use it Reader templateReader = new StringReader(template); // create a Velocity context object and add the asset final VelocityContext context = new VelocityContext(); context.put("item", item); context.put("calipso", calipso); // create a writer for capturing the Velocity output StringWriter writer = new StringWriter(); // execute the velocity script and capture the output in writer Velocity.evaluate(context, writer, item.getRefId(), templateReader); // get the output as a string html = writer.getBuffer().toString(); } else { // no template exists, just output manual HTML to feed xhtmlrenderer StringBuffer htmlBuffer = getDefaultHeader(); htmlBuffer.append("<h1>").append( localizer.getString(item.getSpace().getNameTranslationResourceKey(), callerComponent)) .append(": ").append(item.getRefId()).append("</h1>"); // htmlBuffer.append("<table cellspacing='0'>"); // htmlBuffer.append("<tr><th>") // .append(localizer.getString("asset.form.inventoryCode", callerComponent)) // .append("</th><td>") // .append(asset.getInventoryCode()); // htmlBuffer.append("</td></tr>"); // if(MapUtils.isNotEmpty(asset.getCustomAttributes())){ // Map<AssetTypeCustomAttribute,String> attrs = asset.getCustomAttributes(); // for(Entry<AssetTypeCustomAttribute, String> entry : attrs.entrySet()){ // AssetTypeCustomAttribute customAttr = entry.getKey(); // htmlBuffer.append("<tr><th>") // .append(localizer.getString(customAttr.getNameTranslationResourceKey(), callerComponent)) // .append("</th><td>"); // // if (customAttr.getFormType().equals(AssetTypeCustomAttribute.FORM_TYPE_SELECT) // || customAttr.getFormType().equals(AssetTypeCustomAttribute.FORM_TYPE_OPTIONS_TREE)) { // htmlBuffer.append(XmlUtils.escapeHTML(localizer.getString(customAttr.getLookupValue().getNameTranslationResourceKey(), null))); // } // else if (customAttr.getFormType().equals(AssetTypeCustomAttribute.FORM_TYPE_USER)) { // User user = customAttr.getUserValue(); // htmlBuffer.append(user!=null?XmlUtils.escapeHTML(user.getFullName()):""); // } else if (customAttr.getFormType().equals(AssetTypeCustomAttribute.FORM_TYPE_ORGANIZATION)) { // Organization org = customAttr.getOrganizationValue(); // htmlBuffer.append(org!=null?XmlUtils.escapeHTML(org.getName()):""); // } else if (customAttr.getFormType().equals(AssetTypeCustomAttribute.FORM_TYPE_ASSET)) { // Asset innerAsset = customAttr.getAssetValue(); // htmlBuffer.append(innerAsset!=null?XmlUtils.escapeHTML(innerAsset.getInventoryCode()):""); // } else if (customAttr.getFormType().equals(AssetTypeCustomAttribute.FORM_TYPE_COUNTRY)) { // Country country = customAttr.getCountryValue(); // htmlBuffer.append(country!=null?localizer.getString("country."+country.getId(), callerComponent):""); // } else { // htmlBuffer.append(XmlUtils.escapeHTML(entry.getValue())); // } // htmlBuffer.append("</td></tr>"); // } // } // htmlBuffer.append("</table>"); htmlBuffer.append("</body></html>"); html = htmlBuffer.toString(); } } catch (Exception e) { logger.error("Failed to creare PDF for item, html: \n" + html, e); } // convert HTML string to PDF and store it in the buffer output stream writePdf(calipso, os, html); return os.toByteArray(); }
From source file:gr.abiss.calipso.util.PdfUtils.java
public static byte[] getPdf(CalipsoService calipso, Asset asset, Component callerComponent) { ByteArrayOutputStream os = new ByteArrayOutputStream(); String html = null;/*from w ww . j a v a2 s . com*/ try { Localizer localizer = callerComponent.getLocalizer(); String template = calipso.getPrintTemplateTextForAsset(asset.getId());// asset.getAssetType().getPrintingTemplate().getTemplateText(); if (template != null) { // template exists, use it Reader templateReader = new StringReader(template); // create a Velocity context object and add the asset final VelocityContext context = new VelocityContext(); context.put("rootAsset", asset); context.put("calipso", calipso); // create a writer for capturing the Velocity output StringWriter writer = new StringWriter(); // execute the velocity script and capture the output in writer Velocity.evaluate(context, writer, asset.getInventoryCode(), templateReader); // get the output as a string html = writer.getBuffer().toString(); // logger.debug("Velocity result: \n"+html); } else { StringBuffer htmlBuffer = getDefaultHeader(); htmlBuffer .append("<h1>").append(localizer .getString(asset.getAssetType().getNameTranslationResourceKey(), callerComponent)) .append("</h1>"); htmlBuffer.append("<table cellspacing='0'>"); htmlBuffer.append("<tr><th>") .append(localizer.getString("asset.form.inventoryCode", callerComponent)) .append("</th><td>").append(asset.getInventoryCode()); htmlBuffer.append("</td></tr>"); if (MapUtils.isNotEmpty(asset.getCustomAttributes())) { Map<AssetTypeCustomAttribute, String> attrs = asset.getCustomAttributes(); for (Entry<AssetTypeCustomAttribute, String> entry : attrs.entrySet()) { AssetTypeCustomAttribute customAttr = entry.getKey(); htmlBuffer .append("<tr><th>").append(localizer .getString(customAttr.getNameTranslationResourceKey(), callerComponent)) .append("</th><td>"); if (customAttr.getFormType().equals(AssetTypeCustomAttribute.FORM_TYPE_SELECT) || customAttr .getFormType().equals(AssetTypeCustomAttribute.FORM_TYPE_OPTIONS_TREE)) { htmlBuffer.append(XmlUtils.escapeHTML(localizer .getString(customAttr.getLookupValue().getNameTranslationResourceKey(), null))); } else if (customAttr.getFormType().equals(AssetTypeCustomAttribute.FORM_TYPE_USER)) { User user = customAttr.getUserValue(); htmlBuffer.append(user != null ? XmlUtils.escapeHTML(user.getFullName()) : ""); } else if (customAttr.getFormType() .equals(AssetTypeCustomAttribute.FORM_TYPE_ORGANIZATION)) { Organization org = customAttr.getOrganizationValue(); htmlBuffer.append(org != null ? XmlUtils.escapeHTML(org.getName()) : ""); } else if (customAttr.getFormType().equals(AssetTypeCustomAttribute.FORM_TYPE_ASSET)) { Asset innerAsset = customAttr.getAssetValue(); htmlBuffer.append( innerAsset != null ? XmlUtils.escapeHTML(innerAsset.getInventoryCode()) : ""); } else if (customAttr.getFormType().equals(AssetTypeCustomAttribute.FORM_TYPE_COUNTRY)) { Country country = customAttr.getCountryValue(); htmlBuffer.append(country != null ? localizer.getString("country." + country.getId(), callerComponent) : ""); } else { htmlBuffer.append(XmlUtils.escapeHTML(entry.getValue())); } htmlBuffer.append("</td></tr>"); } } htmlBuffer.append("</table>"); htmlBuffer.append("</body></html>"); html = htmlBuffer.toString(); } // convert HTML string to PDF and store it in the buffer output stream } catch (Exception e) { logger.error("Failed to creare PDF for asset, html: \n" + html, e); } writePdf(calipso, os, html); return os.toByteArray(); }