org.apache.commons.jexl3.MapContext Java Examples

The following examples show how to use org.apache.commons.jexl3.MapContext. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: SandboxTest.java    From commons-jexl with Apache License 2.0 6 votes vote down vote up
@Test
public void testCantSeeMe() throws Exception {
    JexlContext jc = new MapContext();
    String expr = "foo.doIt()";
    JexlScript script;
    Object result = null;

    JexlSandbox sandbox = new JexlSandbox(false);
    sandbox.allow(Foo.class.getName());
    JexlEngine sjexl = new JexlBuilder().sandbox(sandbox).strict(true).safe(false).create();

    jc.set("foo", new CantSeeMe());
    script = sjexl.createScript(expr);
    try {
        result = script.execute(jc);
        Assert.fail("should have failed, doIt()");
    } catch (JexlException xany) {
        //
    }
    jc.set("foo", new Foo("42"));
        result = script.execute(jc);
    Assert.assertEquals(42, ((Integer) result).intValue());
}
 
Example #2
Source File: JexlRowFactory.java    From timbuctoo with GNU General Public License v3.0 6 votes vote down vote up
@Override
public String getRawValue(String key) {
  if (data.containsKey(key)) {
    return data.get(key);
  } else if (expressions.containsKey(key)) {
    try {
      JexlContext jexlContext = new MapContext();
      jexlContext.set("v", data);
      Object result = expressions.get(key).evaluate(jexlContext);
      if (result != null) {
        return result.toString();
      } else {
        return null;
      }
    } catch (Throwable throwable) {
      LOG.info("Error during mapping", throwable);
      errorHandler.valueGenerateFailed(
        key,
        String.format("Could not execute expression '%s' for row with values: '%s.", expressions.get(key), data)
      );
      return null;
    }
  } else {
    return null;
  }
}
 
Example #3
Source File: ExtractCCDAAttributes.java    From nifi with Apache License 2.0 6 votes vote down vote up
@OnScheduled
public void onScheduled(final ProcessContext context) throws IOException {
    getLogger().debug("Loading packages");
    final StopWatch stopWatch = new StopWatch(true);

    // Load required MDHT packages
    System.setProperty( "org.eclipse.emf.ecore.EPackage.Registry.INSTANCE",
            "org.eclipse.emf.ecore.impl.EPackageRegistryImpl" );
    CDAPackage.eINSTANCE.eClass();
    HITSPPackage.eINSTANCE.eClass();
    CCDPackage.eINSTANCE.eClass();
    ConsolPackage.eINSTANCE.eClass();
    IHEPackage.eINSTANCE.eClass();
    stopWatch.stop();
    getLogger().debug("Loaded packages in {}", new Object[] {stopWatch.getDuration(TimeUnit.MILLISECONDS)});

    // Initialize JEXL
    jexl = new JexlBuilder().cache(1024).debug(false).silent(true).strict(false).create();
    jexlCtx = new MapContext();

    getLogger().debug("Loading mappings");
    loadMappings(); // Load CDA mappings for parser

}
 
Example #4
Source File: JexlClaimsMapper.java    From cxf with Apache License 2.0 6 votes vote down vote up
public ProcessedClaimCollection mapClaims(String sourceRealm, ProcessedClaimCollection sourceClaims,
    String targetRealm, ClaimsParameters parameters) {
    JexlContext context = new MapContext();
    context.set("sourceClaims", sourceClaims);
    context.set("targetClaims", new ProcessedClaimCollection());
    context.set("sourceRealm", sourceRealm);
    context.set("targetRealm", targetRealm);
    context.set("claimsParameters", parameters);

    JexlScript s = getScript();
    if (s == null) {
        LOG.warning("No claim mapping script defined");
        return new ProcessedClaimCollection(); // TODO Check if null or an exception would be more
                                               // appropriate
    }
    return (ProcessedClaimCollection)s.execute(context);
}
 
Example #5
Source File: MappingManagerImpl.java    From syncope with Apache License 2.0 6 votes vote down vote up
/**
 * Build __NAME__ for propagation.
 * First look if there is a defined connObjectLink for the given resource (and in
 * this case evaluate as JEXL); otherwise, take given connObjectKey.
 *
 * @param realm given any object
 * @param orgUnit external resource
 * @param connObjectKey connector object key
 * @return the value to be propagated as __NAME__
 */
private Name evaluateNAME(final Realm realm, final OrgUnit orgUnit, final String connObjectKey) {
    if (StringUtils.isBlank(connObjectKey)) {
        // LOG error but avoid to throw exception: leave it to the external resource
        LOG.warn("Missing ConnObjectKey value for {}: ", orgUnit.getResource());
    }

    // Evaluate connObjectKey expression
    String connObjectLink = orgUnit == null
            ? null
            : orgUnit.getConnObjectLink();
    String evalConnObjectLink = null;
    if (StringUtils.isNotBlank(connObjectLink)) {
        JexlContext jexlContext = new MapContext();
        JexlUtils.addFieldsToContext(realm, jexlContext);
        evalConnObjectLink = JexlUtils.evaluate(connObjectLink, jexlContext);
    }

    return getName(evalConnObjectLink, connObjectKey);
}
 
Example #6
Source File: MappingManagerImpl.java    From syncope with Apache License 2.0 6 votes vote down vote up
/**
 * Build __NAME__ for propagation.
 * First look if there is a defined connObjectLink for the given resource (and in
 * this case evaluate as JEXL); otherwise, take given connObjectKey.
 *
 * @param any given any object
 * @param provision external resource
 * @param connObjectKey connector object key
 * @return the value to be propagated as __NAME__
 */
private Name evaluateNAME(final Any<?> any, final Provision provision, final String connObjectKey) {
    if (StringUtils.isBlank(connObjectKey)) {
        // LOG error but avoid to throw exception: leave it to the external resource
        LOG.warn("Missing ConnObjectKey value for {}: ", provision.getResource());
    }

    // Evaluate connObjectKey expression
    String connObjectLink = provision == null || provision.getMapping() == null
            ? null
            : provision.getMapping().getConnObjectLink();
    String evalConnObjectLink = null;
    if (StringUtils.isNotBlank(connObjectLink)) {
        JexlContext jexlContext = new MapContext();
        JexlUtils.addFieldsToContext(any, jexlContext);
        JexlUtils.addPlainAttrsToContext(any.getPlainAttrs(), jexlContext);
        JexlUtils.addDerAttrsToContext(any, derAttrHandler, jexlContext);
        evalConnObjectLink = JexlUtils.evaluate(connObjectLink, jexlContext);
    }

    return getName(evalConnObjectLink, connObjectKey);
}
 
Example #7
Source File: MappingTest.java    From syncope with Apache License 2.0 6 votes vote down vote up
@Test
public void anyConnObjectLink() {
    Realm realm = mock(Realm.class);
    when(realm.getFullPath()).thenReturn("/even");

    User user = mock(User.class);
    when(user.getUsername()).thenReturn("rossini");
    when(user.getRealm()).thenReturn(realm);
    assertNotNull(user);

    JexlContext jexlContext = new MapContext();
    JexlUtils.addFieldsToContext(user, jexlContext);

    String connObjectLink = "'uid=' + username + ',ou=people,o=isp'";
    assertEquals("uid=rossini,ou=people,o=isp", JexlUtils.evaluate(connObjectLink, jexlContext));

    connObjectLink = "'uid=' + username + realm.replaceAll('/', ',o=') + ',ou=people,o=isp'";
    assertEquals("uid=rossini,o=even,ou=people,o=isp", JexlUtils.evaluate(connObjectLink, jexlContext));
}
 
Example #8
Source File: DerAttrHandlerImpl.java    From syncope with Apache License 2.0 5 votes vote down vote up
private static Map<DerSchema, String> getValues(
    final GroupableRelatable<?, ?, ?, ?, ?> any, final Membership<?> membership, final Set<DerSchema> schemas) {

    Map<DerSchema, String> result = new HashMap<>(schemas.size());

    schemas.forEach(schema -> {
        JexlContext jexlContext = new MapContext();
        JexlUtils.addPlainAttrsToContext(any.getPlainAttrs(membership), jexlContext);
        JexlUtils.addFieldsToContext(any, jexlContext);

        result.put(schema, JexlUtils.evaluate(schema.getExpression(), jexlContext));
    });

    return result;
}
 
Example #9
Source File: SandboxTest.java    From commons-jexl with Apache License 2.0 5 votes vote down vote up
@Test
public void testNoJexl312() throws Exception {
    JexlContext ctxt = new MapContext();
    
    JexlEngine sjexl = new JexlBuilder().safe(false).strict(true).create();
    JexlScript foo = sjexl.createScript("x.getFoo()", "x");
    try {
        foo.execute(ctxt, new Foo44());
        Assert.fail("should have thrown");
    } catch (JexlException xany) {
        Assert.assertNotNull(xany);
    }
}
 
Example #10
Source File: ArrayTest.java    From commons-jexl with Apache License 2.0 5 votes vote down vote up
/**
 * An example for array access.
 */
static void example(Output out) throws Exception {
    /*
     * First step is to retrieve an instance of a JexlEngine;
     * it might be already existing and shared or created anew.
     */
    JexlEngine jexl = new JexlBuilder().create();
    /*
     *  Second make a jexlContext and put stuff in it
     */
    JexlContext jc = new MapContext();

    List<Object> l = new ArrayList<Object>();
    l.add("Hello from location 0");
    Integer two = 2;
    l.add(two);
    jc.set("array", l);

    JexlExpression e = jexl.createExpression("array[1]");
    Object o = e.evaluate(jc);
    out.print("Object @ location 1 = ", o, two);

    e = jexl.createExpression("array[0].length()");
    o = e.evaluate(jc);

    out.print("The length of the string at location 0 is : ", o, 21);
}
 
Example #11
Source File: DefaultNotificationManager.java    From syncope with Apache License 2.0 5 votes vote down vote up
private static String evaluate(final String template, final Map<String, Object> jexlVars) {
    StringWriter writer = new StringWriter();
    JexlUtils.newJxltEngine().
            createTemplate(template).
            evaluate(new MapContext(jexlVars), writer);
    return writer.toString();
}
 
Example #12
Source File: TemplateUtils.java    From syncope with Apache License 2.0 5 votes vote down vote up
private static Attr evaluateAttr(final Attr template, final MapContext jexlContext) {
    Attr result = new Attr();
    result.setSchema(template.getSchema());

    if (template.getValues() != null && !template.getValues().isEmpty()) {
        template.getValues().forEach(value -> {
            String evaluated = JexlUtils.evaluate(value, jexlContext);
            if (StringUtils.isNotBlank(evaluated)) {
                result.getValues().add(evaluated);
            }
        });
    }

    return result;
}
 
Example #13
Source File: JEXLItemTransformerImpl.java    From syncope with Apache License 2.0 5 votes vote down vote up
@Override
public List<Object> beforePull(
        final Item item,
        final EntityTO entityTO,
        final List<Object> values) {

    if (StringUtils.isNotBlank(pullJEXL) && values != null) {
        List<Object> newValues = new ArrayList<>(values.size());
        values.forEach(value -> {
            JexlContext jexlContext = new MapContext();
            jexlContext.set("value", value);
            if (entityTO instanceof AnyTO) {
                JexlUtils.addFieldsToContext((AnyTO) entityTO, jexlContext);
                JexlUtils.addAttrsToContext(((AnyTO) entityTO).getPlainAttrs(), jexlContext);
                JexlUtils.addAttrsToContext(((AnyTO) entityTO).getDerAttrs(), jexlContext);
                JexlUtils.addAttrsToContext(((AnyTO) entityTO).getVirAttrs(), jexlContext);
            } else if (entityTO instanceof RealmTO) {
                JexlUtils.addFieldsToContext((RealmTO) entityTO, jexlContext);
            }

            newValues.add(JexlUtils.evaluate(pullJEXL, jexlContext));
        });

        return newValues;
    }

    return JEXLItemTransformer.super.beforePull(item, entityTO, values);
}
 
Example #14
Source File: JEXLItemTransformerImpl.java    From syncope with Apache License 2.0 5 votes vote down vote up
@Override
public Pair<AttrSchemaType, List<PlainAttrValue>> beforePropagation(
        final Item item,
        final Entity entity,
        final AttrSchemaType schemaType,
        final List<PlainAttrValue> values) {

    if (StringUtils.isNotBlank(propagationJEXL) && values != null) {
        values.forEach(value -> {
            Object originalValue = value.getValue();
            if (originalValue != null) {
                JexlContext jexlContext = new MapContext();
                if (entity != null) {
                    JexlUtils.addFieldsToContext(entity, jexlContext);
                    if (entity instanceof Any) {
                        JexlUtils.addPlainAttrsToContext(((Any<?>) entity).getPlainAttrs(), jexlContext);
                        JexlUtils.addDerAttrsToContext(((Any<?>) entity), derAttrHandler, jexlContext);
                    }
                }
                jexlContext.set("value", originalValue);

                value.setBinaryValue(null);
                value.setBooleanValue(null);
                value.setDateValue(null);
                value.setDoubleValue(null);
                value.setLongValue(null);
                value.setStringValue(JexlUtils.evaluate(propagationJEXL, jexlContext));
            }
        });

        return Pair.of(AttrSchemaType.String, values);
    }

    return JEXLItemTransformer.super.beforePropagation(item, entity, schemaType, values);
}
 
Example #15
Source File: LDAPMembershipPropagationActions.java    From syncope with Apache License 2.0 5 votes vote down vote up
private String evaluateGroupConnObjectLink(final String connObjectLinkTemplate, final Group group) {
    LOG.debug("Evaluating connObjectLink for {}", group);

    JexlContext jexlContext = new MapContext();
    JexlUtils.addFieldsToContext(group, jexlContext);
    JexlUtils.addPlainAttrsToContext(group.getPlainAttrs(), jexlContext);
    JexlUtils.addDerAttrsToContext(group, derAttrHandler, jexlContext);

    return JexlUtils.evaluate(connObjectLinkTemplate, jexlContext);
}
 
Example #16
Source File: GlobalVariableValidationAction.java    From android-uiconductor with Apache License 2.0 5 votes vote down vote up
@Override
boolean validateRaw(ActionContext actionContext, AndroidDeviceDriver androidDeviceDriver) {
  // Create or retrieve an engine
  JexlEngine jexl = new JexlBuilder().create();

  // Create an expression
  JexlExpression e = jexl.createExpression(expression);

  JexlContext jc = new MapContext();

  // To use advanced expression, need a converter to do the trick, the expression will be like
  // "uicdTypeConverter.toInt($uicd_var1) + uicdTypeConverter.toInt($uicd_var2)";
  if (expression.contains(TYPE_CONVERTER_OBJ_KEYWORD)) {
    jc.set(TYPE_CONVERTER_OBJ_KEYWORD, new UicdTypeConverter());
  }
  // Create a context and add data
  // jc.set("$uicd_var1", new String("adbcd"));
  // Set the displayStr so that we can see the result in the test details.
  displayStr = expandUicdGlobalVariableToJexl(expression, jc, actionContext);

  // Now evaluate the expression, getting the result
  boolean ret = false;
  try {
    Object o = e.evaluate(jc);
    ret = Boolean.parseBoolean(o.toString());
  } catch (Exception ex) {
    System.out.println(ex.getMessage());
  }
  displayStr = String.format("%s|validation result:%s", displayStr, ret);
  return ret;
}
 
Example #17
Source File: DerAttrHandlerImpl.java    From syncope with Apache License 2.0 5 votes vote down vote up
private static Map<DerSchema, String> getValues(final Any<?> any, final Set<DerSchema> schemas) {
    Map<DerSchema, String> result = new HashMap<>(schemas.size());

    schemas.forEach(schema -> {
        JexlContext jexlContext = new MapContext();
        JexlUtils.addPlainAttrsToContext(any.getPlainAttrs(), jexlContext);
        JexlUtils.addFieldsToContext(any, jexlContext);

        result.put(schema, JexlUtils.evaluate(schema.getExpression(), jexlContext));
    });

    return result;
}
 
Example #18
Source File: MailTemplateTest.java    From syncope with Apache License 2.0 5 votes vote down vote up
private static String evaluate(final String template, final Map<String, Object> jexlVars) {
    StringWriter writer = new StringWriter();
    JexlUtils.newJxltEngine().
            createTemplate(template).
            evaluate(new MapContext(jexlVars), writer);
    return writer.toString();
}
 
Example #19
Source File: JexlUtils.java    From syncope with Apache License 2.0 5 votes vote down vote up
public static boolean evaluateMandatoryCondition(
        final String mandatoryCondition,
        final Any<?> any,
        final DerAttrHandler derAttrHandler) {

    JexlContext jexlContext = new MapContext();
    addPlainAttrsToContext(any.getPlainAttrs(), jexlContext);
    addDerAttrsToContext(any, derAttrHandler, jexlContext);

    return Boolean.parseBoolean(evaluate(mandatoryCondition, jexlContext));
}
 
Example #20
Source File: AntennaDoctorEngine.java    From datacollector with Apache License 2.0 5 votes vote down vote up
public List<AntennaDoctorMessage> onValidation(AntennaDoctorStageContext context, String groupName, String configName, ErrorCode errorCode, Object... args) {
  JexlContext jexlContext = new MapContext();
  jexlContext.set("issue", new StageIssueJexl(groupName, configName, errorCode, args));
  jexlContext.set("stageDef", context.getStageDefinition());
  jexlContext.set("stageConf", context.getStageConfiguration());
  return evaluate(context, AntennaDoctorRuleBean.Entity.VALIDATION, jexlContext);
}
 
Example #21
Source File: AntennaDoctorEngine.java    From datacollector with Apache License 2.0 5 votes vote down vote up
public List<AntennaDoctorMessage> onStage(AntennaDoctorStageContext context, String errorMessage) {
  JexlContext jexlContext = new MapContext();
  jexlContext.set("issue", new StageIssueJexl(errorMessage));
  jexlContext.set("stageDef", context.getStageDefinition());
  jexlContext.set("stageConf", context.getStageConfiguration());
  return evaluate(context, AntennaDoctorRuleBean.Entity.STAGE, jexlContext);
}
 
Example #22
Source File: AntennaDoctorEngine.java    From datacollector with Apache License 2.0 5 votes vote down vote up
public List<AntennaDoctorMessage> onStage(AntennaDoctorStageContext context, ErrorCode errorCode, Object... args) {
  JexlContext jexlContext = new MapContext();
  jexlContext.set("issue", new StageIssueJexl(errorCode, args));
  jexlContext.set("stageDef", context.getStageDefinition());
  jexlContext.set("stageConf", context.getStageConfiguration());
  return evaluate(context, AntennaDoctorRuleBean.Entity.STAGE, jexlContext);
}
 
Example #23
Source File: AntennaDoctorEngine.java    From datacollector with Apache License 2.0 5 votes vote down vote up
public List<AntennaDoctorMessage> onStage(AntennaDoctorStageContext context, Exception exception) {
  JexlContext jexlContext = new MapContext();
  jexlContext.set("issue", new StageIssueJexl(exception));
  jexlContext.set("stageDef", context.getStageDefinition());
  jexlContext.set("stageConf", context.getStageConfiguration());
  return evaluate(context, AntennaDoctorRuleBean.Entity.STAGE, jexlContext);
}
 
Example #24
Source File: ExpressionLanguageJEXLImpl.java    From oval with Eclipse Public License 2.0 5 votes vote down vote up
@Override
@SuppressWarnings("unchecked")
public Object evaluate(final String expression, final Map<String, ?> values) throws ExpressionEvaluationException {
   LOG.debug("Evaluating JEXL expression: {1}", expression);
   try {
      final JexlExpression expr = expressionCache.get(expression);
      return expr.evaluate(new MapContext((Map<String, Object>) values));
   } catch (final Exception ex) {
      throw new ExpressionEvaluationException("Evaluating JEXL expression failed: " + expression, ex);
   }
}
 
Example #25
Source File: AntennaDoctorEngine.java    From datacollector with Apache License 2.0 4 votes vote down vote up
public List<AntennaDoctorMessage> onRest(AntennaDoctorContext context, Exception exception) {
  JexlContext jexlContext = new MapContext();
  jexlContext.set("issue", new StageIssueJexl(exception));
  return evaluate(context, AntennaDoctorRuleBean.Entity.REST, jexlContext);
}
 
Example #26
Source File: AntennaDoctorEngine.java    From datacollector with Apache License 2.0 4 votes vote down vote up
public List<AntennaDoctorMessage> onRest(AntennaDoctorContext context, ErrorCode errorCode, Object... args) {
  JexlContext jexlContext = new MapContext();
  jexlContext.set("issue", new StageIssueJexl(errorCode, args));
  return evaluate(context, AntennaDoctorRuleBean.Entity.REST, jexlContext);
}
 
Example #27
Source File: MethodPropertyTest.java    From tools-journey with Apache License 2.0 4 votes vote down vote up
/**
 * An example for method access.
 */
public static void example(final Output out) throws Exception {
    /**
     * First step is to retrieve an instance of a JexlEngine;
     * it might be already existing and shared or created anew.
     */
    JexlEngine jexl = new JexlBuilder().create();
    /*
     *  Second make a jexlContext and put stuff in it
     */
    JexlContext jc = new MapContext();

    /**
     * The Java equivalents of foo and number for comparison and checking
     */
    Foo foo = new Foo();
    Integer number = new Integer(10);

    jc.set("foo", foo);
    jc.set("number", number);

    /*
     *  access a method w/o args
     */
    JexlExpression e = jexl.createExpression("foo.getFoo()");
    Object o = e.evaluate(jc);
    out.print("value returned by the method getFoo() is : ", o, foo.getFoo());

    /*
     *  access a method w/ args
     */
    e = jexl.createExpression("foo.convert(1)");
    o = e.evaluate(jc);
    out.print("value of " + e.getParsedText() + " is : ", o, foo.convert(1));

    e = jexl.createExpression("foo.convert(1+7)");
    o = e.evaluate(jc);
    out.print("value of " + e.getParsedText() + " is : ", o, foo.convert(1+7));

    e = jexl.createExpression("foo.convert(1+number)");
    o = e.evaluate(jc);
    out.print("value of " + e.getParsedText() + " is : ", o, foo.convert(1+number.intValue()));

    /*
     * access a property
     */
    e = jexl.createExpression("foo.bar");
    o = e.evaluate(jc);
    out.print("value returned for the property 'bar' is : ", o, foo.get("bar"));

}
 
Example #28
Source File: MethodPropertyTest.java    From commons-jexl with Apache License 2.0 4 votes vote down vote up
/**
 * An example for method access.
 */
public static void example(final Output out) throws Exception {
    /*
     * First step is to retrieve an instance of a JexlEngine;
     * it might be already existing and shared or created anew.
     */
    JexlEngine jexl = new JexlBuilder().create();
    /*
     *  Second make a jexlContext and put stuff in it
     */
    JexlContext jc = new MapContext();

    /*
     * The Java equivalents of foo and number for comparison and checking
     */
    Foo foo = new Foo();
    Integer number = 10;

    jc.set("foo", foo);
    jc.set("number", number);

    /*
     *  access a method w/o args
     */
    JexlExpression e = jexl.createExpression("foo.getFoo()");
    Object o = e.evaluate(jc);
    out.print("value returned by the method getFoo() is : ", o, foo.getFoo());

    /*
     *  access a method w/ args
     */
    e = jexl.createExpression("foo.convert(1)");
    o = e.evaluate(jc);
    out.print("value of " + e.getParsedText() + " is : ", o, foo.convert(1));

    e = jexl.createExpression("foo.convert(1+7)");
    o = e.evaluate(jc);
    out.print("value of " + e.getParsedText() + " is : ", o, foo.convert(1+7));

    e = jexl.createExpression("foo.convert(1+number)");
    o = e.evaluate(jc);
    out.print("value of " + e.getParsedText() + " is : ", o, foo.convert(1+ number));

    /*
     * access a property
     */
    e = jexl.createExpression("foo.bar");
    o = e.evaluate(jc);
    out.print("value returned for the property 'bar' is : ", o, foo.get("bar"));

}
 
Example #29
Source File: JEXLTemplateModel.java    From jweb-cms with GNU Affero General Public License v3.0 4 votes vote down vote up
@Override
public Object eval(int expressionId, Map<String, Object> bindings) {
    return expressions.get(expressionId).evaluate(new MapContext(bindings));
}
 
Example #30
Source File: JexlProvider.java    From joyrpc with Apache License 2.0 4 votes vote down vote up
@Override
public Object evaluate(final Map<String, Object> context) {
    return expression.evaluate(new MapContext(context));
}