Java Code Examples for javax.xml.transform.stream.StreamResult

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 jbpmmigration, under directory /src/main/java/org/jbpm/migration/.

Source file: XmlUtils.java

  34 
vote

/** 
 * Write an XML document (formatted) to a given <code>File</code>.
 * @param input The input XML document.
 * @param output The intended <code>File</code>.
 */
public static void writeFile(final Document input,final File output){
  final StreamResult result=new StreamResult(new StringWriter());
  format(new DOMSource(input),result);
  try {
    new FileWriter(output).write(result.getWriter().toString());
  }
 catch (  final IOException ioEx) {
    LOGGER.error("Problem writing XML to file.",ioEx);
  }
}
 

Example 2

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

Source file: XMLHelpers.java

  33 
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 3

From project Activiti-KickStart, under directory /activiti-kickstart-java/src/main/java/org/activiti/kickstart/service/alfresco/.

Source file: AlfrescoKickstartServiceImpl.java

  32 
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 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 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 6

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

Source file: SOAPUtil.java

  32 
vote

public static String getString(SOAPMessage msg){
  StringWriter w=new StringWriter();
  StreamResult result=new StreamResult(w);
  print(msg,result);
  w.flush();
  return w.toString();
}
 

Example 7

From project cdk, under directory /generator/src/main/java/org/richfaces/cdk/xmlconfig/.

Source file: JAXBBinding.java

  32 
vote

@Override public <T>void marshal(Writer output,String schemaLocation,T model) throws CdkException {
  try {
    StreamResult result=new StreamResult(output);
    marshal(result,schemaLocation,model);
    output.flush();
    output.close();
  }
 catch (  FileNotFoundException e) {
    throw new CdkException("File not found",e);
  }
catch (  IOException e) {
    throw new CdkException("XML file writting error",e);
  }
}
 

Example 8

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 9

From project coala, under directory /modules/coala-communication/src/main/java/org/openehealth/coala/transformer/.

Source file: XmlTransformer.java

  32 
vote

/** 
 * Transform the XML and XSL into HTML and return the result it as string.
 * @param xmlString the valid XML string.
 * @return htmlString the HTML code.
 * @throws CdaXmlTransformerException if their is a error on transforming XML and XSL into HTML.
 */
private String transformXmlAndXslIntoHtml(String xmlString) throws CdaXmlTransformerException {
  String htmlString=null;
  try {
    StringWriter stringWriter=new StringWriter();
    StreamSource xmlStreamSource=new StreamSource(new StringReader(xmlString));
    StreamResult htmlStreamResult=new StreamResult(stringWriter);
    transformer.transform(xmlStreamSource,htmlStreamResult);
    htmlString=stringWriter.toString();
  }
 catch (  Exception e) {
    throw new CdaXmlTransformerException("Couldn't transform a CDA XML string into valid HTML via XSLT.",e);
  }
  return htmlString;
}
 

Example 10

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 11

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 12

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 13

From project echo3, under directory /src/server-java-examples/chatserver/src/java/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 14

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 15

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 16

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 17

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 18

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 19

From project lenya, under directory /org.apache.lenya.core.impl/src/main/java/org/apache/lenya/xml/.

Source file: DocumentHelper.java

  32 
vote

/** 
 * Writes a document to a file. A new file is created if it does not exist.
 * @param document The document to save.
 * @param file The file to save the document to.
 * @throws IOException if an error occurs
 * @throws TransformerConfigurationException if an error occurs
 * @throws TransformerException if an error occurs
 */
public static void writeDocument(Document document,File file) throws TransformerConfigurationException, TransformerException, IOException {
  if (document == null)   throw new IllegalArgumentException("illegal usage, parameter document may not be null");
  if (file == null)   throw new IllegalArgumentException("illegal usage, parameter file may not be null");
  file.getParentFile().mkdirs();
  file.createNewFile();
  DOMSource source=new DOMSource(document);
  StreamResult result=new StreamResult(file);
  getTransformer(document.getDoctype()).transform(source,result);
}
 

Example 20

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

Source file: ConnectionCreate.java

  31 
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 21

From project Aion-Extreme, under directory /AE-go_GameServer/src/com/aionemu/gameserver/utils/xml/.

Source file: SchemaGen.java

  31 
vote

public static void main(String[] args) throws Exception {
  final File baseDir=new File("./data/static_data");
class MySchemaOutputResolver extends SchemaOutputResolver {
    public Result createOutput(    String namespaceUri,    String suggestedFileName) throws IOException {
      return new StreamResult(new File(baseDir,"static_data1.xsd"));
    }
  }
  JAXBContext context=JAXBContext.newInstance(StaticData.class);
  context.generateSchema(new MySchemaOutputResolver());
}
 

Example 22

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 23

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

Source file: XsltTask.java

  31 
vote

private void transform(File infile,File outfile) throws IOException {
  InputStream fis=null;
  OutputStream fos=null;
  try {
    final Transformer transformer=createTransformer();
    fis=new BufferedInputStream(new FileInputStream(infile));
    fos=new BufferedOutputStream(createOutputStream(outfile));
    StreamResult res=new StreamResult(fos);
    Source src=new StreamSource(fis);
    setTransformationParameters(transformer);
    if (env.isVerbose()) {
      logVerbose("Processing :'%s'\n",infile);
      logVerbose("        to :'%s'\n",outfile);
      logVerbose("using xslt :'%s'\n",styleFile);
    }
 else {
      env.logInfo("Processing 1 file.\n");
    }
    transformer.transform(src,res);
    fis.close();
    fos.flush();
    fos.close();
  }
 catch (  TransformerException e) {
    throw new BuildException(e);
  }
 finally {
    StreamUtils.close(fis);
    StreamUtils.close(fos);
  }
}
 

Example 24

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 25

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 26

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

Source file: BPELUnitUtil.java

  31 
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 27

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

Source file: XPathOperation.java

  31 
vote

protected String writeAsXML(Node node){
  StringWriter stringWriter=new StringWriter();
  Result result=new StreamResult(stringWriter);
  Source source=new DOMSource(node);
  try {
    getTransformer().transform(source,result);
  }
 catch (  TransformerException exception) {
    throw new OperationException("writing to xml failed",exception);
  }
  return stringWriter.toString();
}
 

Example 28

From project chromattic, under directory /metamodel/src/main/java/org/chromattic/metamodel/typegen/.

Source file: XMLNodeTypeSerializer.java

  31 
vote

@Override public void writeTo(Writer writer) throws Exception {
  SAXTransformerFactory factory=(SAXTransformerFactory)SAXTransformerFactory.newInstance();
  TransformerHandler handler=factory.newTransformerHandler();
  handler.getTransformer().setOutputProperty(OutputKeys.METHOD,"xml");
  handler.getTransformer().setOutputProperty(OutputKeys.ENCODING,"UTF-8");
  handler.getTransformer().setOutputProperty(OutputKeys.INDENT,"yes");
  handler.getTransformer().setOutputProperty("{http://xml.apache.org/xslt}indent-amount","2");
  handler.setResult(new StreamResult(writer));
  docXML=new DocumentEmitter(handler,handler);
  docXML.comment("Node type generation prototype");
  writeTo();
}
 

Example 29

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 30

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 31

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 32

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

Source file: PreferenceGuiHome.java

  31 
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 33

From project contribution_eevolution_warehouse_management, under directory /extension/eevolution/warehousemanagement/src/main/java/org/compiere/print/.

Source file: ReportEngine.java

  31 
vote

/** 
 * Write XML to writer
 * @param writer writer
 * @return true if success
 */
public boolean createXML(Writer writer){
  try {
    m_printData.createXML(new StreamResult(writer));
    writer.flush();
    writer.close();
    return true;
  }
 catch (  Exception e) {
    log.log(Level.SEVERE,"(w)",e);
  }
  return false;
}
 

Example 34

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 35

From project core_5, under directory /exo.core.component.xml-processing/src/test/java/org/exoplatform/services/xml/transform/.

Source file: TestPipe.java

  31 
vote

public void testTidyAndXsl() throws Exception {
  InputStream res=resourceStream("rss-in.xhtml");
  assertTrue("Empty input file",res.available() > 0);
  String OUTPUT_FILENAME=resourceURL("rss-out.xml").getPath();
  OutputStream outputFileOutputStream=new FileOutputStream(OUTPUT_FILENAME);
  TRAXTransformer traxTransformer=traxTemplates.newTransformer();
  htmlTransformer.initResult(traxTransformer.getTransformerAsResult());
  traxTransformer.initResult(new StreamResult(outputFileOutputStream));
  htmlTransformer.transform(new StreamSource(res));
  res.close();
  FileInputStream outputFileInputStream=new FileInputStream(OUTPUT_FILENAME);
  assertTrue("Output is empty",outputFileInputStream.available() > 0);
  outputFileInputStream.close();
}
 

Example 36

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

Source file: XSLT1.java

  31 
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 37

From project cpptasks-parallel, under directory /src/main/java/net/sf/antcontrib/cpptasks/apple/.

Source file: PropertyListSerialization.java

  31 
vote

/** 
 * Serializes a property list into a Cocoa XML Property List document.
 * @param propertyList property list.
 * @param file destination.
 * @param comments comments to insert into document.
 * @throws SAXException if exception during serialization.
 * @throws TransformerConfigurationException if exception creating serializer.
 */
public static void serialize(final Map propertyList,final List comments,final File file) throws IOException, SAXException, TransformerConfigurationException {
  SAXTransformerFactory sf=(SAXTransformerFactory)SAXTransformerFactory.newInstance();
  TransformerHandler handler=sf.newTransformerHandler();
  FileOutputStream os=new FileOutputStream(file);
  StreamResult result=new StreamResult(os);
  handler.setResult(result);
  handler.startDocument();
  for (Iterator iter=comments.iterator(); iter.hasNext(); ) {
    char[] comment=String.valueOf(iter.next()).toCharArray();
    handler.comment(comment,0,comment.length);
  }
  AttributesImpl attributes=new AttributesImpl();
  handler.startElement(null,"plist","plist",attributes);
  serializeMap(propertyList,handler);
  handler.endElement(null,"plist","plist");
  handler.endDocument();
}
 

Example 38

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 39

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

Source file: HL72Xml.java

  31 
vote

public void parse(InputStream is) throws IOException, TransformerConfigurationException, SAXException {
  byte[] buf=new byte[256];
  int len=is.read(buf);
  HL7Segment msh=HL7Segment.parseMSH(buf,buf.length);
  String charsetName=HL7Charset.toCharsetName(msh.getField(17,charset));
  Reader reader=new InputStreamReader(new SequenceInputStream(new ByteArrayInputStream(buf,0,len),is),charsetName);
  TransformerHandler th=getTransformerHandler();
  th.getTransformer().setOutputProperty(OutputKeys.INDENT,indent ? "yes" : "no");
  th.setResult(new StreamResult(System.out));
  HL7Parser hl7Parser=new HL7Parser(th);
  hl7Parser.setIncludeNamespaceDeclaration(includeNamespaceDeclaration);
  hl7Parser.parse(reader);
}
 

Example 40

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

Source file: XsltTransformer.java

  31 
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 41

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 42

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 43

From project drools-chance, under directory /drools-shapes/drools-shapes-reasoner-generator/src/main/java/org/drools/semantics/builder/model/.

Source file: SemanticXSDModelImpl.java

  31 
vote

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

Example 44

From project droolsjbpm-tools, under directory /drools-eclipse/org.guvnor.eclipse.webdav/src/kernel/org/eclipse/webdav/internal/kernel/.

Source file: DocumentMarshaler.java

  31 
vote

public void print(Document document,Writer writer,String encoding) throws IOException {
  Transformer transformer=null;
  try {
    transformer=TransformerFactory.newInstance().newTransformer();
  }
 catch (  TransformerConfigurationException e) {
    throw new IOException(e.getMessageAndLocation());
  }
catch (  TransformerFactoryConfigurationError e) {
    throw new IOException(e.getMessage());
  }
  DOMSource source=new DOMSource(document);
  StreamResult result=new StreamResult(writer);
  try {
    transformer.transform(source,result);
  }
 catch (  TransformerException e) {
    throw new IOException(e.getMessageAndLocation());
  }
}
 

Example 45

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

  31 
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 46

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

  31 
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 47

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

Source file: DescriptorReader.java

  31 
vote

public void write(File file) throws CoreException {
  DocumentBuilder documentBuilder=ContentUtil.createDocumentBuilder();
  Transformer serializer=ContentUtil.createTransformer();
  Document document=documentBuilder.newDocument();
  writeDocument(document);
  DOMSource source=new DOMSource(document);
  try {
    StreamResult target=new StreamResult(file);
    serializer.setOutputProperty(OutputKeys.INDENT,"yes");
    serializer.transform(source,target);
  }
 catch (  TransformerException e) {
    throw new CoreException(new Status(Status.ERROR,ContentPlugin.PLUGIN_ID,"Could not write initialization data for tutorial"));
  }
}
 

Example 48

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

Source file: Helper.java

  31 
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 49

From project emite, under directory /src/main/java/com/calclab/emite/base/xml/.

Source file: XMLPacketImpl.java

  31 
vote

@Override public String toString(){
  try {
    final StringWriter buffer=new StringWriter();
    transformer.transform(new DOMSource(element),new StreamResult(buffer));
    return buffer.toString();
  }
 catch (  final TransformerException e) {
    throw new InternalError("Transformer error");
  }
}
 

Example 50

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 51

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 52

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

Source file: Utils.java

  31 
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 53

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

Source file: XHTMLBuilderExample.java

  31 
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 54

From project flyingsaucer, under directory /flying-saucer-examples/src/main/java/org/xhtmlrenderer/demo/browser/.

Source file: ViewSourceAction.java

  31 
vote

public void actionPerformed(ActionEvent evt){
  TransformerFactory tfactory=TransformerFactory.newInstance();
  Transformer serializer;
  try {
    serializer=tfactory.newTransformer();
    serializer.setOutputProperty(OutputKeys.INDENT,"yes");
    serializer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount","2");
    Element document=panel.getRootBox().getElement();
    DOMSource source=new DOMSource(document);
    StreamResult output=new StreamResult(System.out);
    serializer.transform(source,output);
  }
 catch (  TransformerException ex) {
    ex.printStackTrace();
    throw new RuntimeException(ex);
  }
}
 

Example 55

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

Source file: XMLTools.java

  31 
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 56

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 57

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 58

From project GraphWalker, under directory /src/main/java/org/graphwalker/.

Source file: StatisticsManager.java

  31 
vote

public void writeFullReport(PrintStream out){
  log.info("Writing full report");
  try {
    styleTemplate.transform(new JDOMSource((Document)this.progress.clone()),new StreamResult(out));
  }
 catch (  TransformerException e) {
    throw new RuntimeException("Could not create report",e);
  }
}
 

Example 59

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 60

From project gxa, under directory /atlas-index-api/src/test/java/uk/ac/ebi/gxa/index/.

Source file: MockIndexLoader.java

  31 
vote

private static void loadSolrDump(CoreContainer container,String core,String dump) throws SolrServerException, IOException, TransformerException {
  SolrServer solr=new EmbeddedSolrServer(container,core);
  Source source=new StreamSource(MockIndexLoader.class.getClassLoader().getResourceAsStream("META-INF/" + dump));
  Source xslt=new StreamSource(MockIndexLoader.class.getClassLoader().getResourceAsStream("META-INF/dumpconverter.xslt"));
  StringWriter sw=new StringWriter();
  Result result=new StreamResult(sw);
  TransformerFactory transfactory=TransformerFactory.newInstance();
  Transformer transformer=transfactory.newTransformer(xslt);
  transformer.transform(source,result);
  DirectXmlRequest request=new DirectXmlRequest("/update",sw.toString());
  solr.request(request);
  solr.optimize();
  solr.commit();
}
 

Example 61

From project harmony, under directory /harmony.common.serviceinterface/src/main/java/org/opennaas/extensions/idb/serviceinterface/databinding/utils/.

Source file: JaxbSerializer.java

  31 
vote

/** 
 * Convert Object to XML.
 * @param obj Object to be converted to a XML-String
 * @return XML String XML-String derived out of Object
 * @throws JAXBException A JAXBException
 */
@Override @SuppressWarnings("unchecked") public String objectToXml(final Object obj) throws JAXBException {
  final ByteArrayOutputStream outputStream=new ByteArrayOutputStream();
  final StreamResult result=new StreamResult(outputStream);
  try {
    if (obj.getClass().isAnnotationPresent(XmlRootElement.class)) {
      this.marshaller.marshal(obj,result);
    }
 else {
      final Class<?> objClass=obj.getClass();
      this.marshaller.marshal(new JAXBElement(new QName(objClass.getName()),objClass,obj),result);
    }
  }
 catch (  final NullPointerException npe) {
    throw new JAXBException(npe.getMessage() + "\n\nMay be caused by an invalid XMLGregorianCalendar.\n" + "Please make shure to use the generateXMLCalendar"+ " method from Helpers to create new Calendars to"+ " avoid illegal calendar states",npe);
  }
  return (outputStream.toString());
}
 

Example 62

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

Source file: OpenIDConsumerUnitTestCase.java

  31 
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 63

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

Source file: WsdlDocument.java

  31 
vote

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

Example 64

From project iserve, under directory /iserve-parent/iserve-importer-hrests/src/main/java/uk/ac/open/kmi/iserve/importer/hrests/.

Source file: HrestsImporter.java

  31 
vote

@Override protected InputStream transformStream(String serviceDescription) throws ImporterException {
  Document document=parser.parseDOM(new ByteArrayInputStream(serviceDescription.getBytes()),null);
  DOMSource source=new DOMSource(document);
  ByteArrayOutputStream bout=new ByteArrayOutputStream();
  StreamResult result=new StreamResult(bout);
  try {
    transformer.transform(source,result);
  }
 catch (  TransformerException e) {
    throw new ImporterException(e);
  }
  if (null == result.getOutputStream())   return null;
  String resultString=result.getOutputStream().toString();
  return new ByteArrayInputStream(resultString.getBytes());
}
 

Example 65

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

Source file: ProjectConfiguration.java

  31 
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 66

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 67

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 68

From project jcr-benchmark, under directory /src/main/java/org/exoplatform/jcr/benchmark/jcrapi/xml/.

Source file: AbstractContentCreatorForExportTest.java

  31 
vote

@Override protected void createContent(Node parent,TestCase tc,JCRTestContext context) throws Exception {
  Node node=parent.addNode(context.generateUniqueName("testNode"));
  addPath(node.getPath());
  File destFile=File.createTempFile(context.generateUniqueName("testExportImport"),".xml");
  destFile.deleteOnExit();
  OutputStream outputStream=new FileOutputStream(destFile);
  SAXTransformerFactory saxFact=(SAXTransformerFactory)TransformerFactory.newInstance();
  TransformerHandler transformerHandler=saxFact.newTransformerHandler();
  transformerHandler.setResult(new StreamResult(outputStream));
  addOutputStream(outputStream);
  addTransformerHandler(transformerHandler);
}
 

Example 69

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

Source file: SpecdoxTransformer.java

  31 
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 70

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

Source file: XmlUtil.java

  31 
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 71

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

Source file: RendererImpl.java

  31 
vote

protected Result buildResult(File targetFile,FormatPlan formatPlan) throws RenderingException, XSLTException {
  if (StandardDocBookFormatMetadata.PDF.getName().equals(formatPlan.getName())) {
    return new ResultImpl(targetFile,componentRegistry);
  }
 else {
    return new StreamResult(targetFile);
  }
}
 

Example 72

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

Source file: PropertyTree.java

  31 
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 73

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 74

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

Source file: Helper.java

  31 
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 75

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

Source file: XMLFormatPostProcessor.java

  31 
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 76

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

Source file: Util.java

  31 
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 77

From project jPOS, under directory /jpos/src/main/java/org/jpos/iso/filter/.

Source file: XSLTFilter.java

  31 
vote

/** 
 * @param channel current ISOChannel instance
 * @param m ISOMsg to filter
 * @param evt LogEvent
 * @return an ISOMsg (possibly parameter m)
 * @throws VetoException
 */
public ISOMsg filter(ISOChannel channel,ISOMsg m,LogEvent evt) throws VetoException {
  try {
    m.setPackager(packager);
    ByteArrayOutputStream os=new ByteArrayOutputStream();
    if (reread || transformer == null)     transformer=tfactory.newTransformer(new StreamSource(xsltfile));
    transformer.transform(new StreamSource(new ByteArrayInputStream(m.pack())),new StreamResult(os));
    m.unpack(os.toByteArray());
  }
 catch (  Exception e) {
    throw new VetoException(e);
  }
  return m;
}
 

Example 78

From project jreepad, under directory /src/jreepad/io/.

Source file: XmlWriter.java

  31 
vote

public void write(OutputStream out,JreepadTreeModel document) throws IOException {
  StreamResult result=new StreamResult(out);
  SAXTransformerFactory factory=(SAXTransformerFactory)SAXTransformerFactory.newInstance();
  TransformerHandler handler;
  try {
    handler=factory.newTransformerHandler();
    handler.getTransformer().setOutputProperty(OutputKeys.INDENT,"yes");
  }
 catch (  TransformerConfigurationException e) {
    throw new IOException(e.toString());
  }
  handler.setResult(result);
  try {
    write(handler,document);
  }
 catch (  SAXException e) {
    throw new IOException(e.toString());
  }
}
 

Example 79

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

Source file: SAXXMLSerializer.java

  31 
vote

public void startDocument() throws SAXException {
  try {
    SAXTransformerFactory factory=(SAXTransformerFactory)SAXTransformerFactory.newInstance();
    TransformerHandler f=factory.newTransformerHandler();
    f.setResult(new StreamResult(out));
    super.setContentHandler(f);
  }
 catch (  Exception e) {
    throw new SAXException(e);
  }
  super.startDocument();
}
 

Example 80

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 81

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 82

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 83

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 84

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

Source file: WebContextRootSynchronizerTest.java

  31 
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 85

From project Lily, under directory /global/util/src/main/java/org/lilyproject/util/xml/.

Source file: XmlProducer.java

  31 
vote

public XmlProducer(OutputStream outputStream) throws SAXException, TransformerConfigurationException {
  TransformerHandler serializer=getTransformerHandler();
  serializer.getTransformer().setOutputProperty(OutputKeys.METHOD,"xml");
  serializer.getTransformer().setOutputProperty(OutputKeys.ENCODING,"UTF-8");
  serializer.setResult(new StreamResult(outputStream));
  this.result=serializer;
  result.startDocument();
  newLine();
}
 

Example 86

From project litle-sdk-for-java, under directory /lib/apache-cxf-2.5.2/samples/jaxws_dispatch_provider/src/main/java/demo/hwDispatch/server/.

Source file: GreeterDOMSourcePayloadProvider.java

  31 
vote

public DOMSource invoke(DOMSource request){
  DOMSource response=new DOMSource();
  try {
    System.out.println("Incoming Client Request as a DOMSource data in PAYLOAD Mode");
    Transformer transformer=TransformerFactory.newInstance().newTransformer();
    StreamResult result=new StreamResult(System.out);
    transformer.transform(request,result);
    System.out.println("\n");
    InputStream is=getClass().getResourceAsStream("GreetMeDocLiteralResp3.xml");
    SOAPMessage greetMeResponse=MessageFactory.newInstance().createMessage(null,is);
    is.close();
    response.setNode(greetMeResponse.getSOAPBody().extractContentAsDocument());
  }
 catch (  Exception ex) {
    ex.printStackTrace();
  }
  return response;
}
 

Example 87

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

Source file: XMLUtil.java

  30 
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 88

From project BlameSubversion-plugin, under directory /src/main/java/hudson/scm/.

Source file: BlameSubversionSCM.java

  30 
vote

/** 
 * Called after checkout/update has finished to compute the changelog.
 */
private boolean calcChangeLog(AbstractBuild<?,?> build,File changelogFile,BuildListener listener,List<External> externals) throws IOException, InterruptedException {
  if (build.getPreviousBuild() == null) {
    return createEmptyChangeLog(changelogFile,listener,"log");
  }
  OutputStream os=new BufferedOutputStream(new FileOutputStream(changelogFile));
  boolean created;
  try {
    created=new BlameSubversionChangeLogBuilder(build,listener,this).run(externals,new StreamResult(os));
  }
  finally {
    os.close();
  }
  if (!created)   createEmptyChangeLog(changelogFile,listener,"log");
  return true;
}
 

Example 89

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

Source file: XmlPrettifyAction.java

  30 
vote

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

Example 90

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

Source file: XSLTICalendarContentProcessorImpl.java

  30 
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 91

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

Source file: ChukwaMetricsList.java

  30 
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 92

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

Source file: NCBIEUtilsAccessService.java

  30 
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 93

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

Source file: RDFaParserImp.java

  30 
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 94

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

Source file: XmlTools.java

  30 
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 95

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

Source file: XMLUtils.java

  30 
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 96

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

Source file: XMLUtils.java

  30 
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 97

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

Source file: BatchTest.java

  30 
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 98

From project Ebselen, under directory /ebselen-core/src/main/java/com/lazerycode/ebselen/handlers/.

Source file: XMLHandler.java

  30 
vote

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

Example 99

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

Source file: FormatCommand.java

  30 
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 100

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

Source file: XmlSerializer.java

  30 
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 101

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

Source file: Fits.java

  30 
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 102

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

Source file: ExportToImage.java

  30 
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 103

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

Source file: DOMElementProprtyEditor.java

  30 
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 104

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

Source file: PublishingTFAction.java

  30 
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 105

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

Source file: ChukwaMetricsList.java

  30 
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 106

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

Source file: ReportInputStream.java

  30 
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 107

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

Source file: ASDocScreenScraper.java

  30 
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 108

From project jboss-jstl-api_spec, under directory /src/main/java/org/apache/taglibs/standard/tag/common/xml/.

Source file: TransformSupport.java

  30 
vote

public int doEndTag() throws JspException {
  try {
    Object xml=this.xml;
    if (xml == null)     if (bodyContent != null && bodyContent.getString() != null)     xml=bodyContent.getString().trim();
 else     xml="";
    Source source=getSource(xml,xmlSystemId);
    if (result != null)     t.transform(source,result);
 else     if (var != null) {
      Document d=db.newDocument();
      Result doc=new DOMResult(d);
      t.transform(source,doc);
      pageContext.setAttribute(var,d,scope);
    }
 else {
      Result page=new StreamResult(new SafeWriter(pageContext.getOut()));
      t.transform(source,page);
    }
    return EVAL_PAGE;
  }
 catch (  SAXException ex) {
    throw new JspException(ex);
  }
catch (  ParserConfigurationException ex) {
    throw new JspException(ex);
  }
catch (  IOException ex) {
    throw new JspException(ex);
  }
catch (  TransformerException ex) {
    throw new JspException(ex);
  }
}
 

Example 109

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

Source file: XmlBuilder.java

  30 
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 110

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

Source file: TestXmlSerializer.java

  30 
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 111

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

Source file: ParticleIO.java

  30 
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 112

From project karaf, under directory /deployer/blueprint/src/main/java/org/apache/karaf/deployer/blueprint/.

Source file: BlueprintTransformer.java

  30 
vote

public static Set<String> analyze(Source source) throws Exception {
  if (transformer == null) {
    if (tf == null) {
      tf=TransformerFactory.newInstance();
    }
    Source s=new StreamSource(BlueprintTransformer.class.getResourceAsStream("extract.xsl"));
    transformer=tf.newTransformer(s);
  }
  Set<String> refers=new TreeSet<String>();
  ByteArrayOutputStream bout=new ByteArrayOutputStream();
  Result r=new StreamResult(bout);
  transformer.transform(source,r);
  ByteArrayInputStream bin=new ByteArrayInputStream(bout.toByteArray());
  bout.close();
  BufferedReader br=new BufferedReader(new InputStreamReader(bin));
  String line=br.readLine();
  while (line != null) {
    line=line.trim();
    if (line.length() > 0) {
      String parts[]=line.split("\\s*,\\s*");
      for (int i=0; i < parts.length; i++) {
        int n=parts[i].lastIndexOf('.');
        if (n > 0) {
          String pkg=parts[i].substring(0,n);
          if (!pkg.startsWith("java.")) {
            refers.add(pkg);
          }
        }
      }
    }
    line=br.readLine();
  }
  br.close();
  return refers;
}
 

Example 113

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

Source file: ClarkAnnotation.java

  30 
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 114

From project license-maven-plugin, under directory /src/main/java/org/codehaus/mojo/license/.

Source file: LicenseSummaryWriter.java

  30 
vote

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

Example 115

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

Source file: DefaultXmlWriter.java

  30 
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 116

From project c24-spring, under directory /c24-spring-core/src/main/java/biz/c24/io/spring/oxm/.

Source file: C24Marshaller.java

  29 
vote

public void marshal(Object graph,Result result) throws IOException, XmlMappingException {
  Assert.isInstanceOf(StreamResult.class,result,UNSUPPORTED_RESULT);
  Assert.isInstanceOf(ComplexDataObject.class,graph);
  XMLSink sink=getXmlSinkFrom((StreamResult)result);
  sink.writeObject((ComplexDataObject)graph);
}
 

Example 117

From project l2jserver2, under directory /l2jserver2-tools/src/main/java/com/l2jserver/model/template/character/.

Source file: CharacterTemplateConverter.java

  29 
vote

public static void main(String[] args) throws SQLException, IOException, ClassNotFoundException, JAXBException {
  Class.forName("com.mysql.jdbc.Driver");
  final File target=new File("generated/template");
  System.out.println("Generating template classes...");
  final JAXBContext c=JAXBContext.newInstance(CharacterTemplate.class);
  c.generateSchema(new SchemaOutputResolver(){
    @Override public Result createOutput(    String namespaceUri,    String suggestedFileName) throws IOException {
      return new StreamResult(new File(target,"character.xsd"));
    }
  }
);
  final Marshaller m=c.createMarshaller();
  m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT,true);
  final Connection conn=DriverManager.getConnection(JDBC_URL,JDBC_USERNAME,JDBC_PASSWORD);
  try {
    final PreparedStatement st=conn.prepareStatement("SELECT * FROM char_templates " + "LEFT JOIN lvlupgain ON (char_templates.Classid = lvlupgain.classid)");
    try {
      st.execute();
      final ResultSet rs=st.getResultSet();
      while (rs.next()) {
        CharacterTemplate t=fillTemplate(rs);
        final File file=new File(target,"character/" + camelCase(t.getID().getCharacterClass().name()) + ".xml");
        file.getParentFile().mkdirs();
        m.marshal(t,file);
      }
    }
  finally {
      st.close();
    }
  }
  finally {
    conn.close();
  }
}