List of usage examples for java.io Writer flush
public abstract void flush() throws IOException;
From source file:fi.uta.infim.usaproxyreportgenerator.App.java
/** * Generates the actual HTML report file for a single session. * @param session the session to generate the report for * @param outputDir output directory for reports * @throws IOException if the report template cannot be read * @throws TemplateException if there is a problem processing the template *//*from ww w . j a v a 2 s. com*/ private static void generateHTMLReport(UsaProxySession session, File outputDir) throws IOException, TemplateException { JSONObject httptraffic = new JSONObject(); for (UsaProxyHTTPTraffic t : session.getSortedHttpTrafficSessions()) { System.out.print("processing traffic id " + t.getSessionID() + "... "); httptraffic.accumulate(t.getSessionID().toString(), JSONObject.fromObject(t, config)); } JSONObject tf = new JSONObject(); tf.accumulate("DEFAULTELEMENTCOLOR", UsaProxyHTTPTrafficJSONProcessor.DEFAULTELEMENTCOLOR); tf.accumulate("DEFAULTVIEWPORTCOLOR", UsaProxyHTTPTrafficJSONProcessor.DEFAULTVIEWPORTCOLOR); tf.accumulate("httptraffics", httptraffic); Map<String, Object> sessionRoot = new HashMap<String, Object>(); sessionRoot.put("data", tf.toString()); sessionRoot.put("timestamp", session.getStart()); sessionRoot.put("id", session.getSessionID()); sessionRoot.put("ip", session.getAddress().getHostAddress()); sessionRoot.put("httpTraffics", session.getSortedHttpTrafficSessions()); Configuration cfg = new Configuration(); // Specify the data source where the template files come from. cfg.setClassForTemplateLoading(App.class, "/" + TEMPLATEDIR); cfg.setObjectWrapper(new DefaultObjectWrapper()); Template temp = cfg.getTemplate(REPORTTEMPLATE); Map<String, Object> root = new HashMap<String, Object>(); root.put("session", sessionRoot); root.put("httpTrafficListIdPrefix", HTTPTRAFFICLISTIDPREFIX); root.put("placeholderIdPrefix", PLACEHOLDERIDPREFIX); try { Writer out = new OutputStreamWriter(new FileOutputStream( new File(outputDir, "usaproxy-session-report-" + session.getSessionID() + ".html"))); temp.process(root, out); out.flush(); } catch (IOException e) { System.err.println("Error opening output file: " + e.getLocalizedMessage()); } }
From source file:com.sample.ecommerce.util.ElasticSearchUtil.java
public static String render(String templateName, Object model) { Writer writer = new StringWriter(); MustacheFactory mf = new DefaultMustacheFactory(); Mustache mustache = mf.compile(/*from ww w . j a v a2s. com*/ new StringReader(getContentFromClasspath("/search/templates/" + templateName + ".mustache")), "example"); mustache.execute(writer, model); try { writer.flush(); } catch (IOException ex) { Logger.getLogger(ElasticSearchUtil.class.getName()).log(Level.SEVERE, null, ex); } return writer.toString(); }
From source file:FileCopyUtils.java
/** * Copy the contents of the given Reader to the given Writer. * Closes both when done./*from w ww . jav a 2 s. c o m*/ * @param in the Reader to copy from * @param out the Writer to copy to * @return the number of characters copied * @throws IOException in case of I/O errors */ public static int copy(Reader in, Writer out) throws IOException { try { int byteCount = 0; char[] buffer = new char[BUFFER_SIZE]; int bytesRead = -1; while ((bytesRead = in.read(buffer)) != -1) { out.write(buffer, 0, bytesRead); byteCount += bytesRead; } out.flush(); return byteCount; } finally { try { in.close(); } catch (IOException ex) { System.out.println("Could not close Reader" + ex); } try { out.close(); } catch (IOException ex) { System.out.println("Could not close Writer:" + ex); } } }
From source file:ch.zhaw.iamp.rct.weights.Weights.java
private static void matrixToCsv(final RealMatrix matrix, final String targetFilePath) throws IOException { Writer out = new FileWriter(targetFilePath); for (int i = 0; i < matrix.getRowDimension(); ++i) { for (int j = 0; j < matrix.getColumnDimension(); ++j) { out.append("" + matrix.getEntry(i, j)); if (j < matrix.getColumnDimension() - 1) { out.append(","); }// w w w . j a v a2s . co m } out.append("\n"); out.flush(); } }
From source file:com.cisco.dvbu.ps.common.scriptutil.ScriptUtil.java
/** * Create a command file for UNIX or Windows from name value pairs strings constructed based on passed in xml content * @param xmlFilePath xml File Path/*ww w .j a v a 2 s . co m*/ * @param nodeName String return name values for passed in node name and node value. * is treated as all nodes * @param nodeValue String return name values for passed in node name and node value. * is treated as all node values * @param options additional options to return the node name or attributes such as "-noid -noattributes" * @param commandOutputFile The fully qualifed path of the command output file * @param commandHeader The command file header such as #!/bin/bash * @param commandType The type of command file [UNIX|WINDOWS] {use export for UNIX, use set for WINDOWS) * UNIX: export name="value" * WINDOWS: set name=value * usage createCommandFileFromXML xmlFilePath * * "-noid -noattributes" /Users/rthummal/mywork/clients/ps/CisDeployTool/resources/abc.sh #!/bin/bash UNIX * usage createCommandFileFromXML xmlFilePath hostname localhost "" C:\opt\pdtool/abc.bat "echo off" WINDOWS * usage createCommandFileFromXML xmlFilePath hostname * "-noid" /opt/pdtool/abc.sh #!/bin/bash UNIX */ public static void createCommandFileFromXML(String xmlFilePath, String nodeName, String nodeValue, String options, String commandOutputFile, String commandHeader, String commandType) { boolean win = false; String cmdPrefix = "export "; if (commandType != null && commandType.equals("WINDOWS")) { win = true; cmdPrefix = "set "; } String nameValuePairs = XMLUtils.getNameValuePairsFromXML(xmlFilePath, null, null, nodeName, nodeValue, options); if (nameValuePairs != null) { StringBuffer sb = new StringBuffer(); sb.append(commandHeader + "\n"); StringTokenizer st = new StringTokenizer(nameValuePairs, "|"); while (st.hasMoreTokens()) { sb.append(cmdPrefix); String nameValuePair = st.nextToken(); if (!win) { nameValuePair = nameValuePair.replace("=", "=\""); nameValuePair += "\""; } sb.append(nameValuePair + "\n"); } try { Writer out = new OutputStreamWriter(new FileOutputStream(commandOutputFile)); out.write(sb.toString()); out.flush(); } catch (FileNotFoundException e) { logger.error("Could not wirte to command file " + commandOutputFile, e); throw new ValidationException(e.getMessage(), e); } catch (IOException e) { logger.error("Could not wirte to command file " + commandOutputFile, e); throw new ValidationException(e.getMessage(), e); } } }
From source file:com.netxforge.oss2.core.xml.CastorUtils.java
/** * Marshall to a string first, then write the string to the file. This * way the original config isn't lost if the xml from the marshall is hosed. * * FIXME: This could still stand to write to a temporary file and/or make a * temporary backup of the production configuration file. * * @param config a {@link java.lang.Object} object. * @param cfgFile a {@link java.io.File} object. * @throws org.exolab.castor.xml.MarshalException if any. * @throws org.exolab.castor.xml.ValidationException if any. * @throws java.io.IOException if any./*from w w w.j a v a2s .c om*/ */ public static void marshalViaString(Object config, File cfgFile) throws MarshalException, ValidationException, IOException { StringWriter stringWriter = new StringWriter(); marshal(config, stringWriter); Writer fileWriter = new OutputStreamWriter(new FileOutputStream(cfgFile), "UTF-8"); fileWriter.write(stringWriter.toString()); fileWriter.flush(); fileWriter.close(); }
From source file:org.apache.manifoldcf.authorities.authorities.jira.JiraSession.java
private static String convertToString(HttpResponse httpResponse) throws IOException { HttpEntity entity = httpResponse.getEntity(); if (entity != null) { InputStream is = entity.getContent(); try {//from ww w . ja v a 2s . co m char[] buffer = new char[65536]; Reader r = new InputStreamReader(is, getCharSet(entity)); Writer w = new StringWriter(); try { while (true) { int amt = r.read(buffer); if (amt == -1) break; w.write(buffer, 0, amt); } } finally { w.flush(); } return w.toString(); } finally { is.close(); } } return ""; }
From source file:com.android.email.mail.transport.Rfc822Output.java
/** * Write text (either as main body or inside a multipart), preceded by appropriate headers. * * Note this always uses base64, even when not required. Slightly less efficient for * US-ASCII text, but handles all formats even when non-ascii chars are involved. A small * optimization might be to prescan the string for safety and send raw if possible. * * @param writer the output writer/*from w ww . java 2 s .co m*/ * @param out the output stream inside the writer (used for byte[] access) * @param text The original text of the message */ private static void writeTextWithHeaders(Writer writer, OutputStream out, String text) throws IOException { writeHeader(writer, "Content-Type", "text/plain; charset=utf-8"); writeHeader(writer, "Content-Transfer-Encoding", "base64"); writer.write("\r\n"); byte[] bytes = text.getBytes("UTF-8"); writer.flush(); out.write(Base64.encode(bytes, Base64.CRLF)); }
From source file:Main.java
/** * Write the entire contents of the supplied string to the given writer. This method always flushes and closes the writer when * finished.//from w w w . j a v a 2 s . c om * * @param content the content to write to the writer; may be null * @param writer the writer to which the content is to be written * @throws IOException * @throws IllegalArgumentException if the writer is null */ public static void write(String content, Writer writer) throws IOException { boolean error = false; try { if (content != null) { writer.write(content); } } catch (IOException e) { error = true; // this error should be thrown, even if there is an error flushing/closing writer throw e; } catch (RuntimeException e) { error = true; // this error should be thrown, even if there is an error flushing/closing writer throw e; } finally { try { writer.flush(); } catch (IOException e) { if (!error) throw e; } finally { try { writer.close(); } catch (IOException e) { if (!error) throw e; } } } }
From source file:com.github.mavogel.ilias.printer.VelocityOutputPrinter.java
/** * Prints the header, content and output to the given print stream with a custom template. * * @param outputType the desired output type. @see {@link OutputType} * @param templateName the name of the template * @param contextMap the context for velocity * @throws Exception in case of a error, so the caller can handle it *//*from www. j a v a 2 s .c o m*/ private static void printWithCustomTemplate(final OutputType outputType, final String templateName, final Map<String, Object> contextMap) throws Exception { Velocity.init(); Writer writer = null; try { final Template template = Velocity.getTemplate(templateName); final VelocityContext context = new VelocityContext(); contextMap.forEach((k, v) -> context.put(k, v)); writer = new BufferedWriter(createFileWriter(outputType, templateName)); template.merge(context, writer); writer.flush(); } catch (ResourceNotFoundException rnfe) { LOG.error("Couldn't find the template with name '" + templateName + "'"); throw new Exception(rnfe.getMessage()); } catch (ParseErrorException pee) { LOG.error("Syntax error: problem parsing the template ' " + templateName + "': " + pee.getMessage()); throw new Exception(pee.getMessage()); } catch (MethodInvocationException mie) { LOG.error( "An invoked method on the template '" + templateName + "' threw an error: " + mie.getMessage()); throw new Exception(mie.getMessage()); } catch (Exception e) { LOG.error("Error: " + e.getMessage()); throw e; } finally { if (writer != null) writer.close(); } }