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:Main.java
/** * Transforms a {@link Source} object into a {@link String} representation. * /* w w w. j av a 2 s . co m*/ * @param xml the source input. * @param pretty if {@code true} then pretty print with white space. * @param writer write the string to this {@link Writer}. * @throws TransformerException */ public static void toString(Source xml, boolean pretty, Writer writer) throws TransformerException { final TransformerFactory factory = TransformerFactory.newInstance(); try { factory.setAttribute("{http://xml.apache.org/xalan}indent-amount", 2); } catch (IllegalArgumentException iae) { // try a different ident amount try { factory.setAttribute("indent-number", 2); } catch (IllegalArgumentException iae2) { // ignore } } final Transformer transformer = factory.newTransformer(); if (pretty) { transformer.setOutputProperty(OutputKeys.INDENT, "yes"); transformer.setOutputProperty(OutputKeys.ENCODING, "utf-8"); } transformer.transform(xml, new StreamResult(writer)); }
From source file:com.alfaariss.oa.util.configuration.handler.text.PlainTextConfigurationHandler.java
/** * Writes the configuration to System.out. * @see IConfigurationHandler#saveConfiguration(org.w3c.dom.Document) *//*w ww. ja va 2 s . c o m*/ public void saveConfiguration(Document oConfigurationDocument) throws ConfigurationException { try { Transformer transformer = TransformerFactory.newInstance().newTransformer(); transformer.setOutputProperty(OutputKeys.METHOD, "xml"); transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8"); transformer.setOutputProperty(OutputKeys.VERSION, "1.0"); transformer.setOutputProperty(OutputKeys.INDENT, "yes"); transformer.transform(new DOMSource(oConfigurationDocument), new StreamResult(System.out)); } catch (TransformerException e) { _logger.error("Error while transforming document", e); throw new ConfigurationException(SystemErrors.ERROR_CONFIG_WRITE); } catch (Exception e) { _logger.error("Internal error during write of configuration", e); throw new ConfigurationException(SystemErrors.ERROR_INTERNAL); } }
From source file:com.hangum.tadpole.engine.sql.util.export.XMLExporter.java
/** * make content file//from w w w . ja va 2s . c o m * * @param tableName * @param rsDAO * @return * @throws Exception */ public static String makeContentFile(String tableName, QueryExecuteResultDTO rsDAO) throws Exception { String strTmpDir = PublicTadpoleDefine.TEMP_DIR + tableName + System.currentTimeMillis() + PublicTadpoleDefine.DIR_SEPARATOR; String strFile = tableName + ".xml"; String strFullPath = strTmpDir + strFile; final StringWriter stWriter = new StringWriter(); final List<Map<Integer, Object>> dataList = rsDAO.getDataList().getData(); DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder builder = factory.newDocumentBuilder(); final Document doc = builder.newDocument(); final Element results = doc.createElement(tableName); doc.appendChild(results); Map<Integer, String> mapLabelName = rsDAO.getColumnLabelName(); for (int i = 0; i < dataList.size(); i++) { Map<Integer, Object> mapColumns = dataList.get(i); Element row = doc.createElement("Row"); results.appendChild(row); for (int j = 1; j < mapColumns.size(); j++) { String columnName = mapLabelName.get(j); String strValue = mapColumns.get(j) == null ? "" : "" + mapColumns.get(j); Element node = doc.createElement(columnName); node.appendChild(doc.createTextNode(strValue)); row.appendChild(node); } } DOMSource domSource = new DOMSource(doc); TransformerFactory tf = TransformerFactory.newInstance(); tf.setAttribute("indent-number", 4); Transformer transformer = tf.newTransformer(); transformer.setOutputProperty(OutputKeys.INDENT, "yes"); transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes"); transformer.setOutputProperty(OutputKeys.METHOD, "xml"); transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");//"ISO-8859-1"); StreamResult sr = new StreamResult(stWriter); transformer.transform(domSource, sr); FileUtils.writeStringToFile(new File(strFullPath), stWriter.toString(), true); return strFullPath; }
From source file:com.c4om.utils.xmlutils.JavaXMLUtils.java
/** * Method that converts a W3C {@link Document} object to a String * @param document the document to convert * @param indent whether lines must be indented or not * @param omitDeclaration whether the XML declaration should be omitted or not. * @param encoding the encoding placed at the XML declaration. Be carefully: Specifying here an encoding only takes effect at the XML declaration. If you are going to write the string to an output stream (e.g. to a file), you must also take care of the encoding there, for example, by means of {@link org.apache.commons.io.output.XmlStreamWriter}. * @return the {@link String} representation of the document * @throws TransformerException if there are problems during the conversion *///from w ww . j a v a2 s. co m public static String convertW3CDocumentToString(Document document, boolean indent, boolean omitDeclaration, String encoding) throws TransformerException { TransformerFactory tf = TransformerFactory.newInstance(); Transformer transformer = tf.newTransformer(); transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, omitDeclaration ? "yes" : "no"); transformer.setOutputProperty(OutputKeys.INDENT, indent ? "yes" : "no"); if (encoding != null) { transformer.setOutputProperty(OutputKeys.ENCODING, encoding); } StringWriter writer = new StringWriter(); transformer.transform(new DOMSource(document), new StreamResult(writer)); String output = writer.getBuffer().toString(); return output; }
From source file:com.aurel.track.lucene.util.openOffice.OOIndexer.java
/** * Get the string content of an xml file *///from ww w . j a v a 2s . c o m public String parseXML(File file) { Document document = null; DocumentBuilderFactory documentBuilderfactory = DocumentBuilderFactory.newInstance(); DocumentBuilder builder = null; try { builder = documentBuilderfactory.newDocumentBuilder(); } catch (ParserConfigurationException e) { LOGGER.info("Building the document builder from factory failed with " + e.getMessage()); LOGGER.debug(ExceptionUtils.getStackTrace(e)); return null; } try { document = builder.parse(file); } catch (SAXException e) { LOGGER.info("Parsing the XML document " + file.getPath() + " failed with " + e.getMessage()); LOGGER.debug(ExceptionUtils.getStackTrace(e)); } catch (IOException e) { LOGGER.info("Reading the XML document " + file.getPath() + " failed with " + e.getMessage()); LOGGER.debug(ExceptionUtils.getStackTrace(e)); } if (document == null) { return null; } StringWriter result = new StringWriter(); Transformer transformer = null; try { TransformerFactory transformerFactory = TransformerFactory.newInstance(); transformer = transformerFactory.newTransformer(); transformer.setOutputProperty(OutputKeys.INDENT, "yes"); transformer.setOutputProperty(OutputKeys.METHOD, "xml"); transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8"); transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2"); } catch (TransformerConfigurationException e) { LOGGER.warn( "Creating the transformer failed with TransformerConfigurationException: " + e.getMessage()); LOGGER.debug(ExceptionUtils.getStackTrace(e)); return null; } try { transformer.transform(new DOMSource(document), new StreamResult(result)); } catch (TransformerException e) { LOGGER.warn("Transform failed with TransformerException: " + e.getMessage()); LOGGER.debug(ExceptionUtils.getStackTrace(e)); } return result.getBuffer().toString(); }
From source file:XMLUtils.java
public static void writeTo(Source src, OutputStream os, int indent, String charset, String omitXmlDecl) { Transformer it;// www .ja va 2s.c o m try { //charset = "utf-8"; it = newTransformer(); it.setOutputProperty(OutputKeys.METHOD, "xml"); if (indent > -1) { it.setOutputProperty(OutputKeys.INDENT, "yes"); it.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", Integer.toString(indent)); } it.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, omitXmlDecl); it.setOutputProperty(OutputKeys.ENCODING, charset); it.transform(src, new StreamResult(os)); } catch (TransformerException e) { throw new RuntimeException("Failed to configure TRaX", e); } }
From source file:com.alfaariss.oa.util.configuration.handler.file.FileConfigurationHandler.java
/** * Save the configuration to the file.// w ww .j ava 2 s . c om * @see IConfigurationHandler#saveConfiguration(org.w3c.dom.Document) */ public void saveConfiguration(Document oConfigurationDocument) throws ConfigurationException { OutputStream os = null; try { os = new FileOutputStream(_fConfig); //create output format which uses new lines and tabs Transformer transformer = TransformerFactory.newInstance().newTransformer(); transformer.setOutputProperty(OutputKeys.METHOD, "xml"); transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8"); transformer.setOutputProperty(OutputKeys.VERSION, "1.0"); transformer.setOutputProperty(OutputKeys.INDENT, "yes"); transformer.transform(new DOMSource(oConfigurationDocument), new StreamResult(os)); } catch (FileNotFoundException e) { _logger.error("Error writing configuration, file not found", e); throw new ConfigurationException(SystemErrors.ERROR_RESOURCE_CONNECT); } catch (TransformerException e) { _logger.error("Error while transforming document", e); throw new ConfigurationException(SystemErrors.ERROR_CONFIG_WRITE); } finally { try { if (os != null) os.close(); } catch (IOException e) { _logger.debug("Error closing configuration outputstream", e); } } }
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 w w . j a v a 2 s. c o 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:com.stratelia.webactiv.util.XMLConfigurationStore.java
@Override public void serialize() throws FileNotFoundException, IOException { FileOutputStream out = new FileOutputStream(new File(configFileName)); StreamResult streamResult = new StreamResult(out); TransformerFactory tf = TransformerFactory.newInstance(); Transformer serializer;// w ww . j ava2 s .c o m try { serializer = tf.newTransformer(); serializer.setOutputProperty(OutputKeys.ENCODING, CharEncoding.UTF_8); serializer.setOutputProperty(OutputKeys.INDENT, "yes"); serializer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "no"); DOMSource domSource = new DOMSource(xmlConfigDOMDoc); serializer.transform(domSource, streamResult); } catch (TransformerException ex) { Logger.getLogger(XMLConfigurationStore.class.getName()).log(Level.SEVERE, null, ex); } finally { IOUtils.closeQuietly(out); } }
From source file:eu.scidipes.toolkits.palibrary.utils.XMLUtils.java
private static String nodeToString(final Node doc, final Properties outputProperties) { try {//w w w.jav a2 s . com final Transformer transformer = transformerFactory.newTransformer(); outputProperties.put(OutputKeys.METHOD, "xml"); outputProperties.put(OutputKeys.ENCODING, "UTF-8"); transformer.setOutputProperties(outputProperties); final StringWriter writer = new StringWriter(); transformer.transform(new DOMSource(doc), new StreamResult(writer)); return writer.getBuffer().toString(); } catch (final TransformerException e) { LOG.error(e.getMessage(), e); } return ""; }