Exemple #1
0
  public void saveToXml(String fileName)
      throws ParserConfigurationException, FileNotFoundException, TransformerException,
          TransformerConfigurationException {
    System.out.println("Saving network topology to file " + fileName);
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    DocumentBuilder parser = factory.newDocumentBuilder();
    Document doc = parser.newDocument();

    Element root = doc.createElement("neuralNetwork");
    root.setAttribute("dateOfExport", new Date().toString());
    Element layers = doc.createElement("structure");
    layers.setAttribute("numberOfLayers", Integer.toString(this.numberOfLayers()));

    for (int il = 0; il < this.numberOfLayers(); il++) {
      Element layer = doc.createElement("layer");
      layer.setAttribute("index", Integer.toString(il));
      layer.setAttribute("numberOfNeurons", Integer.toString(this.getLayer(il).numberOfNeurons()));

      for (int in = 0; in < this.getLayer(il).numberOfNeurons(); in++) {
        Element neuron = doc.createElement("neuron");
        neuron.setAttribute("index", Integer.toString(in));
        neuron.setAttribute(
            "NumberOfInputs", Integer.toString(this.getLayer(il).getNeuron(in).numberOfInputs()));
        neuron.setAttribute(
            "threshold", Double.toString(this.getLayer(il).getNeuron(in).threshold));

        for (int ii = 0; ii < this.getLayer(il).getNeuron(in).numberOfInputs(); ii++) {
          Element input = doc.createElement("input");
          input.setAttribute("index", Integer.toString(ii));
          input.setAttribute(
              "weight", Double.toString(this.getLayer(il).getNeuron(in).getInput(ii).weight));

          neuron.appendChild(input);
        }

        layer.appendChild(neuron);
      }

      layers.appendChild(layer);
    }

    root.appendChild(layers);
    doc.appendChild(root);

    // save
    File xmlOutputFile = new File(fileName);
    FileOutputStream fos;
    Transformer transformer;

    fos = new FileOutputStream(xmlOutputFile);
    // Use a Transformer for output
    TransformerFactory transformerFactory = TransformerFactory.newInstance();
    transformer = transformerFactory.newTransformer();
    DOMSource source = new DOMSource(doc);
    StreamResult result = new StreamResult(fos);
    // transform source into result will do save
    transformer.setOutputProperty("encoding", "iso-8859-2");
    transformer.setOutputProperty("indent", "yes");
    transformer.transform(source, result);
  }
  private String importXMI(File sourceFile)
      throws FileNotFoundException, TransformerConfigurationException, TransformerException {

    BufferedReader styledata;
    StreamSource sourcedata;
    Templates stylesheet;
    Transformer trans;

    // Get the stylesheet file stream

    styledata =
        new BufferedReader(
            new FileReader(
                new File(
                    getClass().getClassLoader().getResource("verifier/xmi2lem.xsl").getFile())));
    sourcedata = new StreamSource(new FileReader(sourceFile));

    // Initialize Saxon
    TransformerFactory factory = TransformerFactoryImpl.newInstance();
    stylesheet = factory.newTemplates(new StreamSource(styledata));

    // Apply the transformation
    trans = stylesheet.newTransformer();
    StringWriter sw = new StringWriter();
    trans.transform(sourcedata, new StreamResult(sw));

    // return sw.toString();
    return sw.getBuffer().substring(sw.getBuffer().indexOf("model"));
  }
  /**
   * Transforms the given XML string using the XSL string.
   *
   * @param xmlString The String containg the XML to transform
   * @param xslString The XML Stylesheet String containing the transform instructions
   * @return String representation of the transformation
   */
  public static String transform(String xmlString, String xslString) {

    String shortString = new String(xmlString);
    if (shortString.length() > 100) shortString = shortString.substring(0, 100) + "...";

    try {

      TransformerFactory tFactory = TransformerFactory.newInstance();

      logger.logComment("Transforming string: " + shortString);

      StreamSource xslFileSource = new StreamSource(new StringReader(xslString));

      Transformer transformer = tFactory.newTransformer(xslFileSource);

      StringWriter writer = new StringWriter();

      transformer.transform(
          new StreamSource(new StringReader(xmlString)), new StreamResult(writer));

      String shortResult = writer.toString();
      if (shortResult.length() > 100) shortResult = shortResult.substring(0, 100) + "...";

      logger.logComment("Result: " + shortResult);

      return writer.toString();
    } catch (TransformerException e) {
      GuiUtils.showErrorMessage(logger, "Error when transforming the XML: " + shortString, e, null);
      return null;
    }
  }
  /**
   * Transforms the given XML file using the specified XSL file.
   *
   * @param origXmlFile The file containg the XML to transform
   * @param xslString The XML Stylesheet conntaining the transform instructions
   * @return String representation of the transformation
   */
  public static String transform(File origXmlFile, String xslString) {
    if (!origXmlFile.exists()) {
      GuiUtils.showErrorMessage(
          logger, "Warning, XML file: " + origXmlFile + " doesn't exist", null, null);
      return null;
    }

    try {

      TransformerFactory tFactory = TransformerFactory.newInstance();

      StreamSource xslFileSource = new StreamSource(new StringReader(xslString));

      Transformer transformer = tFactory.newTransformer(xslFileSource);

      StringWriter writer = new StringWriter();

      transformer.transform(new StreamSource(origXmlFile), new StreamResult(writer));

      return writer.toString();
    } catch (Exception e) {
      GuiUtils.showErrorMessage(logger, "Error when loading the XML file: " + origXmlFile, e, null);
      return null;
    }
  }
  private static Transformer getTransformer() throws TransformerException {
    if (_transformer == null) {
      TransformerFactory factory = TransformerFactory.newInstance();
      _transformer = factory.newTransformer();
    }

    return _transformer;
  }
Exemple #6
0
  protected void doGet(HttpServletRequest req, HttpServletResponse res)
      throws ServletException, IOException {
    try {
      DateFormat df = DateFormat.getDateTimeInstance();
      String titleStr = "C3P0 Status - " + df.format(new Date());

      DocumentBuilderFactory fact = DocumentBuilderFactory.newInstance();
      DocumentBuilder db = fact.newDocumentBuilder();
      Document doc = db.newDocument();

      Element htmlElem = doc.createElement("html");
      Element headElem = doc.createElement("head");

      Element titleElem = doc.createElement("title");
      titleElem.appendChild(doc.createTextNode(titleStr));

      Element bodyElem = doc.createElement("body");

      Element h1Elem = doc.createElement("h1");
      h1Elem.appendChild(doc.createTextNode(titleStr));

      Element h3Elem = doc.createElement("h3");
      h3Elem.appendChild(doc.createTextNode("PooledDataSources"));

      Element pdsDlElem = doc.createElement("dl");
      pdsDlElem.setAttribute("class", "PooledDataSources");
      for (Iterator ii = C3P0Registry.getPooledDataSources().iterator(); ii.hasNext(); ) {
        PooledDataSource pds = (PooledDataSource) ii.next();
        StatusReporter sr = findStatusReporter(pds, doc);
        pdsDlElem.appendChild(sr.reportDtElem());
        pdsDlElem.appendChild(sr.reportDdElem());
      }

      headElem.appendChild(titleElem);
      htmlElem.appendChild(headElem);

      bodyElem.appendChild(h1Elem);
      bodyElem.appendChild(h3Elem);
      bodyElem.appendChild(pdsDlElem);
      htmlElem.appendChild(bodyElem);

      res.setContentType("application/xhtml+xml");

      TransformerFactory tf = TransformerFactory.newInstance();
      Transformer transformer = tf.newTransformer();
      Source src = new DOMSource(doc);
      Result result = new StreamResult(res.getOutputStream());
      transformer.transform(src, result);
    } catch (IOException e) {
      throw e;
    } catch (Exception e) {
      throw new ServletException(e);
    }
  }
  void outputDocument(Writer out) throws Exception {
    // Set up the output transformer
    TransformerFactory transfac = TransformerFactory.newInstance();
    Transformer trans = transfac.newTransformer();
    //		trans.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
    trans.setOutputProperty(OutputKeys.INDENT, "yes");
    trans.setOutputProperty(OutputKeys.METHOD, "html");

    // Print the DOM node
    StreamResult result = new StreamResult(out);
    DOMSource source = new DOMSource(this.document);
    trans.transform(source, result);
  }
Exemple #8
0
  public void write(SecureItemTable tbl, char[] password) throws IOException {
    OutputStream os = new FileOutputStream(file);
    OutputStream xmlout;

    if (password.length == 0) {
      xmlout = os;
      os = null;
    } else {
      PBEKeySpec keyspec = new PBEKeySpec(password);
      Cipher c;
      try {
        SecretKeyFactory fac = SecretKeyFactory.getInstance("PBEWithMD5AndDES");
        SecretKey key = fac.generateSecret(keyspec);

        c = Cipher.getInstance("PBEWithMD5AndDES");
        c.init(Cipher.ENCRYPT_MODE, key, pbeSpec);
      } catch (java.security.GeneralSecurityException exc) {
        os.close();
        IOException ioe = new IOException("Security exception during write");
        ioe.initCause(exc);
        throw ioe;
      }

      CipherOutputStream out = new CipherOutputStream(os, c);
      xmlout = out;
    }

    try {
      TransformerFactory tf = TransformerFactory.newInstance();
      Transformer t = tf.newTransformer();

      DOMSource src = new DOMSource(tbl.getDocument());
      StringWriter writer = new StringWriter();
      StreamResult sr = new StreamResult(writer);
      t.transform(src, sr);

      OutputStreamWriter osw = new OutputStreamWriter(xmlout, StandardCharsets.UTF_8);
      osw.write(writer.toString());
      osw.close();
    } catch (Exception exc) {
      IOException ioe = new IOException("Unable to serialize XML");
      ioe.initCause(exc);
      throw ioe;
    } finally {
      xmlout.close();
      if (os != null) os.close();
    }

    tbl.setDirty(false);
    return;
  }
 public SchematronTransformer() throws TransformerConfigurationException {
   step1 =
       transformerFactory.newTransformer(
           new StreamSource(
               getClass().getResourceAsStream("/iso-schematron-xslt2/iso_dsdl_include.xsl")));
   step2 =
       transformerFactory.newTransformer(
           new StreamSource(
               getClass().getResourceAsStream("/iso-schematron-xslt2/iso_abstract_expand.xsl")));
   step3 =
       transformerFactory.newTransformer(
           new StreamSource(
               getClass().getResourceAsStream("/iso-schematron-xslt2/iso_svrl_for_xslt2.xsl")));
 }
  /**
   * http://www.atmarkit.co.jp/fxml/rensai2/xmltool04/02.html
   *
   * @return
   */
  private static Transformer getTransformer() {
    if (s_transformer == null) {
      TransformerFactory transFactory = TransformerFactory.newInstance();
      try {
        s_transformer = transFactory.newTransformer();
      } catch (TransformerConfigurationException e) {
      }

      s_transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
      s_transformer.setOutputProperty(OutputKeys.INDENT, "yes");
    } // if

    return s_transformer;
  }
  /**
   * Method adds a new Spring bean definition to the XML application context file.
   *
   * @param project
   * @param jaxbElement
   */
  public void addBeanDefinition(File configFile, Project project, Object jaxbElement) {
    Source xsltSource;
    Source xmlSource;
    try {
      xsltSource =
          new StreamSource(new ClassPathResource("transform/add-bean.xsl").getInputStream());
      xsltSource.setSystemId("add-bean");
      xmlSource = new StringSource(FileUtils.readToString(new FileInputStream(configFile)));

      // create transformer
      Transformer transformer = transformerFactory.newTransformer(xsltSource);
      transformer.setParameter(
          "bean_content",
          getXmlContent(jaxbElement)
              .replaceAll("(?m)^(.)", getTabs(1, project.getSettings().getTabSize()) + "$1"));

      // transform
      StringResult result = new StringResult();
      transformer.transform(xmlSource, result);
      FileUtils.writeToFile(
          format(result.toString(), project.getSettings().getTabSize()), configFile);
      return;
    } catch (IOException e) {
      throw new ApplicationRuntimeException(UNABLE_TO_READ_TRANSFORMATION_SOURCE, e);
    } catch (TransformerException e) {
      throw new ApplicationRuntimeException(FAILED_TO_UPDATE_BEAN_DEFINITION, e);
    }
  }
Exemple #12
0
  public static String format(String xmlStr) { // Instantiate transformer input
    Source xmlInput = new StreamSource(new StringReader(xmlStr));
    StreamResult xmlOutput = new StreamResult(new StringWriter());

    // Configure transformer
    Transformer transformer;
    try {
      transformer = TransformerFactory.newInstance().newTransformer();
    } catch (TransformerConfigurationException e) {
      logger.error(e.getMessage(), e);
      return xmlStr;
    } catch (TransformerFactoryConfigurationError e) {
      // TODO Auto-generated catch block
      logger.error(e.getMessage(), e);
      return xmlStr;
    } // An identity transformer

    try {
      transformer.setOutputProperty(OutputKeys.INDENT, "yes");
      transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");

      transformer.transform(xmlInput, xmlOutput);
    } catch (TransformerException e) {
      logger.error(e.getMessage(), e);
      return xmlStr;
    }

    return xmlOutput.getWriter().toString();
  }
Exemple #13
0
 public void toSave() {
   try {
     TransformerFactory tf = TransformerFactory.newInstance();
     Transformer transformer = tf.newTransformer();
     DOMSource source = new DOMSource(document);
     transformer.setOutputProperty(OutputKeys.ENCODING, "GB2312");
     transformer.setOutputProperty(OutputKeys.INDENT, "yes");
     PrintWriter pw = new PrintWriter(new FileOutputStream(filename));
     StreamResult result = new StreamResult(pw);
     transformer.transform(source, result);
   } catch (TransformerException mye) {
     mye.printStackTrace();
   } catch (IOException exp) {
     exp.printStackTrace();
   }
 }
 private void soapMessage(String path, String wsName, String wsPortName) {
   try {
     URL wsdlURL = new URL(APP_SERVER + path);
     final String NS = AbstractServiceImpl.WS_TARGET_NAMESPACE;
     Service service = Service.create(wsdlURL, new QName(NS, wsName));
     Dispatch<Source> dispatcher =
         service.createDispatch(new QName(NS, wsPortName), Source.class, Service.Mode.PAYLOAD);
     Source request = new StreamSource(new StringReader("<hello/>"));
     Source response = dispatcher.invoke(request);
     assertNotNull(response);
     Transformer transformer = TransformerFactory.newInstance().newTransformer();
     final StringWriter writer = new StringWriter();
     Result output = new StreamResult(writer);
     transformer.transform(response, output);
     Message message = new Message("clientMessages");
     message.dumpFormattedMessage(
         EchoServiceClient.class, Message.LevelEnum.INFO, "receivedAnswer", writer.toString());
   } catch (MalformedURLException e) {
     e.printStackTrace();
     fail(String.valueOf(e));
   } catch (TransformerConfigurationException e) {
     e.printStackTrace();
   } catch (TransformerException e) {
     e.printStackTrace();
   }
 }
  /**
   * Marshal jaxb element and try to perform basic formatting like namespace clean up and attribute
   * formatting with xsl transformation.
   *
   * @param jaxbElement
   * @return
   */
  private String getXmlContent(Object jaxbElement) {
    StringResult jaxbContent = new StringResult();

    springBeanMarshaller.marshal(jaxbElement, jaxbContent);

    Source xsltSource;
    try {
      xsltSource =
          new StreamSource(new ClassPathResource("transform/format-bean.xsl").getInputStream());
      Transformer transformer = transformerFactory.newTransformer(xsltSource);

      // transform
      StringResult result = new StringResult();
      transformer.transform(new StringSource(jaxbContent.toString()), result);

      if (log.isDebugEnabled()) {
        log.debug("Created bean definition:\n" + result.toString());
      }

      return result.toString();
    } catch (IOException e) {
      throw new ApplicationRuntimeException(UNABLE_TO_READ_TRANSFORMATION_SOURCE, e);
    } catch (TransformerException e) {
      throw new ApplicationRuntimeException(FAILED_TO_UPDATE_BEAN_DEFINITION, e);
    }
  }
 private InputStream getInputStream(Source source) throws Exception {
   Transformer trans = TransformerFactory.newInstance().newTransformer();
   ByteArrayBuffer bab = new ByteArrayBuffer();
   StreamResult result = new StreamResult(bab);
   trans.transform(source, result);
   return bab.newInputStream();
 }
 /**
  * Parses an XML file on disk into a Writer
  *
  * @param fromPath the file to use as the source
  * @param toWriter the destination Writer
  * @throws javax.xml.transform.TransformerException
  * @throws java.io.IOException
  */
 public static void transform(File fromPath, Writer toWriter)
     throws TransformerException, IOException {
   Reader reader = bomCheck(fromPath);
   TransformerFactory.newInstance()
       .newTransformer()
       .transform(new StreamSource(reader), new StreamResult(toWriter));
 }
  /**
   * Method removes a Spring bean definition from the XML application context file. Bean definition
   * is identified by its id or bean name.
   *
   * @param project
   * @param id
   */
  public void removeBeanDefinition(File configFile, Project project, String id) {
    Source xsltSource;
    Source xmlSource;
    try {
      xsltSource =
          new StreamSource(new ClassPathResource("transform/delete-bean.xsl").getInputStream());
      xsltSource.setSystemId("delete-bean");

      List<File> configFiles = new ArrayList<>();
      configFiles.add(configFile);
      configFiles.addAll(getConfigImports(configFile, project));

      for (File file : configFiles) {
        xmlSource = new StringSource(FileUtils.readToString(new FileInputStream(configFile)));

        // create transformer
        Transformer transformer = transformerFactory.newTransformer(xsltSource);
        transformer.setParameter("bean_id", id);

        // transform
        StringResult result = new StringResult();
        transformer.transform(xmlSource, result);
        FileUtils.writeToFile(format(result.toString(), project.getSettings().getTabSize()), file);
        return;
      }
    } catch (IOException e) {
      throw new ApplicationRuntimeException(UNABLE_TO_READ_TRANSFORMATION_SOURCE, e);
    } catch (TransformerException e) {
      throw new ApplicationRuntimeException(FAILED_TO_UPDATE_BEAN_DEFINITION, e);
    }
  }
Exemple #19
0
  /**
   * Writes a table to a XML-file
   *
   * @param t - Output Model
   * @param destination - File Destination
   */
  public static void writeXML(Model t, String destination) {

    try {
      // Create the XML document builder, and document that will be used
      DocumentBuilderFactory xmlBuilder = DocumentBuilderFactory.newInstance();
      DocumentBuilder Builder = xmlBuilder.newDocumentBuilder();
      Document xmldoc = Builder.newDocument();

      // create Document node, and get it into the file
      Element Documentnode = xmldoc.createElement("SPREADSHEET");
      xmldoc.appendChild(Documentnode);

      // create element nodes, and their attributes (Cells, and row/column
      // data) and their content
      for (int row = 1; row < t.getRows(); row++) {
        for (int col = 1; col < t.getCols(col); col++) {
          Element cell = xmldoc.createElement("CELL");
          // set attributes
          cell.setAttribute("column", Integer.toString(col));
          cell.setAttribute("row", Integer.toString(col));
          // set content
          cell.appendChild(xmldoc.createTextNode((String) t.getContent(row, col)));
          // append node to document node
          Documentnode.appendChild(cell);
        }
      }
      // Creating a datastream for the DOM tree
      TransformerFactory transformerFactory = TransformerFactory.newInstance();
      Transformer transformer = transformerFactory.newTransformer();
      // Indentation to make the XML file look better
      transformer.setOutputProperty(OutputKeys.METHOD, "xml");
      transformer.setOutputProperty(OutputKeys.INDENT, "yes");
      // remove the java version
      transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
      DOMSource stream = new DOMSource(xmldoc);
      StreamResult target = new StreamResult(new File(destination));
      // write the file
      transformer.transform(stream, target);

    } catch (ParserConfigurationException e) {
      System.out.println("Can't create the XML document builder");
    } catch (TransformerConfigurationException e) {
      System.out.println("Can't create transformer");
    } catch (TransformerException e) {
      System.out.println("Can't write to file");
    }
  }
Exemple #20
0
  private void message(String text, HttpServletResponse response, PublishAsType publishAs) {
    ServletOutputStream out;
    String xmlText;
    Server.logger.errorLogEntry(text);
    try {

      xmlText =
          "<?xml version = \"1.0\" encoding=\"utf-8\"?><request><error type=\""
              + type
              + "\">"
              + "<message><version>"
              + Server.serverVersion
              + "</version><errortext>"
              + XMLUtil.getAsTagValue(text)
              + "</errortext></message></error></request>";
      //		System.out.println("xml text = "+xmlText);
      response.setHeader(
          "Cache-Control", "no-cache, must-revalidate, private, no-store, s-maxage=0, max-age=0");
      response.setHeader("Pragma", "no-cache");
      response.setDateHeader("Expires", 0);

      if (publishAs == PublishAsType.HTML) {
        response.setContentType("text/html;charset=utf-8");
        out = response.getOutputStream();
        Source xmlSource = new StreamSource(new StringReader(xmlText));
        Result result = new StreamResult(out);
        TransformerFactory transFact = TransformerFactory.newInstance();
        Transformer trans = transFact.newTransformer(xsltSource);
        // System.out.println(PortalEnv.appID+": xsl transformation="+PortalEnv.errorXSL);
        trans.transform(xmlSource, result);
      } else {
        response.setContentType("text/xml;charset=utf-8");
        // response.sendError(550);
        out = response.getOutputStream();
        out.println(xmlText);
      }
    } catch (IOException ioe) {
      System.out.println(ioe);
      ioe.printStackTrace();
    } catch (TransformerConfigurationException tce) {
      System.out.println(tce);
      tce.printStackTrace();
    } catch (TransformerException te) {
      System.out.println(te);
      te.printStackTrace();
    }
  }
Exemple #21
0
 public static String documentToString(Document document) {
   TransformerFactory tf = TransformerFactory.newInstance();
   Transformer transformer = null;
   try {
     transformer = tf.newTransformer();
   } catch (TransformerConfigurationException e) {
     throw new RuntimeException(e);
   }
   transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
   StringWriter writer = new StringWriter();
   try {
     transformer.transform(new DOMSource(document), new StreamResult(writer));
   } catch (TransformerException e) {
     throw new RuntimeException(e);
   }
   String output = writer.getBuffer().toString().replaceAll("\n|\r", "");
   return output;
 }
 private DOMSource toDOMSource(Source source) throws Exception {
   if (source instanceof DOMSource) {
     return (DOMSource) source;
   }
   Transformer trans = TransformerFactory.newInstance().newTransformer();
   DOMResult result = new DOMResult();
   trans.transform(source, result);
   return new DOMSource(result.getNode());
 }
  /**
   * Transforms a DOM Document into a file on disk
   *
   * @param fromDocument the Document to use as the source
   * @param toPath the destination file path represented as a String
   * @throws java.io.IOException
   * @throws javax.xml.transform.TransformerException
   */
  public static void transform(Document fromDocument, File toPath)
      throws TransformerException, IOException {
    Transformer transformer = TransformerFactory.newInstance().newTransformer();
    transformer.setOutputProperty(OutputKeys.INDENT, "yes");

    DOMSource source = new DOMSource(fromDocument);
    StreamResult result = new StreamResult(new BufferedWriter(new FileWriter(toPath)));
    transformer.transform(source, result);
  }
  public static String transform(File fromPath) throws TransformerException, IOException {
    Transformer transformer = TransformerFactory.newInstance().newTransformer();
    transformer.setOutputProperty(OutputKeys.INDENT, "yes");

    Reader reader = bomCheck(fromPath);

    StringWriter sw = new StringWriter();
    transformer.transform(new StreamSource(reader), new StreamResult(sw));
    return sw.toString();
  }
 /**
  * Writes an XML file from a Document object.
  *
  * @param doc the Document object to be written to file
  * @param file the file to be written
  * @throws IOException
  * @author Klaus Meffert
  * @since 2.0
  */
 public static void writeFile(Document doc, File file) throws IOException {
   // Use a Transformer for output
   TransformerFactory tFactory = TransformerFactory.newInstance();
   Transformer transformer;
   try {
     transformer = tFactory.newTransformer();
   } catch (TransformerConfigurationException tex) {
     throw new IOException(tex.getMessage());
   }
   DOMSource source = new DOMSource(doc);
   FileOutputStream fos = new FileOutputStream(file);
   StreamResult result = new StreamResult(fos);
   try {
     transformer.transform(source, result);
     fos.close();
   } catch (TransformerException tex) {
     throw new IOException(tex.getMessage());
   }
 }
  /**
   * Transforms a DOM Document into a String
   *
   * @param fromDocument the Document to use as the source
   * @return the XML as a String
   * @throws java.io.IOException
   * @throws javax.xml.transform.TransformerException
   */
  public static String transform(Document fromDocument) throws TransformerException, IOException {
    Transformer transformer = TransformerFactory.newInstance().newTransformer();
    transformer.setOutputProperty(OutputKeys.INDENT, "yes");

    StringWriter sw = new StringWriter();
    StreamResult result = new StreamResult(sw);
    DOMSource source = new DOMSource(fromDocument);
    transformer.transform(source, result);
    return sw.toString();
  }
  /**
   * Transforms a DOM Document into a String
   *
   * @param fromDocument the Document to use as the source
   * @param omitXmlDeclaration will not write the XML header if true
   * @return the XML as a String
   * @throws java.io.IOException
   * @throws javax.xml.transform.TransformerException
   */
  public static String transform(Document fromDocument, boolean omitXmlDeclaration)
      throws TransformerException, IOException {
    Transformer transformer = TransformerFactory.newInstance().newTransformer();
    transformer.setOutputProperty(OutputKeys.INDENT, "yes");
    if (omitXmlDeclaration) transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");

    StringWriter sw = new StringWriter();
    transformer.transform(new DOMSource(fromDocument), new StreamResult(sw));
    return sw.toString();
  }
 /**
  * Transforms a streamed XML representation into a DOM Document
  *
  * @param reader the XML fragment as an input stream to use as the source
  * @param toDocument the destination Document
  * @throws javax.xml.transform.TransformerException
  */
 public static void transform(UnicodeReader reader, Document toDocument)
     throws TransformerException {
   try {
     TransformerFactory.newInstance()
         .newTransformer()
         .transform(new StreamSource(reader), new DOMResult(toDocument));
   } catch (Exception e) {
     throw new TransformerException("Cannot remove byte-order-mark from XML file");
   }
 }
Exemple #29
0
  /**
   * Save the XML description of the circuit
   *
   * @param output an output stream to write in
   * @return true if the dump was successful, false either
   */
  public boolean dumpToXml(OutputStream output) {
    Document doc;
    Element root;

    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    DocumentBuilder builder;

    try {
      builder = factory.newDocumentBuilder();
      doc = builder.newDocument();
    } catch (ParserConfigurationException pce) {
      System.err.println("dumpToXmlFile: unable to write XML save file.");
      return false;
    }

    root = doc.createElement("Circuit");
    root.setAttribute("name", this.getName());

    for (iterNodes = this.nodes.iterator(); iterNodes.hasNext(); )
      iterNodes.next().dumpToXml(doc, root);

    root.normalize();
    doc.appendChild(root);

    try {
      TransformerFactory tffactory = TransformerFactory.newInstance();
      Transformer transformer = tffactory.newTransformer();
      transformer.setOutputProperty(OutputKeys.INDENT, "yes");
      DOMSource source = new DOMSource(doc);
      StreamResult result = new StreamResult(output);
      transformer.transform(source, result);
    } catch (TransformerConfigurationException tce) {
      System.err.println("dumpToXmlFile:  Configuration Transformer exception.");
      return false;
    } catch (TransformerException te) {
      System.err.println("dumpToXmlFile: Transformer exception.");
      return false;
    }

    return true;
  }
 /**
  * Transforms a streamed XML representation into a DOM Document
  *
  * @param in the XML fragment as an input stream to use as the source
  * @param toDocument the destination Document
  * @throws javax.xml.transform.TransformerException
  */
 public static void transform(InputStream in, Document toDocument) throws TransformerException {
   // Reader reader = new BufferedReader(new InputStreamReader(in));
   try {
     // removeBOM(reader);
     Reader reader = bomCheck(in);
     TransformerFactory.newInstance()
         .newTransformer()
         .transform(new StreamSource(reader), new DOMResult(toDocument));
   } catch (Exception e) {
     throw new TransformerException("Cannot remove byte-order-mark from XML file");
   }
 }