示例#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();
    }
  }
  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();
    }
  }
  /**
   * 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;
  }
  @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();
    }
  }
示例#5
0
    @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;
    }
  private static void serializeEntry(TransformerHandler hd, Entry entry) throws SAXException {

    AttributesImpl entryAttributes = new AttributesImpl();

    for (Iterator<String> it = entry.getAttributes().iterator(); it.hasNext(); ) {
      String key = it.next();

      entryAttributes.addAttribute("", "", key, "", entry.getAttributes().getValue(key));
    }

    hd.startElement("", "", ENTRY_ELEMENT, entryAttributes);

    StringList tokens = entry.getTokens();

    for (Iterator<String> it = tokens.iterator(); it.hasNext(); ) {

      hd.startElement("", "", TOKEN_ELEMENT, new AttributesImpl());

      String token = it.next();

      hd.characters(token.toCharArray(), 0, token.length());

      hd.endElement("", "", TOKEN_ELEMENT);
    }

    hd.endElement("", "", ENTRY_ELEMENT);
  }
示例#7
0
  /**
   * Creates a new generator.
   *
   * @param providers the list of page providers to use.
   * @param dest the destination directory.
   * @param url the public url corresponding to the the destination directory.
   * @throws IOException if the files could not be written.
   */
  public SitemapGenerator(final Collection<PageProvider> providers, final File dest, final URI url)
      throws IOException {

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

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

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

    final StreamResult streamResult = new StreamResult(writer);

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

      this.transformerHandler = tf.newTransformerHandler();

      final Transformer serializer = transformerHandler.getTransformer();

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

      transformerHandler.setResult(streamResult);
    } catch (TransformerConfigurationException e) {
      throw new RuntimeException(e);
    }
  }
示例#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);
      }
    }
  /** {@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;
    }
  }
 public void create(Properties ctx, TransformerHandler document) throws SAXException {
   int AD_Column_ID = Env.getContextAsInt(ctx, X_AD_Column.COLUMNNAME_AD_Column_ID);
   AttributesImpl atts = new AttributesImpl();
   X_AD_Column m_Column = new X_AD_Column(ctx, AD_Column_ID, getTrxName(ctx));
   createColumnBinding(atts, m_Column);
   document.startElement("", "", "column", atts);
   document.endElement("", "", "column");
 }
 public void create(Properties ctx, TransformerHandler document) throws SAXException {
   int AD_Ref_List_ID = Env.getContextAsInt(ctx, X_AD_Ref_List.COLUMNNAME_AD_Ref_List_ID);
   X_AD_Ref_List m_Ref_List = new X_AD_Ref_List(ctx, AD_Ref_List_ID, getTrxName(ctx));
   AttributesImpl atts = new AttributesImpl();
   createRefListBinding(atts, m_Ref_List);
   document.startElement("", "", "referencelist", atts);
   document.endElement("", "", "referencelist");
 }
 public void create(Properties ctx, TransformerHandler document) throws SAXException {
   int AD_Workflow_ID = Env.getContextAsInt(ctx, X_AD_Workflow.COLUMNNAME_AD_Workflow_ID);
   int AD_Role_ID = Env.getContextAsInt(ctx, X_AD_Role.COLUMNNAME_AD_Role_ID);
   AttributesImpl atts = new AttributesImpl();
   createWorkflowAccessBinding(atts, AD_Workflow_ID, AD_Role_ID);
   document.startElement("", "", "workflowaccess", atts);
   document.endElement("", "", "workflowaccess");
 }
示例#13
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());
   }
 }
 @Override
 public void create(Properties ctx, TransformerHandler document) throws SAXException {
   String SQLStatement = Env.getContext(ctx, X_AD_Package_Exp_Detail.COLUMNNAME_SQLStatement);
   String DBType = Env.getContext(ctx, X_AD_Package_Exp_Detail.COLUMNNAME_DBType);
   AttributesImpl atts = new AttributesImpl();
   createSQLStatmentBinding(atts, SQLStatement, DBType);
   document.startElement("", "", "SQLStatement", atts);
   document.endElement("", "", "SQLStatement");
 }
示例#15
0
 /**
  * Writes the root start tag to the result.
  *
  * @throws SAXException
  */
 protected void writeStartDocument() {
   try {
     AttributesImpl atts = new AttributesImpl();
     handler.startDocument();
     handler.startElement(Constants.MARCXML_NS_URI, COLLECTION, COLLECTION, atts);
   } catch (SAXException e) {
     throw new MarcException("SAX error occured while writing start document", e);
   }
 }
 // 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));
   }
 }
示例#17
0
      private void addElement(final String element, final String string) throws SAXException {
        final AttributesImpl noAttributes = new AttributesImpl();

        transformerHandler.startElement("", "", element, noAttributes);

        if (string != null) {
          transformerHandler.characters(string.toCharArray(), 0, string.length());
        }

        transformerHandler.endElement("", "", element);
      }
  public void create(Properties ctx, TransformerHandler document) throws SAXException {
    int AD_Form_ID = Env.getContextAsInt(ctx, "AD_Form_ID");
    if (forms.contains(AD_Form_ID)) return;

    forms.add(AD_Form_ID);
    X_AD_Form m_Form = new X_AD_Form(ctx, AD_Form_ID, null);
    AttributesImpl atts = new AttributesImpl();
    createFormBinding(atts, m_Form);
    document.startElement("", "", "form", atts);
    document.endElement("", "", "form");
  }
示例#19
0
  /**
   * Writes the root end tag to the result.
   *
   * @throws SAXException
   */
  protected void writeEndDocument() {
    try {
      if (indent) handler.ignorableWhitespace("\n".toCharArray(), 0, 1);

      handler.endElement(Constants.MARCXML_NS_URI, COLLECTION, COLLECTION);
      handler.endPrefixMapping("");
      handler.endDocument();
    } catch (SAXException e) {
      throw new MarcException("SAX error occured while writing end document", e);
    }
  }
示例#20
0
  void generateSuccessNode(int searchNodeId) {
    try {
      AttributesImpl atts = new AttributesImpl();
      atts.addAttribute("", "", "id", "CDATA", "" + searchNodeId);
      hdTree.startElement("", "", "succ", atts);
      hdTree.endElement("", "", "succ");

    } catch (SAXException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
  }
示例#21
0
 public void finish() throws IOException {
   if (!finished) {
     try {
       transformerHandler.endElement(NS, "", "urlset");
       transformerHandler.endDocument();
       this.writer.close();
       finished = true;
     } catch (SAXException e) {
       throw new RuntimeException(e);
     }
   }
 }
示例#22
0
 /**
  * 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;
 }
示例#23
0
  /**
   * Return a new {@link TransformerHandler} based on a given precompiled {@link Templates}. The
   * handler {@link Transformer}'s {@link ErrorListener} is set to {@link TransformerErrorListener}
   * to raise exceptions and give proper warnings.
   */
  public TransformerHandler newTransformerHandler(Templates template)
      throws TransformerConfigurationException {
    final TransformerHandler handler = this.tFactory.newTransformerHandler(template);

    /*
     * We want to raise transformer exceptions on <xml:message terminate="true">, so
     * we add a custom listener. Also, various XSLT processors react in different ways
     * to transformation errors -- some of them report error as recoverable, some of
     * them report error as unrecoverable.
     */
    handler.getTransformer().setErrorListener(new TransformerErrorListener());
    return handler;
  }
示例#24
0
  public void executedAtExit(Store store, int solutionsNo) {

    try {

      hdTree.endElement("", "", "tree");
      hdTree.endDocument();

      hdVis.endElement("", "", "visualization");
      hdVis.endDocument();

    } catch (SAXException e) {
      e.printStackTrace();
    }
  }
示例#25
0
  void generateTrycNode(int searchNodeId, int parentNode, PrimitiveConstraint c) {
    try {
      AttributesImpl atts = new AttributesImpl();
      atts.addAttribute("", "", "id", "CDATA", "" + searchNodeId);
      atts.addAttribute("", "", "parent", "CDATA", "" + parentNode);
      atts.addAttribute("", "", "choice", "CDATA", c.toString());
      hdTree.startElement("", "", "tryc", atts);
      hdTree.endElement("", "", "tryc");

    } catch (SAXException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
  }
示例#26
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);
    }
  }
示例#27
0
  /**
   * 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;
  }
    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;
      }
    }
示例#29
0
  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);
    }
  }
示例#30
0
  void generateFailNode(int searchNodeId, int parentNode, String name, int size, int value) {
    try {
      AttributesImpl atts = new AttributesImpl();
      atts.addAttribute("", "", "id", "CDATA", "" + searchNodeId);
      atts.addAttribute("", "", "parent", "CDATA", "" + parentNode);
      atts.addAttribute("", "", "name", "CDATA", name);
      atts.addAttribute("", "", "size", "CDATA", "" + size);
      atts.addAttribute("", "", "value", "CDATA", "" + value);
      hdTree.startElement("", "", "fail", atts);
      hdTree.endElement("", "", "fail");

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