public ExprNode validate(ExprValidationContext validationContext) throws ExprValidationException {
    // Must have 2 child nodes
    if (this.getChildNodes().length < 1) {
      throw new IllegalStateException("Group relational op node must have 1 or more parameters");
    }
    evaluators = ExprNodeUtility.getEvaluators(this.getChildNodes());

    Class typeOne = JavaClassHelper.getBoxedType(evaluators[0].getType());

    // collections, array or map not supported
    if ((typeOne.isArray())
        || (JavaClassHelper.isImplementsInterface(typeOne, Collection.class))
        || (JavaClassHelper.isImplementsInterface(typeOne, Map.class))) {
      throw new ExprValidationException(
          "Collection or array comparison is not allowed for the IN, ANY, SOME or ALL keywords");
    }

    List<Class> comparedTypes = new ArrayList<Class>();
    comparedTypes.add(typeOne);
    hasCollectionOrArray = false;
    for (int i = 0; i < this.getChildNodes().length - 1; i++) {
      Class propType = evaluators[i + 1].getType();
      if (propType.isArray()) {
        hasCollectionOrArray = true;
        if (propType.getComponentType() != Object.class) {
          comparedTypes.add(propType.getComponentType());
        }
      } else if (JavaClassHelper.isImplementsInterface(propType, Collection.class)) {
        hasCollectionOrArray = true;
      } else if (JavaClassHelper.isImplementsInterface(propType, Map.class)) {
        hasCollectionOrArray = true;
      } else {
        comparedTypes.add(propType);
      }
    }

    // Determine common denominator type
    Class coercionType;
    try {
      coercionType =
          JavaClassHelper.getCommonCoercionType(
              comparedTypes.toArray(new Class[comparedTypes.size()]));
    } catch (CoercionException ex) {
      throw new ExprValidationException("Implicit conversion not allowed: " + ex.getMessage());
    }

    // Must be either numeric or string
    if (coercionType != String.class) {
      if (!JavaClassHelper.isNumeric(coercionType)) {
        throw new ExprValidationException(
            "Implicit conversion from datatype '"
                + coercionType.getSimpleName()
                + "' to numeric is not allowed");
      }
    }

    computer = relationalOpEnum.getComputer(coercionType, coercionType, coercionType);
    return null;
  }
Exemplo n.º 2
0
  public IntervalOpImpl(
      DatetimeMethodEnum method,
      String methodNameUse,
      EventType[] typesPerStream,
      List<ExprNode> expressions)
      throws ExprValidationException {

    ExprEvaluator evaluatorEndTimestamp = null;
    Class timestampType;

    if (expressions.get(0) instanceof ExprStreamUnderlyingNode) {
      ExprStreamUnderlyingNode und = (ExprStreamUnderlyingNode) expressions.get(0);
      parameterStreamNum = und.getStreamId();
      EventType type = typesPerStream[parameterStreamNum];
      parameterPropertyStart = type.getStartTimestampPropertyName();
      if (parameterPropertyStart == null) {
        throw new ExprValidationException(
            "For date-time method '"
                + methodNameUse
                + "' the first parameter is event type '"
                + type.getName()
                + "', however no timestamp property has been defined for this event type");
      }

      timestampType = type.getPropertyType(parameterPropertyStart);
      EventPropertyGetter getter = type.getGetter(parameterPropertyStart);
      evaluatorTimestamp = new ExprEvaluatorStreamLongProp(parameterStreamNum, getter);

      if (type.getEndTimestampPropertyName() != null) {
        parameterPropertyEnd = type.getEndTimestampPropertyName();
        EventPropertyGetter getterEndTimestamp = type.getGetter(type.getEndTimestampPropertyName());
        evaluatorEndTimestamp =
            new ExprEvaluatorStreamLongProp(parameterStreamNum, getterEndTimestamp);
      } else {
        parameterPropertyEnd = parameterPropertyStart;
      }
    } else {
      evaluatorTimestamp = expressions.get(0).getExprEvaluator();
      timestampType = evaluatorTimestamp.getType();

      if (expressions.get(0) instanceof ExprIdentNode) {
        ExprIdentNode identNode = (ExprIdentNode) expressions.get(0);
        parameterStreamNum = identNode.getStreamId();
        parameterPropertyStart = identNode.getResolvedPropertyName();
        parameterPropertyEnd = parameterPropertyStart;
      }

      if (!JavaClassHelper.isDatetimeClass(evaluatorTimestamp.getType())) {
        throw new ExprValidationException(
            "For date-time method '"
                + methodNameUse
                + "' the first parameter expression returns '"
                + evaluatorTimestamp.getType()
                + "', however requires a Date, Calendar, Long-type return value or event (with timestamp)");
      }
    }

    IntervalComputer intervalComputer = IntervalComputerFactory.make(method, expressions);

    // evaluation without end timestamp
    if (evaluatorEndTimestamp == null) {
      if (JavaClassHelper.isSubclassOrImplementsInterface(timestampType, Calendar.class)) {
        intervalOpEval = new IntervalOpEvalCal(intervalComputer);
      } else if (JavaClassHelper.isSubclassOrImplementsInterface(timestampType, Date.class)) {
        intervalOpEval = new IntervalOpEvalDate(intervalComputer);
      } else if (JavaClassHelper.getBoxedType(timestampType) == Long.class) {
        intervalOpEval = new IntervalOpEvalLong(intervalComputer);
      } else {
        throw new IllegalArgumentException(
            "Invalid interval first parameter type '" + timestampType + "'");
      }
    } else {
      if (JavaClassHelper.isSubclassOrImplementsInterface(timestampType, Calendar.class)) {
        intervalOpEval = new IntervalOpEvalCalWithEnd(intervalComputer, evaluatorEndTimestamp);
      } else if (JavaClassHelper.isSubclassOrImplementsInterface(timestampType, Date.class)) {
        intervalOpEval = new IntervalOpEvalDateWithEnd(intervalComputer, evaluatorEndTimestamp);
      } else if (JavaClassHelper.getBoxedType(timestampType) == Long.class) {
        intervalOpEval = new IntervalOpEvalLongWithEnd(intervalComputer, evaluatorEndTimestamp);
      } else {
        throw new IllegalArgumentException(
            "Invalid interval first parameter type '" + timestampType + "'");
      }
    }
  }
  /**
   * Ctor.
   *
   * @param assignments the list of variable assignments
   * @param variableService variable service
   * @param eventAdapterService event adapters
   * @throws com.espertech.esper.epl.expression.core.ExprValidationException when variables cannot
   *     be found
   */
  public VariableReadWritePackage(
      List<OnTriggerSetAssignment> assignments,
      VariableService variableService,
      EventAdapterService eventAdapterService)
      throws ExprValidationException {
    this.metaData = new VariableMetaData[assignments.size()];
    this.readersForGlobalVars = new VariableReader[assignments.size()];
    this.mustCoerce = new boolean[assignments.size()];
    this.writers = new WriteDesc[assignments.size()];

    this.variableTypes = new HashMap<String, Object>();
    this.eventAdapterService = eventAdapterService;
    this.variableService = variableService;

    Map<EventTypeSPI, CopyMethodDesc> eventTypeWrittenProps =
        new HashMap<EventTypeSPI, CopyMethodDesc>();
    int count = 0;
    List<VariableTriggerSetDesc> assignmentList = new ArrayList<VariableTriggerSetDesc>();

    for (OnTriggerSetAssignment expressionWithAssignments : assignments) {
      Pair<String, ExprNode> possibleVariableAssignment =
          ExprNodeUtility.checkGetAssignmentToVariableOrProp(
              expressionWithAssignments.getExpression());
      if (possibleVariableAssignment == null) {
        throw new ExprValidationException(
            "Missing variable assignment expression in assignment number " + count);
      }
      assignmentList.add(
          new VariableTriggerSetDesc(
              possibleVariableAssignment.getFirst(),
              possibleVariableAssignment.getSecond().getExprEvaluator()));

      String fullVariableName = possibleVariableAssignment.getFirst();
      String variableName = fullVariableName;
      String subPropertyName = null;

      int indexOfDot = variableName.indexOf('.');
      if (indexOfDot != -1) {
        subPropertyName = variableName.substring(indexOfDot + 1, variableName.length());
        variableName = variableName.substring(0, indexOfDot);
      }

      VariableMetaData variableMetadata = variableService.getVariableMetaData(variableName);
      metaData[count] = variableMetadata;
      if (variableMetadata == null) {
        throw new ExprValidationException(
            "Variable by name '" + variableName + "' has not been created or configured");
      }
      if (variableMetadata.isConstant()) {
        throw new ExprValidationException(
            "Variable by name '" + variableName + "' is declared constant and may not be set");
      }
      if (variableMetadata.getContextPartitionName() == null) {
        readersForGlobalVars[count] =
            variableService.getReader(variableName, VariableService.NOCONTEXT_AGENTINSTANCEID);
      }

      if (subPropertyName != null) {
        if (variableMetadata.getEventType() == null) {
          throw new ExprValidationException(
              "Variable by name '"
                  + variableName
                  + "' does not have a property named '"
                  + subPropertyName
                  + "'");
        }
        EventType type = variableMetadata.getEventType();
        if (!(type instanceof EventTypeSPI)) {
          throw new ExprValidationException(
              "Variable by name '"
                  + variableName
                  + "' event type '"
                  + type.getName()
                  + "' not writable");
        }
        EventTypeSPI spi = (EventTypeSPI) type;
        EventPropertyWriter writer = spi.getWriter(subPropertyName);
        EventPropertyGetter getter = spi.getGetter(subPropertyName);
        if (writer == null) {
          throw new ExprValidationException(
              "Variable by name '"
                  + variableName
                  + "' the property '"
                  + subPropertyName
                  + "' is not writable");
        }

        variableTypes.put(fullVariableName, spi.getPropertyType(subPropertyName));
        CopyMethodDesc writtenProps = eventTypeWrittenProps.get(spi);
        if (writtenProps == null) {
          writtenProps = new CopyMethodDesc(variableName, new ArrayList<String>());
          eventTypeWrittenProps.put(spi, writtenProps);
        }
        writtenProps.getPropertiesCopied().add(subPropertyName);

        writers[count] = new WriteDesc(spi, variableName, writer, getter);
      } else {

        // determine types
        Class expressionType = possibleVariableAssignment.getSecond().getExprEvaluator().getType();

        if (variableMetadata.getEventType() != null) {
          if ((expressionType != null)
              && (!JavaClassHelper.isSubclassOrImplementsInterface(
                  expressionType, variableMetadata.getEventType().getUnderlyingType()))) {
            throw new VariableValueException(
                "Variable '"
                    + variableName
                    + "' of declared event type '"
                    + variableMetadata.getEventType().getName()
                    + "' underlying type '"
                    + variableMetadata.getEventType().getUnderlyingType().getName()
                    + "' cannot be assigned a value of type '"
                    + expressionType.getName()
                    + "'");
          }
          variableTypes.put(variableName, variableMetadata.getEventType().getUnderlyingType());
        } else {

          Class variableType = variableMetadata.getType();
          variableTypes.put(variableName, variableType);

          // determine if the expression type can be assigned
          if (variableType != java.lang.Object.class) {
            if ((JavaClassHelper.getBoxedType(expressionType) != variableType)
                && (expressionType != null)) {
              if ((!JavaClassHelper.isNumeric(variableType))
                  || (!JavaClassHelper.isNumeric(expressionType))) {
                throw new ExprValidationException(
                    VariableServiceUtil.getAssigmentExMessage(
                        variableName, variableType, expressionType));
              }

              if (!(JavaClassHelper.canCoerce(expressionType, variableType))) {
                throw new ExprValidationException(
                    VariableServiceUtil.getAssigmentExMessage(
                        variableName, variableType, expressionType));
              }

              mustCoerce[count] = true;
            }
          }
        }
      }

      count++;
    }

    this.assignments = assignmentList.toArray(new VariableTriggerSetDesc[assignmentList.size()]);

    if (eventTypeWrittenProps.isEmpty()) {
      copyMethods = Collections.EMPTY_MAP;
      return;
    }

    copyMethods = new HashMap<EventTypeSPI, EventBeanCopyMethod>();
    for (Map.Entry<EventTypeSPI, CopyMethodDesc> entry : eventTypeWrittenProps.entrySet()) {
      List<String> propsWritten = entry.getValue().getPropertiesCopied();
      String[] props = propsWritten.toArray(new String[propsWritten.size()]);
      EventBeanCopyMethod copyMethod = entry.getKey().getCopyMethod(props);
      if (copyMethod == null) {
        throw new ExprValidationException(
            "Variable '"
                + entry.getValue().getVariableName()
                + "' of declared type "
                + JavaClassHelper.getClassNameFullyQualPretty(entry.getKey().getUnderlyingType())
                + "' cannot be assigned to");
      }
      copyMethods.put(entry.getKey(), copyMethod);
    }
  }