Java Code Examples for javax.xml.transform.dom.DOMSource
The following code examples are extracted from open source projects. You can click to
vote up the examples that are useful to you.
Example 1
From project bpelunit, under directory /tycho/net.bpelunit.toolsupport/src/net/bpelunit/toolsupport/util/schema/.
Source file: WSDLParser.java

/** * Creates a StringReader for the passed Element. * @param element * @return * @throws TransformerFactoryConfigurationError * @throws TransformerConfigurationException * @throws TransformerException */ private StringReader getStringReaderFromElement(org.w3c.dom.Element element) throws TransformerFactoryConfigurationError, TransformerConfigurationException, TransformerException { DOMSource source=new DOMSource(element); StringWriter stringWriter=new StringWriter(); Result result=new StreamResult(stringWriter); TransformerFactory factory=TransformerFactory.newInstance(); Transformer transformer=factory.newTransformer(); transformer.transform(source,result); StringReader stringReader=new StringReader(stringWriter.getBuffer().toString()); return stringReader; }
Example 2
From project cloudify, under directory /esc/src/main/java/org/cloudifysource/esc/driver/provisioning/azure/client/.
Source file: MicrosoftAzureModelUtils.java

private static String getStringFromDocument(final Document doc) throws MicrosoftAzureException { try { DOMSource domSource=new DOMSource(doc); StringWriter writer=new StringWriter(); StreamResult result=new StreamResult(writer); TransformerFactory tf=TransformerFactory.newInstance(); Transformer transformer=tf.newTransformer(); transformer.transform(domSource,result); return writer.toString(); } catch ( TransformerException ex) { throw new MicrosoftAzureException(ex); } }
Example 3
From project components, under directory /soap/src/test/java/org/switchyard/component/soap/.
Source file: SOAPGatewayTest.java

private String toString(Node node) throws Exception { TransformerFactory transFactory=TransformerFactory.newInstance(); Transformer transformer=transFactory.newTransformer(); StringWriter sw=new StringWriter(); DOMSource source=new DOMSource(node); StreamResult result=new StreamResult(sw); transformer.transform(source,result); return sw.toString(); }
Example 4
From project core_1, under directory /common/src/main/java/org/switchyard/common/xml/.
Source file: XMLHelper.java

/** * Compare two DOM Nodes. * @param node1 The first Node. * @param node2 The second Node. * @return true if equals, false otherwise. * @throws ParserConfigurationException Parser confiuration exception * @throws TransformerException Transformer exception * @throws SAXException SAX exception * @throws IOException If unable to read the stream */ public static boolean compareXMLContent(final Node node1,final Node node2) throws ParserConfigurationException, TransformerException, SAXException, IOException { TransformerFactory transFactory=TransformerFactory.newInstance(); Transformer transformer=transFactory.newTransformer(); StringWriter writer1=new StringWriter(); StringWriter writer2=new StringWriter(); DOMSource source=new DOMSource(node1); StreamResult result=new StreamResult(writer1); transformer.transform(source,result); source=new DOMSource(node2); result=new StreamResult(writer2); transformer.transform(source,result); return compareXMLContent(writer1.toString(),writer2.toString()); }
Example 5
From project echo2, under directory /src/exampleapp/chatserver/src/java/echo2example/chatserver/.
Source file: ChatServerServlet.java

/** * Renders the response DOM document to the <code>HttpServletResponse</code>. * @param response the outgoing <code>HttpServletResponse</code> * @param responseDocument the response DOM document */ private void renderResponseDocument(HttpServletResponse response,Document responseDocument) throws IOException { response.setContentType("text/xml; charset=UTF-8"); try { TransformerFactory tFactory=TransformerFactory.newInstance(); Transformer transformer=tFactory.newTransformer(); DOMSource source=new DOMSource(responseDocument); StreamResult result=new StreamResult(response.getWriter()); transformer.transform(source,result); } catch ( TransformerException ex) { throw new IOException("Unable to write document to OutputStream: " + ex.toString()); } }
Example 6
From project echo3, under directory /src/server-java/app/nextapp/echo/app/util/.
Source file: DomUtil.java

/** * Work method for public save() methods. */ private static void saveImpl(Document document,StreamResult output,Properties outputProperties) throws SAXException { try { TransformerFactory tFactory=getTransformerFactory(); Transformer transformer=tFactory.newTransformer(); if (outputProperties != null) { transformer.setOutputProperties(outputProperties); } DOMSource source=new DOMSource(document); transformer.transform(source,output); } catch ( TransformerException ex) { throw new SAXException("Unable to write document to OutputStream.",ex); } }
Example 7
From project Guit, under directory /src/main/java/com/guit/junit/dom/.
Source file: ElementMock.java

public static String getOuterXml(Node n) throws ParserConfigurationException, TransformerFactoryConfigurationError, TransformerException { Transformer xformer=TransformerFactory.newInstance().newTransformer(); xformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION,"yes"); StreamResult result=new StreamResult(new StringWriter()); DOMSource source=new DOMSource(n); xformer.transform(source,result); String xmlString=result.getWriter().toString(); return xmlString; }
Example 8
From project hbasene, under directory /src/main/java/org/hbasene/index/create/.
Source file: IndexConfiguration.java

public void write(OutputStream out){ try { Document doc=writeDocument(); DOMSource source=new DOMSource(doc); StreamResult result=new StreamResult(out); TransformerFactory transFactory=TransformerFactory.newInstance(); Transformer transformer=transFactory.newTransformer(); transformer.transform(source,result); } catch ( Exception e) { throw new RuntimeException(e); } }
Example 9
From project jcr-openofficeplugin, under directory /src/main/java/org/exoplatform/applications/ooplugin/client/.
Source file: DavCommand.java

private void serializeElement(Element element) throws Exception { TransformerFactory transformerFactory=TransformerFactory.newInstance(); Transformer transformer=transformerFactory.newTransformer(); DOMSource source=new DOMSource(element.getOwnerDocument()); ByteArrayOutputStream outStream=new ByteArrayOutputStream(); StreamResult resultStream=new StreamResult(outStream); transformer.transform(source,resultStream); requestDataBytes=outStream.toByteArray(); }
Example 10
From project lenya, under directory /org.apache.lenya.core.impl/src/main/java/org/apache/lenya/xml/.
Source file: DocumentHelper.java

/** * Writes a document to a file. A new file is created if it does not exist. * @param document The document to save. * @param file The file to save the document to. * @throws IOException if an error occurs * @throws TransformerConfigurationException if an error occurs * @throws TransformerException if an error occurs */ public static void writeDocument(Document document,File file) throws TransformerConfigurationException, TransformerException, IOException { if (document == null) throw new IllegalArgumentException("illegal usage, parameter document may not be null"); if (file == null) throw new IllegalArgumentException("illegal usage, parameter file may not be null"); file.getParentFile().mkdirs(); file.createNewFile(); DOMSource source=new DOMSource(document); StreamResult result=new StreamResult(file); getTransformer(document.getDoctype()).transform(source,result); }
Example 11
From project Maimonides, under directory /src/com/codeko/apps/maimonides/seneca/.
Source file: GeneradorFicherosSeneca.java

private String docToString(Document doc) throws TransformerException { StringWriter sw=new StringWriter(); StreamResult result=new StreamResult(sw); DOMSource source=new DOMSource(doc); getTransformer().transform(source,result); String contenido=sw.toString(); Obj.cerrar(sw); source=null; result=null; return contenido; }
Example 12
From project miso-lims, under directory /core/src/main/java/uk/ac/bbsrc/tgac/miso/core/util/.
Source file: SubmissionUtils.java

/** * Transforms a DOM Document into a file on disk * @param fromDocument the Document to use as the source * @param toPath the destination file path represented as a String * @throws java.io.IOException * @throws javax.xml.transform.TransformerException */ public static void transform(Document fromDocument,File toPath) throws TransformerException, IOException { Transformer transformer=TransformerFactory.newInstance().newTransformer(); transformer.setOutputProperty(OutputKeys.INDENT,"yes"); DOMSource source=new DOMSource(fromDocument); StreamResult result=new StreamResult(new BufferedWriter(new FileWriter(toPath))); transformer.transform(source,result); }
Example 13
From project Mockey, under directory /src/java/com/mockey/storage/xml/.
Source file: MockeyXmlFactory.java

private String getDocumentAsString(Document document) throws IOException, TransformerException { Transformer transformer=TransformerFactory.newInstance().newTransformer(); transformer.setOutputProperty(OutputKeys.INDENT,"yes"); transformer.setOutputProperty(OutputKeys.METHOD,"xml"); transformer.setOutputProperty(OutputKeys.ENCODING,HTTP.UTF_8); StreamResult result=new StreamResult(new StringWriter()); DOMSource source=new DOMSource(document); transformer.transform(source,result); return result.getWriter().toString(); }
Example 14
From project ndg, under directory /ndg-commons-core/src/main/java/br/org/indt/ndg/common/.
Source file: ResultWriter.java

public String write() throws ParserConfigurationException, Exception { DOMSource domSource=new DOMSource(getDocument()); StreamResult streamResult=new StreamResult(new StringWriter()); TransformerFactory tf=TransformerFactory.newInstance(); Transformer serializer=tf.newTransformer(); serializer.setOutputProperty(OutputKeys.ENCODING,Resources.ENCODING); serializer.setOutputProperty(OutputKeys.INDENT,"yes"); serializer.transform(domSource,streamResult); String xmlString=streamResult.getWriter().toString(); return xmlString; }
Example 15
From project openengsb-framework, under directory /itests/src/test/java/org/openengsb/itests/exam/.
Source file: WSPortIT.java

@Test public void testStartSimpleWorkflow_ShouldReturn42() throws Exception { Thread.currentThread().setContextClassLoader(getClass().getClassLoader()); Dispatch<DOMSource> dispatcher=createMessageDispatcher(); String secureRequest=prepareRequest(METHOD_CALL_STRING,"admin","password"); SecretKey sessionKey=generateSessionKey(); String encryptedMessage=encryptMessage(secureRequest,sessionKey); DOMSource request=convertMessageToDomSource(encryptedMessage); DOMSource response=dispatchMessage(dispatcher,request); String result=transformResponseToMessage(response); verifyEncryptedResult(sessionKey,result); }
Example 16
From project Agot-Java, under directory /src/main/java/got/utility/.
Source file: ConnectionCreate.java

/** * saveCenters() Saves the centers to disk. */ private void saveCenters(){ try { final String fileName=new FileSave("Where To Save centers.txt ?","connection.xml").getPathString(); if (fileName == null) { return; } final FileOutputStream out=new FileOutputStream(fileName); DocumentBuilderFactory docFactory=DocumentBuilderFactory.newInstance(); DocumentBuilder docBuilder=docFactory.newDocumentBuilder(); Document doc=docBuilder.newDocument(); Element rootElement=doc.createElement("Connections"); doc.appendChild(rootElement); for ( Connection conn : m_conns) { Element connection=doc.createElement("Connection"); rootElement.appendChild(connection); Attr attr=doc.createAttribute("t1"); attr.setValue(conn.start); connection.setAttributeNode(attr); Attr attr1=doc.createAttribute("t2"); attr1.setValue(conn.end); connection.setAttributeNode(attr1); } TransformerFactory transformerFactory=TransformerFactory.newInstance(); Transformer transformer=transformerFactory.newTransformer(); DOMSource source=new DOMSource(doc); StreamResult result=new StreamResult(new File(fileName)); transformer.transform(source,result); System.out.println("Data written to :" + new File(fileName).getCanonicalPath()); } catch ( final FileNotFoundException ex) { ex.printStackTrace(); } catch ( final HeadlessException ex) { ex.printStackTrace(); } catch ( final Exception ex) { ex.printStackTrace(); } }
Example 17
From project ant4eclipse, under directory /org.ant4eclipse.ant.pde/src/org/ant4eclipse/ant/pde/.
Source file: PatchFeatureManifestTask.java

/** * Replaces the given plug-in-versions in given feature.xml-File. * @param featureXml The feature.xml file. NOTE: this file will be <b>changed</b> and thus must be writable * @param qualifier The new version for this feature. If set to null, the "version"-attribute of the "feature"-tag won't be changed * @param newBundleVersions A map containing plugin-id (String) - version (String) associations * @throws Exception */ protected void replaceVersions(File featureXml,String qualifier,StringMap newBundleVersions) throws Exception { Assure.notNull("featureXml",featureXml); Assure.assertTrue(featureXml.isFile(),"featureXml (" + featureXml + ") must point to an existing file"); DocumentBuilder builder=DocumentBuilderFactory.newInstance().newDocumentBuilder(); Document featureDom=builder.parse(featureXml); if (qualifier != null) { Element featureElement=featureDom.getDocumentElement(); String featureVersion=featureElement.getAttribute("version"); if (featureVersion != null && featureVersion.endsWith(".qualifier")) { featureElement.setAttribute("version",PdeBuildHelper.resolveVersion(new Version(featureVersion),qualifier).toString()); } } NodeList pluginNodes=featureDom.getDocumentElement().getElementsByTagName("plugin"); for (int i=0; i < pluginNodes.getLength(); i++) { Element element=(Element)pluginNodes.item(i); String id=element.getAttribute("id"); if (newBundleVersions.containsKey(id)) { String version=newBundleVersions.get(id); element.setAttribute("version",version); } } DOMSource domSource=new DOMSource(featureDom); Transformer transformer=TransformerFactory.newInstance().newTransformer(); StreamResult result=new StreamResult(featureXml); transformer.transform(domSource,result); }
Example 18
From project any23, under directory /core/src/main/java/org/apache/any23/extractor/html/.
Source file: DomUtils.java

/** * Given a <i>DOM</i> {@link Node} produces the <i>XML</i> serializationomitting the <i>XML declaration</i>. * @param node node to be serialized. * @param indent if <code>true</code> the output is indented. * @return the XML serialization. * @throws TransformerException if an error occurs during theserializator initialization and activation. * @throws java.io.IOException */ public static String serializeToXML(Node node,boolean indent) throws TransformerException, IOException { final DOMSource domSource=new DOMSource(node); final Transformer transformer=TransformerFactory.newInstance().newTransformer(); transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION,"yes"); transformer.setOutputProperty(OutputKeys.METHOD,"xml"); transformer.setOutputProperty(OutputKeys.ENCODING,"UTF-8"); if (indent) { transformer.setOutputProperty(OutputKeys.INDENT,"yes"); transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount","4"); } final StringWriter sw=new StringWriter(); final StreamResult sr=new StreamResult(sw); transformer.transform(domSource,sr); sw.close(); return sw.toString(); }
Example 19
From project Archimedes, under directory /br.org.archimedes.io.xml/src/br/org/archimedes/io/xml/parsers/.
Source file: XMLParser.java

/** * Validades a XML file based on his xsd Schema * @param doc The document to be validated * @return True if the file is valid or the validator is null, false otherwise */ private boolean validadeXMLSchema(Document doc){ if (validator == null) return true; try { validator.validate(new DOMSource(doc)); } catch ( SAXException e) { e.printStackTrace(); return false; } catch ( IOException e) { e.printStackTrace(); } return true; }
Example 20
From project bioclipse.seneca, under directory /plugins/net.bioclipse.seneca/src/org/openscience/cdk/structgen/pubchem/.
Source file: PubchemStructureGenerator.java

/** * convert an XML {@link Document} into a {@link String}. * @return String containg the document. */ private static String getXMLString(Document requestDocument){ try { TransformerFactory transformerFactory=TransformerFactory.newInstance(); Transformer transformer=transformerFactory.newTransformer(); DOMSource source=new DOMSource(requestDocument); StringWriter stringWriter=new StringWriter(); StreamResult streamResult=new StreamResult(stringWriter); transformer.transform(source,streamResult); return stringWriter.toString(); } catch ( Exception e) { e.printStackTrace(); return ""; } }
Example 21
From project blacktie, under directory /blacktie-admin-services/src/main/java/org/jboss/narayana/blacktie/administration/.
Source file: BlacktieStompAdministrationService.java

String printNode(Node node){ try { TransformerFactory transfac=TransformerFactory.newInstance(); Transformer trans=transfac.newTransformer(); trans.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION,"yes"); trans.setOutputProperty(OutputKeys.INDENT,"yes"); StringWriter sw=new StringWriter(); StreamResult result=new StreamResult(sw); DOMSource source=new DOMSource(node); trans.transform(source,result); String xmlString=sw.toString(); return xmlString; } catch ( TransformerException e) { log.error(e); } return null; }
Example 22
From project blueprint-namespaces, under directory /blueprint/blueprint-core/src/main/java/org/apache/aries/blueprint/container/.
Source file: Parser.java

public void validate(Schema schema){ try { Validator validator=schema.newValidator(); for ( Document doc : this.documents) { validator.validate(new DOMSource(doc)); } } catch ( Exception e) { throw new ComponentDefinitionException("Unable to validate xml",e); } }
Example 23
From project cascading, under directory /src/xml/cascading/operation/xml/.
Source file: XPathOperation.java

protected String writeAsXML(Node node){ StringWriter stringWriter=new StringWriter(); Result result=new StreamResult(stringWriter); Source source=new DOMSource(node); try { getTransformer().transform(source,result); } catch ( TransformerException exception) { throw new OperationException("writing to xml failed",exception); } return stringWriter.toString(); }
Example 24
From project cdk, under directory /generator/src/main/java/org/richfaces/cdk/templatecompiler/model/.
Source file: ElementsHandler.java

@Override public ModelElement getElement(DOMResult rt){ Element domElement=getDomElement(rt); AnyElement element=JAXB.unmarshal(new DOMSource(domElement),AnyElement.class); String prefix=domElement.getPrefix(); QName name=new QName(domElement.getNamespaceURI(),domElement.getLocalName(),null != prefix ? prefix : XMLConstants.DEFAULT_NS_PREFIX); element.setName(name); return element; }
Example 25
From project cilia-workbench, under directory /cilia-workbench-common/src/fr/liglab/adele/cilia/workbench/common/xml/.
Source file: XMLHelpers.java

/** * Writes a document using its DOM representation. * @param document the document * @param file the file, on the local file system. * @throws CiliaException the metadata exception */ public static void writeDOM(Document document,File file) throws CiliaException { Source source=new DOMSource(document); TransformerFactory transformerFactory=TransformerFactory.newInstance(); try { Transformer xformer=transformerFactory.newTransformer(); xformer.setOutputProperty(OutputKeys.INDENT,"yes"); StreamResult result=new StreamResult(file); xformer.transform(source,result); } catch ( TransformerException e) { throw new CiliaException("XML transformer error",e); } }
Example 26
From project codjo-segmentation, under directory /codjo-segmentation-server/src/main/java/net/codjo/segmentation/server/plugin/.
Source file: PreferenceGuiHome.java

private String domToString(Document rootDocument) throws TransformerException { StringWriter writer=new StringWriter(); TransformerFactory tFactory=TransformerFactory.newInstance(); Transformer transformer=tFactory.newTransformer(new StreamSource(new StringReader("<xsl:stylesheet xmlns:xsl=\"http://www.w3.org/1999/XSL/Transform\" version=\"1.0\">" + " <xsl:output method=\"xml\" encoding=\"ISO-8859-1\"/>" + " <xsl:template match=\"/\" > <xsl:copy-of select=\".\"/> </xsl:template>"+ "</xsl:stylesheet>"))); transformer.transform(new DOMSource(rootDocument),new StreamResult(writer)); return writer.toString(); }
Example 27
From project DeuceSTM, under directory /src/test/org/deuce/benchmark/lee/.
Source file: XMLHelper.java

static void generateXMLReportSummary(boolean timeout,boolean xmlreport,double elapsed) throws TransformerFactoryConfigurationError { try { LeeRouterGlobalLock.obtainStats(null,elapsed,xmlreport); LeeRouterGlobalLock.xmlReport(doc); Element root=doc.getDocumentElement(); Element element=doc.createElement("ElapsedTime"); element.setTextContent(Double.toString(elapsed)); root.appendChild(element); element=doc.createElement("Timeout"); element.setTextContent(Boolean.toString(timeout)); root.appendChild(element); DOMSource domSource=new DOMSource(doc); TransformerFactory tf=TransformerFactory.newInstance(); Transformer transformer=tf.newTransformer(); transformer.setOutputProperty(OutputKeys.METHOD,"xml"); transformer.setOutputProperty(OutputKeys.ENCODING,"ISO-8859-1"); transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount","4"); transformer.setOutputProperty(OutputKeys.INDENT,"yes"); StringWriter sw=new StringWriter(); StreamResult sr=new StreamResult(sw); transformer.transform(domSource,sr); System.out.println(sw.toString()); } catch ( TransformerConfigurationException e) { e.printStackTrace(); } catch ( TransformerException e) { e.printStackTrace(); } }
Example 28
From project drools-chance, under directory /drools-shapes/drools-shapes-reasoner-generator/src/main/java/org/drools/semantics/builder/model/.
Source file: SemanticXSDModelImpl.java

private String compactXML(String source) throws IOException, ParserConfigurationException, SAXException, XPathExpressionException, TransformerException { DocumentBuilderFactory doxFactory=DocumentBuilderFactory.newInstance(); DocumentBuilder builder=doxFactory.newDocumentBuilder(); InputSource is=new InputSource(new StringReader(source)); Document dox=builder.parse(is); dox.normalize(); XPathFactory xpathFactory=XPathFactory.newInstance(); XPathExpression xpathExp=xpathFactory.newXPath().compile("//text()[normalize-space(.) = '']"); NodeList emptyTextNodes=(NodeList)xpathExp.evaluate(dox,XPathConstants.NODESET); for (int i=0; i < emptyTextNodes.getLength(); i++) { Node emptyTextNode=emptyTextNodes.item(i); emptyTextNode.getParentNode().removeChild(emptyTextNode); } TransformerFactory tFactory=TransformerFactory.newInstance(); tFactory.setAttribute("indent-number",new Integer(2)); Transformer transformer=tFactory.newTransformer(); transformer.setOutputProperty(OutputKeys.INDENT,"yes"); DOMSource domSrc=new DOMSource(dox); ByteArrayOutputStream baos=new ByteArrayOutputStream(); StreamResult result=new StreamResult(baos); transformer.transform(domSrc,result); return new String(baos.toByteArray()); }
Example 29
From project droolsjbpm-tools, under directory /drools-eclipse/org.guvnor.eclipse.webdav/src/kernel/org/eclipse/webdav/internal/kernel/.
Source file: DocumentMarshaler.java

public void print(Document document,Writer writer,String encoding) throws IOException { Transformer transformer=null; try { transformer=TransformerFactory.newInstance().newTransformer(); } catch ( TransformerConfigurationException e) { throw new IOException(e.getMessageAndLocation()); } catch ( TransformerFactoryConfigurationError e) { throw new IOException(e.getMessage()); } DOMSource source=new DOMSource(document); StreamResult result=new StreamResult(writer); try { transformer.transform(source,result); } catch ( TransformerException e) { throw new IOException(e.getMessageAndLocation()); } }
Example 30
From project EasySOA, under directory /easysoa-proxy/easysoa-proxy-core/easysoa-proxy-core-api/src/main/java/org/easysoa/proxy/core/api/records/assertions/.
Source file: AbstractAssertion.java

/** * Convert a Node in String * @param node The node to convert * @return The XML string representation of the node */ public String nodeToString(Node node) throws Exception { StringWriter sw=new StringWriter(); Transformer t=TransformerFactory.newInstance().newTransformer(); t.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION,"yes"); t.transform(new DOMSource(node),new StreamResult(sw)); return sw.toString(); }
Example 31
From project eclipse-integration-cloudfoundry, under directory /org.cloudfoundry.ide.eclipse.server.tests/src/org/cloudfoundry/ide/eclipse/server/tests/sts/util/.
Source file: StsTestUtil.java

public static String canocalizeXml(String originalServerXml) throws Exception { DocumentBuilderFactory documentBuilderFactory=DocumentBuilderFactory.newInstance(); DocumentBuilder builder=documentBuilderFactory.newDocumentBuilder(); Document document=builder.parse(new InputSource(new StringReader(originalServerXml))); document.normalize(); TransformerFactory factory=TransformerFactory.newInstance(); Transformer transformer=factory.newTransformer(); StringWriter writer=new StringWriter(); transformer.setOutputProperty(OutputKeys.INDENT,"yes"); transformer.transform(new DOMSource(document.getDocumentElement()),new StreamResult(writer)); return writer.toString().replace("\\s+\\n","\\n"); }
Example 32
From project eclipse-integration-commons, under directory /org.springsource.ide.eclipse.commons.content.core/src/org/springsource/ide/eclipse/commons/content/core/util/.
Source file: DescriptorReader.java

public void write(File file) throws CoreException { DocumentBuilder documentBuilder=ContentUtil.createDocumentBuilder(); Transformer serializer=ContentUtil.createTransformer(); Document document=documentBuilder.newDocument(); writeDocument(document); DOMSource source=new DOMSource(document); try { StreamResult target=new StreamResult(file); serializer.setOutputProperty(OutputKeys.INDENT,"yes"); serializer.transform(source,target); } catch ( TransformerException e) { throw new CoreException(new Status(Status.ERROR,ContentPlugin.PLUGIN_ID,"Could not write initialization data for tutorial")); } }
Example 33
From project ElasticSearchExample, under directory /src/main/java/de/jetwick/ese/util/.
Source file: Helper.java

public static String getDocumentAsString(Node node,boolean prettyXml) throws TransformerException, UnsupportedEncodingException { Transformer transformer=TransformerFactory.newInstance().newTransformer(); if (prettyXml) { transformer.setOutputProperty(OutputKeys.INDENT,"yes"); } transformer.setOutputProperty(OutputKeys.ENCODING,"UTF-8"); ByteArrayOutputStream baos=new ByteArrayOutputStream(); transformer.transform(new DOMSource(node),new StreamResult(baos)); return baos.toString("UTF-8"); }
Example 34
From project emite, under directory /src/main/java/com/calclab/emite/base/xml/.
Source file: XMLPacketImpl.java

@Override public String toString(){ try { final StringWriter buffer=new StringWriter(); transformer.transform(new DOMSource(element),new StreamResult(buffer)); return buffer.toString(); } catch ( final TransformerException e) { throw new InternalError("Transformer error"); } }
Example 35
From project empire-db, under directory /empire-db/src/main/java/org/apache/empire/xml/.
Source file: XMLWriter.java

/** * Prints out the DOM-Tree. The file will be truncated if it exists or created if if does not exist. * @param doc The XML-Document to print * @param filename The name of the file to write the XML-Document to */ public static void saveAsFile(Document doc,String filename){ try { File file=new File(filename); if (file.exists() == true) { file.delete(); } DOMSource domSource=new DOMSource(doc); StreamResult streamResult=new StreamResult(file); TransformerFactory transformerFactory=TransformerFactory.newInstance(); Transformer trf=transformerFactory.newTransformer(); trf.transform(domSource,streamResult); } catch ( Exception ex) { log.error("Error: Could not write XML to file: " + filename); } }
Example 36
From project Euclidean-Pattern-Generator, under directory /src/com/hisschemoller/sequencer/controller/file/.
Source file: SaveProjectCommand.java

private void printXML(Document document){ try { TransformerFactory transFactory=TransformerFactory.newInstance(); Transformer transformer=transFactory.newTransformer(); transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION,"yes"); transformer.setOutputProperty(OutputKeys.INDENT,"yes"); StringWriter stringWriter=new StringWriter(); StreamResult result=new StreamResult(stringWriter); DOMSource source=new DOMSource(document); transformer.transform(source,result); String xmlString=stringWriter.toString(); System.out.println("Here's the xml:\n\n" + xmlString); } catch ( Exception exception) { showMessage("SaveProjectCommand.printXML() Exception: " + exception.getMessage()); } }
Example 37
public static String xmlNodeToString(Node node) throws Exception { Source source=new DOMSource(node); StringWriter stringWriter=new StringWriter(); Result result=new StreamResult(stringWriter); TransformerFactory factory=TransformerFactory.newInstance(); Transformer transformer=factory.newTransformer(); transformer.setOutputProperty(OutputKeys.INDENT,"yes"); transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount","2"); transformer.transform(source,result); return stringWriter.getBuffer().toString(); }
Example 38
From project Flapi, under directory /src/test/java/unquietcode/tools/flapi/examples/xhtml/.
Source file: XHTMLBuilderExample.java

private void printDocument(Document doc){ try { Transformer transformer=TransformerFactory.newInstance().newTransformer(); transformer.setOutputProperty(OutputPropertiesFactory.S_KEY_INDENT_AMOUNT,"4"); transformer.setOutputProperty(OutputKeys.INDENT,"yes"); transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION,"yes"); System.out.println(); transformer.transform(new DOMSource(doc),new StreamResult(System.out)); } catch ( Exception ex) { throw new RuntimeException(ex); } }
Example 39
From project flyingsaucer, under directory /flying-saucer-examples/src/main/java/org/xhtmlrenderer/demo/browser/.
Source file: ViewSourceAction.java

public void actionPerformed(ActionEvent evt){ TransformerFactory tfactory=TransformerFactory.newInstance(); Transformer serializer; try { serializer=tfactory.newTransformer(); serializer.setOutputProperty(OutputKeys.INDENT,"yes"); serializer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount","2"); Element document=panel.getRootBox().getElement(); DOMSource source=new DOMSource(document); StreamResult output=new StreamResult(System.out); serializer.transform(source,output); } catch ( TransformerException ex) { ex.printStackTrace(); throw new RuntimeException(ex); } }
Example 40
From project gatein-common, under directory /common/src/main/java/org/gatein/common/xml/.
Source file: XMLTools.java

/** * Converts an document to a String representation. */ private static String toString(Document doc,Properties format) throws TransformerException { Transformer transformer=TransformerFactory.newInstance().newTransformer(); transformer.setOutputProperties(format); StringWriter writer=new StringWriter(); Source source=new DOMSource(doc); Result result=new StreamResult(writer); transformer.transform(source,result); return writer.toString(); }
Example 41
From project GnucashMobile, under directory /GnucashMobile/src/org/gnucash/android/ui/accounts/.
Source file: ExportDialogFragment.java

/** * Writes out the file held in <code>document</code> to <code>outputWriter</code> * @param document {@link Document} containing the OFX document structure * @param outputWriter {@link Writer} to use in writing the file to stream */ public void write(Document document,Writer outputWriter){ try { TransformerFactory transformerFactory=TransformerFactory.newInstance(); Transformer transformer=transformerFactory.newTransformer(); DOMSource source=new DOMSource(document); StreamResult result=new StreamResult(outputWriter); transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount","2"); transformer.setOutputProperty(OutputKeys.INDENT,"yes"); transformer.transform(source,result); } catch ( TransformerConfigurationException txconfigException) { txconfigException.printStackTrace(); } catch ( TransformerException tfException) { tfException.printStackTrace(); } }
Example 42
From project grails-ide, under directory /org.grails.ide.eclipse.core/src/org/grails/ide/eclipse/core/model/.
Source file: GrailsInstallManager.java

private void save(Document document){ try { IPath grailsInstallFile=GrailsCoreActivator.getDefault().getStateLocation().append("grails.installs"); TransformerFactory transformerFactory=TransformerFactory.newInstance(); Transformer transformer=transformerFactory.newTransformer(); transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION,"no"); transformer.setOutputProperty(OutputKeys.INDENT,"yes"); transformer.setOutputProperty(OutputKeys.ENCODING,"ISO-8859-1"); Writer out=new OutputStreamWriter(new FileOutputStream(grailsInstallFile.toFile()),"ISO-8859-1"); StreamResult result=new StreamResult(out); DOMSource source=new DOMSource(document); transformer.transform(source,result); out.close(); } catch ( IOException e) { GrailsCoreActivator.log(e); } catch ( TransformerException e) { GrailsCoreActivator.log(e); } }
Example 43
From project integration-tests, under directory /picketlink-openid-tests/src/test/java/org/picketlink/test/integration/openid/.
Source file: OpenIDConsumerUnitTestCase.java

protected void write(HtmlPage page) throws Exception { Document doc=page; Source source=new DOMSource(doc); StringWriter sw=new StringWriter(); Result streamResult=new StreamResult(sw); Transformer transformer=TransformerFactory.newInstance().newTransformer(); transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION,"yes"); transformer.setOutputProperty(OutputKeys.INDENT,"no"); transformer.transform(source,streamResult); System.out.println(sw.toString()); }
Example 44
From project interoperability-framework, under directory /interfaces/web/generic-soap-client/src/main/java/eu/impact_project/wsclient/generic/.
Source file: WsdlDocument.java

private InputStream prepareSchema(Element el) throws TransformerException { @SuppressWarnings("unchecked") Map<String,String> namespaces=wsdlObject.getNamespaces(); for ( Map.Entry<String,String> ns : namespaces.entrySet()) { if (!ns.getKey().equals("")) el.setAttribute("xmlns:" + ns.getKey(),ns.getValue()); } String url=wsdlUrl.toString(); String contextUrl=url.substring(0,url.lastIndexOf("/") + 1); NodeList imports=el.getElementsByTagNameNS("http://www.w3.org/2001/XMLSchema","import"); for (int i=0; i < imports.getLength(); i++) { Element currentImport=(Element)imports.item(i); String location=currentImport.getAttribute("schemaLocation"); boolean isAbsolute=location.startsWith("http"); if (!isAbsolute) { currentImport.setAttribute("schemaLocation",contextUrl + location); } } TransformerFactory tFactory=TransformerFactory.newInstance(); Transformer transformer=tFactory.newTransformer(); OutputStream os=new ByteArrayOutputStream(); DOMSource source=new DOMSource(el); StreamResult result=new StreamResult(os); transformer.transform(source,result); String temp=os.toString(); return new ByteArrayInputStream(temp.getBytes()); }
Example 45
From project iserve, under directory /iserve-parent/iserve-importer-hrests/src/main/java/uk/ac/open/kmi/iserve/importer/hrests/.
Source file: HrestsImporter.java

@Override protected InputStream transformStream(String serviceDescription) throws ImporterException { Document document=parser.parseDOM(new ByteArrayInputStream(serviceDescription.getBytes()),null); DOMSource source=new DOMSource(document); ByteArrayOutputStream bout=new ByteArrayOutputStream(); StreamResult result=new StreamResult(bout); try { transformer.transform(source,result); } catch ( TransformerException e) { throw new ImporterException(e); } if (null == result.getOutputStream()) return null; String resultString=result.getOutputStream().toString(); return new ByteArrayInputStream(resultString.getBytes()); }
Example 46
From project jangaroo-tools, under directory /asdoc-scraping/src/main/java/net/jangaroo/tools/asdocscreenscraper/.
Source file: ASDocScreenScraper.java

private static Document loadAndParse(URI url) throws TransformerException, ParserConfigurationException, SAXException, IOException { Document document=TIDY.parseDOM(new BufferedInputStream(url.toURL().openStream()),null); DOMSource domSource=new DOMSource(document.getDocumentElement()); Transformer serializer=TransformerFactory.newInstance().newTransformer(); serializer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION,"no"); serializer.setOutputProperty(OutputKeys.ENCODING,"UTF-8"); serializer.setOutputProperty(OutputKeys.DOCTYPE_PUBLIC,"-//W3C//DTD XHTML 1.0 Transitional//EN"); String localXHtmlDoctype=new File(".").getAbsoluteFile().toURI().toString() + "xhtml1/DTD/xhtml1-transitional.dtd"; serializer.setOutputProperty(OutputKeys.DOCTYPE_SYSTEM,localXHtmlDoctype); StringWriter result=new StringWriter(); serializer.transform(domSource,new StreamResult(result)); String xhtmlText=result.toString(); xhtmlText=xhtmlText.replaceAll(" id=\"(pageFilter|propertyDetail)\"",""); DocumentBuilderFactory domFactory=DocumentBuilderFactory.newInstance(); domFactory.setValidating(false); domFactory.setNamespaceAware(true); DocumentBuilder builder=domFactory.newDocumentBuilder(); return builder.parse(new InputSource(new StringReader(xhtmlText))); }
Example 47
From project jASM_16, under directory /src/main/java/de/codesourcery/jasm16/ide/.
Source file: ProjectConfiguration.java

private void writeXML(Document doc,File file) throws TransformerFactoryConfigurationError, TransformerException { final Source source=new DOMSource(doc); final Result result=new StreamResult(file); final Transformer xformer=TransformerFactory.newInstance().newTransformer(); xformer.transform(source,result); }
Example 48
From project jbpmmigration, under directory /src/main/java/org/jbpm/migration/.
Source file: XmlUtils.java

/** * Write an XML document (formatted) to a given <code>File</code>. * @param input The input XML document. * @param output The intended <code>File</code>. */ public static void writeFile(final Document input,final File output){ final StreamResult result=new StreamResult(new StringWriter()); format(new DOMSource(input),result); try { new FileWriter(output).write(result.getWriter().toString()); } catch ( final IOException ioEx) { LOGGER.error("Problem writing XML to file.",ioEx); } }
Example 49
From project jCAE, under directory /amibe/src/org/jcae/mesh/xmldata/.
Source file: XMLReader.java

public void read(File in) throws SAXException, IOException { Document dom=createDocument(in); if (getXSD() != null) getValidator().validate(new DOMSource(dom)); try { read(dom); } catch ( XPathExpressionException ex) { LOGGER.log(Level.SEVERE,ex.getMessage(),ex); } }
Example 50
From project jdeltasync, under directory /src/main/java/com/googlecode/jdeltasync/.
Source file: XmlUtil.java

/** * Writes the specified {@link Document} to an {@link OutputStream} in the specified format. * @param doc the {@link Document}. * @param out the stream to write to. * @param compact if <code>true</code> the XML will be written in compactformat without any extra whitespaces. * @throws XmlException on XML errors. */ public static void writeDocument(Document doc,OutputStream out,boolean compact) throws XmlException { try { TransformerFactory tf=TransformerFactory.newInstance(); Transformer serializer=tf.newTransformer(); serializer.setOutputProperty(OutputKeys.ENCODING,"UTF-8"); serializer.setOutputProperty(OutputKeys.INDENT,compact ? "no" : "yes"); serializer.transform(new DOMSource(doc),new StreamResult(out)); } catch ( TransformerException e) { throw new XmlException(e); } }
Example 51
From project jentrata-msh, under directory /Commons/src/main/java/hk/hku/cecid/piazza/commons/util/.
Source file: PropertyTree.java

/** * Creates a new instance of PropertyTree. * @param node the root node of the properties source. * @throws ComponentException if the properties could not be constructed from the specified node. */ public PropertyTree(org.w3c.dom.Node node) throws ComponentException { try { TransformerFactory factory=TransformerFactory.newInstance(); Transformer transformer=factory.newTransformer(); ByteArrayOutputStream baos=new ByteArrayOutputStream(); transformer.transform(new DOMSource(node),new StreamResult(baos)); dom=new SAXReader().read(new ByteArrayInputStream(baos.toByteArray())); } catch ( Exception e) { throw new ComponentException("Unable to construct from the given node",e); } }
Example 52
From project jetty-project, under directory /jetty-jboss/src/main/java/org/jboss/jetty/.
Source file: Jetty.java

/** * @param configElement XML fragment from jboss-service.xml */ public void setConfigurationElement(Element configElement){ _configElement=configElement; try { DOMSource source=new DOMSource(configElement); CharArrayWriter writer=new CharArrayWriter(); StreamResult result=new StreamResult(writer); TransformerFactory factory=TransformerFactory.newInstance(); Transformer transformer=factory.newTransformer(); transformer.transform(source,result); _xmlConfigString=writer.toString(); int index=_xmlConfigString.indexOf("?>"); if (index >= 0) { index+=2; while ((_xmlConfigString.charAt(index) == '\n') || (_xmlConfigString.charAt(index) == '\r')) index++; } _xmlConfigString=_xmlConfigString.substring(index); if (_log.isDebugEnabled()) _log.debug("Passing xml config to jetty:\n" + _xmlConfigString); setXMLConfiguration(_xmlConfigString); } catch ( TransformerConfigurationException tce) { _log.error("Can't transform config Element -> xml:",tce); } catch ( TransformerException te) { _log.error("Can't transform config Element -> xml:",te); } catch ( Exception e) { _log.error("Unexpected exception converting configuration Element -> xml",e); } }
Example 53
public static String getDocumentAsString(Node node,boolean prettyXml) throws TransformerException, UnsupportedEncodingException { Transformer transformer=TransformerFactory.newInstance().newTransformer(); if (prettyXml) { transformer.setOutputProperty(OutputKeys.INDENT,"yes"); } transformer.setOutputProperty(OutputKeys.ENCODING,"UTF-8"); ByteArrayOutputStream baos=new ByteArrayOutputStream(); transformer.transform(new DOMSource(node),new StreamResult(baos)); return baos.toString("UTF-8"); }
Example 54
/** * Returns a string that represents the given node. * @param node Node to return the XML for. * @return Returns an XML string. */ public static String getXml(Node node){ try { Transformer tf=TransformerFactory.newInstance().newTransformer(); tf.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION,"yes"); tf.setOutputProperty(OutputKeys.ENCODING,"UTF-8"); StreamResult dest=new StreamResult(new StringWriter()); tf.transform(new DOMSource(node),dest); return dest.getWriter().toString(); } catch ( Exception e) { } return ""; }
Example 55
From project jmeter-components, under directory /src/main/java/com/atlantbh/jmeter/plugins/xmlformatter/.
Source file: XMLFormatPostProcessor.java

public String serialize2(String unformattedXml) throws Exception { final Document document=XmlUtil.stringToXml(unformattedXml); TransformerFactory tfactory=TransformerFactory.newInstance(); StringWriter buffer=new StringWriter(); Transformer serializer=tfactory.newTransformer(); serializer.setOutputProperty(OutputKeys.INDENT,"yes"); serializer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount","2"); serializer.transform(new DOMSource(document),new StreamResult(buffer)); return buffer.toString(); }
Example 56
@Override public final <T>List<T> unmarshal(Class<T> type){ List<T> result=new ArrayList<T>(); for ( Element element : elements) { result.add(JAXB.unmarshal(new DOMSource(element),type)); } return result; }
Example 57
From project jSCSI, under directory /bundles/initiator/src/main/java/org/jscsi/initiator/.
Source file: Configuration.java

/** * Reads the given configuration file in memory and creates a DOM representation. * @throws SAXException If this operation is supported but failed for some reason. * @throws ParserConfigurationException If a <code>DocumentBuilder</code> cannot be created which satisfies the configuration requested. * @throws IOException If any IO errors occur. */ private final Document parse(final File schemaLocation,final File configFile) throws ConfigurationException { try { final SchemaFactory schemaFactory=SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI); final Schema schema=schemaFactory.newSchema(schemaLocation); final Validator validator=schema.newValidator(); final DocumentBuilderFactory domFactory=DocumentBuilderFactory.newInstance(); domFactory.setNamespaceAware(true); final DocumentBuilder builder=domFactory.newDocumentBuilder(); final Document doc=builder.parse(configFile); final DOMSource source=new DOMSource(doc); final DOMResult result=new DOMResult(); validator.validate(source,result); return (Document)result.getNode(); } catch ( final SAXException exc) { throw new ConfigurationException(exc); } catch ( final ParserConfigurationException exc) { throw new ConfigurationException(exc); } catch ( final IOException exc) { throw new ConfigurationException(exc); } }
Example 58
From project jumpnevolve, under directory /lib/slick/src/org/newdawn/slick/particles/.
Source file: ParticleIO.java

/** * Save a particle system with only ConfigurableEmitters in to an XML file * @param out The location to which we'll save * @param system The system to store * @throws IOException Indicates a failure to save or encode the system XML. */ public static void saveConfiguredSystem(OutputStream out,ParticleSystem system) throws IOException { try { DocumentBuilder builder=DocumentBuilderFactory.newInstance().newDocumentBuilder(); Document document=builder.newDocument(); Element root=document.createElement("system"); root.setAttribute("additive","" + (system.getBlendingMode() == ParticleSystem.BLEND_ADDITIVE)); root.setAttribute("points","" + (system.usePoints())); document.appendChild(root); for (int i=0; i < system.getEmitterCount(); i++) { ParticleEmitter current=system.getEmitter(i); if (current instanceof ConfigurableEmitter) { Element element=emitterToElement(document,(ConfigurableEmitter)current); root.appendChild(element); } else { throw new RuntimeException("Only ConfigurableEmitter instances can be stored"); } } Result result=new StreamResult(new OutputStreamWriter(out,"utf-8")); DOMSource source=new DOMSource(document); TransformerFactory factory=TransformerFactory.newInstance(); Transformer xformer=factory.newTransformer(); xformer.setOutputProperty(OutputKeys.INDENT,"yes"); xformer.transform(source,result); } catch ( Exception e) { Log.error(e); throw new IOException("Unable to save configured particle system"); } }
Example 59
/** * save dom into ouputstream * @param os * @param e */ public static void saveDom(OutputStream os,Element e){ DOMSource source=new DOMSource(e); TransformerFactory transFactory=TransformerFactory.newInstance(); Transformer transformer; try { transformer=transFactory.newTransformer(); transformer.setOutputProperty("indent","yes"); StreamResult result=new StreamResult(os); transformer.transform(source,result); os.flush(); } catch ( UnsupportedEncodingException e1) { e1.printStackTrace(LogUtil.getWarnStream(LOG)); } catch ( IOException e1) { e1.printStackTrace(LogUtil.getWarnStream(LOG)); } catch ( TransformerConfigurationException e2) { e2.printStackTrace(LogUtil.getWarnStream(LOG)); } catch ( TransformerException ex) { ex.printStackTrace(LogUtil.getWarnStream(LOG)); } }
Example 60
From project karaf, under directory /deployer/blueprint/src/test/java/org/apache/karaf/deployer/blueprint/.
Source file: BlueprintDeploymentListenerTest.java

public void testPackagesExtraction() throws Exception { BlueprintDeploymentListener l=new BlueprintDeploymentListener(); File f=new File(getClass().getClassLoader().getResource("test.xml").toURI()); Set<String> pkgs=BlueprintTransformer.analyze(new DOMSource(BlueprintTransformer.parse(f.toURL()))); assertNotNull(pkgs); assertEquals(1,pkgs.size()); Iterator<String> it=pkgs.iterator(); assertEquals("org.apache.aries.blueprint.sample",it.next()); }
Example 61
From project Kayak, under directory /Kayak-ui/src/main/java/com/github/kayak/ui/connections/.
Source file: ConnectionManager.java

public void writeToFile(OutputStream stream){ try { DocumentBuilderFactory dbf=DocumentBuilderFactory.newInstance(); DocumentBuilder db=dbf.newDocumentBuilder(); Document doc=db.newDocument(); Element root=doc.createElement("Connections"); doc.appendChild(root); Element favouritesElement=doc.createElement("Favourites"); for ( BusURL url : favourites) { try { Element favourite=doc.createElement("Connection"); favourite.setAttribute("host",url.getHost()); favourite.setAttribute("port",Integer.toString(url.getPort())); favourite.setAttribute("name",url.getBus()); favouritesElement.appendChild(favourite); } catch ( Exception ex) { } } root.appendChild(favouritesElement); TransformerFactory transformerFactory=TransformerFactory.newInstance(); Transformer transformer=transformerFactory.newTransformer(); DOMSource source=new DOMSource(doc); StreamResult result=new StreamResult(stream); transformer.transform(source,result); } catch ( Exception ex) { logger.log(Level.SEVERE,"Error while writing connections to file\n"); } }
Example 62
From project libra, under directory /tests/org.eclipse.libra.facet.test/src/org/eclipse/libra/facet/test/.
Source file: WebContextRootSynchronizerTest.java

private byte[] saveDomToBytes(Document xmlDocument) throws TransformerException { ByteArrayOutputStream os=new ByteArrayOutputStream(); TransformerFactory transformerFactory=TransformerFactory.newInstance(); Transformer transformer=transformerFactory.newTransformer(); transformer.transform(new DOMSource(xmlDocument),new StreamResult(os)); return os.toByteArray(); }
Example 63
From project Lily, under directory /cr/indexer/model/src/main/java/org/lilyproject/indexer/model/indexerconf/.
Source file: IndexerConfBuilder.java

private void validate(Document document) throws IndexerConfException { try { SchemaFactory factory=SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI); URL url=getClass().getClassLoader().getResource("org/lilyproject/indexer/model/indexerconf/indexerconf.xsd"); Schema schema=factory.newSchema(url); Validator validator=schema.newValidator(); validator.validate(new DOMSource(document)); } catch ( Exception e) { throw new IndexerConfException("Error validating indexer configuration against XML Schema.",e); } }
Example 64
From project litle-sdk-for-java, under directory /lib/apache-cxf-2.5.2/samples/jaxws_dispatch_provider/src/main/java/demo/hwDispatch/server/.
Source file: GreeterDOMSourceMessageProvider.java

public DOMSource invoke(DOMSource request){ DOMSource response=new DOMSource(); try { MessageFactory factory=MessageFactory.newInstance(); SOAPMessage soapReq=factory.createMessage(); soapReq.getSOAPPart().setContent(request); System.out.println("Incoming Client Request as a DOMSource data in MESSAGE Mode"); soapReq.writeTo(System.out); System.out.println("\n"); InputStream is=getClass().getResourceAsStream("GreetMeDocLiteralResp2.xml"); SOAPMessage greetMeResponse=factory.createMessage(null,is); is.close(); response.setNode(greetMeResponse.getSOAPPart()); } catch ( Exception ex) { ex.printStackTrace(); } return response; }
Example 65
From project lyo.testsuite, under directory /org.eclipse.lyo.testsuite.server/src/main/java/org/eclipse/lyo/testsuite/server/util/.
Source file: OSLCUtils.java

public static String createStringFromXMLDoc(Document document) throws TransformerException { TransformerFactory tf=TransformerFactory.newInstance(); Transformer transformer=tf.newTransformer(); transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION,"yes"); StringWriter writer=new StringWriter(); transformer.transform(new DOMSource(document),new StreamResult(writer)); return writer.getBuffer().toString(); }
Example 66
From project MEditor, under directory /editor-common/editor-common-server/src/main/java/cz/mzk/editor/server/fedora/utils/.
Source file: FedoraUtils.java

/** * @param document */ public static String getStringFromDocument(Document document,boolean omitXmlDeclaration) throws TransformerException { TransformerFactory transFactory=TransformerFactory.newInstance(); Transformer transformer=transFactory.newTransformer(); StringWriter buffer=new StringWriter(); if (omitXmlDeclaration) { transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION,"yes"); } transformer.transform(new DOMSource(document),new StreamResult(buffer)); return buffer.toString(); }
Example 67
From project moho, under directory /moho-common/src/main/java/com/voxeo/moho/common/util/.
Source file: XmlUtils.java

public static String render(final Node node){ try { final StringWriter writer=new StringWriter(); final DOMSource domSource=new DOMSource(node); final StreamResult streamResult=new StreamResult(writer); final TransformerFactory tf=TransformerFactory.newInstance(); final Transformer serializer=tf.newTransformer(); serializer.setOutputProperty(OutputKeys.INDENT,"yes"); serializer.transform(domSource,streamResult); return writer.toString(); } catch ( final Exception e) { throw new RuntimeException("Error serializing DOM",e); } }
Example 68
From project netty-xmpp, under directory /src/main/java/es/udc/pfc/xmpp/xml/.
Source file: XMLUtil.java

/** * Returns the String representation of an Element. * @param element the Element to convert * @return the String representation of a Element */ public static final String toString(final Element element){ try { final StringWriter buffer=new StringWriter(); transformer.transform(new DOMSource(element),new StreamResult(buffer)); return buffer.toString(); } catch ( final TransformerException e) { throw new InternalError("Transformer error"); } }
Example 69
public static void write(NodeLibrary library,StreamResult streamResult,File file){ try { DocumentBuilder builder=DocumentBuilderFactory.newInstance().newDocumentBuilder(); Document doc=builder.newDocument(); Element rootElement=doc.createElement("ndbx"); rootElement.setAttribute("type","file"); rootElement.setAttribute("formatVersion",NodeLibrary.CURRENT_FORMAT_VERSION); rootElement.setAttribute("uuid",library.getUuid().toString()); doc.appendChild(rootElement); Set<String> propertyNames=library.getPropertyNames(); ArrayList<String> orderedNames=new ArrayList<String>(propertyNames); Collections.sort(orderedNames); for ( String propertyName : orderedNames) { String propertyValue=library.getProperty(propertyName); Element e=doc.createElement("property"); e.setAttribute("name",propertyName); e.setAttribute("value",propertyValue); rootElement.appendChild(e); } writeFunctionRepository(doc,rootElement,library.getFunctionRepository(),file); writeNode(doc,rootElement,library.getRoot(),library.getNodeRepository()); DOMSource domSource=new DOMSource(doc); TransformerFactory tf=TransformerFactory.newInstance(); Transformer serializer=tf.newTransformer(); serializer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount","4"); serializer.setOutputProperty(OutputKeys.INDENT,"yes"); serializer.transform(domSource,streamResult); } catch ( ParserConfigurationException e) { throw new RuntimeException(e); } catch ( TransformerException e) { throw new RuntimeException(e); } }
Example 70
/** * save dom into ouputstream * @param os * @param e */ public static void saveDom(OutputStream os,Element e){ DOMSource source=new DOMSource(e); TransformerFactory transFactory=TransformerFactory.newInstance(); Transformer transformer; try { transformer=transFactory.newTransformer(); transformer.setOutputProperty("indent","yes"); StreamResult result=new StreamResult(os); transformer.transform(source,result); os.flush(); } catch ( UnsupportedEncodingException e1) { LOG.error("Error: ",e1); } catch ( IOException e1) { LOG.error("Error: ",e1); } catch ( TransformerConfigurationException e2) { LOG.error("Error: ",e2); } catch ( TransformerException ex) { LOG.error("Error: ",ex); } }
Example 71
From project ODE-X, under directory /spi/src/main/java/org/apache/ode/spi/compiler/.
Source file: ParserUtils.java

public static String domToString(Document doc) throws ParserException { try { TransformerFactory transformFactory=TransformerFactory.newInstance(); Transformer tform=transformFactory.newTransformer(); tform.setOutputProperty(OutputKeys.INDENT,"yes"); StringWriter writer=new StringWriter(); tform.transform(new DOMSource(doc),new StreamResult(writer)); return writer.toString(); } catch ( Exception e) { throw new ParserException(e); } }
Example 72
From project open-data-node, under directory /src/main/java/sk/opendata/odn/serialization/rdf/.
Source file: AbstractRdfSerializer.java

@Override public String serialize(List<RecordType> records) throws OdnSerializationException { Document doc=docBuilder.newDocument(); Element rdfElement=doc.createElementNS(NS_RDF,"rdf:RDF"); rdfElement.setAttribute("xmlns:rdf",NS_RDF); rdfElement.setAttribute("xmlns:skos",NS_SKOS); rdfElement.setAttribute("xmlns:dc",NS_DC); rdfElement.setAttribute("xmlns:opendata",NS_OPENDATA); addCustomRdfNsElements(rdfElement); doc.appendChild(rdfElement); for ( RecordType record : records) { Element concept=doc.createElement("skos:Concept"); concept.setAttribute("rdf:about",getConceptRdfAbout(record)); serializeRecord(doc,concept,record); rdfElement.appendChild(concept); } StringWriter sw=new StringWriter(); StreamResult result=new StreamResult(sw); DOMSource source=new DOMSource(doc); try { transformer.transform(source,result); } catch ( TransformerException e) { throw new OdnSerializationException(e.getMessage(),e); } return sw.toString(); }
Example 73
From project openclaws, under directory /cat/WEB-INF/src/edu/rit/its/claws/cat/.
Source file: ClawsDocument.java

/** * Returns an xml document as a string. * @param doc the XML Document * @param t the translator to process the doc with * @return The string representation of the document * @throws Exception */ protected static String docToString(Document doc,Translator t) throws Exception { try { if (t != null) doc=t.translate(doc); TransformerFactory tFactory=TransformerFactory.newInstance(); Transformer transformer=tFactory.newTransformer(); DOMSource source=new DOMSource(doc); StringWriter sw=new StringWriter(); StreamResult result=new StreamResult(sw); transformer.transform(source,result); String xmlString=sw.toString(); return xmlString; } catch ( Exception e) { throw e; } }
Example 74
From project org.eclipse.scout.builder, under directory /org.eclipse.scout.releng.ant/src/org/eclipse/scout/releng/ant/category/.
Source file: CategoryTask.java

private void writeXmlFile(Document document) throws Exception { OutputStream fos=null; try { if (!getCategoryFile().exists()) { getCategoryFile().getParentFile().mkdirs(); } fos=new FileOutputStream(getCategoryFile()); TransformerFactory transformerFactory=TransformerFactory.newInstance(); Transformer transformer=transformerFactory.newTransformer(); transformer.setOutputProperty(OutputKeys.INDENT,"yes"); transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount","2"); DOMSource source=new DOMSource(document); StreamResult result=new StreamResult(fos); transformer.transform(source,result); } finally { fos.close(); } }
Example 75
From project OWASP-WebScarab, under directory /src/org/owasp/webscarab/plugin/saml/.
Source file: SamlHTTPClient.java

private String outputDocument(Document document) throws TransformerConfigurationException, TransformerException { ByteArrayOutputStream outputStream=new ByteArrayOutputStream(); Result result=new StreamResult(outputStream); Transformer xformer=TransformerFactory.newInstance().newTransformer(); Source source=new DOMSource(document); xformer.transform(source,result); String encodedChangedSamlResponse=Base64.encode(outputStream.toByteArray()); return Encoding.urlEncode(encodedChangedSamlResponse); }
Example 76
From project autopsy, under directory /Core/src/org/sleuthkit/autopsy/coreutils/.
Source file: XMLUtil.java

/** * Saves XML files to disk * @param clazz the class this method is invoked from * @param xmlPath the full path to save the XML to * @param encoding to encoding, such as "UTF-8", to encode the file with * @param doc the document to save */ public static boolean saveDoc(Class clazz,String xmlPath,String encoding,final Document doc){ TransformerFactory xf=TransformerFactory.newInstance(); xf.setAttribute("indent-number",new Integer(1)); boolean success=false; try { Transformer xformer=xf.newTransformer(); xformer.setOutputProperty(OutputKeys.METHOD,"xml"); xformer.setOutputProperty(OutputKeys.INDENT,"yes"); xformer.setOutputProperty(OutputKeys.ENCODING,encoding); xformer.setOutputProperty(OutputKeys.STANDALONE,"yes"); xformer.setOutputProperty(OutputKeys.VERSION,"1.0"); File file=new File(xmlPath); FileOutputStream stream=new FileOutputStream(file); Result out=new StreamResult(new OutputStreamWriter(stream,encoding)); xformer.transform(new DOMSource(doc),out); stream.flush(); stream.close(); success=true; } catch ( UnsupportedEncodingException e) { Logger.getLogger(clazz.getName()).log(Level.SEVERE,"Should not happen",e); } catch ( TransformerConfigurationException e) { Logger.getLogger(clazz.getName()).log(Level.SEVERE,"Error writing XML file",e); } catch ( TransformerException e) { Logger.getLogger(clazz.getName()).log(Level.SEVERE,"Error writing XML file",e); } catch ( FileNotFoundException e) { Logger.getLogger(clazz.getName()).log(Level.SEVERE,"Error writing XML file: cannot write to file: " + xmlPath,e); } catch ( IOException e) { Logger.getLogger(clazz.getName()).log(Level.SEVERE,"Error writing XML file: cannot write to file: " + xmlPath,e); } return success; }
Example 77
From project BMach, under directory /src/jsyntaxpane/actions/.
Source file: XmlPrettifyAction.java

@Override public void actionPerformed(ActionEvent e){ if (transformer == null) { return; } JTextComponent target=getTextComponent(e); try { SyntaxDocument sdoc=ActionUtils.getSyntaxDocument(target); StringWriter out=new StringWriter(sdoc.getLength()); StringReader reader=new StringReader(target.getText()); InputSource src=new InputSource(reader); Document doc=getDocBuilder().parse(src); getTransformer().transform(new DOMSource(doc),new StreamResult(out)); target.setText(out.toString()); } catch ( SAXParseException ex) { showErrorMessage(target,String.format("XML error: %s\nat(%d, %d)",ex.getMessage(),ex.getLineNumber(),ex.getColumnNumber())); ActionUtils.setCaretPosition(target,ex.getLineNumber(),ex.getColumnNumber() - 1); } catch ( TransformerException ex) { showErrorMessage(target,ex.getMessageAndLocation()); } catch ( SAXException ex) { showErrorMessage(target,ex.getLocalizedMessage()); } catch ( IOException ex) { showErrorMessage(target,ex.getLocalizedMessage()); } }
Example 78
From project CCR-Validator, under directory /src/main/java/org/openhealthdata/validation/.
Source file: CCRV1SchemaValidator.java

private void validate(Document xml){ try { ccr=null; validator.validate(new DOMSource(xml)); JAXBContext jc=JAXBContext.newInstance("org.astm.ccr"); Unmarshaller um=jc.createUnmarshaller(); ccr=(ContinuityOfCareRecord)um.unmarshal(new DOMSource(xml)); } catch ( SAXException e) { logger.log(Level.SEVERE,"Not Valid CCR XML: " + e.getMessage()); } catch ( IOException e) { logger.log(Level.SEVERE,"Exception during validating",e); e.printStackTrace(); } catch ( JAXBException e) { logger.log(Level.SEVERE,"Exception during unmarshalling XML DOM",e); e.printStackTrace(); } }
Example 79
From project chukwa, under directory /src/main/java/org/apache/hadoop/chukwa/inputtools/jplugin/.
Source file: ChukwaMetricsList.java

public String toXml() throws Exception { DocumentBuilderFactory factory=DocumentBuilderFactory.newInstance(); DocumentBuilder docBuilder=null; docBuilder=factory.newDocumentBuilder(); Document doc=docBuilder.newDocument(); Element root=doc.createElement(getRecordType()); doc.appendChild(root); root.setAttribute("ts",getTimestamp() + ""); for ( ChukwaMetrics metrics : getMetricsList()) { Element elem=doc.createElement("Metrics"); elem.setAttribute("key",metrics.getKey()); for ( Entry<String,String> attr : metrics.getAttributes().entrySet()) { elem.setAttribute(attr.getKey(),attr.getValue()); } root.appendChild(elem); } Transformer transformer=TransformerFactory.newInstance().newTransformer(); transformer.setOutputProperty("indent","yes"); StringWriter sw=new StringWriter(); transformer.transform(new DOMSource(doc),new StreamResult(sw)); return sw.toString(); }
Example 80
From project cidb, under directory /ncbieutils-access-service/src/main/java/edu/toronto/cs/cidb/ncbieutils/.
Source file: NCBIEUtilsAccessService.java

protected String getSummariesXML(List<String> idList){ String queryList=getSerializedList(idList); String url=composeURL(TERM_SUMMARY_QUERY_SCRIPT,TERM_SUMMARY_PARAM_NAME,queryList); try { Document response=readXML(url); NodeList nodes=response.getElementsByTagName("Item"); for (int i=0; i < nodes.getLength(); ++i) { Node n=nodes.item(i); if (n.getNodeType() == Node.ELEMENT_NODE) { if (n.getFirstChild() != null) { n.replaceChild(response.createTextNode(fixCase(n.getTextContent())),n.getFirstChild()); } } } Source source=new DOMSource(response); StringWriter stringWriter=new StringWriter(); Result result=new StreamResult(stringWriter); TransformerFactory factory=TransformerFactory.newInstance(); Transformer transformer=factory.newTransformer(); transformer.transform(source,result); return stringWriter.getBuffer().toString(); } catch ( Exception ex) { this.logger.error("Error while trying to retrieve summaries for ids " + idList + " "+ ex.getClass().getName()+ " "+ ex.getMessage(),ex); } return ""; }
Example 81
From project Cilia_1, under directory /framework/runtime/src/main/java/fr/liglab/adele/cilia/framework/data/.
Source file: XmlTools.java

/** * Convert a Node in XML String. * @param node to be converted. * @return the XML string. */ public static String nodeToString(Node node) throws CiliaException { Source source=new DOMSource(node); StringWriter stringWriter=new StringWriter(); Result result=new StreamResult(stringWriter); try { Transformer transformer=TransformerFactory.newInstance().newTransformer(); transformer.transform(source,result); String strResult=stringWriter.getBuffer().toString(); strResult=strResult.replace("<?xml version=\"1.0\" encoding=\"UTF-8\"?>",""); return strResult; } catch ( TransformerException e) { e.printStackTrace(); throw new CiliaException(e.getMessage()); } }
Example 82
From project cipango, under directory /cipango-console/src/main/java/org/cipango/console/.
Source file: SvgServlet.java

private byte[] doXsl(byte[] source){ try { ByteArrayOutputStream os=new ByteArrayOutputStream(); StreamResult result=new StreamResult(os); TransformerFactory factory=TransformerFactory.newInstance(); DocumentBuilderFactory documentBuilderFactory=DocumentBuilderFactory.newInstance(); DocumentBuilder documentBuilder=documentBuilderFactory.newDocumentBuilder(); Node doc=documentBuilder.parse(new ByteArrayInputStream(source)); Transformer transformer=factory.newTransformer(new StreamSource(getClass().getResourceAsStream("dataToSvg.xsl"))); transformer.transform(new DOMSource(doc),result); return os.toByteArray(); } catch ( Throwable e) { _logger.warn("Unable to do XSL transformation",e); return source; } }
Example 83
From project code_swarm, under directory /src/org/codeswarm/repositoryevents/.
Source file: CodeSwarmEventsSerializer.java

/** * actually serializes the list to the file denoted by pathToFile * @param pathToFile the path to the xml file to serialize to.It gets created if it doesn't exist. * @throws javax.xml.parsers.ParserConfigurationException When the serialization failed * @throws javax.xml.transform.TransformerConfigurationException When the serialization failed * @throws java.io.IOException When the serialization failed * @throws javax.xml.transform.TransformerException When the serialization failed */ public void serialize(String pathToFile) throws ParserConfigurationException, TransformerConfigurationException, IOException, TransformerException { Document d=DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument(); Element events=d.createElement("file_events"); for ( Event e : list.getEvents()) { Element event=d.createElement("event"); event.setAttribute("filename",e.getFilename()); event.setAttribute("date",String.valueOf(e.getDate())); event.setAttribute("author",e.getAuthor()); events.appendChild(event); } d.appendChild(events); Transformer t=TransformerFactory.newInstance().newTransformer(); File f=new File(pathToFile); if (!f.exists()) { f.createNewFile(); } FileOutputStream out=new FileOutputStream(f); StreamResult result=new StreamResult(out); t.transform(new DOMSource(d),result); out.close(); }
Example 84
From project code_swarm-gource-my-conf, under directory /src/org/codeswarm/repositoryevents/.
Source file: CodeSwarmEventsSerializer.java

/** * actually serializes the list to the file denoted by pathToFile * @param pathToFile the path to the xml file to serialize to. It gets created if it doesn't exist. * @throws javax.xml.parsers.ParserConfigurationException When the serialization failed * @throws javax.xml.transform.TransformerConfigurationException When the serialization failed * @throws java.io.IOException When the serialization failed * @throws javax.xml.transform.TransformerException When the serialization failed */ public void serialize(String pathToFile) throws ParserConfigurationException, TransformerConfigurationException, IOException, TransformerException { Document d=DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument(); Element events=d.createElement("file_events"); for ( Event e : list.getEvents()) { Element event=d.createElement("event"); event.setAttribute("filename",e.getFilename()); event.setAttribute("date",String.valueOf(e.getDate())); event.setAttribute("author",e.getAuthor()); events.appendChild(event); } d.appendChild(events); Transformer t=TransformerFactory.newInstance().newTransformer(); File f=new File(pathToFile); if (!f.exists()) { f.createNewFile(); } FileOutputStream out=new FileOutputStream(f); StreamResult result=new StreamResult(out); t.transform(new DOMSource(d),result); out.close(); }
Example 85
From project codjo-data-process, under directory /codjo-data-process-common/src/main/java/net/codjo/dataprocess/common/util/.
Source file: XMLUtils.java

public static String nodeToString(Node node,boolean replaceCRLF,boolean removeSpaceChar) throws TransformerException { String result; StringWriter strWriter=new StringWriter(); TransformerFactory tFactory=TransformerFactory.newInstance(); Transformer transformer=tFactory.newTransformer(); transformer.transform(new DOMSource(node),new StreamResult(strWriter)); String str=getRidOfHeader(strWriter.toString()); if (replaceCRLF) { result=flattenAndReplaceCRLF(str,removeSpaceChar); } else { result=flatten(str,removeSpaceChar); } return result; }
Example 86
From project Core_2, under directory /parser-xml/src/main/java/org/jboss/forge/parser/xml/.
Source file: XMLParser.java

public static byte[] toXMLByteArray(final Node node){ try { DocumentBuilderFactory factory=DocumentBuilderFactory.newInstance(); factory.setNamespaceAware(true); DocumentBuilder builder=factory.newDocumentBuilder(); Document root=builder.newDocument(); writeRecursive(root,node); Transformer transformer=TransformerFactory.newInstance().newTransformer(); transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount","2"); transformer.setOutputProperty(OutputKeys.INDENT,"yes"); ByteArrayOutputStream stream=new ByteArrayOutputStream(); StreamResult result=new StreamResult(stream); transformer.transform(new DOMSource(root),result); return stream.toByteArray(); } catch ( Exception e) { throw new XMLParserException("Could not export Node strcuture to XML",e); } }
Example 87
From project Cours-3eme-ann-e, under directory /Java/FerryInpres/src/information_client/.
Source file: MainForm.java

private void sendDocument(Document doc) throws TransformerConfigurationException, TransformerException, IOException, ClassNotFoundException { String MAIN_SERVEUR=prop.getProperty("MAIN_SERVEUR"); int MAIN_PORT=Integer.parseInt(prop.getProperty("MAIN_PORT")); Socket sock=new Socket(MAIN_SERVEUR,MAIN_PORT); InputStream sock_in=sock.getInputStream(); OutputStream sock_out=sock.getOutputStream(); StringWriter out=new StringWriter(); TransformerFactory transFactory=TransformerFactory.newInstance(); Transformer transform=transFactory.newTransformer(); transform.setOutputProperty(OutputKeys.METHOD,"xml"); transform.setOutputProperty(OutputKeys.INDENT,"yes"); Source input=new DOMSource(doc); Result output=new StreamResult(out); transform.transform(input,output); ObjectOutputStream obj_out=new ObjectOutputStream(sock_out); String xml_str=out.toString(); System.out.println(xml_str); obj_out.writeObject(xml_str); sock_out.flush(); try { String filename=(String)(new ObjectInputStream(sock_in)).readObject(); this.informationsText.setText(filename); this.erreurLabel.setText("Demande r?ussie"); } catch ( Exception e) { System.err.println(e); this.erreurLabel.setText("Erreur lors du traitement de la demande"); } }
Example 88
From project dawn-common, under directory /org.dawb.common.util/src/org/dawb/common/util/xml/.
Source file: XMLUtils.java

private static String getNodeValue(NodeList nodeList) throws TransformerFactoryConfigurationError, TransformerException { final Transformer serializer=TransformerFactory.newInstance().newTransformer(); serializer.setURIResolver(null); final StringBuilder buf=new StringBuilder(); for (int i=0; i < nodeList.getLength(); i++) { final StringWriter sw=new StringWriter(); serializer.transform(new DOMSource(nodeList.item(i)),new StreamResult(sw)); String xml=sw.toString(); final Matcher matcher=HEADER_PATTERN.matcher(xml); if (matcher.matches()) { xml=matcher.group(1); } buf.append(xml); buf.append("\n"); } return buf.toString(); }
Example 89
From project descriptors, under directory /spi/src/main/java/org/jboss/shrinkwrap/descriptor/spi/node/dom/.
Source file: XmlDomDescriptorExporterImpl.java

/** * {@inheritDoc} * @see org.jboss.shrinkwrap.descriptor.spi.node.NodeDescriptorExporterImpl#to(org.jboss.shrinkwrap.descriptor.spi.node.Node,java.io.OutputStream) */ @Override public void to(final Node node,final OutputStream out) throws DescriptorExportException { try { DocumentBuilderFactory factory=DocumentBuilderFactory.newInstance(); factory.setNamespaceAware(true); DocumentBuilder builder=factory.newDocumentBuilder(); Document root=builder.newDocument(); root.setXmlStandalone(true); writeRecursive(root,node); Transformer transformer=TransformerFactory.newInstance().newTransformer(); transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount","2"); transformer.setOutputProperty(OutputKeys.INDENT,"yes"); transformer.setOutputProperty(OutputKeys.STANDALONE,"yes"); StreamResult result=new StreamResult(out); transformer.transform(new DOMSource(root),result); } catch ( Exception e) { throw new DescriptorExportException("Could not export Node structure to XML",e); } }
Example 90
From project dev-examples, under directory /template/src/main/java/org/richfaces/example/.
Source file: XMLBodySerializer.java

public String serialize(NodeList childNodes,Document xmlDocument) throws ParsingException { try { StringWriter out; DocumentFragment fragment=xmlDocument.createDocumentFragment(); for (int i=0; i < childNodes.getLength(); i++) { fragment.appendChild(childNodes.item(i).cloneNode(true)); } TransformerFactory transformerFactory=TransformerFactory.newInstance(); Transformer transformer=transformerFactory.newTransformer(); transformer.setErrorListener(new ErrorListener(){ public void error( TransformerException exception) throws TransformerException { } public void fatalError( TransformerException exception) throws TransformerException { } public void warning( TransformerException exception) throws TransformerException { } } ); transformer.setOutputProperty("indent","yes"); transformer.setOutputProperty("omit-xml-declaration","yes"); out=new StringWriter(); StreamResult result=new StreamResult(out); transformer.transform(new DOMSource(fragment),result); return out.toString(); } catch ( Exception e) { throw new ParsingException(e); } }
Example 91
From project droolsjbpm-integration, under directory /drools-camel/src/test/java/org/drools/camel/component/.
Source file: BatchTest.java

public String prettyPrintXml(String xmlSource){ try { DocumentBuilderFactory factory=DocumentBuilderFactory.newInstance(); DocumentBuilder builder=factory.newDocumentBuilder(); Document doc=builder.parse(new InputSource(new StringReader(xmlSource))); TransformerFactory tfactory=TransformerFactory.newInstance(); tfactory.setAttribute("indent-number",4); Transformer serializer; ByteArrayOutputStream baos=new ByteArrayOutputStream(); serializer=tfactory.newTransformer(); serializer.setOutputProperty(OutputKeys.INDENT,"yes"); serializer.transform(new DOMSource(doc),new StreamResult(new OutputStreamWriter(baos,"UTF-8"))); return new String(baos.toByteArray()); } catch ( Exception e) { throw new RuntimeException(e); } }
Example 92
From project Ebselen, under directory /ebselen-core/src/main/java/com/lazerycode/ebselen/handlers/.
Source file: XMLHandler.java

/** * Write the current XML object to file. * @param absoluteFileName - Absolute filename to write XML object to * @return String - Directory that file has been written to * @throws Exception */ public String writeXMLFile(String absoluteFileName) throws Exception { if (this.xmlDocument == null) { LOGGER.error("The Document object is null, unable to generate a file!"); return null; } Source source=new DOMSource(this.xmlDocument); FileHandler outputFile=new FileHandler(absoluteFileName,true); try { Result output=new StreamResult(outputFile.getWriteableFile()); TransformerFactory.newInstance().newTransformer().transform(source,output); } catch ( TransformerConfigurationException Ex) { LOGGER.error(" Error creating file: " + Ex); } catch ( TransformerException Ex) { LOGGER.error(" Error creating file: " + Ex); } outputFile.close(); return outputFile.getAbsoluteFile(); }
Example 93
From project fedora-client, under directory /fedora-client-core/src/main/java/com/yourmediashelf/fedora/util/.
Source file: XmlSerializer.java

protected static byte[] doc2bytes(Node node){ try { Source source=new DOMSource(node); ByteArrayOutputStream out=new ByteArrayOutputStream(); Result result=new StreamResult(out); TransformerFactory factory=TransformerFactory.newInstance(); Transformer transformer=factory.newTransformer(); transformer.transform(source,result); return out.toByteArray(); } catch ( TransformerConfigurationException e) { e.printStackTrace(); } catch ( TransformerException e) { e.printStackTrace(); } return null; }
Example 94
From project galaxy, under directory /src/co/paralleluniverse/common/util/.
Source file: DOMElementProprtyEditor.java

@Override public String getAsText(){ try { final Node node=(Node)getValue(); Source source=new DOMSource(node); StringWriter stringWriter=new StringWriter(); Result result=new StreamResult(stringWriter); TransformerFactory factory=TransformerFactory.newInstance(); Transformer transformer=factory.newTransformer(); transformer.transform(source,result); return stringWriter.getBuffer().toString(); } catch ( TransformerConfigurationException e) { e.printStackTrace(); } catch ( TransformerException e) { e.printStackTrace(); } return null; }
Example 95
From project GeoBI, under directory /print/src/main/java/org/mapfish/print/map/renderers/.
Source file: SVGTileRenderer.java

private TranscoderInput getTranscoderInput(URL url,Transformer transformer,RenderingContext context){ final float zoomFactor=transformer.getSvgFactor() * context.getStyleFactor(); if (svgZoomOut != null && zoomFactor != 1.0f) { try { DOMResult transformedSvg=new DOMResult(); final TransformerFactory factory=TransformerFactory.newInstance(); javax.xml.transform.Transformer xslt=factory.newTransformer(new DOMSource(svgZoomOut)); xslt.setParameter("zoomFactor",zoomFactor); final URLConnection urlConnection=url.openConnection(); if (context.getReferer() != null) { urlConnection.setRequestProperty("Referer",context.getReferer()); } final InputStream inputStream=urlConnection.getInputStream(); Document doc; try { xslt.transform(new StreamSource(inputStream),transformedSvg); doc=(Document)transformedSvg.getNode(); if (LOGGER.isDebugEnabled()) { printDom(doc); } } finally { inputStream.close(); } return new TranscoderInput(doc); } catch ( Exception e) { context.addError(e); return null; } } else { return new TranscoderInput(url.toString()); } }
Example 96
From project HiTune_1, under directory /chukwa-hitune-dist/src/java/org/apache/hadoop/chukwa/inputtools/jplugin/.
Source file: ChukwaMetricsList.java

public String toXml() throws Exception { DocumentBuilderFactory factory=DocumentBuilderFactory.newInstance(); DocumentBuilder docBuilder=null; docBuilder=factory.newDocumentBuilder(); Document doc=docBuilder.newDocument(); Element root=doc.createElement(getRecordType()); doc.appendChild(root); root.setAttribute("ts",getTimestamp() + ""); for ( ChukwaMetrics metrics : getMetricsList()) { Element elem=doc.createElement("Metrics"); elem.setAttribute("key",metrics.getKey()); for ( Entry<String,String> attr : metrics.getAttributes().entrySet()) { elem.setAttribute(attr.getKey(),attr.getValue()); } root.appendChild(elem); } Transformer transformer=TransformerFactory.newInstance().newTransformer(); transformer.setOutputProperty("indent","yes"); StringWriter sw=new StringWriter(); transformer.transform(new DOMSource(doc),new StreamResult(sw)); return sw.toString(); }
Example 97
From project jagger, under directory /chassis/core/src/main/java/com/griddynamics/jagger/reporting/.
Source file: ReportInputStream.java

public ReportInputStream(InputStream input,boolean removeFrame){ this.removeFrame=removeFrame; try { try { DocumentBuilderFactory factory=DocumentBuilderFactory.newInstance(); DocumentBuilder parser=factory.newDocumentBuilder(); Document document=parser.parse(input); processNode(document); Transformer transformer=TransformerFactory.newInstance().newTransformer(); ByteArrayOutputStream xmlOutput=new ByteArrayOutputStream(65536); try { transformer.transform(new DOMSource(document),new StreamResult(xmlOutput)); } finally { xmlOutput.close(); } this.xmlInput=new ByteArrayInputStream(xmlOutput.toByteArray()); } finally { input.close(); } } catch ( Exception e) { throw new RuntimeException(e); } }
Example 98
From project jboss-jstl-api_spec, under directory /src/main/java/org/apache/taglibs/standard/tag/common/xml/.
Source file: TransformSupport.java

/** * Retrieves a Source from the given Object, whether it be a String, Reader, Node, or other supported types (even a Source already). If 'url' is true, then we must be passed a String and will interpret it as a URL. A null input always results in a null output. */ private Source getSource(Object o,String systemId) throws SAXException, ParserConfigurationException, IOException { if (o == null) return null; else if (o instanceof Source) { return (Source)o; } else if (o instanceof String) { return getSource(new StringReader((String)o),systemId); } else if (o instanceof Reader) { XMLReader xr=XMLReaderFactory.createXMLReader(); xr.setEntityResolver(new ParseSupport.JstlEntityResolver(pageContext)); InputSource s=new InputSource((Reader)o); s.setSystemId(wrapSystemId(systemId)); Source result=new SAXSource(xr,s); result.setSystemId(wrapSystemId(systemId)); return result; } else if (o instanceof Node) { return new DOMSource((Node)o); } else if (o instanceof List) { List l=(List)o; if (l.size() == 1) { return getSource(l.get(0),systemId); } else { throw new IllegalArgumentException(Resources.getMessage("TRANSFORM_SOURCE_INVALID_LIST")); } } else { throw new IllegalArgumentException(Resources.getMessage("TRANSFORM_SOURCE_UNRECOGNIZED") + o.getClass()); } }
Example 99
/** * Saves the lesson to an {@link OutputStream} which contains an XMLdocument. Don't use this method directly. Use the {@link LessonProvider} instead.XML-Schema: <lesson> <deck> <card frontside="bla" backside="bla"/> .. </deck> .. </lesson> */ public static void saveAsXMLFile(File file,Lesson lesson) throws IOException, TransformerException, ParserConfigurationException { OutputStream out; ZipOutputStream zipOut=null; if (Settings.loadIsSaveCompressed()) { out=zipOut=new ZipOutputStream(new FileOutputStream(file)); zipOut.putNextEntry(new ZipEntry(LESSON_ZIP_ENTRY_NAME)); } else { out=new FileOutputStream(file); } try { Document document=DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument(); Element lessonTag=document.createElement(LESSON); document.appendChild(lessonTag); writeCategory(document,lessonTag,lesson.getRootCategory()); writeLearnHistory(document,lesson.getLearnHistory()); Transformer transformer=TransformerFactory.newInstance().newTransformer(); transformer.setOutputProperty(OutputKeys.ENCODING,"UTF-8"); transformer.setOutputProperty(OutputKeys.INDENT,"yes"); transformer.transform(new DOMSource(document),new StreamResult(out)); } finally { if (zipOut != null) zipOut.closeEntry(); else if (out != null) out.close(); } try { removeUnusedImagesFromRepository(lesson); if (zipOut == null) writeImageRepositoryToDisk(new File(file.getParent())); else writeImageRepositoryToZip(zipOut); } finally { if (zipOut != null) zipOut.close(); } }
Example 100
From project LABPipe, under directory /src/org/bultreebank/labpipe/tools/.
Source file: ClarkAnnotation.java

private String extractResultFragment(Document doc){ try { Transformer tr=TransformerFactory.newInstance().newTransformer(); tr.setOutputProperty(OutputKeys.INDENT,"yes"); tr.setOutputProperty(OutputKeys.METHOD,"xml"); tr.setOutputProperty(OutputKeys.ENCODING,ServiceConstants.PIPE_CHARACTER_ENCODING); tr.setOutputProperty("{http://xml.apache.org/xslt}indent-amount","0"); StringWriter resultBuffer=new StringWriter(); tr.transform(new DOMSource(doc),new StreamResult(resultBuffer)); return resultBuffer.getBuffer().toString(); } catch ( Exception ex) { logger.severe(ex.getMessage()); } return ""; }
Example 101
From project leviathan, under directory /scrapper/src/main/java/com/zaubersoftware/leviathan/api/engine/impl/pipe/.
Source file: XMLPipe.java

/** * Applies the XSL Transformation and returns the resulting Node. * @param node * @param model * @param oformat * @return * @throws TransformerFactoryConfigurationError */ private Node applyXSLT(final Node node,final Map<String,Object> model,final Properties oformat){ Validate.notNull(node,"The node cannot be null."); try { final Transformer transformer=template.newTransformer(); Validate.notNull(transformer); for ( final Entry<String,Object> entry : model.entrySet()) { transformer.setParameter(entry.getKey(),entry.getValue()); } Properties options; if (oformat != null) { options=new Properties(oformat); } else { options=new Properties(); } if (this.encoding != null) { options.setProperty(OutputKeys.ENCODING,this.encoding); } transformer.setOutputProperties(options); final DOMResult result=new DOMResult(); transformer.transform(new DOMSource(node),result); return result.getNode(); } catch ( final TransformerException e) { this.logger.error("An error ocurred while applying the XSL transformation",e); throw new NotImplementedException("Handle exception with context stack handlers"); } catch ( final TransformerFactoryConfigurationError e) { this.logger.error("An error ocurred while applying the XSL transformation",e); throw new NotImplementedException("Handle exception with context stack handlers"); } }
Example 102
From project license-maven-plugin, under directory /src/main/java/org/codehaus/mojo/license/.
Source file: LicenseSummaryWriter.java

public static void writeLicenseSummary(List<ProjectLicenseInfo> dependencies,File outputFile) throws ParserConfigurationException, TransformerException { DocumentBuilderFactory fact=DocumentBuilderFactory.newInstance(); DocumentBuilder parser=fact.newDocumentBuilder(); Document doc=parser.newDocument(); Node root=doc.createElement("licenseSummary"); doc.appendChild(root); Node dependenciesNode=doc.createElement("dependencies"); root.appendChild(dependenciesNode); for ( ProjectLicenseInfo dep : dependencies) { dependenciesNode.appendChild(createDependencyNode(doc,dep)); } Result result=new StreamResult(outputFile.toURI().getPath()); Transformer xformer=TransformerFactory.newInstance().newTransformer(); xformer.setOutputProperty(OutputKeys.INDENT,"yes"); xformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount","2"); xformer.transform(new DOMSource(doc),result); }
Example 103
From project liquibase, under directory /liquibase-core/src/main/java/liquibase/util/xml/.
Source file: DefaultXmlWriter.java

public void write(Document doc,OutputStream outputStream) throws IOException { try { TransformerFactory factory=TransformerFactory.newInstance(); try { factory.setAttribute("indent-number",4); } catch ( Exception e) { ; } Transformer transformer=factory.newTransformer(); transformer.setOutputProperty(OutputKeys.METHOD,"xml"); transformer.setOutputProperty(OutputKeys.INDENT,"yes"); transformer.setOutputProperty(OutputKeys.ENCODING,"UTF-8"); transformer.transform(new DOMSource(doc),new StreamResult(new OutputStreamWriter(outputStream,"utf-8"))); } catch ( TransformerException e) { throw new IOException(e.getMessage()); } }
Example 104
From project lyo.rio, under directory /org.eclipse.lyo.rio.core/src/main/java/org/eclipse/lyo/rio/util/.
Source file: XmlUtils.java

public static String prettyPrint(Document doc){ TransformerFactory tfactory=TransformerFactory.newInstance(); Transformer serializer; StringWriter writer=new StringWriter(); try { serializer=tfactory.newTransformer(); serializer.setOutputProperty(OutputKeys.INDENT,"yes"); serializer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount","2"); serializer.transform(new DOMSource(doc),new StreamResult(writer)); return writer.toString(); } catch ( TransformerException e) { throw new RuntimeException(e); } }
Example 105
From project lyo.server, under directory /org.eclipse.lyo.samples.bugzilla/src/main/java/org/eclipse/lyo/samples/bugzilla/utils/.
Source file: XmlUtils.java

public static String prettyPrint(Document doc){ TransformerFactory tfactory=TransformerFactory.newInstance(); Transformer serializer; StringWriter writer=new StringWriter(); try { serializer=tfactory.newTransformer(); serializer.setOutputProperty(OutputKeys.INDENT,"yes"); serializer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount","2"); serializer.transform(new DOMSource(doc),new StreamResult(writer)); return writer.toString(); } catch ( TransformerException e) { throw new RuntimeException(e); } }
Example 106
From project maven-android-plugin, under directory /src/main/java/com/jayway/maven/plugins/android/.
Source file: AbstractInstrumentationMojo.java

/** * Write the junit report xml file. */ private void writeJunitReportToFile(){ TransformerFactory xfactory=TransformerFactory.newInstance(); Transformer xformer=null; try { xformer=xfactory.newTransformer(); } catch ( TransformerConfigurationException e) { e.printStackTrace(); } Source source=new DOMSource(junitReport); FileWriter writer=null; try { String directory=new StringBuilder().append(project.getBuild().getDirectory()).append("/surefire-reports").toString(); FileUtils.forceMkdir(new File(directory)); String fileName=new StringBuilder().append(directory).append("/TEST-").append(DeviceHelper.getDescriptiveName(device)).append(".xml").toString(); File reportFile=new File(fileName); writer=new FileWriter(reportFile); Result result=new StreamResult(writer); xformer.transform(source,result); getLog().info("Report file written to " + reportFile.getAbsolutePath()); } catch ( IOException e) { threwException=true; exceptionMessages.append("Failed to write test report file"); exceptionMessages.append(e.getMessage()); } catch ( TransformerException e) { threwException=true; exceptionMessages.append("Failed to transform document to write to test report file"); exceptionMessages.append(e.getMessage()); } finally { IOUtils.closeQuietly(writer); } }
Example 107
From project maven-wagon, under directory /wagon-providers/wagon-webdav-jackrabbit/src/main/java/org/apache/jackrabbit/webdav/client/methods/.
Source file: XmlRequestEntity.java

public XmlRequestEntity(Document xmlDocument) throws IOException { super(); ByteArrayOutputStream out=new ByteArrayOutputStream(); try { TransformerFactory factory=TransformerFactory.newInstance(); Transformer transformer=factory.newTransformer(); transformer.setOutputProperty(OutputKeys.METHOD,"xml"); transformer.setOutputProperty(OutputKeys.ENCODING,"UTF-8"); transformer.setOutputProperty(OutputKeys.INDENT,"no"); transformer.transform(new DOMSource(xmlDocument),new StreamResult(out)); } catch ( TransformerException e) { log.error("XML serialization failed",e); IOException exception=new IOException("XML serialization failed"); exception.initCause(e); throw exception; } delegatee=new StringRequestEntity(out.toString(),"text/xml","UTF-8"); }
Example 108
From project mgwt, under directory /src/main/java/com/googlecode/mgwt/linker/linker/.
Source file: XMLPermutationProvider.java

protected String transformDocumentToString(Document document) throws XMLPermutationProviderException { try { StringWriter xml=new StringWriter(); Transformer transformer=TransformerFactory.newInstance().newTransformer(); transformer.setOutputProperty(OutputKeys.INDENT,"yes"); transformer.transform(new DOMSource(document),new StreamResult(xml)); String permMapString=xml.toString(); return permMapString; } catch ( TransformerConfigurationException e) { logger.log(Level.SEVERE,"can not transform document to String"); throw new XMLPermutationProviderException("can not transform document to String",e); } catch ( TransformerFactoryConfigurationError e) { logger.log(Level.SEVERE,"can not transform document to String"); throw new XMLPermutationProviderException("can not transform document to String",e); } catch ( TransformerException e) { logger.log(Level.SEVERE,"can not transform document to String"); throw new XMLPermutationProviderException("can not transform document to String",e); } }
Example 109
From project mylyn.context, under directory /org.eclipse.mylyn.context.tests/src/org/eclipse/mylyn/context/tests/support/.
Source file: DomContextWriter.java

private void writeDOMtoStream(Document document){ Source source=new DOMSource(document); result=new StreamResult(outputStream); Transformer xformer=null; try { xformer=TransformerFactory.newInstance().newTransformer(); xformer.transform(source,result); } catch ( TransformerConfigurationException e) { e.printStackTrace(); } catch ( TransformerFactoryConfigurationError e) { e.printStackTrace(); } catch ( TransformerException e1) { e1.printStackTrace(); } }
Example 110
From project mylyn.incubator, under directory /connector-tutorial/org.eclipse.mylyn.xml3.core/src/org/eclipse/mylyn/internal/examples/xml/core/.
Source file: XmlTaskDataHandler.java

public void writeTaskData(TaskRepository repository,File file,TaskData taskData,IProgressMonitor monitor) throws CoreException { try { DocumentBuilderFactory factory=DocumentBuilderFactory.newInstance(); DocumentBuilder loader=factory.newDocumentBuilder(); Document document; if (taskData.isNew()) { document=loader.newDocument(); document.appendChild(document.createElement("task")); } else { document=loader.parse(file); } updateDocument(repository,file,document,document.getDocumentElement(),taskData,monitor); TransformerFactory transformerFactory=TransformerFactory.newInstance(); Transformer transformer=transformerFactory.newTransformer(); transformer.transform(new DOMSource(document),new StreamResult(file)); } catch ( Exception e) { throw new CoreException(new Status(IStatus.ERROR,XmlCorePlugin.ID_PLUGIN,NLS.bind("Error parsing task ''{0}''",file.getAbsolutePath()),e)); } }
Example 111
From project OpenEMRConnect, under directory /oeclib/src/main/java/ke/go/moh/oec/lib/.
Source file: XmlPacker.java

/** * Packs a DOM Document structure into an XML string. * @param doc the DOM Document structure to pack * @return the packed XML string */ String packDocument(Document doc){ StringWriter stringWriter=new StringWriter(); try { Transformer t=TransformerFactory.newInstance().newTransformer(); t.setOutputProperty(OutputKeys.INDENT,"yes"); t.setOutputProperty(OutputKeys.STANDALONE,"yes"); Source source=new DOMSource(doc); t.transform(source,new StreamResult(stringWriter)); } catch ( TransformerConfigurationException ex) { Logger.getLogger(XmlPacker.class.getName()).log(Level.SEVERE,null,ex); } catch ( TransformerException ex) { Logger.getLogger(XmlPacker.class.getName()).log(Level.SEVERE,null,ex); } String returnString=stringWriter.toString(); try { stringWriter.close(); } catch ( IOException ex) { } return returnString; }
Example 112
From project pegadi, under directory /client/src/main/java/org/pegadi/artis/.
Source file: Artis.java

/** * Saves this article to a file. If filename is <code>null</code> the user will be presented with a filedialog. * @return <code>true</code> if the saving was successfull. * @throws IOException Any error during file handling. */ protected boolean fileSave(String fileName) throws IOException { if (fileName == null) { fileName=getFileName(); if (fileName == null) { return false; } } FileOutputStream fos; try { log.info("Saving file to: " + fileName); fos=new FileOutputStream(fileName); } catch ( FileNotFoundException fnfe) { log.error("File not found (illegal file name?)"); return false; } try { Transformer t=TransformerFactory.newInstance().newTransformer(); t.transform(new DOMSource(article.getDocument()),new StreamResult(fos)); } catch ( TransformerException e) { log.error("Error transforming article",e); } return true; }