Exemplo n.º 1
2
  public static void writeXmlFile(Document doc, File saveFile, boolean systemOut) {
    try {

      Source source = new DOMSource(doc);
      Transformer xformer = TransformerFactory.newInstance().newTransformer();
      xformer.setParameter(OutputKeys.INDENT, "yes");
      xformer.setOutputProperty(OutputKeys.INDENT, "yes");
      xformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4");

      if (saveFile != null) {
        Result result = new StreamResult(saveFile);
        xformer.transform(source, result);
      }

      Writer outputWriter = new StringWriter();
      Result stringOut = new StreamResult(outputWriter);
      xformer.transform(source, stringOut);

      //            new SinglePanelPopup(new TextAreaPane(outputWriter.toString()));

      if (systemOut) {
        Result system = new StreamResult(System.out);
        xformer.transform(source, system);
      }

    } catch (TransformerConfigurationException e) {
    } catch (TransformerException e) {
    }
  }
Exemplo n.º 2
0
  /**
   * Creates the xml representation of the job in argument
   *
   * @throws TransformerException
   * @throws ParserConfigurationException
   */
  public InputStream jobToxml(TaskFlowJob job)
      throws TransformerException, ParserConfigurationException {
    DocumentBuilderFactory dbfac = DocumentBuilderFactory.newInstance();
    DocumentBuilder docBuilder = dbfac.newDocumentBuilder();
    Document doc = docBuilder.newDocument();
    doc.setXmlStandalone(true);

    // create the xml tree corresponding to this job
    Element rootJob = createRootJobElement(doc, job);
    doc.appendChild(rootJob);

    // set up a transformer
    TransformerFactory transfac = TransformerFactory.newInstance();
    Transformer trans = transfac.newTransformer();
    trans.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "no");
    trans.setOutputProperty(OutputKeys.INDENT, "yes");
    // If the encoding property is set on the client JVM, use it (it has to match the server-side
    // encoding),
    // otherwise use UTF-8
    if (PASchedulerProperties.FILE_ENCODING.isSet()) {
      trans.setOutputProperty(
          OutputKeys.ENCODING, PASchedulerProperties.FILE_ENCODING.getValueAsString());
    } else {
      trans.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
    }
    trans.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");

    // write the xml
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    StreamResult result = new StreamResult(baos);
    DOMSource source = new DOMSource(doc);
    trans.transform(source, result);
    byte[] array = baos.toByteArray();
    return new ByteArrayInputStream(array);
  }
Exemplo n.º 3
0
  /**
   * Prevede DOM na String s danym kodovanim.
   *
   * @param node
   * @param encoding muze byt null
   * @param pretty prida nove radky za elementy
   * @return
   * @throws ProblemException
   */
  public static String domToString(Node node, String encoding, boolean pretty)
      throws ProblemException {

    if (node == null) return null;

    String usedEncoding = encoding == null ? DEFAULT_ENCODING : encoding;

    if (Checker.isBlank(usedEncoding)) {
      throw new ProblemException(XmlProblem.INVALID_ENCODING);
    }

    TransformerFactory transformerFactory = TransformerFactory.newInstance();
    DOMSource source = new DOMSource(node);

    try (StringWriter writer = new StringWriter()) {
      StreamResult result = new StreamResult(writer);

      Transformer transformer = transformerFactory.newTransformer();
      transformer.setOutputProperty(OutputKeys.METHOD, "xml");
      transformer.setOutputProperty(OutputKeys.ENCODING, usedEncoding);
      transformer.setOutputProperty(OutputKeys.INDENT, pretty ? "yes" : "no");
      transformer.setOutputProperty(OutputKeys.STANDALONE, "no");
      transformer.transform(source, result);

      return writer.toString();

    } catch (Exception e) {
      logger.error(e.toString(), e);
      throw new ProblemException(e, XmlProblem.SERIALIZE_DOM);
    }
  }
Exemplo n.º 4
0
  public void savePreset(String name, Layout layout) {
    Preset preset = addPreset(new Preset(name, layout));

    try {
      // Create file if dont exist
      FileObject folder = FileUtil.getConfigFile("layoutpresets");
      if (folder == null) {
        folder = FileUtil.getConfigRoot().createFolder("layoutpresets");
      }
      FileObject presetFile = folder.getFileObject(name, "xml");
      if (presetFile == null) {
        presetFile = folder.createData(name, "xml");
      }

      // Create doc
      DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
      DocumentBuilder documentBuilder = factory.newDocumentBuilder();
      final Document document = documentBuilder.newDocument();
      document.setXmlVersion("1.0");
      document.setXmlStandalone(true);

      // Write doc
      preset.writeXML(document);

      // Write XML file
      Source source = new DOMSource(document);
      Result result = new StreamResult(FileUtil.toFile(presetFile));
      Transformer transformer = TransformerFactory.newInstance().newTransformer();
      transformer.setOutputProperty(OutputKeys.INDENT, "yes");
      transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
      transformer.transform(source, result);
    } catch (Exception e) {
      e.printStackTrace();
    }
  }
Exemplo n.º 5
0
  /**
   * Writes the specified Node to the given writer.
   *
   * @param node A DOM node.
   * @param writer A stream writer.
   * @throws IOException Thrown if the file cannot be created.
   */
  public void writeAsMusicXML(Document doc, BufferedWriter writer) throws IOException {
    /*
     * writer.write("<"+node.getNodeName()); NamedNodeMap attr =
     * node.getAttributes(); if (attr!=null) for (int i=0;
     * i<attr.getLength(); i++) writer.write(" " +
     * attr.item(i).getNodeName() + "=" + attr.item(i).getNodeValue());
     * writer.write(">"); writer.newLine(); NodeList nlist =
     * node.getChildNodes(); for (int i=0; i<nlist.getLength(); i++)
     * writeAsMusicXML(writer, nlist.item(i));
     * writer.write("</"+node.getNodeName()+">"); writer.newLine();
     */
    try {
      TransformerFactory transfac = TransformerFactory.newInstance();
      Transformer trans = transfac.newTransformer();
      // trans.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
      trans.setOutputProperty(OutputKeys.INDENT, "yes");
      trans.setOutputProperty(
          OutputKeys.DOCTYPE_PUBLIC, "-//Recordare//DTD MusicXML 2.0 Partwise//EN");
      trans.setOutputProperty(
          OutputKeys.DOCTYPE_SYSTEM, "http://www.musicxml.org/dtds/partwise.dtd");

      // create string from xml tree
      // StringWriter sw = new StringWriter();
      StreamResult result = new StreamResult(writer);
      DOMSource source = new DOMSource(doc);

      trans.transform(source, result);
    } catch (Exception e) {
      e.printStackTrace();
    }
    // String xmlString = sw.toString();
    // }
  }
Exemplo n.º 6
0
  public static String getStringFromDocument(Document doc) {
    try {
      doc.normalize();
      DOMSource domSource = new DOMSource(doc);
      StringWriter writer = new StringWriter();
      StreamResult result = new StreamResult(writer);
      TransformerFactory tf = TransformerFactory.newInstance();
      Transformer transformer = tf.newTransformer();
      //
      transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
      int indent = 2;
      if (indent > 0) {
        transformer.setOutputProperty(OutputKeys.INDENT, "yes");
        transformer.setOutputProperty(
            "{http://xml.apache.org/xslt}indent-amount", Integer.toString(indent));
      }
      //

      transformer.transform(domSource, result);
      return writer.toString();
    } catch (TransformerException ex) {
      ex.printStackTrace();
      return null;
    }
  }
Exemplo n.º 7
0
  /**
   * Creates a new generator.
   *
   * @param providers the list of page providers to use.
   * @param dest the destination directory.
   * @param url the public url corresponding to the the destination directory.
   * @throws IOException if the files could not be written.
   */
  public SitemapGenerator(final Collection<PageProvider> providers, final File dest, final URI url)
      throws IOException {

    LOG.info("Initializing...");

    this.uri = url;
    this.providers = providers;
    this.location = dest;

    this.writer = new FileWriter(new File(location, "sitemap_index.xml"));

    final StreamResult streamResult = new StreamResult(writer);

    try {
      tf.setAttribute("indent-number", 2);

      this.transformerHandler = tf.newTransformerHandler();

      final Transformer serializer = transformerHandler.getTransformer();

      serializer.setOutputProperty(OutputKeys.ENCODING, "UTF-8"); //
      serializer.setOutputProperty(OutputKeys.METHOD, "xml");
      serializer.setOutputProperty(OutputKeys.INDENT, "yes");

      transformerHandler.setResult(streamResult);
    } catch (TransformerConfigurationException e) {
      throw new RuntimeException(e);
    }
  }
Exemplo n.º 8
0
  /**
   * @param source
   * @param result
   * @param omit_xml_declaration
   * @param method_xml
   * @param indent
   * @throws Docx4JException
   * @since 3.3.1
   */
  public static void serialize(
      Source source,
      Result result,
      boolean omit_xml_declaration,
      boolean method_xml,
      boolean indent)
      throws Docx4JException {

    // Xalan <= 2.7.2 can't handle astral characters:
    // https://issues.apache.org/jira/browse/XALANJ-2419
    // but org.docx4j.org.apache.xalan repackaging is patched to fix this

    try {
      Transformer serializer =
          new org.docx4j.org.apache.xalan.transformer.TransformerIdentityImpl();

      if (omit_xml_declaration) {
        serializer.setOutputProperty(javax.xml.transform.OutputKeys.OMIT_XML_DECLARATION, "yes");
      }
      if (method_xml) {
        serializer.setOutputProperty(
            javax.xml.transform.OutputKeys.METHOD, "xml"); // probably the default anyway?	
      }
      if (indent) {
        serializer.setOutputProperty(javax.xml.transform.OutputKeys.INDENT, "yes");
        // actual indent amount is set in
        // org/docx4j/org/apache/xml/serializer/docx4j_xalan_output_xml.properties
      }

      serializer.transform(source, result);

    } catch (Exception e) {
      throw new Docx4JException("Exception writing Document to OutputStream: " + e.getMessage(), e);
    }
  }
Exemplo n.º 9
0
  /**
   * Creates the <code>String</code> version of the XML file creating using the specified root node.
   *
   * @param ome The root node.
   * @param binaryData Pass <code>true</code> to add the binary data, <code>false</code> otherwise.
   * @return See above.
   * @throws Exception Thrown if an error occurred while writing the XML file.
   */
  private String createXMLDocument(OME ome, boolean binaryData) throws Exception {
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    DocumentBuilder parser = factory.newDocumentBuilder();
    Document document = parser.newDocument();
    Element root = ome.asXMLElement(document);
    root.setAttribute("xmlns", XML_NS);
    root.setAttribute("xmlns:xsi", XSI_NS);
    root.setAttribute("xsi:schemaLocation", XML_NS + " " + SCHEMA_LOCATION);
    document.appendChild(root);

    // Add Planar data
    if (binaryData) {
      NodeList nodes = document.getElementsByTagName(BIN_DATA_TAG);
      for (int i = 0; i < nodes.getLength(); i++) {
        nodes.item(i).setTextContent(PLANE);
      }
    }
    TransformerFactory tFactory = TransformerFactory.newInstance();
    Transformer transformer = tFactory.newTransformer();
    transformer.setOutputProperty(OutputKeys.INDENT, "yes");
    transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4");
    Source source = new DOMSource(document);
    ByteArrayOutputStream os = new ByteArrayOutputStream();
    Result result = new StreamResult(new OutputStreamWriter(os, "utf-8"));
    transformer.transform(source, result);
    return os.toString();
  }
Exemplo n.º 10
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);
  }
Exemplo n.º 11
0
  /**
   * Serialize the Document object.
   *
   * @param dom the document to serialize
   * @return the serialized dom String
   */
  public static byte[] getDocumentToByteArray(Document dom) {
    try {
      TransformerFactory tFactory = TransformerFactory.newInstance();

      Transformer transformer = tFactory.newTransformer();
      transformer.setOutputProperty(OutputKeys.INDENT, "yes");
      transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "no");
      transformer.setOutputProperty(OutputKeys.METHOD, "html");
      // TODO should be fixed to read doctype declaration
      // transformer.setOutputProperty(OutputKeys.DOCTYPE_PUBLIC,
      // "-//W3C//DTD XHTML 1.0 Transitional//EN\"
      // \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd");
      transformer.setOutputProperty(
          OutputKeys.DOCTYPE_PUBLIC,
          "-//W3C//DTD XHTML 1.0 Strict//EN\" "
              + "\"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd");

      // transformer.setOutputProperty(OutputKeys.DOCTYPE_PUBLIC,
      // "-//W3C//DTD HTML 4.01//EN\" \"http://www.w3.org/TR/html4/strict.dtd");
      DOMSource source = new DOMSource(dom);

      ByteArrayOutputStream out = new ByteArrayOutputStream();
      Result result = new StreamResult(out);
      transformer.transform(source, result);

      // System.out.println("Injected Javascript!");
      return out.toByteArray();
    } catch (TransformerConfigurationException e) {
      LOGGER.error(e.getMessage(), e);
    } catch (TransformerException e) {
      LOGGER.error(e.getMessage(), e);
    }
    return null;
  }
Exemplo n.º 12
0
  public static boolean transformXML(Document doc, String saveDirectory, String fileName) {
    String saveFile = null;
    boolean success = false;
    // set up a transformer
    try {
      TransformerFactory transfac = TransformerFactory.newInstance();
      Transformer trans = transfac.newTransformer();
      trans.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "no");
      trans.setOutputProperty(OutputKeys.INDENT, "yes");
      trans.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4");

      doc.setXmlStandalone(true);

      saveFile = saveDirectory + fileName;

      // create string from xml tree
      Result result = new StreamResult(new File(saveFile));
      Source source = new DOMSource(doc);

      // perform transformation of String to XML and output to file
      trans.transform(source, result);
      success = true;
    } catch (Exception e) {
      e.printStackTrace();
      success = false;
    }
    return success;
  }
 private Transformer getTransformerConfiguredWithIndentation()
     throws TransformerConfigurationException {
   final Transformer transformer = TransformerFactoryImpl.newInstance().newTransformer();
   transformer.setOutputProperty(OutputKeys.INDENT, "yes");
   transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4");
   return transformer;
 }
  public static void exportSVG(File file, Algorithm algorithm, Config config, int width, int height)
      throws TransformerException, IOException {
    DOMImplementation impl = SVGDOMImplementation.getDOMImplementation();
    String svgNS = SVGDOMImplementation.SVG_NAMESPACE_URI;
    Document doc = impl.createDocument(svgNS, "svg", null);

    Element svgRoot = doc.getDocumentElement();

    svgRoot.setAttributeNS(null, "width", Integer.toString(width));
    svgRoot.setAttributeNS(null, "height", Integer.toString(height));

    SvgPainter painter = new SvgPainter(doc, svgRoot);

    AlgorithmPainter algorithmPainter = new AlgorithmPainter(algorithm, config, painter);

    algorithmPainter.setWidth(width);
    algorithmPainter.setHeight(height);
    algorithmPainter.paint();

    TransformerFactory transformerFactory = TransformerFactory.newInstance();
    Transformer transformer = transformerFactory.newTransformer();
    DOMSource source = new DOMSource(doc);
    FileOutputStream fos = new FileOutputStream(file);
    StreamResult result = new StreamResult(fos);

    transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "no");
    transformer.setOutputProperty(OutputKeys.METHOD, "xml");
    transformer.setOutputProperty(OutputKeys.INDENT, "yes");
    transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
    transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4");

    transformer.transform(source, result);

    fos.close();
  }
Exemplo n.º 15
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();
  }
Exemplo n.º 16
0
  /**
   * Converts a given list of SoundResources to an XML string.
   *
   * @param a list of SoundResources to convert to an XML string
   * @return an XML String representation of the given SoundResources.
   * @throws TransformerFactoryConfigurationError when transformer factory is configured incorrectly
   * @throws TransformerConfigurationException when transformer is configured incorrectly
   * @throws TransformerException when an exceptional condition occurs during the transformation
   *     process
   */
  private String soundResourcesToString(List<SoundResource> soundResources)
      throws TransformerFactoryConfigurationError, TransformerConfigurationException,
          TransformerException {
    // create XML document and add the root element
    Document xml = docBuilder.newDocument();
    Element composition = xml.createElement("composition");
    xml.appendChild(composition);

    // create sound elements recursively
    xml = buildXML(xml, composition, soundResources);

    // indent 4 spaces and remove XML declaration
    TransformerFactory transFactory = TransformerFactory.newInstance();
    Transformer xmlTransformer = transFactory.newTransformer();
    xmlTransformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
    xmlTransformer.setOutputProperty(OutputKeys.INDENT, "yes");
    xmlTransformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4");

    // convert XML to String
    StringWriter writer = new StringWriter();
    StreamResult result = new StreamResult(writer);
    DOMSource source = new DOMSource(xml);
    xmlTransformer.transform(source, result);
    String xmlString = writer.toString();
    return xmlString;
  }
Exemplo n.º 17
0
  private void writeXmlDocument(File file, Document doc) {
    try {
      // set up a transformer
      TransformerFactory transfac = TransformerFactory.newInstance();
      Transformer trans = transfac.newTransformer();
      trans.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
      trans.setOutputProperty(OutputKeys.INDENT, "yes");

      // create string from xml tree
      FileWriter writer = new FileWriter(file);
      StreamResult result = new StreamResult(writer);
      DOMSource source = new DOMSource(doc);
      trans.transform(source, result);

      writer.close();
    } catch (TransformerConfigurationException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    } catch (TransformerException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    } catch (IOException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
  }
Exemplo n.º 18
0
  public void write(HttpServletResponse response) {
    StreamResult streamResult;
    SAXTransformerFactory tf;
    TransformerHandler hd;
    Transformer serializer;

    try {
      try {
        streamResult = new StreamResult(response.getWriter());
        tf = (SAXTransformerFactory) SAXTransformerFactory.newInstance();
        hd = tf.newTransformerHandler();
        serializer = hd.getTransformer();

        serializer.setOutputProperty(OutputKeys.ENCODING, "utf-8");
        serializer.setOutputProperty(
            OutputKeys.DOCTYPE_SYSTEM, "http://labs.omniti.com/resmon/trunk/resources/resmon.dtd");
        serializer.setOutputProperty(OutputKeys.INDENT, "yes");

        hd.setResult(streamResult);
        hd.startDocument();
        AttributesImpl atts = new AttributesImpl();
        hd.startElement("", "", "ResmonResults", atts);
        for (ResmonResult r : s) {
          r.write(hd);
        }
        hd.endElement("", "", "ResmonResults");
        hd.endDocument();
      } catch (TransformerConfigurationException tce) {
        response.getWriter().println(tce.getMessage());
      } catch (SAXException se) {
        response.getWriter().println(se.getMessage());
      }
    } catch (IOException ioe) {
    }
  }
Exemplo n.º 19
0
      public SiteMapFile(int count) throws IOException, SAXException {
        this.fileName = name + '_' + count + ".xml";
        writer = new FileWriter(new File(location, fileName));
        final StreamResult streamResult = new StreamResult(writer);

        try {
          transformerHandler = tf.newTransformerHandler();

          Transformer serializer = transformerHandler.getTransformer();

          serializer.setOutputProperty(OutputKeys.ENCODING, "UTF-8"); //
          serializer.setOutputProperty(OutputKeys.METHOD, "xml");
          serializer.setOutputProperty(OutputKeys.INDENT, "yes");

          transformerHandler.setResult(streamResult);
          transformerHandler.startDocument();

          AttributesImpl schemaLocation = new AttributesImpl();

          transformerHandler.startPrefixMapping("xsd", XMLConstants.W3C_XML_SCHEMA_NS_URI);
          transformerHandler.startPrefixMapping("xsi", XMLConstants.W3C_XML_SCHEMA_INSTANCE_NS_URI);

          schemaLocation.addAttribute(
              XMLConstants.W3C_XML_SCHEMA_NS_URI,
              "schemaLocation",
              "xsi:schemaLocation",
              "CDATA",
              "http://www.sitemaps.org/schemas/sitemap/0.9/sitemap.xsd");

          transformerHandler.startElement(NS, "", "urlset", schemaLocation);
        } catch (TransformerConfigurationException e) {
          throw new RuntimeException(e);
        }
      }
Exemplo n.º 20
0
  /**
   * Write the XML document to the file trace.xml from
   * http://java.developpez.com/faq/xml/?page=xslt#creerXmlDom
   */
  public boolean close() {
    boolean status = true;
    try {
      // Create the DOM source
      Source source = new DOMSource(m_document);

      // Create the output file
      File file = new File(m_fileName);
      Result resultat = new StreamResult(m_fileName);

      // Create the transformer
      TransformerFactory fabrique = TransformerFactory.newInstance();
      Transformer transformer = fabrique.newTransformer();
      transformer.setOutputProperty(OutputKeys.INDENT, "yes");
      transformer.setOutputProperty(OutputKeys.ENCODING, "ISO-8859-1");

      // Transformation
      transformer.transform(source, resultat);
    } catch (Exception e) {
      System.out.println("Error creating the file trace.xml");
      status = false;
      e.printStackTrace();
    }
    return status;
  }
Exemplo n.º 21
0
  /**
   * Write the specified WSDL definition to the specified Writer.
   *
   * @param wsdlDef the WSDL definition to be written.
   * @param sink the Writer to write the xml to.
   */
  public void writeWSDL(Definition wsdlDef, Writer sink) throws WSDLException {
    String encoding = null;
    try {
      TransformerFactory transformerFactory = TransformerFactory.newInstance();
      Transformer transformer = transformerFactory.newTransformer();

      transformer.setOutputProperty(OutputKeys.INDENT, "yes");
      transformer.setOutputProperty(OutputKeys.METHOD, "xml");

      // Unless a width is set, there will be only line breaks but no indentation.
      // The IBM JDK and the Sun JDK don't agree on the property name,
      // so we set them both.
      //
      transformer.setOutputProperty("{http://xml.apache.org/xalan}indent-amount", "2");
      transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");
      if (encoding != null) {
        transformer.setOutputProperty(OutputKeys.ENCODING, encoding);
      }

      Document document = ((DefinitionImpl) wsdlDef).getDocument();
      if (document == null) {
        ((DefinitionImpl) wsdlDef).updateElement(true);
        document = ((DefinitionImpl) wsdlDef).getDocument();
      }

      transformer.transform(new DOMSource(document), new StreamResult(sink));
    } catch (TransformerException exception) {
      throw new WSDLException(WSDLException.OTHER_ERROR, "Failed to save Definitions.", exception);
    }
  }
Exemplo n.º 22
0
  @Override
  public void notifyAfterMobsim(AfterMobsimEvent event) {
    if (!trackIteration) return;

    try {
      DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
      DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();

      Document document = documentBuilder.newDocument();
      Element schedules = document.createElement("services");
      document.appendChild(schedules);

      for (Service service : services) {
        schedules.appendChild(buildXmlService(document, service));
      }

      TransformerFactory transformerFactory = TransformerFactory.newInstance();
      Transformer transformer = transformerFactory.newTransformer();
      transformer.setOutputProperty(OutputKeys.INDENT, "yes");
      transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4");

      DOMSource source = new DOMSource(document);

      this.openFile(controlerIO.getIterationFilename(event.getIteration(), "av_services.xml.gz"));
      StreamResult result = new StreamResult(this.writer);

      transformer.transform(source, result);
    } catch (ParserConfigurationException
        | TransformerFactoryConfigurationError
        | TransformerException e) {
      throw new RuntimeException("Error while dumping AV schedules");
    } finally {
      this.close();
    }
  }
Exemplo n.º 23
0
  public static void main(String[] args) {

    String outputDir = "./";

    for (int i = 0; i < args.length; i++) {
      String arg = args[i];
      if ("-o".equals(arg)) {
        outputDir = args[++i];
        continue;
      } else {
        System.out.println("XMLSchemaGenerator -o <path to newly created xsd schema file>");
        return;
      }
    }

    File f = new File(outputDir, "JGroups-" + Version.major + "." + Version.minor + ".xsd");
    try {
      FileWriter fw = new FileWriter(f, false);
      DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
      DocumentBuilder builder = factory.newDocumentBuilder();
      DOMImplementation impl = builder.getDOMImplementation();
      Document xmldoc = impl.createDocument("http://www.w3.org/2001/XMLSchema", "xs:schema", null);
      xmldoc.getDocumentElement().setAttribute("targetNamespace", "urn:org:jgroups");
      xmldoc.getDocumentElement().setAttribute("elementFormDefault", "qualified");

      Element xsElement = xmldoc.createElement("xs:element");
      xsElement.setAttribute("name", "config");
      xmldoc.getDocumentElement().appendChild(xsElement);

      Element complexType = xmldoc.createElement("xs:complexType");
      xsElement.appendChild(complexType);

      Element allType = xmldoc.createElement("xs:choice");
      allType.setAttribute("maxOccurs", "unbounded");
      complexType.appendChild(allType);

      Set<Class<?>> classes = getClasses("bboss.org.jgroups.protocols", Protocol.class);
      for (Class<?> clazz : classes) {
        classToXML(xmldoc, allType, clazz, "");
      }
      classes = getClasses("bboss.org.jgroups.protocols.pbcast", Protocol.class);
      for (Class<?> clazz : classes) {
        classToXML(xmldoc, allType, clazz, "pbcast.");
      }

      DOMSource domSource = new DOMSource(xmldoc);
      StreamResult streamResult = new StreamResult(fw);
      TransformerFactory tf = TransformerFactory.newInstance();
      Transformer serializer = tf.newTransformer();
      serializer.setOutputProperty(OutputKeys.METHOD, "xml");
      serializer.setOutputProperty(OutputKeys.INDENT, "yes");
      serializer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "1");
      serializer.transform(domSource, streamResult);

      fw.flush();
      fw.close();
    } catch (Exception e) {
      e.printStackTrace();
    }
  }
Exemplo n.º 24
0
  public void write(Document doc, OutputStream outputStream) throws IOException {
    //        OutputFormat format = new OutputFormat(doc);
    //        format.setIndenting(true);
    //        format.setEncoding("UTF-8");
    //        XMLSerializer serializer = new XMLSerializer(outputStream, format);
    //        serializer.asDOMSerializer();
    //        serializer.serialize(doc);

    try {
      TransformerFactory factory = TransformerFactory.newInstance();
      try {
        factory.setAttribute("indent-number", 4);
      } catch (Exception e) {; // guess we can't set it, that's ok
      }

      Transformer transformer = factory.newTransformer();
      transformer.setOutputProperty(OutputKeys.METHOD, "xml");
      transformer.setOutputProperty(OutputKeys.INDENT, "yes");
      transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");

      // need to nest outputStreamWriter to get around JDK 5 bug.  See
      // http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6296446
      transformer.transform(
          new DOMSource(doc), new StreamResult(new OutputStreamWriter(outputStream, "utf-8")));
    } catch (TransformerException e) {
      throw new IOException(e.getMessage());
    }
  }
Exemplo n.º 25
0
  public static void prettyPrintXml(Document doc, OutputStream out, int indent) {
    DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
    TransformerFactory tfactory = TransformerFactory.newInstance();

    // set indent spaces on factory
    //        tfactory.setAttribute("indent-number", new Integer(indent));

    try {
      Transformer serializer = tfactory.newTransformer();

      // turn on indenting on transformer (serializer)
      serializer.setOutputProperty(OutputKeys.INDENT, "yes");
      serializer.setOutputProperty(
          "{http://xml.apache.org/xslt}indent-amount",
          //            		String.valueOf(indent));
          "2");

      serializer.transform(
          new DOMSource(doc), new StreamResult(new OutputStreamWriter(out, "utf-8")));
    } catch (Exception e) {

      // this is fatal, just dump stack and throw runtime exception
      e.printStackTrace();

      throw new RuntimeException(e);
    }
  }
Exemplo n.º 26
0
 public void createXml(String fileName) {
   Element root = this.document.createElement("employees");
   this.document.appendChild(root);
   Element employee = this.document.createElement("employee");
   Element name = this.document.createElement("name");
   name.appendChild(this.document.createTextNode("丁宏亮"));
   employee.appendChild(name);
   Element sex = this.document.createElement("sex");
   sex.appendChild(this.document.createTextNode("m"));
   employee.appendChild(sex);
   Element age = this.document.createElement("age");
   age.appendChild(this.document.createTextNode("30"));
   employee.appendChild(age);
   root.appendChild(employee);
   TransformerFactory tf = TransformerFactory.newInstance();
   try {
     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);
     System.out.println("生成XML文件成功!");
   } catch (TransformerConfigurationException e) {
     System.out.println(e.getMessage());
   } catch (IllegalArgumentException e) {
     System.out.println(e.getMessage());
   } catch (FileNotFoundException e) {
     System.out.println(e.getMessage());
   } catch (TransformerException e) {
     System.out.println(e.getMessage());
   }
 }
  /** {@inheritDoc} */
  @Override
  public void write(ProjectFile projectFile, OutputStream stream) throws IOException {
    try {
      if (CONTEXT == null) {
        throw CONTEXT_EXCEPTION;
      }

      //
      // The Primavera schema defines elements as nillable, which by
      // default results in
      // JAXB generating elements like this <element xsl:nil="true"/>
      // whereas Primavera itself simply omits these elements.
      //
      // The XSLT stylesheet below transforms the XML generated by JAXB on
      // the fly to remove any nil elements.
      //
      TransformerFactory transFact = TransformerFactory.newInstance();
      TransformerHandler handler =
          ((SAXTransformerFactory) transFact)
              .newTransformerHandler(
                  new StreamSource(new ByteArrayInputStream(NILLABLE_STYLESHEET.getBytes())));
      handler.setResult(new StreamResult(stream));
      Transformer transformer = handler.getTransformer();
      transformer.setOutputProperty(OutputKeys.INDENT, "yes");
      transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");

      m_projectFile = projectFile;
      m_calendar = Calendar.getInstance();

      Marshaller marshaller = CONTEXT.createMarshaller();

      marshaller.setProperty(Marshaller.JAXB_SCHEMA_LOCATION, "");

      m_factory = new ObjectFactory();
      m_apibo = m_factory.createAPIBusinessObjects();

      writeProjectProperties();
      writeCalendars();
      writeResources();
      writeTasks();
      writeAssignments();

      DatatypeConverter.setParentFile(m_projectFile);

      marshaller.marshal(m_apibo, handler);
    } catch (JAXBException ex) {
      throw new IOException(ex.toString());
    } catch (TransformerConfigurationException ex) {
      throw new IOException(ex.toString());
    } finally {
      m_projectFile = null;
      m_factory = null;
      m_apibo = null;
      m_project = null;
      m_wbsSequence = 0;
      m_relationshipObjectID = 0;
      m_calendar = null;
    }
  }
Exemplo n.º 28
0
 public static String prettyPrint(Document xml) throws Exception {
   Transformer tf = TransformerFactory.newInstance().newTransformer();
   tf.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
   tf.setOutputProperty(OutputKeys.INDENT, "yes");
   Writer out = new StringWriter();
   tf.transform(new DOMSource(xml), new StreamResult(out));
   return (out.toString());
 }
Exemplo n.º 29
0
  /**
   * Writes visual structure to output XML
   *
   * @param visualStructure Given visual structure
   * @param pageViewport Page's viewport
   */
  public void writeXML(VisualStructure visualStructure, Viewport pageViewport) {
    try {
      DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
      DocumentBuilder docBuilder = docFactory.newDocumentBuilder();

      doc = docBuilder.newDocument();
      Element vipsElement = doc.createElement("VIPSPage");

      String pageTitle =
          pageViewport
              .getRootElement()
              .getOwnerDocument()
              .getElementsByTagName("title")
              .item(0)
              .getTextContent();

      vipsElement.setAttribute("Url", pageViewport.getRootBox().getBase().toString());
      vipsElement.setAttribute("PageTitle", pageTitle);
      vipsElement.setAttribute("WindowWidth", String.valueOf(pageViewport.getContentWidth()));
      vipsElement.setAttribute("WindowHeight", String.valueOf(pageViewport.getContentHeight()));
      vipsElement.setAttribute("PageRectTop", String.valueOf(pageViewport.getAbsoluteContentY()));
      vipsElement.setAttribute("PageRectLeft", String.valueOf(pageViewport.getAbsoluteContentX()));
      vipsElement.setAttribute("PageRectWidth", String.valueOf(pageViewport.getContentWidth()));
      vipsElement.setAttribute("PageRectHeight", String.valueOf(pageViewport.getContentHeight()));
      vipsElement.setAttribute("neworder", "0");
      vipsElement.setAttribute("order", String.valueOf(pageViewport.getOrder()));

      doc.appendChild(vipsElement);

      writeVisualBlocks(vipsElement, visualStructure);

      TransformerFactory transformerFactory = TransformerFactory.newInstance();
      Transformer transformer = transformerFactory.newTransformer();
      transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
      transformer.setOutputProperty(OutputKeys.INDENT, "yes");
      DOMSource source = new DOMSource(doc);

      if (_escapeOutput) {
        StreamResult result = new StreamResult(new File(_filename + ".xml"));
        transformer.transform(source, result);
      } else {
        StringWriter writer = new StringWriter();
        transformer.transform(source, new StreamResult(writer));
        String result = writer.toString();

        result = result.replaceAll("&gt;", ">");
        result = result.replaceAll("&lt;", "<");
        result = result.replaceAll("&quot;", "\"");

        FileWriter fstream = new FileWriter(_filename + ".xml");
        fstream.write(result);
        fstream.close();
      }
    } catch (Exception e) {
      System.err.println("Error: " + e.getMessage());
      e.printStackTrace();
    }
  }
Exemplo n.º 30
0
 static {
   try {
     t = TransformerFactory.newInstance().newTransformer();
     t.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
     t.setOutputProperty(OutputKeys.INDENT, "yes");
   } catch (Exception e) {
     e.printStackTrace();
   }
 }