List of usage examples for org.w3c.dom Document setXmlStandalone
public void setXmlStandalone(boolean xmlStandalone) throws DOMException;
From source file:org.apache.hadoop.gateway.filter.rewrite.impl.xml.XmlUrlRewriteRulesExporter.java
@Override public void store(UrlRewriteRulesDescriptor descriptor, Writer writer) throws IOException { try {//w ww . ja v a2 s.c o m DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance(); DocumentBuilder builder = builderFactory.newDocumentBuilder(); Document document = builder.newDocument(); document.setXmlStandalone(true); Element root = document.createElement(ROOT); document.appendChild(root); if (!descriptor.getFunctions().isEmpty()) { Element functionsElement = document.createElement(FUNCTIONS); root.appendChild(functionsElement); for (UrlRewriteFunctionDescriptor function : descriptor.getFunctions()) { Element functionElement = createElement(document, function.name(), function); functionsElement.appendChild(functionElement); } } if (!descriptor.getRules().isEmpty()) { for (UrlRewriteRuleDescriptor rule : descriptor.getRules()) { Element ruleElement = createRule(document, rule); root.appendChild(ruleElement); } } if (!descriptor.getFilters().isEmpty()) { for (UrlRewriteFilterDescriptor filter : descriptor.getFilters()) { Element filterElement = createFilter(document, filter); root.appendChild(filterElement); } } TransformerFactory transformerFactory = TransformerFactory.newInstance(); transformerFactory.setAttribute("indent-number", 2); Transformer transformer = transformerFactory.newTransformer(); //transformer.setOutputProperty( OutputKeys.OMIT_XML_DECLARATION, "yes" ); transformer.setOutputProperty(OutputKeys.STANDALONE, "yes"); transformer.setOutputProperty(OutputKeys.INDENT, "yes"); StreamResult result = new StreamResult(writer); DOMSource source = new DOMSource(document); transformer.transform(source, result); } catch (ParserConfigurationException e) { throw new IOException(e); } catch (TransformerException e) { throw new IOException(e); } catch (InvocationTargetException e) { LOG.failedToWriteRulesDescriptor(e); } catch (NoSuchMethodException e) { LOG.failedToWriteRulesDescriptor(e); } catch (IntrospectionException e) { LOG.failedToWriteRulesDescriptor(e); } catch (IllegalAccessException e) { LOG.failedToWriteRulesDescriptor(e); } }
From source file:org.eclipse.thym.android.core.adt.AndroidProjectGenerator.java
private void updateAppName(String appName) throws CoreException { DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); dbf.setNamespaceAware(true);// w w w . ja v a 2 s . com DocumentBuilder db; try { db = dbf.newDocumentBuilder(); IPath stringsPath = new Path(getDestination().toString()).append(DIR_RES).append(DIR_VALUES) .append(FILE_XML_STRINGS); File strings = stringsPath.toFile(); Document configDocument = db.parse(strings); XPath xpath = XPathFactory.newInstance().newXPath(); try { XPathExpression expr = xpath.compile("//string[@name=\"app_name\"]"); Node node = (Node) expr.evaluate(configDocument, XPathConstants.NODE); node.setTextContent(appName); configDocument.setXmlStandalone(true); Source source = new DOMSource(configDocument); StreamResult result = new StreamResult(strings); // Write the DOM document to the file TransformerFactory transformerFactory = TransformerFactory.newInstance(); Transformer xformer = transformerFactory.newTransformer(); xformer.transform(source, result); } catch (XPathExpressionException e) {//We continue because this affects the displayed app name // which is not a show stopper during development AndroidCore.log(IStatus.ERROR, "Error when updating the application name", e); } catch (TransformerConfigurationException e) { AndroidCore.log(IStatus.ERROR, "Error when updating the application name", e); } catch (TransformerException e) { AndroidCore.log(IStatus.ERROR, "Error when updating the application name", e); } } catch (ParserConfigurationException e) { throw new CoreException(new Status(IStatus.ERROR, HybridCore.PLUGIN_ID, "Parser error when parsing /res/values/strings.xml", e)); } catch (SAXException e) { throw new CoreException( new Status(IStatus.ERROR, HybridCore.PLUGIN_ID, "Parsing error on /res/values/strings.xml", e)); } catch (IOException e) { throw new CoreException(new Status(IStatus.ERROR, HybridCore.PLUGIN_ID, "IO error when parsing /res/values/strings.xml", e)); } }
From source file:org.eclipse.thym.blackberry.core.bdt.BlackBerryProjectGenerator.java
private void updateAppName(String appName) throws CoreException { DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); dbf.setNamespaceAware(true);//from ww w .ja va 2s . c o m DocumentBuilder db; try { db = dbf.newDocumentBuilder(); IPath stringsPath = new Path(getDestination().toString()).append(DIR_RES).append(DIR_VALUES) .append(FILE_XML_STRINGS); File strings = stringsPath.toFile(); Document configDocument = db.parse(strings); XPath xpath = XPathFactory.newInstance().newXPath(); try { XPathExpression expr = xpath.compile("//string[@name=\"app_name\"]"); Node node = (Node) expr.evaluate(configDocument, XPathConstants.NODE); node.setTextContent(appName); configDocument.setXmlStandalone(true); Source source = new DOMSource(configDocument); StreamResult result = new StreamResult(strings); // Write the DOM document to the file TransformerFactory transformerFactory = TransformerFactory.newInstance(); Transformer xformer = transformerFactory.newTransformer(); xformer.transform(source, result); } catch (XPathExpressionException e) {//We continue because this affects the displayed app name // which is not a show stopper during development BlackBerryCore.log(IStatus.ERROR, "Error when updating the application name", e); } catch (TransformerConfigurationException e) { BlackBerryCore.log(IStatus.ERROR, "Error when updating the application name", e); } catch (TransformerException e) { BlackBerryCore.log(IStatus.ERROR, "Error when updating the application name", e); } } catch (ParserConfigurationException e) { throw new CoreException(new Status(IStatus.ERROR, HybridCore.PLUGIN_ID, "Parser error when parsing /res/values/strings.xml", e)); } catch (SAXException e) { throw new CoreException( new Status(IStatus.ERROR, HybridCore.PLUGIN_ID, "Parsing error on /res/values/strings.xml", e)); } catch (IOException e) { throw new CoreException(new Status(IStatus.ERROR, HybridCore.PLUGIN_ID, "IO error when parsing /res/values/strings.xml", e)); } }
From source file:org.gephi.desktop.preview.PresetUtils.java
public void savePreset(PreviewPreset preset) { int exist = -1; for (int i = 0; i < presets.size(); i++) { PreviewPreset p = presets.get(i); if (p.getName().equals(preset.getName())) { exist = i;//from w w w . j ava 2 s.c o m break; } } if (exist == -1) { addPreset(preset); } else { presets.set(exist, preset); } try { //Create file if dont exist FileObject folder = FileUtil.getConfigFile("previewpresets"); if (folder == null) { folder = FileUtil.getConfigRoot().createFolder("previewpresets"); } String filename = DigestUtils.sha1Hex(preset.getName());//Safe filename FileObject presetFile = folder.getFileObject(filename, "xml"); if (presetFile == null) { presetFile = folder.createData(filename, "xml"); } //Create doc DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder documentBuilder = factory.newDocumentBuilder(); final Document document = documentBuilder.newDocument(); document.setXmlVersion("1.0"); document.setXmlStandalone(true); //Write doc writeXML(document, preset); //Write XML file try (OutputStream outputStream = presetFile.getOutputStream()) { Source source = new DOMSource(document); Result result = new StreamResult(outputStream); Transformer transformer = TransformerFactory.newInstance().newTransformer(); transformer.setOutputProperty(OutputKeys.INDENT, "yes"); transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8"); transformer.transform(source, result); } } catch (Exception ex) { Exceptions.printStackTrace(ex); } }
From source file:org.jboss.as.jdr.util.XMLSanitizer.java
public InputStream sanitize(InputStream in) throws Exception { byte[] content = IOUtils.toByteArray(in); try {/*from www . j ava 2 s . co m*/ // storing the entire file in memory in case we need to bail. Document doc = builder.parse(new ByteArrayInputStream(content)); doc.setXmlStandalone(true); Object result = expression.evaluate(doc, XPathConstants.NODESET); NodeList nodes = (NodeList) result; for (int i = 0; i < nodes.getLength(); i++) { nodes.item(i).setTextContent(""); } DOMSource source = new DOMSource(doc); ByteArrayOutputStream output = new ByteArrayOutputStream(); StreamResult outStream = new StreamResult(output); transformer.transform(source, outStream); return new ByteArrayInputStream(output.toByteArray()); } catch (Exception e) { ROOT_LOGGER.debug("Error while sanitizing an xml document", e); return new ByteArrayInputStream(content); } }
From source file:org.jboss.tools.aerogear.hybrid.android.core.adt.AndroidProjectGenerator.java
private void updateAppName(String appName) throws CoreException { DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); dbf.setNamespaceAware(true);// ww w . jav a 2s.c o m DocumentBuilder db; try { db = dbf.newDocumentBuilder(); IPath stringsPath = new Path(getDestination().toString()).append(DIR_RES).append(DIR_VALUES) .append(FILE_XML_STRINGS); File strings = stringsPath.toFile(); Document configDocument = db.parse(strings); XPath xpath = XPathFactory.newInstance().newXPath(); try { XPathExpression expr = xpath.compile("//string[@name=\"app_name\"]"); Node node = (Node) expr.evaluate(configDocument, XPathConstants.NODE); node.setTextContent(appName); configDocument.setXmlStandalone(true); Source source = new DOMSource(configDocument); StreamResult result = new StreamResult(strings); // Write the DOM document to the file TransformerFactory transformerFactory = TransformerFactory.newInstance(); Transformer xformer = transformerFactory.newTransformer(); xformer.transform(source, result); } catch (XPathExpressionException e) {//We continue because this affects the displayed app name // which is not a show stopper during development AndroidCore.log(IStatus.ERROR, "Error when updating the application name", e); } catch (TransformerConfigurationException e) { AndroidCore.log(IStatus.ERROR, "Error when updating the application name", e); } catch (TransformerException e) { AndroidCore.log(IStatus.ERROR, "Error when updating the application name", e); } } catch (ParserConfigurationException e) { throw new CoreException(new Status(IStatus.ERROR, HybridCore.PLUGIN_ID, "Parser error when parsing /res/values/strings.xml", e)); } catch (SAXException e) { throw new CoreException( new Status(IStatus.ERROR, HybridCore.PLUGIN_ID, "Parsing error on /res/values/strings.xml", e)); } catch (IOException e) { throw new CoreException(new Status(IStatus.ERROR, HybridCore.PLUGIN_ID, "IO error when parsing /res/values/strings.xml", e)); } }
From source file:org.mapsforge.directions.TurnByTurnDescriptionToString.java
/** * Creates a KML (Keyhole markup language) version of the directions. * // w ww. j av a 2 s .c o m * @return a KML string * @throws ParserConfigurationException * if the DOM can't be built * @throws TransformerConfigurationException * if turning the DOM into a string fails * @throws TransformerException * if turning the DOM into a string fails * @throws TransformerFactoryConfigurationError * if turning the DOM into a string fails */ public String toKML() throws ParserConfigurationException, TransformerConfigurationException, TransformerException, TransformerFactoryConfigurationError { // This creates a new DOM Document dom = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument(); // And let's get this started dom.setXmlVersion("1.0"); dom.setXmlStandalone(true); Element kml = dom.createElement("kml"); dom.appendChild(kml); kml.setAttribute("xmlns", "http://www.opengis.net/kml/2.2"); Element document = dom.createElement("Document"); kml.appendChild(document); Element name = dom.createElement("name"); name.setTextContent( "MapsForge directions from " + streets.firstElement().name + " to " + streets.lastElement().name); document.appendChild(name); Element style = dom.createElement("Style"); style.setAttribute("id", "MapsForgeStyle"); document.appendChild(style); Element lineStyle = dom.createElement("LineStyle"); style.appendChild(lineStyle); Element color = dom.createElement("color"); color.setTextContent("ff0000ff"); lineStyle.appendChild(color); Element width = dom.createElement("width"); width.setTextContent("3"); lineStyle.appendChild(width); for (TurnByTurnStreet street : streets) { Element placemark = dom.createElement("Placemark"); document.appendChild(placemark); Element placemarkName = dom.createElement("name"); placemarkName.setTextContent(street.name); placemark.appendChild(placemarkName); Element lineString = dom.createElement("LineString"); placemark.appendChild(lineString); Element coordinates = dom.createElement("coordinates"); lineString.appendChild(coordinates); String coordinatesContent = ""; for (GeoCoordinate c : street.points) { coordinatesContent += c.getLongitude() + "," + c.getLatitude() + " "; } coordinatesContent = coordinatesContent.substring(0, coordinatesContent.length() - 1); // remove last space coordinates.setTextContent(coordinatesContent); Element extendedData = dom.createElement("ExtendedData"); placemark.appendChild(extendedData); Element length = dom.createElement("Length"); extendedData.appendChild(length); length.setTextContent(Double.toString(street.length)); Element angle = dom.createElement("AngleToPreviousStreet"); extendedData.appendChild(angle); angle.setTextContent(Double.toString(street.angleFromStreetLastStreet)); Element styleUrl = dom.createElement("styleUrl"); placemark.appendChild(styleUrl); styleUrl.setTextContent("#MapsForgeStyle"); } // This is for turning the DOM object into a proper StringWriter StringWriter stringWriter = new StringWriter(); TransformerFactory.newInstance().newTransformer().transform(new DOMSource(dom), new StreamResult(stringWriter)); return stringWriter.getBuffer().toString(); }
From source file:org.mapsforge.directions.TurnByTurnDescriptionToString.java
/** * Creates a GPX (GPS Exchange Format) version of the directions. * //from ww w .j a va 2 s . c o m * @return a KML string * @throws ParserConfigurationException * if the DOM can't be built * @throws TransformerConfigurationException * if turning the DOM into a string fails * @throws TransformerException * if turning the DOM into a string fails * @throws TransformerFactoryConfigurationError * if turning the DOM into a string fails */ public String toGPX() throws ParserConfigurationException, TransformerConfigurationException, TransformerException, TransformerFactoryConfigurationError { // This creates a new DOM Document dom = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument(); // And let's get this started dom.setXmlVersion("1.0"); dom.setXmlStandalone(true); Element gpx = dom.createElement("gpx"); dom.appendChild(gpx); gpx.setAttribute("version", "1.1"); gpx.setAttribute("xmlns", "http://www.topografix.com/GPX/1/1"); gpx.setAttribute("xmlns:xsi", "http://www.w3.org/2001/XMLSchema-instance"); gpx.setAttribute("xmlns:mf", "http://tom.mapsforge.de"); gpx.setAttribute("xsi:schemaLocation", "http://www.topografix.com/GPX/1/1 http://www.topografix.com/gpx/1/1/gpx.xsd"); gpx.setAttribute("creator", "tom.mapsforge.de"); Element metadata = dom.createElement("metadata"); gpx.appendChild(metadata); Element name = dom.createElement("name"); name.setTextContent( "MapsForge directions from " + streets.firstElement().name + " to " + streets.lastElement().name); metadata.appendChild(name); for (TurnByTurnStreet street : streets) { Element trk = dom.createElement("trk"); gpx.appendChild(trk); Element trkName = dom.createElement("name"); trkName.setTextContent(street.name); trk.appendChild(trkName); Element trkseg = dom.createElement("trkseg"); trk.appendChild(trkseg); for (GeoCoordinate c : street.points) { Element trkpt = dom.createElement("trkpt"); trkseg.appendChild(trkpt); trkpt.setAttribute("lat", Double.toString(c.getLatitude())); trkpt.setAttribute("lon", Double.toString(c.getLongitude())); } Element extensions = dom.createElement("extensions"); trkseg.appendChild(extensions); Element length = dom.createElement("mf:Length"); extensions.appendChild(length); length.setTextContent(Double.toString(street.length)); Element angle = dom.createElement("mf:AngleToPreviousStreet"); extensions.appendChild(angle); angle.setTextContent(Double.toString(street.angleFromStreetLastStreet)); } // This is for turning the DOM object into a proper StringWriter StringWriter stringWriter = new StringWriter(); TransformerFactory.newInstance().newTransformer().transform(new DOMSource(dom), new StreamResult(stringWriter)); return stringWriter.getBuffer().toString(); }
From source file:org.opendatakit.services.utilities.EncryptionUtils.java
private static boolean writeSubmissionManifest(EncryptedFormInformation formInfo, File submissionXml, File submissionXmlEnc, List<MimeFile> mediaFiles) { FileOutputStream out = null;//from w ww . j a v a 2s . c o m try { DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); DocumentBuilder db = dbf.newDocumentBuilder(); Document d = db.newDocument(); d.setXmlStandalone(true); Element e = d.createElementNS(XML_ENCRYPTED_TAG_NAMESPACE, DATA); e.setPrefix(null); e.setAttribute(ID, formInfo.tableId); e.setAttribute(ENCRYPTED, "yes"); d.appendChild(e); Element c; c = d.createElementNS(XML_ENCRYPTED_TAG_NAMESPACE, BASE64_ENCRYPTED_KEY); Text txtNode; txtNode = d.createTextNode(formInfo.base64RsaEncryptedSymmetricKey); c.appendChild(txtNode); e.appendChild(c); c = d.createElementNS(XML_OPENROSA_NAMESPACE, META); c.setPrefix("orx"); { Element instanceTag = d.createElementNS(XML_OPENROSA_NAMESPACE, INSTANCE_ID); txtNode = d.createTextNode(formInfo.instanceId); instanceTag.appendChild(txtNode); c.appendChild(instanceTag); } e.appendChild(c); for (MimeFile file : mediaFiles) { c = d.createElementNS(XML_ENCRYPTED_TAG_NAMESPACE, MEDIA); Element fileTag = d.createElementNS(XML_ENCRYPTED_TAG_NAMESPACE, FILE); txtNode = d.createTextNode(file.file.getName()); fileTag.appendChild(txtNode); c.appendChild(fileTag); e.appendChild(c); } c = d.createElementNS(XML_ENCRYPTED_TAG_NAMESPACE, ENCRYPTED_XML_FILE); txtNode = d.createTextNode(submissionXmlEnc.getName()); c.appendChild(txtNode); e.appendChild(c); c = d.createElementNS(XML_ENCRYPTED_TAG_NAMESPACE, BASE64_ENCRYPTED_ELEMENT_SIGNATURE); txtNode = d.createTextNode(formInfo.getBase64EncryptedElementSignature()); c.appendChild(txtNode); e.appendChild(c); out = new FileOutputStream(submissionXml); TransformerFactory factory = TransformerFactory.newInstance(); Transformer transformer = factory.newTransformer(); Properties outFormat = new Properties(); outFormat.setProperty(OutputKeys.INDENT, "no"); outFormat.setProperty(OutputKeys.METHOD, "xml"); outFormat.setProperty(OutputKeys.OMIT_XML_DECLARATION, "yes"); outFormat.setProperty(OutputKeys.VERSION, "1.0"); outFormat.setProperty(OutputKeys.ENCODING, "UTF-8"); transformer.setOutputProperties(outFormat); DOMSource domSource = new DOMSource(d.getDocumentElement()); StreamResult result = new StreamResult(out); transformer.transform(domSource, result); out.flush(); out.close(); } catch (FileNotFoundException ex) { WebLogger.getLogger(formInfo.appName).printStackTrace(ex); WebLogger.getLogger(formInfo.appName).e(t, "Error writing submission.xml for encrypted submission: " + submissionXml.getParentFile().getName()); return false; } catch (UnsupportedEncodingException ex) { WebLogger.getLogger(formInfo.appName).printStackTrace(ex); WebLogger.getLogger(formInfo.appName).e(t, "Error writing submission.xml for encrypted submission: " + submissionXml.getParentFile().getName()); return false; } catch (IOException ex) { WebLogger.getLogger(formInfo.appName).printStackTrace(ex); WebLogger.getLogger(formInfo.appName).e(t, "Error writing submission.xml for encrypted submission: " + submissionXml.getParentFile().getName()); return false; } catch (TransformerConfigurationException ex) { WebLogger.getLogger(formInfo.appName).printStackTrace(ex); WebLogger.getLogger(formInfo.appName).e(t, "Error writing submission.xml for encrypted submission: " + submissionXml.getParentFile().getName()); return false; } catch (TransformerException ex) { WebLogger.getLogger(formInfo.appName).printStackTrace(ex); WebLogger.getLogger(formInfo.appName).e(t, "Error writing submission.xml for encrypted submission: " + submissionXml.getParentFile().getName()); return false; } catch (ParserConfigurationException ex) { WebLogger.getLogger(formInfo.appName).printStackTrace(ex); WebLogger.getLogger(formInfo.appName).e(t, "Error writing submission.xml for encrypted submission: " + submissionXml.getParentFile().getName()); return false; } finally { if (out != null) { try { out.close(); } catch (IOException e) { // ignore } } } return true; }
From source file:org.ow2.proactive.scheduler.common.job.factories.Job2XMLTransformer.java
/** * Creates the xml representation of the job in argument * * @throws TransformerException/*from w w w . j a v a2 s . c o m*/ * @throws ParserConfigurationException */ public InputStream jobToxml(TaskFlowJob job) throws TransformerException, ParserConfigurationException { DocumentBuilderFactory dbfac = DocumentBuilderFactory.newInstance(); DocumentBuilder docBuilder = dbfac.newDocumentBuilder(); Document doc = docBuilder.newDocument(); doc.setXmlStandalone(true); // create the xml tree corresponding to this job Element rootJob = createRootJobElement(doc, job); doc.appendChild(rootJob); // set up a transformer TransformerFactory transfac = TransformerFactory.newInstance(); Transformer trans = transfac.newTransformer(); trans.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "no"); trans.setOutputProperty(OutputKeys.INDENT, "yes"); // If the encoding property is set on the client JVM, use it (it has to match the server-side encoding), // otherwise use UTF-8 if (PASchedulerProperties.FILE_ENCODING.isSet()) { trans.setOutputProperty(OutputKeys.ENCODING, PASchedulerProperties.FILE_ENCODING.getValueAsString()); } else { trans.setOutputProperty(OutputKeys.ENCODING, "UTF-8"); } trans.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2"); // write the xml ByteArrayOutputStream baos = new ByteArrayOutputStream(); StreamResult result = new StreamResult(baos); DOMSource source = new DOMSource(doc); trans.transform(source, result); byte[] array = baos.toByteArray(); return new ByteArrayInputStream(array); }