protected CommandEvaluator<Criterion, Object> compileIdentifierToValueCMP(
     IdentifierToValueCMP node) {
   Identifier id = node.getIdentifier();
   if (id instanceof Field) {
     String name = id.getName();
     Value value = node.getValue();
     if (INSTANCE_ID_FIELD.equals(name)) {
       value.setValue(Long.valueOf((String) value.getValue()));
     } else if (INSTANCE_STARTED_FIELD.equals(name) || INSTANCE_LAST_ACTIVE_FIELD.equals(name)) {
       try {
         value.setValue(ISO8601DateParser.parse((String) value.getValue()));
       } catch (ParseException ex) {
         throw new RuntimeException(ex);
       }
     }
   }
   if (node instanceof Equality) {
     return compileEqual((Equality) node);
   } else if (node instanceof Less) {
     return compileLess((Less) node);
   } else if (node instanceof Greater) {
     return compileGreater((Greater) node);
   } else if (node instanceof GE) {
     return compileGE((GE) node);
   } else if (node instanceof LE) {
     return compileLE((LE) node);
   } else if (node instanceof Like) {
     return compileLike((Like) node);
   } else {
     throw new IllegalArgumentException("Unsupported node " + node.getClass());
   }
 }
  /**
   * @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;
  }
Exemple #3
0
 static void addFilterOnPrefixedDate(Criteria crit, String prefixedDate, String dateAttribute) {
   Date realDate = null;
   try {
     realDate = ISO8601DateParser.parse(getDateWithoutOp(prefixedDate));
   } catch (ParseException e) {
     // Never occurs, the deploy date format is pre-validated by the filter
   }
   addFilterOnPrefixedDate(crit, prefixedDate, realDate, dateAttribute);
 }
 private int compareInstanceUsingKey(
     String key, ProcessInstanceDAO instanceDAO1, ProcessInstanceDAO instanceDAO2) {
   String s1 = null;
   String s2 = null;
   boolean ascending = true;
   String orderKey = key;
   if (key.startsWith("+") || key.startsWith("-")) {
     orderKey = key.substring(1, key.length());
     if (key.startsWith("-")) ascending = false;
   }
   ProcessDAO process1 = getProcess(instanceDAO1.getProcess().getProcessId());
   ProcessDAO process2 = getProcess(instanceDAO2.getProcess().getProcessId());
   if ("pid".equals(orderKey)) {
     s1 = process1.getProcessId().toString();
     s2 = process2.getProcessId().toString();
   } else if ("name".equals(orderKey)) {
     s1 = process1.getProcessId().getLocalPart();
     s2 = process2.getProcessId().getLocalPart();
   } else if ("namespace".equals(orderKey)) {
     s1 = process1.getProcessId().getNamespaceURI();
     s2 = process2.getProcessId().getNamespaceURI();
   } else if ("version".equals(orderKey)) {
     s1 = "" + process1.getVersion();
     s2 = "" + process2.getVersion();
   } else if ("status".equals(orderKey)) {
     s1 = "" + instanceDAO1.getState();
     s2 = "" + instanceDAO2.getState();
   } else if ("started".equals(orderKey)) {
     s1 = ISO8601DateParser.format(instanceDAO1.getCreateTime());
     s2 = ISO8601DateParser.format(instanceDAO2.getCreateTime());
   } else if ("last-active".equals(orderKey)) {
     s1 = ISO8601DateParser.format(instanceDAO1.getLastActiveTime());
     s2 = ISO8601DateParser.format(instanceDAO2.getLastActiveTime());
   }
   if (ascending) return s1.compareTo(s2);
   else return s2.compareTo(s1);
 }
 public boolean dateMatch(List<String> dateFilters, Date instanceDate, InstanceFilter filter) {
   boolean match = true;
   for (String ddf : dateFilters) {
     String isoDate = ISO8601DateParser.format(instanceDate);
     String critDate = Filter.getDateWithoutOp(ddf);
     if (ddf.startsWith("=")) {
       if (!isoDate.startsWith(critDate)) match = false;
     } else if (ddf.startsWith("<=")) {
       if (!isoDate.startsWith(critDate) && isoDate.compareTo(critDate) > 0) match = false;
     } else if (ddf.startsWith(">=")) {
       if (!isoDate.startsWith(critDate) && isoDate.compareTo(critDate) < 0) match = false;
     } else if (ddf.startsWith("<")) {
       if (isoDate.compareTo(critDate) > 0) match = false;
     } else if (ddf.startsWith(">")) {
       if (isoDate.compareTo(critDate) < 0) match = false;
     }
   }
   return match;
 }
  /**
   * 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();
    }
  }
  protected INEvaluator<String, Criterion, Object> compileIn(final In in) {
    if (in.getIdentifier() instanceof Property) {
      propertyInQuery = true;
      final Property property = (Property) in.getIdentifier();
      return new INEvaluator<String, Criterion, Object>() {
        public Criterion evaluate(Object paramValue) {
          Disjunction disj = Restrictions.disjunction();

          String propertyNS = property.getNamespace();
          String propertyName = property.getName();

          for (Value value : in.getValues()) {
            Conjunction conj = Restrictions.conjunction();
            if (!StringUtils.isEmpty(property.getNamespace())) {
              conj.add(Restrictions.gt(PROPERTY_NS_DB_FIELD, propertyNS));
            }
            conj.add(Restrictions.gt(PROPERTY_NAME_DB_FIELD, propertyName));
            conj.add(Restrictions.gt(PROPERTY_VALUE_DB_FIELD, value.getValue()));

            disj.add(conj);
          }
          return disj;
        };

        public String getIdentifier() {
          return property.toString();
        };
      };
    } else {
      final String fieldName = in.getIdentifier().getName();

      if (INSTANCE_STATUS_FIELD.equals(fieldName)) {
        short noState = 200; // TODO move to constants
        final Disjunction disj = Restrictions.disjunction();

        final Collection values = ValuesHelper.extract((Collection<Value>) in.getValues());

        if (values.contains(STATUS_ACTIVE)) {
          disj.add(Restrictions.eq(INSTANCE_STATUS_DB_FIELD, ProcessState.STATE_NEW));
          disj.add(Restrictions.eq(INSTANCE_STATUS_DB_FIELD, ProcessState.STATE_ACTIVE));
          disj.add(Restrictions.eq(INSTANCE_STATUS_DB_FIELD, ProcessState.STATE_READY));
        }
        if (values.contains(STATUS_SUSPENDED)) {
          disj.add(Restrictions.eq(INSTANCE_STATUS_DB_FIELD, ProcessState.STATE_SUSPENDED));
        }
        if (values.contains(STATUS_ERROR)) {
          disj.add(
              Restrictions.eq(
                  INSTANCE_STATUS_DB_FIELD, noState)); // Error instance state doesn't exist yet
        }
        if (values.contains(STATUS_COMPLETED)) {
          disj.add(Restrictions.eq(INSTANCE_STATUS_DB_FIELD, ProcessState.STATE_COMPLETED_OK));
        }
        if (values.contains(STATUS_TERMINATED)) {
          disj.add(Restrictions.eq(INSTANCE_STATUS_DB_FIELD, ProcessState.STATE_TERMINATED));
        }
        if (values.contains(STATUS_FAULTED)) {
          disj.add(
              Restrictions.eq(INSTANCE_STATUS_DB_FIELD, ProcessState.STATE_COMPLETED_WITH_FAULT));
        }
        return new INEvaluator<String, Criterion, Object>() {
          public Criterion evaluate(Object paramValue) {
            return disj;
          };

          public String getIdentifier() {
            return INSTANCE_STATUS_DB_FIELD;
          };
        };
      } else {
        final Collection objValues;
        final Collection<Value> values = in.getValues();
        if (INSTANCE_ID_FIELD.equals(fieldName)) {
          objValues = new ArrayList<Long>(values.size());
          for (Value value : values) {
            objValues.add(Long.valueOf((String) value.getValue()));
          }
        } else if (INSTANCE_STARTED_FIELD.equals(fieldName)
            || INSTANCE_LAST_ACTIVE_FIELD.equals(fieldName)) {
          objValues = new ArrayList<Date>(values.size());
          try {
            for (Value value : values) {
              objValues.add(ISO8601DateParser.parse((String) value.getValue()));
            }
          } catch (ParseException ex) {
            throw new RuntimeException(ex);
          }
        } else {
          objValues = ValuesHelper.extract((Collection<Value>) values);
        }
        final String dbField = getDBField(fieldName);
        return new INEvaluator<String, Criterion, Object>() {
          /** @see org.apache.ode.ql.eval.skel.CommandEvaluator#evaluate(java.lang.Object) */
          public Criterion evaluate(Object paramValue) {
            return Restrictions.in(dbField, objValues);
          }

          /** @see org.apache.ode.ql.eval.skel.Identified#getIdentifier() */
          public String getIdentifier() {
            return dbField;
          }
        };
      }
    }
  }