Exemplo n.º 1
1
  /**
   * Uses a Vector of TransformerHandlers to pipe XML input document through a series of 1 or more
   * transformations. Called by {@link #pipeDocument}.
   *
   * @param vTHandler Vector of Transformation Handlers (1 per stylesheet).
   * @param source absolute URI to XML input
   * @param target absolute path to transformation output.
   */
  public void usePipe(Vector vTHandler, String source, String target)
      throws TransformerException, TransformerConfigurationException, FileNotFoundException,
          IOException, SAXException, SAXNotRecognizedException {
    XMLReader reader = XMLReaderFactory.createXMLReader();
    TransformerHandler tHFirst = (TransformerHandler) vTHandler.firstElement();
    reader.setContentHandler(tHFirst);
    reader.setProperty("http://xml.org/sax/properties/lexical-handler", tHFirst);
    for (int i = 1; i < vTHandler.size(); i++) {
      TransformerHandler tHFrom = (TransformerHandler) vTHandler.elementAt(i - 1);
      TransformerHandler tHTo = (TransformerHandler) vTHandler.elementAt(i);
      tHFrom.setResult(new SAXResult(tHTo));
    }
    TransformerHandler tHLast = (TransformerHandler) vTHandler.lastElement();
    Transformer trans = tHLast.getTransformer();
    Properties outputProps = trans.getOutputProperties();
    Serializer serializer = SerializerFactory.getSerializer(outputProps);

    FileOutputStream out = new FileOutputStream(target);
    try {
      serializer.setOutputStream(out);
      tHLast.setResult(new SAXResult(serializer.asContentHandler()));
      reader.parse(source);
    } finally {
      // Always clean up the FileOutputStream,
      // even if an exception was thrown in the try block
      if (out != null) out.close();
    }
  }
Exemplo n.º 2
0
  /**
   * Transform the passed XML string with the stated stylesheet.
   *
   * <p>Enables passing any amount of <code>parameters</code> into the stylesheet using a <code>
   * Hashtable</code> to store them as name:value pairs where the key is the name of the parameter
   * and the value is the value.<br>
   * The parameter can be matched in the XSL as follows:<br>
   * &lt;xsl:value-of select=&quot;$parameter_name&quot;&gt;.
   *
   * @return String The transformed XML
   * @param xmlString String XML input string
   * @param xslFileName String XSL stylesheet filename
   * @param parameters the list of parameters to pass to the XSL stylesheet.
   * @exception TransformerException Any exception thrown during the transform process
   */
  public static String transform(String xmlString, String xslFileName, HashMap parameters)
      throws TransformerException {
    try {
      StringWriter stringWriter = new StringWriter();
      Source xmlSource = new StreamSource(new StringReader(xmlString));
      Templates template = (Templates) xslcache.getTemplate(xslFileName);
      Transformer trans = template.newTransformer();

      if (parameters != null) {
        Set keys = parameters.keySet();
        Iterator it = keys.iterator();
        while (it.hasNext()) {
          String name = (String) it.next();
          String value = (String) parameters.get(name);
          trans.setParameter(name, value);
        }
      }
      trans.transform(xmlSource, new StreamResult(stringWriter));
      return stringWriter.toString();

    } catch (TransformerConfigurationException e) {
      throw new TransformerException(
          "Transformer could not be created: " + e.getClass().getName() + " - " + e.getMessage());
    } catch (TransformerException e) {
      throw new TransformerException(
          "Error during transformation: " + e.getClass().getName() + " - " + e.getMessage());
    } catch (Exception e) {
      throw new TransformerException(
          "Unknown error during transformation: "
              + e.getClass().getName()
              + " - "
              + e.getMessage());
    }
  }
Exemplo n.º 3
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.º 4
0
  protected void doTransform(
      MuleMessage message, String outputEncoding, Source sourceDoc, Result result)
      throws Exception {
    DefaultErrorListener errorListener = new DefaultErrorListener(this);
    javax.xml.transform.Transformer transformer = null;

    try {
      transformer = (javax.xml.transform.Transformer) transformerPool.borrowObject();

      transformer.setErrorListener(errorListener);
      transformer.setOutputProperty(OutputKeys.ENCODING, outputEncoding);

      // set transformation parameters
      if (contextProperties != null) {
        for (Entry<String, Object> parameter : contextProperties.entrySet()) {
          String key = parameter.getKey();
          transformer.setParameter(
              key, evaluateTransformParameter(key, parameter.getValue(), message));
        }
      }

      transformer.transform(sourceDoc, result);

      if (errorListener.isError()) {
        throw errorListener.getException();
      }
    } finally {
      if (transformer != null) {
        transformerPool.returnObject(transformer);
      }
    }
  }
Exemplo n.º 5
0
  /** Save the modifications */
  public static void writeDocument(String filename, Node written) {
    Transformer transformer = null;
    try {
      transformer = ScilabTransformerFactory.newInstance().newTransformer();
    } catch (TransformerConfigurationException e1) {
      System.err.println(ERROR_WRITE + filename);
      return;
    } catch (TransformerFactoryConfigurationError e1) {
      System.err.println(ERROR_WRITE + filename);
      return;
    }
    transformer.setOutputProperty(OutputKeys.INDENT, "yes");

    StreamResult result = new StreamResult(new File(filename));
    DOMSource source = new DOMSource(written);
    try {
      transformer.transform(source, result);
    } catch (TransformerException e) {
      System.err.println(ERROR_WRITE + filename);
      return;
    }

    // Invalidate the current document
    if (filename.equals(USER_CONFIG_FILE)) {
      doc = null;
    }
  }
Exemplo n.º 6
0
 public String transform(String type, String input, Map<String, String> transformModel)
     throws TransformException {
   if (log.isDebugEnabled()) {
     log.debug("transform(input=" + input + ")");
   }
   try {
     Templates template = templates.get(type);
     if (log.isDebugEnabled()) {
       log.debug("template=" + template);
     }
     if (template != null) {
       Transformer transformer = template.newTransformer();
       StringWriter writer = new StringWriter(INITIAL_BUFFER_SIZE);
       transformer.setErrorListener(new DefaultErrorListener());
       if (transformModel != null) {
         for (Map.Entry<String, String> entry : transformModel.entrySet()) {
           transformer.setParameter(entry.getKey(), entry.getValue());
         }
       }
       transformer.transform(new StreamSource(new StringReader(input)), new StreamResult(writer));
       String result = writer.toString().trim();
       if (log.isDebugEnabled()) {
         log.debug("result=" + result);
       }
       return result;
     } else {
       String errMsg = "Transformation '" + type + "' not available";
       log.error(errMsg);
       throw new RuntimeException(errMsg);
     }
   } catch (Exception e) {
     log.error("Error during transform", e);
     throw new TransformException(e);
   }
 }
Exemplo n.º 7
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);
 }
Exemplo n.º 8
0
  public void storeMappings(WorkspaceLanguageConfiguration config) throws CoreException {
    try {
      // Encode mappings as XML and serialize as a String.
      Document doc = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument();
      Element rootElement = doc.createElement(WORKSPACE_MAPPINGS);
      doc.appendChild(rootElement);
      addContentTypeMappings(config.getWorkspaceMappings(), rootElement);
      Transformer serializer = createSerializer();
      DOMSource source = new DOMSource(doc);
      StringWriter buffer = new StringWriter();
      StreamResult result = new StreamResult(buffer);
      serializer.transform(source, result);
      String encodedMappings = buffer.getBuffer().toString();

      IEclipsePreferences node = InstanceScope.INSTANCE.getNode(CCorePlugin.PLUGIN_ID);
      node.put(CCorePreferenceConstants.WORKSPACE_LANGUAGE_MAPPINGS, encodedMappings);
      node.flush();
    } catch (ParserConfigurationException e) {
      throw new CoreException(Util.createStatus(e));
    } catch (TransformerException e) {
      throw new CoreException(Util.createStatus(e));
    } catch (BackingStoreException e) {
      throw new CoreException(Util.createStatus(e));
    }
  }
Exemplo n.º 9
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
  }
Exemplo n.º 10
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());
   }
 }
Exemplo n.º 11
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;
  }
Exemplo n.º 12
0
 /**
  * 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);
 }
Exemplo n.º 13
0
  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);
  }
Exemplo n.º 14
0
  @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);
  }
Exemplo n.º 15
0
  private void eatMemory(int callIndex, File foFile, int replicatorRepeats) throws Exception {
    Source src = new StreamSource(foFile);

    Transformer transformer = replicatorTemplates.newTransformer();
    transformer.setParameter("repeats", new Integer(replicatorRepeats));

    OutputStream out = new NullOutputStream(); // write to /dev/nul
    try {
      FOUserAgent userAgent = fopFactory.newFOUserAgent();
      userAgent.setBaseURL(foFile.getParentFile().toURL().toExternalForm());
      Fop fop = fopFactory.newFop(MimeConstants.MIME_PDF, userAgent, out);
      Result res = new SAXResult(fop.getDefaultHandler());

      transformer.transform(src, res);

      stats.notifyPagesProduced(fop.getResults().getPageCount());
      if (callIndex == 0) {
        System.out.println(
            foFile.getName() + " generates " + fop.getResults().getPageCount() + " pages.");
      }
      stats.checkStats();
    } finally {
      IOUtils.closeQuietly(out);
    }
  }
Exemplo n.º 16
0
  // 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();
  }
Exemplo n.º 17
0
    @Override
    public void go(Source input) throws IOException, ServletException {
      // Set the content-type for the output
      assignContentType(this.getTransformCtx());

      Transformer trans;
      try {
        trans = this.getCompiled().newTransformer();
      } catch (TransformerConfigurationException ex) {
        throw new ServletException(ex);
      }

      // Populate any params which might have been set
      if (this.getTransformCtx().getTransformParams() != null)
        populateParams(trans, this.getTransformCtx().getTransformParams());

      Result res;
      if (this.getNext().isLast())
        res = new StreamResult(this.getNext().getResponse().getOutputStream());
      else res = new SAXResult(this.getNext().getSAXHandler());

      try {
        trans.transform(input, res);
      } catch (TransformerException ex) {
        throw new ServletException(ex);
      }

      this.getNext().done();
    }
Exemplo n.º 18
0
  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);
  }
  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!");
    }
  }
Exemplo n.º 20
0
  /**
   * 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);
    }
  }
Exemplo n.º 21
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.º 22
0
  /**
   * 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);
    }
  }
  @Override
  public boolean handleMessage(LogicalMessageContext logicalMessageContext) {
    try {
      boolean outboundMessage =
          (boolean) logicalMessageContext.get(MessageContext.MESSAGE_OUTBOUND_PROPERTY);

      if (!outboundMessage) {
        return true;
      }

      LogicalMessage logicalMessage = logicalMessageContext.getMessage();

      Transformer transformer =
          _transformerFactory.newTransformer(new StreamSource(_url.openStream()));

      DOMResult domResult = new DOMResult();

      transformer.transform(logicalMessage.getPayload(), domResult);

      logicalMessage.setPayload(new DOMSource(domResult.getNode()));

      return true;
    } catch (Exception e) {
      throw new RuntimeException(e);
    }
  }
Exemplo n.º 24
0
  /**
   * 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);
    }
  }
Exemplo n.º 25
0
  /** Save the modifications */
  public static String dumpNode(Node written) {
    Transformer transformer = null;
    try {
      transformer = ScilabTransformerFactory.newInstance().newTransformer();
    } catch (TransformerConfigurationException e1) {
      System.err.println("Cannot dump xml");
      return "";
    } catch (TransformerFactoryConfigurationError e1) {
      System.err.println("Cannot dump xml");
      return "";
    }
    transformer.setOutputProperty(OutputKeys.INDENT, "yes");

    ByteArrayOutputStream stream = new ByteArrayOutputStream();
    StreamResult result = new StreamResult(new BufferedOutputStream(stream));
    DOMSource source = new DOMSource(written);
    String str = "";
    try {
      transformer.transform(source, result);
      str = stream.toString();
    } catch (TransformerException e) {
      System.err.println("Cannot dump xml");
      return str;
    } finally {
      try {
        stream.close();
      } catch (Exception e) {
      }
    }

    return str;
  }
  /**
   * @param monitor
   * @throws Exception
   */
  private void addServletToGwtXml(IProgressMonitor monitor) throws Exception {

    monitor = Util.getNonNullMonitor(monitor);

    try {

      monitor.beginTask("", 1);

      DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();

      DocumentBuilder builder = factory.newDocumentBuilder();

      File moduleFile = getModuleFile();

      Document document = builder.parse(moduleFile);
      Node module = document.getDocumentElement();

      Element newServlet = document.createElement("servlet");
      newServlet.setAttribute("path", "/" + serviceUri); // $NON-NLS-2$
      newServlet.setAttribute(
          "class",
          getPackageFragment().getElementName() + '.' + getTypeName() + "Impl"); // $NON-NLS-2$

      module.appendChild(newServlet);

      Transformer writer = TransformerFactory.newInstance().newTransformer();

      writer.transform(new DOMSource(document), new StreamResult(moduleFile));

    } finally {
      monitor.done();
    }
  }
 private String transformXml(final Document document) throws TransformerException {
   final Transformer transformer = XmlUtils.createIndentingTransformer();
   final DOMSource source = new DOMSource(document);
   final StreamResult result = new StreamResult(new StringWriter());
   transformer.transform(source, result);
   return result.getWriter().toString();
 }
Exemplo n.º 28
0
  /**
   * Pomocnicza klasa wysyłająca dokument XML do writera
   *
   * @param doc dokument, który chcemy wysłać
   * @param out Writer, do którego chcemy pisać
   */
  private void XML2Writer(Document doc, PrintWriter out) {
    Transformer transformer = null;

    try {

      transformer = TransformerFactory.newInstance().newTransformer();

    } catch (TransformerFactoryConfigurationError e) {

      e.printStackTrace();
    } catch (TransformerConfigurationException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }

    StreamResult result = new StreamResult(out);
    DOMSource source = new DOMSource(doc);

    try {
      if (transformer != null) {
        transformer.transform(source, result);
      }
    } catch (TransformerException e) {

      e.printStackTrace();
    }
  }
 protected Document wbxmlStream2Doc(InputStream in, boolean event) throws Exception {
   XMLStreamReader xmlStreamReader = null;
   XMLEventReader xmlEventReader = null;
   try {
     if (event) {
       xmlEventReader = inFact.createXMLEventReader(in);
     } else {
       xmlStreamReader = inFact.createXMLStreamReader(in);
     }
     Transformer xformer = TransformerFactory.newInstance().newTransformer();
     StAXSource staxSource =
         event ? new StAXSource(xmlEventReader) : new StAXSource(xmlStreamReader);
     DOMResult domResult = new DOMResult();
     xformer.transform(staxSource, domResult);
     Document doc = (Document) domResult.getNode();
     doc.normalize();
     return doc;
   } finally {
     if (xmlStreamReader != null) {
       try {
         xmlStreamReader.close();
       } catch (Exception e) {
       }
     }
     if (xmlEventReader != null) {
       try {
         xmlEventReader.close();
       } catch (Exception e) {
       }
     }
   }
 }
Exemplo n.º 30
0
  // TODO Carregar campos a partir do XML de um .ktr
  @SuppressWarnings("unchecked")
  @Override
  public void loadXML(
      Node stepDomNode, List<DatabaseMeta> databases, Map<String, Counter> sequenceCounters)
      throws KettleXMLException {

    try {
      XStream xs = new XStream(new DomDriver());

      StringWriter sw = new StringWriter();
      Transformer t = TransformerFactory.newInstance().newTransformer();
      // IPC: se algum colocar um caracter, seja qual for, no getXML() o
      // getFirstChild() para de funcionar aqui!
      t.transform(
          new DOMSource(
              XMLHandler.getSubNode(stepDomNode, Field.DATA_ROOT_NODE.name()).getFirstChild()),
          new StreamResult(sw));

      Map<String, Object> data = (Map<String, Object>) xs.fromXML(sw.toString());

      endpointUri = (String) data.get(Field.ENDPOINT_URI.name());
      defaultGraph = (String) data.get(Field.DEFAULT_GRAPH.name());
      queryString = (String) data.get(Field.QUERY_STRING.name());
      prefixes = (List<List<String>>) data.get(Field.PREFIXES.name());

      varResult = (String) data.get(Field.VAR_RESULT.name());

    } catch (Throwable e) {
      e.printStackTrace();
    }
  }