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:org.alfresco.util.XMLUtil.java
/** utility function for serializing a node */ public static void print(final Node n, final Writer output, final boolean indent) { try {/*from w w w. jav a2s.c o m*/ final TransformerFactory tf = TransformerFactory.newInstance(); final Transformer t = tf.newTransformer(); t.setOutputProperty(OutputKeys.INDENT, indent ? "yes" : "no"); t.setOutputProperty(OutputKeys.ENCODING, "UTF-8"); t.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "no"); t.setOutputProperty(OutputKeys.METHOD, "xml"); if (LOGGER.isDebugEnabled()) { LOGGER.debug("writing out a document for " + (n instanceof Document ? ((Document) n).getDocumentElement() : n).getNodeName() + " to " + (output instanceof StringWriter ? "string" : output)); } t.transform(new DOMSource(n), new StreamResult(output)); } catch (TransformerException te) { te.printStackTrace(); assert false : te.getMessage(); } }
From source file:org.ambraproject.rhino.content.xml.AbstractXpathReader.java
protected AbstractXpathReader() { // XPath isn't thread-safe, so we need one per instance of this class this.xPath = XPATH_FACTORY.get().newXPath(); try {/* w w w. j a va2 s.co m*/ this.transformer = TRANSFORMER_FACTORY.get().newTransformer(); } catch (TransformerConfigurationException e) { throw new RuntimeException(e); } // The output will be stored in a character-encoded context (JSON or the database), // so declaring the encoding as part of the string doesn't make sense. transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes"); }
From source file:org.ambraproject.rhino.content.xml.AbstractXpathReader.java
private static String recoverXml(Node node) { ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); try {/*from w w w . j a v a2s. c om*/ Transformer transformer = TransformerFactory.newInstance().newTransformer(); transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes"); transformer.transform(new DOMSource(node), new StreamResult(outputStream)); } catch (TransformerException e) { throw new RuntimeException(e); } return new String(outputStream.toByteArray()); // TODO: Encoding? }
From source file:org.ambraproject.util.TextUtils.java
/** * Transforms an org.w3c.dom.Document into a String * * @param node Document to transform/*from w w w .j ava 2 s . c o m*/ * @return String representation of node * @throws TransformerException TransformerException */ public static String getAsXMLString(final Node node) throws TransformerException { final Transformer tf = TransformerFactory.newInstance().newTransformer(); final StringWriter stringWriter = new StringWriter(); tf.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes"); tf.transform(new DOMSource(node), new StreamResult(stringWriter)); return stringWriter.toString(); }
From source file:org.apache.ambari.server.upgrade.UpgradeCatalog220.java
protected void updateKnoxTopology() throws AmbariException { AmbariManagementController ambariManagementController = injector .getInstance(AmbariManagementController.class); for (final Cluster cluster : getCheckedClusterMap(ambariManagementController.getClusters()).values()) { Config topology = cluster.getDesiredConfigByType(TOPOLOGY_CONFIG); if (topology != null) { String content = topology.getProperties().get(CONTENT_PROPERTY); if (content != null) { Document topologyXml = convertStringToDocument(content); if (topologyXml != null) { Element root = topologyXml.getDocumentElement(); if (root != null) { NodeList providerNodes = root.getElementsByTagName("provider"); boolean authorizationProviderExists = false; try { for (int i = 0; i < providerNodes.getLength(); i++) { Node providerNode = providerNodes.item(i); NodeList childNodes = providerNode.getChildNodes(); for (int k = 0; k < childNodes.getLength(); k++) { Node child = childNodes.item(k); child.normalize(); String childTextContent = child.getTextContent(); if (childTextContent != null && childTextContent.toLowerCase().equals("authorization")) { authorizationProviderExists = true; break; }/* ww w. j a v a2s . c om*/ } if (authorizationProviderExists) { break; } } } catch (Exception e) { e.printStackTrace(); LOG.error( "Error occurred during check 'authorization' provider already exists in topology." + e); return; } if (!authorizationProviderExists) { NodeList nodeList = root.getElementsByTagName("gateway"); if (nodeList != null && nodeList.getLength() > 0) { boolean rangerPluginEnabled = isConfigEnabled(cluster, AbstractUpgradeCatalog.CONFIGURATION_TYPE_RANGER_KNOX_PLUGIN_PROPERTIES, AbstractUpgradeCatalog.PROPERTY_RANGER_KNOX_PLUGIN_ENABLED); Node gatewayNode = nodeList.item(0); Element newProvider = topologyXml.createElement("provider"); Element role = topologyXml.createElement("role"); role.appendChild(topologyXml.createTextNode("authorization")); newProvider.appendChild(role); Element name = topologyXml.createElement("name"); if (rangerPluginEnabled) { name.appendChild(topologyXml.createTextNode("XASecurePDPKnox")); } else { name.appendChild(topologyXml.createTextNode("AclsAuthz")); } newProvider.appendChild(name); Element enabled = topologyXml.createElement("enabled"); enabled.appendChild(topologyXml.createTextNode("true")); newProvider.appendChild(enabled); gatewayNode.appendChild(newProvider); DOMSource topologyDomSource = new DOMSource(root); StringWriter writer = new StringWriter(); try { Transformer transformer = TransformerFactory.newInstance().newTransformer(); transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8"); transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes"); transformer.setOutputProperty(OutputKeys.METHOD, "xml"); transformer.setOutputProperty(OutputKeys.INDENT, "yes"); transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "5"); transformer.transform(topologyDomSource, new StreamResult(writer)); } catch (TransformerConfigurationException e) { e.printStackTrace(); LOG.error( "Unable to create transformer instance, to convert Document(XML) to String. " + e); return; } catch (TransformerException e) { e.printStackTrace(); LOG.error("Unable to transform Document(XML) to StringWriter. " + e); return; } content = writer.toString(); Map<String, String> updates = Collections.singletonMap(CONTENT_PROPERTY, content); updateConfigurationPropertiesForCluster(cluster, TOPOLOGY_CONFIG, updates, true, false); } } } } } } } }
From source file:org.apache.axis2.jaxws.handler.LogicalMessageImpl.java
private Payloads createPayloads(Object content) { if (content == null) { return null; }/* w w w .j av a 2s .c om*/ Payloads payloads = new Payloads(); if (Source.class.isAssignableFrom(content.getClass())) { try { Transformer trans = TransformerFactory.newInstance().newTransformer(); // First we have to get the content out of the original // Source object so we can build the cache from there. ByteArrayOutputStream baos = new ByteArrayOutputStream(); StreamResult result = new StreamResult(baos); Source source = (Source) content; trans.transform(source, result); trans.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes"); byte[] bytes = baos.toByteArray(); // Given that we've consumed the original Source object, // we need to create another one with the original content // and assign it back. ByteArrayInputStream bais = new ByteArrayInputStream(bytes); try { // The Source object returned to the handler should be a // DOMSource so that the handler programmer can read the data // multiple times and (as opposed to using a StreamSource) and // they can more easily access the data in DOM form. DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); dbf.setNamespaceAware(true); DocumentBuilder db = dbf.newDocumentBuilder(); Document dom = db.parse(bais); payloads.HANDLER_PAYLOAD = new DOMSource(dom); } catch (ParserConfigurationException e) { throw ExceptionFactory.makeWebServiceException(e); } catch (IOException e) { throw ExceptionFactory.makeWebServiceException(e); } catch (SAXException e) { throw ExceptionFactory.makeWebServiceException(e); } // We need a different byte[] for the cache so that we're not just // building two Source objects that point to the same array. byte[] cacheBytes = new byte[bytes.length]; System.arraycopy(bytes, 0, cacheBytes, 0, bytes.length); // Now build the Soure object for the cache. ByteArrayInputStream cacheBais = new ByteArrayInputStream(cacheBytes); payloads.CACHE_PAYLOAD = new StreamSource(cacheBais); } catch (TransformerConfigurationException e) { throw ExceptionFactory.makeWebServiceException(e); } catch (TransformerFactoryConfigurationError e) { throw ExceptionFactory.makeWebServiceException(e); } catch (TransformerException e) { throw ExceptionFactory.makeWebServiceException(e); } } else { // no cache implemented yet payloads.HANDLER_PAYLOAD = content; payloads.CACHE_PAYLOAD = content; } return payloads; }
From source file:org.apache.cocoon.components.repository.impl.WebDAVRepository.java
public boolean saveContent(String uri, Node node) { try {//from w w w .j a v a 2 s .co m Properties format = new Properties(); format.put(OutputKeys.METHOD, "xml"); format.put(OutputKeys.OMIT_XML_DECLARATION, "yes"); return this.saveContent(uri, XMLUtils.serializeNode(node, format)); } catch (ProcessingException pe) { this.getLogger().error("Error saving dom to: " + this.repoBaseUrl + uri, pe); } return false; }
From source file:org.apache.cocoon.components.repository.impl.WebDAVRepositoryPropertyHelper.java
public boolean setProperty(String uri, String name, String namespace, Node value) { try {/*from w w w . j av a 2 s .com*/ Properties format = new Properties(); format.put(OutputKeys.METHOD, "xml"); format.put(OutputKeys.OMIT_XML_DECLARATION, "yes"); return this.setProperty(uri, name, namespace, XMLUtils.serializeNode(value, format)); } catch (ProcessingException pe) { this.getLogger().error("Error serializing node " + value, pe); } return false; }
From source file:org.apache.cocoon.components.source.impl.WebDAVSource.java
/** * Sets a property for a source.// www .j a v a2 s.co m * * @param sourceproperty Property of the source * * @throws SourceException If an exception occurs during this operation */ public void setSourceProperty(SourceProperty sourceproperty) throws SourceException { initResource(WebdavResource.NOACTION, DepthSupport.DEPTH_0); try { Node node = null; NodeList list = sourceproperty.getValue().getChildNodes(); for (int i = 0; i < list.getLength(); i++) { if ((list.item(i) instanceof Text && !"".equals(list.item(i).getNodeValue())) || list.item(i) instanceof Element) { node = list.item(i); break; } } Properties format = new Properties(); format.put(OutputKeys.METHOD, "xml"); format.put(OutputKeys.OMIT_XML_DECLARATION, "yes"); String prop = XMLUtils.serializeNode(node, format); this.resource.proppatchMethod(new PropertyName(sourceproperty.getNamespace(), sourceproperty.getName()), prop, true); } catch (HttpException e) { final String message = "Unable to set property. Server responded " + e.getReasonCode() + " (" + e.getReason() + ") - " + e.getMessage(); getLogger().debug(message); throw new SourceException("Could not set property ", e); } catch (Exception e) { throw new SourceException("Could not set property ", e); } }
From source file:org.apache.cocoon.serialization.AbstractTextSerializer.java
/** * Set the configurations for this serializer. *//* w w w . j av a2 s . co m*/ public void configure(Configuration conf) throws ConfigurationException { // configure buffer size // Configuration bsc = conf.getChild("buffer-size", false); // if(null != bsc) // outputBufferSize = bsc.getValueAsInteger(DEFAULT_BUFFER_SIZE); // configure xalan String cdataSectionElements = conf.getChild("cdata-section-elements").getValue(null); String dtPublic = conf.getChild("doctype-public").getValue(null); String dtSystem = conf.getChild("doctype-system").getValue(null); String encoding = conf.getChild("encoding").getValue(null); String indent = conf.getChild("indent").getValue(null); String mediaType = conf.getChild("media-type").getValue(null); String method = conf.getChild("method").getValue(null); String omitXMLDeclaration = conf.getChild("omit-xml-declaration").getValue(null); String standAlone = conf.getChild("standalone").getValue(null); String version = conf.getChild("version").getValue(null); final StringBuffer buffer = new StringBuffer(); if (cdataSectionElements != null) { format.put(OutputKeys.CDATA_SECTION_ELEMENTS, cdataSectionElements); buffer.append(";cdata-section-elements=").append(cdataSectionElements); } if (dtPublic != null) { format.put(OutputKeys.DOCTYPE_PUBLIC, dtPublic); buffer.append(";doctype-public=").append(dtPublic); } if (dtSystem != null) { format.put(OutputKeys.DOCTYPE_SYSTEM, dtSystem); buffer.append(";doctype-system=").append(dtSystem); } if (encoding != null) { format.put(OutputKeys.ENCODING, encoding); buffer.append(";encoding=").append(encoding); } if (indent != null) { format.put(OutputKeys.INDENT, indent); buffer.append(";indent=").append(indent); } if (mediaType != null) { format.put(OutputKeys.MEDIA_TYPE, mediaType); buffer.append(";media-type=").append(mediaType); } if (method != null) { format.put(OutputKeys.METHOD, method); buffer.append(";method=").append(method); } if (omitXMLDeclaration != null) { format.put(OutputKeys.OMIT_XML_DECLARATION, omitXMLDeclaration); buffer.append(";omit-xml-declaration=").append(omitXMLDeclaration); } if (standAlone != null) { format.put(OutputKeys.STANDALONE, standAlone); buffer.append(";standalone=").append(standAlone); } if (version != null) { format.put(OutputKeys.VERSION, version); buffer.append(";version=").append(version); } if (buffer.length() > 0) { this.cachingKey = buffer.toString(); } String tFactoryClass = conf.getChild("transformer-factory").getValue(null); if (tFactoryClass != null) { try { this.tfactory = (SAXTransformerFactory) ClassUtils.newInstance(tFactoryClass); if (getLogger().isDebugEnabled()) { getLogger().debug("Using transformer factory " + tFactoryClass); } } catch (Exception e) { throw new ConfigurationException("Cannot load transformer factory " + tFactoryClass, e); } } else { // Standard TrAX behaviour this.tfactory = (SAXTransformerFactory) TransformerFactory.newInstance(); } tfactory.setErrorListener(new TraxErrorHandler(getLogger())); // Check if we need namespace as attributes. try { if (needsNamespacesAsAttributes()) { // Setup a correction pipe this.namespacePipe = new NamespaceAsAttributes(); this.namespacePipe.enableLogging(getLogger()); } } catch (Exception e) { getLogger().warn("Cannot know if transformer needs namespaces attributes - assuming NO.", e); } }