List of usage examples for javax.xml.transform OutputKeys OMIT_XML_DECLARATION
String OMIT_XML_DECLARATION
To view the source code for javax.xml.transform OutputKeys OMIT_XML_DECLARATION.
Click Source Link
From source file:com.granule.json.utils.XML.java
/** * Method to do the transform from an JSON input stream to a XML stream. * Neither input nor output streams are closed. Closure is left up to the caller. * * @param JSONStream The XML stream to convert to JSON * @param XMLStream The stream to write out JSON to. The contents written to this stream are always in UTF-8 format. * @param verbose Flag to denote whether or not to render the XML text in verbose (indented easy to read), or compact (not so easy to read, but smaller), format. * * @throws IOException Thrown if an IO error occurs. */// ww w . jav a 2 s .co m public static void toXml(InputStream JSONStream, OutputStream XMLStream, boolean verbose) throws IOException { if (logger.isLoggable(Level.FINER)) { logger.entering(className, "toXml(InputStream, OutputStream)"); } if (XMLStream == null) { throw new NullPointerException("XMLStream cannot be null"); } else if (JSONStream == null) { throw new NullPointerException("JSONStream cannot be null"); } else { if (logger.isLoggable(Level.FINEST)) { logger.logp(Level.FINEST, className, "transform", "Parsing the JSON and a DOM builder."); } try { //Get the JSON from the stream. JSONObject jObject = new JSONObject(JSONStream); //Create a new document DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); DocumentBuilder dBuilder = dbf.newDocumentBuilder(); Document doc = dBuilder.newDocument(); if (logger.isLoggable(Level.FINEST)) { logger.logp(Level.FINEST, className, "transform", "Parsing the JSON content to XML"); } convertJSONObject(doc, doc.getDocumentElement(), jObject, "jsonObject"); //Serialize it. TransformerFactory tfactory = TransformerFactory.newInstance(); Transformer serializer = null; if (verbose) { serializer = tfactory.newTransformer(new StreamSource(new StringReader(styleSheet))); ; } else { serializer = tfactory.newTransformer(); } Properties oprops = new Properties(); oprops.put(OutputKeys.METHOD, "xml"); oprops.put(OutputKeys.OMIT_XML_DECLARATION, "yes"); oprops.put(OutputKeys.VERSION, "1.0"); oprops.put(OutputKeys.INDENT, "true"); serializer.setOutputProperties(oprops); serializer.transform(new DOMSource(doc), new StreamResult(XMLStream)); } catch (Exception ex) { IOException iox = new IOException("Problem during conversion"); iox.initCause(ex); throw iox; } } if (logger.isLoggable(Level.FINER)) { logger.exiting(className, "toXml(InputStream, OutputStream)"); } }
From source file:es.juntadeandalucia.panelGestion.negocio.utiles.Utils.java
public static byte[] documentToByte(Document document) throws TransformerException { ByteArrayOutputStream bos = new ByteArrayOutputStream(); TransformerFactory tf = TransformerFactory.newInstance(); Transformer transformer = tf.newTransformer(); transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "no"); transformer.setOutputProperty(OutputKeys.METHOD, "xml"); transformer.setOutputProperty(OutputKeys.INDENT, "yes"); transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2"); transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8"); transformer.transform(new DOMSource(document), new StreamResult(bos)); return bos.toByteArray(); }
From source file:es.gob.afirma.signers.ooxml.be.fedict.eid.applet.service.signer.AbstractXmlSignatureService.java
protected static void writeDocumentNoClosing(final Document document, final OutputStream documentOutputStream, final boolean omitXmlDeclaration) throws TransformerException { final NoCloseOutputStream outputStream = new NoCloseOutputStream(documentOutputStream); final Result result = new StreamResult(outputStream); final Transformer xformer = TransformerFactory.newInstance().newTransformer(); if (omitXmlDeclaration) { xformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes"); //$NON-NLS-1$ }//from w ww .ja va 2 s . c o m final Source source = new DOMSource(document); xformer.transform(source, result); }
From source file:org.openmrs.web.controller.report.CohortReportFormController.java
/** * @see org.springframework.web.servlet.mvc.SimpleFormController#onSubmit(javax.servlet.http.HttpServletRequest, * javax.servlet.http.HttpServletResponse, java.lang.Object, * org.springframework.validation.BindException) *///from w w w . j a v a2 s .co m @Override protected ModelAndView onSubmit(HttpServletRequest request, HttpServletResponse response, Object commandObj, BindException errors) throws Exception { CommandObject command = (CommandObject) commandObj; // do simpleframework serialization of everything but 'rows', and add those via handcoded xml, since // serializing them is not reversible ReportSchema rs = new ReportSchema(); rs.setReportSchemaId(command.getReportId()); rs.setName(command.getName()); rs.setDescription(command.getDescription()); rs.setReportParameters(command.getParameters()); rs.setDataSetDefinitions(new ArrayList<DataSetDefinition>()); Serializer serializer = OpenmrsUtil.getSerializer(); StringWriter sw = new StringWriter(); serializer.write(rs, sw); DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); dbf.setValidating(false); DocumentBuilder db = dbf.newDocumentBuilder(); Document xml = db.parse(new InputSource( new StringReader("<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"no\"?>" + sw.toString()))); Node node = findChild(xml, "reportSchema"); node = findChild(node, "dataSets"); Element dsd = xml.createElement("dataSetDefinition"); dsd.setAttribute("name", "cohorts"); dsd.setAttribute("class", "org.openmrs.report.CohortDataSetDefinition"); node.appendChild(dsd); Element strategies = xml.createElement("strategies"); strategies.setAttribute("class", "java.util.LinkedHashMap"); dsd.appendChild(strategies); Element descriptions = xml.createElement("descriptions"); descriptions.setAttribute("class", "java.util.LinkedHashMap"); dsd.appendChild(descriptions); for (CohortReportRow row : command.getRows()) { if (StringUtils.hasText(row.getQuery())) { Element entry = xml.createElement("entry"); strategies.appendChild(entry); Element nameEl = xml.createElement("string"); Text val = xml.createTextNode(row.getName()); val.setNodeValue(row.getName()); nameEl.appendChild(val); entry.appendChild(nameEl); Element cohort = xml.createElement("cohort"); entry.appendChild(cohort); cohort.setAttribute("class", "org.openmrs.reporting.PatientSearch"); Element strategyEl = xml.createElement("specification"); val = xml.createTextNode(row.getQuery()); val.setNodeValue(row.getQuery()); strategyEl.appendChild(val); cohort.appendChild(strategyEl); } if (StringUtils.hasText(row.getDescription())) { Element entry = xml.createElement("entry"); descriptions.appendChild(entry); Element el = xml.createElement("string"); Text val = xml.createTextNode(row.getName()); val.setNodeValue(row.getName()); el.appendChild(val); entry.appendChild(el); el = xml.createElement("string"); val = xml.createTextNode(row.getDescription()); val.setNodeValue(row.getDescription()); el.appendChild(val); entry.appendChild(el); } } // now turn this into an xml string System.setProperty("javax.xml.transform.TransformerFactory", "com.sun.org.apache.xalan.internal.xsltc.trax.TransformerFactoryImpl"); TransformerFactory transfac = TransformerFactory.newInstance(); Transformer trans = transfac.newTransformer(); trans.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes"); trans.setOutputProperty(OutputKeys.INDENT, "yes"); trans.setOutputProperty(OutputKeys.METHOD, "xml"); StringWriter out = new StringWriter(); StreamResult result = new StreamResult(out); DOMSource source = new DOMSource(xml); trans.transform(source, result); String schemaXml = out.toString(); ReportSchemaXml rsx = new ReportSchemaXml(); rsx.populateFromReportSchema(rs); rsx.setXml(schemaXml); rsx.updateXmlFromAttributes(); rsx.setUuid(request.getParameter("parentUUID")); ReportService rptSvc = (ReportService) Context.getService(ReportService.class); if (rsx.getReportSchemaId() != null) { rptSvc.saveReportSchemaXml(rsx); } else { rptSvc.saveReportSchemaXml(rsx); } return new ModelAndView(new RedirectView(getSuccessView() + "?reportId=" + rsx.getReportSchemaId())); }
From source file:com.jayway.maven.plugins.android.phase01generatesources.GenerateSourcesMojo.java
/** * Copy the AndroidManifest.xml from androidManifestFile to destinationManifestFile * * @throws MojoExecutionException//from w w w.j av a2s. c o m */ protected void copyManifest() throws MojoExecutionException { getLog().debug("copyManifest: " + androidManifestFile + " -> " + destinationManifestFile); if (androidManifestFile == null) { getLog().debug("Manifest copying disabled. Using default manifest only"); return; } try { DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); DocumentBuilder db = dbf.newDocumentBuilder(); Document doc = db.parse(androidManifestFile); Source source = new DOMSource(doc); TransformerFactory xfactory = TransformerFactory.newInstance(); Transformer xformer = xfactory.newTransformer(); xformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes"); FileWriter writer = null; try { destinationManifestFile.getParentFile().mkdirs(); writer = new FileWriter(destinationManifestFile, false); if (doc.getXmlEncoding() != null && doc.getXmlVersion() != null) { String xmldecl = String.format("<?xml version=\"%s\" encoding=\"%s\"?>%n", doc.getXmlVersion(), doc.getXmlEncoding()); writer.write(xmldecl); } Result result = new StreamResult(writer); xformer.transform(source, result); getLog().info("Manifest copied from " + androidManifestFile + " to " + destinationManifestFile); } finally { IOUtils.closeQuietly(writer); } } catch (Exception e) { getLog().error("Error during copyManifest"); throw new MojoExecutionException("Error during copyManifest", e); } }
From source file:net.sf.joost.stx.Processor.java
/** * Initialize the output properties to the values specified in the * transformation sheet or to their default values, resp. *///from w w w . j ava 2 s . c o m public void initOutputProperties() { outputProperties = new Properties(); outputProperties.setProperty(OutputKeys.ENCODING, transformNode.outputEncoding); outputProperties.setProperty(OutputKeys.MEDIA_TYPE, "text/xml"); outputProperties.setProperty(OutputKeys.METHOD, transformNode.outputMethod); outputProperties.setProperty(OutputKeys.OMIT_XML_DECLARATION, "no"); outputProperties.setProperty(OutputKeys.STANDALONE, "no"); outputProperties.setProperty(OutputKeys.VERSION, "1.0"); }
From source file:com.amalto.core.plugin.base.xslt.XSLTTransformerPluginBean.java
/** * @throws XtentisException//from ww w . j av a 2 s . com * * @ejb.interface-method view-type = "local" * @ejb.facade-method */ public void execute(TransformerPluginContext context) throws XtentisException { try { // fetch data from context Transformer transformer = (Transformer) context.get(TRANSFORMER); String outputMethod = (String) context.get(OUTPUT_METHOD); TypedContent xmlTC = (TypedContent) context.get(INPUT_XML); // get the charset String charset = Util.extractCharset(xmlTC.getContentType()); // get the xml String String xml = new String(xmlTC.getContentBytes(), charset); // get the xml parameters TypedContent parametersTC = (TypedContent) context.get(INPUT_PARAMETERS); if (parametersTC != null) { String parametersCharset = Util.extractCharset(parametersTC.getContentType()); byte[] parametersBytes = parametersTC.getContentBytes(); if (parametersBytes != null) { String parameters = new String(parametersBytes, parametersCharset); Document parametersDoc = Util.parse(parameters); NodeList paramList = Util.getNodeList(parametersDoc.getDocumentElement(), "//Parameter"); //$NON-NLS-1$ for (int i = 0; i < paramList.getLength(); i++) { String paramName = Util.getFirstTextNode(paramList.item(i), "Name"); //$NON-NLS-1$ String paramValue = Util.getFirstTextNode(paramList.item(i), "Value"); //$NON-NLS-1$ if (paramValue == null) paramValue = ""; //$NON-NLS-1$ if (paramName != null) { transformer.setParameter(paramName, paramValue); } } } } // FIXME: ARRRRGHHHHHH - How do you prevent the Transformer to process doctype instructions? // Sets the current time transformer.setParameter("TIMESTAMP", getTimestamp()); //$NON-NLS-1$ transformer.setErrorListener(new ErrorListener() { public void error(TransformerException exception) throws TransformerException { transformatioError = exception.getMessage(); } public void fatalError(TransformerException exception) throws TransformerException { transformatioError = exception.getMessage(); } public void warning(TransformerException exception) throws TransformerException { transformationeWarning = exception.getMessage(); } }); transformatioError = null; transformationeWarning = null; ByteArrayOutputStream baos = new ByteArrayOutputStream(); if ("xml".equals(outputMethod) || "xhtml".equals(outputMethod)) { //$NON-NLS-1$ //$NON-NLS-2$ DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder(); Document document = builder.newDocument(); DOMResult domResult = new DOMResult(document); transformer.transform(new StreamSource(new StringReader(xml)), domResult); if (transformationeWarning != null) { String err = "Warning processing the XSLT: " + transformationeWarning; //$NON-NLS-1$ LOG.warn(err); } if (transformatioError != null) { String err = "Error processing the XSLT: " + transformatioError; //$NON-NLS-1$ LOG.error(err); throw new XtentisException(err); } Node rootNode = document.getDocumentElement(); // process the cross-referencings NodeList xrefl = Util.getNodeList(rootNode.getOwnerDocument(), "//*[@xrefCluster]"); //$NON-NLS-1$ int len = xrefl.getLength(); for (int i = 0; i < len; i++) { Element xrefe = (Element) xrefl.item(i); xrefe = processMappings(xrefe); } TransformerFactory transFactory = new net.sf.saxon.TransformerFactoryImpl(); Transformer serializer = transFactory.newTransformer(); serializer.setOutputProperty(OutputKeys.METHOD, outputMethod); serializer.setOutputProperty(OutputKeys.INDENT, "yes"); //$NON-NLS-1$ serializer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes"); //$NON-NLS-1$ serializer.transform(new DOMSource(rootNode), new StreamResult(baos)); } else { if (transformationeWarning != null) { String err = "Warning processing the XSLT: " + transformationeWarning; //$NON-NLS-1$ LOG.warn(err); } if (transformatioError != null) { String err = "Error processing the XSLT: " + transformatioError; //$NON-NLS-1$ LOG.error(err); throw new XtentisException(err); } // transform the item transformer.transform(new StreamSource(new StringReader(xml)), new StreamResult(baos)); } // Call Back byte[] bytes = baos.toByteArray(); if (LOG.isDebugEnabled()) { LOG.debug("execute() Inserting XSL Result in '" + OUTPUT_TEXT + "'\n" + new String(bytes, "utf-8")); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ } context.put(OUTPUT_TEXT, new TypedContent(bytes, ("xhtml".equals(outputMethod) ? "application/xhtml+xml" //$NON-NLS-1$//$NON-NLS-2$ : "text/" //$NON-NLS-1$ + outputMethod) + "; charset=utf-8")); //$NON-NLS-1$ context.getPluginCallBack().contentIsReady(context); } catch (Exception e) { String err = "Could not start the XSLT plugin"; //$NON-NLS-1$ LOG.error(err, e); throw new XtentisException(err); } }
From source file:serverTools.java
public String createServerConfig(String node, String jsonString) { String result = node + "::"; try {/*from w w w. ja v a 2 s . co m*/ String ret; JSONObject jo = new JSONObject(jsonString); UUID uid = UUID.randomUUID(); String varName = node; String varIP = jo.get("ip").toString(); String varHyp = jo.get("hypervisor").toString(); String varVmconfigs = jo.get("vmconfigs").toString(); String varTransport = jo.get("transport").toString(); String varDesc = jo.get("description").toString(); // make sure that remote directory exist // Get the JSONArray value associated with the Result key JSONArray storageArray = jo.getJSONArray("storages"); String configDir = this.makeRelativeDirs("/" + varName + "/config"); this.makeRelativeDirs("/" + varName + "/screenshots"); this.makeRelativeDirs("/" + varName + "/vm/configs"); // Cration d'un nouveau DOM DocumentBuilderFactory fabrique = DocumentBuilderFactory.newInstance(); DocumentBuilder constructeur = fabrique.newDocumentBuilder(); Document document = constructeur.newDocument(); // Proprits du DOM document.setXmlStandalone(true); // Cration de l'arborescence du DOM Element server = document.createElement("server"); document.appendChild(server); //racine.appendChild(document.createComment("Commentaire sous la racine")); Element name = document.createElement("name"); server.appendChild(name); name.setTextContent(varName); Element ip = document.createElement("ip"); server.appendChild(ip); ip.setTextContent(varIP); Element hypervisor = document.createElement("hypervisor"); server.appendChild(hypervisor); hypervisor.setTextContent(varHyp); Element transport = document.createElement("transport"); server.appendChild(transport); transport.setTextContent(varTransport); Element descEl = document.createElement("description"); server.appendChild(descEl); descEl.setTextContent(varDesc); Element vmconfigs = document.createElement("vmconfigs"); server.appendChild(vmconfigs); vmconfigs.setTextContent(varVmconfigs); JSONObject coordinatesObj = jo.getJSONObject("coordinates"); Element coordinatesEl = document.createElement("coordinates"); server.appendChild(coordinatesEl); coordinatesEl.setAttribute("building", coordinatesObj.get("building").toString()); coordinatesEl.setAttribute("street", coordinatesObj.get("street").toString()); coordinatesEl.setAttribute("city", coordinatesObj.get("city").toString()); coordinatesEl.setAttribute("latitude", coordinatesObj.get("latitude").toString()); coordinatesEl.setAttribute("longitude", coordinatesObj.get("longitude").toString()); //<storages> Element storages = document.createElement("storages"); server.appendChild(storages); int resultCount = storageArray.length(); for (int i = 0; i < resultCount; i++) { Element repository = document.createElement("repository"); storages.appendChild(repository); Element path = document.createElement("target"); repository.appendChild(path); JSONObject newStorage = storageArray.getJSONObject(i); String storageName = newStorage.get("name").toString(); String storagePath = newStorage.get("target").toString(); storageName = storageName.replaceAll(" ", "_"); storagePath = storagePath.replaceAll(" ", "_"); repository.setAttribute("type", newStorage.get("type").toString()); repository.setAttribute("name", storageName); path.setTextContent(storagePath); Element source = document.createElement("source"); repository.appendChild(source); String storageSource = newStorage.get("source").toString(); source.setTextContent(storageSource); String localStorageDir = this.makeRelativeDirs("/" + varName + "/vm/storages/" + storageName); if (localStorageDir == "Error") { return result + "Error: cannot create " + varName + "/vm/storages/" + storageName; } } //</storages> // Get network information (look for bridges) Element networks = document.createElement("networks"); server.appendChild(networks); JSONObject joAction = new JSONObject(); joAction.put("name", "add"); joAction.put("driver", varHyp); joAction.put("transport", varTransport); joAction.put("description", varDesc); ArrayList<String> optList = new ArrayList<String>(); optList.add("ip=" + varIP); String varPasswd = ""; varPasswd = jo.opt("password").toString(); if (varPasswd.length() > 0) { optList.add("exchange_keys=" + varPasswd); } joAction.put("options", optList); String msg = callOvnmanager(node, joAction.toString()); JSONObject joMsg = new JSONObject(msg); JSONObject joActionRes = joMsg.getJSONObject("action"); result += joActionRes.get("result").toString(); //write the content into xml file String pathToXml = configDir + "/" + varName + ".xml"; File xmlOutput = new File(pathToXml); TransformerFactory transformerFactory = TransformerFactory.newInstance(); Transformer transformer = transformerFactory.newTransformer(); transformer.setOutputProperty(OutputKeys.INDENT, "yes"); transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes"); DOMSource source = new DOMSource(document); StreamResult streamRes = new StreamResult(xmlOutput); transformer.transform(source, streamRes); } catch (Exception e) { log(ERROR, "create xml file has failed", e); return result + "Error: " + e.toString(); } //ret = "done"; return result; }
From source file:be.fedict.eid.applet.service.signer.AbstractXmlSignatureService.java
protected void writeDocumentNoClosing(Document document, OutputStream documentOutputStream, boolean omitXmlDeclaration) throws TransformerConfigurationException, TransformerFactoryConfigurationError, TransformerException, IOException { NoCloseOutputStream outputStream = new NoCloseOutputStream(documentOutputStream); Result result = new StreamResult(outputStream); Transformer xformer = TransformerFactory.newInstance().newTransformer(); if (omitXmlDeclaration) { xformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes"); }//from www. j a v a2 s.com Source source = new DOMSource(document); xformer.transform(source, result); }
From source file:org.openmrs.module.atomfeed.AtomFeedUtil.java
/** * Updates content of atom feed header file by re-creating new xml header block and writing it * into given file. Actually, if given atom feed header file does not exists, it creates it. * Otherwise, it changes values of "updated", "versionId" and "entriesSize" elements within * header xml tree.//from w ww . j av a2 s .com * * @param atomfeedheader the file target to be updated * @param entriesSize the size in bytes of entries payload, which is related to given feed * header */ private static void updateFeedFileHeader(File atomfeedheader, long entriesSize) { try { // We need a Document DocumentBuilderFactory dbfac = DocumentBuilderFactory.newInstance(); DocumentBuilder docBuilder = dbfac.newDocumentBuilder(); Document doc = docBuilder.newDocument(); // ////////////////////// // Creating the XML tree // create the root element and add it to the document Element root = doc.createElement("feed"); root.setAttribute("xmlns", "http://www.w3.org/2005/Atom"); doc.appendChild(root); // create title element, add its text, and add to root Element title = doc.createElement("title"); Text titleText = doc.createTextNode(AtomFeedConstants.ATOM_FEED_TITLE); title.appendChild(titleText); root.appendChild(title); // create title element, add its attrs, and add to root Element selflink = doc.createElement("link"); selflink.setAttribute("href", AtomFeedUtil.getFeedUrl()); selflink.setAttribute("rel", "self"); root.appendChild(selflink); Element serverlink = doc.createElement("link"); serverlink.setAttribute("href", getWebServiceUrl()); root.appendChild(serverlink); // create title element, add its text, and add to root Element id = doc.createElement("id"); Text idText = doc.createTextNode(AtomFeedConstants.ATOM_FEED_ID); id.appendChild(idText); root.appendChild(id); // create updated element, add its text, and add to root Element updated = doc.createElement("updated"); Date lastModified = new Date(); Text updatedText = doc.createTextNode(dateToRFC3339(lastModified)); updated.appendChild(updatedText); root.appendChild(updated); // create versionId element, add its text, and add to root Element versionId = doc.createElement("versionId"); Text versionIdText = doc.createTextNode(String.valueOf(lastModified.getTime())); versionId.appendChild(versionIdText); root.appendChild(versionId); // create versionId element, add its text, and add to root Element entriesSizeElement = doc.createElement("entriesSize"); Text entriesSizeText = doc.createTextNode(String.valueOf(entriesSize)); entriesSizeElement.appendChild(entriesSizeText); root.appendChild(entriesSizeElement); /* * Print the xml to the file */ // set up a transformer TransformerFactory transfac = TransformerFactory.newInstance(); Transformer trans = transfac.newTransformer(); trans.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "no"); trans.setOutputProperty(OutputKeys.INDENT, "no"); // create string from xml tree FileWriter fw = new FileWriter(atomfeedheader); StreamResult result = new StreamResult(fw); DOMSource source = new DOMSource(doc); trans.transform(source, result); // print xml for debugging purposes if (log.isTraceEnabled()) { StringWriter sw = new StringWriter(); result = new StreamResult(sw); trans.transform(source, result); log.trace("Here's the initial xml:\n\n" + sw.toString()); } } catch (Exception e) { log.error("unable to initialize feed at: " + atomfeedheader.getAbsolutePath(), e); } }