List of usage examples for javax.xml.transform OutputKeys CDATA_SECTION_ELEMENTS
String CDATA_SECTION_ELEMENTS
To view the source code for javax.xml.transform OutputKeys CDATA_SECTION_ELEMENTS.
Click Source Link
From source file:Main.java
public static String xml2Str(Document document) { try {/* w w w. j ava 2 s . c o m*/ DOMSource source = new DOMSource(document); StringWriter writer = new StringWriter(); Result result = new StreamResult(writer); Transformer transformer = TransformerFactory.newInstance().newTransformer(); transformer.setOutputProperty(OutputKeys.INDENT, "yes"); transformer.setOutputProperty(OutputKeys.CDATA_SECTION_ELEMENTS, "yes"); transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2"); transformer.transform(source, result); return (writer.getBuffer().toString()); } catch (Exception e) { e.printStackTrace(); } return ""; }
From source file:net.sf.joost.trax.TransformerImpl.java
/** * Constructor/*from w w w .java 2 s . co m*/ * * @param processor A <code>Processor</code> object. */ protected TransformerImpl(Processor processor) { this.processor = processor; // set tracing manager on processor object if (processor instanceof DebugProcessor) { DebugProcessor dbp = (DebugProcessor) processor; dbp.setTraceManager(traceManager); dbp.setTransformer(this); Emitter emitter = processor.getEmitter(); if (emitter instanceof DebugEmitter) { ((DebugEmitter) emitter).setTraceManager(traceManager); } } supportedProperties.add(OutputKeys.ENCODING); supportedProperties.add(OutputKeys.MEDIA_TYPE); supportedProperties.add(OutputKeys.METHOD); supportedProperties.add(OutputKeys.OMIT_XML_DECLARATION); supportedProperties.add(OutputKeys.STANDALONE); supportedProperties.add(OutputKeys.VERSION); supportedProperties.add(TrAXConstants.OUTPUT_KEY_SUPPORT_DISABLE_OUTPUT_ESCAPING); ignoredProperties.add(OutputKeys.CDATA_SECTION_ELEMENTS); ignoredProperties.add(OutputKeys.DOCTYPE_PUBLIC); ignoredProperties.add(OutputKeys.DOCTYPE_SYSTEM); ignoredProperties.add(OutputKeys.INDENT); }
From source file:de.betterform.connector.xslt.XSLTSubmissionHandler.java
/** * Serializes and submits the specified instance data over the * <code>xslt</code> protocol. * * @param submission the submission issuing the request. * @param instance the instance data to be serialized and submitted. * @return xslt transformation result./* www .jav a 2 s .co m*/ * @throws XFormsException if any error occurred during submission. */ public Map submit(Submission submission, Node instance) throws XFormsException { try { if (LOGGER.isDebugEnabled()) { LOGGER.debug("uri: " + getURI()); } URI uri = ConnectorHelper.resolve(submission.getContainerObject().getProcessor().getBaseURI(), getURI()); Map parameters = ConnectorHelper.getURLParameters(uri); URI stylesheetURI = ConnectorHelper.removeURLParameters(uri); if (LOGGER.isDebugEnabled()) { LOGGER.debug("stylesheet uri: " + stylesheetURI); } // pass output properties from submission CachingTransformerService transformerService = (CachingTransformerService) getContext() .get(TransformerService.TRANSFORMER_SERVICE); if (transformerService == null) { if (uri.getScheme().equals("http")) { transformerService = new CachingTransformerService(new HttpResourceResolver()); } else if (uri.getScheme().equals("file")) { transformerService = new CachingTransformerService(new FileResourceResolver()); } else { throw new XFormsException( "Protocol " + stylesheetURI.getScheme() + " not supported for XSLT Submission Handler"); } } if (parameters != null && parameters.get("nocache") != null) { transformerService.setNoCache(true); } Transformer transformer = transformerService.getTransformer(stylesheetURI); if (submission.getVersion() != null) { transformer.setOutputProperty(OutputKeys.VERSION, submission.getVersion()); } if (submission.getIndent() != null) { transformer.setOutputProperty(OutputKeys.INDENT, Boolean.TRUE.equals(submission.getIndent()) ? "yes" : "no"); } if (submission.getMediatype() != null) { transformer.setOutputProperty(OutputKeys.MEDIA_TYPE, submission.getMediatype()); } if (submission.getEncoding() != null) { transformer.setOutputProperty(OutputKeys.ENCODING, submission.getEncoding()); } else { transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8"); } if (submission.getOmitXMLDeclaration() != null) { transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, Boolean.TRUE.equals(submission.getOmitXMLDeclaration()) ? "yes" : "no"); } if (submission.getStandalone() != null) { transformer.setOutputProperty(OutputKeys.STANDALONE, Boolean.TRUE.equals(submission.getStandalone()) ? "yes" : "no"); } if (submission.getCDATASectionElements() != null) { transformer.setOutputProperty(OutputKeys.CDATA_SECTION_ELEMENTS, submission.getCDATASectionElements()); } // pass parameters form uri if any if (parameters != null) { Iterator iterator = parameters.keySet().iterator(); String name; while (iterator.hasNext()) { name = (String) iterator.next(); transformer.setParameter(name, parameters.get(name)); } } // transform instance to byte array ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); long start = System.currentTimeMillis(); DOMSource domSource; //check for 'parse' param String parseParam = null; if (parameters.containsKey("parseString")) { parseParam = (String) parameters.get("parseString"); } if (parseParam != null && parseParam.equalsIgnoreCase("true")) { String xmlString = DOMUtil.getTextNodeAsString(instance); domSource = new DOMSource(DOMUtil.parseString(xmlString, true, false)); } else { domSource = new DOMSource(instance); } transformer.transform(domSource, new StreamResult(outputStream)); long end = System.currentTimeMillis(); if (LOGGER.isDebugEnabled()) { LOGGER.debug("transformation time: " + (end - start) + " ms"); } // create input stream from result InputStream inputStream = new ByteArrayInputStream(outputStream.toByteArray()); Map response = new HashMap(); response.put(XFormsProcessor.SUBMISSION_RESPONSE_STREAM, inputStream); return response; } catch (Exception e) { throw new XFormsException(e); } }
From source file:Main.java
/** * Writes a DOM document to a stream. The precise output format is not * guaranteed but this method will attempt to indent it sensibly. * * <p class="nonnormative"><b>Important</b>: There might be some problems * with <code><![CDATA[ ]]></code> sections in the DOM tree you pass * into this method. Specifically, some CDATA sections my not be written as * CDATA section or may be merged with other CDATA section at the same * level. Also if plain text nodes are mixed with CDATA sections at the same * level all text is likely to end up in one big CDATA section. * <br>// w w w .j a v a 2 s .c o m * For nodes that only have one CDATA section this method should work fine. * </p> * * @param doc DOM document to be written * @param out data sink * @param enc XML-defined encoding name (for example, "UTF-8") * @throws IOException if JAXP fails or the stream cannot be written to */ public static void write(Document doc, OutputStream out, String enc) throws IOException { if (enc == null) { throw new NullPointerException( "You must set an encoding; use \"UTF-8\" unless you have a good reason not to!"); // NOI18N } Document doc2 = normalize(doc); ClassLoader orig = Thread.currentThread().getContextClassLoader(); Thread.currentThread() .setContextClassLoader(AccessController.doPrivileged(new PrivilegedAction<ClassLoader>() { // #195921 @Override public ClassLoader run() { return new ClassLoader(ClassLoader.getSystemClassLoader().getParent()) { @Override public InputStream getResourceAsStream(String name) { if (name.startsWith("META-INF/services/")) { return new ByteArrayInputStream(new byte[0]); // JAXP #6723276 } return super.getResourceAsStream(name); } }; } })); try { TransformerFactory tf = TransformerFactory.newInstance(); Transformer t = tf.newTransformer(new StreamSource(new StringReader(IDENTITY_XSLT_WITH_INDENT))); DocumentType dt = doc2.getDoctype(); if (dt != null) { String pub = dt.getPublicId(); if (pub != null) { t.setOutputProperty(OutputKeys.DOCTYPE_PUBLIC, pub); } String sys = dt.getSystemId(); if (sys != null) { t.setOutputProperty(OutputKeys.DOCTYPE_SYSTEM, sys); } } t.setOutputProperty(OutputKeys.ENCODING, enc); try { t.setOutputProperty(ORACLE_IS_STANDALONE, "yes"); } catch (IllegalArgumentException x) { // fine, introduced in JDK 7u4 } // See #123816 Set<String> cdataQNames = new HashSet<String>(); collectCDATASections(doc2, cdataQNames); if (cdataQNames.size() > 0) { StringBuilder cdataSections = new StringBuilder(); for (String s : cdataQNames) { cdataSections.append(s).append(' '); //NOI18N } t.setOutputProperty(OutputKeys.CDATA_SECTION_ELEMENTS, cdataSections.toString()); } Source source = new DOMSource(doc2); Result result = new StreamResult(out); t.transform(source, result); } catch (javax.xml.transform.TransformerException | RuntimeException e) { // catch anything that happens throw new IOException(e); } finally { Thread.currentThread().setContextClassLoader(orig); } }
From source file:com.mediaworx.xmlutils.XmlHelper.java
/** * Converts the document to a formatted XML String (indentation level is 4) using the given encoding. * @param document The document to be converted to String * @param cdataElements String array containing the names of all elements that are to be added within CDATA sections * @param encoding encoding to be used (added in the XML declaration) * @return the String representation of the given Document *//*w w w . j a v a 2 s . co m*/ public String getXmlStringFromDocument(Document document, String[] cdataElements, String encoding) { cleanEmptyTextNodes(document); TransformerFactory tf = TransformerFactory.newInstance(); Transformer transformer; try { transformer = tf.newTransformer(); } catch (TransformerConfigurationException e) { LOG.error("Exception configuring the XML transformer", e); return ""; } transformer.setOutputProperty(OutputKeys.METHOD, "xml"); transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes"); transformer.setOutputProperty(OutputKeys.INDENT, "yes"); if (cdataElements != null && cdataElements.length > 0) { String cdataElementsJoined = StringUtils.join(cdataElements, ' '); transformer.setOutputProperty(OutputKeys.CDATA_SECTION_ELEMENTS, cdataElementsJoined); } transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4"); OutputStream out = new ByteArrayOutputStream(); try { transformer.transform(new DOMSource(document), new StreamResult(out)); } catch (TransformerException e) { LOG.error("Exception transforming the XML document to String", e); } finally { try { out.close(); } catch (IOException e) { // it seems the output stream was closed already LOG.warn("Exception closing the output stream", e); } } StringBuilder xml = new StringBuilder("<?xml version=\"1.0\" encoding=\"").append(encoding) .append("\"?>\n"); xml.append(out.toString()); return xml.toString(); }
From source file:nl.armatiek.xslweb.serializer.ZipSerializer.java
private void processInlineEntry(String uri, String localName, String qName, Attributes attributes) throws Exception { String name = attributes.getValue("", "name"); if (name == null) { throw new SAXException("No attribute \"name\" specified on inline-entry element"); }// w w w . jav a2s.co m Serializer serializer = webApp.getProcessor().newSerializer(this.zos); for (int i = 0; i < attributes.getLength(); i++) { String n = attributes.getLocalName(i); if (n.equals("name")) { continue; } String value = attributes.getValue(i); if (n.equals(OutputKeys.CDATA_SECTION_ELEMENTS)) { value = value.replaceAll("\\{\\}", "{''}"); } serializer.setOutputProperty(Property.get(n), value); } ZipEntry entry = new ZipEntry(name); zos.putNextEntry(entry); this.xsw = serializer.getXMLStreamWriter(); this.serializingHandler = new ContentHandlerToXMLStreamWriter(xsw); }
From source file:nl.armatiek.xslweb.web.servlet.XSLWebServlet.java
private Destination getDestination(WebApp webApp, HttpServletRequest req, HttpServletResponse resp, OutputStream os, Properties outputProperties, PipelineStep currentStep, PipelineStep nextStep) throws Exception { Destination dest;/* w ww. j av a2 s.c om*/ if (nextStep == null) { Serializer serializer = webApp.getProcessor().newSerializer(os); if (outputProperties != null) { for (String key : outputProperties.stringPropertyNames()) { String value = outputProperties.getProperty(key); if (key.equals(OutputKeys.CDATA_SECTION_ELEMENTS)) { value = value.replaceAll("\\{\\}", "{''}"); } Property prop = Property.get(key); if (prop == null) { continue; } serializer.setOutputProperty(prop, value); } } XMLStreamWriter xsw = new CleanupXMLStreamWriter(serializer.getXMLStreamWriter()); dest = new XMLStreamWriterDestination(xsw); } else if (nextStep instanceof TransformerStep || nextStep instanceof SchemaValidatorStep) { dest = new XdmSourceDestination(); } else if (nextStep instanceof JSONSerializerStep) { dest = ((JSONSerializerStep) nextStep).getDestination(webApp, req, resp, os, outputProperties); } else if (nextStep instanceof ZipSerializerStep) { dest = ((ZipSerializerStep) nextStep).getDestination(webApp, req, resp, os, outputProperties); } else if (nextStep instanceof ResourceSerializerStep) { dest = ((ResourceSerializerStep) nextStep).getDestination(webApp, req, resp, os, outputProperties); } else if (nextStep instanceof FopSerializerStep) { dest = ((FopSerializerStep) nextStep).getDestination(webApp, req, resp, os, outputProperties); } else { throw new XSLWebException("Could not determine destination"); } return getDestination(webApp, dest, currentStep); }
From source file:org.apache.cocoon.serialization.AbstractTextSerializer.java
/** * Set the configurations for this serializer. *///www . j a v a 2s.com 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); } }
From source file:org.expath.tools.model.exist.EXistSequence.java
/** * Borrowed from {@link org.expath.tools.saxon.model.SaxonSequence} *//* ww w. j av a 2 s. co m*/ private Properties makeOutputProperties(final SerialParameters params) throws ToolsException { final Properties props = new Properties(); setOutputKey(props, OutputKeys.METHOD, params.getMethod()); setOutputKey(props, OutputKeys.MEDIA_TYPE, params.getMediaType()); setOutputKey(props, OutputKeys.ENCODING, params.getEncoding()); setOutputKey(props, OutputKeys.CDATA_SECTION_ELEMENTS, params.getCdataSectionElements()); setOutputKey(props, OutputKeys.DOCTYPE_PUBLIC, params.getDoctypePublic()); setOutputKey(props, OutputKeys.DOCTYPE_SYSTEM, params.getDoctypeSystem()); setOutputKey(props, OutputKeys.INDENT, params.getIndent()); setOutputKey(props, OutputKeys.OMIT_XML_DECLARATION, params.getOmitXmlDeclaration()); setOutputKey(props, OutputKeys.STANDALONE, params.getStandalone()); setOutputKey(props, OutputKeys.VERSION, params.getVersion()); return props; }
From source file:org.fireflow.model.io.resource.ResourceSerializer.java
public static void serialize(List<ResourceDef> resources, OutputStream out, String charset) throws IOException, SerializerException { try {//from w ww .j a va 2 s . co m Document document = serializeToDOM(resources); TransformerFactory transformerFactory = TransformerFactory.newInstance(); Transformer transformer = transformerFactory.newTransformer(); transformer.setOutputProperty(OutputKeys.ENCODING, charset); transformer.setOutputProperty(OutputKeys.INDENT, "yes"); transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2"); transformer.setOutputProperty(OutputKeys.CDATA_SECTION_ELEMENTS, CDATA_SECTION_ELEMENT_LIST); transformer.transform(new DOMSource(document), new StreamResult(out)); out.flush(); } catch (TransformerConfigurationException e) { throw new SerializerException(e); } catch (TransformerException e) { throw new SerializerException(e); } finally { } }