コード例 #1
1
ファイル: PipeDocument.java プロジェクト: nuxleus/lcmc
  /**
   * 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();
    }
  }
コード例 #2
0
ファイル: XSLTransform.java プロジェクト: yaguza2/openedge
    @Override
    public ContentHandler getSAXHandler() throws IOException, ServletException {
      this.handlerUsed = true;

      // Set the content-type for the output
      assignContentType(this.getTransformCtx());

      TransformerHandler tHandler;
      try {
        SAXTransformerFactory saxTFact = (SAXTransformerFactory) TransformerFactory.newInstance();
        tHandler = saxTFact.newTransformerHandler(this.getCompiled());
      } catch (TransformerConfigurationException ex) {
        throw new ServletException(ex);
      }

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

      if (this.getNext().isLast())
        tHandler.setResult(new StreamResult(this.getNext().getResponse().getOutputStream()));
      else tHandler.setResult(new SAXResult(this.getNext().getSAXHandler()));

      return tHandler;
    }
コード例 #3
0
  public void write(HttpServletResponse response) {
    StreamResult streamResult;
    SAXTransformerFactory tf;
    TransformerHandler hd;
    Transformer serializer;

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

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

        hd.setResult(streamResult);
        hd.startDocument();
        AttributesImpl atts = new AttributesImpl();
        hd.startElement("", "", "ResmonResults", atts);
        for (ResmonResult r : s) {
          r.write(hd);
        }
        hd.endElement("", "", "ResmonResults");
        hd.endDocument();
      } catch (TransformerConfigurationException tce) {
        response.getWriter().println(tce.getMessage());
      } catch (SAXException se) {
        response.getWriter().println(se.getMessage());
      }
    } catch (IOException ioe) {
    }
  }
コード例 #4
0
  /**
   * Builds a Tika-compatible SAX content handler, which will be used to generate+capture the XHTML
   */
  private ContentHandler buildContentHandler(Writer output, RenderingContext context) {
    // Create the main transformer
    SAXTransformerFactory factory = (SAXTransformerFactory) SAXTransformerFactory.newInstance();
    TransformerHandler handler;

    try {
      handler = factory.newTransformerHandler();
    } catch (TransformerConfigurationException e) {
      throw new RenditionServiceException("SAX Processing isn't available - " + e);
    }

    handler.getTransformer().setOutputProperty(OutputKeys.INDENT, "yes");
    handler.setResult(new StreamResult(output));
    handler.getTransformer().setOutputProperty(OutputKeys.METHOD, "xml");

    // Change the image links as they go past
    String dirName = null, imgPrefix = null;
    if (context.getParamWithDefault(PARAM_IMAGES_SAME_FOLDER, false)) {
      imgPrefix = getImagesPrefixName(context);
    } else {
      dirName = getImagesDirectoryName(context);
    }
    ContentHandler contentHandler =
        new TikaImageRewritingContentHandler(handler, dirName, imgPrefix);

    // If required, wrap it to only return the body
    boolean bodyOnly = context.getParamWithDefault(PARAM_BODY_CONTENTS_ONLY, false);
    if (bodyOnly) {
      contentHandler = new BodyContentHandler(contentHandler);
    }

    // All done
    return contentHandler;
  }
コード例 #5
0
  /**
   * Creates a new generator.
   *
   * @param providers the list of page providers to use.
   * @param dest the destination directory.
   * @param url the public url corresponding to the the destination directory.
   * @throws IOException if the files could not be written.
   */
  public SitemapGenerator(final Collection<PageProvider> providers, final File dest, final URI url)
      throws IOException {

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

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

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

    final StreamResult streamResult = new StreamResult(writer);

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

      this.transformerHandler = tf.newTransformerHandler();

      final Transformer serializer = transformerHandler.getTransformer();

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

      transformerHandler.setResult(streamResult);
    } catch (TransformerConfigurationException e) {
      throw new RuntimeException(e);
    }
  }
コード例 #6
0
  @Override
  protected void marshalToOutputStream(
      Marshaller ms, Object obj, OutputStream os, Annotation[] anns, MediaType mt)
      throws Exception {

    Templates t = createTemplates(getOutTemplates(anns, mt), outParamsMap, outProperties);
    if (t == null && supportJaxbOnly) {
      super.marshalToOutputStream(ms, obj, os, anns, mt);
      return;
    }
    TransformerHandler th = null;
    try {
      th = factory.newTransformerHandler(t);
    } catch (TransformerConfigurationException ex) {
      TemplatesImpl ti = (TemplatesImpl) t;
      th = factory.newTransformerHandler(ti.getTemplates());
      this.trySettingProperties(th, ti);
    }
    Result result = new StreamResult(os);
    if (systemId != null) {
      result.setSystemId(systemId);
    }
    th.setResult(result);

    if (getContext() == null) {
      th.startDocument();
    }
    ms.marshal(obj, th);
    if (getContext() == null) {
      th.endDocument();
    }
  }
コード例 #7
0
      public SiteMapFile(int count) throws IOException, SAXException {
        this.fileName = name + '_' + count + ".xml";
        writer = new FileWriter(new File(location, fileName));
        final StreamResult streamResult = new StreamResult(writer);

        try {
          transformerHandler = tf.newTransformerHandler();

          Transformer serializer = transformerHandler.getTransformer();

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

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

          AttributesImpl schemaLocation = new AttributesImpl();

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

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

          transformerHandler.startElement(NS, "", "urlset", schemaLocation);
        } catch (TransformerConfigurationException e) {
          throw new RuntimeException(e);
        }
      }
コード例 #8
0
    @Override
    public void run(@NotNull ProgressIndicator indicator) {
      try {
        SAXTransformerFactory transformerFactory =
            (SAXTransformerFactory) TransformerFactory.newInstance();
        TransformerHandler handler = transformerFactory.newTransformerHandler();
        handler.getTransformer().setOutputProperty(OutputKeys.INDENT, "yes");
        handler
            .getTransformer()
            .setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4");

        final String configurationNameIncludedDate =
            PathUtil.suggestFileName(myConfiguration.getName())
                + " - "
                + new SimpleDateFormat(HISTORY_DATE_FORMAT).format(new Date());

        myOutputFile =
            new File(
                AbstractImportTestsAction.getTestHistoryRoot(myProject),
                configurationNameIncludedDate + ".xml");
        FileUtilRt.createParentDirs(myOutputFile);
        handler.setResult(new StreamResult(new FileWriter(myOutputFile)));
        final SMTestProxy.SMRootTestProxy root = myRoot;
        final RunConfiguration configuration = myConfiguration;
        if (root != null && configuration != null) {
          TestResultsXmlFormatter.execute(root, configuration, myConsoleProperties, handler);
        }
      } catch (ProcessCanceledException e) {
        throw e;
      } catch (Exception e) {
        LOG.info("Export to history failed", e);
      }
    }
コード例 #9
0
  public boolean run(Collection<SubversionSCM.External> externals, Result changeLog)
      throws IOException, InterruptedException {
    boolean changelogFileCreated = false;

    final SVNClientManager manager = SubversionSCM.createSvnClientManager();
    try {
      SVNLogClient svnlc = manager.getLogClient();
      TransformerHandler th = createTransformerHandler();
      th.setResult(changeLog);
      SVNXMLLogHandler logHandler = new SVNXMLLogHandler(th);
      // work around for http://svnkit.com/tracker/view.php?id=175
      th.setDocumentLocator(DUMMY_LOCATOR);
      logHandler.startDocument();

      for (ModuleLocation l : scm.getLocations(build)) {
        changelogFileCreated |= buildModule(l.getURL(), svnlc, logHandler);
      }
      for (SubversionSCM.External ext : externals) {
        changelogFileCreated |=
            buildModule(getUrlForPath(build.getWorkspace().child(ext.path)), svnlc, logHandler);
      }

      if (changelogFileCreated) {
        logHandler.endDocument();
      }

      return changelogFileCreated;
    } finally {
      manager.dispose();
    }
  }
コード例 #10
0
  /** {@inheritDoc} */
  @Override
  public void write(ProjectFile projectFile, OutputStream stream) throws IOException {
    try {
      if (CONTEXT == null) {
        throw CONTEXT_EXCEPTION;
      }

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

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

      Marshaller marshaller = CONTEXT.createMarshaller();

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

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

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

      DatatypeConverter.setParentFile(m_projectFile);

      marshaller.marshal(m_apibo, handler);
    } catch (JAXBException ex) {
      throw new IOException(ex.toString());
    } catch (TransformerConfigurationException ex) {
      throw new IOException(ex.toString());
    } finally {
      m_projectFile = null;
      m_factory = null;
      m_apibo = null;
      m_project = null;
      m_wbsSequence = 0;
      m_relationshipObjectID = 0;
      m_calendar = null;
    }
  }
コード例 #11
0
ファイル: Processor.java プロジェクト: vibe13/asm
 public final ContentHandler createContentHandler() {
   try {
     TransformerHandler handler = saxtf.newTransformerHandler(templates);
     handler.setResult(new SAXResult(outputHandler));
     return handler;
   } catch (TransformerConfigurationException ex) {
     throw new RuntimeException(ex.toString());
   }
 }
コード例 #12
0
 // TransformerHandler
 public void setResult(Result result) throws IllegalArgumentException {
   Check.notNull(result);
   if (result instanceof SAXResult) {
     setTarget((SAXResult) result);
   } else {
     TransformerHandler th = saxHelper.newIdentityTransformerHandler();
     th.setResult(result);
     setTarget(new SAXResult(th));
   }
 }
コード例 #13
0
  @Override
  public String serialize(List<Book> books) throws Exception {
    SAXTransformerFactory factory =
        (SAXTransformerFactory) TransformerFactory.newInstance(); // 取得SAXTransformerFactory实例
    TransformerHandler handler = factory.newTransformerHandler(); // 从factory获取TransformerHandler实例
    Transformer transformer = handler.getTransformer(); // 从handler获取Transformer实例
    transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8"); // 设置输出采用的编码方式
    transformer.setOutputProperty(OutputKeys.INDENT, "yes"); // 是否自动添加额外的空白
    transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "no"); // 是否忽略XML声明

    StringWriter writer = new StringWriter();
    Result result = new StreamResult(writer);
    handler.setResult(result);

    String uri = ""; // 代表命名空间的URI 当URI无值时 须置为空字符串
    String localName = ""; // 命名空间的本地名称(不包含前缀) 当没有进行命名空间处理时 须置为空字符串

    handler.startDocument();
    handler.startElement(uri, localName, "books", null);

    AttributesImpl attrs = new AttributesImpl(); // 负责存放元素的属性信息
    char[] ch = null;
    for (Book book : books) {
      attrs.clear(); // 清空属性列表
      attrs.addAttribute(
          uri,
          localName,
          "id",
          "string",
          String.valueOf(book.getId())); // 添加一个名为id的属性(type影响不大,这里设为string)
      handler.startElement(uri, localName, "book", attrs); // 开始一个book元素
      // 关联上面设定的id属性

      handler.startElement(uri, localName, "name", null); // 开始一个name元素
      // 没有属性
      ch = String.valueOf(book.getName()).toCharArray();
      handler.characters(ch, 0, ch.length); // 设置name元素的文本节点
      handler.endElement(uri, localName, "name");

      handler.startElement(uri, localName, "price", null); // 开始一个price元素
      // 没有属性
      ch = String.valueOf(book.getPrice()).toCharArray();
      handler.characters(ch, 0, ch.length); // 设置price元素的文本节点
      handler.endElement(uri, localName, "price");

      handler.endElement(uri, localName, "book");
    }
    handler.endElement(uri, localName, "books");
    handler.endDocument();

    return writer.toString();
  }
コード例 #14
0
  void prepareTreeHeader() {

    PrintWriter printWriter;

    try {
      printWriter = new PrintWriter(new FileOutputStream(treeFilename));
    } catch (FileNotFoundException e) {
      e.printStackTrace();
      printWriter = new PrintWriter(new StringWriter());
    }

    StreamResult streamResult = new StreamResult(printWriter);
    SAXTransformerFactory tf = (SAXTransformerFactory) SAXTransformerFactory.newInstance();

    try {

      hdTree = tf.newTransformerHandler();

      Transformer serializer = hdTree.getTransformer();
      serializer.setOutputProperty(OutputKeys.ENCODING, "UTF-8"); // "ISO-8859-1");
      serializer.setOutputProperty(OutputKeys.INDENT, "yes");
      serializer.setOutputProperty(OutputKeys.STANDALONE, "yes");
      serializer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4");

      hdTree.setResult(streamResult);

      hdTree.startDocument();

      AttributesImpl atts = new AttributesImpl();
      atts.addAttribute("", "", "version", "CDATA", "1.0");
      atts.addAttribute("", "", "xmln:xsi", "CDATA", "http://www.w3.org/2001/XMLSchema-instance");
      atts.addAttribute("", "", "xsi:noNamespaceSchemaLocation", "CDATA", "tree.xsd");

      String ourText = " Generated by JaCoP solver; " + getDateTime() + " ";
      char[] comm = ourText.toCharArray();
      hdTree.comment(comm, 0, comm.length);

      hdTree.startElement("", "", "tree", atts);

      atts = new AttributesImpl();
      atts.addAttribute("", "", "id", "CDATA", "0");
      hdTree.startElement("", "", "root", atts);
      hdTree.endElement("", "", "root");

    } catch (TransformerConfigurationException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    } catch (SAXException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
  }
コード例 #15
0
ファイル: TikaCLI.java プロジェクト: slavianp/webscrap
 /**
  * Returns a transformer handler that serializes incoming SAX events to XHTML or HTML (depending
  * the given method) using the given output encoding.
  *
  * @see <a href="https://issues.apache.org/jira/browse/TIKA-277">TIKA-277</a>
  * @param output output stream
  * @param method "xml" or "html"
  * @param encoding output encoding, or <code>null</code> for the platform default
  * @return {@link System#out} transformer handler
  * @throws TransformerConfigurationException if the transformer can not be created
  */
 private static TransformerHandler getTransformerHandler(
     OutputStream output, String method, String encoding, boolean prettyPrint)
     throws TransformerConfigurationException {
   SAXTransformerFactory factory = (SAXTransformerFactory) SAXTransformerFactory.newInstance();
   TransformerHandler handler = factory.newTransformerHandler();
   handler.getTransformer().setOutputProperty(OutputKeys.METHOD, method);
   handler.getTransformer().setOutputProperty(OutputKeys.INDENT, prettyPrint ? "yes" : "no");
   if (encoding != null) {
     handler.getTransformer().setOutputProperty(OutputKeys.ENCODING, encoding);
   }
   handler.setResult(new StreamResult(output));
   return handler;
 }
コード例 #16
0
 /* (non-Javadoc)
  * @see org.exist.collections.Trigger#prepare(java.lang.String, org.w3c.dom.Document)
  */
 public void prepare(
     int event,
     DBBroker broker,
     Txn transaction,
     XmldbURI documentName,
     DocumentImpl existingDocument)
     throws TriggerException {
   SAXResult result = new SAXResult();
   result.setHandler(getOutputHandler());
   result.setLexicalHandler(getLexicalOutputHandler());
   handler.setResult(result);
   setOutputHandler(handler);
   setLexicalOutputHandler(handler);
 }
コード例 #17
0
  protected void prepareHTMLView(InputStream older, InputStream newer) throws Exception {
    InputSource oldSource = new InputSource(older);
    InputSource newSource = new InputSource(newer);

    HtmlCleaner cleaner = new HtmlCleaner();
    Locale locale = Locale.getDefault();

    String prefix = "diff";

    DomTreeBuilder oldHandler;
    DomTreeBuilder newHandler;
    try {
      oldHandler = new DomTreeBuilder();
      cleaner.cleanAndParse(oldSource, oldHandler);
      newHandler = new DomTreeBuilder();
      cleaner.cleanAndParse(newSource, newHandler);
    } catch (Exception e) {
      throw new UsecaseException("Error while parsing document for diffing: ", e);
    }
    TextNodeComparator leftComparator = new TextNodeComparator(oldHandler, locale);
    TextNodeComparator rightComparator = new TextNodeComparator(newHandler, locale);

    SAXTransformerFactory tf = (SAXTransformerFactory) TransformerFactory.newInstance();
    TransformerHandler result = tf.newTransformerHandler();

    ByteArrayOutputStream out = new ByteArrayOutputStream();

    Result domResult = new StreamResult(out);
    result.setResult(domResult);

    ContentHandler htmlDiff = result;
    // Document content filtering
    // XslFilter filter = new XslFilter();
    // ContentHandler postProcess = filter.xsl(result, "htmldiff.xsl");
    try {
      startDiffDocument(htmlDiff);
      SimpleDiffOutput output = new SimpleDiffOutput(htmlDiff, prefix);
      BodyNode diffNode = HTMLDiffer.diff(leftComparator, rightComparator);
      output.toHTML(diffNode);
      finishDiffDocument(htmlDiff);
      setParameter(
          "html-output",
          DocumentBuilderFactory.newInstance()
              .newDocumentBuilder()
              .parse(new ByteArrayInputStream(out.toByteArray())));
    } catch (Exception e) {
      throw new UsecaseException("Failed translating diff document to xml: ", e);
    }
  }
コード例 #18
0
ファイル: BinaryParseData.java プロジェクト: bram1et/wbcrwlr
  /**
   * Returns a transformer handler that serializes incoming SAX events to XHTML or HTML (depending
   * the given method) using the given output encoding.
   *
   * @param encoding output encoding, or <code>null</code> for the platform default
   */
  private static TransformerHandler getTransformerHandler(
      OutputStream out, String method, String encoding) throws TransformerConfigurationException {

    TransformerHandler transformerHandler = SAX_TRANSFORMER_FACTORY.newTransformerHandler();
    Transformer transformer = transformerHandler.getTransformer();
    transformer.setOutputProperty(OutputKeys.METHOD, method);
    transformer.setOutputProperty(OutputKeys.INDENT, "yes");

    if (encoding != null) {
      transformer.setOutputProperty(OutputKeys.ENCODING, encoding);
    }

    transformerHandler.setResult(new StreamResult(new PrintStream(out)));
    return transformerHandler;
  }
コード例 #19
0
    public State(UnmarshallingContext context) throws SAXException {
      result = dom.createUnmarshaller(context);

      handler.setResult(result);

      // emulate the start of documents
      try {
        handler.setDocumentLocator(context.getLocator());
        handler.startDocument();
        declarePrefixes(context, context.getAllDeclaredPrefixes());
      } catch (SAXException e) {
        context.handleError(e);
        throw e;
      }
    }
コード例 #20
0
ファイル: MarcXmlWriter.java プロジェクト: roneldecius/marc4j
  protected void setHandler(Result result, Source stylesheet) throws MarcException {
    try {
      TransformerFactory factory = TransformerFactory.newInstance();
      if (!factory.getFeature(SAXTransformerFactory.FEATURE))
        throw new UnsupportedOperationException("SAXTransformerFactory is not supported");

      SAXTransformerFactory saxFactory = (SAXTransformerFactory) factory;
      if (stylesheet == null) handler = saxFactory.newTransformerHandler();
      else handler = saxFactory.newTransformerHandler(stylesheet);
      handler.getTransformer().setOutputProperty(OutputKeys.METHOD, "xml");
      handler.setResult(result);

    } catch (Exception e) {
      throw new MarcException(e.getMessage(), e);
    }
  }
コード例 #21
0
  /**
   * Creates a {@link ContentHandler} instance that serializes the received SAX events to the given
   * output stream.
   *
   * @param stream output stream to which the SAX events are serialized
   * @return SAX content handler
   * @throws RepositoryException if an error occurs
   */
  private ContentHandler getExportContentHandler(OutputStream stream) throws RepositoryException {
    try {
      SAXTransformerFactory stf = (SAXTransformerFactory) SAXTransformerFactory.newInstance();
      TransformerHandler handler = stf.newTransformerHandler();

      Transformer transformer = handler.getTransformer();
      transformer.setOutputProperty(OutputKeys.METHOD, "xml");
      transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
      transformer.setOutputProperty(OutputKeys.INDENT, "no");

      handler.setResult(new StreamResult(stream));
      return handler;
    } catch (TransformerFactoryConfigurationError e) {
      throw new RepositoryException("SAX transformer implementation not available", e);
    } catch (TransformerException e) {
      throw new RepositoryException("Error creating an XML export content handler", e);
    }
  }
コード例 #22
0
  /**
   * @param urlString The URL of the page to retrieve
   * @return A Node with a well formed XML doc coerced from the page.
   * @throws Exception if something goes wrong. No error handling at all for brevity.
   */
  public Node getHtmlUrlNode(String urlString) throws Exception {
    TransformerHandler th = stf.newTransformerHandler();

    // This dom result will contain the results of the transformation
    DOMResult dr = new DOMResult();
    th.setResult(dr);

    parser.setContentHandler(th);

    URL url = new URL(urlString);
    URLConnection urlConn = url.openConnection();
    InputStream stream = urlConn.getInputStream();

    // This is where the magic happens to convert HTML to XML
    parser.parse(new InputSource(stream));
    stream.close();

    return dr.getNode();
  }
コード例 #23
0
  /**
   * Serializes the given entries to the given {@link java.io.OutputStream}.
   *
   * <p>After the serialization is finished the provided {@link java.io.OutputStream} remains open.
   *
   * @param out stream to serialize to
   * @param entries entries to serialize
   * @param casesensitive indicates if the written dictionary should be case sensitive or case
   *     insensitive.
   * @throws java.io.IOException If an I/O error occurs
   */
  public static void serialize(OutputStream out, Iterator<Entry> entries, boolean casesensitive)
      throws IOException {
    StreamResult streamResult = new StreamResult(out);
    SAXTransformerFactory tf = (SAXTransformerFactory) SAXTransformerFactory.newInstance();

    TransformerHandler hd;
    try {
      hd = tf.newTransformerHandler();
    } catch (TransformerConfigurationException e) {
      throw new AssertionError("The Transformer configuration must be valid!");
    }

    Transformer serializer = hd.getTransformer();
    serializer.setOutputProperty(OutputKeys.ENCODING, CHARSET);
    serializer.setOutputProperty(OutputKeys.INDENT, "yes");

    hd.setResult(streamResult);

    try {
      hd.startDocument();

      AttributesImpl dictionaryAttributes = new AttributesImpl();

      dictionaryAttributes.addAttribute(
          "", "", ATTRIBUTE_CASE_SENSITIVE, "", String.valueOf(casesensitive));
      hd.startElement("", "", DICTIONARY_ELEMENT, dictionaryAttributes);

      while (entries.hasNext()) {
        Entry entry = entries.next();

        serializeEntry(hd, entry);
      }

      hd.endElement("", "", DICTIONARY_ELEMENT);

      hd.endDocument();
    } catch (SAXException e) {
      // TODO update after Java6 upgrade
      throw (IOException)
          new IOException("Error during serialization: " + e.getMessage()).initCause(e);
    }
  }
コード例 #24
0
  public void validate(Source source, Result result) throws SAXException, IOException {

    if (result == null || result instanceof StAXResult) {

      if (identityTransformer1 == null) {
        try {
          SAXTransformerFactory tf =
              fComponentManager.getFeature(Constants.ORACLE_FEATURE_SERVICE_MECHANISM)
                  ? (SAXTransformerFactory) SAXTransformerFactory.newInstance()
                  : (SAXTransformerFactory)
                      TransformerFactory.newInstance(
                          DEFAULT_TRANSFORMER_IMPL, StAXValidatorHelper.class.getClassLoader());
          identityTransformer1 = tf.newTransformer();
          identityTransformer2 = tf.newTransformerHandler();
        } catch (TransformerConfigurationException e) {
          // this is impossible, but again better safe than sorry
          throw new TransformerFactoryConfigurationError(e);
        }
      }

      handler = new ValidatorHandlerImpl(fComponentManager);
      if (result != null) {
        handler.setContentHandler(identityTransformer2);
        identityTransformer2.setResult(result);
      }

      try {
        identityTransformer1.transform(source, new SAXResult(handler));
      } catch (TransformerException e) {
        if (e.getException() instanceof SAXException) throw (SAXException) e.getException();
        throw new SAXException(e);
      } finally {
        handler.setContentHandler(null);
      }
      return;
    }
    throw new IllegalArgumentException(
        JAXPValidationMessageFormatter.formatMessage(
            Locale.getDefault(),
            "SourceResultMismatch",
            new Object[] {source.getClass().getName(), result.getClass().getName()}));
  }
コード例 #25
0
  @Override
  protected void setSAXConsumer(SAXConsumer consumer) {
    TransformerHandler handler = createTransformerHandler();

    if (consumer instanceof SaxonSerializer) {
      // serializer will finish setup of handler result
      SaxonSerializer serializer = (SaxonSerializer) consumer;
      serializer.setTransformerHandler(handler);
    } else {
      SAXResult result = new SAXResult();
      result.setHandler(consumer);
      // According to TrAX specification, all TransformerHandlers are LexicalHandlers
      result.setLexicalHandler(consumer);
      handler.setResult(result);
    }

    SAXConsumerAdapter saxConsumerAdapter = new SAXConsumerAdapter();
    saxConsumerAdapter.setContentHandler(handler);

    super.setSAXConsumer(saxConsumerAdapter);
  }
コード例 #26
0
  @Override
  public InputStream process(InputStream sourceStream) throws PreProcessorException {
    try {
      final TransformerHandler transformerHandler = handlerFactory.newTransformerHandler();
      final PipedInputStream resultStream = new PipedInputStream();
      final PipedOutputStream out = new PipedOutputStream(resultStream);
      transformerHandler.getTransformer().setOutputProperties(format);
      transformerHandler.setResult(new StreamResult(out));

      processingThread =
          DestroyableThreadWrapper.newThread(
              new JsonStreamProcessor(transformerHandler, sourceStream, out));
      processingThread.start();

      return resultStream;
    } catch (IOException ex) {
      throw new PreProcessorException(ex);
    } catch (TransformerConfigurationException ex) {
      throw new PreProcessorException(ex);
    }
  }
コード例 #27
0
  /** Parses the given InputSource after, applying the given XMLFilter. */
  private Document parseInputSourceWithFilter(InputSource s, XMLFilter f)
      throws SAXException, IOException {
    if (f != null) {
      // prepare an output Document
      Document o = db.newDocument();

      // use TrAX to adapt SAX events to a Document object
      th.setResult(new DOMResult(o));
      XMLReader xr = XMLReaderFactory.createXMLReader();
      xr.setEntityResolver(new JstlEntityResolver(pageContext));
      //   (note that we overwrite the filter's parent.  this seems
      //    to be expected usage.  we could cache and reset the old
      //    parent, but you can't setParent(null), so this wouldn't
      //    be perfect.)
      f.setParent(xr);
      f.setContentHandler(th);
      f.parse(s);
      return o;
    } else {
      return parseInputSource(s);
    }
  }
コード例 #28
0
 public void parse(Result out) throws ConfigException {
   try {
     String rootpath =
         AssemblingParser.class.getPackage().getName().replaceAll("\\.", "/") + "/" + root_file;
     InputStream root =
         Thread.currentThread().getContextClassLoader().getResourceAsStream(rootpath);
     SAXParser parser = factory.newSAXParser();
     XMLReader reader = parser.getXMLReader();
     TransformerHandler xform = transfactory.newTransformerHandler();
     xform.setResult(out);
     reader.setContentHandler(new AssemblingContentHandler(this, xform));
     reader.parse(new InputSource(root));
   } catch (IOException e) {
     throw new ConfigException("Exception raised during parsing", e);
   } catch (ParserConfigurationException e) {
     throw new ConfigException("Exception raised during parsing", e);
   } catch (SAXException e) {
     throw new ConfigException("Exception raised during parsing", e);
   } catch (TransformerConfigurationException e) {
     throw new ConfigException("Exception raised during parsing", e);
   }
 }
コード例 #29
0
  protected void prepareXMLView(InputStream older, InputStream newer) throws UsecaseException {
    SAXTransformerFactory tf = (SAXTransformerFactory) TransformerFactory.newInstance();

    TransformerHandler result;
    try {
      result = tf.newTransformerHandler();
    } catch (TransformerConfigurationException e) {
      throw new UsecaseException("Failed to create handler for diff", e);
    }
    ByteArrayOutputStream out = new ByteArrayOutputStream();

    Result domResult = new StreamResult(out);
    result.setResult(domResult);

    ContentHandler xmlDiff = result;

    // Document content filtering
    // XslFilter filter = new XslFilter();
    // ContentHandler postProcess = filter.xsl(result, "tagdiff.xsl");

    try {
      startDiffDocument(xmlDiff);
      DaisyDiff.diffTag(
          new BufferedReader(new InputStreamReader(older)),
          new BufferedReader(new InputStreamReader(newer)),
          xmlDiff);
      finishDiffDocument(xmlDiff);
    } catch (Exception e) {
      throw new UsecaseException("Failed to create diff report: ", e);
    }
    try {
      DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
      setParameter("xml-output", builder.parse(new ByteArrayInputStream(out.toByteArray())));
    } catch (Exception e) {
      throw new UsecaseException("Failed translating diff document to xml: ", e);
    }
  }
コード例 #30
0
  public void handle(
      String target, Request baseRequest, HttpServletRequest request, HttpServletResponse response)
      throws IOException, ServletException {
    response.setContentType("text/html;charset=utf-8");
    response.setStatus(HttpServletResponse.SC_OK);
    baseRequest.setHandled(true);

    boolean htmlOut = false;

    try {
      String oldString = request.getParameter("old");
      String newString = request.getParameter("new");

      if (oldString == null || newString == null) {
        return;
      }

      InputStream oldStream = new ByteArrayInputStream(oldString.getBytes());
      InputStream newStream = new ByteArrayInputStream(newString.getBytes());

      SAXTransformerFactory tf = (SAXTransformerFactory) TransformerFactory.newInstance();
      TransformerHandler result = tf.newTransformerHandler();
      result.setResult(new StreamResult(response.getOutputStream()));

      String[] css = new String[] {};
      XslFilter filter = new XslFilter();
      ContentHandler postProcess = htmlOut ? filter.xsl(result, "diff.xsl") : result;

      Locale locale = Locale.getDefault();
      String prefix = "diff";

      HtmlCleaner cleaner = new HtmlCleaner();
      DomTreeBuilder oldHandler = new DomTreeBuilder();

      InputSource oldSource = new InputSource(oldStream);
      oldSource.setEncoding("UTF-8");
      InputSource newSource = new InputSource(newStream);
      newSource.setEncoding("UTF-8");
      cleaner.cleanAndParse(oldSource, oldHandler);

      TextNodeComparator leftComparator = new TextNodeComparator(oldHandler, locale);

      DomTreeBuilder newHandler = new DomTreeBuilder();
      cleaner.cleanAndParse(newSource, newHandler);
      TextNodeComparator rightComparator = new TextNodeComparator(newHandler, locale);

      postProcess.startDocument();
      postProcess.startElement("", "div", "div", new AttributesImpl());
      doCSS(css, postProcess);
      postProcess.startElement("", "diff", "diff", new AttributesImpl());
      HtmlSaxDiffOutput output = new HtmlSaxDiffOutput(postProcess, prefix);

      HTMLDiffer differ = new HTMLDiffer(output);
      differ.diff(leftComparator, rightComparator);

      postProcess.endElement("", "diff", "diff");
      postProcess.endElement("", "div", "div");
      postProcess.endDocument();
    } catch (Throwable e) {
      e.printStackTrace();
      if (e.getCause() != null) {
        e.getCause().printStackTrace();
      }
      if (e instanceof SAXException) {
        ((SAXException) e).getException().printStackTrace();
      }
    }
  }