List of usage examples for javax.xml.transform OutputKeys MEDIA_TYPE
String MEDIA_TYPE
To view the source code for javax.xml.transform OutputKeys MEDIA_TYPE.
Click Source Link
From source file:Main.java
private static String getIndented(Document aDoc) { String outputXml = ""; try {/*from w w w . jav a2 s. com*/ TransformerFactory tf = TransformerFactory.newInstance(); // tf.setAttribute("indent-number", new Integer(4)); Transformer transformer; transformer = tf.newTransformer(); transformer.setOutputProperty(OutputKeys.INDENT, "yes"); transformer.setOutputProperty(OutputKeys.METHOD, "xml"); transformer.setOutputProperty(OutputKeys.MEDIA_TYPE, "text/xml"); transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2"); StreamResult result = new StreamResult(new StringWriter()); DOMSource source = new DOMSource(aDoc); transformer.transform(source, result); outputXml = result.getWriter().toString(); } catch (TransformerConfigurationException e) { e.printStackTrace(); } catch (TransformerException e) { e.printStackTrace(); } return outputXml; }
From source file:Main.java
private static void writeTo(Result result, Document document) throws TransformerConfigurationException, TransformerException, FileNotFoundException, UnsupportedEncodingException { // Use a Transformer for output TransformerFactory tFactory = TransformerFactory.newInstance(); tFactory.setAttribute("indent-number", new Integer(4)); Transformer transformer = tFactory.newTransformer(); DOMSource source = new DOMSource(document); transformer.setOutputProperty(OutputKeys.METHOD, "xml"); // NOI18N transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8"); // NOI18N transformer.setOutputProperty(OutputKeys.MEDIA_TYPE, "text/xml"); // NOI18N transformer.setOutputProperty(OutputKeys.STANDALONE, "yes"); // NOI18N // indent the output to make it more legible... try {/*from w ww.j a v a 2 s . c o m*/ transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4"); // NOI18N transformer.setOutputProperty(OutputKeys.INDENT, "yes"); // NOI18N } catch (IllegalArgumentException e) { // the JAXP implementation doesn't support indentation, no big deal //e.printStackTrace(); } transformer.transform(source, result); }
From source file:Main.java
/** * DOCUMENT ME!/*from w ww.ja v a 2s . c om*/ * * @return DOCUMENT ME! * * @throws TransformerConfigurationException DOCUMENT ME! * @throws TransformerException DOCUMENT ME! * @throws Exception DOCUMENT ME! */ public static byte[] writeToBytes(Document document) throws TransformerConfigurationException, TransformerException, Exception { byte[] ret = null; TransformerFactory tFactory = TransformerFactory.newInstance(); tFactory.setAttribute("indent-number", new Integer(4)); Transformer transformer = tFactory.newTransformer(); DOMSource source = new DOMSource(document); ByteArrayOutputStream bos = new ByteArrayOutputStream(); StreamResult result = new StreamResult(bos); transformer.setOutputProperty(OutputKeys.METHOD, "xml"); // NOI18N transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8"); // NOI18N transformer.setOutputProperty(OutputKeys.MEDIA_TYPE, "text/xml"); // NOI18N transformer.setOutputProperty(OutputKeys.STANDALONE, "yes"); // NOI18N // indent the output to make it more legible... try { transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4"); // NOI18N transformer.setOutputProperty(OutputKeys.INDENT, "yes"); // NOI18N } catch (IllegalArgumentException e) { // the JAXP implementation doesn't support indentation, no big deal //e.printStackTrace(); } try { transformer.transform(source, result); ret = bos.toByteArray(); } finally { if (bos != null) { bos.flush(); bos.close(); } } return ret; }
From source file:net.sf.joost.trax.TransformerImpl.java
/** * Constructor//w w w. ja v a2 s . com * * @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./* w ww.ja va 2s . 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:org.fcrepo.localservices.saxon.SaxonServlet.java
/** * Apply stylesheet to source document//ww w . j ava2 s. c om */ private void apply(String style, String source, HttpServletRequest req, HttpServletResponse res) throws Exception { // Validate parameters if (style == null) { throw new TransformerException("No style parameter supplied"); } if (source == null) { throw new TransformerException("No source parameter supplied"); } InputStream sourceStream = null; try { // Load the stylesheet (adding to cache if necessary) Templates pss = tryCache(style); Transformer transformer = pss.newTransformer(); Enumeration<?> p = req.getParameterNames(); while (p.hasMoreElements()) { String name = (String) p.nextElement(); if (!(name.equals("style") || name.equals("source"))) { String value = req.getParameter(name); transformer.setParameter(name, new StringValue(value)); } } // Start loading the document to be transformed sourceStream = getInputStream(source); // Set the appropriate output mime type String mime = pss.getOutputProperties().getProperty(OutputKeys.MEDIA_TYPE); if (mime == null) { res.setContentType("text/html"); } else { res.setContentType(mime); } // Transform StreamSource ss = new StreamSource(sourceStream); ss.setSystemId(source); transformer.transform(ss, new StreamResult(res.getOutputStream())); } finally { if (sourceStream != null) { try { sourceStream.close(); } catch (Exception e) { } } } }
From source file:com.hp.hpl.jena.grddl.impl.GRDDL.java
private String mimetype(Transformer t) { String mt = t.getOutputProperty(OutputKeys.MEDIA_TYPE); return mt == null ? "application/rdf+xml" : mt; }
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 ww w.j a v a 2s.c om*/ 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:net.sourceforge.vulcan.core.support.AbstractProjectDomBuilder.java
public String transform(Document document, Map<String, ?> transformParameters, Locale locale, String format, Result result) throws SAXException, IOException, TransformerException, NoSuchTransformFormatException { final Transformer transformer = createTransformer(format); if (transformParameters != null) { for (String key : transformParameters.keySet()) { transformer.setParameter(key, transformParameters.get(key)); }/*from w ww . j av a 2 s .c o m*/ } transformer.transform(new JDOMSource(document), result); return transformer.getOutputProperty(OutputKeys.MEDIA_TYPE); }
From source file:org.apache.cocoon.serialization.AbstractTextSerializer.java
/** * Set the configurations for this serializer. *///from ww w. j a v a 2s . 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); } }