Java Code Examples for javax.xml.transform.Transformer

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 Activiti-KickStart, under directory /activiti-kickstart-java/src/main/java/org/activiti/kickstart/service/alfresco/.

Source file: AlfrescoKickstartServiceImpl.java

  41 
vote

protected void prettyLogXml(String xml){
  try {
    Transformer transformer=TransformerFactory.newInstance().newTransformer();
    transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount","2");
    transformer.setOutputProperty(OutputKeys.INDENT,"yes");
    Source xmlInput=new StreamSource(new StringReader(xml));
    StreamResult xmlOutput=new StreamResult(new StringWriter());
    transformer.transform(xmlInput,xmlOutput);
    LOGGER.info(xmlOutput.getWriter().toString());
  }
 catch (  Exception e) {
    e.printStackTrace();
  }
}
 

Example 2

From project DTE, under directory /src/cl/nic/dte/util/.

Source file: Utilities.java

  37 
vote

public static void generatePDF(InputStream xmlFile,InputStream xslFile,OutputStream pdfFile) throws FOPException, FileNotFoundException, TransformerException {
  FopFactory fopFactory=FopFactory.newInstance();
  FOUserAgent foUserAgent=fopFactory.newFOUserAgent();
  Fop fop=fopFactory.newFop(MimeConstants.MIME_PDF,foUserAgent,pdfFile);
  TransformerFactory factory=TransformerFactory.newInstance();
  Transformer transformer=factory.newTransformer(new StreamSource(xslFile));
  transformer.setParameter("versionParam","2.0");
  Source src=new StreamSource(xmlFile);
  Result res=new SAXResult(fop.getDefaultHandler());
  transformer.transform(src,res);
}
 

Example 3

From project Agot-Java, under directory /src/main/java/got/utility/.

Source file: ConnectionCreate.java

  32 
vote

/** 
 * 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 4

From project any23, under directory /core/src/main/java/org/apache/any23/extractor/html/.

Source file: DomUtils.java

  32 
vote

/** 
 * 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 5

From project apb, under directory /modules/apb-base/src/apb/tasks/.

Source file: XsltTask.java

  32 
vote

private Transformer createTransformer() throws TransformerConfigurationException {
  Templates templates=readTemplates();
  Transformer transformer=templates.newTransformer();
  for (  String name : outputProperties.keySet()) {
    transformer.setOutputProperty(name,outputProperties.get(name));
  }
  transformer.setErrorListener(new XsltErrorListener());
  return transformer;
}
 

Example 6

From project bpelunit, under directory /net.bpelunit.framework/src/main/java/net/bpelunit/framework/control/util/.

Source file: BPELUnitUtil.java

  32 
vote

private static String serializeXML(Node node) throws TransformerException {
  TransformerFactory tf=TransformerFactory.newInstance();
  Transformer t=tf.newTransformer();
  t.setOutputProperty(OutputKeys.INDENT,"yes");
  t.setOutputProperty(OutputKeys.METHOD,"xml");
  ByteArrayOutputStream bOS=new ByteArrayOutputStream();
  t.transform(new DOMSource(node),new StreamResult(bOS));
  return bOS.toString();
}
 

Example 7

From project CampusLifePortlets, under directory /src/main/java/org/jasig/portlet/campuslife/dao/.

Source file: ScreenScrapingService.java

  32 
vote

/** 
 * Get portlet-specific XML for clean, valid HTML.
 * @param cleanHtml
 * @return
 * @throws TransformerException
 * @throws IOException
 */
protected String getXml(String cleanHtml) throws TransformerException, IOException {
  final StreamSource xsltSource=new StreamSource(xslt.getInputStream());
  final Transformer identityTransformer=transformerFactory.newTransformer(xsltSource);
  identityTransformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION,"yes");
  final StringWriter outputWriter=new StringWriter();
  final StreamResult outputTarget=new StreamResult(outputWriter);
  final StreamSource xmlSource=new StreamSource(new StringReader(cleanHtml));
  identityTransformer.transform(xmlSource,outputTarget);
  final String content=outputWriter.toString();
  return content;
}
 

Example 8

From project Carolina-Digital-Repository, under directory /metadata/src/main/java/edu/unc/lib/dl/xml/.

Source file: ModsXmlHelper.java

  32 
vote

public static Document transform(Element mods) throws TransformerException {
  Source modsSrc=new JDOMSource(mods);
  JDOMResult dcResult=new JDOMResult();
  Transformer t=null;
  try {
    t=mods2dc.newTransformer();
  }
 catch (  TransformerConfigurationException e) {
    throw new Error("There was a problem configuring the transformer.",e);
  }
  t.transform(modsSrc,dcResult);
  return dcResult.getDocument();
}
 

Example 9

From project cilia-workbench, under directory /cilia-workbench-common/src/fr/liglab/adele/cilia/workbench/common/xml/.

Source file: XMLHelpers.java

  32 
vote

/** 
 * 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 10

From project cloudify, under directory /esc/src/main/java/org/cloudifysource/esc/driver/provisioning/azure/client/.

Source file: MicrosoftAzureModelUtils.java

  32 
vote

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 11

From project codjo-segmentation, under directory /codjo-segmentation-server/src/main/java/net/codjo/segmentation/server/plugin/.

Source file: PreferenceGuiHome.java

  32 
vote

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 12

From project components, under directory /soap/src/test/java/org/switchyard/component/soap/.

Source file: SOAPGatewayTest.java

  32 
vote

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 13

From project core_1, under directory /common/src/main/java/org/switchyard/common/xml/.

Source file: XMLHelper.java

  32 
vote

/** 
 * 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 14

From project Cours-3eme-ann-e, under directory /XML/XSLT-examples/XSLT1/.

Source file: XSLT1.java

  32 
vote

public static void main(String[] args) throws IOException, TransformerException {
  File stylesheet=new File("../../exemples/XSLT/ex8.xslt");
  File srcFile=new File("../../exemples/XSLT/library.xml");
  java.io.Writer destFile=new OutputStreamWriter(System.out,"ISO-8859-1");
  TransformerFactory factory=TransformerFactory.newInstance();
  Source xslt=new StreamSource(stylesheet);
  Transformer transformer=factory.newTransformer(xslt);
  Source request=new StreamSource(srcFile);
  Result response=new StreamResult(destFile);
  transformer.transform(request,response);
}
 

Example 15

From project dcm4che, under directory /dcm4che-tool/dcm4che-tool-hl7rcv/src/main/java/org/dcm4che/tool/hl7rcv/.

Source file: HL7Rcv.java

  32 
vote

private byte[] xslt(HL7Segment msh,byte[] msg,int off,int len) throws Exception {
  String charsetName=HL7Charset.toCharsetName(msh.getField(17,charset));
  ByteArrayOutputStream out=new ByteArrayOutputStream();
  TransformerHandler th=factory.newTransformerHandler(tpls);
  Transformer t=th.getTransformer();
  t.setParameter("MessageControlID",HL7Segment.nextMessageControlID());
  t.setParameter("DateTimeOfMessage",HL7Segment.timeStamp(new Date()));
  if (xsltParams != null)   for (int i=1; i < xsltParams.length; i++, i++)   t.setParameter(xsltParams[i - 1],xsltParams[i]);
  th.setResult(new SAXResult(new HL7ContentHandler(new OutputStreamWriter(out,charsetName))));
  new HL7Parser(th).parse(new InputStreamReader(new ByteArrayInputStream(msg,off,len),charsetName));
  return out.toByteArray();
}
 

Example 16

From project descriptors, under directory /metadata-parser/src/main/java/org/jboss/shrinkwrap/descriptor/metadata/xslt/.

Source file: XsltTransformer.java

  32 
vote

/** 
 * Simple transformation method. 
 * @param sourcePath - Absolute path to source xml file. 
 * @param xsltPath - Absolute path to xslt file. 
 * @param resultDir - Directory where you want to put resulting files. 
 * @param parameters - Map defining global XSLT parameters based via tranformer to the XSLT file. 
 * @throws TransformerException 
 */
public static void simpleTransform(final String sourcePath,final String xsltPath,final String resultDir,final Map<String,String> parameters) throws TransformerException {
  final TransformerFactory tFactory=TransformerFactory.newInstance("net.sf.saxon.TransformerFactoryImpl",null);
  final Transformer transformer=tFactory.newTransformer(new StreamSource(new File(xsltPath)));
  applyParameters(transformer,parameters);
  transformer.transform(new StreamSource(new File(sourcePath)),new StreamResult(new File(resultDir)));
}
 

Example 17

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

  32 
vote

/** 
 * 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 18

From project echo2, under directory /src/exampleapp/chatserver/src/java/echo2example/chatserver/.

Source file: ChatServerServlet.java

  32 
vote

/** 
 * 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 19

From project echo3, under directory /src/server-java/app/nextapp/echo/app/util/.

Source file: DomUtil.java

  32 
vote

/** 
 * 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 20

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

  32 
vote

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 21

From project eclipse-integration-commons, under directory /org.springsource.ide.eclipse.commons.tests.util/src/org/springsource/ide/eclipse/commons/tests/util/.

Source file: StsTestUtil.java

  32 
vote

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 22

From project ElasticSearchExample, under directory /src/main/java/de/jetwick/ese/util/.

Source file: Helper.java

  32 
vote

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 23

From project farebot, under directory /src/com/codebutler/farebot/.

Source file: Utils.java

  32 
vote

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 24

From project Flapi, under directory /src/test/java/unquietcode/tools/flapi/examples/xhtml/.

Source file: XHTMLBuilderExample.java

  32 
vote

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 25

From project gatein-common, under directory /common/src/main/java/org/gatein/common/xml/.

Source file: XMLTools.java

  32 
vote

/** 
 * 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 26

From project gatein-toolbox, under directory /gen/core/src/main/java/org/gatein/descriptorgenerator/.

Source file: Main.java

  32 
vote

private static void reformatXML(Reader src,Writer dst) throws Exception {
  String s="" + "<xsl:stylesheet version=\"1.0\" xmlns:xsl=\"http://www.w3.org/1999/XSL/Transform\">\n" + "<xsl:output method=\"xml\" omit-xml-declaration=\"yes\"/>\n"+ "<xsl:strip-space elements=\"*\"/>\n"+ "<xsl:template match=\"@*|node()\">\n"+ "<xsl:copy>\n"+ "<xsl:apply-templates select=\"@*|node()\"/>\n"+ "</xsl:copy>\n"+ "</xsl:template>\n"+ "</xsl:stylesheet>";
  TransformerFactory factory=TransformerFactory.newInstance();
  factory.setAttribute("indent-number",2);
  Transformer transformer=factory.newTransformer(new StreamSource(new StringReader(s)));
  transformer.setOutputProperty(OutputKeys.ENCODING,"UTF-8");
  transformer.setOutputProperty(OutputKeys.METHOD,"xml");
  transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount",Integer.toString(2));
  transformer.setOutputProperty(OutputKeys.INDENT,"yes");
  StreamSource source=new StreamSource(src);
  StreamResult result=new StreamResult(dst);
  transformer.transform(source,result);
}
 

Example 27

From project Guit, under directory /src/main/java/com/guit/junit/dom/.

Source file: ElementMock.java

  32 
vote

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 28

From project hbasene, under directory /src/main/java/org/hbasene/index/create/.

Source file: IndexConfiguration.java

  32 
vote

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 29

From project integration-tests, under directory /picketlink-openid-tests/src/test/java/org/picketlink/test/integration/openid/.

Source file: OpenIDConsumerUnitTestCase.java

  32 
vote

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 30

From project interoperability-framework, under directory /interfaces/web/wsdl-client/src/main/java/eu/impact_project/wsclient/.

Source file: SOAPresults.java

  32 
vote

private String useXslt(String xml,String xsltPath) throws TransformerException {
  InputStream soapStream=new ByteArrayInputStream(xml.getBytes());
  System.getProperty("javax.xml.parsers.DocumentBuilderFactory","net.sf.saxon.TransformerFactoryImpl");
  Source xmlSource=new StreamSource(soapStream);
  URL urlxsl=getClass().getResource(xsltPath);
  File xsltFile=new File(urlxsl.getFile());
  Source xsltSource=new StreamSource(xsltFile);
  TransformerFactory transFact=TransformerFactory.newInstance();
  Transformer trans=transFact.newTransformer(xsltSource);
  ByteArrayOutputStream htmlOut=new ByteArrayOutputStream();
  Result res=new StreamResult(htmlOut);
  trans.transform(xmlSource,res);
  return htmlOut.toString();
}
 

Example 31

From project jASM_16, under directory /src/main/java/de/codesourcery/jasm16/ide/.

Source file: ProjectConfiguration.java

  32 
vote

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 32

From project jboss-modules, under directory /src/test/java/org/jboss/modules/.

Source file: JAXPModuleTest.java

  32 
vote

public void checkTransformer(Class<?> clazz,boolean fake) throws Exception {
  Transformer parser=invokeMethod(clazz.newInstance(),"transformer");
  TransformerFactory factory=invokeMethod(clazz.newInstance(),"transformerFactory");
  Assert.assertEquals(__TransformerFactory.class.getName(),factory.getClass().getName());
  if (fake) {
    Assert.assertEquals(FakeTransformer.class.getName(),parser.getClass().getName());
  }
 else {
    Assert.assertSame(TransformerFactory.newInstance().newTransformer().getClass(),parser.getClass());
  }
}
 

Example 33

From project jbpmmigration, under directory /src/main/java/org/jbpm/migration/.

Source file: XmlUtils.java

  32 
vote

/** 
 * Format an XML  {@link Source} to a pretty-printable {@link StreamResult}.
 * @param input The (unformatted) input XML  {@link Source}.
 * @return The formatted {@link StreamResult}.
 */
public static void format(final Source input,final Result output){
  try {
    final Transformer transformer=createTransformer(null);
    transformer.setOutputProperty(OutputKeys.INDENT,"yes");
    transformer.transform(input,output);
  }
 catch (  final Exception ex) {
    LOGGER.error("Problem formatting DOM representation.",ex);
  }
}
 

Example 34

From project jcr-openofficeplugin, under directory /src/main/java/org/exoplatform/applications/ooplugin/client/.

Source file: DavCommand.java

  32 
vote

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 35

From project JDave, under directory /jdave-report-plugin/src/java/org/jdave/maven/report/.

Source file: SpecdoxTransformer.java

  32 
vote

public void transform(String filename,String specXmlDir,String outputDir,File xref) throws TransformerException {
  Source xmlSource=new StreamSource(new StringReader("<?xml version=\"1.0\" ?><foo></foo>"));
  Source xsltSource=new StreamSource(Specdox.class.getResourceAsStream("/specdox.xsl"));
  xsltSource.setSystemId("/specdox.xsl");
  TransformerFactory transFact=new TransformerFactoryImpl();
  Transformer trans=transFact.newTransformer(xsltSource);
  trans.setParameter("spec-file-dir",specXmlDir);
  trans.setParameter("xref",xref.getName());
  trans.setParameter("output-dir",outputDir);
  trans.setParameter("frameset-index-filename",filename);
  trans.transform(xmlSource,new StreamResult(System.out));
}
 

Example 36

From project jdeltasync, under directory /src/main/java/com/googlecode/jdeltasync/.

Source file: XmlUtil.java

  32 
vote

/** 
 * 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 37

From project jentrata-msh, under directory /Commons/src/main/java/hk/hku/cecid/piazza/commons/util/.

Source file: PropertyTree.java

  32 
vote

/** 
 * 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 38

From project Jetwick, under directory /src/main/java/de/jetwick/util/.

Source file: Helper.java

  32 
vote

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 39

From project jgraphx, under directory /src/com/mxgraph/util/.

Source file: mxXmlUtils.java

  32 
vote

/** 
 * 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 40

From project jmeter-components, under directory /src/main/java/com/atlantbh/jmeter/plugins/xmlformatter/.

Source file: XMLFormatPostProcessor.java

  32 
vote

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 41

From project jOOX, under directory /jOOX/src/main/java/org/joox/.

Source file: Util.java

  32 
vote

/** 
 * Transform an  {@link Element} into a <code>String</code>.
 */
static final String toString(Element element){
  try {
    ByteArrayOutputStream out=new ByteArrayOutputStream();
    Transformer transformer=TransformerFactory.newInstance().newTransformer();
    transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION,"yes");
    Source source=new DOMSource(element);
    Result target=new StreamResult(out);
    transformer.transform(source,target);
    return out.toString();
  }
 catch (  Exception e) {
    return "[ ERROR IN toString() : " + e.getMessage() + " ]";
  }
}
 

Example 42

From project kabeja, under directory /blocks/xslt/src/main/java/org/kabeja/xslt/.

Source file: SAXXSLTFilter.java

  32 
vote

protected void setParameters(TransformerHandler h){
  Transformer tf=h.getTransformer();
  Iterator i=this.properties.keySet().iterator();
  while (i.hasNext()) {
    String name=(String)i.next();
    if (!PROPERTY_XSLTSTYLESHEET.equals(i)) {
      tf.setParameter(name,this.properties.get(name));
    }
  }
}
 

Example 43

From project lenya, under directory /org.apache.lenya.core.cocoon/src/main/java/org/apache/lenya/cms/cocoon/source/.

Source file: RepositorySource.java

  32 
vote

void transform(org.w3c.dom.Document edoc,PipedOutputStream pos) throws TransformerException {
  TransformerFactory tFactory=TransformerFactory.newInstance();
  Transformer transformer=tFactory.newTransformer();
  transformer.setOutputProperty("encoding","UTF-8");
  transformer.setOutputProperty("indent","yes");
  transformer.transform(new DOMSource(edoc),new StreamResult(pos));
}
 

Example 44

From project libra, under directory /tests/org.eclipse.libra.facet.test/src/org/eclipse/libra/facet/test/.

Source file: WebContextRootSynchronizerTest.java

  32 
vote

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 45

From project litle-sdk-for-java, under directory /lib/apache-cxf-2.5.2/samples/in_jvm_transport/src/main/java/demo/colocated/client/.

Source file: DispatchSourceClient.java

  32 
vote

private static String decodeSource(Source source,String uri,String name) throws Exception {
  Transformer transformer=TransformerFactory.newInstance().newTransformer();
  ContentHandler handler=new ContentHandler(uri,name);
  transformer.transform(source,new SAXResult(handler));
  return handler.getValue();
}
 

Example 46

From project lyo.core, under directory /OSLC4JJenaProvider/src/org/eclipse/lyo/oslc4j/provider/jena/.

Source file: JenaModelHelper.java

  32 
vote

private static Transformer createTransformer(){
  try {
    Transformer transformer=TransformerFactory.newInstance().newTransformer();
    transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION,"yes");
    return transformer;
  }
 catch (  TransformerException e) {
    throw new RuntimeException(e);
  }
}
 

Example 47

From project lyo.testsuite, under directory /org.eclipse.lyo.testsuite.server/src/main/java/org/eclipse/lyo/testsuite/server/util/.

Source file: OSLCUtils.java

  32 
vote

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 48

From project MEditor, under directory /editor-common/editor-common-server/src/main/java/cz/mzk/editor/server/fedora/utils/.

Source file: FedoraUtils.java

  32 
vote

/** 
 * @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 49

From project mob, under directory /com.netappsid.mob/src/com/netappsid/mob/ejb3/xml/.

Source file: PersistenceUnitUtils.java

  32 
vote

public Document applyXslt(Document document,URL... xslt) throws IOException, TransformerException {
  Document temp=document;
  for (  URL url : xslt) {
    Transformer transformer=transformerFactory.newTransformer(new StreamSource(url.openStream()));
    DocumentSource source=new DocumentSource(temp);
    DocumentResult result=new DocumentResult();
    transformer.transform(source,result);
    temp=result.getDocument();
  }
  return temp;
}
 

Example 50

From project Mockey, under directory /src/java/com/mockey/storage/xml/.

Source file: MockeyXmlFactory.java

  32 
vote

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 51

From project mylyn.context, under directory /org.eclipse.mylyn.context.core/src/org/eclipse/mylyn/internal/context/core/.

Source file: SaxContextWriter.java

  32 
vote

public void writeContextToStream(IInteractionContext context) throws IOException {
  if (outputStream == null) {
    IOException ioe=new IOException("OutputStream not set");
    throw ioe;
  }
  try {
    Transformer transformer=TransformerFactory.newInstance().newTransformer();
    transformer.transform(new SAXSource(new SaxWriter(),new InteractionContextInputSource(context)),new StreamResult(outputStream));
  }
 catch (  TransformerException e) {
    StatusHandler.log(new Status(IStatus.ERROR,ContextCorePlugin.ID_PLUGIN,"Could not write context",e));
    throw new IOException(e.getMessage());
  }
}
 

Example 52

From project ndg, under directory /ndg-commons-core/src/main/java/br/org/indt/ndg/common/.

Source file: ResultWriter.java

  32 
vote

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 53

From project ant4eclipse, under directory /org.ant4eclipse.ant.pde/src/org/ant4eclipse/ant/pde/.

Source file: PatchFeatureManifestTask.java

  31 
vote

/** 
 * 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 54

From project autopsy, under directory /Core/src/org/sleuthkit/autopsy/coreutils/.

Source file: XMLUtil.java

  31 
vote

/** 
 * 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 55

From project bioclipse.seneca, under directory /plugins/net.bioclipse.seneca/src/org/openscience/cdk/structgen/pubchem/.

Source file: PubchemStructureGenerator.java

  31 
vote

/** 
 * 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 56

From project blacktie, under directory /blacktie-admin-services/src/main/java/org/jboss/narayana/blacktie/administration/.

Source file: BlacktieStompAdministrationService.java

  31 
vote

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 57

From project CalendarPortlet, under directory /src/main/java/org/jasig/portlet/calendar/processor/.

Source file: XSLTICalendarContentProcessorImpl.java

  31 
vote

protected final InputStream transformToICal(InputStream in) throws CalendarException {
  StreamSource xmlSource=new StreamSource(in);
  ByteArrayOutputStream out=new ByteArrayOutputStream();
  try {
    log.debug("Stylesheet is " + xslFile);
    InputStream xsl=this.getClass().getClassLoader().getResourceAsStream(xslFile);
    Transformer tx=TransformerFactory.newInstance().newTransformer(new StreamSource(xsl));
    tx.transform(xmlSource,new StreamResult(out));
    log.debug(out.toString());
    InputStream result=new ByteArrayInputStream(out.toByteArray());
    return result;
  }
 catch (  TransformerConfigurationException tce) {
    log.error("Failed to configure transformer",tce);
    throw new CalendarException("Failed to configure transformer",tce);
  }
catch (  TransformerException txe) {
    throw new CalendarException("Failed transformation",txe);
  }
}
 

Example 58

From project chukwa, under directory /src/main/java/org/apache/hadoop/chukwa/inputtools/jplugin/.

Source file: ChukwaMetricsList.java

  31 
vote

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 59

From project cidb, under directory /ncbieutils-access-service/src/main/java/edu/toronto/cs/cidb/ncbieutils/.

Source file: NCBIEUtilsAccessService.java

  31 
vote

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 60

From project cider, under directory /src/net/yacy/cider/parser/idiom/rdfa/.

Source file: RDFaParserImp.java

  31 
vote

public void parse(Reader in,String base) throws IOException, TransformerException, TransformerConfigurationException {
  if (theTemplates == null) {
    this.getClass().getClassLoader();
    StreamSource aSource=new StreamSource(ClassLoader.getSystemResource("net/yacy/serlex/parser/rdfa/RDFaParser.xsl").openStream());
    TransformerFactory aFactory=TransformerFactory.newInstance();
    theTemplates=aFactory.newTemplates(aSource);
  }
  Transformer aTransformer=theTemplates.newTransformer();
  aTransformer.setParameter("parser",this);
  aTransformer.setParameter("url",base);
  aTransformer.transform(new StreamSource(in),new StreamResult(new OutputStream(){
    public void write(    int b) throws IOException {
    }
  }
));
}
 

Example 61

From project Cilia_1, under directory /framework/runtime/src/main/java/fr/liglab/adele/cilia/framework/data/.

Source file: XmlTools.java

  31 
vote

/** 
 * 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 62

From project cipango, under directory /cipango-console/src/main/java/org/cipango/console/.

Source file: SvgServlet.java

  31 
vote

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 63

From project code_swarm, under directory /src/org/codeswarm/repositoryevents/.

Source file: CodeSwarmEventsSerializer.java

  31 
vote

/** 
 * 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 64

From project code_swarm-gource-my-conf, under directory /src/org/codeswarm/repositoryevents/.

Source file: CodeSwarmEventsSerializer.java

  31 
vote

/** 
 * 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 65

From project codjo-data-process, under directory /codjo-data-process-common/src/main/java/net/codjo/dataprocess/common/util/.

Source file: XMLUtils.java

  31 
vote

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 66

From project Core_2, under directory /parser-xml/src/main/java/org/jboss/forge/parser/xml/.

Source file: XMLParser.java

  31 
vote

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 67

From project crash, under directory /jcr/core/src/main/java/org/crsh/jcr/.

Source file: Exporter.java

  31 
vote

@Override public void startElement(String uri,String localName,String qName,Attributes attributes) throws SAXException {
  try {
    String fileName=XML.fileName(qName);
    fs.startDirectory(fileName);
    ByteArrayOutputStream out=new ByteArrayOutputStream();
    StreamResult streamResult=new StreamResult(out);
    SAXTransformerFactory tf=(SAXTransformerFactory)SAXTransformerFactory.newInstance();
    TransformerHandler hd=tf.newTransformerHandler();
    Transformer serializer=hd.getTransformer();
    serializer.setOutputProperty(OutputKeys.ENCODING,"UTF-8");
    serializer.setOutputProperty(OutputKeys.INDENT,"yes");
    hd.setResult(streamResult);
    hd.startDocument();
    for (    Map.Entry<String,String> mapping : mappings.entrySet()) {
      String prefix=mapping.getKey();
      hd.startPrefixMapping(prefix,mapping.getValue());
    }
    hd.startElement(uri,localName,qName,attributes);
    hd.endElement(uri,localName,qName);
    for (    String prefix : mappings.keySet()) {
      hd.endPrefixMapping(prefix);
    }
    hd.endDocument();
    out.close();
    byte[] content=out.toByteArray();
    fs.file("crash__content.xml",content.length,new ByteArrayInputStream(content));
  }
 catch (  Exception e) {
    throw new SAXException(e);
  }
}
 

Example 68

From project dawn-common, under directory /org.dawb.common.util/src/org/dawb/common/util/xml/.

Source file: XMLUtils.java

  31 
vote

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 69

From project DeuceSTM, under directory /src/test/org/deuce/benchmark/lee/.

Source file: XMLHelper.java

  31 
vote

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 70

From project dev-examples, under directory /template/src/main/java/org/richfaces/example/.

Source file: XMLBodySerializer.java

  31 
vote

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 71

From project droolsjbpm-integration, under directory /drools-camel/src/test/java/org/drools/camel/component/.

Source file: BatchTest.java

  31 
vote

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 72

From project eclim, under directory /org.eclim.core/java/org/eclim/plugin/core/command/xml/.

Source file: FormatCommand.java

  31 
vote

/** 
 * {@inheritDoc}
 */
public Object execute(CommandLine commandLine) throws Exception {
  String restoreNewline=null;
  FileInputStream in=null;
  try {
    String file=commandLine.getValue(Options.FILE_OPTION);
    int indent=commandLine.getIntValue(Options.INDENT_OPTION);
    String format=commandLine.getValue("m");
    String newline=System.getProperty("line.separator");
    if (newline.equals("\r\n") && format.equals("unix")) {
      restoreNewline=newline;
      System.setProperty("line.separator","\n");
    }
 else     if (newline.equals("\n") && format.equals("dos")) {
      restoreNewline=newline;
      System.setProperty("line.separator","\r\n");
    }
    TransformerFactory factory=TransformerFactory.newInstance();
    factory.setAttribute("indent-number",Integer.valueOf(indent));
    Transformer serializer=factory.newTransformer();
    serializer.setOutputProperty(OutputKeys.INDENT,"yes");
    StringWriter out=new StringWriter();
    in=new FileInputStream(file);
    serializer.transform(new SAXSource(new InputSource(in)),new StreamResult(out));
    return out.toString();
  }
  finally {
    IOUtils.closeQuietly(in);
    if (restoreNewline != null) {
      System.setProperty("line.separator",restoreNewline);
    }
  }
}
 

Example 73

From project empire-db, under directory /empire-db/src/main/java/org/apache/empire/xml/.

Source file: XMLWriter.java

  31 
vote

/** 
 * 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 74

From project Euclidean-Pattern-Generator, under directory /src/com/hisschemoller/sequencer/controller/file/.

Source file: SaveProjectCommand.java

  31 
vote

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 75

From project fedora-client, under directory /fedora-client-core/src/main/java/com/yourmediashelf/fedora/util/.

Source file: XmlSerializer.java

  31 
vote

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 76

From project fits_1, under directory /src/edu/harvard/hul/ois/fits/.

Source file: Fits.java

  31 
vote

public static void outputStandardSchemaXml(FitsOutput fitsOutput,OutputStream out) throws XMLStreamException, IOException {
  XmlContent xml=fitsOutput.getStandardXmlContent();
  XMLOutputFactory xmlOutputFactory=XMLOutputFactory.newInstance();
  Transformer transformer=null;
  TransformerFactory tFactory=TransformerFactory.newInstance();
  String prettyPrintXslt=FITS_XML + "prettyprint.xslt";
  try {
    Templates template=tFactory.newTemplates(new StreamSource(prettyPrintXslt));
    transformer=template.newTransformer();
  }
 catch (  Exception e) {
    transformer=null;
  }
  if (xml != null && transformer != null) {
    xml.setRoot(true);
    ByteArrayOutputStream xmlOutStream=new ByteArrayOutputStream();
    OutputStream xsltOutStream=new ByteArrayOutputStream();
    try {
      XMLStreamWriter sw=xmlOutputFactory.createXMLStreamWriter(xmlOutStream);
      xml.output(sw);
      Source source=new StreamSource(new ByteArrayInputStream(xmlOutStream.toByteArray()));
      Result rstream=new StreamResult(xsltOutStream);
      transformer.transform(source,rstream);
      out.write(xsltOutStream.toString().getBytes("UTF-8"));
      out.flush();
    }
 catch (    Exception e) {
      System.err.println("error converting output to a standard schema format");
    }
 finally {
      xmlOutStream.close();
      xsltOutStream.close();
    }
  }
 else {
    System.err.println("Error: output cannot be converted to a standard schema format for this file");
  }
}
 

Example 77

From project flyingsaucer, under directory /flying-saucer-core/src/main/java/org/xhtmlrenderer/resource/.

Source file: XMLResource.java

  31 
vote

XMLResource createXMLResource(XMLResource target){
  Source input=null;
  DOMResult output=null;
  TransformerFactory xformFactory=null;
  Transformer idTransform=null;
  XMLReader xmlReader=null;
  long st=0L;
  xmlReader=XMLResource.newXMLReader();
  addHandlers(xmlReader);
  setParserFeatures(xmlReader);
  st=System.currentTimeMillis();
  try {
    input=new SAXSource(xmlReader,target.getResourceInputSource());
    DocumentBuilderFactory dbf=DocumentBuilderFactory.newInstance();
    dbf.setNamespaceAware(true);
    dbf.setValidating(false);
    output=new DOMResult(dbf.newDocumentBuilder().newDocument());
    xformFactory=TransformerFactory.newInstance();
    idTransform=xformFactory.newTransformer();
  }
 catch (  Exception ex) {
    throw new XRRuntimeException("Failed on configuring SAX to DOM transformer.",ex);
  }
  try {
    idTransform.transform(input,output);
  }
 catch (  Exception ex) {
    throw new XRRuntimeException("Can't load the XML resource (using TRaX transformer). " + ex.getMessage(),ex);
  }
  long end=System.currentTimeMillis();
  target.setElapsedLoadTime(end - st);
  XRLog.load("Loaded document in ~" + target.getElapsedLoadTime() + "ms");
  target.setDocument((Document)output.getNode());
  return target;
}
 

Example 78

From project freemind, under directory /freemind/accessories/plugins/.

Source file: ExportToImage.java

  31 
vote

public void transForm(Source xmlSource,InputStream xsltStream,File resultFile,String areaCode){
  Source xsltSource=new StreamSource(xsltStream);
  Result result=new StreamResult(resultFile);
  try {
    TransformerFactory transFact=TransformerFactory.newInstance();
    Transformer trans=transFact.newTransformer(xsltSource);
    trans.setParameter("destination_dir",resultFile.getName() + "_files/");
    trans.setParameter("area_code",areaCode);
    trans.setParameter("folding_type",getController().getFrame().getProperty("html_export_folding"));
    trans.transform(xmlSource,result);
  }
 catch (  Exception e) {
    freemind.main.Resources.getInstance().logException(e);
  }
  ;
  return;
}
 

Example 79

From project galaxy, under directory /src/co/paralleluniverse/common/util/.

Source file: DOMElementProprtyEditor.java

  31 
vote

@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 80

From project GNDMS, under directory /taskflows/publishing/server/src/de/zib/gndms/taskflows/publishing/server/.

Source file: PublishingTFAction.java

  31 
vote

@Override protected void onInProgress(@NotNull String wid,@NotNull TaskState state,boolean isRestartedTask,boolean altTaskState) throws Exception {
  ensureOrder();
  PublishingOrder order=getOrderBean();
  final Slice slice=this.findSlice(order.getSliceId());
  if (null == slice)   throw new NoSuchResourceException("Could not find slice with id " + order.getSliceId());
{
    Specifier<Void> sliceSpecifier=UriFactory.createSliceSpecifier(getGridConfig().getBaseUrl(),slice.getSubspace().getId(),slice.getKind().getId(),order.getSliceId());
    setSliceSpecifier(sliceSpecifier);
  }
  if (null == slice) {
    throw new IllegalArgumentException("No Slice set in Order!");
  }
  final MapConfig config=new MapConfig(getConfigMapData());
  final String slicePath=slice.getSubspace().getPathForSlice(slice);
  final String oldMetaFile=slicePath + File.separatorChar + order.getMetadataFile();
  final String newMetaFile=slicePath + "." + order.getMetadataFile();
  final String oidPrefix=config.hasOption("oidPrefix") ? config.getOption("oidPrefix") : "";
  final String newOid=oidPrefix + "." + slice.getId()+ "."+ order.getMetadataFile().substring(0,order.getMetadataFile().length() - 4);
  try {
    Source xsltSource=new StreamSource(this.getClass().getResourceAsStream(PublishingTaskFlowMeta.XSLT_FILE));
    Transformer transformer=transformerFactory.newTransformer(xsltSource);
    transformer.setParameter("identifier",newOid);
    transformer.transform(new StreamSource(new FileInputStream(oldMetaFile)),new StreamResult(new FileOutputStream(newMetaFile)));
  }
 catch (  RuntimeException e) {
    transit(TaskState.FAILED);
  }
  slice.setPublished(true);
  updateSlice(slice);
  getSliceProvider().invalidate(slice.getId());
  setProgress(1);
  transitWithPayload(new PublishingTaskFlowResult(),TaskState.FINISHED);
  super.onInProgress(wid,state,isRestartedTask,altTaskState);
}
 

Example 81

From project GnucashMobile, under directory /GnucashMobile/src/org/gnucash/android/ui/accounts/.

Source file: ExportDialogFragment.java

  31 
vote

/** 
 * 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 82

From project grails-ide, under directory /org.grails.ide.eclipse.core/src/org/grails/ide/eclipse/core/model/.

Source file: GrailsInstallManager.java

  31 
vote

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 83

From project gravitext, under directory /gravitext-xmlprod/src/main/java/com/gravitext/xml/producer/perftests/.

Source file: JaxpPerfTest.java

  31 
vote

protected void serializeGraph(List<GraphItem> graph,TestOutput out) throws IOException, TransformerConfigurationException, TransformerFactoryConfigurationError, SAXException {
  StreamResult sr;
  if (useWriter())   sr=new StreamResult(out.getWriter());
 else   sr=new StreamResult(out.getStream());
  SAXTransformerFactory tf=(SAXTransformerFactory)SAXTransformerFactory.newInstance();
  TransformerHandler hd=tf.newTransformerHandler();
  Transformer serializer=hd.getTransformer();
  serializer.setOutputProperty(OutputKeys.ENCODING,getEncoding());
  serializer.setOutputProperty(OutputKeys.DOCTYPE_SYSTEM,"bogus.dtd");
  if (!getIndent().isCompressed()) {
    serializer.setOutputProperty(OutputKeys.INDENT,"yes");
  }
  hd.setResult(sr);
  hd.startDocument();
  hd.startElement("","","testdoc",emptyAtts);
  for (  GraphItem g : graph) {
    AttributesImpl atts=new AttributesImpl();
    atts.addAttribute("","","name","CDATA",g.getName());
    atts.addAttribute("","","value","CDATA",String.valueOf(g.getValue()));
    atts.addAttribute("urn:some-unique-id","score","graph:score","CDATA",String.valueOf(g.getScore()));
    hd.startElement("urn:some-unique-id","item","graph:item",atts);
    hd.startElement("","","content",emptyAtts);
    String cdata=g.getContent();
    hd.characters(cdata.toCharArray(),0,cdata.length());
    hd.endElement("","","content");
    if (g.getList().size() > 0) {
      hd.startElement("","","list",emptyAtts);
      for (      String gl : g.getList()) {
        hd.startElement("","","listItem",emptyAtts);
        hd.characters(gl.toCharArray(),0,gl.length());
        hd.endElement("","","listItem");
      }
      hd.endElement("","","list");
    }
    hd.endElement("urn:some-unique-id","item","graph:item");
  }
  hd.endElement("","","testdoc");
  hd.endDocument();
}
 

Example 84

From project HiTune_1, under directory /chukwa-hitune-dist/src/java/org/apache/hadoop/chukwa/inputtools/jplugin/.

Source file: ChukwaMetricsList.java

  31 
vote

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 85

From project jagger, under directory /chassis/core/src/main/java/com/griddynamics/jagger/reporting/.

Source file: ReportInputStream.java

  31 
vote

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 86

From project jangaroo-tools, under directory /asdoc-scraping/src/main/java/net/jangaroo/tools/asdocscreenscraper/.

Source file: ASDocScreenScraper.java

  31 
vote

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 87

From project jbpm-form-builder, under directory /jbpm-gwt-form-builder/src/main/java/org/jbpm/formbuilder/server/render/xsl/.

Source file: Renderer.java

  31 
vote

@Override public Object render(URL url,Map<String,Object> inputData) throws RendererException {
  try {
    StreamSource template=new StreamSource(url.openStream());
    Transformer transformer=factory.newTransformer(template);
    StringWriter writer=new StringWriter();
    StreamResult result=new StreamResult(writer);
    StreamSource inputSource=new StreamSource(toInputString(inputData));
    transformer.transform(inputSource,result);
    return writer.toString();
  }
 catch (  IOException e) {
    throw new RendererException("I/O problem rendering " + url,e);
  }
catch (  TransformerConfigurationException e) {
    throw new RendererException("transformer configuration problem rendering " + url,e);
  }
catch (  TransformerException e) {
    throw new RendererException("transformer problem rendering " + url,e);
  }
 finally {
    new File(url.getFile()).delete();
  }
}
 

Example 88

From project jCAE, under directory /amibe/src/org/jcae/mesh/xmldata/.

Source file: XMLHelper.java

  31 
vote

/** 
 * Write a DOM to a file. 
 */
public static void writeXML(Document document,File file) throws IOException {
  StreamResult result=new StreamResult(new BufferedOutputStream(new FileOutputStream(file)));
  TransformerFactory transFactory=TransformerFactory.newInstance();
  try {
    Transformer transformer=transFactory.newTransformer();
    transformer.setOutputProperty("indent","yes");
    transformer.transform(new DOMSource(document),result);
  }
 catch (  TransformerConfigurationException ex) {
    throw new IOException(ex.getMessage());
  }
catch (  TransformerException ex) {
    throw new IOException(ex.getMessage());
  }
  result.getOutputStream().close();
}
 

Example 89

From project jdocbook-core, under directory /src/main/java/org/jboss/jdocbook/profile/.

Source file: ProfilerImpl.java

  31 
vote

/** 
 * {@inheritDoc}
 */
public void profile(ProfilingSource profilingSource){
  try {
    final File targetFile=profilingSource.resolveProfiledDocumentFile();
    log.info("applying DocBook profiling [" + targetFile.getAbsolutePath() + "]");
    if (!targetFile.getParentFile().exists()) {
      boolean created=targetFile.getParentFile().mkdirs();
      if (!created) {
        log.info("Unable to create parent directory " + targetFile.getAbsolutePath());
      }
    }
    final String languageString=render(profilingSource.getLanguage());
    Transformer xslt=transformerBuilder().buildStandardTransformer(Constants.MAIN_PROFILE_XSL_RESOURCE);
    xslt.setParameter("l10n.gentext.language",languageString);
    final String profilingAttributeName=configuration().getProfiling().getAttributeName();
    if (profilingAttributeName == null || "lang".equals(profilingAttributeName)) {
      xslt.setParameter("profile.attribute","lang");
      xslt.setParameter("profile.lang",languageString);
    }
 else {
      xslt.setParameter("profile.attribute",profilingAttributeName);
      xslt.setParameter("profile.value",configuration().getProfiling().getAttributeValue());
    }
    xslt.transform(buildSource(profilingSource.resolveDocumentFile()),buildResult(targetFile));
  }
 catch (  TransformerException e) {
    throw new XSLTException("error performing translation [" + e.getLocationAsString() + "] : "+ e.getMessage(),e);
  }
}
 

Example 90

From project jetty-project, under directory /jetty-jboss/src/main/java/org/jboss/jetty/.

Source file: Jetty.java

  31 
vote

/** 
 * @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 91

From project jMemorize, under directory /src/jmemorize/core/io/.

Source file: XmlBuilder.java

  31 
vote

/** 
 * 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 92

From project JsTestDriver, under directory /JsTestDriver/src/com/google/jstestdriver/output/.

Source file: TestXmlSerializer.java

  31 
vote

public TestXmlSerializer(Writer fileWriter){
  try {
    transformerHandler=((SAXTransformerFactory)SAXTransformerFactory.newInstance()).newTransformerHandler();
    Transformer transformer=transformerHandler.getTransformer();
    transformer.setOutputProperty(OutputKeys.METHOD,"xml");
    transformer.setOutputProperty(OutputKeys.ENCODING,"UTF-8");
    transformer.setOutputProperty(OutputKeys.INDENT,"yes");
    transformerHandler.setResult(new StreamResult(fileWriter));
  }
 catch (  TransformerConfigurationException e) {
    throw new RuntimeException(e);
  }
catch (  TransformerFactoryConfigurationError e) {
    throw new RuntimeException(e);
  }
}
 

Example 93

From project jsword, under directory /src/main/java/org/crosswire/common/xml/.

Source file: TransformingSAXEventProvider.java

  31 
vote

@Override public void transform(Source xmlSource,Result outputTarget) throws TransformerException {
  TemplateInfo tinfo;
  try {
    tinfo=getTemplateInfo();
  }
 catch (  IOException e) {
    throw new TransformerException(e);
  }
  Transformer transformer=tinfo.getTemplates().newTransformer();
  for (  Object obj : outputs.keySet()) {
    String key=(String)obj;
    String val=getOutputProperty(key);
    transformer.setOutputProperty(key,val);
  }
  for (  String key : params.keySet()) {
    Object val=params.get(key);
    transformer.setParameter(key,val);
  }
  if (errors != null) {
    transformer.setErrorListener(errors);
  }
  if (resolver != null) {
    transformer.setURIResolver(resolver);
  }
  transformer.transform(xmlSource,outputTarget);
}
 

Example 94

From project jumpnevolve, under directory /lib/slick/src/org/newdawn/slick/particles/.

Source file: ParticleIO.java

  31 
vote

/** 
 * 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 95

From project Kairos, under directory /src/java/org/apache/nutch/util/.

Source file: DomUtil.java

  31 
vote

/** 
 * 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 96

From project Kayak, under directory /Kayak-ui/src/main/java/com/github/kayak/ui/connections/.

Source file: ConnectionManager.java

  31 
vote

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 97

From project knicker, under directory /src/main/java/net/jeremybrooks/knicker/.

Source file: Util.java

  31 
vote

/** 
 * Call the URI using an HTTP GET request, returning the response as an xml Document instance. <p/> This method accepts an AuthenticationToken, and will set the request header parameter 'auth_token' with the token. If the token is null, the header parameter will not be set.
 * @param uri   the URI to call.
 * @param token the authentication token.
 * @return server response as a Document instance, or null if the serverdid not return anything.
 * @throws KnickerException if the uri is invalid, or if there are any errors.
 */
static Document doGet(String uri,AuthenticationToken token) throws KnickerException {
  if (uri == null || uri.trim().isEmpty()) {
    throw new KnickerException("Parameter uri cannot be null or empty.");
  }
  if (!uri.startsWith("http://") && !uri.startsWith("https://")) {
    throw new KnickerException("Parameter uri must start with http:// or https://");
  }
  KnickerLogger.getLogger().log("GET URL: '" + uri + "'");
  CharArrayWriter writer;
  try {
    URL url=parseUrl(uri);
    URLConnection conn=url.openConnection();
    conn.setConnectTimeout(getConnTimeout());
    conn.setReadTimeout(getReadTimeout());
    conn.addRequestProperty("api_key",System.getProperty("WORDNIK_API_KEY"));
    if (token != null) {
      conn.addRequestProperty("auth_token",token.getToken());
    }
    StreamSource streamSource=new StreamSource(conn.getInputStream());
    writer=new CharArrayWriter();
    StreamResult streamResult=new StreamResult(writer);
    TransformerFactory factory=TransformerFactory.newInstance();
    Transformer transformer=factory.newTransformer();
    transformer.transform(streamSource,streamResult);
    KnickerLogger.getLogger().log("----------RESPONSE START----------");
    KnickerLogger.getLogger().log(writer.toString());
    KnickerLogger.getLogger().log("----------RESPONSE END----------");
  }
 catch (  Exception e) {
    throw new KnickerException("Error getting a response from the server.",e);
  }
  return getDocument(writer.toString());
}
 

Example 98

From project kwegg, under directory /lib/readwrite/opennlp-tools/src/java/opennlp/tools/dictionary/serializer/.

Source file: DictionarySerializer.java

  31 
vote

/** 
 * Serializes the given entries to the given  {@link OutputStream}.
 * @param out 
 * @param entries 
 * @throws IOException If an I/O error occurs
 */
public static void serialize(OutputStream out,Iterator entries) throws IOException {
  GZIPOutputStream gzipOut=new GZIPOutputStream(out);
  StreamResult streamResult=new StreamResult(gzipOut);
  SAXTransformerFactory tf=(SAXTransformerFactory)SAXTransformerFactory.newInstance();
  TransformerHandler hd;
  try {
    hd=tf.newTransformerHandler();
  }
 catch (  TransformerConfigurationException e1) {
    throw new AssertionError("The Tranformer configuration must be valid!");
  }
  Transformer serializer=hd.getTransformer();
  serializer.setOutputProperty(OutputKeys.ENCODING,CHARSET);
  serializer.setOutputProperty(OutputKeys.INDENT,"yes");
  hd.setResult(streamResult);
  try {
    hd.startDocument();
    hd.startElement("","",DICTIONARY_ELEMENT,new AttributesImpl());
    while (entries.hasNext()) {
      Entry entry=(Entry)entries.next();
      serializeEntry(hd,entry);
    }
    hd.endElement("","",DICTIONARY_ELEMENT);
    hd.endDocument();
  }
 catch (  SAXException e) {
    throw new IOException("There was an error during serialization!");
  }
  gzipOut.finish();
}
 

Example 99

From project LABPipe, under directory /src/org/bultreebank/labpipe/tools/.

Source file: ClarkAnnotation.java

  31 
vote

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 100

From project leviathan, under directory /scrapper/src/main/java/com/zaubersoftware/leviathan/api/engine/impl/pipe/.

Source file: XMLPipe.java

  31 
vote

/** 
 * 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 101

From project liquibase, under directory /liquibase-core/src/main/java/liquibase/util/xml/.

Source file: DefaultXmlWriter.java

  31 
vote

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 102

From project lyo.rio, under directory /org.eclipse.lyo.rio.core/src/main/java/org/eclipse/lyo/rio/util/.

Source file: XmlUtils.java

  31 
vote

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 103

From project lyo.server, under directory /org.eclipse.lyo.samples.bugzilla/src/main/java/org/eclipse/lyo/samples/bugzilla/utils/.

Source file: XmlUtils.java

  31 
vote

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 104

From project maven-android-plugin, under directory /src/main/java/com/jayway/maven/plugins/android/.

Source file: AbstractInstrumentationMojo.java

  31 
vote

/** 
 * 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 105

From project maven-doxia, under directory /doxia-modules/doxia-module-fo/src/main/java/org/apache/maven/doxia/module/fo/.

Source file: FoUtils.java

  31 
vote

/** 
 * Converts an FO file to a PDF file using FOP.
 * @param fo the FO file, not null.
 * @param pdf the target PDF file, not null.
 * @param resourceDir The base directory for relative path resolution, could be null.If null, defaults to the parent directory of fo.
 * @param foUserAgent the FOUserAgent to use.May be null, in which case a default user agent will be used.
 * @throws javax.xml.transform.TransformerException In case of a conversion problem.
 * @since 1.1.1
 */
public static void convertFO2PDF(File fo,File pdf,String resourceDir,FOUserAgent foUserAgent) throws TransformerException {
  FOUserAgent userAgent=(foUserAgent == null ? getDefaultUserAgent(fo,resourceDir) : foUserAgent);
  OutputStream out=null;
  try {
    try {
      out=new BufferedOutputStream(new FileOutputStream(pdf));
    }
 catch (    IOException e) {
      throw new TransformerException(e);
    }
    Result res=null;
    try {
      Fop fop=FOP_FACTORY.newFop(MimeConstants.MIME_PDF,userAgent,out);
      res=new SAXResult(fop.getDefaultHandler());
    }
 catch (    FOPException e) {
      throw new TransformerException(e);
    }
    Transformer transformer=null;
    try {
      transformer=TRANSFORMER_FACTORY.newTransformer();
    }
 catch (    TransformerConfigurationException e) {
      throw new TransformerException(e);
    }
    transformer.transform(new StreamSource(fo),res);
  }
  finally {
    IOUtil.close(out);
  }
}
 

Example 106

From project maven-wagon, under directory /wagon-providers/wagon-webdav-jackrabbit/src/main/java/org/apache/jackrabbit/webdav/client/methods/.

Source file: XmlRequestEntity.java

  31 
vote

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 107

From project mgwt, under directory /src/main/java/com/googlecode/mgwt/linker/linker/.

Source file: XMLPermutationProvider.java

  31 
vote

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 108

From project moho, under directory /moho-common/src/main/java/com/voxeo/moho/common/util/.

Source file: XmlUtils.java

  31 
vote

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 109

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

  31 
vote

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 110

From project ned, under directory /NEDCatalogTool2/src/org/ned/server/nedcatalogtool2/datasource/.

Source file: LanguageInfoSerializer.java

  31 
vote

public void printXml(List<NedLanguage> list,PrintWriter writer) throws TransformerConfigurationException, SAXException {
  StreamResult streamResult=new StreamResult(writer);
  SAXTransformerFactory tf=(SAXTransformerFactory)SAXTransformerFactory.newInstance();
  TransformerHandler hd=tf.newTransformerHandler();
  Transformer serializer=hd.getTransformer();
  serializer.setOutputProperty(OutputKeys.ENCODING,"UTF-8");
  serializer.setOutputProperty(OutputKeys.STANDALONE,"yes");
  serializer.setOutputProperty(OutputKeys.INDENT,"yes");
  hd.setResult(streamResult);
  hd.startDocument();
  if (list != null && !list.isEmpty()) {
    write(hd,list);
  }
  hd.endDocument();
}
 

Example 111

From project nodebox, under directory /src/main/java/nodebox/node/.

Source file: NDBXWriter.java

  31 
vote

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 112

From project nutch, under directory /src/java/org/apache/nutch/util/.

Source file: DomUtil.java

  31 
vote

/** 
 * 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 113

From project cascading, under directory /src/xml/cascading/operation/xml/.

Source file: XPathOperation.java

  30 
vote

/** 
 * Method getTransformer returns the transformer of this XPathOperation object.
 * @return the transformer (type Transformer) of this XPathOperation object.
 * @throws TransformerConfigurationException when
 */
public Transformer getTransformer() throws TransformerConfigurationException {
  if (transformer != null)   return transformer;
  transformer=TransformerFactory.newInstance().newTransformer();
  transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION,"yes");
  return transformer;
}
 

Example 114

From project BMach, under directory /src/jsyntaxpane/actions/.

Source file: XmlPrettifyAction.java

  29 
vote

public static Transformer getTransformer(){
  if (transformer == null) {
    TransformerFactory tfactory=TransformerFactory.newInstance();
    try {
      transformer=tfactory.newTransformer();
    }
 catch (    TransformerConfigurationException ex) {
      throw new IllegalArgumentException("Unable to create transformer. ",ex);
    }
  }
  return transformer;
}
 

Example 115

From project Maimonides, under directory /src/com/codeko/apps/maimonides/seneca/.

Source file: GeneradorFicherosSeneca.java

  29 
vote

public Transformer getTransformer(){
  if (trans == null) {
    TransformerFactory transfac=TransformerFactory.newInstance();
    try {
      trans=transfac.newTransformer();
      trans.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION,"yes");
      trans.setOutputProperty(OutputKeys.INDENT,"yes");
    }
 catch (    TransformerConfigurationException ex) {
      Logger.getLogger(GeneradorFicherosSeneca.class.getName()).log(Level.SEVERE,null,ex);
    }
  }
  return trans;
}