@Override
  public Object[] extract(T item) {
    ExpressionParser parser = new SpelExpressionParser();
    EvaluationContext elContext = new CoreMappingEvaluationContext(item);
    elContext.getPropertyAccessors().add(new ExtendedAttributePropertyAccessor());

    try (InputStream iStream = resource.getInputStream()) {
      List<String> expressions = IOUtils.readLines(iStream);
      List<Object> fields = Lists.newArrayListWithCapacity(expressions.size());
      for (String expression : expressions) {
        String value = parser.parseExpression(expression).getValue(elContext, String.class);
        if (value != null && value.contains("\"") && !"\"\"".equals(value)) {
          value = value.replaceAll("\"", "\"\"");
        }
        if (value != null && value.contains(",")) {
          StringBuilder sb = new StringBuilder(value.length() + 2);
          sb.append("\"");
          sb.append(value);
          sb.append("\"");
          value = sb.toString();
        }
        fields.add(value);
      }
      return fields.toArray(new Object[fields.size()]);
    } catch (IOException e) {
      throw new RuntimeException(e);
    }
  }
示例#2
0
  /**
   * 取得field中spel表达是的值
   *
   * @param pjp
   * @param field
   * @return
   */
  private String getSpelKey(ProceedingJoinPoint pjp, String field) {
    Method method = getMethod(pjp);
    Object[] args = pjp.getArgs();
    // String field = cache.field();

    if (StringUtils.isEmpty(field)) {
      LOGGER.error(
          "method {}.{}'s annotation field is empty. This may be an error.",
          method.getClass(),
          method.getName());
    }
    LocalVariableTableParameterNameDiscoverer u = new LocalVariableTableParameterNameDiscoverer();

    String[] paraNameArr = u.getParameterNames(method);

    // 应用SPEL进行key的解析

    ExpressionParser parser = new SpelExpressionParser();

    // SPEL高低文

    StandardEvaluationContext context = new StandardEvaluationContext();

    // 把办法参数放入SPEL高低文中

    for (int i = 0; i < paraNameArr.length; i++) {
      context.setVariable(paraNameArr[i], args[i]);
    }
    if (field.contains(",")) {
      return getKeyForStr(parser, context, field);
    }
    String value = parser.parseExpression(field).getValue(context, String.class);
    return value;
  }
  private static PartitionStrategy parsePartitionExpression(String expression) {

    List<String> expressions = Arrays.asList(expression.split("/"));

    ExpressionParser parser = new SpelExpressionParser();
    PartitionStrategy.Builder psb = new PartitionStrategy.Builder();
    StandardEvaluationContext ctx = new StandardEvaluationContext(psb);
    for (String expr : expressions) {
      try {
        Expression e = parser.parseExpression(expr);
        psb = e.getValue(ctx, PartitionStrategy.Builder.class);
      } catch (SpelParseException spe) {
        if (!expr.trim().endsWith(")")) {
          throw new StoreException(
              "Invalid partitioning expression '"
                  + expr
                  + "' -  did you forget the closing parenthesis?",
              spe);
        } else {
          throw new StoreException("Invalid partitioning expression '" + expr + "'!", spe);
        }
      } catch (SpelEvaluationException see) {
        throw new StoreException(
            "Invalid partitioning expression '" + expr + "' - failed evaluation!", see);
      } catch (NullPointerException npe) {
        throw new StoreException(
            "Invalid partitioning expression '" + expr + "' - was evaluated to null!", npe);
      }
    }
    return psb.build();
  }
  @Test
  public void testPropertyNavigation() throws Exception {
    ExpressionParser parser = new SpelExpressionParser();

    // Inventions Array
    StandardEvaluationContext teslaContext = TestScenarioCreator.getTestEvaluationContext();
    //		teslaContext.setRootObject(tesla);

    // evaluates to "Induction motor"
    String invention = parser.parseExpression("inventions[3]").getValue(teslaContext, String.class);
    assertEquals("Induction motor", invention);

    // Members List
    StandardEvaluationContext societyContext = new StandardEvaluationContext();
    IEEE ieee = new IEEE();
    ieee.Members[0] = tesla;
    societyContext.setRootObject(ieee);

    // evaluates to "Nikola Tesla"
    String name = parser.parseExpression("Members[0].Name").getValue(societyContext, String.class);
    assertEquals("Nikola Tesla", name);

    // List and Array navigation
    // evaluates to "Wireless communication"
    invention =
        parser.parseExpression("Members[0].Inventions[6]").getValue(societyContext, String.class);
    assertEquals("Wireless communication", invention);
  }
示例#5
0
  private boolean tryExtractPropertyValueFrom(Object bean) {
    ExpressionParser parser = new SpelExpressionParser();
    Expression exp = parser.parseExpression(propertyName);
    beanPropertyValue = exp.getValue(bean);

    return valueMatcher.matches(beanPropertyValue);
  }
示例#6
0
 /** @param condition */
 public static final void prepare(Condition condition) {
   ExpressionParser parser = new SpelExpressionParser();
   if (condition != null && StringUtils.isNotBlank(condition.getExpression())) {
     List<Expression> expressions = new ArrayList<Expression>();
     expressions.add(parser.parseExpression(condition.getExpression()));
     condition.setExpressions(expressions);
   }
 }
 @Test
 public void test() {
   ExpressionParser parser = new SpelExpressionParser();
   Expression expression = parser.parseExpression("('Hello' + ' World').concat(#end)");
   EvaluationContext context = new StandardEvaluationContext();
   context.setVariable("end", "!");
   System.out.println(expression.getValue(context));
   Assert.assertEquals("Hello World!", expression.getValue(context));
 }
示例#8
0
  @Test
  public void SafeNavigation() {
    ExpressionParser parser = new SpelExpressionParser();

    SpringSprout ss = new SpringSprout();
    StandardEvaluationContext context = new StandardEvaluationContext(ss);

    String myName = parser.parseExpression("whiteship?.name").getValue(context, String.class);
    assertThat(myName, is(nullValue()));
  }
  @Test
  public void testEqualityCheck() throws Exception {
    ExpressionParser parser = new SpelExpressionParser();

    StandardEvaluationContext context = new StandardEvaluationContext();
    context.setRootObject(tesla);

    Expression exp = parser.parseExpression("name == 'Nikola Tesla'");
    boolean isEqual = exp.getValue(context, Boolean.class); // evaluates to true
    assertTrue(isEqual);
  }
  @Test
  public void testFunctions() throws Exception {
    ExpressionParser parser = new SpelExpressionParser();
    StandardEvaluationContext context = new StandardEvaluationContext();

    context.registerFunction(
        "reverseString",
        StringUtils.class.getDeclaredMethod("reverseString", new Class[] {String.class}));

    String helloWorldReversed =
        parser.parseExpression("#reverseString('hello world')").getValue(context, String.class);
    assertEquals("dlrow olleh", helloWorldReversed);
  }
 /**
  * Optionally maps parameter names to explicit expressions. The named parameter support in Spring
  * is limited to simple parameter names with no special characters, so this feature allows you to
  * specify a simple name in the SQL query and then have it translated into an expression at
  * runtime. The target of the expression depends on the context: generally in an outbound setting
  * it is a Message, and in an inbound setting it is a result set row (a Map or a domain object if
  * a RowMapper has been provided). The {@link #setStaticParameters(Map) static parameters} can be
  * referred to in an expression using the variable <code>#staticParameters</code>, for example:
  *
  * <p>&nbsp;
  *
  * <table>
  * <caption>Parameter Expressions Samples</caption>
  * <tr>
  * <th><b>Key</b></th>
  * <th><b>Value (Expression)</b></th>
  * <th><b>Example SQL</b></th>
  * </tr>
  * <tr>
  * <td>id</td>
  * <td>{@code payload.businessKey}</td>
  * <td>{@code select * from items where id=:id}</td>
  * </tr>
  * <tr>
  * <td>date</td>
  * <td>{@code headers['timestamp']}</td>
  * <td>{@code select * from items where created>:date}</td>
  * </tr>
  * <tr>
  * <td>key</td>
  * <td>{@code #staticParameters['foo'].toUpperCase()}</td>
  * <td>{@code select * from items where name=:key}</td>
  * </tr>
  * </table>
  *
  * <p>
  *
  * @param parameterExpressions the parameter expressions to set
  */
 public void setParameterExpressions(Map<String, String> parameterExpressions) {
   Map<String, Expression[]> paramExpressions =
       new HashMap<String, Expression[]>(parameterExpressions.size());
   for (Map.Entry<String, String> entry : parameterExpressions.entrySet()) {
     String key = entry.getKey();
     String expression = entry.getValue();
     Expression[] expressions =
         new Expression[] {
           PARSER.parseExpression(expression),
           PARSER.parseExpression("#root.![" + expression + "]")
         };
     paramExpressions.put(key, expressions);
   }
   this.parameterExpressions = paramExpressions;
 }
  @SuppressWarnings("unchecked")
  @Test
  public void testSpecialVariables() throws Exception {
    // create an array of integers
    List<Integer> primes = new ArrayList<>();
    primes.addAll(Arrays.asList(2, 3, 5, 7, 11, 13, 17));

    // create parser and set variable 'primes' as the array of integers
    ExpressionParser parser = new SpelExpressionParser();
    StandardEvaluationContext context = new StandardEvaluationContext();
    context.setVariable("primes", primes);

    // all prime numbers > 10 from the list (using selection ?{...})
    List<Integer> primesGreaterThanTen =
        (List<Integer>) parser.parseExpression("#primes.?[#this>10]").getValue(context);
    assertEquals("[11, 13, 17]", primesGreaterThanTen.toString());
  }
  @Test
  public void testRootObject() throws Exception {
    GregorianCalendar c = new GregorianCalendar();
    c.set(1856, 7, 9);

    //  The constructor arguments are name, birthday, and nationaltiy.
    Inventor tesla = new Inventor("Nikola Tesla", c.getTime(), "Serbian");

    ExpressionParser parser = new SpelExpressionParser();
    Expression exp = parser.parseExpression("name");

    StandardEvaluationContext context = new StandardEvaluationContext();
    context.setRootObject(tesla);

    String name = (String) exp.getValue(context);
    assertEquals("Nikola Tesla", name);
  }
示例#14
0
文件: Test.java 项目: feisuo/Spring
  public static void main(String[] args) {
    Inventor inventor = new Inventor("Suyash", "Bhartiya");
    // PlaceOfBirth placeOfBirth=new PlaceOfBirth("Delhi","Bharat");

    ExpressionParser parser = new SpelExpressionParser();

    EvaluationContext context = new StandardEvaluationContext(inventor);
    // EvaluationContext context=new StandardEvaluationContext(placeOfBirth);

    Expression expression = parser.parseExpression("Birthdate.Year + 1900");

    int year = expression.getValue(context, Integer.class);

    // String city = (String) parser.parseExpression("placeOfBirth.City").getValue(context);
    System.out.println("Year : " + year); // evaluates to Year : 2014
    // System.out.println("City : "+city);		// evaluates to City : Delhi

  }
 /** Create an {@link ExpressionEvaluatingMessageProcessor} for the given expression String. */
 public ExpressionEvaluatingMessageProcessor(String expression, Class<T> expectedType) {
   Assert.hasLength(expression, "The expression must be non empty");
   try {
     this.expression = parser.parseExpression(expression);
     this.getEvaluationContext().addPropertyAccessor(new MapAccessor());
     this.expectedType = expectedType;
   } catch (ParseException e) {
     throw new IllegalArgumentException("Failed to parse expression.", e);
   }
 }
  @SuppressWarnings("unchecked")
  public <T> ResultMatcher property(final String nameAndProperty, final Matcher<T> matcher) {
    return mvcResult -> {
      // <インスタンス名>.<プロパティ名> ( 例: page.number ) の形式の文字列を
      // インスタンス名とプロパティ名に分割する
      Pattern p = Pattern.compile("^(\\S+?)\\.(\\S+)$");
      java.util.regex.Matcher m = p.matcher(nameAndProperty);
      assertThat(m.find(), is(true));
      String name = m.group(1);
      String property = m.group(2);

      // プロパティの値を取得してチェックする
      ModelMap modelMap = mvcResult.getModelAndView().getModelMap();
      Object object = modelMap.get(name);
      assertThat(object, is(notNullValue()));
      EvaluationContext context = new StandardEvaluationContext(object);
      ExpressionParser parser = new SpelExpressionParser();
      Expression exp = parser.parseExpression(property);
      Object value = exp.getValue(context);
      assertThat((T) value, matcher);
    };
  }
 private Collection<ConfigAttribute> getEentConfigAttributes(SecurityRule rule) {
   List<ConfigAttribute> configAttributes = new ArrayList<ConfigAttribute>();
   if (rule.getAttributes() != null) {
     for (String attribute : rule.getAttributes()) {
       configAttributes.add(new SecurityConfig(attribute));
     }
   }
   if (StringUtils.hasText(rule.getExpression())) {
     configAttributes.add(
         new EventExpressionConfigAttribute(
             expressionParser.parseExpression(rule.getExpression())));
   }
   return configAttributes;
 }
  @Test
  public void resuelveEcuacion() {

    ExpressionParser parser;
    Expression exp;
    Double x1 = 0.0, x2 = 0.0;

    parser = new SpelExpressionParser();

    // la ecuacion es x^2+10x+21

    // para x1
    // TODO, completar este test case para obtener X1

    exp = parser.parseExpression("(10+T(Math).sqrt(10^2-(4*(1*21))))/2");
    x1 = exp.getValue(Double.class);
    Assert.assertEquals(new Double(7), x1);

    // para x2
    // TODO, completar este test case para obtener X2
    exp = parser.parseExpression("(10-T(Math).sqrt(10^2-(4*(1*21))))/2");
    x2 = exp.getValue(Double.class);
    Assert.assertEquals(new Double(3), x2);
  }
示例#19
0
  public static void main(String[] args) {
    // 创建一个ExpressionParser对象,用于解析表达式
    ExpressionParser parser = new SpelExpressionParser();

    List<String> list = new ArrayList<String>();
    list.add("疯狂Java讲义");
    list.add("疯狂Ajax讲义");
    list.add("疯狂XML讲义");
    list.add("经典Java EE企业应用实战");
    EvaluationContext ctx = new StandardEvaluationContext();
    ctx.setVariable("mylist", list);
    // 得到的新集合的元素是原集合的每个元素length()方法返回值
    Expression expr = parser.parseExpression("#mylist.![length()]");
    System.out.println(expr.getValue(ctx));

    List<Person> list2 = new ArrayList<Person>();
    list2.add(new Person(1, "孙悟空", 162));
    list2.add(new Person(1, "猪八戒", 182));
    list2.add(new Person(1, "牛魔王", 195));
    ctx.setVariable("mylist2", list2);
    // 得到的新集合的元素是原集合的每个元素name属性值
    expr = parser.parseExpression("#mylist2.![name]");
    System.out.println(expr.getValue(ctx));
  }
  @Override
  public void bindReplier(
      String name, MessageChannel requests, MessageChannel replies, Properties properties) {
    if (logger.isInfoEnabled()) {
      logger.info("binding replier: " + name);
    }
    validateConsumerProperties(name, properties, SUPPORTED_REPLYING_CONSUMER_PROPERTIES);
    RabbitPropertiesAccessor accessor = new RabbitPropertiesAccessor(properties);
    Queue requestQueue =
        new Queue(applyPrefix(accessor.getPrefix(this.defaultPrefix), applyRequests(name)));
    declareQueueIfNotPresent(requestQueue);
    this.doRegisterConsumer(name, requests, requestQueue, accessor, false);

    AmqpOutboundEndpoint replyQueue = new AmqpOutboundEndpoint(rabbitTemplate);
    replyQueue.setExpressionRoutingKey(
        EXPRESSION_PARSER.parseExpression("headers['" + AmqpHeaders.REPLY_TO + "']"));
    configureOutboundHandler(replyQueue, accessor);
    doRegisterProducer(name, replies, replyQueue, accessor);
  }
 private AmqpOutboundEndpoint buildOutboundEndpoint(
     final String name, RabbitPropertiesAccessor properties, RabbitTemplate rabbitTemplate) {
   String queueName = applyPrefix(properties.getPrefix(this.defaultPrefix), name);
   String partitionKeyExtractorClass = properties.getPartitionKeyExtractorClass();
   Expression partitionKeyExpression = properties.getPartitionKeyExpression();
   AmqpOutboundEndpoint queue = new AmqpOutboundEndpoint(rabbitTemplate);
   if (partitionKeyExpression == null && !StringUtils.hasText(partitionKeyExtractorClass)) {
     declareQueueIfNotPresent(new Queue(queueName));
     queue.setRoutingKey(queueName); // uses default exchange
   } else {
     queue.setExpressionRoutingKey(
         EXPRESSION_PARSER.parseExpression(buildPartitionRoutingExpression(queueName)));
     // if the stream is partitioned, create one queue for each target partition
     for (int i = 0; i < properties.getNextModuleCount(); i++) {
       this.rabbitAdmin.declareQueue(new Queue(queueName + "-" + i));
     }
   }
   configureOutboundHandler(queue, properties);
   return queue;
 }
示例#22
0
 private String getKeyForStr(
     ExpressionParser parser, StandardEvaluationContext context, String field) {
   StringBuffer value = new StringBuffer();
   String[] valus = field.split(",");
   for (String lv : valus) {
     if (StringUtils.isEmpty(lv)) {
       break;
     }
     if (lv.contains("#")) {
       String rv = parser.parseExpression(lv).getValue(context, String.class);
       value.append(rv);
     } else {
       value.append(lv);
     }
     value.append("-");
   }
   String val = value.toString();
   val = val.substring(0, val.length() - 1);
   return val;
 }
  // Section 7.5
  @Test
  public void testLiterals() throws Exception {
    ExpressionParser parser = new SpelExpressionParser();

    String helloWorld =
        (String) parser.parseExpression("'Hello World'").getValue(); // evals to "Hello World"
    assertEquals("Hello World", helloWorld);

    double avogadrosNumber = (Double) parser.parseExpression("6.0221415E+23").getValue();
    assertEquals(6.0221415E+23, avogadrosNumber, 0);

    int maxValue = (Integer) parser.parseExpression("0x7FFFFFFF").getValue(); // evals to 2147483647
    assertEquals(Integer.MAX_VALUE, maxValue);

    boolean trueValue = (Boolean) parser.parseExpression("true").getValue();
    assertTrue(trueValue);

    Object nullValue = parser.parseExpression("null").getValue();
    assertNull(nullValue);
  }
 /**
  * @deprecated in favor of {@link #setExpressionExchangeName}. Will be changed in a future release
  *     to use an {@link Expression} parameter.
  * @param exchangeNameExpression the expression to set.
  */
 @Deprecated
 public void setExchangeNameExpression(String exchangeNameExpression) {
   Assert.hasText(exchangeNameExpression);
   this.exchangeNameExpression = expressionParser.parseExpression(exchangeNameExpression);
 }
 /**
  * @deprecated in favor of {@link #setExpressionRoutingKey}. Will be changed in a future release
  *     to use an {@link Expression} parameter.
  * @param routingKeyExpression the expression to set.
  */
 @Deprecated
 public void setRoutingKeyExpression(String routingKeyExpression) {
   Assert.hasText(routingKeyExpression);
   setExpressionRoutingKey(expressionParser.parseExpression(routingKeyExpression));
 }
 /**
  * @deprecated in favor of {@link #setExpressionConfirmCorrelation}. Will be changed in a future
  *     release to use {@link Expression} parameter.
  * @param confirmCorrelationExpression the expression to set.
  */
 @Deprecated
 public void setConfirmCorrelationExpression(String confirmCorrelationExpression) {
   Assert.hasText(confirmCorrelationExpression);
   setExpressionConfirmCorrelation(expressionParser.parseExpression(confirmCorrelationExpression));
 }
示例#27
0
 public static Object parse(String expression, Object root) {
   return parser.parseExpression(expression, parserContext).getValue(root);
 }