Exemplo n.º 1
0
 /**
  * Recursively resolves all components links.
  *
  * @param item the to resolve the links
  */
 @Override
 public void execute(Item item, RequestContext context) throws ProcessorException {
   if (item instanceof Page) {
     try {
       resolvePage((Page) item);
     } catch (TransformerException e) {
       LOG.error(e.getMessage(), e);
       throw new ProcessorException(e);
     }
   } else if (item instanceof ComponentPresentation) {
     try {
       resolveComponent(((ComponentPresentation) item).getComponent());
     } catch (TransformerException e) {
       LOG.error(e.getMessage(), e);
       throw new ProcessorException(e);
     }
   } else if (item instanceof Component) {
     try {
       resolveComponent((Component) item);
     } catch (TransformerException e) {
       LOG.error(e.getMessage(), e);
       throw new ProcessorException(e);
     }
   } else {
     LOG.debug(
         "RichTextResolverFilter. Item is not a GenericPage or GenericComponent so no component to resolve");
   }
   LOG.debug("RichTextResolverFilter finished");
 }
Exemplo n.º 2
0
  /**
   * Extracts the workflow from the plan.
   *
   * @param plan the plan to extract the workflow from.
   * @return The workflow File
   * @throws PluginException if an error occurs extracting the workflow from the plan.
   */
  private File getWorkflowFile(final Document plan) throws PluginException {

    final XPathFactory xPathfactory = XPathFactory.newInstance();
    final XPath xpath = xPathfactory.newXPath();

    Writer writer = null;
    try {

      xpath.setNamespaceContext(new PlanNamespaceContext());
      final XPathExpression expr = xpath.compile(xpathSelectWorkflow);
      final Element elementWorkflow = (Element) expr.evaluate(plan, XPathConstants.NODE);

      // Prepare the DOM document for writing
      final Source source = new DOMSource(elementWorkflow);
      final File workflowFile = new File(new File(RODA_HOME, "data"), WORKFLOW_FILENAME);
      writer = new OutputStreamWriter(new FileOutputStream(workflowFile));
      final Result result = new StreamResult(writer);

      // Write the DOM document to the file
      final Transformer xformer = TransformerFactory.newInstance().newTransformer();
      xformer.transform(source, result);

      writer.close();

      return workflowFile;

    } catch (XPathExpressionException e) {
      logger.error("Error compiling XPATH expression or evaluating the plan - " + e.getMessage());
      throw new PluginException(
          "Error compiling XPATH expression or evaluating the plan - " + e.getMessage(), e);
    } catch (FileNotFoundException e) {
      logger.error("Error opening output file for writting - " + e.getMessage());
      throw new PluginException("Error opening output file for writting - " + e.getMessage(), e);
    } catch (TransformerFactoryConfigurationError e) {
      logger.error("Error writing workflow file - " + e.getMessage());
      throw new PluginException("Error writing workflow file - " + e.getMessage(), e);
    } catch (TransformerException e) {
      logger.error("Error writing workflow file - " + e.getMessage());
      throw new PluginException("Error writing workflow file - " + e.getMessage(), e);
    } catch (IOException e) {
      logger.error("Error writing workflow file - " + e.getMessage());
      throw new PluginException("Error writing workflow file - " + e.getMessage(), e);
    } finally {

      if (writer != null) {
        try {
          writer.close();
        } catch (IOException e) {
          logger.error("Error closing output writer - " + e.getMessage());
        }
      }
    }
  }
Exemplo n.º 3
0
 SAXParseException transform(TransformerException exception) throws TransformerException {
   Throwable cause = exception.getException();
   // Xalan takes it upon itself to catch exceptions and pass them to the ErrorListener.
   if (cause instanceof RuntimeException) throw (RuntimeException) cause;
   if (cause instanceof SAXException
       || cause instanceof IncorrectSchemaException
       || cause instanceof IOException) throw exception;
   SourceLocator locator = exception.getLocator();
   if (locator == null) return new SAXParseException(exception.getMessage(), null);
   // Xalan sometimes loses the systemId; work around this.
   String s = locator.getSystemId();
   if (s == null) s = systemId;
   return new SAXParseException(exception.getMessage(), null, s, locator.getLineNumber(), -1);
 }
  /**
   * Implements javax.xml.transform.sax.TransformerHandler.setResult() Enables the user of the
   * TransformerHandler to set the to set the Result for the transformation.
   *
   * @param result A Result instance, should not be null
   * @throws IllegalArgumentException if result is invalid for some reason
   */
  public void setResult(Result result) throws IllegalArgumentException {
    _result = result;

    if (null == result) {
      ErrorMsg err = new ErrorMsg(ErrorMsg.ER_RESULT_NULL);
      throw new IllegalArgumentException(err.toString()); // "result should not be null");
    }

    if (_isIdentity) {
      try {
        // Connect this object with output system directly
        SerializationHandler outputHandler = _transformer.getOutputHandler(result);
        _transformer.transferOutputProperties(outputHandler);

        _handler = outputHandler;
        _lexHandler = outputHandler;
      } catch (TransformerException e) {
        _result = null;
      }
    } else if (_done) {
      // Run the transformation now, if not already done
      try {
        _transformer.setDOM(_dom);
        _transformer.transform(null, _result);
      } catch (TransformerException e) {
        // What the hell are we supposed to do with this???
        throw new IllegalArgumentException(e.getMessage());
      }
    }
  }
Exemplo n.º 5
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.º 6
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.º 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());
   }
 }
Exemplo n.º 8
0
  /**
   * Transform the input document
   *
   * @param xml The input xml
   * @return The rendered HTML
   * @throws IOException
   */
  public Document transform(Document document) throws IOException {

    String renderedHTML = "";

    javax.xml.transform.Transformer transformer;

    Document transformedDoc = null;

    try {

      transformer = m_template.newTransformer();
      assignParameters(transformer, m_params);
      DocumentSource fileSource = new DocumentSource(document);
      // Source fileSource = new StreamSource(xml);
      // Result result = new StreamResult(renderedHTML);
      DocumentResult result = new DocumentResult();

      transformer.transform(fileSource, result);

      transformedDoc = result.getDocument();

    } catch (TransformerConfigurationException e) {
      throw new IOException(e.getMessage());
    } catch (TransformerException e) {
      throw new IOException(e.getMessage());
    }

    return transformedDoc;
  }
Exemplo n.º 9
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());
    }
  }
  /**
   * Test whether a specified node is visible in the logical view of a TreeWalker or NodeIterator.
   * This function will be called by the implementation of TreeWalker and NodeIterator; it is not
   * intended to be called directly from user code.
   *
   * @param n The node to check to see if it passes the filter or not.
   * @return a constant to determine whether the node is accepted, rejected, or skipped, as defined
   *     above .
   */
  public short acceptNode(int n, XPathContext xctxt) {

    try {
      xctxt.pushCurrentNode(n);
      xctxt.pushIteratorRoot(m_context);
      if (DEBUG) {
        System.out.println("traverser: " + m_traverser);
        System.out.print("node: " + n);
        System.out.println(", " + m_cdtm.getNodeName(n));
        // if(m_cdtm.getNodeName(n).equals("near-east"))
        System.out.println("pattern: " + m_pattern.toString());
        m_pattern.debugWhatToShow(m_pattern.getWhatToShow());
      }

      XObject score = m_pattern.execute(xctxt);

      if (DEBUG) {
        // System.out.println("analysis: "+Integer.toBinaryString(m_analysis));
        System.out.println("score: " + score);
        System.out.println("skip: " + (score == NodeTest.SCORE_NONE));
      }

      // System.out.println("\n::acceptNode - score: "+score.num()+"::");
      return (score == NodeTest.SCORE_NONE) ? DTMIterator.FILTER_SKIP : DTMIterator.FILTER_ACCEPT;
    } catch (javax.xml.transform.TransformerException se) {

      // TODO: Fix this.
      throw new RuntimeException(se.getMessage());
    } finally {
      xctxt.popCurrentNode();
      xctxt.popIteratorRoot();
    }
  }
Exemplo n.º 11
0
 protected WXSSchema nouveauSchemaInclu(
     final URL urlSchemaParent,
     final String schemaLocation,
     final String espaceImport,
     final WXSSchema schemaParent)
     throws JaxeException {
   try {
     final URL urls = resoudreURI(getURLParent(urlSchemaParent), schemaLocation);
     if (urls == null)
       throw new JaxeException("include/import : location not found : " + schemaLocation);
     for (WXSSchema schemaInclu : schemasInclu)
       if (schemaInclu.getURL().toURI().normalize().equals(urls.toURI().normalize())) {
         ajouterEspaces(
             schemaInclu, schemaParent, espaceImport); // une chance de plus de trouver un pr?fixe
         return (schemaInclu);
       }
     final WXSSchema schemaInclu = new WXSSchema(lireDocument(urls), urls, this, schemaParent);
     ajouterEspaces(schemaInclu, schemaParent, espaceImport);
     schemasInclu.add(schemaInclu);
     schemaInclu.inclusions();
     return (schemaInclu);
   } catch (final MalformedURLException ex) {
     throw new JaxeException("include/import : MalformedURLException: " + ex.getMessage(), ex);
   } catch (final URISyntaxException ex) {
     throw new JaxeException("include/import : URISyntaxException: " + ex.getMessage(), ex);
   } catch (final TransformerException ex) {
     throw new JaxeException("include/import : TransformerException: " + ex.getMessage(), ex);
   }
 }
Exemplo n.º 12
0
  public static String format(String xmlStr) { // Instantiate transformer input
    Source xmlInput = new StreamSource(new StringReader(xmlStr));
    StreamResult xmlOutput = new StreamResult(new StringWriter());

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

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

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

    return xmlOutput.getWriter().toString();
  }
Exemplo n.º 13
0
  // taken from
  // http://www.exampledepot.com/egs/javax.xml.transform/BasicXsl.html
  // This method applies the xslFilename to inFilename and writes
  // the output to outFilename.
  public static void xsl(File inFile, File outFile, InputStream xslStream) throws Exception {
    try {
      // Create transformer factory
      TransformerFactory factory = TransformerFactory.newInstance();

      // Use the factory to create a template containing the xsl file
      Templates template = factory.newTemplates(new StreamSource(xslStream));

      // Use the template to create a transformer
      Transformer xformer = template.newTransformer();

      // Prepare the input and output files
      Source source = new StreamSource(new FileInputStream(inFile));
      Result result = new StreamResult(new FileOutputStream(outFile));

      // Apply the xsl file to the source file and write the result to the
      // output file
      xformer.transform(source, result);
    } catch (TransformerException e) {
      // An error occurred while applying the XSL file
      // Get location of error in input file
      SourceLocator locator = e.getLocator();
      int col = locator.getColumnNumber();
      int line = locator.getLineNumber();
      throw new Exception(
          String.format("XSL exception line %d col %d message: %s", line, col, e.getMessage()));
    }
  }
Exemplo n.º 14
0
 public void parse(String systemId) throws IOException, SAXException {
   try {
     TransformerFactory transformerFactory = TransformerFactory.newInstance();
     Transformer transformer = transformerFactory.newTransformer();
     Result result = new SAXResult(getContentHandler());
     transformer.transform(source, result);
   } catch (TransformerException e) {
     throw new SAXException(e.getMessage(), e);
   }
 }
Exemplo n.º 15
0
 public String getMailingListEmailsAsString(List<MLEmail> emails) {
   String out = "";
   try {
     Document doc = getMailingListEmailsAsXML(emails);
     out = DOMUtils.serialize(doc);
   } catch (TransformerException ex) {
     logger.error(ex.getMessage(), ex);
   }
   return out;
 }
Exemplo n.º 16
0
 public InputStream openStream() {
   try {
     ByteArrayOutputStream os = new ByteArrayOutputStream();
     TransformerFactory transformerFactory = TransformerFactory.newInstance();
     Transformer transformer = transformerFactory.newTransformer();
     Result result = new StreamResult(os);
     transformer.transform(source, result);
     return new ByteArrayInputStream(os.toByteArray());
   } catch (TransformerException e) {
     throw new ServingXmlException(e.getMessage(), e);
   }
 }
  /**
   * This method needs to override AxesWalker.acceptNode because FilterExprWalkers don't need to,
   * and shouldn't, do a node test.
   *
   * @param n The node to check to see if it passes the filter or not.
   * @return a constant to determine whether the node is accepted, rejected, or skipped, as defined
   *     above .
   */
  public short acceptNode(int n) {

    try {
      if (getPredicateCount() > 0) {
        countProximityPosition(0);

        if (!executePredicates(n, m_lpi.getXPathContext())) return DTMIterator.FILTER_SKIP;
      }

      return DTMIterator.FILTER_ACCEPT;
    } catch (javax.xml.transform.TransformerException se) {
      throw new RuntimeException(se.getMessage());
    }
  }
Exemplo n.º 18
0
  public static void saveDocumenteDisk(Document document, String pathXml) throws IOException {
    try {
      DOMSource source = new DOMSource(document);
      StreamResult result = new StreamResult(new File(pathXml));

      TransformerFactory transformerFactory = TransformerFactory.newInstance();

      Transformer transformer = transformerFactory.newTransformer();
      transformer.transform(source, result);
    } catch (TransformerConfigurationException e) {
      throw new IOException("Error: " + e.getMessage());
    } catch (TransformerException e) {
      throw new IOException("Error: " + e.getMessage());
    }
  }
 public String toString() {
   // Element docEl = getDocument().getDocumentElement();
   // return docEl.toString();
   Source input = new DOMSource(getDocument());
   StringWriter sw = new StringWriter();
   Result output = new StreamResult(sw);
   try {
     Transformer idTransformer = xformFactory.newTransformer();
     idTransformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
     idTransformer.transform(input, output);
     return sw.toString();
   } catch (TransformerException e) {
     return e.getMessage();
   }
 }
Exemplo n.º 20
0
        @Override
        public void handleMessage(InputMessage msg) throws PluginException {
          StreamSource xmlSource = new StreamSource(new ByteArrayInputStream(msg.body()));
          ByteArrayOutputStream output = new ByteArrayOutputStream();
          StreamResult result = new StreamResult(output);

          try {
            transformer.transform(xmlSource, result);
            XsltProcessor.this.publishToChannel("output", msg.withBody(output.toString()));
          } catch (TransformerException e) {
            String ms = "Unable to transform document";
            notifier.notify(NotificationType.BadData, ms + ": " + e.getMessage());
            throw new PluginException(ms + ".", e);
          }
        }
Exemplo n.º 21
0
  /**
   * Performs an xsl transformation against an XML document
   *
   * @param template The compiled XSL template to be run
   * @param xmlDoc xml document to be transformed
   * @param xslProperties default classification
   * @return the transformed document.
   * @throws TransformerException
   */
  public static Document transform(
      Templates template, Document xmlDoc, Map<String, Object> parameters)
      throws TransformerException {
    ByteArrayOutputStream baos;
    ByteArrayInputStream bais = null;
    Document resultDoc;
    try {
      Transformer transformer = template.newTransformer();

      DBF.setNamespaceAware(true);
      DocumentBuilder builder = DBF.newDocumentBuilder();
      StreamResult resultOutput = null;
      Source source = new DOMSource(xmlDoc);
      baos = new ByteArrayOutputStream();
      try {
        resultOutput = new StreamResult(baos);
        if (parameters != null && !parameters.isEmpty()) {
          for (Map.Entry<String, Object> entry : parameters.entrySet()) {
            LOGGER.debug("Adding parameter key: {} value: {}", entry.getKey(), entry.getValue());
            String key = entry.getKey();
            Object value = entry.getValue();
            if (key != null && !key.isEmpty() && value != null) {
              transformer.setParameter(key, value);
            } else {
              LOGGER.debug("Null or empty value for parameter: {}", entry.getKey());
            }
          }
        } else {
          LOGGER.warn("All properties were null.  Using \"last-resort\" defaults: U, USA, MTS");
        }

        transformer.transform(source, resultOutput);
        bais = new ByteArrayInputStream(baos.toByteArray());
        resultDoc = builder.parse(bais);
      } finally {
        IOUtils.closeQuietly(bais);
        IOUtils.closeQuietly(baos);
      }

      return resultDoc;
    } catch (TransformerException e) {
      LOGGER.warn(e.getMessage(), e);
      throw e;
    } catch (Exception e) {
      LOGGER.warn(e.getMessage(), e);
      throw new TransformerException("Error while transforming document: " + e.getMessage(), e);
    }
  }
Exemplo n.º 22
0
 /** Converts the given {@link Node} to a {@link String}. */
 public static String nodeToString(Node node) {
   StringWriter sw = new StringWriter();
   if (node instanceof Attr) {
     Attr attr = (Attr) node;
     return attr.getValue();
   }
   try {
     Transformer t = TransformerFactory.newInstance().newTransformer();
     t.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
     t.setOutputProperty(OutputKeys.INDENT, "yes");
     t.transform(new DOMSource(node), new StreamResult(sw));
   } catch (TransformerException te) {
     LOG.warning("Transformer Exception: " + te.getMessage());
   }
   return sw.toString();
 }
Exemplo n.º 23
0
  @Override
  public void render(Parameters blockParameters, Writer w, RenderHints hints)
      throws FrameworkException {

    if (decorate) {
      try {
        decorateIntro(hints, w, null);
      } catch (IOException ioe) {
        throw new FrameworkException(ioe);
      }
    }
    String name = getResource();
    ResourceLoader loader = ResourceLoader.Type.valueOf(resourceType.toUpperCase()).get();
    try {
      InputStream is = loader.getResourceAsStream(name);
      if (is == null)
        throw new FrameworkException(
            "No such resource " + loader.getResource(name) + " in " + loader);
      if (xsl == null) {
        Reader r = loader.getReader(is, name);
        char[] buf = new char[1000];
        int c;
        while ((c = r.read(buf, 0, 1000)) > 0) {
          w.write(buf, 0, c);
        }
      } else {
        /// convert using the xsl and spit out that.
        URL x = ResourceLoader.getConfigurationRoot().getResource(xsl);
        Utils.xslTransform(blockParameters, loader.getResource(name), is, w, x);
      }
    } catch (IOException ioe) {
      throw new FrameworkException(ioe);
    } catch (javax.xml.transform.TransformerException te) {
      throw new FrameworkException(te.getMessage(), te);
    } catch (RuntimeException e) {
      log.debug(e.getMessage(), e);
      throw e;
    } finally {
      if (decorate) {
        try {
          decorateOutro(hints, w);
        } catch (IOException ioe) {
          throw new FrameworkException(ioe);
        }
      }
    }
  }
Exemplo n.º 24
0
  private String formatXML(String str) {
    try {
      // Use a Transformer for output
      TransformerFactory tFactory = TransformerFactory.newInstance();
      // Surround this setting in a try/catch for compatibility with Java 1.4. This setting is
      // required
      // for Java 1.5
      try {
        tFactory.setAttribute("indent-number", 2);
      } catch (IllegalArgumentException e) {
        // Ignore
      }
      Transformer transformer = tFactory.newTransformer();
      transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
      transformer.setOutputProperty(OutputKeys.INDENT, "yes");
      transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");

      // Transform the requested string into a nice formatted XML string
      StreamSource source = new StreamSource(new StringReader(str));
      StringWriter sw = new StringWriter();
      StreamResult result = new StreamResult(sw);
      transformer.transform(source, result);
      return sw.toString();

    } catch (TransformerConfigurationException tce) {
      // Error generated by the parser
      System.out.println("\n** Transformer Factory error");
      System.out.println("   " + tce.getMessage());

      // Use the contained exception, if any
      Throwable x = tce;
      if (tce.getException() != null) x = tce.getException();
      x.printStackTrace();

    } catch (TransformerException te) {
      // Error generated by the parser
      System.out.println("\n** Transformation error");
      System.out.println("   " + te.getMessage());

      // Use the contained exception, if any
      Throwable x = te;
      if (te.getException() != null) x = te.getException();
      x.printStackTrace();
    }
    return str;
  }
 /**
  * Writes an XML file from a Document object.
  *
  * @param doc the Document object to be written to file
  * @param file the file to be written
  * @throws IOException
  * @author Klaus Meffert
  * @since 2.0
  */
 public static void writeFile(Document doc, File file) throws IOException {
   // Use a Transformer for output
   TransformerFactory tFactory = TransformerFactory.newInstance();
   Transformer transformer;
   try {
     transformer = tFactory.newTransformer();
   } catch (TransformerConfigurationException tex) {
     throw new IOException(tex.getMessage());
   }
   DOMSource source = new DOMSource(doc);
   FileOutputStream fos = new FileOutputStream(file);
   StreamResult result = new StreamResult(fos);
   try {
     transformer.transform(source, result);
     fos.close();
   } catch (TransformerException tex) {
     throw new IOException(tex.getMessage());
   }
 }
Exemplo n.º 26
0
 /**
  * @param dom the DOM document.
  * @return a string representation of the DOM.
  */
 public static String getDocumentToString(Document dom) {
   try {
     Source source = new DOMSource(dom);
     StringWriter stringWriter = new StringWriter();
     Result result = new StreamResult(stringWriter);
     TransformerFactory factory = TransformerFactory.newInstance();
     Transformer transformer = factory.newTransformer();
     transformer.setOutputProperty(OutputKeys.INDENT, "yes");
     transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
     transformer.setOutputProperty(OutputKeys.METHOD, "html");
     transformer.transform(source, result);
     return stringWriter.getBuffer().toString();
   } catch (TransformerConfigurationException e) {
     LOGGER.error(e.getMessage(), e);
   } catch (TransformerException e) {
     LOGGER.error(e.getMessage(), e);
   }
   return null;
 }
  /**
   * Process Item, correcting CC-License if encountered.
   *
   * @param item
   * @throws SQLException
   * @throws AuthorizeException
   * @throws IOException
   */
  protected static void handleItem(Item item) throws SQLException, AuthorizeException, IOException {
    Bundle[] bundles = item.getBundles("CC-LICENSE");

    if (bundles == null || bundles.length == 0) return;

    Bundle bundle = bundles[0];

    Bitstream bitstream = bundle.getBitstreamByName("license_rdf");

    String license_rdf = new String(copy(bitstream));

    /* quickly fix xml by ripping out offensive parts */
    license_rdf = license_rdf.replaceFirst("<license", "");
    license_rdf = license_rdf.replaceFirst("</license>", "");

    StringWriter result = new StringWriter();

    try {
      templates
          .newTransformer()
          .transform(
              new StreamSource(new ByteArrayInputStream(license_rdf.getBytes())),
              new StreamResult(result));
    } catch (TransformerException e) {
      throw new RuntimeException(e.getMessage(), e);
    }

    StringBuffer buffer = result.getBuffer();

    Bitstream newBitstream =
        bundle.createBitstream(new ByteArrayInputStream(buffer.toString().getBytes()));

    newBitstream.setName(bitstream.getName());
    newBitstream.setDescription(bitstream.getDescription());
    newBitstream.setFormat(bitstream.getFormat());
    newBitstream.setSource(bitstream.getSource());
    newBitstream.setUserFormatDescription(bitstream.getUserFormatDescription());
    newBitstream.update();

    bundle.removeBitstream(bitstream);

    bundle.update();
  }
Exemplo n.º 28
0
  /**
   * Writes out the document held in <code>node</code> to <code>outputWriter</code>
   *
   * @param node {@link Node} containing the OFX document structure. Usually the parent node
   * @param outputWriter {@link java.io.Writer} to use in writing the file to stream
   * @param omitXmlDeclaration Flag which causes the XML declaration to be omitted
   */
  private void write(Node node, Writer outputWriter, boolean omitXmlDeclaration) {
    try {
      TransformerFactory transformerFactory = TransformerFactory.newInstance();
      Transformer transformer = transformerFactory.newTransformer();
      DOMSource source = new DOMSource(node);
      StreamResult result = new StreamResult(outputWriter);

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

      transformer.transform(source, result);
    } catch (TransformerException tfException) {
      Log.e(LOG_TAG, tfException.getMessage());
      Crashlytics.logException(tfException);
    }
  }
  public Element subscribe(
      Element subscribeElement, AssertionType assertion, NhinTargetSystemType target)
      throws InvalidFilterFault, InvalidMessageContentExpressionFault,
          InvalidProducerPropertiesExpressionFault, InvalidTopicExpressionFault,
          NotifyMessageNotSupportedFault, ResourceUnknownFault, SubscribeCreationFailedFault,
          TopicExpressionDialectUnknownFault, TopicNotSupportedFault,
          UnacceptableInitialTerminationTimeFault, UnrecognizedPolicyRequestFault,
          UnsupportedPolicyRequestFault {
    Element resp = null;

    Dispatch<Source> sourceDispatch = getNotificationProducerDispath(target, assertion);

    try {
      if (sourceDispatch != null) {
        Document subscribeRequestDocument = buildSubscribeRequestMessage(subscribeElement);

        Source input = new DOMSource(subscribeRequestDocument);
        Source result = sourceDispatch.invoke(input);
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        javax.xml.transform.Result streamResult = new javax.xml.transform.stream.StreamResult(bos);

        Transformer xformer = TransformerFactory.newInstance().newTransformer();
        xformer.transform(result, streamResult);

        String resultXml = new String(bos.toByteArray());
        resp = parseSubscribeResponse(resultXml);
      } else {
        log.error("The source dispatch object was null");
      }
    } catch (ParserConfigurationException ex) {
      log.error("ParserConfigurationException sending subscribe message: " + ex.getMessage(), ex);
      // TODO: Create and throw generic exception
    } catch (TransformerConfigurationException ex) {
      log.error(
          "TransformerConfigurationException sending subscribe message: " + ex.getMessage(), ex);
      // TODO: Create and throw generic exception
    } catch (TransformerException ex) {
      log.error("TransformerException sending subscribe message: " + ex.getMessage(), ex);
      // TODO: Create and throw generic exception
    }
    return resp;
  }
Exemplo n.º 30
0
  /**
   * Runs an XSLT file on the given JDOM document.
   *
   * @param xsltFileName The name of the file that contains the XSLT definition.
   * @param doc The JDOM document the XSL transformation should be applied to. The first index
   *     refers to the i-th parameter, the index will be 0 for the parameter name and 1 for the
   *     parameter value. See {@link Transformer#setParameter(String, Object)}
   * @param xsltParams Parameters that should be applied to the transformation.
   * @return The output file with the result of the transformation.
   */
  public static OutputFile runXSLT(String xsltFileName, Document doc, String[][] xsltParams) {
    StringWriter writer = new StringWriter();
    try {
      Transformer transformer = getTransformer(xsltFileName);
      transformer.reset();
      if (xsltParams != null) {
        for (int i = 0; i < xsltParams.length; i++)
          transformer.setParameter(xsltParams[i][0], xsltParams[i][1]);
      }
      DocumentWrapper docw =
          new DocumentWrapper(doc, "", ((Controller) transformer).getConfiguration());
      Result result = new StreamResult(writer);
      transformer.transform(docw, result);

      return new OutputFile(writer.toString());
    } catch (TransformerException e) {
      Log.error(TAG, e.getMessage());
    }
    return null;
  }