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.zimbra.cs.service.AutoDiscoverServlet.java
private static String createResponseDoc(String displayName, String email, String serviceUrl) throws Exception { DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); factory.setNamespaceAware(true);//ww w .j a v a 2s .com 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:edu.isi.pfindr.servlets.QueryServlet.java
/** * get the XML string of the results of an SQL Query * // w w w .j a v a 2s .com * @param request * the servlet request * @param conn * the DB connection * @return the XML string to be saved in a file */ @SuppressWarnings("unused") private String saveXML(HttpServletRequest request, Connection conn) { String sql = request.getParameter("sql"); JSONObject json; String phenotypes = ""; try { // get the query results json = new JSONObject(sql); String sqlQuery = Utils.getPhenotypesSQL(json); logger.info(sqlQuery); PreparedStatement stmt = conn.prepareStatement(sqlQuery); Utils.loadValues(stmt, json, "", false); JSONArray group = new JSONArray(request.getParameter("template")); JSONArray rows = Utils.executeSQL(stmt); stmt.close(); // create the document builder DocumentBuilderFactory dbfac = DocumentBuilderFactory.newInstance(); DocumentBuilder docBuilder = dbfac.newDocumentBuilder(); Document doc = docBuilder.newDocument(); Element root = doc.createElement("Phenotypes"); doc.appendChild(root); // append the query results to the document JSONObject res = Utils.toJSONObject(group, rows); Utils.toXML(doc, root, res); // transform the document to an XML string TransformerFactory transfac = TransformerFactory.newInstance(); Transformer trans = transfac.newTransformer(); trans.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes"); trans.setOutputProperty(OutputKeys.INDENT, "yes"); StringWriter sw = new StringWriter(); StreamResult result = new StreamResult(sw); DOMSource source = new DOMSource(doc); trans.transform(source, result); phenotypes = sw.toString(); } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (ParserConfigurationException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (TransformerConfigurationException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (TransformerException e) { // TODO Auto-generated catch block e.printStackTrace(); } return phenotypes; }
From source file:com.marklogic.xcc.ContentFactory.java
static byte[] bytesFromW3cNode(Node node) { ByteArrayOutputStream bos = new ByteArrayOutputStream(); Result rslt = new StreamResult(bos); Source src = new DOMSource(node); Transformer transformer;//from www . j av a 2 s. c o m try { transformer = getTransformerFactory().newTransformer(); transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8"); transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes"); transformer.transform(src, rslt); } catch (TransformerException e) { throw new RuntimeException("Cannot serialize Node: " + e, e); } return bos.toByteArray(); }
From source file:eu.eidas.auth.engine.EIDASSAMLEngine.java
private String computeSimpleValue(XSAnyImpl xmlString) { TransformerFactory transFactory = TransformerFactory.newInstance(); Transformer transformer = null; try {// ww w. j av a2 s . c o m transformer = transFactory.newTransformer(); transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes"); } catch (TransformerConfigurationException e) { LOG.warn(SAML_EXCHANGE, "ERROR : transformer configuration exception", e); } StringWriter buffer = new StringWriter(); try { if (transformer != null && xmlString != null && xmlString.getUnknownXMLObjects() != null && !xmlString.getUnknownXMLObjects().isEmpty()) { transformer.transform(new DOMSource(xmlString.getUnknownXMLObjects().get(0).getDOM()), new StreamResult(buffer)); } } catch (TransformerException e) { LOG.warn(SAML_EXCHANGE, "ERROR : transformer exception", e); } return buffer.toString(); }
From source file:cz.mzk.editor.server.fedora.utils.FedoraUtils.java
/** * @param document/*from ww w. j av a 2 s . co m*/ */ public static String getStringFromDocument(Document document, boolean omitXmlDeclaration) throws TransformerException { TransformerFactory transFactory = TransformerFactory.newInstance(); Transformer transformer = transFactory.newTransformer(); StringWriter buffer = new StringWriter(); if (omitXmlDeclaration) { transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes"); } transformer.transform(new DOMSource(document), new StreamResult(buffer)); return buffer.toString(); }
From source file:com.photon.phresco.service.tools.TechnologyDataGenerator.java
/** * Create pom.xml file for each module/* www. jav a 2s . c o m*/ * @param module * @param ext * @param groupId2 * @return * @throws PhrescoException */ private File createPomFile(String name, String groupId, String artifactId, String version, String ext) throws PhrescoException { System.out.println("Creating Pom File For " + name); File file = new File(outputRootDir, "pom.xml"); DocumentBuilderFactory domFactory = DocumentBuilderFactory.newInstance(); try { DocumentBuilder domBuilder = domFactory.newDocumentBuilder(); org.w3c.dom.Document newDoc = domBuilder.newDocument(); Element rootElement = newDoc.createElement("project"); newDoc.appendChild(rootElement); Element modelVersion = newDoc.createElement("modelVersion"); modelVersion.setTextContent("4.0.0"); rootElement.appendChild(modelVersion); Element groupIdEle = newDoc.createElement("groupId"); groupIdEle.setTextContent(groupId); rootElement.appendChild(groupIdEle); Element artifactIdEle = newDoc.createElement("artifactId"); artifactIdEle.setTextContent(artifactId); rootElement.appendChild(artifactIdEle); Element versionEle = newDoc.createElement("version"); versionEle.setTextContent(version); rootElement.appendChild(versionEle); Element packaging = newDoc.createElement("packaging"); packaging.setTextContent(ext); rootElement.appendChild(packaging); Element description = newDoc.createElement("description"); description.setTextContent("created by phresco"); rootElement.appendChild(description); TransformerFactory transfac = TransformerFactory.newInstance(); Transformer trans = transfac.newTransformer(); trans.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes"); trans.setOutputProperty(OutputKeys.INDENT, "yes"); StringWriter sw = new StringWriter(); StreamResult result = new StreamResult(sw); DOMSource source = new DOMSource(newDoc); trans.transform(source, result); String xmlString = sw.toString(); FileWriter writer = new FileWriter(file); writer.write(xmlString); writer.close(); } catch (Exception e) { throw new PhrescoException(); } return file; }
From source file:com.jkoolcloud.tnt4j.streams.utils.Utils.java
/** * Transforms (serializes) XML DOM document to string. * * @param doc/*www.j a va 2 s . c o m*/ * document to transform to string * @return XML string representation of document * @throws javax.xml.transform.TransformerException * If an exception occurs while transforming XML DOM document to string */ public static String documentToString(Node doc) throws TransformerException { StringWriter sw = new StringWriter(); TransformerFactory tf = TransformerFactory.newInstance(); Transformer transformer = tf.newTransformer(); transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "no"); // NON-NLS transformer.setOutputProperty(OutputKeys.METHOD, "xml"); // NON-NLS transformer.setOutputProperty(OutputKeys.INDENT, "yes"); // NON-NLS transformer.setOutputProperty(OutputKeys.ENCODING, UTF8); transformer.transform(new DOMSource(doc), new StreamResult(sw)); return sw.toString(); // NOTE: if return as single line // return sw.toString().replaceAll("\n|\r", ""); // NON-NLS }
From source file:eu.eidas.auth.engine.core.stork.StorkExtensionProcessor.java
private String extractEDocValue(final XSAnyImpl xmlString) { TransformerFactory transFactory = TransformerFactory.newInstance(); Transformer transformer = null; try {//from w w w . j a v a 2 s . c o m transformer = transFactory.newTransformer(); transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes"); } catch (TransformerConfigurationException e) { LOG.warn(AbstractProtocolEngine.SAML_EXCHANGE, "Error transformer configuration exception", e.getMessage()); LOG.debug(AbstractProtocolEngine.SAML_EXCHANGE, "Error transformer configuration exception", e); } StringWriter buffer = new StringWriter(); try { if (transformer != null && xmlString != null && xmlString.getUnknownXMLObjects() != null && !xmlString.getUnknownXMLObjects().isEmpty()) { transformer.transform(new DOMSource(xmlString.getUnknownXMLObjects().get(0).getDOM()), new StreamResult(buffer)); } } catch (TransformerException e) { LOG.info(AbstractProtocolEngine.SAML_EXCHANGE, "BUSINESS EXCEPTION : Error transformer exception", e.getMessage()); LOG.debug(AbstractProtocolEngine.SAML_EXCHANGE, "BUSINESS EXCEPTION : Error transformer exception", e); } return buffer.toString(); }
From source file:com.francelabs.datafari.servlets.admin.FieldWeight.java
/** * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse * response) Checks if the files still exist Used to modify the weight of * a field//from w w w .j a v a2s . c om */ @Override protected void doPost(final HttpServletRequest request, final HttpServletResponse response) throws ServletException, IOException { try { if ((config == null) || !new File(env + File.separator + "solrconfig.xml").exists()) {// If // the // files // did // not // existed // when // the // constructor // was // runned if (!new File(env + File.separator + "solrconfig.xml").exists()) { LOGGER.error( "Error while opening the configuration file, solrconfig.xml, in FieldWeight doPost, please make sure this file exists at " + env + "conf/ . Error 69029"); // If // not // an // error // is // printed final PrintWriter out = response.getWriter(); out.append( "Error while opening the configuration file, please retry, if the problem persists contact your system administrator. Error Code : 69029"); out.close(); return; } else { config = new File(env + File.separator + "solrconfig.xml"); } } if (customSearchHandler == null) { if (new File( env + File.separator + "customs_solrconfig" + File.separator + "custom_search_handler.incl") .exists()) { customSearchHandler = new File(env + File.separator + "customs_solrconfig" + File.separator + "custom_search_handler.incl"); } } try { final String type = request.getParameter("type"); if (searchHandler == null) { findSearchHandler(); } if (!usingCustom) { // The custom search handler is not used. // That means that the current config must // be commented in the solrconfig.xml file // and the modifications must be saved in // the custom search handler file // Get the content of solrconfig.xml file as a string String configContent = FileUtils.getFileContent(config); // Retrieve the searchHandler from the configContent final Node originalSearchHandler = XMLUtils.getSearchHandlerNode(config); final String strSearchHandler = XMLUtils.nodeToString(originalSearchHandler); // Create a commented equivalent of the strSearchHandler final String commentedSearchHandler = "<!--" + strSearchHandler + "-->"; // Replace the searchHandler in the solrconfig.xml file by // the commented version configContent = configContent.replace(strSearchHandler, commentedSearchHandler); FileUtils.saveStringToFile(config, configContent); // create the new custom_search_handler document doc = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument(); // Import the search handler node from the solrconfig doc to // the custom search handler doc searchHandler = doc.importNode(searchHandler, true); // Make the new node an actual item in the target document searchHandler = doc.appendChild(searchHandler); final Node n = run(searchHandler.getChildNodes(), type); childList = n.getParentNode().getChildNodes(); // Save the custom_search_handler.incl file XMLUtils.docToFile(doc, customSearchHandler); } if (childList == null) { final Node n = run(searchHandler.getChildNodes(), type); childList = n.getParentNode().getChildNodes(); } for (int i = 0; i < childList.getLength(); i++) { // Get the str // node final Node n = childList.item(i); if (n.getNodeName().equals("str")) { String name = ""; // Get it's attributes final NamedNodeMap map = n.getAttributes(); for (int j = 0; j < map.getLength(); j++) { if (map.item(j).getNodeName().equals("name")) {// Get // the // name name = map.item(j).getNodeValue(); } } if (name.equals(type)) { // If it's pf or qf according // to what the user selected // Get the parameters final String field = request.getParameter("field").toString(); final String value = request.getParameter("value").toString(); final String text = n.getTextContent(); // Get the // value of // the node, // Search for the requested field, if it is there // return the weight, if not return 0 final int index = text.indexOf(field + "^"); if (index != -1) { // If the field is already // weighted final int pas = field.length() + 1; final String textCut = text.substring(index + pas); if (value.equals("0")) { // If the user entered // 0 if (textCut.indexOf(" ") == -1) { // field is // the last // one then // we just // cut the // end of // the text // content n.setTextContent((text.substring(0, index)).trim()); } else { // the field and the part after n.setTextContent((text.substring(0, index) + text.substring(index + pas + textCut.indexOf(" "))).trim()); } } else { // If the user typed any other values if (textCut.indexOf(" ") == -1) { n.setTextContent(text.substring(0, index + pas) + value); } else { n.setTextContent(text.substring(0, index + pas) + value + text.substring(index + pas + textCut.indexOf(" "))); } } } else { // If it's not weighted if (!value.equals("0")) { // append the field and // it's value n.setTextContent((n.getTextContent() + " " + field + "^" + value).trim()); } } break; } } } // Apply the modifications final TransformerFactory transformerFactory = TransformerFactory.newInstance(); final Transformer transformer = transformerFactory.newTransformer(); transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes"); transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8"); transformer.setOutputProperty(OutputKeys.INDENT, "yes"); final DOMSource source = new DOMSource(searchHandler); final StreamResult result = new StreamResult(customSearchHandler); transformer.transform(source, result); } catch (final TransformerException e) { LOGGER.error( "Error while modifying the solrconfig.xml, in FieldWeight doPost, pls make sure the file is valid. Error 69030", e); final PrintWriter out = response.getWriter(); out.append( "Error while modifying the config file, please retry, if the problem persists contact your system administrator. Error Code : 69030"); out.close(); return; } } catch (final Exception e) { final PrintWriter out = response.getWriter(); out.append( "Something bad happened, please retry, if the problem persists contact your system administrator. Error code : 69511"); out.close(); LOGGER.error("Unindentified error in FieldWeight doPost. Error 69511", e); } }
From source file:cz.cas.lib.proarc.common.export.mets.MetsUtils.java
/** * * Transforms the xml document to a string * * @param doc/* www . j a va 2s. com*/ * @return */ public static String documentToString(Document doc) throws MetsExportException { try { StringWriter sw = new StringWriter(); 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(OutputKeys.ENCODING, "UTF-8"); transformer.transform(new DOMSource(doc), new StreamResult(sw)); return sw.toString(); } catch (TransformerException ex) { throw new MetsExportException("Error converting Document to String", false, ex); } }