public void commitChanges(VariableInstance var, ScopeFrame scopeFrame, Node value)
     throws ExternalVariableModuleException {
   if (var.declaration.extVar != null) /* external variable */ {
     if (__log.isDebugEnabled())
       __log.debug(
           "Write external variable: name="
               + var.declaration
               + " value="
               + DOMUtils.domToString(value));
     VariableInstance related = scopeFrame.resolve(var.declaration.extVar.related);
     Node reference = null;
     try {
       reference = fetchVariableData(var, scopeFrame, true);
     } catch (FaultException fe) {
       // In this context this is not necessarily a problem, since the assignment may re-init the
       // related var
     }
     VariableContext.ValueReferencePair vrp = _brc.writeExtVar(var, reference, value);
     commitChanges(related, scopeFrame, vrp.reference);
   } else /* normal variable */ {
     if (__log.isDebugEnabled())
       __log.debug(
           "Write variable: name=" + var.declaration + " value=" + DOMUtils.domToString(value));
     _brc.commitChanges(var, value);
   }
   writeProperties(var, value);
 }
 /**
  * Proxy to {@link OdeRTInstanceContext#initializeVariable(Variable, Node)} then write properties.
  */
 public Node initializeVariable(VariableInstance var, ScopeFrame scopeFrame, Node val)
     throws ExternalVariableModuleException {
   try {
     if (var.declaration.extVar != null) /* external variable */ {
       if (__log.isDebugEnabled())
         __log.debug(
             "Initialize external variable: name="
                 + var.declaration
                 + " value="
                 + DOMUtils.domToString(val));
       Node reference = null;
       try {
         reference = fetchVariableData(var, scopeFrame, true);
       } catch (FaultException fe) {
         // In this context this is not necessarily a problem, since the assignment may re-init the
         // related var
       }
       if (reference != null) val = _brc.readExtVar(var, reference);
       return val;
     } else /* normal variable */ {
       if (__log.isDebugEnabled())
         __log.debug(
             "Initialize variable: name="
                 + var.declaration
                 + " value="
                 + DOMUtils.domToString(val));
       return _brc.initializeVariable(var, val);
     }
   } finally {
     writeProperties(var, val);
   }
 }
示例#3
0
 /**
  * Returns a {@link XMLSchemaType}
  *
  * @see javax.wsdl.extensions.ExtensionDeserializer#unmarshall(java.lang.Class,
  *     javax.xml.namespace.QName, org.w3c.dom.Element, javax.wsdl.Definition,
  *     javax.wsdl.extensions.ExtensionRegistry)
  */
 public ExtensibilityElement unmarshall(
     Class clazz,
     QName qname,
     Element element,
     Definition definition,
     ExtensionRegistry extensionRegistry)
     throws WSDLException {
   DOMUtils.pancakeNamespaces(element);
   return new XMLSchemaType(DOMUtils.domToString(element));
 }
示例#4
0
  @Test
  public void testSimplePassing() throws Exception {
    server.deployService(
        "TestSoapHeader",
        "dummy-service.wsdl",
        new QName("http://axis2.ode.apache.org", "DummyService"),
        "DummyServiceSOAP11port_http",
        new MessageReceiver() {
          public void receive(MessageContext messageCtx) throws AxisFault {
            System.out.println(messageCtx.getEnvelope());
            OMElement cidElmt = messageCtx.getEnvelope().getHeader().getFirstElement();
            // Also checking if the session is included in passing
            assertTrue(messageCtx.getEnvelope().toString().indexOf("session") > 0);

            assertEquals("ConversationId", cidElmt.getLocalName());
            assertEquals("ZZZXYZ", cidElmt.getText());

            MessageContext outMsgContext = Utils.createOutMessageContext(messageCtx);
            outMsgContext.getOperationContext().addMessageContext(outMsgContext);

            // Far too many lines of code...
            SOAPFactory factory = OMAbstractFactory.getSOAP11Factory();
            SOAPEnvelope env = factory.createSOAPEnvelope();
            SOAPHeader header = factory.createSOAPHeader(env);
            SOAPBody body = factory.createSOAPBody(env);
            outMsgContext.setEnvelope(env);
            OMElement respElmt =
                factory.createOMElement(
                    new QName("http://axis2.ode.apache.org", "faultTestResponse"));
            body.addChild(respElmt);
            respElmt.setText("dummy");
            SOAPHeaderBlock headerBlock =
                factory.createSOAPHeaderBlock(
                    "ConversationId",
                    factory.createOMNamespace("http://my.company/super/protocol", "pns"),
                    header);
            headerBlock.setText("ZZYV");
            AxisEngine.send(outMsgContext);
          }
        });

    if (!server.isDeployed("TestSoapHeader")) server.deployProcess("TestSoapHeader");

    String response =
        server.sendRequestFile(
            "http://localhost:8888/processes/headerTest", "TestSoapHeader", "testRequest.soap");

    Element rootElemt = DOMUtils.stringToDOM(response);
    Element cidElemt = DOMUtils.getFirstChildElement(DOMUtils.getFirstChildElement(rootElemt));
    assertEquals("ConversationId", cidElemt.getLocalName());
    assertEquals("ZZYV", cidElemt.getTextContent());

    server.undeployProcess("TestSoapHeader");
  }
  public void createSoapBody(
      org.apache.axiom.soap.SOAPBody sb,
      SOAPBody soapBody,
      Message msgDef,
      Element message,
      String rpcWrapper)
      throws AxisFault {
    OMElement partHolder =
        isRPC
            ? soapFactory.createOMElement(
                new QName(soapBody.getNamespaceURI(), rpcWrapper, "odens"), sb)
            : sb;
    List<Part> parts = msgDef.getOrderedParts(soapBody.getParts());

    for (Part part : parts) {
      Element srcPartEl = DOMUtils.findChildByName(message, new QName(null, part.getName()));
      if (srcPartEl == null) {
        throw new AxisFault("Missing required part in ODE Message");
      }

      OMElement omPart = OMUtils.toOM(srcPartEl, soapFactory);
      if (isRPC) {
        partHolder.addChild(omPart);
      } else {
        for (Iterator<OMNode> i = omPart.getChildren(); i.hasNext(); ) {
          partHolder.addChild(i.next());
        }
      }
    }
  }
  /**
   * @see
   *     org.apache.ode.bpel.explang.ExpressionLanguageRuntime#evaluate(org.apache.ode.bpel.obj.OExpression,
   *     org.apache.ode.bpel.explang.EvaluationContext)
   */
  public List evaluate(OExpression cexp, EvaluationContext ctx)
      throws FaultException, EvaluationException {
    List result;
    Object someRes = evaluate(cexp, ctx, XPathConstants.NODESET);

    if (someRes instanceof List) {
      result = (List) someRes;
      if (__log.isDebugEnabled()) {
        __log.debug("Returned list of size " + result.size());
      }

      if ((result.size() == 1) && !(result.get(0) instanceof Node)) {
        // Dealing with a Java class
        Object simpleType = result.get(0);

        // Dates get a separate treatment as we don't want to call toString on them
        String textVal;

        if (simpleType instanceof Date) {
          textVal = ISO8601DateParser.format((Date) simpleType);
        } else if (simpleType instanceof DurationValue) {
          textVal = ((DurationValue) simpleType).getStringValue();
        } else {
          textVal = simpleType.toString();
        }

        // Wrapping in a document
        Document d = DOMUtils.newDocument();

        // Giving our node a parent just in case it's an LValue expression
        Element wrapper = d.createElement("wrapper");
        Text text = d.createTextNode(textVal);
        wrapper.appendChild(text);
        d.appendChild(wrapper);
        result = Collections.singletonList(text);
      }
    } else if (someRes instanceof NodeList) {
      NodeList retVal = (NodeList) someRes;
      if (__log.isDebugEnabled()) {
        __log.debug("Returned node list of size " + retVal.getLength());
      }
      result = new ArrayList(retVal.getLength());

      for (int m = 0; m < retVal.getLength(); ++m) {
        Node val = retVal.item(m);

        if (val.getNodeType() == Node.DOCUMENT_NODE) {
          val = ((Document) val).getDocumentElement();
        }

        result.add(val);
      }
    } else {
      result = null;
    }

    return result;
  }
  /**
   * Cast XQuery sequence into an opaque list
   *
   * @param type type
   * @param result result
   * @return value
   * @throws XQException XQException
   */
  private Object getResultValue(QName type, XQResultSequence result) throws XQException {
    Document document = DOMUtils.newDocument();
    Object resultValue = null;
    if (XPathConstants.NODESET.equals(type)) {
      List list = new ArrayList();

      while (result.next()) {
        Object itemValue = getItemValue(result.getItem());
        if (itemValue instanceof Document) {
          itemValue = DOMUtils.cloneNode(document, ((Document) itemValue).getDocumentElement());
        } else if (itemValue instanceof Node) {
          itemValue = DOMUtils.cloneNode(document, (Node) itemValue);
        }

        if (itemValue != null) {
          list.add(itemValue);
        }
      }

      resultValue = list;
    } else if (XPathConstants.NODE.equals(type)) {
      XQItem item = null;
      if (result.count() > 0) {
        result.first();
        if (result.isOnItem()) {
          item = result.getItem();
        }
      }
      if (item != null) {
        resultValue = getItemValue(item);
        if (resultValue instanceof Node) {
          resultValue = DOMUtils.cloneNode(document, (Node) resultValue);
        }
      }
    } else if (XPathConstants.STRING.equals(type)) {
      resultValue = result.getSequenceAsString(new Properties());
    } else if (XPathConstants.NUMBER.equals(type)) {
      resultValue = result.getSequenceAsString(new Properties());
      resultValue = Integer.parseInt((String) resultValue);
    } else if (XPathConstants.BOOLEAN.equals(type)) {
      resultValue = result.getSequenceAsString(new Properties());
      resultValue = Boolean.parseBoolean((String) resultValue);
    }
    return resultValue;
  }
示例#8
0
 public Element getPartnerEPR() {
   entering("PartnerLinkDAOImpl.getPartnerEPR");
   if (_partnerEPR != null) return _partnerEPR;
   if (_self.getPartnerEPR() == null) return null;
   try {
     return _partnerEPR = DOMUtils.stringToDOM(_self.getPartnerEPR());
   } catch (Exception e) {
     throw new RuntimeException(e);
   }
 }
示例#9
0
 public void setMyEPR(Element val) {
   entering("PartnerLinkDAOImpl.setMyEPR");
   _myEPR = val;
   if (val == null) {
     _self.setMyEPR(null);
   } else {
     _self.setMyEPR(DOMUtils.domToBytes(val));
   }
   getSession().update(_self);
 }
 public Node fetchVariableData(
     VariableInstance variable, ScopeFrame scopeFrame, boolean forWriting) throws FaultException {
   if (variable.declaration.extVar != null) {
     // Note, that when using external variables, the database will not contain the value of the
     // variable, instead we need to go the external variable subsystems.
     Element reference =
         (Element)
             _brc.fetchVariableData(
                 scopeFrame.resolve(variable.declaration.extVar.related), false);
     try {
       Node ret = _brc.readExtVar(variable, reference);
       if (ret == null) {
         throw new FaultException(
             _runtime._oprocess.constants.qnUninitializedVariable,
             "The external variable \""
                 + variable.declaration.name
                 + "\" has not been initialized.");
       }
       return ret;
     } catch (IncompleteKeyException ike) {
       // This indicates that the external variable needed to be written do, put has not been.
       __log.error(
           "External variable could not be read due to incomplete key; the following key "
               + "components were missing: "
               + ike.getMissing());
       throw new FaultException(
           _runtime._oprocess.constants.qnUninitializedVariable,
           "The extenral variable \""
               + variable.declaration.name
               + "\" has not been properly initialized;"
               + "the following key compoenents were missing:"
               + ike.getMissing());
     } catch (ExternalVariableModuleException e) {
       throw new BpelEngineException(e);
     }
   } else /* not external */ {
     Node data = _brc.fetchVariableData(variable, forWriting);
     if (data == null) {
       // Special case of messageType variables with no part
       if (variable.declaration.type instanceof OMessageVarType) {
         OMessageVarType msgType = (OMessageVarType) variable.declaration.type;
         if (msgType.parts.size() == 0) {
           Document doc = DOMUtils.newDocument();
           Element root = doc.createElement("message");
           doc.appendChild(root);
           return root;
         }
       }
       throw new FaultException(
           _runtime._oprocess.constants.qnUninitializedVariable,
           "The variable " + variable.declaration.name + " isn't properly initialized.");
     }
     return data;
   }
 }
示例#11
0
 /**
  * Get Variable data for the given variable name, for this scope instance
  *
  * @param varName Variable Name
  * @return DOM Node as XML String. If no value exists or variable not initialized, NULL will be
  *     returnrd.
  */
 public String getVariableData(String varName) {
   String value = null;
   try {
     OScope.Variable var = __scope.getVisibleVariable(varName);
     VariableInstance varInstance = new VariableInstance(__scopeInstanceId, var);
     Node varNode = __runtimeContext.fetchVariableData(varInstance, null, false);
     value = DOMUtils.domToString(varNode);
   } catch (Throwable e) {
     // Don't throw any exception back to the caller. Just return null as value.
   }
   return value;
 }
  public Node getPartData(Element message, OMessageVarType.Part part) {
    // borrowed from ASSIGN.evalQuery()
    Node ret = DOMUtils.findChildByName(message, new QName(null, part.name));
    if (part.type instanceof OElementVarType) {
      QName elName = ((OElementVarType) part.type).elementType;
      ret = DOMUtils.findChildByName((Element) ret, elName);
    } else if (part.type == null) {
      // Special case of header parts never referenced in the WSDL def
      if (ret != null
          && ret.getNodeType() == Node.ELEMENT_NODE
          && ((Element) ret).getAttribute("headerPart") != null
          && DOMUtils.getTextContent(ret) == null)
        ret = DOMUtils.getFirstChildElement((Element) ret);
      // The needed part isn't there, dynamically creating it
      if (ret == null) {
        ret = message.getOwnerDocument().createElementNS(null, part.name);
        ((Element) ret).setAttribute("headerPart", "true");
        message.appendChild(ret);
      }
    }

    return ret;
  }
示例#13
0
  /**
   * Create a property mapping based on the initial values in the deployment descriptor.
   *
   * @param dd
   * @return
   */
  public static Map<QName, Node> calcInitialProperties(
      Properties properties, TDeployment.Process dd) {
    HashMap<QName, Node> ret = new HashMap<QName, Node>();

    for (Object key1 : properties.keySet()) {
      String key = (String) key1;
      Document doc = DOMUtils.newDocument();
      doc.appendChild(doc.createElementNS(null, "temporary-simple-type-wrapper"));
      doc.getDocumentElement().appendChild(doc.createTextNode(properties.getProperty(key)));

      ret.put(new QName(key), doc.getDocumentElement());
    }

    for (TDeployment.Process.Property property : dd.getPropertyArray()) {
      Element elmtContent = DOMUtils.getElementContent(property.getDomNode());
      if (elmtContent != null) {
        // We'll need DOM Level 3
        Document doc = DOMUtils.newDocument();
        doc.appendChild(doc.importNode(elmtContent, true));
        ret.put(property.getName(), doc.getDocumentElement());
      } else ret.put(property.getName(), property.getDomNode().getFirstChild());
    }
    return ret;
  }
  /**
   * Evaluate expression and return a date
   *
   * @param cexp cexp
   * @param context context
   * @return type
   * @throws FaultException FaultException
   * @throws EvaluationException EvaluationException
   */
  public Calendar evaluateAsDate(OExpression cexp, EvaluationContext context)
      throws FaultException, EvaluationException {
    List literal = DOMUtils.toList(evaluate(cexp, context, XPathConstants.NODESET));

    if (literal.size() == 0) {
      throw new FaultException(
          cexp.getOwner().getConstants().getQnSelectionFailure(),
          "No results for expression: " + cexp);
    }

    if (literal.size() > 1) {
      throw new FaultException(
          cexp.getOwner().getConstants().getQnSelectionFailure(),
          "Multiple results for expression: " + cexp);
    }

    Object date = literal.get(0);

    if (date instanceof Calendar) {
      return (Calendar) date;
    }

    if (date instanceof Date) {
      Calendar cal = Calendar.getInstance();
      cal.setTime((Date) date);

      return cal;
    }

    if (date instanceof Element) {
      date = ((Element) date).getTextContent();
    }

    try {
      return ISO8601DateParser.parseCal(date.toString());
    } catch (Exception ex) {
      String errmsg = "Invalid date: " + literal;
      __log.error(errmsg, ex);
      throw new FaultException(
          cexp.getOwner().getConstants().getQnInvalidExpressionValue(), errmsg);
    }
  }
  /**
   * Evaluate expression and return opaque type
   *
   * @param cexp cexp
   * @param ctx ctx
   * @param type type
   * @return type
   * @throws FaultException FaultException
   * @throws EvaluationException EvaluationException
   */
  private Object evaluate(OExpression cexp, EvaluationContext ctx, QName type)
      throws FaultException, EvaluationException {
    try {
      OXQuery10ExpressionBPEL20 oxquery10 = ((OXQuery10ExpressionBPEL20) cexp);

      XQDataSource xqds = new SaxonXQDataSource();
      XQConnection xqconn = xqds.getConnection();

      Configuration configuration = ((SaxonXQConnection) xqconn).getConfiguration();
      configuration.setAllNodesUntyped(true);
      configuration.setHostLanguage(Configuration.XQUERY);

      XQStaticContext staticEnv = xqconn.getStaticContext();

      NSContext nsContext = oxquery10.getNamespaceCtx();
      Set<String> prefixes = nsContext.getPrefixes();
      for (String prefix : prefixes) {
        String uri = nsContext.getNamespaceURI(prefix);
        staticEnv.declareNamespace(prefix, uri);
      }

      configuration.setSchemaValidationMode(Validation.SKIP);
      xqconn.setStaticContext(staticEnv);

      // Prepare expression, for starters
      String xquery =
          oxquery10
              .getXquery()
              .replaceFirst(
                  Constants.XQUERY_FUNCTION_HANDLER_COMPILER,
                  Constants.XQUERY_FUNCTION_HANDLER_RUNTIME);
      XQPreparedExpression exp = xqconn.prepareExpression(xquery);

      JaxpFunctionResolver funcResolver = new JaxpFunctionResolver(ctx, oxquery10);
      JaxpVariableResolver variableResolver =
          new JaxpVariableResolver(ctx, oxquery10, configuration);
      // Bind external variables to runtime values
      for (QName variable : exp.getAllUnboundExternalVariables()) {
        // Evaluate referenced variable
        Object value = variableResolver.resolveVariable(variable);

        if (value instanceof Value) {
          SaxonXQConnection saxonConn = (SaxonXQConnection) xqconn;
          try {
            Item item = ((Value) value).asItem();
            if (item == null) {
              exp.bindSequence(variable, xqconn.createSequence(Collections.EMPTY_LIST.iterator()));
            } else {
              XQItem item2 = new SaxonXQItem(item, saxonConn);
              exp.bindItem(variable, item2);
            }
          } catch (XPathException e) {
            __log.warn("", e);
          }
        } else {

          if (value instanceof Date) {
            Date d = (Date) value;
            value = org.apache.ode.utils.ISO8601DateParser.format(d);
          }

          // Figure out type of variable
          XQSequenceType xqType = getItemType(xqconn, value);

          // Saxon doesn't like binding sequences to variables
          if (value instanceof Node) {
            // a node is a node-list, but the inverse isn't true.
            // so, if the value is truly a node, leave it alone.
          } else if (value instanceof NodeList) {
            // So extract the first item from the node list
            NodeList nodeList = (NodeList) value;
            ArrayList nodeArray = new ArrayList();
            for (int i = 0; i < nodeList.getLength(); i++) {
              nodeArray.add(nodeList.item(i));
            }
            value = xqconn.createSequence(nodeArray.iterator());
          }

          // Bind value with external variable
          if (value != null && xqType != null) {
            if (value instanceof XQSequence) {
              exp.bindSequence(variable, (XQSequence) value);
            } else {
              if (xqType instanceof XQItemType) {
                exp.bindObject(variable, value, (XQItemType) xqType);
              }
            }
          }
        }
      }

      // Set context node
      Node contextNode = (ctx.getRootNode() == null) ? DOMUtils.newDocument() : ctx.getRootNode();
      contextNode.setUserData(
          XQuery10BpelFunctions.USER_DATA_KEY_FUNCTION_RESOLVER, funcResolver, null);
      exp.bindItem(
          XQConstants.CONTEXT_ITEM,
          xqconn.createItemFromNode(contextNode, xqconn.createNodeType()));

      // Execute query
      XQResultSequence result = exp.executeQuery();

      // Cast Saxon result to Java result
      Object evalResult = getResultValue(type, result);

      if ((evalResult != null) && __log.isDebugEnabled()) {
        __log.debug(
            "Expression "
                + cexp.toString()
                + " generated result "
                + evalResult
                + " - type="
                + evalResult.getClass().getName());

        if (ctx.getRootNode() != null) {
          __log.debug("Was using context node " + DOMUtils.domToString(ctx.getRootNode()));
        }
      }

      return evalResult;
    } catch (XQException xqe) {
      // Extracting the real cause from all this wrapping isn't a simple task
      Throwable cause = (xqe.getCause() != null) ? xqe.getCause() : xqe;

      if (cause instanceof DynamicError) {
        Throwable th = ((DynamicError) cause).getException();

        if (th != null) {
          cause = th;

          if (cause.getCause() != null) {
            cause = cause.getCause();
          }
        }
      }

      throw new EvaluationException(
          "Error while executing an XQuery expression: " + cause.toString(), cause);
    } catch (WrappedResolverException wre) {
      __log.debug("Could not evaluate expression because of ", wre);
      throw (FaultException) wre.getCause();
    }
  }
示例#16
0
 public void setProperty(final QName pid, final QName propName, final Node value) {
   setProperty(pid, propName, DOMUtils.domToStringLevel2(value));
 }