org.apache.xml.serializer.SerializationHandler Java Examples

The following examples show how to use org.apache.xml.serializer.SerializationHandler. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: ElemTextLiteral.java    From j2objc with Apache License 2.0 6 votes vote down vote up
/**
 * Copy the text literal to the result tree.
 *
 * @param transformer non-null reference to the the current transform-time state.
 *
 * @throws TransformerException
 */
public void execute(
        TransformerImpl transformer)
          throws TransformerException
{
  try
  {
    SerializationHandler rth = transformer.getResultTreeHandler();

      if (m_disableOutputEscaping)
    {
      rth.processingInstruction(javax.xml.transform.Result.PI_DISABLE_OUTPUT_ESCAPING, "");
    }

    rth.characters(m_ch, 0, m_ch.length);

    if (m_disableOutputEscaping)
    {
      rth.processingInstruction(javax.xml.transform.Result.PI_ENABLE_OUTPUT_ESCAPING, "");
    }
  }
  catch(SAXException se)
  {
    throw new TransformerException(se);
  }
}
 
Example #2
Source File: SerializerUtils.java    From j2objc with Apache License 2.0 6 votes vote down vote up
/**
 * Copy DOM attributes to the result element.
 *
 * @param src Source node with the attributes
 *
 * @throws TransformerException
 */
public static void addAttributes(SerializationHandler handler, int src)
    throws TransformerException
{

    TransformerImpl transformer =
        (TransformerImpl) handler.getTransformer();
    DTM dtm = transformer.getXPathContext().getDTM(src);

    for (int node = dtm.getFirstAttribute(src);
        DTM.NULL != node;
        node = dtm.getNextAttribute(node))
    {
        addAttribute(handler, node);
    }
}
 
Example #3
Source File: SerializerUtils.java    From j2objc with Apache License 2.0 6 votes vote down vote up
/**
 * Returns whether a namespace is defined
 *
 *
 * @param attr Namespace attribute node
 * @param dtm The DTM that owns attr.
 *
 * @return True if the namespace is already defined in
 * list of namespaces
 */
public static boolean isDefinedNSDecl(
    SerializationHandler serializer,
    int attr,
    DTM dtm)
{

    if (DTM.NAMESPACE_NODE == dtm.getNodeType(attr))
    {

        // String prefix = dtm.getPrefix(attr);
        String prefix = dtm.getNodeNameX(attr);
        String uri = serializer.getNamespaceURIFromPrefix(prefix);
        //      String uri = getURI(prefix);

        if ((null != uri) && uri.equals(dtm.getStringValue(attr)))
            return true;
    }

    return false;
}
 
Example #4
Source File: SerializerUtils.java    From j2objc with Apache License 2.0 6 votes vote down vote up
/**
 * This function checks to make sure a given prefix is really
 * declared.  It might not be, because it may be an excluded prefix.
 * If it's not, it still needs to be declared at this point.
 * TODO: This needs to be done at an earlier stage in the game... -sb
 *
 * NEEDSDOC @param dtm
 * NEEDSDOC @param namespace
 *
 * @throws org.xml.sax.SAXException
 */
public static void ensureNamespaceDeclDeclared(
    SerializationHandler handler,
    DTM dtm,
    int namespace)
    throws org.xml.sax.SAXException
{

    String uri = dtm.getNodeValue(namespace);
    String prefix = dtm.getNodeNameX(namespace);

    if ((uri != null && uri.length() > 0) && (null != prefix))
    {
        String foundURI;
        NamespaceMappings ns = handler.getNamespaceMappings();
        if (ns != null)
        {

            foundURI = ns.lookupNamespace(prefix);
            if ((null == foundURI) || !foundURI.equals(uri))
            {
                handler.startPrefixMapping(prefix, uri, false);
            }
        }
    }
}
 
Example #5
Source File: TransformerHandlerImpl.java    From j2objc with Apache License 2.0 6 votes vote down vote up
/**
   * 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
  {

    if (null == result)
      throw new IllegalArgumentException(XSLMessages.createMessage(XSLTErrorResources.ER_RESULT_NULL, null)); //"result should not be null");

    try
    {
//      ContentHandler handler =
//        m_transformer.createResultContentHandler(result);
//      m_transformer.setContentHandler(handler);
        SerializationHandler xoh = 
            m_transformer.createSerializationHandler(result);
        m_transformer.setSerializationHandler(xoh);
    }
    catch (javax.xml.transform.TransformerException te)
    {
      throw new IllegalArgumentException(XSLMessages.createMessage(XSLTErrorResources.ER_RESULT_COULD_NOT_BE_SET, null)); //"result could not be set");
    }

    m_result = result;
  }
 
Example #6
Source File: ElemAttribute.java    From j2objc with Apache License 2.0 6 votes vote down vote up
/**
 * Resolve the namespace into a prefix.  At this level, if no prefix exists, 
 * then return a manufactured prefix.
 *
 * @param rhandler The current result tree handler.
 * @param prefix The probable prefix if already known.
 * @param nodeNamespace  The namespace, which should not be null.
 *
 * @return The prefix to be used.
 */
protected String resolvePrefix(SerializationHandler rhandler,
                               String prefix, String nodeNamespace)
  throws TransformerException
{

  if (null != prefix && (prefix.length() == 0 || prefix.equals("xmlns")))
  {
    // Since we can't use default namespace, in this case we try and 
    // see if a prefix has already been defined or this namespace.
    prefix = rhandler.getPrefix(nodeNamespace);

    // System.out.println("nsPrefix: "+nsPrefix);           
    if (null == prefix || prefix.length() == 0 || prefix.equals("xmlns"))
    {
      if(nodeNamespace.length() > 0)
      {
          NamespaceMappings prefixMapping = rhandler.getNamespaceMappings();
          prefix = prefixMapping.generateNextPrefix();
      }
      else
        prefix = "";
    }
  }
  return prefix;
}
 
Example #7
Source File: ElemElement.java    From j2objc with Apache License 2.0 6 votes vote down vote up
/**
   * Resolve the namespace into a prefix.  Meant to be
   * overidded by elemAttribute if this class is derived.
   *
   * @param rhandler The current result tree handler.
   * @param prefix The probable prefix if already known.
   * @param nodeNamespace  The namespace.
   *
   * @return The prefix to be used.
   */
  protected String resolvePrefix(SerializationHandler rhandler,
                                 String prefix, String nodeNamespace)
    throws TransformerException
  {

//    if (null != prefix && prefix.length() == 0)
//    {
//      String foundPrefix = rhandler.getPrefix(nodeNamespace);
//
//      // System.out.println("nsPrefix: "+nsPrefix);           
//      if (null == foundPrefix)
//        foundPrefix = "";
//    }
    return prefix;
  }
 
Example #8
Source File: SAX2DTM2.java    From j2objc with Apache License 2.0 6 votes vote down vote up
/**
 * Copy the String value of a Text node to a SerializationHandler
 */
protected final void copyTextNode(final int nodeID, SerializationHandler handler)
    throws SAXException
{
    if (nodeID != DTM.NULL) {
  	    int dataIndex = m_dataOrQName.elementAt(nodeID);
        if (dataIndex >= 0) {
            m_chars.sendSAXcharacters(handler,
                                      dataIndex >>> TEXT_LENGTH_BITS,
                                      dataIndex & TEXT_LENGTH_MAX);
        } else {
            m_chars.sendSAXcharacters(handler, m_data.elementAt(-dataIndex),
                                      m_data.elementAt(-dataIndex+1));
        }
    }
}
 
Example #9
Source File: ElemTemplateElement.java    From j2objc with Apache License 2.0 6 votes vote down vote up
/**
 * Send startPrefixMapping events to the result tree handler
 * for all declared prefix mappings in the stylesheet.
 *
 * @param transformer non-null reference to the the current transform-time state.
 * @param ignorePrefix string prefix to not startPrefixMapping
 *
 * @throws TransformerException
 */
void executeNSDecls(TransformerImpl transformer, String ignorePrefix) throws TransformerException
{  
  try
  {
    if (null != m_prefixTable)
    {
      SerializationHandler rhandler = transformer.getResultTreeHandler();
      int n = m_prefixTable.size();

      for (int i = n - 1; i >= 0; i--)
      {
        XMLNSDecl decl = (XMLNSDecl) m_prefixTable.get(i);

        if (!decl.getIsExcluded() && !(null != ignorePrefix && decl.getPrefix().equals(ignorePrefix)))
        {
          rhandler.startPrefixMapping(decl.getPrefix(), decl.getURI(), true);
        }
      }
    }
  }
  catch(org.xml.sax.SAXException se)
  {
    throw new TransformerException(se);
  }
}
 
Example #10
Source File: TransformerImpl.java    From j2objc with Apache License 2.0 5 votes vote down vote up
/**
 * Process the source tree to the output result.
 * @param xmlSource  The input for the source tree.
 * @param outputTarget The output source target.
 * @param shouldRelease  Flag indicating whether to release DTMManager. 
 *
 * @throws TransformerException
 */
public void transform(Source xmlSource, Result outputTarget, boolean shouldRelease)
        throws TransformerException
{

  synchronized (m_reentryGuard)
  {
    SerializationHandler xoh = createSerializationHandler(outputTarget);
    this.setSerializationHandler(xoh);        

    m_outputTarget = outputTarget;

    transform(xmlSource, shouldRelease);
  }
}
 
Example #11
Source File: DOM3TreeWalker.java    From j2objc with Apache License 2.0 5 votes vote down vote up
/**
 * Constructor.
 * @param   contentHandler serialHandler The implemention of the SerializationHandler interface
 */
DOM3TreeWalker(
    SerializationHandler serialHandler,
    DOMErrorHandler errHandler,
    LSSerializerFilter filter,
    String newLine) {
    fSerializer = serialHandler;
    //fErrorHandler = errHandler == null ? new DOMErrorHandlerImpl() : errHandler; // Should we be using the default?
    fErrorHandler = errHandler;
    fFilter = filter;
    fLexicalHandler = null;
    fNewLine = newLine;

    fNSBinder = new NamespaceSupport();
    fLocalNSBinder = new NamespaceSupport();
    
    fDOMConfigProperties = fSerializer.getOutputFormat();
    fSerializer.setDocumentLocator(fLocator);
    initProperties(fDOMConfigProperties);
    
    try {
        // Bug see Bugzilla  26741
        fLocator.setSystemId(
            System.getProperty("user.dir") + File.separator + "dummy.xsl");
    } catch (SecurityException se) { // user.dir not accessible from applet

    }
}
 
Example #12
Source File: TreeWalker2Result.java    From j2objc with Apache License 2.0 5 votes vote down vote up
/**
 * Constructor.
 *
 * @param transformer Non-null transformer instance
 * @param handler The Result tree handler to use
 */
public TreeWalker2Result(TransformerImpl transformer,
                         SerializationHandler handler)
{

  super(handler, null);

  m_transformer = transformer;
  m_handler = handler;
}
 
Example #13
Source File: ElemTemplateElement.java    From j2objc with Apache License 2.0 5 votes vote down vote up
/**
 * Send endPrefixMapping events to the result tree handler
 * for all declared prefix mappings in the stylesheet.
 *
 * @param transformer non-null reference to the the current transform-time state.
 * @param ignorePrefix string prefix to not endPrefixMapping
 * 
 * @throws TransformerException
 */
void unexecuteNSDecls(TransformerImpl transformer, String ignorePrefix) throws TransformerException
{
 
  try
  {
    if (null != m_prefixTable)
    {
      SerializationHandler rhandler = transformer.getResultTreeHandler();
      int n = m_prefixTable.size();

      for (int i = 0; i < n; i++)
      {
        XMLNSDecl decl = (XMLNSDecl) m_prefixTable.get(i);

        if (!decl.getIsExcluded() && !(null != ignorePrefix && decl.getPrefix().equals(ignorePrefix)))
        {
          rhandler.endPrefixMapping(decl.getPrefix());
        }
      }
    }
  }
  catch(org.xml.sax.SAXException se)
  {
    throw new TransformerException(se);
  }
}
 
Example #14
Source File: SAX2DTM2.java    From j2objc with Apache License 2.0 5 votes vote down vote up
/**
 * Copy  attribute nodes from an element .
 *
 * @param nodeID The Element node identity
 * @param handler The SerializationHandler
 */
protected final void copyAttributes(final int nodeID, SerializationHandler handler)
    throws SAXException{

   for(int current = getFirstAttributeIdentity(nodeID); current != DTM.NULL; current = getNextAttributeIdentity(current)){
        int eType = _exptype2(current);
        copyAttribute(current, eType, handler);
   }
}
 
Example #15
Source File: ElemAttribute.java    From j2objc with Apache License 2.0 5 votes vote down vote up
/**
 * Construct a node in the result tree.  This method is overloaded by 
 * xsl:attribute. At this class level, this method creates an element.
 *
 * @param nodeName The name of the node, which may be null.
 * @param prefix The prefix for the namespace, which may be null.
 * @param nodeNamespace The namespace of the node, which may be null.
 * @param transformer non-null reference to the the current transform-time state.
 * @param sourceNode non-null reference to the <a href="http://www.w3.org/TR/xslt#dt-current-node">current source node</a>.
 * @param mode reference, which may be null, to the <a href="http://www.w3.org/TR/xslt#modes">current mode</a>.
 *
 * @throws TransformerException
 */
void constructNode(
        String nodeName, String prefix, String nodeNamespace, TransformerImpl transformer)
          throws TransformerException
{

  if(null != nodeName && nodeName.length() > 0)
  {
    SerializationHandler rhandler = transformer.getSerializationHandler();

    // Evaluate the value of this attribute
    String val = transformer.transformToString(this);
    try 
    {
      // Let the result tree handler add the attribute and its String value.
      String localName = QName.getLocalPart(nodeName);
      if(prefix != null && prefix.length() > 0){
          rhandler.addAttribute(nodeNamespace, localName, nodeName, "CDATA", val, true);
      }else{
          rhandler.addAttribute("", localName, nodeName, "CDATA", val, true);
      }
    }
    catch (SAXException e)
    {
    }
  }
}
 
Example #16
Source File: TransformerImpl.java    From j2objc with Apache License 2.0 5 votes vote down vote up
/**
    * Execute each of the children of a template element.
    *
    * @param elem The ElemTemplateElement that contains the children
    * that should execute.
    * @param handler The ContentHandler to where the result events
    * should be fed.
    *
    * @throws TransformerException
    * @xsl.usage advanced
    */
   public void executeChildTemplates(
           ElemTemplateElement elem, ContentHandler handler)
             throws TransformerException
   {

     SerializationHandler xoh = this.getSerializationHandler();

     // These may well not be the same!  In this case when calling
     // the Redirect extension, it has already set the ContentHandler
     // in the Transformer.
     SerializationHandler savedHandler = xoh;

     try
     {
       xoh.flushPending();

       // %REVIEW% Make sure current node is being pushed.
       LexicalHandler lex = null;
       if (handler instanceof LexicalHandler) {
          lex = (LexicalHandler) handler;
       }
       m_serializationHandler = new ToXMLSAXHandler(handler, lex, savedHandler.getEncoding());
       m_serializationHandler.setTransformer(this);
       executeChildTemplates(elem, true);
     }
     catch (TransformerException e)
     {
       throw e;
     }
     catch (SAXException se) {
     	 throw new TransformerException(se);
     }
     finally
     {
       m_serializationHandler = savedHandler;
  }
}
 
Example #17
Source File: SerializerUtils.java    From j2objc with Apache License 2.0 5 votes vote down vote up
/**
 * Given a result tree fragment, walk the tree and
 * output it to the SerializationHandler.
 *
 * @param obj Result tree fragment object
 * @param support XPath context for the result tree fragment
 *
 * @throws org.xml.sax.SAXException
 */
public static void outputResultTreeFragment(
    SerializationHandler handler,
    XObject obj,
    XPathContext support)
    throws org.xml.sax.SAXException
{

    int doc = obj.rtf();
    DTM dtm = support.getDTM(doc);

    if (null != dtm)
    {
        for (int n = dtm.getFirstChild(doc);
            DTM.NULL != n;
            n = dtm.getNextSibling(n))
        {
            handler.flushPending();

            // I think. . . . This used to have a (true) arg
            // to flush prefixes, will that cause problems ???
            if (dtm.getNodeType(n) == DTM.ELEMENT_NODE
                    && dtm.getNamespaceURI(n) == null)
                handler.startPrefixMapping("", "");
            dtm.dispatchToEvents(n, handler);
        }
    }
}
 
Example #18
Source File: SerializerUtils.java    From j2objc with Apache License 2.0 5 votes vote down vote up
/**
 * Copy an DOM attribute to the created output element, executing
 * attribute templates as need be, and processing the xsl:use
 * attribute.
 *
 * @param handler SerializationHandler to which the attributes are added.
 * @param attr Attribute node to add to SerializationHandler.
 *
 * @throws TransformerException
 */
public static void addAttribute(SerializationHandler handler, int attr)
    throws TransformerException
{

    TransformerImpl transformer =
        (TransformerImpl) handler.getTransformer();
    DTM dtm = transformer.getXPathContext().getDTM(attr);

    if (SerializerUtils.isDefinedNSDecl(handler, attr, dtm))
        return;

    String ns = dtm.getNamespaceURI(attr);

    if (ns == null)
        ns = "";

    // %OPT% ...can I just store the node handle?
    try
    {
        handler.addAttribute(
            ns,
            dtm.getLocalName(attr),
            dtm.getNodeName(attr),
            "CDATA",
            dtm.getNodeValue(attr), false);
    }
    catch (SAXException e)
    {
        // do something?
    }
}
 
Example #19
Source File: SAX2DTM2.java    From j2objc with Apache License 2.0 5 votes vote down vote up
/**
 * Copy an Attribute node to a SerializationHandler
 *
 * @param nodeID The node identity
 * @param exptype The expanded type of the Element node
 * @param handler The SerializationHandler
 */
protected final void copyAttribute(int nodeID, int exptype,
    SerializationHandler handler)
    throws SAXException
{
    /*
        final String uri = getNamespaceName(node);
        if (uri.length() != 0) {
            final String prefix = getPrefix(node);
            handler.namespaceAfterStartElement(prefix, uri);
        }
        handler.addAttribute(getNodeName(node), getNodeValue(node));
    */
    final ExtendedType extType = m_extendedTypes[exptype];
    final String uri = extType.getNamespace();
    final String localName = extType.getLocalName();

    String prefix = null;
    String qname = null;
    int dataIndex = _dataOrQName(nodeID);
    int valueIndex = dataIndex;
        if (dataIndex <= 0) {
            int prefixIndex = m_data.elementAt(-dataIndex);
            valueIndex = m_data.elementAt(-dataIndex+1);
            qname = m_valuesOrPrefixes.indexToString(prefixIndex);
            int colonIndex = qname.indexOf(':');
            if (colonIndex > 0) {
                prefix = qname.substring(0, colonIndex);
            }
        }
        if (uri.length() != 0) {
            handler.namespaceAfterStartElement(prefix, uri);
        }

    String nodeName = (prefix != null) ? qname : localName;
    String nodeValue = (String)m_values.elementAt(valueIndex);

    handler.addAttribute(nodeName, nodeValue);
}
 
Example #20
Source File: ClonerToResultTree.java    From j2objc with Apache License 2.0 4 votes vote down vote up
/**
 * Clone an element with or without children.
 * TODO: Fix or figure out node clone failure!
 * the error condition is severe enough to halt processing.
 *
 * @param node The node to clone
 * @param shouldCloneAttributes Flag indicating whether to 
 * clone children attributes
 * 
 * @throws TransformerException
 */
public static void cloneToResultTree(int node, int nodeType, DTM dtm, 
                                           SerializationHandler rth,
                                           boolean shouldCloneAttributes)
  throws TransformerException
{

  try
  {
    switch (nodeType)
    {
    case DTM.TEXT_NODE :
      dtm.dispatchCharactersEvents(node, rth, false);
      break;
    case DTM.DOCUMENT_FRAGMENT_NODE :
    case DTM.DOCUMENT_NODE :
      // Can't clone a document, but refrain from throwing an error
      // so that copy-of will work
      break;
    case DTM.ELEMENT_NODE :
      {
        // Note: SAX apparently expects "no namespace" to be
        // represented as "" rather than null.
        String ns = dtm.getNamespaceURI(node);
        if (ns==null) ns="";
        String localName = dtm.getLocalName(node);
    //  rth.startElement(ns, localName, dtm.getNodeNameX(node), null);
    //  don't call a real SAX startElement (as commented out above),
    //  call a SAX-like startElement, to be able to add attributes after this call
        rth.startElement(ns, localName, dtm.getNodeNameX(node));
        
 // If outputting attrs as separate events, they must
 // _follow_ the startElement event. (Think of the
 // xsl:attribute directive.)
        if (shouldCloneAttributes)
        {
          SerializerUtils.addAttributes(rth, node);
          SerializerUtils.processNSDecls(rth, node, nodeType, dtm);
        }
      }
      break;
    case DTM.CDATA_SECTION_NODE :
      rth.startCDATA();          
      dtm.dispatchCharactersEvents(node, rth, false);
      rth.endCDATA();
      break;
    case DTM.ATTRIBUTE_NODE :
      SerializerUtils.addAttribute(rth, node);
      break;
	case DTM.NAMESPACE_NODE:
		// %REVIEW% Normally, these should have been handled with element.
		// It's possible that someone may write a stylesheet that tries to
		// clone them explicitly. If so, we need the equivalent of
		// rth.addAttribute().
			    SerializerUtils.processNSDecls(rth,node,DTM.NAMESPACE_NODE,dtm);
		break;
    case DTM.COMMENT_NODE :
      XMLString xstr = dtm.getStringValue (node);
      xstr.dispatchAsComment(rth);
      break;
    case DTM.ENTITY_REFERENCE_NODE :
      rth.entityReference(dtm.getNodeNameX(node));
      break;
    case DTM.PROCESSING_INSTRUCTION_NODE :
      {
        // %REVIEW% Is the node name the same as the "target"?
        rth.processingInstruction(dtm.getNodeNameX(node), 
                                    dtm.getNodeValue(node));
      }
      break;
    default :
      //"Can not create item in result tree: "+node.getNodeName());
      throw new  TransformerException(
                       "Can't clone node: "+dtm.getNodeName(node));
    }
  }
  catch(org.xml.sax.SAXException se)
  {
    throw new TransformerException(se);
  }
}
 
Example #21
Source File: TransformerImpl.java    From j2objc with Apache License 2.0 4 votes vote down vote up
public void setSerializationHandler(SerializationHandler xoh)
{
   m_serializationHandler = xoh;
}
 
Example #22
Source File: ElemCopyOf.java    From j2objc with Apache License 2.0 4 votes vote down vote up
/**
 * The xsl:copy-of element can be used to insert a result tree
 * fragment into the result tree, without first converting it to
 * a string as xsl:value-of does (see [7.6.1 Generating Text with
 * xsl:value-of]).
 *
 * @param transformer non-null reference to the the current transform-time state.
 *
 * @throws TransformerException
 */
public void execute(
        TransformerImpl transformer)
          throws TransformerException
{
  try
  {
    XPathContext xctxt = transformer.getXPathContext();
    int sourceNode = xctxt.getCurrentNode();
    XObject value = m_selectExpression.execute(xctxt, sourceNode, this);

    SerializationHandler handler = transformer.getSerializationHandler();

    if (null != value)
                      {
      int type = value.getType();
      String s;

      switch (type)
      {
      case XObject.CLASS_BOOLEAN :
      case XObject.CLASS_NUMBER :
      case XObject.CLASS_STRING :
        s = value.str();

        handler.characters(s.toCharArray(), 0, s.length());
        break;
      case XObject.CLASS_NODESET :

        // System.out.println(value);
        DTMIterator nl = value.iter();

        // Copy the tree.
        DTMTreeWalker tw = new TreeWalker2Result(transformer, handler);
        int pos;

        while (DTM.NULL != (pos = nl.nextNode()))
        {
          DTM dtm = xctxt.getDTMManager().getDTM(pos);
          short t = dtm.getNodeType(pos);

          // If we just copy the whole document, a startDoc and endDoc get 
          // generated, so we need to only walk the child nodes.
          if (t == DTM.DOCUMENT_NODE)
          {
            for (int child = dtm.getFirstChild(pos); child != DTM.NULL;
                 child = dtm.getNextSibling(child))
            {
              tw.traverse(child);
            }
          }
          else if (t == DTM.ATTRIBUTE_NODE)
          {
            SerializerUtils.addAttribute(handler, pos);
          }
          else
          {
            tw.traverse(pos);
          }
        }
        // nl.detach();
        break;
      case XObject.CLASS_RTREEFRAG :
        SerializerUtils.outputResultTreeFragment(
          handler, value, transformer.getXPathContext());
        break;
      default :
        
        s = value.str();

        handler.characters(s.toCharArray(), 0, s.length());
        break;
      }
    }
                      
    // I don't think we want this.  -sb
    //  if (transformer.getDebug())
    //  transformer.getTraceManager().fireSelectedEvent(sourceNode, this,
    //  "endSelect", m_selectExpression, value);

  }
  catch(org.xml.sax.SAXException se)
  {
    throw new TransformerException(se);
  }

}
 
Example #23
Source File: SAX2DTM2.java    From j2objc with Apache License 2.0 4 votes vote down vote up
/**
 * Copy an Element node to a SerializationHandler.
 *
 * @param nodeID The node identity
 * @param exptype The expanded type of the Element node
 * @param handler The SerializationHandler
 * @return The qualified name of the Element node.
 */
protected final String copyElement(int nodeID, int exptype,
                           SerializationHandler handler)
    throws SAXException
{
    final ExtendedType extType = m_extendedTypes[exptype];
    String uri = extType.getNamespace();
    String name = extType.getLocalName();

    if (uri.length() == 0) {
        handler.startElement(name);
        return name;
    }
    else {
        int qnameIndex = m_dataOrQName.elementAt(nodeID);

        if (qnameIndex == 0) {
            handler.startElement(name);
            handler.namespaceAfterStartElement(EMPTY_STR, uri);
            return name;
        }

        if (qnameIndex < 0) {
	        qnameIndex = -qnameIndex;
	        qnameIndex = m_data.elementAt(qnameIndex);
        }

        String qName = m_valuesOrPrefixes.indexToString(qnameIndex);
        handler.startElement(qName);
        int prefixIndex = qName.indexOf(':');
        String prefix;
        if (prefixIndex > 0) {
            prefix = qName.substring(0, prefixIndex);
        }
        else {
            prefix = null;
        }
        handler.namespaceAfterStartElement(prefix, uri);
        return qName;
    }

}
 
Example #24
Source File: SAX2DTM2.java    From j2objc with Apache License 2.0 4 votes vote down vote up
/**
 * Copy  namespace nodes.
 *
 * @param nodeID The Element node identity
 * @param handler The SerializationHandler
 * @param inScope  true if all namespaces in scope should be copied,
 *  false if only the namespace declarations should be copied.
 */
protected final void copyNS(final int nodeID, SerializationHandler handler, boolean inScope)
    throws SAXException
{
    // %OPT% Optimization for documents which does not have any explicit
    // namespace nodes. For these documents, there is an implicit
    // namespace node (xmlns:xml="http://www.w3.org/XML/1998/namespace")
    // declared on the root element node. In this case, there is no
    // need to do namespace copying. We can safely return without
    // doing anything.
    if (m_namespaceDeclSetElements != null &&
        m_namespaceDeclSetElements.size() == 1 &&
        m_namespaceDeclSets != null &&
        ((SuballocatedIntVector)m_namespaceDeclSets.elementAt(0))
        .size() == 1)
        return;

    SuballocatedIntVector nsContext = null;
    int nextNSNode;

    // Find the first namespace node
    if (inScope) {
        nsContext = findNamespaceContext(nodeID);
        if (nsContext == null || nsContext.size() < 1)
            return;
        else
            nextNSNode = makeNodeIdentity(nsContext.elementAt(0));
    }
    else
        nextNSNode = getNextNamespaceNode2(nodeID);

    int nsIndex = 1;
    while (nextNSNode != DTM.NULL) {
        // Retrieve the name of the namespace node
        int eType = _exptype2(nextNSNode);
        String nodeName = m_extendedTypes[eType].getLocalName();

        // Retrieve the node value of the namespace node
        int dataIndex = m_dataOrQName.elementAt(nextNSNode);

        if (dataIndex < 0) {
            dataIndex = -dataIndex;
            dataIndex = m_data.elementAt(dataIndex + 1);
        }

        String nodeValue = (String)m_values.elementAt(dataIndex);

        handler.namespaceAfterStartElement(nodeName, nodeValue);

        if (inScope) {
            if (nsIndex < nsContext.size()) {
                nextNSNode = makeNodeIdentity(nsContext.elementAt(nsIndex));
                nsIndex++;
            }
            else
                return;
        }
        else
            nextNSNode = getNextNamespaceNode2(nextNSNode);
    }
}
 
Example #25
Source File: TransformerImpl.java    From j2objc with Apache License 2.0 4 votes vote down vote up
/**
  * Given a stylesheet element, create a result tree fragment from it's
  * contents.
  * @param templateParent The template element that holds the fragment.
  * @param dtmFrag The DTM to write the RTF into
  * @return the NodeHandle for the root node of the resulting RTF.
  *
  * @throws TransformerException
  * @xsl.usage advanced
  */
 private int transformToRTF(ElemTemplateElement templateParent,DTM dtmFrag)
         throws TransformerException
 {

   XPathContext xctxt = m_xcontext;
   
   ContentHandler rtfHandler = dtmFrag.getContentHandler();

   // Obtain the ResultTreeFrag's root node.
   // NOTE: In SAX2RTFDTM, this value isn't available until after
   // the startDocument has been issued, so assignment has been moved
   // down a bit in the code.
   int resultFragment; // not yet reliably = dtmFrag.getDocument();

   // Save the current result tree handler.
   SerializationHandler savedRTreeHandler = this.m_serializationHandler;


   // And make a new handler for the RTF.
   ToSAXHandler h = new ToXMLSAXHandler();
   h.setContentHandler(rtfHandler);
   h.setTransformer(this);
   
   // Replace the old handler (which was already saved)
   m_serializationHandler = h;

   // use local variable for the current handler
   SerializationHandler rth = m_serializationHandler;

   try
   {
     rth.startDocument();
     
     // startDocument is "bottlenecked" in RTH. We need it acted upon immediately,
     // to set the DTM's state as in-progress, so that if the xsl:variable's body causes
     // further RTF activity we can keep that from bashing this DTM.
     rth.flushPending(); 

     try
     {

       // Do the transformation of the child elements.
       executeChildTemplates(templateParent, true);

       // Make sure everything is flushed!
       rth.flushPending();
       
       // Get the document ID. May not exist until the RTH has not only
       // received, but flushed, the startDocument, and may be invalid
       // again after the document has been closed (still debating that)
       // ... so waiting until just before the end seems simplest/safest. 
resultFragment = dtmFrag.getDocument();      
     }
     finally
     {
       rth.endDocument();
     }
   }
   catch (org.xml.sax.SAXException se)
   {
     throw new TransformerException(se);
   }
   finally
   {

     // Restore the previous result tree handler.
     this.m_serializationHandler = savedRTreeHandler;
   }

   return resultFragment;
 }
 
Example #26
Source File: Exploit.java    From vulnerability-java-samples with GNU General Public License v3.0 4 votes vote down vote up
@Override
public void transform(DOM document, SerializationHandler[] handlers) throws TransletException {
}
 
Example #27
Source File: ElemValueOf.java    From j2objc with Apache License 2.0 4 votes vote down vote up
/**
 * Execute the string expression and copy the text to the
 * result tree.
 * The required select attribute is an expression; this expression
 * is evaluated and the resulting object is converted to a string
 * as if by a call to the string function. The string specifies
 * the string-value of the created text node. If the string is
 * empty, no text node will be created. The created text node will
 * be merged with any adjacent text nodes.
 * @see <a href="http://www.w3.org/TR/xslt#value-of">value-of in XSLT Specification</a>
 *
 * @param transformer non-null reference to the the current transform-time state.
 *
 * @throws TransformerException
 */
public void execute(TransformerImpl transformer) throws TransformerException
{

  XPathContext xctxt = transformer.getXPathContext();
  SerializationHandler rth = transformer.getResultTreeHandler();

  try
  {
    // Optimize for "."
      xctxt.pushNamespaceContext(this);

      int current = xctxt.getCurrentNode();

      xctxt.pushCurrentNodeAndExpression(current, current);

      if (m_disableOutputEscaping)
        rth.processingInstruction(
          javax.xml.transform.Result.PI_DISABLE_OUTPUT_ESCAPING, "");

      try
      {
        Expression expr = m_selectExpression.getExpression();

          expr.executeCharsToContentHandler(xctxt, rth);
      }
      finally
      {
        if (m_disableOutputEscaping)
          rth.processingInstruction(
            javax.xml.transform.Result.PI_ENABLE_OUTPUT_ESCAPING, "");

        xctxt.popNamespaceContext();
        xctxt.popCurrentNodeAndExpression();
      }
  }
  catch (SAXException se)
  {
    throw new TransformerException(se);
  }
  catch (RuntimeException re) {
  	TransformerException te = new TransformerException(re);
  	te.setLocator(this);
  	throw te;
  }
}
 
Example #28
Source File: ElemElement.java    From j2objc with Apache License 2.0 4 votes vote down vote up
/**
 * Construct a node in the result tree.  This method is overloaded by 
 * xsl:attribute. At this class level, this method creates an element.
 * If the node is null, we instantiate only the content of the node in accordance
 * with section 7.1.2 of the XSLT 1.0 Recommendation.
 *
 * @param nodeName The name of the node, which may be <code>null</code>.  If <code>null</code>,
 *                 only the non-attribute children of this node will be processed.
 * @param prefix The prefix for the namespace, which may be <code>null</code>.
 *               If not <code>null</code>, this prefix will be mapped and unmapped.
 * @param nodeNamespace The namespace of the node, which may be not be <code>null</code>.
 * @param transformer non-null reference to the the current transform-time state.
 *
 * @throws TransformerException
 */
void constructNode(
        String nodeName, String prefix, String nodeNamespace, TransformerImpl transformer)
          throws TransformerException
{

  boolean shouldAddAttrs;

  try
  {
    SerializationHandler rhandler = transformer.getResultTreeHandler();

    if (null == nodeName)
    {
      shouldAddAttrs = false;
    }
    else
    {
      if (null != prefix)
      {
        rhandler.startPrefixMapping(prefix, nodeNamespace, true);
      }

      rhandler.startElement(nodeNamespace, QName.getLocalPart(nodeName),
                            nodeName);

      super.execute(transformer);

      shouldAddAttrs = true;
    }

    transformer.executeChildTemplates(this, shouldAddAttrs);

    // Now end the element if name was valid
    if (null != nodeName)
    {
      rhandler.endElement(nodeNamespace, QName.getLocalPart(nodeName),
                          nodeName);
      if (null != prefix)
      {
        rhandler.endPrefixMapping(prefix);
      }
    }
  }
  catch (SAXException se)
  {
    throw new TransformerException(se);
  }
}
 
Example #29
Source File: ElemElement.java    From j2objc with Apache License 2.0 4 votes vote down vote up
/**
 * Create an element in the result tree.
 * The xsl:element element allows an element to be created with a
 * computed name. The expanded-name of the element to be created
 * is specified by a required name attribute and an optional namespace
 * attribute. The content of the xsl:element element is a template
 * for the attributes and children of the created element.
 *
 * @param transformer non-null reference to the the current transform-time state.
 *
 * @throws TransformerException
 */
public void execute(
        TransformerImpl transformer)
          throws TransformerException
{

SerializationHandler rhandler = transformer.getSerializationHandler();
  XPathContext xctxt = transformer.getXPathContext();
  int sourceNode = xctxt.getCurrentNode();
  
  
  String nodeName = m_name_avt == null ? null : m_name_avt.evaluate(xctxt, sourceNode, this);

  String prefix = null;
  String nodeNamespace = "";

  // Only validate if an AVT was used.
  if ((nodeName != null) && (!m_name_avt.isSimple()) && (!XML11Char.isXML11ValidQName(nodeName)))
  {
    transformer.getMsgMgr().warn(
      this, XSLTErrorResources.WG_ILLEGAL_ATTRIBUTE_VALUE,
      new Object[]{ Constants.ATTRNAME_NAME, nodeName });

    nodeName = null;
  }

  else if (nodeName != null)
  {
    prefix = QName.getPrefixPart(nodeName);

    if (null != m_namespace_avt)
    {
      nodeNamespace = m_namespace_avt.evaluate(xctxt, sourceNode, this);
      if (null == nodeNamespace || 
          (prefix != null && prefix.length()>0 && nodeNamespace.length()== 0) )
        transformer.getMsgMgr().error(
            this, XSLTErrorResources.ER_NULL_URI_NAMESPACE);
      else
      {
      // Determine the actual prefix that we will use for this nodeNamespace

      prefix = resolvePrefix(rhandler, prefix, nodeNamespace);
      if (null == prefix)
        prefix = "";

      if (prefix.length() > 0)
        nodeName = (prefix + ":" + QName.getLocalPart(nodeName));
      else
        nodeName = QName.getLocalPart(nodeName);
      }
    }

    // No namespace attribute was supplied. Use the namespace declarations
    // currently in effect for the xsl:element element.
    else    
    {
      try
      {
        // Maybe temporary, until I get this worked out.  test: axes59
        nodeNamespace = getNamespaceForPrefix(prefix);

        // If we get back a null nodeNamespace, that means that this prefix could
        // not be found in the table.  This is okay only for a default namespace
        // that has never been declared.

        if ( (null == nodeNamespace) && (prefix.length() == 0) )
          nodeNamespace = "";
        else if (null == nodeNamespace)
        {
          transformer.getMsgMgr().warn(
            this, XSLTErrorResources.WG_COULD_NOT_RESOLVE_PREFIX,
            new Object[]{ prefix });

          nodeName = null;
        }

      }
      catch (Exception ex)
      {
        transformer.getMsgMgr().warn(
          this, XSLTErrorResources.WG_COULD_NOT_RESOLVE_PREFIX,
          new Object[]{ prefix });

        nodeName = null;
      }
    }
  }

  constructNode(nodeName, prefix, nodeNamespace, transformer);
}
 
Example #30
Source File: ElemCopy.java    From j2objc with Apache License 2.0 4 votes vote down vote up
/**
 * The xsl:copy element provides an easy way of copying the current node.
 * Executing this function creates a copy of the current node into the
 * result tree.
 * <p>The namespace nodes of the current node are automatically
 * copied as well, but the attributes and children of the node are not
 * automatically copied. The content of the xsl:copy element is a
 * template for the attributes and children of the created node;
 * the content is instantiated only for nodes of types that can have
 * attributes or children (i.e. root nodes and element nodes).</p>
 * <p>The root node is treated specially because the root node of the
 * result tree is created implicitly. When the current node is the
 * root node, xsl:copy will not create a root node, but will just use
 * the content template.</p>
 *
 * @param transformer non-null reference to the the current transform-time state.
 *
 * @throws TransformerException
 */
public void execute(
        TransformerImpl transformer)
          throws TransformerException
{
              XPathContext xctxt = transformer.getXPathContext();
    
  try
  {
    int sourceNode = xctxt.getCurrentNode();
    xctxt.pushCurrentNode(sourceNode);
    DTM dtm = xctxt.getDTM(sourceNode);
    short nodeType = dtm.getNodeType(sourceNode);

    if ((DTM.DOCUMENT_NODE != nodeType) && (DTM.DOCUMENT_FRAGMENT_NODE != nodeType))
    {
      SerializationHandler rthandler = transformer.getSerializationHandler();

      // TODO: Process the use-attribute-sets stuff
      ClonerToResultTree.cloneToResultTree(sourceNode, nodeType, dtm, 
                                           rthandler, false);

      if (DTM.ELEMENT_NODE == nodeType)
      {
        super.execute(transformer);
        SerializerUtils.processNSDecls(rthandler, sourceNode, nodeType, dtm);
        transformer.executeChildTemplates(this, true);
        
        String ns = dtm.getNamespaceURI(sourceNode);
        String localName = dtm.getLocalName(sourceNode);
        transformer.getResultTreeHandler().endElement(ns, localName,
                                                      dtm.getNodeName(sourceNode));
      }
    }
    else
    {
      super.execute(transformer);
      transformer.executeChildTemplates(this, true);
    }
  }
  catch(org.xml.sax.SAXException se)
  {
    throw new TransformerException(se);
  }
  finally
  {
    xctxt.popCurrentNode();
  }
}