List of usage examples for javax.xml.transform OutputKeys ENCODING
String ENCODING
To view the source code for javax.xml.transform OutputKeys ENCODING.
Click Source Link
From source file:org.kalypso.kalypsosimulationmodel.utils.SLDHelper.java
private static void exportSLD(final IFile sldFile, final StyledLayerDescriptor descriptor, final IProgressMonitor progressMonitor) throws IOException, SAXException, CoreException { // FIXME: ugly! The bug is elsewhere! if (!sldFile.isSynchronized(IResource.DEPTH_ZERO)) sldFile.refreshLocal(IResource.DEPTH_ZERO, new NullProgressMonitor()); final ByteArrayInputStream stream = new ByteArrayInputStream(descriptor.exportAsXML().getBytes("UTF-8")); //$NON-NLS-1$ final Document doc = XMLTools.parse(stream); final Source source = new DOMSource(doc); final SetContentHelper helper = new SetContentHelper() { @Override/*w ww. ja v a 2 s . c o m*/ protected void write(final OutputStreamWriter writer) throws Throwable { try { final StreamResult result = new StreamResult(writer); final TransformerFactory factory = TransformerFactory.newInstance(); // Comment from Dejan: this works only with Java 1.5, in 1.4 it throws IllegalArgumentException // also, indentation doesn't works with OutputStream, only with OutputStreamWriter :) try { factory.setAttribute("indent-number", new Integer(4)); //$NON-NLS-1$ } catch (final IllegalArgumentException e) { } final Transformer transformer = factory.newTransformer(); transformer.setOutputProperty(OutputKeys.ENCODING, writer.getEncoding()); transformer.setOutputProperty(OutputKeys.INDENT, "yes"); //$NON-NLS-1$ // transformer.setOutputProperty( "{http://xml.apache.org/xslt}indent-amount", "2" ); // //$NON-NLS-1$ // //$NON-NLS-2$ // transformer.setOutputProperty(OutputKeys.METHOD, "xml"); //$NON-NLS-1$ // transformer.setOutputProperty(OutputKeys.MEDIA_TYPE, "text/xml"); //$NON-NLS-1$ //$NON-NLS-2$ transformer.transform(source, result); } finally { IOUtils.closeQuietly(writer); } } }; if (progressMonitor.isCanceled()) throw new CoreException(Status.CANCEL_STATUS); helper.setFileContents(sldFile, false, false, progressMonitor); }
From source file:org.kalypso.model.hydrology.util.optimize.NAOptimizingJob.java
private void saveOptimizeConfig(final File file) { try {/*w w w . j av a 2s . c o m*/ final TransformerFactory factory = TransformerFactory.newInstance(); final Transformer t = factory.newTransformer(); t.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2"); //$NON-NLS-1$ //$NON-NLS-2$ t.setOutputProperty(OutputKeys.INDENT, "yes"); //$NON-NLS-1$ final Node naOptimizeDom = m_data.getOptimizeData().getOptimizeDom(); final Document ownerDocument = naOptimizeDom instanceof Document ? (Document) naOptimizeDom : naOptimizeDom.getOwnerDocument(); final String encoding = ownerDocument.getInputEncoding(); t.setOutputProperty(OutputKeys.ENCODING, encoding); t.transform(new DOMSource(ownerDocument), new StreamResult(file)); } catch (final Exception e) { e.printStackTrace(); } }
From source file:org.kalypso.ogc.gml.serialize.GmlSerializer.java
/** * Most general way to serialize the workspace. All other serialize methods should eventually cal this method. *//*www . j a va 2s .co m*/ public static void serializeWorkspace(final GMLWorkspaceInputSource inputSource, final StreamResult result, final String charsetEncoding) throws GmlSerializeException { try { // TODO: error handling final XMLReader reader = new GMLWorkspaceReader(); // TODO: add an error handler that logs everything into a status // reader.setErrorHandler( null ); // TODO: write gml to a temporary location and replace the target file later, // in order to preserve the old version if anything goes wrong reader.setFeature("http://xml.org/sax/features/namespaces", true); //$NON-NLS-1$ reader.setFeature("http://xml.org/sax/features/namespace-prefixes", true); //$NON-NLS-1$ final Source source = new SAXSource(reader, inputSource); final Transformer transformer = TRANSFORMER_FACTORY.newTransformer(); transformer.setOutputProperty(OutputKeys.ENCODING, charsetEncoding); transformer.setOutputProperty(OutputKeys.INDENT, "yes"); //$NON-NLS-1$ transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "1"); //$NON-NLS-1$ //$NON-NLS-2$ transformer.setOutputProperty(OutputKeys.METHOD, "xml"); //$NON-NLS-1$ // TODO: maybe also use OutputKeys.CDATA_SECTION_ELEMENTS ? See the marshallMethod of the XSDBaseTypeHandlerString // TODO put new QName( NS.OM, "result" ) here instead inside the GMLSaxFactory // Problem: must now know the prefix of NS.OM transformer.transform(source, result); } catch (final Exception e) { throw new GmlSerializeException(Messages.getString("org.kalypso.ogc.gml.serialize.GmlSerializer.4"), e); //$NON-NLS-1$ } }
From source file:org.kapott.hbci.tools.TransactionsToXML.java
public void writeXMLString(Document doc, OutputStream out) { if (doc == null) { throw new NullPointerException("document must not be null"); }//from w w w . j a va 2 s .com if (out == null) { throw new NullPointerException("output stream must not be null"); } try { TransformerFactory transFac = TransformerFactory.newInstance(); Transformer trans = transFac.newTransformer(); trans.setOutputProperty(OutputKeys.METHOD, "xml"); trans.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "no"); trans.setOutputProperty(OutputKeys.ENCODING, "UTF-8"); trans.setOutputProperty(OutputKeys.INDENT, "yes"); Source source = new DOMSource(doc); Result target = new StreamResult(out); trans.transform(source, target); } catch (Exception e) { throw new RuntimeException(e); } }
From source file:org.kuali.coeus.common.budget.framework.nonpersonnel.BudgetJustificationWrapper.java
public String toString() { DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance(); try (Writer out = new StringWriter()) { DocumentBuilder docBuilder = docFactory.newDocumentBuilder(); Document document = docBuilder.newDocument(); Element rootElement = document.createElement("budgetJustification"); rootElement.setAttribute("lastUpdateBy", lastUpdateUser); rootElement.setAttribute("lastUpdateOn", lastUpdateTime); document.appendChild(rootElement); CDATASection cdata = document.createCDATASection(justificationText == null ? "" : justificationText); rootElement.appendChild(cdata);//from w ww.j a v a2s . c o m Transformer tf = TransformerFactory.newInstance().newTransformer(); tf.setOutputProperty(OutputKeys.ENCODING, "UTF-8"); tf.setOutputProperty(OutputKeys.INDENT, "yes"); tf.transform(new DOMSource(document), new StreamResult(out)); return out.toString(); } catch (ParserConfigurationException | TransformerException | IOException e) { throw new RuntimeException(e); } }
From source file:org.lareferencia.backend.indexer.IndexerImpl.java
private Transformer buildTransformer() throws IndexerException { Transformer trf;//from www .j av a 2 s .c om try { StreamSource stylesource = new StreamSource(stylesheet); trf = xformFactory.newTransformer(stylesource); trf = MedatadaDOMHelper.buildXSLTTransformer(stylesheet); trf.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes"); trf.setOutputProperty(OutputKeys.INDENT, "no"); trf.setOutputProperty(OutputKeys.ENCODING, "UTF-8"); } catch (TransformerConfigurationException e) { throw new IndexerException(e.getMessage(), e.getCause()); } return trf; }
From source file:org.lilyproject.runtime.tools.plugin.genclassloader.ClassloaderMojo.java
/** * Create a project file containing the dependencies. * * @throws IOException/*from w w w.j a v a2 s. c om*/ * @throws SAXException */ private void createDependencyListing(File classloaderTemplate) throws IOException, SAXException { if (classloaderTemplate != null && classloaderTemplate.exists()) { getLog().info("Found classloader template, trying to parse it..."); parseClassloaderTemplate(classloaderTemplate); } final boolean hasEntries = entryMap.size() > 0; // fill in file with all dependencies FileOutputStream fos = new FileOutputStream(projectDescriptorFile); TransformerHandler ch = null; TransformerFactory factory = TransformerFactory.newInstance(); if (factory.getFeature(SAXTransformerFactory.FEATURE)) { try { ch = ((SAXTransformerFactory) factory).newTransformerHandler(); // set properties Transformer serializer = ch.getTransformer(); serializer.setOutputProperty(OutputKeys.ENCODING, "UTF-8"); serializer.setOutputProperty(OutputKeys.INDENT, "yes"); serializer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2"); // set result Result result = new StreamResult(fos); ch.setResult(result); // start file generation ch.startDocument(); AttributesImpl atts = new AttributesImpl(); if (this.shareSelf != null) { atts.addAttribute("", "share-self", "share-self", "CDATA", this.shareSelf); } ch.startElement("", "classloader", "classloader", atts); atts.clear(); ch.startElement("", "classpath", "classpath", atts); SortedSet<Artifact> sortedArtifacts = new TreeSet<Artifact>(dependenciesToList); Entry entry; String entryShare; String entryVersion; for (Artifact artifact : sortedArtifacts) { atts.addAttribute("", "groupId", "groupId", "CDATA", artifact.getGroupId()); atts.addAttribute("", "artifactId", "artifactId", "CDATA", artifact.getArtifactId()); if (artifact.getClassifier() != null) { atts.addAttribute("", "classifier", "classifier", "CDATA", artifact.getClassifier()); } if (!artifact.getGroupId().equals("org.lilyproject")) { atts.addAttribute("", "version", "version", "CDATA", artifact.getBaseVersion()); } entry = new Entry(artifact.getGroupId(), artifact.getArtifactId(), artifact.getClassifier()); if (hasEntries && entryMap.containsKey(entry)) { entryVersion = extractAttVal(entryMap.get(entry).getAttributes(), "version"); entryShare = extractAttVal(entryMap.get(entry).getAttributes(), "share"); entryMap.remove(entry); if (entryVersion != null && !entryVersion.equals("") && !entryVersion.equals(artifact.getBaseVersion())) { getLog().warn( "version conflict between entry in template and artifact on classpath for " + entry); } if (entryShare != null) { atts.addAttribute("", "", "share", "CDATA", entryShare); } } else { // atts.addAttribute("", "", "share", "CDATA", SHARE_DEFAULT); } ch.startElement("", "artifact", "artifact", atts); ch.endElement("", "artifact", "artifact"); atts.clear(); } ch.endElement("", "classpath", "classpath"); ch.endElement("", "classloader", "classloader"); ch.endDocument(); fos.close(); if (entryMap.size() > 0) { getLog().warn("Classloader template contains entries that could not be resolved."); } } catch (TransformerConfigurationException ex) { ex.printStackTrace(); throw new SAXException("Unable to get a TransformerHandler."); } } else { throw new RuntimeException("Could not load SAXTransformerFactory."); } }
From source file:org.metaeffekt.dcc.commons.ant.MergeXmlTask.java
private void initialize() { try {/*w w w .ja v a2 s . c o m*/ if (documentBuilderFactory == null) { documentBuilderFactory = DocumentBuilderFactory.newInstance(); documentBuilderFactory.setNamespaceAware(true); } if (documentBuilder == null) { documentBuilder = documentBuilderFactory.newDocumentBuilder(); } if (transformerFactory == null) { transformerFactory = TransformerFactory.newInstance(); } if (transformer == null) { transformer = transformerFactory.newTransformer(); transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8"); transformer.setOutputProperty(OutputKeys.INDENT, "yes"); transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4"); } if (xPathfactory == null) { xPathfactory = XPathFactory.newInstance(); } } catch (IllegalArgumentException | ParserConfigurationException | TransformerConfigurationException | TransformerFactoryConfigurationError e) { throw new BuildException("Cannot initialize XML infrastructure.", e); } }
From source file:org.mule.module.xml.transformer.AbstractXmlTransformer.java
/** * Converts an XML in-memory representation to a String using a specific encoding. * If using an encoding which cannot represent specific characters, these are * written as entities, even if they can be represented as a Java String. * * @param obj Object to convert (could be byte[], String, DOM, or DOM4J Document). * If the object is a byte[], the character * encoding used MUST match the declared encoding standard, or a parse error will occur. * @param outputEncoding Name of the XML encoding to use, e.g. US-ASCII, or null for UTF-8 * @return String including XML header using the specified encoding * @throws TransformerFactoryConfigurationError * On error/*from ww w. java 2 s .c o m*/ * @throws javax.xml.transform.TransformerException * On error * @throws TransformerException */ protected String convertToText(Object obj, String outputEncoding) throws Exception { // Catch the direct translations if (obj instanceof String) { return (String) obj; } else if (obj instanceof Node) { return ((Node) obj).asXML(); } // No easy fix, so use the transformer. Source src = XMLUtils.toXmlSource(xmlInputFactory, useStaxSource, obj); if (src == null) { return null; } StringWriter writer = new StringWriter(); StreamResult result = new StreamResult(writer); Transformer idTransformer = TransformerFactory.newInstance().newTransformer(); if (outputEncoding != null) { idTransformer.setOutputProperty(OutputKeys.ENCODING, outputEncoding); } idTransformer.transform(src, result); return writer.getBuffer().toString(); }
From source file:org.mule.module.xml.transformer.AbstractXmlTransformer.java
/** * Converts an XML in-memory representation to a String using a specific encoding. * * @param obj Object to convert (could be byte[], String, DOM, or DOM4J Document). * If the object is a byte[], the character * encoding used MUST match the declared encoding standard, or a parse error will occur. * @param outputEncoding Name of the XML encoding to use, e.g. US-ASCII, or null for UTF-8 * @return String including XML header using the specified encoding * @throws TransformerFactoryConfigurationError * On error/* w ww .j a v a 2 s.c o m*/ * @throws javax.xml.transform.TransformerException * On error * @throws TransformerException */ protected String convertToBytes(Object obj, String outputEncoding) throws Exception { // Always use the transformer, even for byte[] (to get the encoding right!) Source src = XMLUtils.toXmlSource(xmlInputFactory, useStaxSource, obj); if (src == null) { return null; } StringWriter writer = new StringWriter(); StreamResult result = new StreamResult(writer); Transformer idTransformer = XMLUtils.getTransformer(); idTransformer.setOutputProperty(OutputKeys.ENCODING, outputEncoding); idTransformer.transform(src, result); return writer.getBuffer().toString(); }