/** * Default constructor. * * @throws BuildException */ public void execute() throws BuildException { log("Torque - JDBCToXMLSchema starting"); log("Your DB settings are:"); log("driver : " + dbDriver); log("URL : " + dbUrl); log("user : "******"password : "******"schema : " + dbSchema); DocumentTypeImpl docType = new DocumentTypeImpl(null, "database", null, "database.dtd"); doc = new DocumentImpl(docType); doc.appendChild(doc.createComment(" Autogenerated by KualiTorqueJDBCTransformTask! ")); try { generateXML(); log(xmlSchema); OutputFormat of = new OutputFormat(Method.XML, null, true); of.setLineWidth(120); xmlSerializer = new XMLSerializer(new PrintWriter(new FileOutputStream(xmlSchema)), of); xmlSerializer.serialize(doc); } catch (Exception e) { throw new BuildException(e); } log("Torque - JDBCToXMLSchema finished"); }
/** * store loaded data to xml file * * @throws SearchException */ protected final synchronized void store() throws SearchException { // Collection.Key[] keys=collections.keys(); Iterator<Key> it = collections.keyIterator(); Key k; while (it.hasNext()) { k = it.next(); Element collEl = getCollectionElement(k.getString()); SearchCollection sc = getCollectionByName(k.getString()); setAttributes(collEl, sc); } OutputFormat format = new OutputFormat(doc, null, true); format.setLineSeparator("\r\n"); format.setLineWidth(72); OutputStream os = null; try { XMLSerializer serializer = new XMLSerializer( os = engine.getIOUtil().toBufferedOutputStream(searchFile.getOutputStream()), format); serializer.serialize(doc.getDocumentElement()); } catch (IOException e) { throw new SearchException(e); } finally { engine.getIOUtil().closeSilent(os); } }
private void logToSystemOut(SOAPMessageContext smc) { boolean direction = ((Boolean) smc.get(javax.xml.ws.handler.MessageContext.MESSAGE_OUTBOUND_PROPERTY)) .booleanValue(); String directionStr = direction ? "\n---------Outgoing SOAP message---------" : "\n---------Incoming SOAP message---------"; SOAPMessage message = smc.getMessage(); try { // XML pretty print Document doc = toDocument(message); ByteArrayOutputStream stream = new ByteArrayOutputStream(); OutputFormat format = new OutputFormat(doc); format.setIndenting(true); XMLSerializer serializer = new XMLSerializer(stream, format); serializer.serialize(doc); logger.info( directionStr + "\n" + stream.toString() + "----------End of SOAP message----------\n"); } catch (Exception e) { logger.info( directionStr + "\n Exception was thrown \n----------End of SOAP message----------\n"); } }
public static String printXML(Document doc, OutputFormat outFormat) { StringWriter strWriter = new StringWriter(); XMLSerializer serializer = new XMLSerializer(strWriter, outFormat); try { serializer.serialize(doc); strWriter.close(); } catch (IOException e) { return ""; } return strWriter.toString(); }
public void write(String filename) { if (!filename.endsWith(".xml")) filename += ".xml"; log.info("write vrp: " + filename); XMLConf xmlConfig = new XMLConf(); xmlConfig.setFileName(filename); xmlConfig.setRootElementName("problem"); xmlConfig.setAttributeSplittingDisabled(true); xmlConfig.setDelimiterParsingDisabled(true); writeProblemType(xmlConfig); writeVehiclesAndTheirTypes(xmlConfig); // might be sorted? List<Job> jobs = new ArrayList<Job>(); jobs.addAll(vrp.getJobs().values()); for (VehicleRoute r : vrp.getInitialVehicleRoutes()) { jobs.addAll(r.getTourActivities().getJobs()); } writeServices(xmlConfig, jobs); writeShipments(xmlConfig, jobs); writeInitialRoutes(xmlConfig); writeSolutions(xmlConfig); OutputFormat format = new OutputFormat(); format.setIndenting(true); format.setIndent(5); try { Document document = xmlConfig.createDoc(); Element element = document.getDocumentElement(); element.setAttribute("xmlns", "http://www.w3schools.com"); element.setAttribute("xmlns:xsi", "http://www.w3.org/2001/XMLSchema-instance"); element.setAttribute("xsi:schemaLocation", "http://www.w3schools.com vrp_xml_schema.xsd"); } catch (ConfigurationException e) { logger.error("Exception:", e); e.printStackTrace(); System.exit(1); } try { Writer out = new FileWriter(filename); XMLSerializer serializer = new XMLSerializer(out, format); serializer.serialize(xmlConfig.getDocument()); out.close(); } catch (IOException e) { logger.error("Exception:", e); e.printStackTrace(); System.exit(1); } }
public static void prettyPrintXML(InputStream docStream, OutputStream out) throws ParserConfigurationException, SAXException, IOException { DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder(); Document doc = builder.parse(docStream); OutputFormat fmt = new OutputFormat(doc); fmt.setOmitXMLDeclaration(true); fmt.setLineWidth(72); fmt.setIndenting(true); fmt.setIndent(2); XMLSerializer ser = new XMLSerializer(out, fmt); ser.serialize(doc); }
/** * XMLを標準出力する。 * * @param my_doc XMLの Document Node 。 * @param sortflag ソートするか否か。 */ public static void output(Document my_doc, boolean sortflag, UDF_Env env) { try { if (sortflag) com.udfv.util.UDF_XML.sortDocumentbyEnv(my_doc, env); OutputFormat format = new OutputFormat(my_doc, "UTF-8", true); format.setLineWidth(0); OutputStreamWriter osw = new OutputStreamWriter(System.out, "UTF-8"); XMLSerializer serial = new XMLSerializer(osw, format); serial.serialize(my_doc.getDocumentElement()); } catch (Exception ex) { ex.printStackTrace(); } }
public String getXml() throws IOException { try { ByteArrayOutputStream bos = new ByteArrayOutputStream(); OutputFormat format = new OutputFormat(); format.setLineWidth(200); format.setIndenting(true); format.setIndent(2); XMLSerializer serializer = new XMLSerializer(bos, format); serializer.serialize((Element) this.node); return new String(bos.toByteArray(), "UTF-8"); } catch (Exception e) { e.printStackTrace(); } return null; }
public String format(String unformattedXml) throws EventFormatterConfigurationException { try { final Document document = parseXmlFile(unformattedXml); OutputFormat format = new OutputFormat(document); format.setLineWidth(65); format.setIndenting(true); format.setIndent(2); Writer out = new StringWriter(); XMLSerializer serializer = new XMLSerializer(out, format); serializer.serialize(document); return out.toString(); } catch (IOException e) { throw new EventFormatterConfigurationException(e); } }
/** * Serielizes a document to a file. The file is being encoded in accordance with the value given * in the xml declaration. If no encoding is found then "utf-8" is used. * * @throws IOException */ public static File serializeDocToFile(Document doc, String outputFilePath) throws IOException { File outputFile = new File(outputFilePath); if (outputFile.exists()) { // just in case the user runs DTBSM with the same output URI outputFile.delete(); } FileOutputStream fos = null; OutputStreamWriter osWriter = null; try { String encoding = doc.getXmlEncoding(); if (encoding == null) { encoding = DtbSerializer.DEFAULT_ENCODING; } boolean prettyIndenting = true; OutputFormat of = new OutputFormat(doc, encoding, prettyIndenting); XMLSerializer ser = new XMLSerializer(of); // Create a new (empty) file on disk in the target directory fos = new FileOutputStream(outputFile); if (encoding != null) { osWriter = new OutputStreamWriter(fos, encoding); ser.setOutputCharStream(osWriter); } else { osWriter = new OutputStreamWriter(fos); ser.setOutputCharStream(osWriter); } // Serialize our document into the output stream held by the xml-serializer ser.serialize(doc); } catch (IOException e) { throw e; } finally { try { fos.close(); osWriter.close(); } catch (IOException e) { throw e; } } return outputFile; }
/** * @param path_ret where the file will be saved * @param a getting the information of current status of the editor * @param cnc_a getting the information of current status of the editor * @throws ParserConfigurationException * @throws IOException */ public void save(String tempPath, counts a, connections cnc_a) throws ParserConfigurationException, IOException { try { DocumentBuilderFactory dbf = DocumentBuilderFactoryImpl.newInstance(); // get an instance of builder DocumentBuilder db = dbf.newDocumentBuilder(); // create an instance of DOM Document dom = db.newDocument(); Element el_root = dom.createElement("circuit"); dom.appendChild(el_root); // Root of the components Element cmp_root = dom.createElement("components"); el_root.appendChild(cmp_root); for (component x : a.getComponent_list()) { Element cmpEle = this.createCmpEle(x, dom); cmp_root.appendChild(cmpEle); } // Root of the components Element wire_root = dom.createElement("wires"); el_root.appendChild(wire_root); for (line x : cnc_a.getLine_logs()) { Element wireEle = null; if (x.getId() > 0) { wireEle = this.createWireEle(x, dom); wire_root.appendChild(wireEle); } } OutputFormat format = new OutputFormat(); XMLSerializer serializer = new XMLSerializer(new FileOutputStream(new File(tempPath)), format); serializer.serialize(dom); this.changeTitle(new File(tempPath).getName()); this.setSaved(true); this.setPath(tempPath); taskbar.setText("File is saved successfully."); } catch (FileNotFoundException ex) { Logger.getLogger(Pad_Draw.class.getName()).log(Level.SEVERE, null, ex); } }
private void processXml(Node operation) throws ParserConfigurationException, TransformerConfigurationException { List<Node> targets = getChildNodes(operation, "target"); List<Node> appendOpNodes = getChildNodes(operation, "append"); List<Node> setOpNodes = getChildNodes(operation, "set"); List<Node> replaceOpNodes = getChildNodes(operation, "replace"); List<Node> removeOpNodes = getChildNodes(operation, "remove"); if (targets.isEmpty()) { return; } for (int t = 0; t < targets.size(); t++) { File target = new File(absolutePath(targets.get(t).getTextContent())); if (!target.exists()) { Utils.onError(new Error.FileNotFound(target.getPath())); return; } DocumentBuilder db = DocumentBuilderFactory.newInstance().newDocumentBuilder(); Document doc = null; try { doc = db.parse(target); } catch (Exception ex) { Utils.onError(new Error.FileParse(target.getPath())); return; } for (int i = 0; i < removeOpNodes.size(); i++) removeXmlEntry(doc, removeOpNodes.get(i)); for (int i = 0; i < replaceOpNodes.size(); i++) replaceXmlEntry(doc, replaceOpNodes.get(i)); for (int i = 0; i < setOpNodes.size(); i++) setXmlEntry(doc, setOpNodes.get(i)); for (int i = 0; i < appendOpNodes.size(); i++) appendXmlEntry(doc, appendOpNodes.get(i)); try { OutputFormat format = new OutputFormat(doc); format.setOmitXMLDeclaration(true); format.setLineWidth(65); format.setIndenting(true); format.setIndent(4); Writer out = new FileWriter(target); XMLSerializer serializer = new XMLSerializer(out, format); serializer.serialize(doc); } catch (IOException e) { Utils.onError(new Error.WriteXmlConfig(target.getPath())); } } }
public static void dom() throws IOException { javax.xml.parsers.DocumentBuilder b; try { javax.xml.parsers.DocumentBuilderFactory f = javax.xml.parsers.DocumentBuilderFactory.newInstance(); f.setNamespaceAware(true); // !!! b = f.newDocumentBuilder(); } catch (javax.xml.parsers.ParserConfigurationException e) { e.printStackTrace(); throw new RuntimeException("parser configuration exception"); } org.w3c.dom.DOMImplementation domImpl = b.getDOMImplementation(); // DOM works similar to DOM4J org.w3c.dom.Document doc = domImpl.createDocument("", "todo:todo", null); System.out.println("DOM: "); XMLSerializer serializer = new XMLSerializer(System.out, new OutputFormat(doc)); serializer.serialize(doc); System.out.println(); }
/** * XMLをファイルに出力する。 * * @param my_doc XMLの Document Node 。 * @param os 出力先のストリーム。 * @param sortflag ソートするか否か。 */ public static void output(Document my_doc, OutputStream os, boolean sortflag, UDF_Env env) { if (sortflag) { try { com.udfv.util.UDF_XML.sortDocumentbyEnv(my_doc, env); } catch (Exception e1) { e1.printStackTrace(); } } try { OutputFormat format = new OutputFormat(my_doc, "UTF-8", true); format.setLineWidth(0); // Writer out = new OutputStreamWriter(new FileOutputStream(file), "UTF-8"); Writer out = new OutputStreamWriter(os, "UTF-8"); XMLSerializer serial = new XMLSerializer(out, format); serial.serialize(my_doc.getDocumentElement()); out.close(); } catch (Exception e2) { e2.printStackTrace(); } }
/** * エラーリストを XMLとして出力する。 * * @param el エラーリスト */ public static void outputError(UDF_ErrorList el) { Document doc = UDF_Util.genDocument(); Element root = doc.createElement("udf-error"); for (int i = 0; i < el.getSize(); i++) { el.getError(i).toXML(doc, root); } doc.appendChild(root); try { OutputFormat format = new OutputFormat(doc, "UTF-8", true); format.setLineWidth(0); OutputStreamWriter osw = new OutputStreamWriter(System.out, "UTF-8"); XMLSerializer serial = new XMLSerializer(osw, format); serial.serialize(doc.getDocumentElement()); } catch (Exception e) { e.printStackTrace(); } }
public static void main(String[] args) throws ParserConfigurationException, IOException, SAXException { String xmlUri = "/home/miguel/Scaricati/there.is.only.xul"; DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder(); Document document = documentBuilder.parse(xmlUri); System.out.println("*** Input XML ***"); XMLSerializer serializer = new XMLSerializer(System.out, new OutputFormat()); // As a DOM Serializer serializer.asDOMSerializer(); serializer.serialize(document); System.out.println(""); System.out.println("*** Output RDF ***"); Graph rdfGraph = DomEncoder.encode(document); Model model = ModelFactory.createModelForGraph(rdfGraph); model.write(System.out, "N3"); // model.write(System.out); }
/** * Formats a given unformatted XML string * * @param xml * @return A CDATA wrapped, formatted XML String */ public String formatXML(String xml) { try { // create the factory DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance(); docFactory.setIgnoringComments(true); docFactory.setNamespaceAware(true); docFactory.setExpandEntityReferences(false); SecurityManager securityManager = new SecurityManager(); securityManager.setEntityExpansionLimit(ENTITY_EXPANSION_LIMIT); docFactory.setAttribute(SECURITY_MANAGER_PROPERTY, securityManager); DocumentBuilder docBuilder; Document xmlDoc; // now use the factory to create the document builder docFactory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true); docBuilder = docFactory.newDocumentBuilder(); docBuilder.setEntityResolver(new CarbonEntityResolver()); xmlDoc = docBuilder.parse(new ByteArrayInputStream(xml.getBytes(Charsets.UTF_8))); OutputFormat format = new OutputFormat(xmlDoc); format.setLineWidth(0); format.setIndenting(true); format.setIndent(2); ByteArrayOutputStream baos = new ByteArrayOutputStream(); XMLSerializer serializer = new XMLSerializer(baos, format); serializer.serialize(xmlDoc); xml = baos.toString("UTF-8"); } catch (ParserConfigurationException pce) { throw new IllegalArgumentException("Failed to setup repository: "); } catch (Exception e) { log.error(e); } return "<![CDATA[" + xml + "]]>"; }
public static void domWithURI() throws IOException { javax.xml.parsers.DocumentBuilder b; try { javax.xml.parsers.DocumentBuilderFactory f = javax.xml.parsers.DocumentBuilderFactory.newInstance(); f.setNamespaceAware(true); b = f.newDocumentBuilder(); } catch (javax.xml.parsers.ParserConfigurationException e) { e.printStackTrace(); throw new RuntimeException("parser configuration exception"); } org.w3c.dom.DOMImplementation domImpl = b.getDOMImplementation(); // DOM works similar to DOM4J; however you must provide an URI if a name has a prefix // passing in the the URI with createDocument makes no difference. org.w3c.dom.Document doc = domImpl.createDocument("", "todo:todo", null); // DOM does not add the declaration by default: use plain attribut doc.getDocumentElement().setAttribute("xmlns:todo", "http://www.example.com"); System.out.println("DOM: "); XMLSerializer serializer = new XMLSerializer(System.out, new OutputFormat(doc)); serializer.serialize(doc); System.out.println(); }
private String result2XML(XFacetedResultSet resultSet, Document doc2, long queryTime) { try { } catch (Exception ex) { System.out.println(ex); } try { Node node = null; NamedNodeMap map = null; node = doc2.getElementsByTagName("action").item(0); map = node.getAttributes(); DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); DocumentBuilder db = dbf.newDocumentBuilder(); Document doc = db.newDocument(); Element root = doc.createElement("result"); // Create Root Element if (map.getNamedItem("type").getNodeValue().equals("all") || map.getNamedItem("type").getNodeValue().equals("instanceList")) { Element item = doc.createElement("instanceList"); // Create // element item.setAttribute("count", Integer.toString(resultSet.getLength())); item.setAttribute("time", Long.toString(queryTime)); int start = new Integer(map.getNamedItem("start").getNodeValue()).intValue(); int count = new Integer(map.getNamedItem("count").getNodeValue()).intValue(); int end = start + count; if (end > resultSet.getLength()) end = resultSet.getLength(); for (int i = start; i < end; i++) { SchemaObjectInfo result = resultSet.getResult(i); Element subitem = doc.createElement("instance"); try { subitem.setAttribute("name", java.net.URLDecoder.decode(result.getLabel())); } catch (Exception e) { subitem.setAttribute("name", result.getLabel()); } subitem.setAttribute("uri", result.getURI()); // subitem.setAttribute("snippet", // result.getTextDescription()); try { subitem.setAttribute("snippet", java.net.URLDecoder.decode(resultSet.getSnippet(i))); } catch (Exception e) { subitem.setAttribute("snippet", resultSet.getSnippet(i)); } item.appendChild(subitem); // for debug // System.out.println("result "+i+": // "+resultSet.getResult(i).getLabel()); // System.out.println("//score:"+resultSet.getScore(i)); // System.out.println("//uri:"+resultSet.getResult(i).getURI()); // System.out.println("//id:"+resultSet.getDocID(i)); // System.out.println("//text:"+resultSet.getResult(i).getTextDescription()); // System.out.println("//text:"+resultSet.getSnippet(i)); // for debug } root.appendChild(item); // atach element to Root element } if (map.getNamedItem("type").getNodeValue().equals("all") || map.getNamedItem("type").getNodeValue().equals("conceptList")) { Element item = doc.createElement("conceptList"); // Create // element int start = new Integer(map.getNamedItem("start").getNodeValue()).intValue(); int count = new Integer(map.getNamedItem("count").getNodeValue()).intValue(); int end = start + count; Facet[] facets = resultSet.getCategoryFacets(); if (end > facets.length) end = facets.length; item.setAttribute("count", Integer.toString(facets.length)); for (int i = start; i < end; i++) { Facet result = facets[i]; Element subitem = doc.createElement("concept"); subitem.setAttribute("name", nomalizeLabel(result.getInfo().getLabel())); subitem.setAttribute("uri", result.getInfo().getURI()); subitem.setAttribute("count", String.valueOf(result.getCount())); item.appendChild(subitem); } root.appendChild(item); // atach element to Root element } if (map.getNamedItem("type").getNodeValue().equals("all") || map.getNamedItem("type").getNodeValue().equals("relationList")) { Element item = doc.createElement("relationList"); // Create // element int start = new Integer(map.getNamedItem("start").getNodeValue()).intValue(); int count = new Integer(map.getNamedItem("count").getNodeValue()).intValue(); int end = start + count; Facet[] facets = resultSet.getRelationFacets(); if (end > facets.length) end = facets.length; item.setAttribute("count", Integer.toString(facets.length)); for (int i = start; i < end; i++) { Facet result = facets[i]; Element subitem = doc.createElement("relation"); subitem.setAttribute("name", result.getInfo().getLabel()); subitem.setAttribute("uri", result.getInfo().getURI()); subitem.setAttribute("count", String.valueOf(result.getCount())); if (result.isInverseRelation()) subitem.setAttribute("inverse", "1"); else subitem.setAttribute("inverse", "0"); item.appendChild(subitem); } root.appendChild(item); // atach element to Root element } doc.appendChild(root); // Add Root to Document OutputFormat format = new OutputFormat(doc); // Serialize DOM StringWriter stringOut = new StringWriter(); // Writer will be a // String XMLSerializer serial = new XMLSerializer(stringOut, format); serial.asDOMSerializer(); // As a DOM Serializer serial.serialize(doc.getDocumentElement()); // System.out.println( "STRXML = " + stringOut.toString() ); //Spit // out DOM as a String return stringOut.toString(); } catch (Exception ex) { ex.printStackTrace(); } return null; }