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.protempa.dest.xml.XmlQueryResultsHandler.java
private void printDocument(Document doc) throws IOException, TransformerException { TransformerFactory tf = TransformerFactory.newInstance(); Transformer transformer = tf.newTransformer(); transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes"); transformer.setOutputProperty(OutputKeys.METHOD, "xml"); transformer.setOutputProperty(OutputKeys.INDENT, "yes"); transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8"); transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4"); transformer.transform(new DOMSource(doc), new StreamResult(this.out)); this.out.flush(); }
From source file:org.rdswicthboard.utils.rdf.oai.App.java
public static void main(String[] args) { // create the command line parser CommandLineParser parser = new DefaultParser(); // create the Options Options options = new Options(); options.addOption("i", PROPERTY_INPUT_FILE, true, "input RDF file"); options.addOption("o", PROPERTY_OUTPUT_FILE, true, "output OAI-PMH XML file (default is " + DEFAULT_OUTPUT_FILE + ")"); options.addOption("c", PROPERTY_CONFIG_FILE, true, "configuration file (" + PROPERTIES_FILE + ")"); options.addOption("s", PROPERTY_SET_SPEC, true, "set spec value (default is " + DEFAULT_SET_SPEC + ")"); options.addOption("I", PROPERTY_INPUT_ENCODING, true, "input file encoding (default is " + DEFAULT_ENCODING + ")"); options.addOption("O", PROPERTY_OUTPUT_ENCODING, true, "output file encoding (default is " + DEFAULT_ENCODING + ")"); options.addOption("f", PROPERTY_FORMAT_OUTPUT, false, "format output encoding"); options.addOption("h", PROPERTY_HELP, false, "print this message"); try {/* w ww .java2 s . c o m*/ // parse the command line arguments CommandLine line = parser.parse(options, args); if (line.hasOption(PROPERTY_HELP)) { HelpFormatter formatter = new HelpFormatter(); formatter.printHelp("java -jar rdf2oai-[verion].jar [PARAMETERS] [INPUT FILE] [OUTPUT FILE]", options); System.exit(0); } // variables to store program properties CompositeConfiguration config = new CompositeConfiguration(); config.setProperty(PROPERTY_OUTPUT_FILE, DEFAULT_OUTPUT_FILE); config.setProperty(PROPERTY_INPUT_ENCODING, DEFAULT_ENCODING); config.setProperty(PROPERTY_OUTPUT_ENCODING, DEFAULT_ENCODING); config.setProperty(PROPERTY_SET_SPEC, DEFAULT_SET_SPEC); config.setProperty(PROPERTY_FORMAT_OUTPUT, DEFAULT_FORMAT_OUTPUT); // check if arguments has input file properties if (line.hasOption(PROPERTY_CONFIG_FILE)) { // if it does, load the specified configuration file Path defaultConfig = Paths.get(line.getOptionValue(PROPERTY_CONFIG_FILE)); if (Files.isRegularFile(defaultConfig) && Files.isReadable(defaultConfig)) { config.addConfiguration(new PropertiesConfiguration(defaultConfig.toFile())); } else throw new Exception("Invalid configuration file: " + defaultConfig.toString()); } else { // if it not, try to load default configurationfile Path defaultConfig = Paths.get(PROPERTIES_FILE); if (Files.isRegularFile(defaultConfig) && Files.isReadable(defaultConfig)) { config.addConfiguration(new PropertiesConfiguration(defaultConfig.toFile())); } } // check if arguments has input file if (line.hasOption(PROPERTY_INPUT_FILE)) config.setProperty(PROPERTY_INPUT_FILE, line.getOptionValue(PROPERTY_INPUT_FILE)); // check if arguments has output file if (line.hasOption(PROPERTY_OUTPUT_FILE)) config.setProperty(PROPERTY_OUTPUT_FILE, line.getOptionValue(PROPERTY_OUTPUT_FILE)); // check if arguments has set spec name if (line.hasOption(PROPERTY_SET_SPEC)) config.setProperty(PROPERTY_SET_SPEC, line.getOptionValue(PROPERTY_SET_SPEC)); // check if arguments has input encoding if (line.hasOption(PROPERTY_INPUT_ENCODING)) config.setProperty(PROPERTY_INPUT_ENCODING, line.getOptionValue(PROPERTY_INPUT_ENCODING)); // check if arguments has output encoding if (line.hasOption(PROPERTY_OUTPUT_ENCODING)) config.setProperty(PROPERTY_OUTPUT_ENCODING, line.getOptionValue(PROPERTY_OUTPUT_ENCODING)); // check if arguments has output encoding if (line.hasOption(PROPERTY_FORMAT_OUTPUT)) config.setProperty(PROPERTY_FORMAT_OUTPUT, "yes"); // check if arguments has input file without a key if (line.getArgs().length > 0) { config.setProperty(PROPERTY_INPUT_FILE, line.getArgs()[0]); // check if arguments has output file without a key if (line.getArgs().length > 1) { config.setProperty(PROPERTY_OUTPUT_FILE, line.getArgs()[1]); // check if there is too many arguments if (line.getArgs().length > 2) throw new Exception("Too many arguments"); } } // The program has default output file, but input file must be presented if (!config.containsKey(PROPERTY_INPUT_FILE)) throw new Exception("Please specify input file"); // extract input file String inputFile = config.getString(PROPERTY_INPUT_FILE); // extract output file String outputFile = config.getString(PROPERTY_OUTPUT_FILE); // extract set spec String setSpecName = config.getString(PROPERTY_SET_SPEC); // extract encoding String inputEncoding = config.getString(PROPERTY_INPUT_ENCODING); String outputEncoding = config.getString(PROPERTY_OUTPUT_ENCODING); boolean formatOutput = config.getBoolean(PROPERTY_FORMAT_OUTPUT); // test if source is an regular file and it is readable Path source = Paths.get(inputFile); if (!Files.isRegularFile(source)) throw new Exception("The input file: " + source.toString() + " is not an regular file"); if (!Files.isReadable(source)) throw new Exception("The input file: " + source.toString() + " is not readable"); Path target = Paths.get(outputFile); if (Files.exists(target)) { if (!Files.isRegularFile(target)) throw new Exception("The output file: " + target.toString() + " is not an regular file"); if (!Files.isWritable(target)) throw new Exception("The output file: " + target.toString() + " is not writable"); } // create and setup document builder factory DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); factory.setNamespaceAware(true); // create new document builder DocumentBuilder builder = factory.newDocumentBuilder(); // create oai document Document oai = builder.newDocument(); // set document version oai.setXmlVersion("1.0"); oai.setXmlStandalone(true); // create root OAI-PMH element Element oaiPmh = oai.createElement("OAI-PMH"); // set document namespaces oaiPmh.setAttribute("xmlns", "http://www.openarchives.org/OAI/2.0/"); oaiPmh.setAttributeNS("http://www.w3.org/2000/xmlns/", "xmlns:xsi", "http://www.w3.org/2001/XMLSchema-instance"); oaiPmh.setAttribute("xsi:schemaLocation", "http://www.openarchives.org/OAI/2.0/ http://www.openarchives.org/OAI/2.0/OAI-PMH.xsd"); // append root node oai.appendChild(oaiPmh); // create responseDate element Element responseDate = oai.createElement("responseDate"); // create simple date format DateFormat dateFormat = new SimpleDateFormat(TIME_FORMAT); // generate date String date = dateFormat.format(new Date()); // set current date and time responseDate.setTextContent(date); oaiPmh.appendChild(responseDate); Element listRecords = oai.createElement("ListRecords"); oaiPmh.appendChild(listRecords); // create xpath factory XPathFactory xPathfactory = XPathFactory.newInstance(); // create namespace context NamespaceContext namespaceContext = new NamespaceContext() { public String getNamespaceURI(String prefix) { if (prefix.equals("rdf")) return RDF_NAMESPACE; else if (prefix.equals("rns")) return RNF_NAMESPACE; else return null; } @Override public Iterator<?> getPrefixes(String val) { throw new IllegalAccessError("Not implemented!"); } @Override public String getPrefix(String uri) { throw new IllegalAccessError("Not implemented!"); } }; // create xpath object XPath xpath = xPathfactory.newXPath(); // set namespace contex xpath.setNamespaceContext(namespaceContext); // create XPath expressions XPathExpression idExpr = xpath.compile("/rdf:RDF/rns:Researcher/@rdf:about"); XPathExpression emptyExpr = xpath.compile("//text()[normalize-space(.) = '']"); // create RegEx patterns Pattern pattern = Pattern.compile( "<\\?xml\\s+version=\"[\\d\\.]+\"\\s*\\?>\\s*<\\s*rdf:RDF[^>]*>[\\s\\S]*?<\\s*\\/\\s*rdf:RDF\\s*>"); // read file into a string String content = new String(Files.readAllBytes(source), inputEncoding); Matcher matcher = pattern.matcher(content); // process all records while (matcher.find()) { // convert string to input stream ByteArrayInputStream input = new ByteArrayInputStream( matcher.group().getBytes(StandardCharsets.UTF_8.toString())); // parse the xml document Document doc = builder.parse(input); // remove all spaces NodeList emptyNodes = (NodeList) emptyExpr.evaluate(doc, XPathConstants.NODESET); // Remove each empty text node from document. for (int i = 0; i < emptyNodes.getLength(); i++) { Node emptyTextNode = emptyNodes.item(i); emptyTextNode.getParentNode().removeChild(emptyTextNode); } // obtain researcher id String id = (String) idExpr.evaluate(doc, XPathConstants.STRING); if (StringUtils.isEmpty(id)) throw new Exception("The record identifier can not be empty"); // create record element Element record = oai.createElement("record"); listRecords.appendChild(record); // create header element Element header = oai.createElement("header"); record.appendChild(header); // create identifier element Element identifier = oai.createElement("identifier"); identifier.setTextContent(id); header.appendChild(identifier); // create datestamp element Element datestamp = oai.createElement("datestamp"); datestamp.setTextContent(date); header.appendChild(datestamp); // create set spec element if it exists if (!StringUtils.isEmpty(setSpecName)) { Element setSpec = oai.createElement("setSpec"); setSpec.setTextContent(setSpecName); header.appendChild(setSpec); } // create metadata element Element metadata = oai.createElement("metadata"); record.appendChild(metadata); // import the record metadata.appendChild(oai.importNode(doc.getDocumentElement(), true)); } // create transformer factory TransformerFactory transformerFactory = TransformerFactory.newInstance(); // create transformer Transformer transformer = transformerFactory.newTransformer(); transformer.setOutputProperty(OutputKeys.ENCODING, outputEncoding); if (formatOutput) { transformer.setOutputProperty(OutputKeys.INDENT, "yes"); transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2"); } else transformer.setOutputProperty(OutputKeys.INDENT, "no"); // create dom source DOMSource oaiSource = new DOMSource(oai); // create stream result StreamResult result = new StreamResult(target.toFile()); // stream xml to file transformer.transform(oaiSource, result); // optional stream xml to console for testing //StreamResult consoleResult = new StreamResult(System.out); //transformer.transform(oaiSource, consoleResult); } catch (Exception e) { System.err.println("Error: " + e.getMessage()); //e.printStackTrace(); System.exit(1); } }
From source file:org.roda.common.certification.ODFSignatureUtils.java
private static void writeXML(OutputStream outStream, Node node, boolean indent) throws TransformerFactoryConfigurationError, TransformerException { OutputStreamWriter osw = new OutputStreamWriter(outStream, Charset.forName(RodaConstants.DEFAULT_ENCODING)); BufferedWriter bw = new BufferedWriter(osw); TransformerFactory transformerFactory = new org.apache.xalan.processor.TransformerFactoryImpl(); Transformer serializer = transformerFactory.newTransformer(); serializer.setOutputProperty(OutputKeys.ENCODING, RodaConstants.DEFAULT_ENCODING); if (indent) { serializer.setOutputProperty(OutputKeys.INDENT, "yes"); }//from w w w . java 2 s . c o m DOMSource domSource = new DOMSource(node); StreamResult streamResult = new StreamResult(bw); serializer.transform(domSource, streamResult); IOUtils.closeQuietly(bw); IOUtils.closeQuietly(osw); }
From source file:org.roda.core.plugins.plugins.characterization.ODFSignatureUtils.java
private static void writeXML(OutputStream outStream, Node node, boolean indent) throws TransformerFactoryConfigurationError, TransformerException, IOException { OutputStreamWriter osw = new OutputStreamWriter(outStream, Charset.forName(RodaConstants.DEFAULT_ENCODING)); try (BufferedWriter bw = new BufferedWriter(osw)) { TransformerFactory transformerFactory = new org.apache.xalan.processor.TransformerFactoryImpl(); Transformer serializer = transformerFactory.newTransformer(); serializer.setOutputProperty(OutputKeys.ENCODING, RodaConstants.DEFAULT_ENCODING); if (indent) { serializer.setOutputProperty(OutputKeys.INDENT, "yes"); }//from w w w. j a v a 2 s. c om DOMSource domSource = new DOMSource(node); StreamResult streamResult = new StreamResult(bw); serializer.transform(domSource, streamResult); } }
From source file:org.sakaiproject.kernel.component.core.PersistenceUnitClassLoader.java
/** * Scans the classloader for files named META-INF/orm.xml and consolidates * them./*ww w .ja v a 2 s .com*/ * * @return A consolidated String representing all orm.xml files found. * @throws IOException * @throws SAXException */ private String scanOrmXml() throws TransformerConfigurationException, IOException, SAXException { StringWriter writer = new StringWriter(); StreamResult result = new StreamResult(writer); // SAX2.0 ContentHandler SAXTransformerFactory tf = (SAXTransformerFactory) SAXTransformerFactory.newInstance(); TransformerHandler handler = tf.newTransformerHandler(); Transformer serializer = handler.getTransformer(); serializer.setOutputProperty(OutputKeys.ENCODING, "UTF-8"); serializer.setOutputProperty(OutputKeys.INDENT, "yes"); handler.setResult(result); JpaOrmAccumulator acc = new JpaOrmAccumulator(handler); XMLReader reader = XMLReaderFactory.createXMLReader(); reader.setContentHandler(acc); for (final URL url : findXMLs(ORM_XML)) { reader.parse(new InputSource(url.openStream())); } String writerOut = writer.toString(); String out = XML_HEADER + ENTITY_MAPPINGS_START + writerOut.substring(writerOut.indexOf("<entity ")) + ENTITY_MAPPINGS_END; return out; }
From source file:org.sakaiproject.kernel.component.core.PersistenceUnitClassLoader.java
/** * Marshall/serialize a {@link Document} to an XML String. * * @param doc//from ww w . ja v a 2 s .c o m * @return * @throws TransformerException */ private String toString(Document doc) throws TransformerException { // Serialization through Transform. DOMSource domSource = new DOMSource(doc); StringWriter out = new StringWriter(); StreamResult streamResult = new StreamResult(out); TransformerFactory tf = TransformerFactory.newInstance(); Transformer serializer = tf.newTransformer(); serializer.setOutputProperty(OutputKeys.ENCODING, "UTF-8"); serializer.setOutputProperty(OutputKeys.INDENT, "yes"); serializer.transform(domSource, streamResult); return out.toString(); }
From source file:org.seasr.meandre.components.tools.io.WriteArchive.java
@Override public void initializeCallBack(ComponentContextProperties ccp) throws Exception { super.initializeCallBack(ccp); defaultFolder = getPropertyOrDieTrying(PROP_DEFAULT_FOLDER, true, false, ccp); if (defaultFolder.length() == 0) defaultFolder = ccp.getPublicResourcesDirectory(); else if (!defaultFolder.startsWith(File.separator)) defaultFolder = new File(ccp.getPublicResourcesDirectory(), defaultFolder).getAbsolutePath(); console.fine("Default folder set to: " + defaultFolder); appendTimestamp = Boolean.parseBoolean(getPropertyOrDieTrying(PROP_APPEND_TIMESTAMP, ccp)); timestampFormat = getPropertyOrDieTrying(PROP_TIMESTAMP_FORMAT, ccp); appendExtension = Boolean.parseBoolean(getPropertyOrDieTrying(PROP_APPEND_EXTENSION, ccp)); archiveFormat = getPropertyOrDieTrying(PROP_ARCHIVE_FORMAT, ccp).toLowerCase(); if (!archiveFormat.equals("zip") && !archiveFormat.equals("tar") && !archiveFormat.equals("tgz")) throw new ComponentContextException("Invalid archive format! Must be one of: zip, tar, tgz"); publicResourcesDir = new File(ccp.getPublicResourcesDirectory()).getAbsolutePath(); if (!publicResourcesDir.endsWith(File.separator)) publicResourcesDir += File.separator; outputProperties = new Properties(); outputProperties.setProperty(OutputKeys.INDENT, "yes"); outputProperties.setProperty("{http://xml.apache.org/xslt}indent-amount", "2"); outputProperties.setProperty(OutputKeys.ENCODING, "UTF-8"); }
From source file:org.servalproject.maps.indexgenerator.IndexWriter.java
public static boolean writeXmlIndex(File outputFile, ArrayList<MapInfo> mapInfoList) { // create the xml document builder factory object DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); // create the xml document builder object and get the DOMImplementation object DocumentBuilder builder = null; try {/* w w w . jav a2 s . co m*/ builder = factory.newDocumentBuilder(); } catch (javax.xml.parsers.ParserConfigurationException e) { System.err.println("ERROR: unable to build the XML data. " + e.getMessage()); return false; } DOMImplementation domImpl = builder.getDOMImplementation(); // start to build the document Document document = domImpl.createDocument(null, "maps", null); // get the root element Element rootElement = document.getDocumentElement(); // add the basic metadata Element element = document.createElement("version"); element.setTextContent(VERSION); rootElement.appendChild(element); element = document.createElement("generated"); element.setTextContent(Long.toString(System.currentTimeMillis())); rootElement.appendChild(element); element = document.createElement("author"); element.setTextContent(AUTHOR); rootElement.appendChild(element); element = document.createElement("data_source"); element.setTextContent(DATA_SOURCE); rootElement.appendChild(element); element = document.createElement("data_format"); element.setTextContent(DATA_FORMAT); rootElement.appendChild(element); element = document.createElement("data_format_info"); element.setTextContent(DATA_FORMAT_INFO); rootElement.appendChild(element); element = document.createElement("data_format_version"); element.setTextContent(DATA_FORMAT_VERSION); rootElement.appendChild(element); element = document.createElement("more_info"); element.setTextContent(MORE_INFO); rootElement.appendChild(element); // add the map file information Element mapInfoElement = document.createElement("map-info"); rootElement.appendChild(mapInfoElement); for (MapInfo info : mapInfoList) { mapInfoElement.appendChild(info.toXml(document.createElement("map"))); } // output the xml try { // create a transformer TransformerFactory transFactory = TransformerFactory.newInstance(); Transformer transformer = transFactory.newTransformer(); // set some options on the transformer transformer.setOutputProperty(OutputKeys.ENCODING, "utf-8"); transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "no"); transformer.setOutputProperty(OutputKeys.INDENT, "yes"); transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2"); // get a transformer and supporting classes StreamResult result = new StreamResult(new PrintWriter(outputFile)); DOMSource source = new DOMSource(document); // transform the internal objects into XML and print it transformer.transform(source, result); } catch (javax.xml.transform.TransformerException e) { System.err.println("ERROR: unable to write the XML data. " + e.getMessage()); return false; } catch (FileNotFoundException e) { System.err.println("ERROR: unable to write the XML data. " + e.getMessage()); return false; } return true; }
From source file:org.silverpeas.SilverpeasSettings.xml.transform.XPathTransformer.java
/** * Save the resulting DOM tree into a file. * @param xmlFile the target file./*from w ww.j a v a 2 s .c o m*/ * @param doc the DOM tree. */ public void saveDoc(String xmlFile, Document doc) { try { Transformer transformer = TransformerFactory.newInstance().newTransformer(); transformer.setOutputProperty(OutputKeys.INDENT, "yes"); transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8"); transformer.setOutputProperty(OutputKeys.VERSION, "1.0"); StreamResult result = new StreamResult(new File(xmlFile)); DOMSource source = new DOMSource(doc); transformer.transform(source, result); } catch (TransformerException ex) { Logger.getLogger(XPathTransformer.class.getName()).log(Level.SEVERE, null, ex); } }
From source file:org.soa4all.dashboard.gwt.module.wsmolite.server.WsmoLiteDataServiceImpl.java
private String getXMLString(Document doc) throws Exception { StringWriter buffer = new StringWriter(); Transformer tr = TransformerFactory.newInstance().newTransformer(); tr.setOutputProperty(OutputKeys.METHOD, "xml"); tr.setOutputProperty(OutputKeys.ENCODING, "UTF-8"); tr.transform(new DOMSource(doc), new StreamResult(buffer)); return buffer.getBuffer().toString(); }