Exemplo n.º 1
0
  private Object deserializeInstance(
      IndentedLogger indentedLogger,
      boolean isReadonly,
      boolean isHandleXInclude,
      ConnectionResult connectionResult)
      throws Exception {
    final Object resultingDocument;

    // Create resulting instance whether entire instance is replaced or not, because this:
    // 1. Wraps a Document within a DocumentInfo if needed
    // 2. Performs text nodes adjustments if needed
    try {
      if (!isReadonly) {
        // Resulting instance must not be read-only

        // TODO: What about configuring validation? And what default to choose?
        resultingDocument =
            TransformerUtils.readDom4j(
                connectionResult.getResponseInputStream(),
                connectionResult.resourceURI,
                isHandleXInclude,
                true);

        if (indentedLogger.isDebugEnabled())
          indentedLogger.logDebug("", "deserializing to mutable instance");
      } else {
        // Resulting instance must be read-only

        // TODO: What about configuring validation? And what default to choose?
        // NOTE: isApplicationSharedHint is always false when get get here.
        // isApplicationSharedHint="true" is handled above.
        resultingDocument =
            TransformerUtils.readTinyTree(
                XPathCache.getGlobalConfiguration(),
                connectionResult.getResponseInputStream(),
                connectionResult.resourceURI,
                isHandleXInclude,
                true);

        if (indentedLogger.isDebugEnabled())
          indentedLogger.logDebug("", "deserializing to read-only instance");
      }
    } catch (Exception e) {
      throw new XFormsSubmissionException(
          submission,
          e,
          "xforms:submission: exception while reading XML response.",
          "processing instance replacement",
          new XFormsSubmitErrorEvent(
              containingDocument,
              submission,
              XFormsSubmitErrorEvent.ErrorType.PARSE_ERROR,
              connectionResult));
    }

    return resultingDocument;
  }
Exemplo n.º 2
0
  /** Transform a SAX Source to a TinyTree. */
  public static DocumentInfo readTinyTree(
      Configuration configuration, Source source, boolean handleXInclude) {
    final TinyBuilder treeBuilder = new TinyBuilder();
    try {
      if (handleXInclude) {
        // Insert XIncludeContentHandler
        final TransformerXMLReceiver identityHandler = getIdentityTransformerHandler(configuration);
        identityHandler.setResult(treeBuilder);
        final XMLReceiver receiver =
            new XIncludeProcessor.XIncludeXMLReceiver(
                null,
                identityHandler,
                null,
                new TransformerURIResolver(XMLUtils.ParserConfiguration.PLAIN));
        TransformerUtils.sourceToSAX(source, receiver);
      } else {
        final Transformer identity = getIdentityTransformer(configuration);
        identity.transform(source, treeBuilder);
      }

    } catch (TransformerException e) {
      throw new OXFException(e);
    }
    return (DocumentInfo) treeBuilder.getCurrentRoot();
  }
Exemplo n.º 3
0
  public static org.dom4j.Document createDocument(DebugXML debugXML) {
    final TransformerXMLReceiver identity = TransformerUtils.getIdentityTransformerHandler();
    final LocationDocumentResult result = new LocationDocumentResult();
    identity.setResult(result);

    final ContentHandlerHelper helper =
        new ContentHandlerHelper(
            new ForwardingXMLReceiver(identity) {
              @Override
              public void startDocument() {}

              @Override
              public void endDocument() {}
            });

    try {
      identity.startDocument();
      debugXML.toXML(helper);
      identity.endDocument();
    } catch (SAXException e) {
      throw new OXFException(e);
    }

    return result.getDocument();
  }
Exemplo n.º 4
0
  public void serialize(PipelineContext pipelineContext, URL url) {
    try {
      if (OXFHandler.PROTOCOL.equals(url.getProtocol())) {
        // NOTE: This is probably done as an optimization. Is this really necessary?

        final OutputStream os = ResourceManagerWrapper.instance().getOutputStream(url.getFile());
        try {
          final TransformerXMLReceiver identity = TransformerUtils.getIdentityTransformerHandler();
          identity.setResult(new StreamResult(os));

          readInputAsSAX(pipelineContext, INPUT_DATA, identity);
        } finally {
          // Clean up
          if (os != null) os.close();
        }
      } else {
        // Open the URL
        final URLConnection conn = url.openConnection();
        try {
          conn.setDoOutput(true);
          conn.connect();
          final OutputStream os = conn.getOutputStream();
          try {
            // Create an identity transformer and start the transformation
            final TransformerXMLReceiver identity =
                TransformerUtils.getIdentityTransformerHandler();
            identity.setResult(new StreamResult(os));
            readInputAsSAX(pipelineContext, INPUT_DATA, identity);
          } finally {
            // Clean up
            if (os != null) os.close();
          }
        } finally {
          // Clean up
          if (conn instanceof HttpURLConnection) ((HttpURLConnection) conn).disconnect();
        }
      }
    } catch (Exception e) {
      throw new OXFException(e);
    }
  }
Exemplo n.º 5
0
  public static String domToString(Node node) {
    try {
      Transformer transformer = TransformerUtils.getXMLIdentityTransformer();
      DOMSource source = new DOMSource(node);

      StringBuilderWriter writer = new StringBuilderWriter();
      transformer.transform(source, new StreamResult(writer));
      return writer.toString();
    } catch (TransformerException e) {
      throw new OXFException(e);
    }
  }
    private XMLReceiver getDebugReceiver(final IndentedLogger indentedLogger) {
      final TransformerXMLReceiver identity = TransformerUtils.getIdentityTransformerHandler();
      final StringBuilderWriter writer = new StringBuilderWriter();
      identity.setResult(new StreamResult(writer));

      return new ForwardingXMLReceiver(identity) {
        @Override
        public void endDocument() throws SAXException {
          super.endDocument();
          // Log out at end of document
          indentedLogger.logDebug("", "static state input", "input", writer.toString());
        }
      };
    }
Exemplo n.º 7
0
  /**
   * Transform a SAXStore into a DOM document
   *
   * @param saxStore input SAXStore
   * @return DOM document
   */
  public static org.w3c.dom.Document saxStoreToDomDocument(SAXStore saxStore) {
    try {
      // Convert to dom4j and then to DOM
      return TransformerUtils.dom4jToDomDocument(saxStoreToDom4jDocument(saxStore));
    } catch (TransformerException e) {
      throw new OXFException(e);
    }

    // NOTE: The more straight and efficient implementation below doesn't seem to work
    //        final TransformerHandler identity = getIdentityTransformerHandler();
    //        final DOMResult domResult = new DOMResult();
    //        identity.setResult(domResult);
    //        try {
    //            saxStore.replay(identity);
    //        } catch (SAXException e) {
    //            throw new OXFException(e);
    //        }
    //        return domResult.getNode().getOwnerDocument();
  }
  public Item evaluateItem(XPathContext xpathContext) throws XPathException {

    // Get parameters
    final Item item = argument[0].evaluateItem(xpathContext);
    final String excludeResultPrefixes =
        argument.length >= 2 ? argument[1].evaluateAsString(xpathContext).toString() : null;
    final boolean readonly =
        argument.length >= 3
            && ExpressionTool.effectiveBooleanValue(argument[2].iterate(xpathContext));

    // Make sure it is a NodeInfo
    if (!(item instanceof NodeInfo)) {
      return null;
    }

    // Get Element
    final Element rootElement;
    if (item instanceof NodeWrapper) {
      final Object node = ((NodeWrapper) item).getUnderlyingNode();
      rootElement = (Element) node;
    } else {
      final NodeInfo nodeInfo = (NodeInfo) item;
      final Document document = TransformerUtils.tinyTreeToDom4j2(nodeInfo);
      rootElement = document.getRootElement();
    }

    // Convert to Document or DocumentInfo
    final Object result =
        extractDocument(
            xpathContext.getConfiguration(), rootElement, excludeResultPrefixes, readonly);

    // Return DocumentInfo
    if (result instanceof Document)
      return new DocumentWrapper(
          (Document) result,
          null,
          getContainingDocument(xpathContext).getStaticState().getXPathConfiguration());
    else return (DocumentInfo) result;
  }
  public static Object extractDocument(
      Configuration configuration,
      Element element,
      String excludeResultPrefixes,
      boolean readonly) {
    Object instanceDocument;
    final Document tempDocument;

    // Extract document and adjust namespaces
    // TODO: Implement exactly as per XSLT 2.0
    // TODO: Must implement namespace fixup, the code below can break serialization
    if ("#all".equals(excludeResultPrefixes)) {
      // Special #all
      tempDocument = Dom4jUtils.createDocumentCopyElement(element);
    } else if (excludeResultPrefixes != null && excludeResultPrefixes.trim().length() != 0) {
      // List of prefixes
      final StringTokenizer st = new StringTokenizer(excludeResultPrefixes);
      final Map<String, String> prefixesToExclude = new HashMap<String, String>();
      while (st.hasMoreTokens()) {
        prefixesToExclude.put(st.nextToken(), "");
      }
      tempDocument = Dom4jUtils.createDocumentCopyParentNamespaces(element, prefixesToExclude);
    } else {
      // No exclusion
      tempDocument = Dom4jUtils.createDocumentCopyParentNamespaces(element);
    }

    // Produce DOM or TinyTree
    if (!readonly) {
      instanceDocument = tempDocument;
    } else {
      instanceDocument = TransformerUtils.dom4jToTinyTree(configuration, tempDocument);
    }

    return instanceDocument;
  }
Exemplo n.º 10
0
 /** Compute a digest for a SAX source. */
 public static byte[] getDigest(Source source) {
   final DigestContentHandler digester = new DigestContentHandler();
   TransformerUtils.sourceToSAX(source, digester);
   return digester.getResult();
 }
Exemplo n.º 11
0
    public StaticStateBits(
        PipelineContext pipelineContext,
        ExternalContext externalContext,
        IndentedLogger indentedLogger,
        String existingStaticStateDigest) {

      final boolean computeDigest = isLogStaticStateInput || existingStaticStateDigest == null;

      indentedLogger.startHandleOperation(
          "", "reading input", "existing digest", existingStaticStateDigest);

      final TransformerXMLReceiver documentReceiver =
          TransformerUtils.getIdentityTransformerHandler();
      final LocationDocumentResult documentResult = new LocationDocumentResult();
      documentReceiver.setResult(documentResult);

      final XMLUtils.DigestContentHandler digestReceiver =
          computeDigest ? new XMLUtils.DigestContentHandler("MD5") : null;
      final XMLReceiver extractorOutput;
      if (isLogStaticStateInput) {
        extractorOutput =
            computeDigest
                ? new TeeXMLReceiver(
                    documentReceiver, digestReceiver, getDebugReceiver(indentedLogger))
                : new TeeXMLReceiver(documentReceiver, getDebugReceiver(indentedLogger));
      } else {
        extractorOutput =
            computeDigest ? new TeeXMLReceiver(documentReceiver, digestReceiver) : documentReceiver;
      }

      // Read the input through the annotator and gather namespace mappings
      //
      // Output of annotator is:
      //
      // o annotated page template (TODO: this should not include model elements)
      // o extractor
      //
      // Output of extractor is:
      //
      // o static state document
      // o optionally: digest
      // o optionally: debug output
      //
      readInputAsSAX(
          pipelineContext,
          INPUT_ANNOTATED_DOCUMENT,
          new XFormsAnnotatorContentHandler(
              annotatedTemplate,
              new XFormsExtractorContentHandler(extractorOutput, metadata),
              metadata));

      this.staticStateDocument = documentResult.getDocument();
      this.staticStateDigest =
          computeDigest ? NumberUtils.toHexString(digestReceiver.getResult()) : null;

      assert !isLogStaticStateInput
          || existingStaticStateDigest == null
          || this.staticStateDigest.equals(existingStaticStateDigest);

      indentedLogger.endHandleOperation("computed digest", this.staticStateDigest);
    }