Exemplo n.º 1
0
 @Test
 public void PathClassOfTPathOfQString() {
   assertEquals(
       "variable.property",
       Expressions.path(String.class, Expressions.path(Object.class, "variable"), "property")
           .toString());
 }
Exemplo n.º 2
0
  public void testLambdaCallsBinaryOp() {
    // A parameter for the lambda expression.
    ParameterExpression paramExpr = Expressions.parameter(Integer.TYPE, "arg");

    // This expression represents a lambda expression
    // that adds 1 to the parameter value.
    FunctionExpression lambdaExpr =
        Expressions.lambda(
            Expressions.add(paramExpr, Expressions.constant(2)), Arrays.asList(paramExpr));

    // Print out the expression.
    String s = Expressions.toString(lambdaExpr);
    assertEquals(
        "new net.hydromatic.linq4j.function.Function1() {\n"
            + "  public int apply(Integer arg) {\n"
            + "    return arg + 2;\n"
            + "  }\n"
            + "  public Object apply(Object arg) {\n"
            + "    return apply(\n"
            + "      (Integer) arg);\n"
            + "  }\n"
            + "}\n",
        s);

    // Compile and run the lambda expression.
    // The value of the parameter is 1.
    int n = (Integer) lambdaExpr.compile().dynamicInvoke(1);

    // This code example produces the following output:
    //
    // arg => (arg +2)
    // 3
    assertEquals(3, n);
  }
Exemplo n.º 3
0
  public void testCoalesceLong_OM() throws Exception {
    String viewExpr =
        "select coalesce(longBoxed, intBoxed, shortBoxed) as result"
            + " from "
            + SupportBean.class.getName()
            + ".win:length(1000)";

    EPStatementObjectModel model = new EPStatementObjectModel();
    model.setSelectClause(
        SelectClause.create()
            .add(Expressions.coalesce("longBoxed", "intBoxed", "shortBoxed"), "result"));
    model.setFromClause(
        FromClause.create(
            FilterStream.create(SupportBean.class.getName())
                .addView("win", "length", Expressions.constant(1000))));
    model = (EPStatementObjectModel) SerializableObjectCopier.copy(model);
    assertEquals(viewExpr, model.toEPL());

    epService.initialize();
    selectTestView = epService.getEPAdministrator().create(model);
    selectTestView.addListener(testListener);
    assertEquals(Long.class, selectTestView.getEventType().getPropertyType("result"));

    runCoalesceLong();
  }
Exemplo n.º 4
0
 public void testClassDecl() {
   final NewExpression newExpression =
       Expressions.new_(
           Object.class,
           Collections.<Expression>emptyList(),
           Arrays.<MemberDeclaration>asList(
               new FieldDeclaration(
                   Modifier.PUBLIC | Modifier.FINAL,
                   new ParameterExpression(String.class, "foo"),
                   Expressions.constant("bar")),
               new ClassDeclaration(
                   Modifier.PUBLIC | Modifier.STATIC,
                   "MyClass",
                   null,
                   Collections.<Type>emptyList(),
                   Arrays.<MemberDeclaration>asList(
                       new FieldDeclaration(
                           0, new ParameterExpression(int.class, "x"), Expressions.constant(0)))),
               new FieldDeclaration(0, new ParameterExpression(int.class, "i"), null)));
   assertEquals(
       "new Object(){\n"
           + "  public final String foo = \"bar\";\n"
           + "  public static class MyClass {\n"
           + "    int x = 0;\n"
           + "  }\n"
           + "  int i;\n"
           + "}",
       Expressions.toString(newExpression));
 }
Exemplo n.º 5
0
 @Override
 public Expression accept(Visitor visitor) {
   visitor = visitor.preVisit(this);
   final List<Expression> arguments = Expressions.acceptExpressions(this.arguments, visitor);
   final List<MemberDeclaration> memberDeclarations =
       Expressions.acceptMemberDeclarations(this.memberDeclarations, visitor);
   return visitor.visit(this, arguments, memberDeclarations);
 }
Exemplo n.º 6
0
 /**
  * Gets the expression for an input and counts it.
  *
  * @param index Input ordinal
  * @return Expression to which an input should be translated
  */
 private Expression getInput(int index) {
   Slot slot = inputSlots.get(index);
   if (list == null) {
     slot.count++;
   } else {
     if (slot.count > 1 && slot.parameterExpression == null) {
       slot.parameterExpression = Expressions.parameter(slot.expression.type, "current" + index);
       list.add(Expressions.declare(Modifier.FINAL, slot.parameterExpression, slot.expression));
     }
   }
   return slot.parameterExpression != null ? slot.parameterExpression : slot.expression;
 }
Exemplo n.º 7
0
  private Expression translate0(RexNode expr) {
    if (expr instanceof RexInputRef) {
      // TODO: multiple inputs, e.g. joins
      final Expression input = getInput(0);
      final int index = ((RexInputRef) expr).getIndex();
      final List<RelDataTypeField> fields = program.getInputRowType().getFieldList();
      final RelDataTypeField field = fields.get(index);
      if (fields.size() == 1) {
        return input;
      } else if (input.getType() == Object[].class) {
        return Expressions.convert_(
            Expressions.arrayIndex(input, Expressions.constant(field.getIndex())),
            Types.box(JavaRules.EnumUtil.javaClass(typeFactory, field.getType())));
      } else {
        return Expressions.field(input, field.getName());
      }
    }
    if (expr instanceof RexLocalRef) {
      return translate(program.getExprList().get(((RexLocalRef) expr).getIndex()));
    }
    if (expr instanceof RexLiteral) {
      return Expressions.constant(
          ((RexLiteral) expr).getValue(), typeFactory.getJavaClass(expr.getType()));
    }
    if (expr instanceof RexCall) {
      final RexCall call = (RexCall) expr;
      final SqlOperator operator = call.getOperator();
      final ExpressionType expressionType = SQL_TO_LINQ_OPERATOR_MAP.get(operator);
      if (expressionType != null) {
        switch (operator.getSyntax()) {
          case Binary:
            return Expressions.makeBinary(
                expressionType, translate(call.getOperands()[0]), translate(call.getOperands()[1]));
          case Postfix:
          case Prefix:
            return Expressions.makeUnary(expressionType, translate(call.getOperands()[0]));
          default:
            throw new RuntimeException("unknown syntax " + operator.getSyntax());
        }
      }

      Method method = SQL_OP_TO_JAVA_METHOD_MAP.get(operator);
      if (method != null) {
        List<Expression> exprs = translateList(Arrays.asList(call.operands));
        return !Modifier.isStatic(method.getModifiers())
            ? Expressions.call(exprs.get(0), method, exprs.subList(1, exprs.size()))
            : Expressions.call(method, exprs);
      }

      switch (expr.getKind()) {
        default:
          throw new RuntimeException("cannot translate expression " + expr);
      }
    }
    throw new RuntimeException("cannot translate expression " + expr);
  }
Exemplo n.º 8
0
 /** Returns the expression for a sub-schema. */
 public static Expression subSchemaExpression(Schema schema, String name, Class type) {
   // (Type) schemaExpression.getSubSchema("name")
   Expression call =
       Expressions.call(
           schema.getExpression(),
           BuiltinMethod.SCHEMA_GET_SUB_SCHEMA.method,
           Expressions.constant(name));
   // CHECKSTYLE: IGNORE 2
   //noinspection unchecked
   if (false && type != null && !type.isAssignableFrom(Schema.class)) {
     return unwrap(call, type);
   }
   return call;
 }
  public static void setRHSValue(
      boolean isDecl,
      Stmt decl_or_assgn,
      TIRAbstractAssignStmt node,
      boolean isScalar,
      IRx10ASTGenerator target) {

    if (isDecl) {

      ((DeclStmt) decl_or_assgn).setRHS(Expressions.makeIRx10Exp(node.getRHS(), isScalar, target));
    } else {
      ((AssignStmt) decl_or_assgn)
          .setRHS(Expressions.makeIRx10Exp(node.getRHS(), isScalar, target));
    }
  }
  @Test
  public void Serialization() throws IOException, ClassNotFoundException {
    StringPath expr = Expressions.stringPath("str");
    metadata.addJoin(JoinType.DEFAULT, expr);
    metadata.addFlag(new QueryFlag(Position.AFTER_FILTERS, ""));
    metadata.addGroupBy(expr);
    metadata.addHaving(expr.isEmpty());
    //        metadata.getJoins().get(0).addFlag(new JoinFlag(""));
    metadata.addJoinCondition(expr.isEmpty());
    metadata.addOrderBy(expr.asc());
    metadata.setProjection(expr);
    metadata.addWhere(expr.isEmpty());

    QueryMetadata metadata2 = Serialization.serialize(metadata);

    assertEquals(metadata.getFlags(), metadata2.getFlags());
    assertEquals(metadata.getGroupBy().get(0), metadata2.getGroupBy().get(0));
    assertEquals(metadata.getGroupBy(), metadata2.getGroupBy());
    assertEquals(metadata.getHaving(), metadata2.getHaving());
    assertEquals(metadata.getJoins(), metadata2.getJoins());
    assertEquals(metadata.getModifiers(), metadata2.getModifiers());
    assertEquals(metadata.getOrderBy(), metadata2.getOrderBy());
    assertEquals(metadata.getParams(), metadata2.getParams());
    assertEquals(metadata.getProjection(), metadata2.getProjection());
    assertEquals(metadata.getWhere(), metadata2.getWhere());
  }
Exemplo n.º 11
0
    @Override
    protected PreparedExecution implement(
        RelDataType rowType,
        RelNode rootRel,
        SqlKind sqlKind,
        ClassDeclaration decl,
        Argument[] args) {
      RelDataType resultType = rootRel.getRowType();
      boolean isDml = sqlKind.belongsTo(SqlKind.DML);
      javaCompiler = createCompiler();
      EnumerableRelImplementor relImplementor =
          getRelImplementor(rootRel.getCluster().getRexBuilder());
      BlockExpression expr = relImplementor.implementRoot((EnumerableRel) rootRel);
      ParameterExpression root0 = Expressions.parameter(DataContext.class, "root0");
      String s =
          Expressions.toString(
              Blocks.create(
                  Expressions.declare(
                      Modifier.FINAL, (ParameterExpression) schema.getExpression(), root0),
                  expr),
              false);

      final Executable executable;
      try {
        executable =
            (Executable)
                ExpressionEvaluator.createFastScriptEvaluator(
                    s, Executable.class, new String[] {root0.name});
      } catch (Exception e) {
        throw Helper.INSTANCE.wrap("Error while compiling generated Java code:\n" + s, e);
      }

      if (timingTracer != null) {
        timingTracer.traceTime("end codegen");
      }

      if (timingTracer != null) {
        timingTracer.traceTime("end compilation");
      }

      return new PreparedExecution(
          null, rootRel, resultType, isDml, mapTableModOp(isDml, sqlKind), null) {
        public Object execute() {
          return executable.execute(schema);
        }
      };
    }
Exemplo n.º 12
0
  public void testUnfilteredStreamPrior_OM() throws Exception {
    EPStatementObjectModel subquery = new EPStatementObjectModel();
    subquery.setSelectClause(SelectClause.create().add(Expressions.prior(0, "id")));
    subquery.setFromClause(
        FromClause.create(
            FilterStream.create("S1").addView("win", "length", Expressions.constant(1000))));

    EPStatementObjectModel model = new EPStatementObjectModel();
    model.setSelectClause(SelectClause.create().add(Expressions.subquery(subquery), "idS1"));
    model.setFromClause(FromClause.create(FilterStream.create("S0")));
    model = (EPStatementObjectModel) SerializableObjectCopier.copy(model);

    String stmtText = "select (select prior(0, id) from S1.win:length(1000)) as idS1 from S0";
    assertEquals(stmtText, model.toEPL());
    EPStatement stmt = epService.getEPAdministrator().create(model);
    runUnfilteredStreamPrior(stmt);
  }
Exemplo n.º 13
0
  public void testCompile() throws NoSuchMethodException {
    // Creating a parameter for the expression tree.
    ParameterExpression param = Expressions.parameter(String.class);

    // Creating an expression for the method call and specifying its
    // parameter.
    MethodCallExpression methodCall =
        Expressions.call(Integer.class, "valueOf", Collections.<Expression>singletonList(param));

    // The following statement first creates an expression tree,
    // then compiles it, and then runs it.
    int x =
        Expressions.<Function1<String, Integer>>lambda(
                methodCall, new ParameterExpression[] {param})
            .getFunction()
            .apply("1234");
    assertEquals(1234, x);
  }
Exemplo n.º 14
0
 public void testWriteArray() {
   assertEquals(
       "1 + integers[2 + index]",
       Expressions.toString(
           Expressions.add(
               Expressions.constant(1),
               Expressions.arrayIndex(
                   Expressions.variable(int[].class, "integers"),
                   Expressions.add(
                       Expressions.constant(2), Expressions.variable(int.class, "index"))))));
 }
Exemplo n.º 15
0
 /** Returns the expression to access a table within a schema. */
 public static Expression tableExpression(
     Schema schema, Type elementType, String tableName, Class clazz) {
   final MethodCallExpression expression;
   if (Table.class.isAssignableFrom(clazz)) {
     expression =
         Expressions.call(
             schema.getExpression(),
             BuiltinMethod.SCHEMA_GET_TABLE.method,
             Expressions.constant(tableName));
   } else {
     expression =
         Expressions.call(
             BuiltinMethod.SCHEMAS_QUERYABLE.method,
             DataContext.ROOT,
             schema.getExpression(),
             Expressions.constant(elementType),
             Expressions.constant(tableName));
   }
   return Types.castIfNecessary(clazz, expression);
 }
Exemplo n.º 16
0
 @Test
 public void roundtrip() throws Exception {
   Path<?> path = ExpressionUtils.path(Object.class, "entity");
   SimplePath<?> path2 = Expressions.path(Object.class, "entity");
   assertEquals(path, serialize(path));
   assertEquals(path2, serialize(path2));
   assertEquals(path2.isNull(), serialize(path2.isNull()));
   assertEquals(path.hashCode(), serialize(path).hashCode());
   assertEquals(path2.hashCode(), serialize(path2).hashCode());
   assertEquals(path2.isNull().hashCode(), serialize(path2.isNull()).hashCode());
 }
Exemplo n.º 17
0
 private Expression translate(RexNode expr) {
   Slot slot = map.get(expr);
   if (slot == null) {
     Expression expression = translate0(expr);
     assert expression != null;
     final ParameterExpression parameter;
     if (!inlineRexSet.contains(expr) && !(expr instanceof RexLocalRef)) {
       parameter = Expressions.parameter(expression.getType(), "v" + map.size());
     } else {
       parameter = null;
     }
     slot = new Slot(parameter, expression);
     if (parameter != null && list != null) {
       list.add(Expressions.declare(Modifier.FINAL, slot.parameterExpression, slot.expression));
     }
     map.put(expr, slot);
   }
   slot.count++;
   return slot.parameterExpression != null ? slot.parameterExpression : slot.expression;
 }
Exemplo n.º 18
0
  public void testWriteConstant() {
    // primitives
    assertEquals(
        "new int[] {\n" + "  1,\n" + "  2,\n" + "  -1}",
        Expressions.toString(Expressions.constant(new int[] {1, 2, -1})));

    // objects and nulls
    assertEquals(
        "new String[] {\n" + "  \"foo\",\n" + "  null}",
        Expressions.toString(Expressions.constant(new String[] {"foo", null})));

    // automatically call constructor if it matches fields
    assertEquals(
        "new net.hydromatic.linq4j.test.Linq4jTest.Employee[] {\n"
            + "  new net.hydromatic.linq4j.test.Linq4jTest.Employee(\n"
            + "    100,\n"
            + "    \"Fred\",\n"
            + "    10),\n"
            + "  new net.hydromatic.linq4j.test.Linq4jTest.Employee(\n"
            + "    110,\n"
            + "    \"Bill\",\n"
            + "    30),\n"
            + "  new net.hydromatic.linq4j.test.Linq4jTest.Employee(\n"
            + "    120,\n"
            + "    \"Eric\",\n"
            + "    10),\n"
            + "  new net.hydromatic.linq4j.test.Linq4jTest.Employee(\n"
            + "    130,\n"
            + "    \"Janet\",\n"
            + "    10)}",
        Expressions.toString(Expressions.constant(Linq4jTest.emps)));
  }
Exemplo n.º 19
0
  public void testVariantOneOMToStmt() throws Exception {
    EPStatementObjectModel model = new EPStatementObjectModel();
    model.setInsertInto(InsertIntoClause.create("Event_1", "delta", "product"));
    model.setSelectClause(
        SelectClause.create()
            .add(Expressions.minus("intPrimitive", "intBoxed"), "deltaTag")
            .add(Expressions.multiply("intPrimitive", "intBoxed"), "productTag"));
    model.setFromClause(
        FromClause.create(
            FilterStream.create(SupportBean.class.getName())
                .addView(View.create("win", "length", Expressions.constant(100)))));
    model = (EPStatementObjectModel) SerializableObjectCopier.copy(model);

    EPStatement stmt = runAsserts(null, model);

    String epl =
        "insert into Event_1(delta, product) "
            + "select intPrimitive - intBoxed as deltaTag, intPrimitive * intBoxed as productTag "
            + "from "
            + SupportBean.class.getName()
            + ".win:length(100)";
    assertEquals(epl, model.toEPL());
    assertEquals(epl, stmt.getText());
  }
Exemplo n.º 20
0
  public void testLambdaCallsTwoArgMethod() throws NoSuchMethodException {
    // A parameter for the lambda expression.
    ParameterExpression paramS = Expressions.parameter(String.class, "s");
    ParameterExpression paramBegin = Expressions.parameter(Integer.TYPE, "begin");
    ParameterExpression paramEnd = Expressions.parameter(Integer.TYPE, "end");

    // This expression represents a lambda expression
    // that adds 1 to the parameter value.
    FunctionExpression lambdaExpr =
        Expressions.lambda(
            Expressions.call(
                paramS,
                String.class.getMethod("substring", Integer.TYPE, Integer.TYPE),
                paramBegin,
                paramEnd),
            paramS,
            paramBegin,
            paramEnd);

    // Compile and run the lambda expression.
    String s = (String) lambdaExpr.compile().dynamicInvoke("hello world", 3, 7);

    assertEquals("lo w", s);
  }
Exemplo n.º 21
0
 public RexNode toRex(Expression expression) {
   switch (expression.getNodeType()) {
     case MemberAccess:
       return rexBuilder.makeFieldAccess(
           toRex(((MemberExpression) expression).expression),
           ((MemberExpression) expression).field.getName());
     case GreaterThan:
       return binary(expression, SqlStdOperatorTable.greaterThanOperator);
     case LessThan:
       return binary(expression, SqlStdOperatorTable.lessThanOperator);
     case Parameter:
       return parameter((ParameterExpression) expression);
     case Call:
       MethodCallExpression call = (MethodCallExpression) expression;
       SqlOperator operator = RexToLixTranslator.JAVA_TO_SQL_METHOD_MAP.get(call.method);
       if (operator != null) {
         return rexBuilder.makeCall(
             operator,
             toRex(
                 Expressions.<Expression>list()
                     .appendIfNotNull(call.targetExpression)
                     .appendAll(call.expressions)));
       }
       throw new RuntimeException("Could translate call to method " + call.method);
     case Constant:
       final ConstantExpression constant = (ConstantExpression) expression;
       Object value = constant.value;
       if (value instanceof Number) {
         Number number = (Number) value;
         if (value instanceof Double || value instanceof Float) {
           return rexBuilder.makeApproxLiteral(BigDecimal.valueOf(number.doubleValue()));
         } else if (value instanceof BigDecimal) {
           return rexBuilder.makeExactLiteral((BigDecimal) value);
         } else {
           return rexBuilder.makeExactLiteral(BigDecimal.valueOf(number.longValue()));
         }
       } else if (value instanceof Boolean) {
         return rexBuilder.makeLiteral((Boolean) value);
       } else {
         return rexBuilder.makeLiteral(constant.toString());
       }
     default:
       throw new UnsupportedOperationException(
           "unknown expression type " + expression.getNodeType() + " " + expression);
   }
 }
Exemplo n.º 22
0
  @Test
  public void expressions() throws Exception {
    Map<Class<?>, Object> args = Maps.newHashMap();
    args.put(Object.class, "obj");
    args.put(BeanPath.class, new EntityPathBase<Object>(Object.class, "obj"));
    args.put(Class.class, Integer.class);
    args.put(Class[].class, new Class<?>[] {Object.class, Object.class});
    args.put(java.util.Date.class, new java.util.Date(0));
    args.put(java.sql.Date.class, new java.sql.Date(0));
    args.put(java.sql.Time.class, new java.sql.Time(0));
    args.put(java.sql.Timestamp.class, new java.sql.Timestamp(0));
    args.put(Expression.class, Expressions.enumPath(Gender.class, "e"));
    args.put(
        Expression[].class,
        new Expression<?>[] {Expressions.enumPath(Gender.class, "e"), Expressions.stringPath("s")});
    args.put(FactoryExpression.class, Projections.tuple(Expressions.stringPath("str")));
    args.put(GroupExpression.class, GroupBy.avg(Expressions.numberPath(Integer.class, "num")));
    args.put(Number.class, 1);
    args.put(Operator.class, Ops.AND);
    args.put(Path.class, Expressions.stringPath("str"));
    args.put(PathBuilderValidator.class, PathBuilderValidator.DEFAULT);
    args.put(PathMetadata.class, PathMetadataFactory.forVariable("obj"));
    args.put(PathInits.class, PathInits.DEFAULT);
    args.put(Predicate.class, Expressions.path(Object.class, "obj").isNull());
    args.put(QueryMetadata.class, new DefaultQueryMetadata());
    args.put(String.class, "obj");

    Reflections reflections = new Reflections();
    Set<Class<? extends Expression>> types = reflections.getSubTypesOf(Expression.class);
    for (Class<?> type : types) {
      if (!type.isInterface()
          && !type.isMemberClass()
          && !Modifier.isAbstract(type.getModifiers())) {
        for (Constructor<?> c : type.getConstructors()) {
          Object[] parameters = new Object[c.getParameterTypes().length];
          for (int i = 0; i < c.getParameterTypes().length; i++) {
            parameters[i] =
                Objects.requireNonNull(
                    args.get(c.getParameterTypes()[i]), c.getParameterTypes()[i].getName());
          }
          c.setAccessible(true);
          Object o = c.newInstance(parameters);
          assertEquals(o, Serialization.serialize(o));
        }
      }
    }
  }
Exemplo n.º 23
0
 public void testBlockBuilder() {
   BlockBuilder statements = new BlockBuilder();
   Expression one = statements.append("one", Expressions.constant(1));
   Expression two = statements.append("two", Expressions.constant(2));
   Expression three = statements.append("three", Expressions.add(one, two));
   Expression six = statements.append("six", Expressions.multiply(three, two));
   Expression eighteen = statements.append("eighteen", Expressions.multiply(three, six));
   statements.add(Expressions.return_(null, eighteen));
   assertEquals(
       "{\n"
           + "  final int three = 1 + 2;\n"
           + "  final int six = three * 2;\n"
           + "  final int eighteen = three * six;\n"
           + "  return eighteen;\n"
           + "}\n",
       Expressions.toString(statements.toBlock()));
 }
Exemplo n.º 24
0
 public void testBlockBuilder2() {
   BlockBuilder statements = new BlockBuilder();
   Expression element = statements.append("element", Expressions.constant(null));
   Expression comparator =
       statements.append("comparator", Expressions.constant(null, Comparator.class));
   Expression treeSet =
       statements.append("treeSet", Expressions.new_(TreeSet.class, Arrays.asList(comparator)));
   statements.add(Expressions.return_(null, Expressions.call(treeSet, "add", element)));
   assertEquals(
       "{\n"
           + "  final java.util.Comparator comparator = null;\n"
           + "  final java.util.TreeSet treeSet = new java.util.TreeSet(\n"
           + "    comparator);\n"
           + "  return treeSet.add(null);\n"
           + "}\n",
       Expressions.toString(statements.toBlock()));
 }
  @Override
  public RecordValue variable(GimpleVarDecl decl, VarAllocator allocator) {

    JLValue instance =
        allocator.reserve(decl.getName(), layout.getType(), new RecordConstructor(this));

    if (isUnitPointer()) {
      // If we are using the RecordUnitPtr strategy, then the record value is also it's address
      return new RecordValue(instance, new RecordUnitPtr(instance));

    } else if (decl.isAddressable()) {
      JLValue unitArray =
          allocator.reserveUnitArray(
              decl.getName(), layout.getType(), Optional.of((JExpr) instance));
      FatPtrPair address = new FatPtrPair(new RecordClassValueFunction(this), unitArray);
      JExpr value = Expressions.elementAt(address.getArray(), 0);
      return new RecordValue(value, address);

    } else {

      return new RecordValue(instance);
    }
  }
 /* (non-Javadoc)
  * @see Expression#evaluate(IVariablePool)
  */
 public EvaluationResult evaluate(IEvaluationContext context) throws CoreException {
   if (fTypeName == null) return EvaluationResult.FALSE;
   Object var = context.getDefaultVariable();
   Object adapted = null;
   IAdapterManager manager = Platform.getAdapterManager();
   if (Expressions.isInstanceOf(var, fTypeName)) {
     adapted = var;
   } else {
     if (manager.hasAdapter(var, fTypeName)) {
       adapted = manager.getAdapter(var, fTypeName);
     } else {
       // if the adapter manager doesn't have an adapter contributed,
       // try to see if the variable itself implements IAdaptable
       if (var instanceof IAdaptable) {
         try {
           Class typeClazz = Class.forName(fTypeName, false, var.getClass().getClassLoader());
           adapted = ((IAdaptable) var).getAdapter(typeClazz);
         } catch (ClassNotFoundException e) {
         }
       }
       if (adapted == null) {
         // all attempts failed, return false
         return EvaluationResult.FALSE;
       }
     }
   }
   // the adapted result is null but hasAdapter returned true check
   // if the adapter is loaded.
   if (adapted == null) {
     if (manager.queryAdapter(var, fTypeName) == IAdapterManager.NOT_LOADED) {
       return EvaluationResult.NOT_LOADED;
     } else {
       return EvaluationResult.FALSE;
     }
   }
   return evaluateAnd(new DefaultVariable(context, adapted));
 }
Exemplo n.º 27
0
  @Test
  public void testSODA() {
    // should say fieldsTypes, maybe with object/component prefix
    Map<String, Object> eventTypes = new HashMap<>();
    eventTypes.put(LITERAL_SYMBOL, String.class);
    eventTypes.put(LITERAL_PRICE, Integer.class);

    EPStatementObjectModel model = new EPStatementObjectModel();
    model.setInsertInto(InsertIntoClause.create(LITERAL_RETURN_OBJ));
    model.setSelectClause(
        SelectClause.create().add(Expressions.avg(LITERAL_PRICE), LITERAL_AVG).add(LITERAL_PRICE));
    Filter filter = Filter.create("quotes_default", Expressions.eq(LITERAL_SYMBOL, "A"));
    model.setFromClause(
        FromClause.create(
            FilterStream.create(filter).addView("win", "length", Expressions.constant(2))));
    model.setHavingClause(
        Expressions.gt(Expressions.avg(LITERAL_PRICE), Expressions.constant(60.0)));

    TopologyBuilder builder = new TopologyBuilder();
    builder.setSpout(LITERAL_QUOTES, new RandomSentenceSpout());
    builder
        .setBolt(
            LITERAL_ESPER,
            (new EsperBolt())
                .addEventTypes(eventTypes)
                .addOutputTypes(
                    Collections.singletonMap(
                        LITERAL_RETURN_OBJ, Arrays.asList(LITERAL_AVG, LITERAL_PRICE)))
                .addObjectStatemens(Collections.singleton(model)))
        .shuffleGrouping(LITERAL_QUOTES);
    builder.setBolt("print", new PrinterBolt()).shuffleGrouping(LITERAL_ESPER, LITERAL_RETURN_OBJ);

    Config conf = new Config();
    LocalCluster cluster = new LocalCluster();
    cluster.submitTopology("test", conf, builder.createTopology());
    Utils.sleep(10000);
    cluster.shutdown();
    assertEquals(resultSODA.get(100), new Double(75.0));
    assertEquals(resultSODA.get(50), new Double(75.0));
  }
Exemplo n.º 28
0
  public void testMinMaxWindowStats_OM() throws Exception {
    String viewExpr =
        "select max(longBoxed, intBoxed) as myMax, "
            + "max(longBoxed, intBoxed, shortBoxed) as myMaxEx, "
            + "min(longBoxed, intBoxed) as myMin, "
            + "min(longBoxed, intBoxed, shortBoxed) as myMinEx"
            + " from "
            + SupportBean.class.getName()
            + ".win:length(3)";

    EPStatementObjectModel model = new EPStatementObjectModel();
    model.setSelectClause(
        SelectClause.create()
            .add(Expressions.max("longBoxed", "intBoxed"), "myMax")
            .add(
                Expressions.max(
                    Expressions.property("longBoxed"),
                    Expressions.property("intBoxed"),
                    Expressions.property("shortBoxed")),
                "myMaxEx")
            .add(Expressions.min("longBoxed", "intBoxed"), "myMin")
            .add(
                Expressions.min(
                    Expressions.property("longBoxed"),
                    Expressions.property("intBoxed"),
                    Expressions.property("shortBoxed")),
                "myMinEx"));
    model.setFromClause(
        FromClause.create(
            FilterStream.create(SupportBean.class.getName())
                .addView("win", "length", Expressions.constant(3))));
    model = (EPStatementObjectModel) SerializableObjectCopier.copy(model);
    assertEquals(viewExpr, model.toEPL());

    selectTestView = epService.getEPAdministrator().create(model);
    selectTestView.addListener(testListener);
    testListener.reset();

    runMinMaxWindowStats();
  }
 public AdaptExpression(Element element) throws CoreException {
   fTypeName = element.getAttribute(ATT_TYPE);
   Expressions.checkAttribute(ATT_TYPE, fTypeName.length() > 0 ? fTypeName : null);
 }
 public AdaptExpression(IConfigurationElement configElement) throws CoreException {
   fTypeName = configElement.getAttribute(ATT_TYPE);
   Expressions.checkAttribute(ATT_TYPE, fTypeName);
 }