List of usage examples for javax.xml.transform OutputKeys OMIT_XML_DECLARATION
String OMIT_XML_DECLARATION
To view the source code for javax.xml.transform OutputKeys OMIT_XML_DECLARATION.
Click Source Link
From source file:ca.uviccscu.lp.utils.Utils.java
public static String documentToString(Document d) throws TransformerConfigurationException, TransformerException { Transformer transformer = TransformerFactory.newInstance().newTransformer(); 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"); StreamResult result = new StreamResult(new StringWriter()); DOMSource source = new DOMSource(d); transformer.transform(source, result); String str = result.getWriter().toString(); return str;/*from w w w . j av a 2 s .c om*/ }
From source file:com.ibm.rpe.web.service.docgen.impl.GenerateBaseTemplate.java
private static String transformToString(Document document) { try {// w w w .j av a 2 s . com TransformerFactory transFactory = TransformerFactory.newInstance(); Transformer transformer = transFactory.newTransformer(); StringWriter buffer = new StringWriter(); transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes"); transformer.setOutputProperty(OutputKeys.INDENT, "yes"); transformer.transform(new DOMSource(document), new StreamResult(buffer)); return buffer.toString(); } catch (TransformerException e) { throw new RuntimeException(e); } }
From source file:com.hangum.tadpole.engine.sql.util.QueryUtils.java
/** * execute DML/*from ww w . ja va2s. c o m*/ * * @param userDB * @param strQuery * @param listParam * @param resultType * @throws Exception */ public static String executeDML(final UserDBDAO userDB, final String strQuery, final List<Object> listParam, final String resultType) throws Exception { SqlMapClient client = TadpoleSQLManager.getInstance(userDB); Object effectObject = runSQLOther(userDB, strQuery, listParam); String strReturn = ""; if (resultType.equals(RESULT_TYPE.CSV.name())) { final StringWriter stWriter = new StringWriter(); CSVWriter csvWriter = new CSVWriter(stWriter, ','); String[] arryString = new String[2]; arryString[0] = "effectrow"; arryString[1] = String.valueOf(effectObject); csvWriter.writeNext(arryString); strReturn = stWriter.toString(); } else if (resultType.equals(RESULT_TYPE.JSON.name())) { final JsonArray jsonArry = new JsonArray(); JsonObject jsonObj = new JsonObject(); jsonObj.addProperty("effectrow", String.valueOf(effectObject)); jsonArry.add(jsonObj); strReturn = JSONUtil.getPretty(jsonArry.toString()); } else {//if(resultType.equals(RESULT_TYPE.XML.name())) { DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder builder = factory.newDocumentBuilder(); final Document doc = builder.newDocument(); final Element results = doc.createElement("Results"); doc.appendChild(results); Element row = doc.createElement("Row"); results.appendChild(row); Element node = doc.createElement("effectrow"); node.appendChild(doc.createTextNode(String.valueOf(effectObject))); 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"); final StringWriter stWriter = new StringWriter(); StreamResult sr = new StreamResult(stWriter); transformer.transform(domSource, sr); strReturn = stWriter.toString(); } return strReturn; }
From source file:com.ibm.rpe.web.service.docgen.impl.GenerateBaseTemplate.java
private static String nodeToString(Node node) { StringWriter sw = new StringWriter(); try {//from ww w.java 2s. com Transformer t = TransformerFactory.newInstance().newTransformer(); t.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes"); t.setOutputProperty(OutputKeys.INDENT, "yes"); t.transform(new DOMSource(node), new StreamResult(sw)); } catch (TransformerException te) { System.out.println("nodeToString Transformer Exception"); } return sw.toString(); }
From source file:com.CodeSeance.JSeance.CodeGenXML.ContextManager.java
public XMLObject createXMLObject(Document document) { //Transform to String Transformer transformer;/* w ww.j a v a 2 s .c o m*/ StreamResult result; try { if (ExecutionError.simulate_CONTEXTMANAGER_CREATEXMLOBJECT_ERROR) { ExecutionError.simulate_CONTEXTMANAGER_CREATEXMLOBJECT_ERROR = false; throw new TransformerException("Simulated exception for log testing"); } transformer = TransformerFactory.newInstance().newTransformer(); // The next section is required in order for the JS engine to parse the XML transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes"); result = new StreamResult(new StringWriter()); DOMSource source = new DOMSource(document); transformer.transform(source, result); } catch (TransformerException ex) { // Wrap Exception with RuntimeException since caller won't be able to handle it throw new RuntimeException( ExecutionError.CONTEXTMANAGER_CREATEXMLOBJECT_ERROR.getMessage(ex.getMessage())); } String xmlString = result.getWriter().toString(); // Create the JS Objects Object[] args = { xmlString }; Object jsXMLObj = callJSFunction(XML_CREATE_FN, args); assert jsXMLObj instanceof XMLObject; return (XMLObject) jsXMLObj; }
From source file:edu.cornell.mannlib.vitro.webapp.web.templatemodels.customlistview.CustomListViewConfigFile.java
private String formatXmlNode(Node node) { try {//ww w. j a v a 2s . co m // Set up the output transformer Transformer t = TransformerFactory.newInstance().newTransformer(); t.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes"); t.setOutputProperty(OutputKeys.INDENT, "yes"); // Print the DOM node StringWriter sw = new StringWriter(); StreamResult result = new StreamResult(sw); DOMSource source = new DOMSource(node); t.transform(source, result); return sw.toString(); } catch (TransformerException e) { return "Failed to format XML node: " + node.getTextContent(); } }
From source file:isl.FIMS.servlet.imports.ImportXML.java
protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { this.initVars(request); String username = getUsername(request); Config conf = new Config("EisagwghXML_RDF"); String xsl = ApplicationConfig.SYSTEM_ROOT + "formating/xsl/import/ImportXML.xsl"; String displayMsg = ""; response.setContentType("text/html;charset=UTF-8"); PrintWriter out = response.getWriter(); StringBuilder xml = new StringBuilder( this.xmlStart(this.topmenu, username, this.pageTitle, this.lang, "", request)); // ArrayList<String> notValidMXL = new ArrayList<String>(); HashMap<String, ArrayList> notValidMXL = new <String, ArrayList>HashMap(); if (!ServletFileUpload.isMultipartContent(request)) { displayMsg = "form"; } else {//from www . j av a 2 s . co m // configures some settings String filePath = this.export_import_Folder; java.util.Date date = new java.util.Date(); Timestamp t = new Timestamp(date.getTime()); String currentDir = filePath + t.toString().replaceAll(":", ""); File saveDir = new File(currentDir); if (!saveDir.exists()) { saveDir.mkdir(); } DiskFileItemFactory factory = new DiskFileItemFactory(); factory.setSizeThreshold(DiskFileItemFactory.DEFAULT_SIZE_THRESHOLD); factory.setRepository(saveDir); ArrayList<String> savedIDs = new ArrayList<String>(); ServletFileUpload upload = new ServletFileUpload(factory); upload.setSizeMax(REQUEST_SIZE); // constructs the directory path to store upload file String uploadPath = currentDir; int xmlCount = 0; String[] id = null; try { // parses the request's content to extract file data List formItems = upload.parseRequest(request); Iterator iter = formItems.iterator(); // iterates over form's fields File storeFile = null; while (iter.hasNext()) { FileItem item = (FileItem) iter.next(); // processes only fields that are not form fields if (!item.isFormField()) { String fileName = new File(item.getName()).getName(); filePath = uploadPath + File.separator + fileName; storeFile = new File(filePath); item.write(storeFile); Utils.unzip(fileName, uploadPath); File dir = new File(uploadPath); String[] extensions = new String[] { "xml", "x3ml" }; List<File> files = (List<File>) FileUtils.listFiles(dir, extensions, true); xmlCount = files.size(); for (File file : files) { // saves the file on disk Document doc = ParseXMLFile.parseFile(file.getPath()); String xmlContent = doc.getDocumentElement().getTextContent(); String uri_name = ""; try { uri_name = DMSTag.valueOf("uri_name", "target", type, this.conf)[0]; } catch (DMSException ex) { ex.printStackTrace(); } String uriValue = this.URI_Reference_Path + uri_name + "/"; boolean insertEntity = false; if (xmlContent.contains(uriValue) || file.getName().contains(type)) { insertEntity = true; } Element root = doc.getDocumentElement(); Node admin = Utils.removeNode(root, "admin", true); // File rename = new File(uploadPath + File.separator + id[0] + ".xml"); // boolean isRename = storeFile.renameTo(rename); // ParseXMLFile.saveXMLDocument(rename.getPath(), doc); String schemaFilename = ""; schemaFilename = type; SchemaFile sch = new SchemaFile(schemaFolder + schemaFilename + ".xsd"); TransformerFactory tf = TransformerFactory.newInstance(); Transformer transformer = tf.newTransformer(); transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes"); StringWriter writer = new StringWriter(); transformer.transform(new DOMSource(doc), new StreamResult(writer)); String xmlString = writer.getBuffer().toString().replaceAll("\r", ""); //without admin boolean isValid = sch.validate(xmlString); if ((!isValid && insertEntity)) { notValidMXL.put(file.getName(), null); } else if (insertEntity) { id = initInsertFile(type, false); doc = createAdminPart(id[0], type, doc, username); writer = new StringWriter(); transformer.transform(new DOMSource(doc), new StreamResult(writer)); xmlString = writer.getBuffer().toString().replaceAll("\r", ""); DBCollection col = new DBCollection(this.DBURI, id[1], this.DBuser, this.DBpassword); DBFile dbF = col.createFile(id[0] + ".xml", "XMLDBFile"); dbF.setXMLAsString(xmlString); dbF.store(); ArrayList<String> externalFiles = new <String>ArrayList(); ArrayList<String> externalDBFiles = new <String>ArrayList(); String q = "//*["; for (String attrSet : this.uploadAttributes) { String[] temp = attrSet.split("#"); String func = temp[0]; String attr = temp[1]; if (func.contains("text")) { q += "@" + attr + "]/text()"; } else { q = "data(//*[@" + attr + "]/@" + attr + ")"; } String[] res = dbF.queryString(q); for (String extFile : res) { externalFiles.add(extFile + "#" + attr); } } q = "//"; if (!dbSchemaPath[0].equals("")) { for (String attrSet : this.dbSchemaPath) { String[] temp = attrSet.split("#"); String func = temp[0]; String path = temp[1]; if (func.contains("text")) { q += path + "//text()"; } else { q = "data(//" + path + ")"; } String[] res = dbF.queryString(q); for (String extFile : res) { externalDBFiles.add(extFile); } } } ArrayList<String> missingExternalFiles = new <String>ArrayList(); for (String extFile : externalFiles) { extFile = extFile.substring(0, extFile.lastIndexOf("#")); List<File> f = (List<File>) FileUtils.listFiles(dir, FileFilterUtils.nameFileFilter(extFile), TrueFileFilter.INSTANCE); if (f.size() == 0) { missingExternalFiles.add(extFile); } } if (missingExternalFiles.size() > 0) { notValidMXL.put(file.getName(), missingExternalFiles); } XMLEntity xmlNew = new XMLEntity(this.DBURI, this.systemDbCollection + type, this.DBuser, this.DBpassword, type, id[0]); ArrayList<String> worngFiles = Utils.checkReference(xmlNew, this.DBURI, id[0], type, this.DBuser, this.DBpassword); if (worngFiles.size() > 0) { //dbF.remove(); notValidMXL.put(file.getName(), worngFiles); } //remove duplicates from externalFiles if any HashSet hs = new HashSet(); hs.addAll(missingExternalFiles); missingExternalFiles.clear(); missingExternalFiles.addAll(hs); if (missingExternalFiles.isEmpty() && worngFiles.isEmpty()) { for (String extFile : externalFiles) { String attr = extFile.substring(extFile.lastIndexOf("#") + 1, extFile.length()); extFile = extFile.substring(0, extFile.lastIndexOf("#")); List<File> f = (List<File>) FileUtils.listFiles(dir, FileFilterUtils.nameFileFilter(extFile), TrueFileFilter.INSTANCE); File uploadFile = f.iterator().next(); String content = FileUtils.readFileToString(uploadFile); DBFile uploadsDBFile = new DBFile(this.DBURI, this.adminDbCollection, "Uploads.xml", this.DBuser, this.DBpassword); String mime = Utils.findMime(uploadsDBFile, uploadFile.getName(), attr); String uniqueName = Utils.createUniqueFilename(uploadFile.getName()); File uploadFileUnique = new File(uploadFile.getPath().substring(0, uploadFile.getPath().lastIndexOf(File.separator)) + File.separator + uniqueName); uploadFile.renameTo(uploadFileUnique); xmlString = xmlString.replaceAll(uploadFile.getName(), uniqueName); String upload_path = this.systemUploads + type; File upload_dir = null; ; if (mime.equals("Photos")) { upload_path += File.separator + mime + File.separator + "original" + File.separator; upload_dir = new File(upload_path + uniqueName); FileUtils.copyFile(uploadFileUnique, upload_dir); Utils.resizeImage(uniqueName, upload_path, upload_path.replaceAll("original", "thumbs"), thumbSize); Utils.resizeImage(uniqueName, upload_path, upload_path.replaceAll("original", "normal"), normalSize); xmlString = xmlString.replace("</versions>", "</versions>" + "\n" + "<type>Photos</type>"); } else { upload_path += File.separator + mime + File.separator; upload_dir = new File(upload_path + uniqueName); FileUtils.copyFile(uploadFileUnique, upload_dir); } if (!dbSchemaFolder.equals("")) { if (externalDBFiles.contains(extFile)) { try { DBCollection colSchema = new DBCollection(this.DBURI, dbSchemaFolder, this.DBuser, this.DBpassword); DBFile dbFSchema = colSchema.createFile(uniqueName, "XMLDBFile"); dbFSchema.setXMLAsString(content); dbFSchema.store(); } catch (Exception e) { } } } uploadFileUnique.renameTo(uploadFile); } dbF.setXMLAsString(xmlString); dbF.store(); Utils.updateReferences(xmlNew, this.DBURI, id[0].split(type)[1], type, this.DBpassword, this.DBuser); Utils.updateVocabularies(xmlNew, this.DBURI, id[0].split(type)[1], type, this.DBpassword, this.DBuser, lang); savedIDs.add(id[0]); } else { dbF.remove(); } } } } } Document doc = ParseXMLFile.parseFile(ApplicationConfig.SYSTEM_ROOT + "formating/multi_lang.xml"); Element root = doc.getDocumentElement(); Element contextTag = (Element) root.getElementsByTagName("context").item(0); String uri_name = ""; try { uri_name = DMSTag.valueOf("uri_name", "target", type, this.conf)[0]; } catch (DMSException ex) { } if (notValidMXL.size() == 0) { xsl = conf.DISPLAY_XSL; displayMsg = Messages.ACTION_SUCCESS; displayMsg += Messages.NL + Messages.NL + Messages.URI_ID; String uriValue = ""; xml.append("<Display>").append(displayMsg).append("</Display>\n"); xml.append("<backPages>").append('2').append("</backPages>\n"); for (String saveId : savedIDs) { uriValue = this.URI_Reference_Path + uri_name + "/" + saveId + Messages.NL; xml.append("<codeValue>").append(uriValue).append("</codeValue>\n"); } } else if (notValidMXL.size() >= 1) { xsl = ApplicationConfig.SYSTEM_ROOT + "formating/xsl/import/ImportXML.xsl"; Iterator it = notValidMXL.keySet().iterator(); while (it.hasNext()) { String key = (String) it.next(); ArrayList<String> value = notValidMXL.get(key); if (value != null) { displayMsg += "<line>"; Element select = (Element) contextTag.getElementsByTagName("missingReferences").item(0); displayMsg += select.getElementsByTagName(lang).item(0).getTextContent(); displayMsg = displayMsg.replace("?", key); for (String mis_res : value) { displayMsg += mis_res + ","; } displayMsg = displayMsg.substring(0, displayMsg.length() - 1); displayMsg += "."; displayMsg += "</line>"; } else { displayMsg += "<line>"; Element select = (Element) contextTag.getElementsByTagName("NOT_VALID_XML").item(0); displayMsg += select.getElementsByTagName(lang).item(0).getTextContent(); displayMsg = displayMsg.replace(";", key); displayMsg += "</line>"; } displayMsg += "<line>"; displayMsg += "</line>"; } if (notValidMXL.size() < xmlCount) { displayMsg += "<line>"; Element select = (Element) contextTag.getElementsByTagName("rest_valid").item(0); displayMsg += select.getElementsByTagName(lang).item(0).getTextContent(); displayMsg += "</line>"; for (String saveId : savedIDs) { displayMsg += "<line>"; String uriValue = this.URI_Reference_Path + uri_name + "/" + saveId; select = (Element) contextTag.getElementsByTagName("URI_ID").item(0); displayMsg += select.getElementsByTagName(lang).item(0).getTextContent() + ": " + uriValue; displayMsg += "</line>"; } } } Utils.deleteDir(currentDir); } catch (Exception ex) { ex.printStackTrace(); displayMsg += Messages.NOT_VALID_IMPORT; } } xml.append("<Display>").append(displayMsg).append("</Display>\n"); xml.append("<EntityType>").append(type).append("</EntityType>\n"); xml.append(this.xmlEnd()); try { XMLTransform xmlTrans = new XMLTransform(xml.toString()); xmlTrans.transform(out, xsl); } catch (DMSException e) { e.printStackTrace(); } out.close(); }
From source file:com.evolveum.midpoint.prism.schema.DomToSchemaProcessor.java
private XSSchemaSet parseSchema(Element schema) throws SchemaException { // Make sure that the schema parser sees all the namespace declarations DOMUtil.fixNamespaceDeclarations(schema); XSSchemaSet xss = null;/* ww w . j a va 2 s . c o m*/ try { TransformerFactory transfac = TransformerFactory.newInstance(); Transformer trans = transfac.newTransformer(); trans.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "no"); trans.setOutputProperty(OutputKeys.INDENT, "yes"); DOMSource source = new DOMSource(schema); ByteArrayOutputStream out = new ByteArrayOutputStream(); StreamResult result = new StreamResult(out); trans.transform(source, result); XSOMParser parser = createSchemaParser(); InputSource inSource = new InputSource(new ByteArrayInputStream(out.toByteArray())); // XXX: hack: it's here to make entity resolver work... inSource.setSystemId("SystemId"); // XXX: end hack inSource.setEncoding("utf-8"); parser.parse(inSource); xss = parser.getResult(); } catch (SAXException e) { throw new SchemaException("XML error during XSD schema parsing: " + e.getMessage() + "(embedded exception " + e.getException() + ") in " + shortDescription, e); } catch (TransformerException e) { throw new SchemaException("XML transformer error during XSD schema parsing: " + e.getMessage() + "(locator: " + e.getLocator() + ", embedded exception:" + e.getException() + ") in " + shortDescription, e); } catch (RuntimeException e) { // This sometimes happens, e.g. NPEs in Saxon if (LOGGER.isErrorEnabled()) { LOGGER.error("Unexpected error {} during parsing of schema:\n{}", e.getMessage(), DOMUtil.serializeDOMToString(schema)); } throw new SchemaException( "XML error during XSD schema parsing: " + e.getMessage() + " in " + shortDescription, e); } return xss; }
From source file:com.mirth.connect.plugins.datatypes.xml.XMLBatchAdaptor.java
private String toXML(Node node) throws Exception { Writer writer = new StringWriter(); Transformer transformer = TransformerFactory.newInstance().newTransformer(); transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes"); transformer.setOutputProperty(OutputKeys.INDENT, "yes"); transformer.setOutputProperty(OutputKeys.METHOD, "xml"); transformer.transform(new DOMSource(node), new StreamResult(writer)); return writer.toString(); }