List of usage examples for java.io Writer write
public void write(String str) throws IOException
From source file:bridge.toolkit.commands.S1000DConverter.java
/** * Write the XML in the writer/*from w ww . j a v a 2 s.c om*/ * * @param data * @param isLiteral * @param output * @throws IOException */ private static void writeXMLData(String data, boolean isLiteral, Writer output) throws IOException { char ch[] = data.toCharArray(); for (int i = 0; i < ch.length; i++) { switch (ch[i]) { case '&': output.write("&"); break; case '<': output.write("<"); break; case '>': output.write(">"); break; case '"': if (isLiteral) { output.write("""); break; } default: if (ch[i] >= 128) { output.write("&#"); output.write(new Integer(ch[i]).toString()); output.write(';'); } else if (ch[i] < 32 && ch[i] != '\n' && ch[i] != '\r' && ch[i] != '\t') { throw new IOException("Illegal XML data character " + new Integer(ch[i]).toString()); } else { output.write(ch[i]); } break; } } }
From source file:com.legstar.codegen.CodeGenUtil.java
/** * Apply a velocity template taken from a code generation make xml. * //from w w w . j av a2 s.c o m * @param generatorName the generator name * @param templateName the velocity template to apply * @param modelName the model name * @param model the model providing data for velocity templates * @param parameters additional parameters to pass to template * @param targetFile the file to generate * @param targetCharsetName the target character set. null is interpreted as * the default encoding * @throws CodeGenMakeException if processing fails */ public static void processTemplate(final String generatorName, final String templateName, final String modelName, final Object model, final Map<String, Object> parameters, final File targetFile, final String targetCharsetName) throws CodeGenMakeException { if (LOG.isDebugEnabled()) { LOG.debug("Processing template"); LOG.debug("Template name = " + templateName); LOG.debug("Target file = " + targetFile); LOG.debug("Target charset name = " + targetCharsetName); if (parameters != null) { for (String key : parameters.keySet()) { Object value = parameters.get(key); LOG.debug("Parameter " + key + " = " + value); } } } VelocityContext context = CodeGenUtil.getContext(generatorName); context.put(modelName, model); context.put("serialVersionID", Long.toString(mRandom.nextLong()) + 'L'); if (parameters != null) { for (String key : parameters.keySet()) { context.put(key, parameters.get(key)); } } StringWriter w = new StringWriter(); try { Velocity.mergeTemplate(templateName, "UTF-8", context, w); Writer out = null; try { FileOutputStream fos = new FileOutputStream(targetFile); OutputStreamWriter osw; if (targetCharsetName == null) { osw = new OutputStreamWriter(fos); } else { osw = new OutputStreamWriter(fos, targetCharsetName); } out = new BufferedWriter(osw); out.write(w.toString()); } catch (IOException e) { throw new CodeGenMakeException(e); } finally { if (out != null) { out.close(); } } } catch (ResourceNotFoundException e) { throw new CodeGenMakeException(e); } catch (ParseErrorException e) { throw new CodeGenMakeException(e); } catch (MethodInvocationException e) { throw new CodeGenMakeException(e); } catch (Exception e) { throw new CodeGenMakeException(e); } }
From source file:bridge.toolkit.commands.S1000DConverter.java
/** * Iterate through the DOM tree//from ww w . j a v a 2 s . c o m * * @param node * @param output * @param isDocument * @param encoding * @param internalSubset * @throws IOException */ static void writeNode(Node node, Writer output, boolean isDocument, String encoding, String internalSubset) throws IOException { if (isDocument) { if (encoding == null) output.write("<?xml version=\"1.0\"?>\n\n"); else output.write("<?xml version=\"1.0\" encoding=\"" + encoding + "\"?>\n\n"); DocumentType doctype = node.getOwnerDocument().getDoctype(); if (doctype != null) { String pubid = doctype.getPublicId(); String sysid = doctype.getSystemId(); output.write("<!DOCTYPE "); output.write(node.getNodeName()); if (pubid != null) { output.write(" PUBLIC \""); output.write(pubid); if (sysid != null) { output.write("\" \""); output.write(sysid); } output.write('"'); } else if (sysid != null) { output.write(" SYSTEM \""); output.write(sysid); output.write('"'); } String subset = internalSubset; if (subset == null) subset = doctype.getInternalSubset(); if (subset != null) { output.write(" ["); output.write(subset); output.write(']'); } output.write(">\n\n"); } } writeNode(node, output); if (isDocument) output.write("\n"); }
From source file:com.adr.raspberryleds.HTTPUtils.java
public static JSONObject execPOST(String address, JSONObject params) throws IOException { BufferedReader readerin = null; Writer writerout = null; try {//from w ww.j a v a2s.c om URL url = new URL(address); String query = params.toString(); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setReadTimeout(10000 /* milliseconds */); connection.setConnectTimeout(15000 /* milliseconds */); connection.setRequestMethod("POST"); connection.setAllowUserInteraction(false); connection.setUseCaches(false); connection.setDoInput(true); connection.setDoOutput(true); connection.addRequestProperty("Content-Type", "application/json,encoding=UTF-8"); connection.addRequestProperty("Content-length", String.valueOf(query.length())); writerout = new OutputStreamWriter(connection.getOutputStream(), "UTF-8"); writerout.write(query); writerout.flush(); writerout.close(); writerout = null; int responsecode = connection.getResponseCode(); if (responsecode == HttpURLConnection.HTTP_OK) { StringBuilder text = new StringBuilder(); readerin = new BufferedReader(new InputStreamReader(connection.getInputStream(), "UTF-8")); String line = null; while ((line = readerin.readLine()) != null) { text.append(line); text.append(System.getProperty("line.separator")); } JSONObject result = new JSONObject(text.toString()); if (result.has("exception")) { throw new IOException( MessageFormat.format("Remote exception: {0}.", result.getString("exception"))); } else { return result; } } else { throw new IOException(MessageFormat.format("HTTP response error: {0}. {1}", Integer.toString(responsecode), connection.getResponseMessage())); } } catch (JSONException ex) { throw new IOException(MessageFormat.format("Parse exception: {0}.", ex.getMessage())); } finally { if (writerout != null) { writerout.close(); writerout = null; } if (readerin != null) { readerin.close(); readerin = null; } } }
From source file:org.opennms.ng.services.snmpconfig.SnmpPeerFactory.java
public static void saveToFile(final File file) throws UnsupportedEncodingException, FileNotFoundException, IOException { // Marshal to a string first, then write the string to the file. This // way the original config // isn't lost if the XML from the marshal is hosed. final String marshalledConfig = marshallConfig(); SnmpPeerFactory.getWriteLock().lock(); FileOutputStream out = null;/*from w ww . jav a 2 s . com*/ Writer fileWriter = null; try { if (marshalledConfig != null) { out = new FileOutputStream(file); fileWriter = new OutputStreamWriter(out, "UTF-8"); fileWriter.write(marshalledConfig); fileWriter.flush(); fileWriter.close(); } } finally { IOUtils.closeQuietly(fileWriter); IOUtils.closeQuietly(out); SnmpPeerFactory.getWriteLock().unlock(); } }
From source file:com.adito.util.Utils.java
private static void zeropad(Writer out, String s, int width) throws IOException { while (width > s.length()) { out.write('0'); width--;//from www.ja va 2s . co m } out.write(s); }
From source file:at.riemers.velocity2js.velocity.Velocity2Js.java
public static void generate(String templateName, String functionName, Writer writer, ResourceBundle bundle) throws Exception { Template template = null;/* w w w . j a v a 2s . com*/ //try { template = Velocity.getTemplate(templateName); /*} catch( ResourceNotFoundException rnfe ) { log.error("Example : error : cannot find template " + templateName ); errors.add(rnfe); } catch( ParseErrorException pee ) { //Velocity2JsParseErrorException vpex = new Velocity2JsParseErrorException(pee, ) log.error("Example : Syntax error in template " + templateName + ":" + pee ); errors.add(pee); }*/ if (template != null) { template.process(); SimpleNode node = (SimpleNode) template.getData(); VelocityVisitor visitor = new VelocityVisitor(bundle); writer.write(visitor.visit(node, functionName).toString()); } }
From source file:de.tudarmstadt.ukp.wikipedia.parser.html.HtmlWriter.java
public static void writeFile(String filename, String encoding, String text) { File outFile = new File(filename); Writer destFile = null; try {/*from w w w . j a v a 2s . c om*/ destFile = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(outFile), encoding)); } catch (UnsupportedEncodingException e1) { logger.error("Unsupported encoding exception while opening file " + outFile.getAbsolutePath()); e1.printStackTrace(); } catch (FileNotFoundException e1) { logger.error("File " + outFile.getAbsolutePath() + " not found."); e1.printStackTrace(); } try { destFile.write(text); } catch (IOException e) { logger.error("IO exception while writing file " + outFile.getAbsolutePath()); e.printStackTrace(); } try { destFile.close(); } catch (IOException e) { logger.error("IO exception while closing file " + outFile.getAbsolutePath()); e.printStackTrace(); } }
From source file:com.discursive.jccook.net.SMTPExample.java
public void start() throws SocketException, IOException { SMTPClient client = new SMTPClient(); client.connect("www.discursive.com"); int response = client.getReplyCode(); if (SMTPReply.isPositiveCompletion(response)) { client.setSender("tobrien@discursive.com"); client.addRecipient("tobrien@iesabroad.org"); Writer message = client.sendMessageData(); message.write("This is a test message"); message.close();/*ww w .j a v a 2s . c o m*/ boolean success = client.completePendingCommand(); if (success) { System.out.println("Message sent"); } } else { System.out.println("Error communicating with SMTP server"); } client.disconnect(); }
From source file:com.netflix.zuul.scriptManager.FilterScriptManagerServlet.java
/** * Set an error code and print out the usage docs to the response with a preceding error message * * @param statusCode// w w w . j a v a 2 s.c om * @param response */ private static void setUsageError(int statusCode, String message, HttpServletResponse response) { response.setStatus(statusCode); try { Writer w = response.getWriter(); if (message != null) { w.write(message + "\n\n"); } w.write(getUsageDoc()); } catch (Exception e) { logger.error("Failed to output usage error.", e); // won't throw exception because this is not critical, logging the error is enough } }