Beispiel #1
0
  public UUID exportDiagram(Diagram diagram, String kit, String taskId) throws Exception {
    JavaModelConverter converter = new JavaModelConverter();
    DiagramXml diagramXml = converter.convertToXml(diagram);

    TransformerFactory transformerFactory = TransformerFactory.newInstance();
    transformer = transformerFactory.newTransformer();
    transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");

    String directoryPath =
        String.format("%s/trikKit%s/tasks/%s", PathConstants.STEPIC_PATH, kit, taskId);
    String targetPath =
        String.format(
            "%s/solutions/%s/%s", directoryPath, String.valueOf(diagramXml.getUuid()), taskId);
    File targetDirectory = new File(targetPath);
    targetDirectory.mkdirs();

    new File(String.format("%s/%s", targetPath, PathConstants.PATH_TO_GRAPHICAL_PART)).mkdirs();
    new File(String.format("%s/%s", targetPath, PathConstants.PATH_TO_LOGICAL_PART)).mkdirs();
    new File(String.format("%s/%s", targetPath, PathConstants.PATH_TO_ROOT_ID)).mkdirs();

    copyDefaultFiles(taskId, directoryPath, targetPath);
    exportDiagramXml(diagramXml, targetPath);
    exportRootId(diagramXml.getRootIdXml(), targetPath);
    return diagramXml.getUuid();
  }
Beispiel #2
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());
    }
  }
  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();
    }
  }
  // TODO - change the return type and the factory parameter to be Definitions and ObjectFactory,
  // and move to bpmn-schema
  public BpmnDefinitions correctFlowNodeRefs(
      final BpmnDefinitions definitions, final BpmnObjectFactory factory)
      throws JAXBException, TransformerException {

    JAXBContext context =
        JAXBContext.newInstance(
            factory.getClass(),
            com.processconfiguration.ObjectFactory.class,
            org.omg.spec.bpmn._20100524.di.ObjectFactory.class,
            org.omg.spec.bpmn._20100524.model.ObjectFactory.class,
            org.omg.spec.dd._20100524.dc.ObjectFactory.class,
            org.omg.spec.dd._20100524.di.ObjectFactory.class,
            com.signavio.ObjectFactory.class);

    // Marshal the BPMN into a DOM tree
    DOMResult intermediateResult = new DOMResult();
    Marshaller marshaller = context.createMarshaller();
    marshaller.marshal(factory.createDefinitions(definitions), intermediateResult);

    // Apply the XSLT transformation, generating a new DOM tree
    TransformerFactory transformerFactory = TransformerFactory.newInstance();
    Transformer transformer =
        transformerFactory.newTransformer(
            new StreamSource(
                getClass().getClassLoader().getResourceAsStream("xsd/fix-flowNodeRef.xsl")));
    DOMSource finalSource = new DOMSource(intermediateResult.getNode());
    DOMResult finalResult = new DOMResult();
    transformer.transform(finalSource, finalResult);

    // Unmarshal back to JAXB
    Object def2 = context.createUnmarshaller().unmarshal(finalResult.getNode());
    return ((JAXBElement<BpmnDefinitions>) def2).getValue();
  }
  private void parseWebFragmentXml() throws XMLStreamException, IOException, TransformerException {
    final XMLInputFactory xif = XMLInputFactory.newInstance();
    final XMLStreamReader xsr = xif.createXMLStreamReader(getInputStream());
    xsr.nextTag(); // web-fragment tag skipped

    while (xsr.hasNext() && xsr.nextTag() == XMLStreamConstants.START_ELEMENT) {
      final String tagName = xsr.getLocalName();
      // webFragmentName
      if ("name".equalsIgnoreCase(tagName)) {
        final String element = xsr.getElementText();
        allWebFragmentNames.add(element);
        webFragmentXmlComponents.add("<name>" + element + "</name>");
      } else {
        final TransformerFactory tf = TransformerFactory.newInstance();
        final Transformer t = tf.newTransformer();
        final StringWriter res = new StringWriter();
        t.transform(new StAXSource(xsr), new StreamResult(res));
        final String element =
            org.apache.commons.lang3.StringUtils.substringAfter(res.toString(), "?>");
        if ("ordering".equalsIgnoreCase(tagName)) {
          // ordering
          parseOrdering(element);
        } else {
          // webFragmentXmlComponents
          webFragmentXmlComponents.add(element);
        }
      }
    }
    if (allWebFragmentNames.isEmpty()) {
      throw new IllegalStateException(
          "Name tag is missing. Please specify a name in the web-fragment.xml!");
    }
  }
 /**
  * Call this method to save modified manifest.xml file
  *
  * @throws TransformerException
  */
 public void saveDocument() throws TransformerException {
   TransformerFactory tfactory = TransformerFactory.newInstance();
   Transformer transformer = tfactory.newTransformer();
   DOMSource source = new DOMSource(document);
   StreamResult result = new StreamResult(new File(xmlFullPath));
   transformer.transform(source, result);
 }
Beispiel #7
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());
   }
 }
  @Override
  public void doBody(List<ParameterValue> inputParameters, List<ParameterValue> outputParameters) {
    Document report = null;
    Transformer transformer = null;
    TransformerFactory factory = TransformerFactory.newInstance();
    ReportNameSingleton reportNameSingleton = ReportNameSingleton.getInstance();
    String reportName =
        reportNameSingleton.getExecutedActivityName() + reportNameSingleton.getEngineName();

    try {
      report = Reporter.INSTANCE.getReport();
    } catch (ParserConfigurationException e) {
      Activator.log.error(e);
    }

    try {
      transformer = factory.newTransformer();
    } catch (TransformerConfigurationException e) {
      Activator.log.error(e);
    }
    if (transformer != null) {
      this.writeReport(transformer, report, Platform.getInstanceLocation().getURL(), reportName);
      // System.out.println(Platform.getInstanceLocation().getURL());
    }
  }
  protected Templates getTemplates(String filename) {

    File file = new File(filename);

    // check timestamp if we have it already
    long lastModified = file.lastModified();
    TemplatesCache cache = (TemplatesCache) xslCache.get(file);
    if (cache != null && cache.timestamp == lastModified) return cache.templates;

    cache = new TemplatesCache();
    cache.timestamp = lastModified;

    // get a new
    try {
      TransformerFactory factory = TransformerFactory.newInstance();
      cache.templates = factory.newTemplates(new StreamSource(file));
    } catch (TransformerConfigurationException e) {
      throw new RuntimeException(
          "Exception reading templates from " + filename + ": " + e.getMessage());
    }

    // keep it
    xslCache.put(file, cache);

    // done
    return cache.templates;
  }
Beispiel #10
0
  public String createDrawingXML(String drawing) {
    try {
      DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
      DocumentBuilder docBuilder = docFactory.newDocumentBuilder();

      Document doc = docBuilder.newDocument();
      Element rootElement = doc.createElement("message");

      rootElement.setAttribute("drawing", drawing);
      rootElement.setAttribute("user", user);
      rootElement.setAttribute("cmd", "create");

      doc.appendChild(rootElement);

      TransformerFactory tf = TransformerFactory.newInstance();
      Transformer transformer = tf.newTransformer();
      StringWriter writer = new StringWriter();
      transformer.transform(new DOMSource(doc), new StreamResult(writer));
      String xml = writer.getBuffer().toString().replaceAll("\n|\r", "");

      postData(xml);

      return null;
    } catch (ParserConfigurationException ex) {
      Logger.getLogger(XMLManager.class.getName()).log(Level.SEVERE, null, ex);
      return null;
    } catch (TransformerConfigurationException ex) {
      Logger.getLogger(XMLManager.class.getName()).log(Level.SEVERE, null, ex);
      return null;
    } catch (TransformerException ex) {
      Logger.getLogger(XMLManager.class.getName()).log(Level.SEVERE, null, ex);
      return null;
    }
  }
Beispiel #11
0
  protected static String erdfToRdf(String erdf) throws TransformerException {
    String serializedDOM =
        "<?xml version=\"1.0\" encoding=\"utf-8\"?>"
            + "<html xmlns=\"http://www.w3.org/1999/xhtml\" "
            + "xmlns:b3mn=\"http://b3mn.org/2007/b3mn\" "
            + "xmlns:ext=\"http://b3mn.org/2007/ext\" "
            + "xmlns:rdf=\"http://www.w3.org/1999/02/22-rdf-syntax-ns#\" "
            + "xmlns:atom=\"http://b3mn.org/2007/atom+xhtml\">"
            + "<head profile=\"http://purl.org/NET/erdf/profile\">"
            + "<link rel=\"schema.dc\" href=\"http://purl.org/dc/elements/1.1/\" />"
            + "<link rel=\"schema.dcTerms\" href=\"http://purl.org/dc/terms/ \" />"
            + "<link rel=\"schema.b3mn\" href=\"http://b3mn.org\" />"
            + "<link rel=\"schema.oryx\" href=\"http://oryx-editor.org/\" />"
            + "<link rel=\"schema.raziel\" href=\"http://raziel.org/\" />"
            + "</head><body>"
            + erdf
            + "</body></html>";

    InputStream xsltStream =
        Dispatcher.servletContext.getResourceAsStream("/WEB-INF/lib/extract-rdf.xsl");
    Source xsltSource = new StreamSource(xsltStream);
    Source erdfSource = new StreamSource(new StringReader(serializedDOM));

    TransformerFactory transFact = TransformerFactory.newInstance();
    Transformer trans = transFact.newTransformer(xsltSource);
    StringWriter output = new StringWriter();
    trans.transform(erdfSource, new StreamResult(output));
    return output.toString();
  }
  private static String getXHTMLfromGameXML(String gameXML, String XSL) {
    XSL = XSL.replace("<!DOCTYPE stylesheet [<!ENTITY ROOT \"http://games.ggp.org/base\">]>", "");
    XSL = XSL.replace("&ROOT;", "http://games.ggp.org/base").trim();

    IOString game = new IOString(gameXML);
    IOString xslIOString = new IOString(XSL);
    IOString content = new IOString("");
    try {
      TransformerFactory tFactory = TransformerFactory.newInstance();
      Transformer transformer =
          tFactory.newTransformer(new StreamSource(xslIOString.getInputStream()));
      transformer.setParameter("width", defaultSize.getWidth() - 40);
      transformer.setParameter("height", defaultSize.getHeight() - 40);
      transformer.transform(
          new StreamSource(game.getInputStream()), new StreamResult(content.getOutputStream()));
    } catch (Exception ex) {
      ex.printStackTrace();
    }

    Tidy tidy = new Tidy();
    tidy.setXHTML(true);
    tidy.setShowWarnings(false);
    tidy.setQuiet(true);
    tidy.setDropEmptyParas(false);

    IOString tidied = new IOString("");
    tidy.parse(content.getInputStream(), tidied.getOutputStream());
    return tidied.getString();
  }
Beispiel #13
0
  public String getMemento() {
    String collectData = new String(""); // $NON-NLS-1$

    DocumentBuilderFactory dfactory = DocumentBuilderFactory.newInstance();
    DocumentBuilder docBuilder = null;
    try {
      docBuilder = dfactory.newDocumentBuilder();
      Document doc = docBuilder.newDocument();

      Element rootElement = doc.createElement("collectData"); // $NON-NLS-1$
      rootElement.setAttribute("collectString", fCollectString); // $NON-NLS-1$

      doc.appendChild(rootElement);

      ByteArrayOutputStream s = new ByteArrayOutputStream();

      TransformerFactory factory = TransformerFactory.newInstance();
      Transformer transformer = factory.newTransformer();
      transformer.setOutputProperty(OutputKeys.METHOD, "xml"); // $NON-NLS-1$
      transformer.setOutputProperty(OutputKeys.INDENT, "yes"); // $NON-NLS-1$

      DOMSource source = new DOMSource(doc);
      StreamResult outputTarget = new StreamResult(s);
      transformer.transform(source, outputTarget);

      collectData = s.toString("UTF8"); // $NON-NLS-1$

    } catch (Exception e) {
      e.printStackTrace();
    }
    return collectData;
  }
Beispiel #14
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;
    }
  }
  public static void main(String[] args) throws Exception {
    String in = null;
    String xsl = null;
    String out = null;

    if (args.length != 6) {
      System.err.println("Insufficient args: SimpleTransform -in file -xsl file -out file");
      System.exit(1);
    }

    for (int i = 0; i < args.length; i++) {
      if (args[i].equals("-in")) {
        in = args[++i];
      } else if (args[i].equals("-xsl")) {
        xsl = args[++i];
      } else if (args[i].equals("-out")) {
        out = args[++i];
      } else {
        System.err.println("Unrecognized arg: " + args[i]);
        System.exit(1);
      }
    }

    final TransformerFactory f = TransformerFactory.newInstance();
    final Transformer t = f.newTransformer(new StreamSource(new File(xsl)));
    //         final Source src = new SAXSource(XMLReaderFactory.newInstance(System.err),
    //                                    new InputSource(in));
    final Source src = new SAXSource(new VariableResolver(), new InputSource(in));
    final Result res = new StreamResult(out);

    t.transform(src, res);
  }
  /**
   * Extract an XML element.
   *
   * @param xpathExp
   * @param file
   * @return
   */
  private Document getDocFragment(String xpathExp, XmlMetadata file) {

    Document testDoc = null;

    try {
      XPath xpath = XPathFactory.newInstance().newXPath();
      Node node = (Node) xpath.evaluate(xpathExp, file.getParsedDocument(), XPathConstants.NODE);

      if (node != null) {
        TransformerFactory transFactory = TransformerFactory.newInstance();
        Transformer transformer = transFactory.newTransformer();
        StringWriter buffer = new StringWriter();
        transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
        transformer.transform(new DOMSource(node), new StreamResult(buffer));
        String testStr = buffer.toString();
        LOG.debug("src string: " + testStr);

        DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
        DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
        testDoc =
            dBuilder.parse(new InputSource(new ByteArrayInputStream(testStr.getBytes("utf-8"))));
      }
    } catch (XPathExpressionException xee) {
      LOG.error("Invalid XPath expression: " + xpathExp);
    } catch (Exception e) {
      LOG.error("Error extracting XML content: ", e);
    }

    return testDoc;
  }
Beispiel #17
0
 /**
  * The constructor assigns the schemaLocation associated with this crosswalk. Since the crosswalk
  * is trivial in this case, no properties are utilized.
  *
  * @param properties properties that are needed to configure the crosswalk.
  */
 public XSLTCrosswalk(
     Properties properties,
     String schemaLocation,
     String contentType,
     String docType,
     String encoding)
     throws OAIInternalServerError {
   // 	super("http://www.openarchives.org/OAI/2.0/oai_dc/
   // http://www.openarchives.org/OAI/2.0/oai_dc.xsd");
   super(schemaLocation, contentType, docType, encoding);
   if ("true".equals(properties.getProperty("XSLTCrosswalk.debug"))) debug = true;
   try {
     String xsltName = properties.getProperty("XSLTCrosswalk.xsltName");
     if (xsltName != null) {
       StreamSource xslSource = new StreamSource(new FileInputStream(xsltName));
       TransformerFactory tFactory = TransformerFactory.newInstance();
       this.transformer = tFactory.newTransformer(xslSource);
       this.transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
       this.transformer.setOutputProperty(OutputKeys.STANDALONE, "no");
       this.transformer.setOutputProperty(OutputKeys.INDENT, "yes");
     }
   } catch (Exception e) {
     e.printStackTrace();
     throw new OAIInternalServerError(e.getMessage());
   }
 }
Beispiel #18
0
  /**
   * Sets the XSLT transformer from a Source
   *
   * @param source the source
   * @throws TransformerConfigurationException is thrown if creating a XSLT transformer failed.
   */
  public void setTransformerSource(Source source) throws TransformerConfigurationException {
    TransformerFactory factory = converter.getTransformerFactory();
    if (errorListener != null) {
      factory.setErrorListener(errorListener);
    } else {
      // use a logger error listener so users can see from the logs what the error may be
      factory.setErrorListener(new XsltErrorListener());
    }
    if (getUriResolver() != null) {
      factory.setURIResolver(getUriResolver());
    }

    // Check that the call to newTemplates() returns a valid template instance.
    // In case of an xslt parse error, it will return null and we should stop the
    // deployment and raise an exception as the route will not be setup properly.
    Templates templates = factory.newTemplates(source);
    if (templates != null) {
      setTemplate(templates);
    } else {
      throw new TransformerConfigurationException(
          "Error creating XSLT template. "
              + "This is most likely be caused by a XML parse error. "
              + "Please verify your XSLT file configured.");
    }
  }
Beispiel #19
0
  /**
   * convert an xml document to a string
   *
   * @param node document node
   * @return a string representation of the xml document
   */
  public static String xmlToString(Node node, String encoding) {

    String retXmlAsString = "";

    try {
      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.ENCODING, encoding);

      transformer.transform(source, result);
      retXmlAsString = stringWriter.toString();

      // for some reason encoding is not handling entity references - need
      // to look in to the further
      retXmlAsString = retXmlAsString.replace("&nbsp;", "&#160;");

    } catch (TransformerConfigurationException e) {
      e.printStackTrace();
    } catch (TransformerException e) {
      e.printStackTrace();
    }

    return retXmlAsString;
  }
 private void buildHierarchyDOM() {
   TransformerFactory factory = TransformerFactory.newInstance();
   StreamSource src =
       new StreamSource(
           this.getServletContext()
               .getResourceAsStream("/WEB-INF/classes/gpt/search/browse/ownerHierarchy.xml"));
   log.info("initializing src from stream " + src);
   try {
     Transformer t = factory.newTransformer();
     dom = new DOMResult();
     t.transform(src, dom);
     // now go thru tree, setting up the query attribute for each node
     Node tree = dom.getNode();
     NodeList children = tree.getChildNodes();
     log.info("dom tree contains " + children.getLength() + " nodes");
     for (int i = 0; i < children.getLength(); i++) {
       Node child = children.item(i);
       if (child.getNodeType() == Node.ELEMENT_NODE) {
         Element e = (Element) child;
         String query = computeQuery(e);
         e.setAttribute("query", query);
       }
     }
   } catch (Exception e) {
     log.severe("Could not init ownerHierarchy because exception thrown:");
     StringWriter sw = new StringWriter();
     e.printStackTrace(new PrintWriter(sw));
     log.severe(sw.toString());
   }
 }
Beispiel #21
0
  /**
   * Serialize this instance to a steam.
   *
   * <p>Default deserialization is pretty-printed but not schema-validated.
   *
   * @param out the stream for writing
   * @param validate whether to perform schema validation
   * @throws JAXBException if the steam can't be written to
   */
  public void marshal(final OutputStream out, final Boolean validate) throws JAXBException {
    try {
      // Create an empty DOM
      DOMResult intermediateResult = new DOMResult();

      // Marshal from JAXB to DOM
      Marshaller marshaller = /*BPMN_CONTEXT*/ newContext().createMarshaller();
      marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
      if (validate) {
        marshaller.setSchema(getBpmnSchema() /*BPMN_SCHEMA*/);
      }
      marshaller.marshal(new BpmnObjectFactory().createDefinitions(this), intermediateResult);

      // Apply the XSLT transformation, from DOM to the output stream
      TransformerFactory transformerFactory = TransformerFactory.newInstance();
      Transformer transformer =
          transformerFactory.newTransformer(
              new StreamSource(
                  new java.io.StringBufferInputStream(
                      fixNamespacesXslt[0] + getTargetNamespace() + fixNamespacesXslt[1])));
      DOMSource finalSource = new DOMSource(intermediateResult.getNode());
      StreamResult finalResult = new StreamResult(out);
      transformer.transform(finalSource, finalResult);
    } catch (TransformerException e) {
      throw new JAXBException("Dodgy wrapped exception", e);
    } // TODO - create transformer elsewhere
  }
Beispiel #22
0
  private void runXsltScript() {
    JFileChooser fc = new JFileChooser();
    fc.setDialogTitle("Select XSLT script");
    fc.setFileSelectionMode(JFileChooser.FILES_ONLY);
    int returnVal = fc.showOpenDialog(null);
    if (returnVal == 1) {
      return;
    }
    File fXSLT = fc.getSelectedFile();

    File fXML = new File("C:/Odin/Repository/");
    boolean isDirectory = fXML.isDirectory();
    /* Code adapted from: http://blog.msbbc.co.uk/2007/06/simple-saxon-java-example.html
     * [Accessed 3rd-Sept-2010]
     */
    for (File format : fXML.listFiles()) {
      boolean isSuccessful = false;
      try {
        System.setProperty(
            "javax.xml.transform.TransformerFactory", "net.sf.saxon.TransformerFactoryImpl");
        TransformerFactory tFact = TransformerFactory.newInstance();
        Transformer tf = tFact.newTransformer(new StreamSource(fXSLT));
        tf.transform(new StreamSource(format), new StreamResult(format));
        isSuccessful = true;
      } catch (TransformerException tX) {
        tX.printStackTrace();
      } finally {
        System.out.println(
            "Change of file " + format.getName() + " was successful? " + isSuccessful);
      }
    }
  }
  public void createDom()
      throws ParserConfigurationException, SAXException, IOException, TransformerException {
    String filePath = "maven_template.xml";
    DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
    DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
    Document doc = dBuilder.parse(filePath);

    Node projectUrl = doc.getElementsByTagName("projectUrl").item(0);
    projectUrl.setTextContent("https://github.com/YuesongWang/TestJenkins/");

    Node url = doc.getElementsByTagName("url").item(0);
    url.setTextContent("[email protected]:YuesongWang/TestJenkins.git");

    Node credentialsId = doc.getElementsByTagName("credentialsId").item(0);
    credentialsId.setTextContent("c56c7063-12a8-4a0f-b772-83b16732f6bf");

    Node targets = doc.getElementsByTagName("targets").item(0);
    targets.setTextContent("clean install");

    TransformerFactory transformerFactory = TransformerFactory.newInstance();
    Transformer transformer = transformerFactory.newTransformer();
    DOMSource source = new DOMSource(doc);
    StreamResult result = new StreamResult(new File("config.xml"));
    transformer.transform(source, result);
  }
Beispiel #24
0
  /**
   * @param output
   * @param document
   * @throws IOException
   * @throws TransformerException
   */
  private void saveAsHtml(String output, org.w3c.dom.Document document)
      throws IOException, TransformerException {

    //		check path
    File folder = new File(StringUtil.getFilePath(output));
    if (!folder.canRead()) folder.mkdirs();
    folder = null;

    FileWriter out = new FileWriter(output);
    DOMSource domSource = new DOMSource(document);
    StreamResult streamResult = new StreamResult(out);

    TransformerFactory tf = TransformerFactory.newInstance();
    Transformer serializer = tf.newTransformer();
    // TODO set encoding from a command argument
    serializer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
    serializer.setOutputProperty(OutputKeys.INDENT, "yes");
    serializer.setOutputProperty(OutputKeys.METHOD, "html");
    serializer.setOutputProperty(OutputKeys.STANDALONE, "yes");
    serializer.setOutputProperty(
        OutputKeys.DOCTYPE_PUBLIC, "-//W3C//DTD HTML 4.01 Transitional//EN"); //
    serializer.setOutputProperty(
        OutputKeys.DOCTYPE_SYSTEM, "http://www.w3.org/TR/html4/strict.dtd");

    serializer.transform(domSource, streamResult);
    out.close();
  }
Beispiel #25
0
 // write the content into xml file
 private void writeToXml(String fileName, Document doc) throws Exception {
   TransformerFactory transformerFactory = TransformerFactory.newInstance();
   Transformer transformer = transformerFactory.newTransformer();
   DOMSource source = new DOMSource(doc);
   StreamResult result = new StreamResult(new File(fileName));
   transformer.transform(source, result);
 }
  private void _writeDocument(Document doc, HttpServletResponse response) {
    try {
      doc.getDocumentElement().normalize();

      TransformerFactory transformerFactory = TransformerFactory.newInstance();

      Transformer transformer = transformerFactory.newTransformer();

      DOMSource source = new DOMSource(doc);

      if (_log.isDebugEnabled()) {
        StreamResult result = new StreamResult(System.out);

        transformer.transform(source, result);
      }

      response.setContentType("text/xml; charset=UTF-8");
      response.setHeader("Cache-Control", "no-cache");

      PrintWriter out = response.getWriter();

      StreamResult result = new StreamResult(out);

      transformer.transform(source, result);

      out.flush();
      out.close();
    } catch (Exception e) {
      throw new FCKException(e);
    }
  }
    @Override
    public Object makeObject() throws Exception {
      StreamSource source = XsltTransformer.this.getStreamSource();
      String factoryClassName = XsltTransformer.this.getXslTransformerFactory();
      TransformerFactory factory;

      if (PREFERRED_TRANSFORMER_FACTORY.equals(factoryClassName)
          && !ClassUtils.isClassOnPath(factoryClassName, getClass())) {
        logger.warn(
            "Preferred Transfomer Factory "
                + PREFERRED_TRANSFORMER_FACTORY
                + " not on classpath and no default is set, defaulting to JDK");
        factoryClassName = null;
      }

      if (StringUtils.isNotEmpty(factoryClassName)) {

        factory =
            (TransformerFactory)
                ClassUtils.instanciateClass(factoryClassName, ClassUtils.NO_ARGS, this.getClass());
      } else {
        // fall back to JDK default
        try {
          factory = TransformerFactory.newInstance();
        } catch (TransformerFactoryConfigurationError e) {
          System.setProperty(
              "javax.xml.transform.TransformerFactory", XMLUtils.TRANSFORMER_FACTORY_JDK5);
          factory = TransformerFactory.newInstance();
        }
      }

      factory.setURIResolver(getUriResolver());

      return factory.newTransformer(source);
    }
  @RequestMapping(value = "/validate", method = RequestMethod.POST)
  public void file(File file, BindingResult resultx, HttpServletRequest request, Model model) {

    // Instantiate CWRC XML validator
    CwrcXmlValidator validator = new CwrcXmlValidator();

    // Instantiate a Validator object
    // CwrcValidator validator = CwrcValidatorFactory.NewValidator("CwrcJavaXmlValidator");

    // Do the validation and obtain results.
    Document report =
        validator.ValidateDocContent(file.getSch(), file.getContent(), file.getType());

    // Exporting the validation-result DOM object into a string.
    String xml;
    try {
      TransformerFactory factory = TransformerFactory.newInstance();
      Transformer transformer = factory.newTransformer();

      StringWriter writer = new StringWriter();
      StreamResult result = new StreamResult(writer);
      Source source = new DOMSource(report.getDocumentElement());
      transformer.transform(source, result);
      writer.close();
      xml = writer.toString();
    } catch (Exception e) {
      xml =
          "<validation-result><status>fail</status><error><message>"
              + e.getMessage()
              + "</message></error></validation-result>";
    }

    // Export results for printing
    model.addAttribute("result", xml);
  }
Beispiel #29
0
  /** Gets an XSLT template from the given resource location. */
  public static Templates getStylesheet(String resourcePath, Class<?> sourceClass) {
    InputStream xsltStream;
    if (sourceClass == null) {
      try {
        xsltStream = new FileInputStream(resourcePath);
      } catch (IOException exc) {
        LOGGER.debug("Could not open file", exc);
        return null;
      }
    } else {
      xsltStream = sourceClass.getResourceAsStream(resourcePath);
    }

    try {
      StreamSource xsltSource = new StreamSource(xsltStream);
      // Java XML factories are not declared to be thread safe
      TransformerFactory transformerFactory = TransformerFactory.newInstance();
      transformerFactory.setErrorListener(new XMLListener());
      return transformerFactory.newTemplates(xsltSource);
    } catch (TransformerConfigurationException exc) {
      LOGGER.debug("Could not construct template", exc);
    } finally {
      try {
        if (xsltStream != null) xsltStream.close();
      } catch (IOException e) {
        LOGGER.debug("Could not close file", e);
      }
    }
    return null;
  }
Beispiel #30
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);
    }
  }