예제 #1
0
  public void testEgressType() {
    ExpressionCompiler compiler = new ExpressionCompiler("( $cheese )");
    ParserContext context = new ParserContext();
    context.addInput("$cheese", Cheese.class);

    assertEquals(Cheese.class, compiler.compile(context).getKnownEgressType());
  }
예제 #2
0
  public void testSetCoercion2() {
    ParserContext ctx = new ParserContext();
    ctx.setStrongTyping(true);
    ctx.addInput("sampleBean", SampleBean.class);

    Serializable s = compileSetExpression("sampleBean.map2['bleh']", ctx);

    Foo foo = new Foo();
    executeSetExpression(s, foo, "12");

    assertEquals(12, foo.getSampleBean().getMap2().get("bleh").intValue());

    foo = new Foo();
    executeSetExpression(s, foo, "13");

    assertEquals(13, foo.getSampleBean().getMap2().get("bleh").intValue());

    OptimizerFactory.setDefaultOptimizer("ASM");

    ctx = new ParserContext();
    ctx.setStrongTyping(true);
    ctx.addInput("sampleBean", SampleBean.class);

    s = compileSetExpression("sampleBean.map2['bleh']", ctx);

    foo = new Foo();
    executeSetExpression(s, foo, "12");

    assertEquals(12, foo.getSampleBean().getMap2().get("bleh").intValue());

    executeSetExpression(s, foo, new Integer(12));

    assertEquals(12, foo.getSampleBean().getMap2().get("bleh").intValue());
  }
예제 #3
0
 public void testParameterizedTypeInStrictMode() {
   ParserContext ctx = new ParserContext();
   ctx.setStrongTyping(true);
   ctx.addInput("foo", HashMap.class, new Class[] {String.class, String.class});
   ExpressionCompiler compiler = new ExpressionCompiler("foo.get('bar').toUpperCase()");
   compiler.compile(ctx);
 }
예제 #4
0
  public static Rule_codeRegister parse(ParserContext context) {
    context.push("codeRegister");

    boolean parsed = true;
    int s0 = context.index;
    ArrayList<Rule> e0 = new ArrayList<Rule>();
    Rule rule;

    parsed = false;
    if (!parsed) {
      {
        ArrayList<Rule> e1 = new ArrayList<Rule>();
        int s1 = context.index;
        parsed = true;
        if (parsed) {
          boolean f1 = true;
          int c1 = 0;
          for (int i1 = 0; i1 < 1 && f1; i1++) {
            rule = Rule_codeRegisterP.parse(context);
            if ((f1 = rule != null)) {
              e1.add(rule);
              c1++;
            }
          }
          parsed = c1 == 1;
        }
        if (parsed) e0.addAll(e1);
        else context.index = s1;
      }
    }
    if (!parsed) {
      {
        ArrayList<Rule> e1 = new ArrayList<Rule>();
        int s1 = context.index;
        parsed = true;
        if (parsed) {
          boolean f1 = true;
          int c1 = 0;
          for (int i1 = 0; i1 < 1 && f1; i1++) {
            rule = Rule_codeRegisterV.parse(context);
            if ((f1 = rule != null)) {
              e1.add(rule);
              c1++;
            }
          }
          parsed = c1 == 1;
        }
        if (parsed) e0.addAll(e1);
        else context.index = s1;
      }
    }

    rule = null;
    if (parsed) rule = new Rule_codeRegister(context.text.substring(s0, context.index), e0);
    else context.index = s0;

    context.pop("codeRegister", parsed);

    return (Rule_codeRegister) rule;
  }
 @Override
 public MetadataFieldMapper.Builder parse(
     String name, Map<String, Object> node, ParserContext parserContext)
     throws MapperParsingException {
   Builder builder = new Builder(parserContext.type());
   for (Iterator<Map.Entry<String, Object>> iterator = node.entrySet().iterator();
       iterator.hasNext(); ) {
     Map.Entry<String, Object> entry = iterator.next();
     String fieldName = Strings.toUnderscoreCase(entry.getKey());
     Object fieldNode = entry.getValue();
     if (fieldName.equals("type")) {
       builder.type(fieldNode.toString());
       iterator.remove();
     } else if (fieldName.equals("postings_format")
         && parserContext.indexVersionCreated().before(Version.V_2_0_0_beta1)) {
       // ignore before 2.0, reject on and after 2.0
       iterator.remove();
     } else if (fieldName.equals("fielddata")) {
       // Only take over `loading`, since that is the only option now that is configurable:
       Map<String, String> fieldDataSettings =
           SettingsLoader.Helper.loadNestedFromMap(nodeMapValue(fieldNode, "fielddata"));
       if (fieldDataSettings.containsKey(MappedFieldType.Loading.KEY)) {
         Settings settings =
             settingsBuilder()
                 .put(
                     MappedFieldType.Loading.KEY,
                     fieldDataSettings.get(MappedFieldType.Loading.KEY))
                 .build();
         builder.fieldDataSettings(settings);
       }
       iterator.remove();
     }
   }
   return builder;
 }
    @Override
    public Mapper.Builder parse(String name, Map<String, Object> node, ParserContext parserContext)
        throws MapperParsingException {
      if (parserContext.indexVersionCreated().before(Version.V_1_3_0)) {
        throw new IllegalArgumentException(
            "type="
                + CONTENT_TYPE
                + " is not supported on indices created before version 1.3.0. Is your cluster running multiple datanode versions?");
      }

      FieldNamesFieldMapper.Builder builder = fieldNames();
      if (parserContext.indexVersionCreated().before(Version.V_2_0_0)) {
        parseField(builder, builder.name, node, parserContext);
      }

      for (Iterator<Map.Entry<String, Object>> iterator = node.entrySet().iterator();
          iterator.hasNext(); ) {
        Map.Entry<String, Object> entry = iterator.next();
        String fieldName = Strings.toUnderscoreCase(entry.getKey());
        Object fieldNode = entry.getValue();
        if (fieldName.equals("enabled")) {
          builder.enabled(nodeBooleanValue(fieldNode));
          iterator.remove();
        }
      }
      return builder;
    }
    @Override
    public Mapper.Builder<?, ?> parse(
        String name, Map<String, Object> node, ParserContext parserContext)
        throws MapperParsingException {
      CompletionFieldMapper.Builder builder = completionField(name);
      for (Iterator<Map.Entry<String, Object>> iterator = node.entrySet().iterator();
          iterator.hasNext(); ) {
        Map.Entry<String, Object> entry = iterator.next();
        String fieldName = entry.getKey();
        Object fieldNode = entry.getValue();
        if (fieldName.equals("type")) {
          continue;
        }
        if (fieldName.equals("analyzer")) {
          NamedAnalyzer analyzer = getNamedAnalyzer(parserContext, fieldNode.toString());
          builder.indexAnalyzer(analyzer);
          builder.searchAnalyzer(analyzer);
          iterator.remove();
        } else if (Fields.INDEX_ANALYZER.match(fieldName)) {
          builder.indexAnalyzer(getNamedAnalyzer(parserContext, fieldNode.toString()));
          iterator.remove();
        } else if (Fields.SEARCH_ANALYZER.match(fieldName)) {
          builder.searchAnalyzer(getNamedAnalyzer(parserContext, fieldNode.toString()));
          iterator.remove();
        } else if (fieldName.equals(Fields.PAYLOADS)) {
          builder.payloads(Boolean.parseBoolean(fieldNode.toString()));
          iterator.remove();
        } else if (Fields.PRESERVE_SEPARATORS.match(fieldName)) {
          builder.preserveSeparators(Boolean.parseBoolean(fieldNode.toString()));
          iterator.remove();
        } else if (Fields.PRESERVE_POSITION_INCREMENTS.match(fieldName)) {
          builder.preservePositionIncrements(Boolean.parseBoolean(fieldNode.toString()));
          iterator.remove();
        } else if (Fields.MAX_INPUT_LENGTH.match(fieldName)) {
          builder.maxInputLength(Integer.parseInt(fieldNode.toString()));
          iterator.remove();
        } else if ("fields".equals(fieldName) || "path".equals(fieldName)) {
          if (parseMultiField(builder, name, parserContext, fieldName, fieldNode)) {
            iterator.remove();
          }
        } else if (fieldName.equals(Fields.CONTEXT)) {
          builder.contextMapping(
              ContextBuilder.loadMappings(fieldNode, parserContext.indexVersionCreated()));
          iterator.remove();
        }
      }

      if (builder.searchAnalyzer == null) {
        builder.searchAnalyzer(parserContext.analysisService().analyzer("simple"));
      }

      if (builder.indexAnalyzer == null) {
        builder.indexAnalyzer(parserContext.analysisService().analyzer("simple"));
      }
      // we are just using this as the default to be wrapped by the CompletionPostingsFormatProvider
      // in the SuggesteFieldMapper ctor
      builder.postingsFormat(parserContext.postingFormatService().get("default"));
      return builder;
    }
예제 #8
0
  public void testProvidedExternalTypes() {
    ExpressionCompiler compiler = new ExpressionCompiler("foo.bar");
    ParserContext ctx = new ParserContext();
    ctx.setStrictTypeEnforcement(true);
    ctx.addInput("foo", Foo.class);

    compiler.compile(ctx);
  }
예제 #9
0
  public void testGenericInference2() {
    ParserContext ctx;
    MVEL.analysisCompile(
        "$result = person.maptributes['fooey'].name",
        ctx = ParserContext.create().stronglyTyped().withInput("person", Person.class));

    assertEquals(String.class, ctx.getVarOrInputTypeOrNull("$result"));
  }
예제 #10
0
  public void testTypeCalculation() {
    ParserContext ctx = ParserContext.create().stronglyTyped();
    ctx.addInput("foo", Foo.class);

    Class cls = MVEL.analyze("foo.bar.testList.get(0)", ctx);

    assertTrue(Integer.class.isAssignableFrom(cls));
  }
예제 #11
0
 public static ParserContext parse(String selector, SearchStrategy strategy) {
   ParserContext context = new ParserContext(strategy);
   for (char c : selector.toCharArray()) {
     context.getState().process(context, c);
   }
   context.getState().process(context, (char) 0);
   return context;
 }
  // TODO: should "record" how many properties we have reffered to - and if we
  //       don't get'em'all we throw an exception! Way better than trial and error ;)
  private String substituteBrackets(String sqlQuery) throws QueryException {

    StringBuffer result = new StringBuffer(sqlQuery.length() + 20);
    int left, right;

    // replace {....} with corresponding column aliases
    for (int curr = 0; curr < sqlQuery.length(); curr = right + 1) {
      if ((left = sqlQuery.indexOf('{', curr)) < 0) {
        // No additional open braces found in the string, append the
        // rest of the string in its entirty and quit this loop
        result.append(sqlQuery.substring(curr));
        break;
      }

      // apend everything up until the next encountered open brace
      result.append(sqlQuery.substring(curr, left));

      if ((right = sqlQuery.indexOf('}', left + 1)) < 0) {
        throw new QueryException("Unmatched braces for alias path", sqlQuery);
      }

      String aliasPath = sqlQuery.substring(left + 1, right);
      int firstDot = aliasPath.indexOf('.');
      if (firstDot == -1) {
        if (context.isEntityAlias(aliasPath)) {
          // it is a simple table alias {foo}
          result.append(aliasPath);
          aliasesFound++;
        } else {
          // passing through anything we do not know : to support jdbc escape sequences HB-898
          result.append('{').append(aliasPath).append('}');
        }
      } else {
        String aliasName = aliasPath.substring(0, firstDot);
        boolean isCollection = context.isCollectionAlias(aliasName);
        boolean isEntity = context.isEntityAlias(aliasName);

        if (isCollection) {
          // The current alias is referencing the collection to be eagerly fetched
          String propertyName = aliasPath.substring(firstDot + 1);
          result.append(resolveCollectionProperties(aliasName, propertyName));
          aliasesFound++;
        } else if (isEntity) {
          // it is a property reference {foo.bar}
          String propertyName = aliasPath.substring(firstDot + 1);
          result.append(resolveProperties(aliasName, propertyName));
          aliasesFound++;
        } else {
          // passing through anything we do not know : to support jdbc escape sequences HB-898
          result.append('{').append(aliasPath).append('}');
        }
      }
    }

    // Possibly handle :something parameters for the query ?

    return result.toString();
  }
예제 #13
0
  public void testParameterizedTypeInStrictMode2() {
    ParserContext ctx = new ParserContext();
    ctx.setStrongTyping(true);
    ctx.addInput("ctx", Object.class);

    ExpressionCompiler compiler =
        new ExpressionCompiler("org.mvel2.DataConversion.convert(ctx, String).toUpperCase()");
    assertEquals(String.class, compiler.compile(ctx).getKnownEgressType());
  }
    @SuppressWarnings({"unchecked"})
    @Override
    public XContentMapper.Builder parse(
        String name, Map<String, Object> node, ParserContext parserContext)
        throws MapperParsingException {
      AttachmentMapper.Builder builder = new AttachmentMapper.Builder(name);

      for (Map.Entry<String, Object> entry : node.entrySet()) {
        String fieldName = entry.getKey();
        Object fieldNode = entry.getValue();
        if (fieldName.equals("path")) {
          builder.pathType(parsePathType(name, fieldNode.toString()));
        } else if (fieldName.equals("fields")) {
          Map<String, Object> fieldsNode = (Map<String, Object>) fieldNode;
          for (Map.Entry<String, Object> entry1 : fieldsNode.entrySet()) {
            String propName = entry1.getKey();
            Object propNode = entry1.getValue();

            if (name.equals(propName)) {
              // that is the content
              builder.content(
                  (StringFieldMapper.Builder)
                      parserContext
                          .typeParser("string")
                          .parse(name, (Map<String, Object>) propNode, parserContext));
            } else if ("date".equals(propName)) {
              builder.date(
                  (DateFieldMapper.Builder)
                      parserContext
                          .typeParser("date")
                          .parse("date", (Map<String, Object>) propNode, parserContext));
            } else if ("title".equals(propName)) {
              builder.title(
                  (StringFieldMapper.Builder)
                      parserContext
                          .typeParser("string")
                          .parse("title", (Map<String, Object>) propNode, parserContext));
            } else if ("author".equals(propName)) {
              builder.author(
                  (StringFieldMapper.Builder)
                      parserContext
                          .typeParser("string")
                          .parse("author", (Map<String, Object>) propNode, parserContext));
            } else if ("keywords".equals(propName)) {
              builder.keywords(
                  (StringFieldMapper.Builder)
                      parserContext
                          .typeParser("string")
                          .parse("keywords", (Map<String, Object>) propNode, parserContext));
            }
          }
        }
      }

      return builder;
    }
예제 #15
0
  public void testVarDeclr() {
    String ex = "var a";

    ParserContext ctx = new ParserContext();
    ExpressionCompiler compiler = new ExpressionCompiler(ex);
    compiler.setVerifyOnly(true);
    compiler.compile(ctx);

    assertEquals(1, ctx.getVariables().size());
  }
예제 #16
0
  public void testParameterizedTypeInStrictMode3() {
    ParserContext ctx = new ParserContext();
    ctx.setStrongTyping(true);
    ctx.addInput("base", Base.class);

    ExpressionCompiler compiler = new ExpressionCompiler("base.list");

    assertTrue(
        compiler.compile(ctx).getParserContext().getLastTypeParameters()[0].equals(String.class));
  }
예제 #17
0
  public void testStrictStaticMethodCall() {
    ExpressionCompiler compiler = new ExpressionCompiler("Bar.staticMethod()");
    ParserContext ctx = new ParserContext();
    ctx.addImport("Bar", Bar.class);
    ctx.setStrictTypeEnforcement(true);

    Serializable s = compiler.compile(ctx);

    assertEquals(1, executeExpression(s));
  }
예제 #18
0
  public void testCompileTimeCoercion() {
    ParserContext ctx = new ParserContext();
    ctx.setStrongTyping(true);
    ctx.addInput("foo", Foo.class);

    assertEquals(
        true,
        executeExpression(
            new ExpressionCompiler("foo.bar.woof == 'true'").compile(ctx), createTestMap()));
  }
예제 #19
0
  public void testParameterizedTypeInStrictMode4() {
    ParserContext ctx = new ParserContext();
    ctx.setStrongTyping(true);
    ctx.addInput("base", Base.class);

    ExpressionCompiler compiler = new ExpressionCompiler("base.list.get(1).toUpperCase()");
    CompiledExpression ce = compiler.compile(ctx);

    assertEquals(String.class, ce.getKnownEgressType());
  }
예제 #20
0
  public void testSetAccessorOverloadedEqualsStrictMode2() {
    ParserContext ctx = new ParserContext();
    ctx.setStrongTyping(true);
    ctx.addInput("foo", Foo.class);

    try {
      CompiledExpression expr = new ExpressionCompiler("foo.aValue = 'bar'").compile(ctx);
    } catch (CompileException e) {
      assertTrue(false);
    }
  }
예제 #21
0
  public void testAnalyzer() {
    ParserContext ctx = new ParserContext();
    MVEL.compileExpression("order.id == 10", ctx);

    for (String input : ctx.getInputs().keySet()) {
      System.out.println("input>" + input);
    }

    assertEquals(1, ctx.getInputs().size());
    assertTrue(ctx.getInputs().containsKey("order"));
  }
예제 #22
0
  public void testVarInputs2() {
    ExpressionCompiler compiler =
        new ExpressionCompiler(
            "test != foo && bo.addSomething(trouble); String bleh = foo; twa = bleh;");

    ParserContext ctx = new ParserContext();

    compiler.compile(ctx);

    System.out.println(ctx.getVarOrInputType("bleh"));
  }
예제 #23
0
  public void testAnalysisCompile() {
    ParserContext pCtx = new ParserContext();
    ExpressionCompiler e = new ExpressionCompiler("foo.aValue = 'bar'");
    e.setVerifyOnly(true);

    e.compile(pCtx);

    assertTrue(pCtx.getInputs().keySet().contains("foo"));
    assertEquals(1, pCtx.getInputs().size());
    assertEquals(0, pCtx.getVariables().size());
  }
예제 #24
0
  public void testContextMethodCallsInStrongMode() {
    ParserContext context = new ParserContext();
    context.setStrongTyping(true);
    context.addInput("this", EchoContext.class);

    ExecutableStatement stmt =
        (ExecutableStatement) MVEL.compileExpression("this.echo( 'Mac')", context);
    stmt = (ExecutableStatement) MVEL.compileExpression("echo( 'Mac')", context);

    assertEquals("Mac", MVEL.executeExpression(stmt, new EchoContext()));
  }
예제 #25
0
 @Override
 public MetadataFieldMapper.Builder<?, ?> parse(
     String name, Map<String, Object> node, ParserContext parserContext)
     throws MapperParsingException {
   if (parserContext.indexVersionCreated().onOrAfter(Version.V_2_0_0_beta1)) {
     throw new MapperParsingException(NAME + " is not configurable");
   }
   Builder builder = new Builder(parserContext.mapperService().fullName(NAME));
   parseField(builder, builder.name, node, parserContext);
   return builder;
 }
예제 #26
0
  public void testTypeVarDeclr() {
    String ex = "String a;";
    ParserContext ctx = new ParserContext();
    ExpressionCompiler compiler = new ExpressionCompiler(ex);
    compiler.compile(ctx);

    assertNotNull(ctx.getVariables());
    assertEquals(1, ctx.getVariables().entrySet().size());
    for (Map.Entry<String, Class> entry : ctx.getVariables().entrySet()) {
      assertEquals(String.class, entry.getValue());
    }
  }
예제 #27
0
  public void testStrictTypingCompilation4() throws NoSuchMethodException {
    ParserContext ctx = new ParserContext();

    ctx.addImport(Foo.class);
    ctx.setStrictTypeEnforcement(true);

    ExpressionCompiler compiler = new ExpressionCompiler("x_a = new Foo()");

    compiler.compile(ctx);

    assertEquals(Foo.class, ctx.getVariables().get("x_a"));
  }
예제 #28
0
  public void testEgressTypeCorrect2() {

    ParserContext context = new ParserContext();
    context.setStrongTyping(true);
    context.addInput("this", SampleBean.class);
    ExecutableStatement stmt =
        (ExecutableStatement) MVEL.compileExpression("( map2[ 'yyy' ] )", context);

    SampleBean s = new SampleBean();
    s.getMap2().put("yyy", 1);

    assertEquals(new Integer(1), MVEL.executeExpression(stmt, s));
  }
예제 #29
0
  public void testStrongTyping() {
    ParserContext ctx = new ParserContext();
    ctx.setStrongTyping(true);

    try {
      new ExpressionCompiler("blah").compile(ctx);
    } catch (Exception e) {
      // should fail
      return;
    }

    assertTrue(false);
  }
예제 #30
0
  public void testStrictTypingCompilation3() throws NoSuchMethodException {
    ParserContext ctx = new ParserContext();

    ctx.setStrictTypeEnforcement(true);

    ExpressionCompiler compiler =
        new ExpressionCompiler(
            "message='Hello';b=7;\nSystem.out.println(message + ';' + b);\n"
                + "System.out.println(message + ';' + b); b");

    assertEquals(
        7, executeExpression(compiler.compile(ctx), new DefaultLocalVariableResolverFactory()));
  }