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:fi.csc.emrex.smp.ThymeController.java
private String nodeToString(Node node) { StringWriter sw = new StringWriter(); try {/*from ww w. j av a 2 s . c o m*/ Transformer t = TransformerFactory.newInstance().newTransformer(); t.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes"); t.setOutputProperty(OutputKeys.INDENT, "no"); t.transform(new DOMSource(node), new StreamResult(sw)); } catch (TransformerException te) { log.error("NodeToString Transformer Exception", te); } return sw.toString(); }
From source file:de.huberlin.wbi.hiway.am.galaxy.GalaxyApplicationMaster.java
/** * A helper function for parsing a Galaxy tool's XML file * //from ww w .j a va 2s. co m * @param file * the XML file to be parsed * @return the Galaxy tools described in the XML file */ private GalaxyTool parseToolFile(File file) { System.out.println("Parsing Galaxy tool file " + file); try { DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder(); String path = file.getCanonicalPath(); String dir = path.substring(0, path.lastIndexOf("/")); Document doc = builder.parse(file); Element rootEl = doc.getDocumentElement(); Transformer transformer = TransformerFactory.newInstance().newTransformer(); transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes"); StreamResult result = new StreamResult(new StringWriter()); DOMSource source = new DOMSource(rootEl); transformer.transform(source, result); String toolDescription = result.getWriter().toString(); // (1) parse macros, if any NodeList macrosNds = rootEl.getElementsByTagName("macros"); Map<String, String> macrosByName = new HashMap<>(); for (int i = 0; i < macrosNds.getLength(); i++) { Node macrosNd = macrosNds.item(i); macrosByName.putAll(processMacros(macrosNd, dir)); } // (2) insert macros into the XML and parse the document Pattern p = Pattern.compile("<expand macro=\"([^\"]*)\"(>.*?</expand>|/>)", Pattern.DOTALL); Matcher m = p.matcher(toolDescription); while (m.find()) { String name = m.group(1); String replace = m.group(0); String with = macrosByName.get(name); if (m.group(2).startsWith(">")) { String yield = m.group(2).substring(1, m.group(2).indexOf("</expand>")); with = with.replaceAll("<yield/>", yield.trim()); } if (with != null) toolDescription = toolDescription.replace(replace, with); } doc = builder.parse(new InputSource(new StringReader(toolDescription))); rootEl = doc.getDocumentElement(); String version = rootEl.hasAttribute("version") ? rootEl.getAttribute("version") : "1.0.0"; String id = rootEl.getAttribute("id"); GalaxyTool tool = new GalaxyTool(id, version, dir, galaxyPath); // (3) determine requirements (libraries and executables) of this tool; requirements have to be parsed such that the environment of the task can be // set to include them NodeList requirementNds = rootEl.getElementsByTagName("requirement"); for (int i = 0; i < requirementNds.getLength(); i++) { Element requirementEl = (Element) requirementNds.item(i); String requirementName = requirementEl.getChildNodes().item(0).getNodeValue().trim(); String requirementVersion = requirementEl.getAttribute("version"); tool.addRequirement(requirementName, requirementVersion); } // (4) determine and set the template for the command of the task; this template will be compiled at runtime by Cheetah Element commandEl = (Element) rootEl.getElementsByTagName("command").item(0); if (commandEl != null) { String command = commandEl.getChildNodes().item(0).getNodeValue().trim(); String script = command.split(" ")[0]; String interpreter = commandEl.getAttribute("interpreter"); if (interpreter.length() > 0) { command = command.replace(script, dir + "/" + script); command = interpreter + " " + command; } command = command.replaceAll("\\.value", ""); command = command.replaceAll("\\.dataset", ""); tool.setTemplate(command); } // (5) determine the parameters (atomic, conditional and repeat) of this tool Element inputsEl = (Element) rootEl.getElementsByTagName("inputs").item(0); if (inputsEl != null) tool.setParams(getParams(inputsEl, tool)); // (6) determine the output files produced by this tool Element outputsEl = (Element) rootEl.getElementsByTagName("outputs").item(0); if (outputsEl != null) { NodeList dataNds = outputsEl.getElementsByTagName("data"); for (int i = 0; i < dataNds.getLength(); i++) { Element dataEl = (Element) dataNds.item(i); String name = dataEl.getAttribute("name"); GalaxyParamValue param = new GalaxyParamValue(name); tool.setPath(name); tool.addParam(param); String format = dataEl.getAttribute("format"); String metadata_source = dataEl.getAttribute("metadata_source"); if (format.equals("input") && metadata_source != null && metadata_source.length() > 0) { param.setDataType(metadata_source); } else { param.setDataType(format); } String from_work_dir = dataEl.getAttribute("from_work_dir"); param.setFrom_work_dir(from_work_dir); } } // (7) register the tool in the Galaxy tool data structure if (tool.getTemplate() != null) { Map<String, GalaxyTool> toolMap = addAndGetToolMap(id); toolMap.put(version, tool); } return tool; } catch (SAXException | IOException | TransformerException | XPathExpressionException | ParserConfigurationException e) { e.printStackTrace(); System.exit(-1); return null; } }
From source file:eu.europa.esig.dss.XmlDom.java
/** * This method writes formatted {@link org.w3c.dom.Node} to the outputStream. * * @param node/*from w w w . j av a2 s . c o m*/ * @param out */ private static void printDocument(final Node node, final OutputStream out, final boolean raw) { try { final TransformerFactory tf = TransformerFactory.newInstance(); final Transformer transformer = tf.newTransformer(); transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "no"); transformer.setOutputProperty(OutputKeys.METHOD, "xml"); if (!raw) { transformer.setOutputProperty(OutputKeys.INDENT, "yes"); transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "3"); } transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8"); final DOMSource xmlSource = new DOMSource(node); final OutputStreamWriter writer = new OutputStreamWriter(out, "UTF-8"); final StreamResult outputTarget = new StreamResult(writer); transformer.transform(xmlSource, outputTarget); } catch (Exception e) { throw new DSSException(e); } }
From source file:com.rest4j.generator.Generator.java
private void output(Node node, File file) throws TransformerException, IOException { FileOutputStream fos = new FileOutputStream(file); try {//w w w . j ava2s .c o m for (Node child : Util.it(node.getChildNodes())) { DOMSource source = new DOMSource(child); StreamResult result = new StreamResult(fos); Transformer trans = tFactory.newTransformer(); trans.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes"); trans.setOutputProperty(OutputKeys.INDENT, "no"); trans.transform(source, result); } } finally { IOUtils.closeQuietly(fos); } }
From source file:com.eucalyptus.imaging.manifest.DownloadManifestFactory.java
private static final String nodeToString(Node node, boolean addDeclaration) throws Exception { Transformer tf = TransformerFactory.newInstance().newTransformer(); tf.setOutputProperty(OutputKeys.ENCODING, "UTF-8"); if (!addDeclaration) tf.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes"); Writer out = new StringWriter(); tf.transform(new DOMSource(node), new StreamResult(out)); return out.toString(); }
From source file:eu.impact_project.iif.tw.gen.DeploymentCreator.java
/** * Insert data types/*from w ww . ja va 2 s . c o m*/ * @throws GeneratorException */ public void createPom() throws GeneratorException { File wsdlTemplate = new File(this.pomAbsPath); if (!wsdlTemplate.canRead()) { throw new GeneratorException("Unable to read pom.xml template file: " + this.pomAbsPath); } try { DocumentBuilderFactory docBuildFact = DocumentBuilderFactory.newInstance(); DocumentBuilder docBuilder = docBuildFact.newDocumentBuilder(); doc = docBuilder.parse(this.pomAbsPath); NodeList profilesNodes = doc.getElementsByTagName("profiles"); Node firstProfilesNode = profilesNodes.item(0); List<Deployref> dks = service.getDeployto().getDeployref(); NodeList executionsNode = doc.getElementsByTagName("executions"); Node thirdExecutionsNode = executionsNode.item(2); for (Deployref dk : dks) { boolean isDefaultDeployment = dk.isDefault(); Deployment d = (Deployment) dk.getRef(); String host = d.getHost(); String id = d.getId(); //<profile> // <id>deployment1</id> // <properties> // <tomcat.manager.url>http://localhost:8080/manager</tomcat.manager.url> // <tomcat.user>tomcat</tomcat.user> // <tomcat.password>TxF781!P</tomcat.password> // <war.suffix>deployment1</war.suffix> // </properties> //</profile> //<profile> // <id>deployment2</id> // <properties> // <tomcat.manager.url>http://localhost:8080/manager</tomcat.manager.url> // <tomcat.user>tomcat</tomcat.user> // <tomcat.password>TxF781!P</tomcat.password> // <war.suffix>deployment2</war.suffix> // </properties> //</profile> Element profileElm = doc.createElement("profile"); if (isDefaultDeployment) { Element activationElm = doc.createElement("activation"); Element activeByDefaultElm = doc.createElement("activeByDefault"); activeByDefaultElm.setTextContent("true"); activationElm.appendChild(activeByDefaultElm); profileElm.appendChild(activationElm); } firstProfilesNode.appendChild(profileElm); Element idElm = doc.createElement("id"); idElm.setTextContent(d.getId()); profileElm.appendChild(idElm); Element propertiesElm = doc.createElement("properties"); profileElm.appendChild(propertiesElm); List<Port> ports = d.getPorts().getPort(); String port = "8080"; String type = "http"; for (Port p : ports) { if (p.getType().equals("http")) { port = String.valueOf(p.getValue()); type = p.getType(); } } Element tomcatManagerUrlElm = doc.createElement("tomcat.manager.url"); String managerPath = d.getManager().getPath(); managerPath = (managerPath != null && !managerPath.isEmpty()) ? managerPath : "manager"; tomcatManagerUrlElm.setTextContent(type + "://" + d.getHost() + ":" + port + "/" + managerPath); propertiesElm.appendChild(tomcatManagerUrlElm); Element tomcatUserPropElm = doc.createElement("tomcat.user"); Manager manager = d.getManager(); tomcatUserPropElm.setTextContent(manager.getUser()); propertiesElm.appendChild(tomcatUserPropElm); Element tomcatPasswordPropElm = doc.createElement("tomcat.password"); tomcatPasswordPropElm.setTextContent(manager.getPassword()); propertiesElm.appendChild(tomcatPasswordPropElm); Element warSuffixElm = doc.createElement("war.suffix"); warSuffixElm.setTextContent(d.getId()); propertiesElm.appendChild(warSuffixElm); //<execution> // <id>package-deployment1</id> // <phase>package</phase> // <configuration> // <classifier>deployment1</classifier> // <webappDirectory>${project.build.directory}/${project.build.finalName}_deployment1</webappDirectory> // <webResources> // <resource> // <directory>src/env/deployment1</directory> // </resource> // </webResources> // </configuration> // <goals> // <goal>war</goal> // </goals> //</execution> Element executionElm = doc.createElement("execution"); Element id2Elm = doc.createElement("id"); id2Elm.setTextContent("package-" + d.getId()); executionElm.appendChild(id2Elm); Element phaseElm = doc.createElement("phase"); phaseElm.setTextContent("package"); executionElm.appendChild(phaseElm); Element configurationElm = doc.createElement("configuration"); executionElm.appendChild(configurationElm); Element classifierElm = doc.createElement("classifier"); classifierElm.setTextContent(d.getId()); configurationElm.appendChild(classifierElm); Element webappDirectoryElm = doc.createElement("webappDirectory"); webappDirectoryElm .setTextContent("${project.build.directory}/${project.build.finalName}_" + d.getId()); configurationElm.appendChild(webappDirectoryElm); Element webResourcesElm = doc.createElement("webResources"); Element resourceElm = doc.createElement("resource"); Element directoryElm = doc.createElement("directory"); directoryElm.setTextContent("src/env/" + d.getId()); resourceElm.appendChild(directoryElm); webResourcesElm.appendChild(resourceElm); configurationElm.appendChild(webResourcesElm); Element goalsElm = doc.createElement("goals"); executionElm.appendChild(goalsElm); Element goalElm = doc.createElement("goal"); goalElm.setTextContent("war"); goalsElm.appendChild(goalElm); thirdExecutionsNode.appendChild(executionElm); if (isDefaultDeployment) { NodeList directories = doc.getElementsByTagName("directory"); Node directoryNode = directories.item(0); directoryNode.setTextContent("src/env/" + d.getId()); } // Create different environment dependent configuration files. // Deployment environment dependent files will be stored in // src/env and will then be activated by choosing the corresponding // profile during the corresponding maven phase. // E.g. mvn tomcat:redeploy -P deployment1 // will replace the deployment dependent files by the ones // available under src/env/deployment1. String generatedDir = st.getGenerateDir(); String projMidfix = st.getProjectMidfix(); String projDir = st.getProjectDirectory(); String servDir = FileUtil.makePath(generatedDir, projDir, "src/env", d.getId(), "WEB-INF/services", projMidfix, "META-INF"); FileUtils.forceMkdir(new File(servDir)); String sxmlFile = FileUtil.makePath(generatedDir, projDir, "src/main/webapp/WEB-INF/services", st.getProjectMidfix(), "META-INF") + "services.xml"; GenericCode deplDepServXmlCode = new GenericCode(sxmlFile); //<parameter name="cliCommand1">${clicmd}</parameter> //<parameter name="processingUnit">${tomcat_public_procunitid}</parameter> //<parameter name="publicHttpAccessDir">${tomcat_public_http_access_dir}</parameter> //<parameter name="publicHttpAccessUrl">${tomcat_public_http_access_url}</parameter> //<parameter name="serviceUrlFilter">${service_url_filter}</parameter> List<Operation> operations = service.getOperations().getOperation(); for (Operation operation : operations) { String command = operation.getCommand(); String toolsbasedir = d.getToolsbasedir(); if (toolsbasedir != null && !toolsbasedir.equals("")) { command = toolsbasedir + command; } deplDepServXmlCode.put("cli_cmd_" + String.valueOf(operation.getOid()), command); } deplDepServXmlCode.put("tomcat_public_procunitid", d.getIdentifier()); Dataexchange de = d.getDataexchange(); String accessDir = FileUtil.makePath(de.getAccessdir()); String accessUrl = de.getAccessurl(); deplDepServXmlCode.put("tomcat_public_http_access_dir", accessDir); deplDepServXmlCode.put("tomcat_public_http_access_url", accessUrl); // TODO: filter //deplDepServXmlCode.put("service_url_filter", ); deplDepServXmlCode.evaluate(); deplDepServXmlCode.create(servDir + "services.xml"); logger.debug("Writing: " + servDir + "services.xml"); if (isDefaultDeployment) { defaultDeplServicesFile = servDir + "services.xml"; defaultServicesFile = sxmlFile; } // source String htmlIndexSourcePath = FileUtil.makePath(generatedDir, projDir, "src/main", "webapp") + "index.html"; // substitution GenericCode htmlSourceIndexCode = new GenericCode(htmlIndexSourcePath); htmlSourceIndexCode.put("service_description", service.getDescription()); htmlSourceIndexCode.put("tomcat_public_host", d.getHost()); htmlSourceIndexCode.put("tomcat_public_http_port", port); // target String htmlIndexDir = FileUtil.makePath(generatedDir, projDir, "src/env", d.getId()); FileUtils.forceMkdir(new File(htmlIndexDir)); String htmlIndexTargetPath = FileUtil.makePath(generatedDir, projDir, "src/env", d.getId()) + "index.html"; htmlSourceIndexCode.create(htmlIndexTargetPath); if (isDefaultDeployment) { this.defaultDeplHtmlFile = htmlIndexTargetPath; this.defaultHtmlFile = htmlIndexSourcePath; } // source String wsdlSourcePath = FileUtil.makePath(generatedDir, projDir, "src/main", "webapp") + st.getProjectMidfix() + ".wsdl"; // substitution GenericCode wsdlSourceCode = new GenericCode(wsdlSourcePath); wsdlSourceCode.put("tomcat_public_host", d.getHost()); wsdlSourceCode.put("tomcat_public_http_port", port); // target String wsdlDir = FileUtil.makePath(generatedDir, projDir, "src/env", d.getId()); FileUtils.forceMkdir(new File(wsdlDir)); String wsdlTargetPath = FileUtil.makePath(generatedDir, projDir, "src/env", d.getId()) + st.getProjectMidfix() + ".wsdl"; wsdlSourceCode.create(wsdlTargetPath); if (isDefaultDeployment) { this.defaultDeplWsdlFile = wsdlTargetPath; this.defaultWsdlFile = wsdlSourcePath; } } if (defaultDeplServicesFile != null && !defaultDeplServicesFile.isEmpty()) { FileUtils.copyFile(new File(defaultDeplServicesFile), new File(defaultServicesFile)); FileUtils.copyFile(new File(this.defaultDeplHtmlFile), new File(this.defaultHtmlFile)); FileUtils.copyFile(new File(this.defaultDeplWsdlFile), new File(this.defaultWsdlFile)); } 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", "4"); DOMSource source = new DOMSource(doc); FileOutputStream fos = new FileOutputStream(this.pomAbsPath); StreamResult result = new StreamResult(fos); transformer.transform(source, result); fos.close(); } catch (Exception ex) { logger.error("An exception occurred: " + ex.getMessage()); } }
From source file:br.org.indt.ndg.server.client.TemporaryOpenRosaBussinessDelegate.java
/********** Uploading OpenRosa Surveys and Results **********/ public boolean parseAndPersistSurvey(InputStreamReader inputStreamReader, String contentType) throws IOException { String surveyString = parseMultipartEncodedFile(inputStreamReader, contentType, "filename"); String surveyId = null;//from w w w . j av a 2 s.c o m String surveyIdOriginal = null; Document surveyDomDocument = null; ByteArrayInputStream streamToParse = new ByteArrayInputStream(surveyString.getBytes("UTF-8")); try { surveyDomDocument = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(streamToParse); } catch (SAXException e) { e.printStackTrace(); return false; } catch (ParserConfigurationException e) { e.printStackTrace(); return false; } finally { streamToParse.close(); } NodeList dataNodeList = surveyDomDocument.getElementsByTagName("data"); if (dataNodeList.getLength() != 1) { return false; // there MUST be exactly 1 <data> node } else { Element dataElement = (Element) dataNodeList.item(0); Random rand = new Random(System.currentTimeMillis()); int newId = rand.nextInt(Integer.MAX_VALUE); surveyId = String.valueOf(newId); surveyIdOriginal = dataElement.getAttribute("id"); dataElement.setAttribute("id", String.valueOf(newId)); StringWriter stringWriter = null; try { Source source = new DOMSource(surveyDomDocument); stringWriter = new StringWriter(); Result result = new StreamResult(stringWriter); TransformerFactory factory = TransformerFactory.newInstance(); Transformer transformer = factory.newTransformer(); transformer.setOutputProperty(OutputKeys.INDENT, "no"); transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8"); transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes"); transformer.setOutputProperty(OutputKeys.METHOD, "xml"); transformer.transform(source, result); surveyString = stringWriter.getBuffer().toString(); } catch (Exception e) { e.printStackTrace(); return false; } finally { stringWriter.close(); } log.info("========================"); log.info("Original Survey Id: " + surveyIdOriginal); log.info("New Survey Id: " + surveyId); log.info("========================"); } return persistSurvey(surveyString, surveyId, surveyIdOriginal); }
From source file:com.mediaworx.xmlutils.XmlHelper.java
/** * Converts the document to a formatted XML String (indentation level is 4) using the given encoding. * @param document The document to be converted to String * @param cdataElements String array containing the names of all elements that are to be added within CDATA sections * @param encoding encoding to be used (added in the XML declaration) * @return the String representation of the given Document *//*from w w w.j av a2s .com*/ public String getXmlStringFromDocument(Document document, String[] cdataElements, String encoding) { cleanEmptyTextNodes(document); TransformerFactory tf = TransformerFactory.newInstance(); Transformer transformer; try { transformer = tf.newTransformer(); } catch (TransformerConfigurationException e) { LOG.error("Exception configuring the XML transformer", e); return ""; } transformer.setOutputProperty(OutputKeys.METHOD, "xml"); transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes"); transformer.setOutputProperty(OutputKeys.INDENT, "yes"); if (cdataElements != null && cdataElements.length > 0) { String cdataElementsJoined = StringUtils.join(cdataElements, ' '); transformer.setOutputProperty(OutputKeys.CDATA_SECTION_ELEMENTS, cdataElementsJoined); } transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4"); OutputStream out = new ByteArrayOutputStream(); try { transformer.transform(new DOMSource(document), new StreamResult(out)); } catch (TransformerException e) { LOG.error("Exception transforming the XML document to String", e); } finally { try { out.close(); } catch (IOException e) { // it seems the output stream was closed already LOG.warn("Exception closing the output stream", e); } } StringBuilder xml = new StringBuilder("<?xml version=\"1.0\" encoding=\"").append(encoding) .append("\"?>\n"); xml.append(out.toString()); return xml.toString(); }
From source file:com.amalto.workbench.utils.XSDGenerateHTML.java
/** * Handle a markup element by caching information in a map. * /* w ww . j a v a 2 s . co m*/ * @param markupMap the map to contain the markup. * @param markupElement the element specifying the markup. */ public void handleMarkup(Map markupMap, Element markupElement) { String keyList = markupElement.getAttribute("key"); //$NON-NLS-1$ for (StringTokenizer stringTokenizer = new StringTokenizer(keyList); stringTokenizer.hasMoreTokens();) { String key = stringTokenizer.nextToken(); String markup = markupElement.getAttribute("markup"); //$NON-NLS-1$ if (markup.length() > 0) { ByteArrayOutputStream out = new ByteArrayOutputStream(); try { TransformerFactory transformerFactory = TransformerFactory.newInstance(); Transformer transformer = transformerFactory.newTransformer(); transformer.setOutputProperty(OutputKeys.INDENT, "yes"); //$NON-NLS-1$ transformer.setOutputProperty(OutputKeys.METHOD, "xml"); //$NON-NLS-1$ transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes"); //$NON-NLS-1$ for (Node grandChild = markupElement .getFirstChild(); grandChild != null; grandChild = grandChild.getNextSibling()) { if (grandChild.getNodeType() == Node.ELEMENT_NODE) { transformer.transform(new DOMSource(grandChild), new StreamResult(out)); } } String serialization = out.toString(); serialization = serialization.substring(serialization.indexOf("<div>")); //$NON-NLS-1$ markupMap.put(key, markup + "@" + serialization); //$NON-NLS-1$ } catch (Exception exception) { exception.printStackTrace(System.err); } } } }
From source file:es.juntadeandalucia.panelGestion.negocio.utiles.Utils.java
public static String documentToString(Document document) throws TransformerException { StringWriter sw = new StringWriter(); TransformerFactory tf = TransformerFactory.newInstance(); Transformer transformer = tf.newTransformer(); transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "no"); transformer.setOutputProperty(OutputKeys.METHOD, "xml"); transformer.setOutputProperty(OutputKeys.INDENT, "yes"); transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8"); transformer.transform(new DOMSource(document), new StreamResult(sw)); return sw.toString(); }