List of usage examples for java.io StringWriter close
public void close() throws IOException
From source file:org.kalypso.ogc.sensor.diagview.grafik.GrafikLauncher.java
/** * Opens the grafik tool using an observation template xml object. Note: this method should be called using a * WorkspaceModifyOperation.//from w ww.j a v a2 s . c o m * * @param fileName * the filename to use for the grafik template file * @param odt * the xml binding object * @throws SensorException */ public static IStatus startGrafikODT(final String fileName, final Obsdiagview odt, final IFolder dest, final IProgressMonitor monitor) throws SensorException, CoreException { final String taskName = Messages.getString("GrafikLauncher.0"); //$NON-NLS-1$ monitor.beginTask(taskName, 100); monitor.setTaskName(taskName); monitor.subTask(Messages.getString("GrafikLauncher.1")); //$NON-NLS-1$ try { if (!dest.exists()) dest.create(true, true, new SubProgressMonitor(monitor, 5)); final IFile tplFile = dest.getFile(FileUtilities.nameWithoutExtension(fileName) + ".tpl"); //$NON-NLS-1$ final StringWriter strWriter = new StringWriter(); final RememberForSync[] syncs = odt2tpl(odt, dest, strWriter, new SubProgressMonitor(monitor, 5)); strWriter.close(); // use the windows encoding for the Vorlage because of the grafik tool // which uses it when reading... final SetContentHelper sch = new SetContentHelper( Messages.getString("org.kalypso.ogc.sensor.diagview.grafik.GrafikLauncher.5")) //$NON-NLS-1$ { @Override protected void write(final OutputStreamWriter writer) throws Throwable { writer.write(strWriter.toString()); } }; sch.setFileContents(tplFile, false, false, new SubProgressMonitor(monitor, 5), GRAFIK_ENCODING); startGrafikTPL(tplFile, syncs, new SubProgressMonitor(monitor, 85, SubMonitor.SUPPRESS_NONE)); return Status.OK_STATUS; } catch (final CoreException e) { throw e; } catch (final Throwable e) // generic exception caught { throw new SensorException(e); } }
From source file:com.zimbra.cs.service.AutoDiscoverServlet.java
private static String createResponseDoc(String displayName, String email, String serviceUrl) throws Exception { DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); factory.setNamespaceAware(true);//from w w w . ja va2 s . c o m DocumentBuilder builder = factory.newDocumentBuilder(); Document xmlDoc = builder.newDocument(); Element root = xmlDoc.createElementNS(NS, "Autodiscover"); root.setAttribute("xmlns", NS); root.setAttribute("xmlns:xsi", XSI_NS); root.setAttribute("xmlns:xsd", XSD_NS); xmlDoc.appendChild(root); //Add the response element. Element response = xmlDoc.createElementNS(NS_MOBILE, "Response"); root.appendChild(response); //Add culture to to response Element culture = xmlDoc.createElement("Culture"); culture.appendChild(xmlDoc.createTextNode("en:en")); response.appendChild(culture); //User Element user = xmlDoc.createElement("User"); Element displayNameElm = xmlDoc.createElement("DisplayName"); displayNameElm.appendChild(xmlDoc.createTextNode(displayName)); user.appendChild(displayNameElm); Element emailAddr = xmlDoc.createElement("EMailAddress"); emailAddr.appendChild(xmlDoc.createTextNode(email)); user.appendChild(emailAddr); response.appendChild(user); //Action Element action = xmlDoc.createElement("Action"); Element settings = xmlDoc.createElement("Settings"); Element server = xmlDoc.createElement("Server"); Element type = xmlDoc.createElement("Type"); type.appendChild(xmlDoc.createTextNode("MobileSync")); server.appendChild(type); Element url = xmlDoc.createElement("Url"); url.appendChild(xmlDoc.createTextNode(serviceUrl)); server.appendChild(url); Element name = xmlDoc.createElement("Name"); name.appendChild(xmlDoc.createTextNode(serviceUrl)); server.appendChild(name); settings.appendChild(server); action.appendChild(settings); response.appendChild(action); TransformerFactory transformerFactory = TransformerFactory.newInstance(); Transformer transformer = transformerFactory.newTransformer(); transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes"); transformer.setOutputProperty(OutputKeys.INDENT, "yes"); DOMSource source = new DOMSource(xmlDoc); StringWriter writer = new StringWriter(); StreamResult result = new StreamResult(writer); transformer.transform(source, result); writer.flush(); String xml = writer.toString(); writer.close(); //manually generate xmlns for Autodiscover and Response element, this works //for testexchangeconnectivity.com, but iOS and Android don't like Response's xmlns // StringBuilder str = new StringBuilder(); // str.append("<?xml version=\"1.0\"?>\n"); // str.append("<Autodiscover xmlns:xsd=\"").append(XSD_NS).append("\""); // str.append(" xmlns:xsi=\"").append(XSI_NS).append("\""); // str.append(" xmlns=\"").append(NS).append("\">\n"); // int respIndex = xml.indexOf("<Response>"); // str.append("<Response xmlns=\"").append(NS_MOBILE).append("\">"); // str.append(xml.substring(respIndex + "<Response>".length(), xml.length())); // return str.toString(); return "<?xml version=\"1.0\"?>\n" + xml; }
From source file:com.zimbra.cs.service.AutoDiscoverServlet.java
private static String createResponseDocForEws(String displayName, String email, String serviceUrl, Account acct) throws Exception { Provisioning prov = Provisioning.getInstance(); Server server = prov.getServer(acct); String cn = server.getCn();/*w w w .j a v a2 s . c o m*/ String name = server.getName(); String acctId = acct.getId(); DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); factory.setNamespaceAware(true); DocumentBuilder builder = factory.newDocumentBuilder(); Document xmlDoc = builder.newDocument(); Element root = xmlDoc.createElementNS(NS, "Autodiscover"); root.setAttribute("xmlns", NS); root.setAttribute("xmlns:xsi", XSI_NS); root.setAttribute("xmlns:xsd", XSD_NS); xmlDoc.appendChild(root); //Add the response element. Element response = xmlDoc.createElementNS(NS_OUTLOOK, "Response"); root.appendChild(response); //User Element user = xmlDoc.createElement("User"); Element displayNameElm = xmlDoc.createElement("DisplayName"); displayNameElm.appendChild(xmlDoc.createTextNode(displayName)); user.appendChild(displayNameElm); Element emailAddr = xmlDoc.createElement("EmailAddress"); emailAddr.appendChild(xmlDoc.createTextNode(email)); user.appendChild(emailAddr); Element depId = xmlDoc.createElement("DeploymentId"); depId.appendChild(xmlDoc.createTextNode(acctId)); user.appendChild(depId); response.appendChild(user); //Action Element account = xmlDoc.createElement("Account"); Element acctType = xmlDoc.createElement("AccountType"); acctType.appendChild(xmlDoc.createTextNode("email")); account.appendChild(acctType); response.appendChild(account); Element action = xmlDoc.createElement("Action"); action.appendChild(xmlDoc.createTextNode("settings")); account.appendChild(action); Element protocol = xmlDoc.createElement("Protocol"); account.appendChild(protocol); Element type = xmlDoc.createElement("Type"); type.appendChild(xmlDoc.createTextNode("EXCH")); protocol.appendChild(type); Element ews = xmlDoc.createElement("EwsUrl"); protocol.appendChild(ews); ews.appendChild(xmlDoc.createTextNode(serviceUrl)); Element as = xmlDoc.createElement("ASUrl"); protocol.appendChild(as); as.appendChild(xmlDoc.createTextNode(serviceUrl)); TransformerFactory transformerFactory = TransformerFactory.newInstance(); Transformer transformer = transformerFactory.newTransformer(); transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes"); transformer.setOutputProperty(OutputKeys.INDENT, "yes"); DOMSource source = new DOMSource(xmlDoc); StringWriter writer = new StringWriter(); StreamResult result = new StreamResult(writer); transformer.transform(source, result); writer.flush(); String xml = writer.toString(); writer.close(); return "<?xml version=\"1.0\"?>\n" + xml; }
From source file:org.openecomp.core.utilities.CommonMethods.java
/** * Print stack trace string.//w w w. ja v a2 s . c om * * @return the string */ public static String printStackTrace() { StringWriter sw = new StringWriter(); StackTraceElement[] trace = Thread.currentThread().getStackTrace(); for (StackTraceElement traceElement : trace) { sw.write("\t " + traceElement); sw.write(System.lineSeparator()); } String str = sw.toString(); try { sw.close(); } catch (IOException e0) { System.err.println(e0); } return str; }
From source file:org.apache.oozie.action.hadoop.LauncherMain.java
/** * Write to STDOUT (the task log) the Configuration/Properties values. All properties that contain * any of the strings in the maskSet will be masked when writting it to STDOUT. * * @param header message for the beginning of the Configuration/Properties dump. * @param maskSet set with substrings of property names to mask. * @param conf Configuration/Properties object to dump to STDOUT * @throws IOException thrown if an IO error ocurred. *///ww w .ja v a2 s.c o m @SuppressWarnings("unchecked") protected static void logMasking(String header, Collection<String> maskSet, Iterable conf) throws IOException { StringWriter writer = new StringWriter(); writer.write(header + "\n"); writer.write("--------------------\n"); for (Map.Entry entry : (Iterable<Map.Entry>) conf) { String name = (String) entry.getKey(); String value = (String) entry.getValue(); for (String mask : maskSet) { if (name.contains(mask)) { value = "*MASKED*"; } } writer.write(" " + name + " : " + value + "\n"); } writer.write("--------------------\n"); writer.close(); System.out.println(writer.toString()); System.out.flush(); }
From source file:com.cloudmine.api.rest.JsonUtilities.java
/** * Convert a Map to its representation as a JSON string. * @param map will be converted to its JSON representation * @return valid JSON that represents the passed in map. It should be true that map.equals(jsonToMap(mapToJson(map))) * @throws ConversionException if unable to convert this Map to json. This should never happen *//*from ww w . jav a 2s . com*/ public static String mapToJson(Map<String, ? extends Object> map) throws ConversionException { if (map == null) { return EMPTY_JSON; } StringWriter writer = new StringWriter(); try { jsonMapper.writeValue(writer, map); return writer.toString(); } catch (IOException e) { LOG.error("Trouble writing json", e); throw new ConversionException(e); } finally { try { writer.close(); } catch (IOException e) { //nope don't care } } }
From source file:com.cloudmine.api.rest.JsonUtilities.java
/** * Convert a CMObject to its JSON representation * @param objects the objects to convert * @return valid JSON that represents the passed in objects as a collection of JSON * @throws ConversionException if unable to convert this CMObject to json *///from www . jav a 2 s . c o m public static String cmobjectsToJson(CMObject... objects) throws ConversionException { if (objects == null) { LOG.debug("Received null objects, returning empty json"); return EMPTY_JSON; } Map<String, CMObject> objectMap = new HashMap<String, CMObject>(); for (CMObject object : objects) { objectMap.put(object.getObjectId(), object); } StringWriter writer = new StringWriter(); try { jsonMapper.writeValue(writer, objectMap); return writer.toString(); } catch (IOException e) { LOG.error("Trouble writing json", e); throw new ConversionException(e); } finally { try { writer.close(); } catch (IOException e) { //nope don't care } } }
From source file:org.apache.axis.utils.Admin.java
/** Get an XML document representing this engine's configuration. * * This document is suitable for saving and reloading into the * engine./*from w ww . jav a 2 s. co m*/ * * @param engine the AxisEngine to work with * @return an XML document holding the engine config * @exception AxisFault */ public static Document listConfig(AxisEngine engine) throws AxisFault { StringWriter writer = new StringWriter(); SerializationContext context = new SerializationContext(writer); context.setPretty(true); try { EngineConfiguration config = engine.getConfig(); if (config instanceof WSDDEngineConfiguration) { WSDDDeployment deployment = ((WSDDEngineConfiguration) config).getDeployment(); deployment.writeToContext(context); } } catch (Exception e) { // If the engine config isn't a FileProvider, or we have no // engine config for some odd reason, we'll end up here. throw new AxisFault(Messages.getMessage("noEngineWSDD")); } try { writer.close(); return XMLUtils.newDocument(new InputSource(new StringReader(writer.getBuffer().toString()))); } catch (Exception e) { log.error("exception00", e); return null; } }
From source file:org.cloudifysource.restDoclet.generation.Utils.java
/** * /*from ww w . j a v a2s .c o m*/ * @param body . * @return The body in Json format. * @throws IOException . */ public static String getIndentJson(final String body) throws IOException { if (StringUtils.isBlank(body)) { return null; } StringWriter out = new StringWriter(); JsonParser parser = null; JsonGenerator gen = null; try { JsonFactory fac = new JsonFactory(); parser = fac.createJsonParser(new StringReader(body)); ObjectMapper mapper = new ObjectMapper(); JsonNode node = mapper.readTree(parser); // Create pretty printer: gen = fac.createJsonGenerator(out); gen.useDefaultPrettyPrinter(); // Write: mapper.writeTree(gen, node); gen.close(); parser.close(); return out.toString(); } finally { out.close(); if (gen != null) { gen.close(); } if (parser != null) { parser.close(); } } }
From source file:org.cloudifysource.shell.commands.AddTemplates.java
private static String getIndentJson(final String body) throws IOException { if (StringUtils.isBlank(body)) { return null; }/*from w w w .jav a2 s. c o m*/ StringWriter out = new StringWriter(); JsonParser parser = null; JsonGenerator gen = null; try { JsonFactory fac = new JsonFactory(); parser = fac.createJsonParser(new StringReader(body)); ObjectMapper mapper = new ObjectMapper(); JsonNode node = mapper.readTree(parser); // Create pretty printer: gen = fac.createJsonGenerator(out); gen.useDefaultPrettyPrinter(); // Write: mapper.writeTree(gen, node); gen.close(); parser.close(); return out.toString(); } finally { out.close(); if (gen != null) { gen.close(); } if (parser != null) { parser.close(); } } }