org.wso2.balana.ctx.EvaluationCtx Java Examples

The following examples show how to use org.wso2.balana.ctx.EvaluationCtx. 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: DenyUnlessPermitRuleAlg.java    From balana with Apache License 2.0 6 votes vote down vote up
@Override
public AbstractResult combine(EvaluationCtx context, List parameters, List ruleElements) {

    List<ObligationResult> denyObligations = new ArrayList<ObligationResult>();
    List<Advice> denyAdvices = new ArrayList<Advice>();
    
    for (Object ruleElement : ruleElements) {
        Rule rule = ((RuleCombinerElement) (ruleElement)).getRule();
        AbstractResult result = rule.evaluate(context);
        int value = result.getDecision();

        // if there was a value of PERMIT, then regardless of what else
        // we've seen, we always return PERMIT
        if (value == AbstractResult.DECISION_PERMIT) {
            return result;
        } else if(value == AbstractResult.DECISION_DENY){
            denyObligations.addAll(result.getObligations());
            denyAdvices.addAll(result.getAdvices());
        }
    }

    // if there is not any value of PERMIT. The return DENY
    return ResultFactory.getFactory().getResult(AbstractResult.DECISION_DENY, denyObligations,
                                                                        denyAdvices, context);
}
 
Example #2
Source File: TargetMatchGroup.java    From balana with Apache License 2.0 6 votes vote down vote up
/**
 * Determines whether this <code>TargetMatchGroup</code> matches the input request (whether it
 * is applicable).
 * 
 * @param context the representation of the request
 * 
 * @return the result of trying to match the group with the context
 */
public MatchResult match(EvaluationCtx context) {
    MatchResult result = null;
    
    if (matches.isEmpty()) {
        // nothing in target, return match
        return new MatchResult(MatchResult.MATCH);
    }

    for (TargetMatch targetMatch : matches) {
        result = targetMatch.match(context);
        if (result.getResult() != MatchResult.MATCH)
            break;
    }

    return result;
}
 
Example #3
Source File: MobiAttributeFinder.java    From mobi with GNU Affero General Public License v3.0 6 votes vote down vote up
@Override
public EvaluationResult findAttribute(URI attributeType, URI attributeId, String issuer, URI category,
                                      EvaluationCtx context) {
    if (!categoryIds.contains(category.toString())) {
        return new EvaluationResult(new Status(Collections.singletonList(Status.STATUS_PROCESSING_ERROR),
                "Unsupported category"));
    }

    BasicAttributeDesignator designator = new BasicAttributeDesignator(vf.createIRI(attributeId.toString()),
            vf.createIRI(category.toString()), vf.createIRI(attributeType.toString()));
    List<Literal> values = pip.findAttribute(designator, new BalanaRequest(context.getRequestCtx(), vf, jaxbContext));
    List<AttributeValue> attributeValues = new ArrayList<>();
    values.stream()
            .map(this::getAttributeValue)
            .forEach(attributeValues::add);

    return new EvaluationResult(new BagAttribute(attributeType, attributeValues));
}
 
Example #4
Source File: DefaultResourceFinder.java    From carbon-identity-framework with Apache License 2.0 6 votes vote down vote up
@Override
public Set<String> findDescendantResources(String parentResourceId, EvaluationCtx context) throws Exception {
    Set<String> resourceSet = new HashSet<String>();
    registry = EntitlementServiceComponent.getRegistryService().getSystemRegistry(CarbonContext.
            getThreadLocalCarbonContext().getTenantId());
    if (registry.resourceExists(parentResourceId)) {
        Resource resource = registry.get(parentResourceId);
        if (resource instanceof Collection) {
            Collection collection = (Collection) resource;
            String[] resources = collection.getChildren();
            for (String res : resources) {
                resourceSet.add(res);
                getChildResources(res, resourceSet);
            }
        } else {
            return null;
        }
    }
    return resourceSet;
}
 
Example #5
Source File: FirstApplicableRuleAlg.java    From balana with Apache License 2.0 6 votes vote down vote up
/**
 * Applies the combining rule to the set of rules based on the evaluation context.
 * 
 * @param context the context from the request
 * @param parameters a (possibly empty) non-null <code>List</code> of
 *            <code>CombinerParameter<code>s
 * @param ruleElements the rules to combine
 * 
 * @return the result of running the combining algorithm
 */
public AbstractResult combine(EvaluationCtx context, List parameters, List ruleElements) {
    Iterator it = ruleElements.iterator();
    while (it.hasNext()) {
        Rule rule = ((RuleCombinerElement) (it.next())).getRule();
        AbstractResult result = rule.evaluate(context);
        int value = result.getDecision();

        // in the case of PERMIT, DENY, or INDETERMINATE, we always
        // just return that result, so only on a rule that doesn't
        // apply do we keep going...
        if (value != Result.DECISION_NOT_APPLICABLE) {
            return result;
        }
    }

    // if we got here, then none of the rules applied
    return ResultFactory.getFactory().getResult(Result.DECISION_NOT_APPLICABLE, context);
}
 
Example #6
Source File: DefaultResourceFinder.java    From carbon-identity with Apache License 2.0 6 votes vote down vote up
@Override
public Set<String> findDescendantResources(String parentResourceId, EvaluationCtx context) throws Exception {
    Set<String> resourceSet = new HashSet<String>();
    registry = EntitlementServiceComponent.getRegistryService().getSystemRegistry(CarbonContext.
            getThreadLocalCarbonContext().getTenantId());
    if (registry.resourceExists(parentResourceId)) {
        Resource resource = registry.get(parentResourceId);
        if (resource instanceof Collection) {
            Collection collection = (Collection) resource;
            String[] resources = collection.getChildren();
            for (String res : resources) {
                resourceSet.add(res);
                getChildResources(res, resourceSet);
            }
        } else {
            return null;
        }
    }
    return resourceSet;
}
 
Example #7
Source File: PermitUnlessDenyRuleAlg.java    From balana with Apache License 2.0 6 votes vote down vote up
@Override
public AbstractResult combine(EvaluationCtx context, List parameters, List ruleElements) {

    List<ObligationResult> permitObligations = new ArrayList<ObligationResult>();
    List<Advice> permitAdvices= new ArrayList<Advice>();

    for (Object ruleElement : ruleElements) {
        Rule rule = ((RuleCombinerElement) (ruleElement)).getRule();
        AbstractResult result = rule.evaluate(context);
        int value = result.getDecision();

        // if there was a value of DENY, then regardless of what else
        // we've seen, we always return DENY
        if (value == AbstractResult.DECISION_DENY) {
            return result;
        } else if(value == AbstractResult.DECISION_PERMIT){
            permitObligations.addAll(result.getObligations());
            permitAdvices.addAll(result.getAdvices());
        }
    }

    // if there is not any value of DENY. The return PERMIT
    return ResultFactory.getFactory().getResult(AbstractResult.DECISION_PERMIT,
                                                permitObligations, permitAdvices, context);
}
 
Example #8
Source File: HighestEffectRuleAlg.java    From balana with Apache License 2.0 6 votes vote down vote up
@Override
public AbstractResult combine(EvaluationCtx context, List parameters, List ruleElements) {

    int noOfDenyRules = 0;
    int noOfPermitRules = 0;

    for (Object ruleElement : ruleElements) {
        
        Rule rule = ((RuleCombinerElement) (ruleElement)).getRule();
        AbstractResult result = rule.evaluate(context);

        int value = result.getDecision();
        if (value == Result.DECISION_DENY) {
            noOfDenyRules++;
        } else if (value == Result.DECISION_PERMIT) {
            noOfPermitRules++;
        }
    }

    if(noOfPermitRules > noOfDenyRules){
        return ResultFactory.getFactory().getResult(Result.DECISION_PERMIT, context);            
    } else {
        return ResultFactory.getFactory().getResult(Result.DECISION_DENY, context);     
    }
}
 
Example #9
Source File: SampleAttributeFinderModule.java    From balana with Apache License 2.0 6 votes vote down vote up
@Override
public EvaluationResult findAttribute(URI attributeType, URI attributeId, String issuer,
                                                        URI category, EvaluationCtx context) {
    String roleName = null;
    List<AttributeValue> attributeValues = new ArrayList<AttributeValue>();

    EvaluationResult result = context.getAttribute(attributeType, defaultSubjectId, issuer, category);
    if(result != null && result.getAttributeValue() != null && result.getAttributeValue().isBag()){
        BagAttribute bagAttribute = (BagAttribute) result.getAttributeValue();
        if(bagAttribute.size() > 0){
            String userName = ((AttributeValue) bagAttribute.iterator().next()).encode();
            roleName = findRole(userName);
        }
    }

    if (roleName != null) {
        attributeValues.add(new StringAttribute(roleName));
    }

    return new EvaluationResult(new BagAttribute(attributeType, attributeValues));
}
 
Example #10
Source File: TestResourceFinderModule.java    From balana with Apache License 2.0 6 votes vote down vote up
/**
 * Finds the children resources associated with the given root,
 * assuming the hierarchy is one that this module handles.
 *
 * @param root the root resource in the hierarchy
 * @param context the evaluation's context
 *
 * @return the resource hierarchy
 */
public ResourceFinderResult findChildResources(AttributeValue root,
                                               EvaluationCtx context) {
    // make sure we can handle this hierarchy
    if (! requestApplies(root))
        return new ResourceFinderResult();

    // add the root to the set of resolved resources
    HashSet set = new HashSet();
    set.add(root);

    // add the other resources, which are defined by the conformance tests
    try {
        set.add(new AnyURIAttribute(new URI("urn:root:child1")));
        set.add(new AnyURIAttribute(new URI("urn:root:child2")));
    } catch (URISyntaxException urise) {
        // this will never happen
    }

    return new ResourceFinderResult(set);
}
 
Example #11
Source File: PolicyReference.java    From balana with Apache License 2.0 6 votes vote down vote up
/**
     * Tries to evaluate the policy by calling the combining algorithm on the given policies or
     * rules. The <code>match</code> method must always be called first, and must always return
     * MATCH, before this method is called.
     * 
     * @param context the representation of the request
     * 
     * @return the result of evaluation
     */
    public AbstractResult evaluate(EvaluationCtx context) {
        // if there is no finder, then we return NotApplicable
        if (finder == null){
            //return new Result(Result.DECISION_NOT_APPLICABLE, context.getResourceId().encode());
            return ResultFactory.getFactory().getResult(Result.DECISION_NOT_APPLICABLE, context);
        }

        PolicyFinderResult pfr = finder.findPolicy(reference, policyType, constraints,
                parentMetaData);

        // if we found nothing, then we return NotApplicable
        if (pfr.notApplicable()){
            //return new Result(Result.DECISION_NOT_APPLICABLE, context.getResourceId().encode());
            return ResultFactory.getFactory().getResult(Result.DECISION_NOT_APPLICABLE, context);
        }
        // if there was an error, we return that status data
        if (pfr.indeterminate()){
//            return new Result(Result.DECISION_INDETERMINATE, pfr.getStatus(), context
//                    .getResourceId().encode());
            return ResultFactory.getFactory().getResult(Result.DECISION_INDETERMINATE, pfr.getStatus(), context);
        }
        // we must have found a policy
        return pfr.getPolicy().evaluate(context);
    }
 
Example #12
Source File: FunctionBase.java    From balana with Apache License 2.0 6 votes vote down vote up
/**
 * Evaluates each of the parameters, in order, filling in the argument array with the resulting
 * values. If any error occurs, this method returns the error, otherwise null is returned,
 * signalling that evaluation was successful for all inputs, and the resulting argument list can
 * be used.
 * 
 * @param params a <code>List</code> of <code>Evaluatable</code> objects representing the
 *            parameters to evaluate
 * @param context the representation of the request
 * @param args an array as long as the params <code>List</code> that will, on return, contain
 *            the <code>AttributeValue</code>s generated from evaluating all parameters
 * 
 * @return <code>null</code> if no errors were encountered, otherwise an
 *         <code>EvaluationResult</code> representing the error
 */
protected EvaluationResult evalArgs(List<Evaluatable> params, EvaluationCtx context, AttributeValue[] args) {
    Iterator it = params.iterator();
    int index = 0;

    while (it.hasNext()) {
        // get and evaluate the next parameter
        Evaluatable eval = (Evaluatable) (it.next());
        EvaluationResult result = eval.evaluate(context);

        // If there was an error, pass it back...
        if (result.indeterminate()){
            return result;
        }
        // ...otherwise save it and keep going
        args[index++] = result.getAttributeValue();
    }

    // if no error occurred then we got here, so we return no errors
    return null;
}
 
Example #13
Source File: CurrentEnvModule.java    From balana with Apache License 2.0 6 votes vote down vote up
/**
 * Used to get the current time, date, or dateTime. If one of those values isn't being asked
 * for, or if the types are wrong, then an empty bag is returned.
 * 
 * @param attributeType the datatype of the attributes to find, which must be time, date, or
 *            dateTime for this module to resolve a value
 * @param attributeId the identifier of the attributes to find, which must be one of the three
 *            ENVIRONMENT_* fields for this module to resolve a value
 * @param issuer the issuer of the attributes, or null if unspecified
 * @param category the category of the attribute 
 * @param context the representation of the request data
 * 
 * @return the result of attribute retrieval, which will be a bag with a single attribute, an
 *         empty bag, or an error
 */
public EvaluationResult findAttribute(URI attributeType, URI attributeId, String issuer,
        URI category, EvaluationCtx context) {
    // we only know about environment attributes
    if (!XACMLConstants.ENT_CATEGORY.equals(category.toString())){
        return new EvaluationResult(BagAttribute.createEmptyBag(attributeType));
    }
    // figure out which attribute we're looking for
    String attrName = attributeId.toString();

    if (attrName.equals(ENVIRONMENT_CURRENT_TIME)) {
        return handleTime(attributeType, issuer, context);
    } else if (attrName.equals(ENVIRONMENT_CURRENT_DATE)) {
        return handleDate(attributeType, issuer, context);
    } else if (attrName.equals(ENVIRONMENT_CURRENT_DATETIME)) {
        return handleDateTime(attributeType, issuer, context);
    }

    // if we got here, then it's an attribute that we don't know
    return new EvaluationResult(BagAttribute.createEmptyBag(attributeType));
}
 
Example #14
Source File: XACML3HigherOrderFunction.java    From balana with Apache License 2.0 6 votes vote down vote up
private EvaluationResult getEvaluationResult(EvaluationCtx context, Function function, AttributeValue val1,
                                             AttributeValue val2, boolean isAllFunction) {

    List<Evaluatable> params = new ArrayList<>();
    params.add(val1);
    params.add(val2);
    EvaluationResult result = function.evaluate(params, context);

    if (result.indeterminate()) {
        return result;
    }

    BooleanAttribute bool = (BooleanAttribute) (result.getAttributeValue());
    if (bool.getValue() != isAllFunction) {
        return result;
    }
    return null;
}
 
Example #15
Source File: ResourceFinder.java    From balana with Apache License 2.0 6 votes vote down vote up
/**
 * Finds Resource Ids using the Descendants scope, and returns all resolved identifiers as well
 * as any errors that occurred. If no modules can handle the given Resource Id, then an empty
 * result is returned.
 * 
 * @param parentResourceId the root of the resources
 * @param context the representation of the request data
 * 
 * @return the result of looking for descendant resources
 */
public ResourceFinderResult findDescendantResources(AttributeValue parentResourceId,
        EvaluationCtx context) {
    Iterator it = descendantModules.iterator();

    while (it.hasNext()) {
        ResourceFinderModule module = (ResourceFinderModule) (it.next());

        // ask the module to find the resources
        ResourceFinderResult result = module.findDescendantResources(parentResourceId, context);

        // if we found something, then always return that result
        if (!result.isEmpty())
            return result;
    }

    // no modules applied, so we return an empty result
    logger.info("No ResourceFinderModule existed to handle the " + "descendants of "
            + parentResourceId.encode());

    return new ResourceFinderResult();
}
 
Example #16
Source File: SampleAttributeFinderModule.java    From balana with Apache License 2.0 6 votes vote down vote up
@Override
public EvaluationResult findAttribute(URI attributeType, URI attributeId, String issuer,
                                                        URI category, EvaluationCtx context) {
    String roleName = null;
    List<AttributeValue> attributeValues = new ArrayList<AttributeValue>();

    EvaluationResult result = context.getAttribute(attributeType, defaultSubjectId, issuer, category);
    if(result != null && result.getAttributeValue() != null && result.getAttributeValue().isBag()){
        BagAttribute bagAttribute = (BagAttribute) result.getAttributeValue();
        if(bagAttribute.size() > 0){
            String userName = ((AttributeValue) bagAttribute.iterator().next()).encode();
            roleName = findRole(userName);
        }
    }

    if (roleName != null) {
        attributeValues.add(new StringAttribute(roleName));
    }

    return new EvaluationResult(new BagAttribute(attributeType, attributeValues));
}
 
Example #17
Source File: HigherOrderFunction.java    From balana with Apache License 2.0 6 votes vote down vote up
/**
 * Private helper for the all-of-any and any-of-all functions
 */
private EvaluationResult allAnyHelper(BagAttribute anyBag, BagAttribute allBag,
		Function function, EvaluationCtx context, boolean argumentsAreSwapped) {
	Iterator it = allBag.iterator();

	while (it.hasNext()) {
		AttributeValue value = (AttributeValue) (it.next());
		EvaluationResult result = any(value, anyBag, function, context, argumentsAreSwapped);

		if (result.indeterminate())
			return result;

		if (!((BooleanAttribute) (result.getAttributeValue())).getValue())
			return result;
	}

	return new EvaluationResult(BooleanAttribute.getTrueInstance());
}
 
Example #18
Source File: Target.java    From balana with Apache License 2.0 6 votes vote down vote up
/**
 * Determines whether this <code>Target</code> matches the input request (whether it is
 * applicable).
 *
 * @param context the representation of the request
 *
 * @return the result of trying to match the target and the request
 */
public MatchResult match(EvaluationCtx context) {

    Status firstIndeterminateStatus = null;

    for (AnyOfSelection anyOfSelection : anyOfSelections) {
        MatchResult result = anyOfSelection.match(context);
        if (result.getResult() == MatchResult.NO_MATCH){
            return result;
        } else if(result.getResult() == MatchResult.INDETERMINATE){
            if(firstIndeterminateStatus == null){
                firstIndeterminateStatus = result.getStatus();    
            }
        }
    }

    if(firstIndeterminateStatus == null){
        return new MatchResult(MatchResult.MATCH);
    } else {
        return new MatchResult(MatchResult.INDETERMINATE,
                               firstIndeterminateStatus);
    }
}
 
Example #19
Source File: EqualFunction.java    From balana with Apache License 2.0 6 votes vote down vote up
/**
 * Evaluate the function, using the specified parameters.
 * 
 * @param inputs a <code>List</code> of <code>Evaluatable</code> objects representing the
 *            arguments passed to the function
 * @param context an <code>EvaluationCtx</code> so that the <code>Evaluatable</code> objects can
 *            be evaluated
 * @return an <code>EvaluationResult</code> representing the function's result
 */
public EvaluationResult evaluate(List<Evaluatable> inputs, EvaluationCtx context) {

    // Evaluate the arguments
    AttributeValue[] argValues = new AttributeValue[inputs.size()];
    EvaluationResult result = evalArgs(inputs, context, argValues);
    if (result != null)
        return result;

    if (argValues[1] instanceof StringAttribute
            && XACMLConstants.ANY.equals(((StringAttribute) argValues[1]).getValue())) {
        return EvaluationResult.getInstance(true);
    }

    // Now that we have real values, perform the equals operation
    if(getFunctionId() == ID_EQUAL_CASE_IGNORE){
        return EvaluationResult.getInstance(argValues[0].encode().toLowerCase().
                equals(argValues[1].encode().toLowerCase()));            
    }  else {
        return EvaluationResult.getInstance(argValues[0].equals(argValues[1]));
    }
}
 
Example #20
Source File: IPInRangeFunction.java    From balana with Apache License 2.0 6 votes vote down vote up
/**
 * Evaluates the ip-in-range function, which takes three <code>IPAddressAttribute</code> values.
 * This function return true if the first value falls between the second and third values
 *
 * @param inputs a <code>List</code> of <code>Evaluatable</code> objects representing the
 *            arguments passed to the function
 * @param context the respresentation of the request
 *
 * @return an <code>EvaluationResult</code> containing true or false
 */
public EvaluationResult evaluate(List inputs, EvaluationCtx context) {


    AttributeValue[] argValues = new AttributeValue[inputs.size()];
    EvaluationResult result = evalArgs(inputs, context, argValues);

    // check if any errors occured while resolving the inputs
    if (result != null)
        return result;

    // get the three ip values
    long ipAddressToTest = ipToLong(((IPAddressAttribute)argValues[0]).getAddress());
    long ipAddressMin = ipToLong(((IPAddressAttribute)argValues[1]).getAddress());
    long ipAddressMax = ipToLong(((IPAddressAttribute)argValues[2]).getAddress());

    if(ipAddressMin > ipAddressMax){
        long temp = ipAddressMax;
        ipAddressMax = ipAddressMin;
        ipAddressMin = temp;
    }

    // we're in the range if the middle is now between min and max ip address
    return EvaluationResult.getInstance(ipAddressToTest >= ipAddressMin && ipAddressToTest <= ipAddressMax);
}
 
Example #21
Source File: NotFunction.java    From balana with Apache License 2.0 5 votes vote down vote up
/**
 * Evaluate the function, using the specified parameters.
 * 
 * @param inputs a <code>List</code> of <code>Evaluatable</code> objects representing the
 *            arguments passed to the function
 * @param context an <code>EvaluationCtx</code> so that the <code>Evaluatable</code> objects can
 *            be evaluated
 * @return an <code>EvaluationResult</code> representing the function's result
 */
public EvaluationResult evaluate(List inputs, EvaluationCtx context) {

    // Evaluate the arguments
    AttributeValue[] argValues = new AttributeValue[inputs.size()];
    EvaluationResult result = evalArgs(inputs, context, argValues);
    if (result != null)
        return result;

    // Now that we have a real value, perform the not operation.
    boolean arg = ((BooleanAttribute) argValues[0]).getValue();
    return EvaluationResult.getInstance(!arg);
}
 
Example #22
Source File: RoundFunction.java    From balana with Apache License 2.0 5 votes vote down vote up
/**
 * Evaluate the function, using the specified parameters.
 * 
 * @param inputs a <code>List</code> of <code>Evaluatable</code> objects representing the
 *            arguments passed to the function
 * @param context an <code>EvaluationCtx</code> so that the <code>Evaluatable</code> objects can
 *            be evaluated
 * @return an <code>EvaluationResult</code> representing the function's result
 */
public EvaluationResult evaluate(List inputs, EvaluationCtx context) {

    // Evaluate the arguments
    AttributeValue[] argValues = new AttributeValue[inputs.size()];
    EvaluationResult result = evalArgs(inputs, context, argValues);
    if (result != null)
        return result;

    // Now that we have real values, perform the round operation
    double arg = ((DoubleAttribute) argValues[0]).getValue();
    BigDecimal roundValue = new BigDecimal(arg);

    return new EvaluationResult(new DoubleAttribute(roundValue.setScale(0, RoundingMode.HALF_EVEN).doubleValue()));
}
 
Example #23
Source File: XACML3HigherOrderFunction.java    From balana with Apache License 2.0 5 votes vote down vote up
private EvaluationResult anyAndAllHelper(EvaluationCtx context, Function function, List<AttributeValue> values,
                                         BagAttribute bag, boolean isAllFunction) {

    Iterator it = bag.iterator();
    while (it.hasNext()) {
        AttributeValue bagValue = (AttributeValue) (it.next());
        for (AttributeValue value : values) {
            EvaluationResult result = getEvaluationResult(context, function, value, bagValue, isAllFunction);
            if (result != null) {
                return result;
            }
        }
    }
    return new EvaluationResult(BooleanAttribute.getInstance(isAllFunction));
}
 
Example #24
Source File: SubStringFunction.java    From balana with Apache License 2.0 5 votes vote down vote up
public EvaluationResult evaluate(List<Evaluatable> inputs, EvaluationCtx context) {

        // Evaluate the arguments
        AttributeValue[] argValues = new AttributeValue[inputs.size()];
        EvaluationResult result = evalArgs(inputs, context, argValues);
        if (result != null) {
            return result;
        }

        String processedString = argValues[0].encode().substring(Integer.parseInt(argValues[1].encode()),
                                                        Integer.parseInt(argValues[2].encode()));

        return new EvaluationResult(new StringAttribute(processedString));
    }
 
Example #25
Source File: StringComparingFunction.java    From balana with Apache License 2.0 5 votes vote down vote up
public EvaluationResult evaluate(List<Evaluatable> inputs, EvaluationCtx context) {

        // Evaluate the arguments
        AttributeValue[] argValues = new AttributeValue[inputs.size()];
        EvaluationResult result = evalArgs(inputs, context, argValues);
        if (result != null) {
            return result;
        }

        int id = getFunctionId();

        if(id == ID_STRING_START_WITH || id == ID_ANY_URI_START_WITH){
            // do not want to check for anyURI and String data types. As both attribute values would
            // returns String data type after encode() is done,
            return EvaluationResult.getInstance(argValues[1].encode().
                                                            startsWith(argValues[0].encode()));
        } else if(id == ID_STRING_ENDS_WITH || id == ID_ANY_URI_ENDS_WITH){
            // do not want to check for anyURI and String data types. As both attribute values would
            // returns String data type after encode() is done,
            return EvaluationResult.getInstance(argValues[1].encode().
                                                            endsWith(argValues[0].encode()));
        } else {
            // do not want to check for anyURI and String data types. As both attribute values would
            // returns String data type after encode() is done,
            return EvaluationResult.getInstance(argValues[1].encode().
                                                            contains(argValues[0].encode()));
        }
    }
 
Example #26
Source File: ModFunction.java    From balana with Apache License 2.0 5 votes vote down vote up
/**
 * Evaluate the function, using the specified parameters.
 * 
 * @param inputs a <code>List</code> of <code>Evaluatable</code> objects representing the
 *            arguments passed to the function
 * @param context an <code>EvaluationCtx</code> so that the <code>Evaluatable</code> objects can
 *            be evaluated
 * @return an <code>EvaluationResult</code> representing the function's result
 */
public EvaluationResult evaluate(List inputs, EvaluationCtx context) {

    // Evaluate the arguments
    AttributeValue[] argValues = new AttributeValue[inputs.size()];
    EvaluationResult result = evalArgs(inputs, context, argValues);
    if (result != null)
        return result;

    // Now that we have real values, perform the mod operation
    long arg0 = ((IntegerAttribute) argValues[0]).getValue();
    long arg1 = ((IntegerAttribute) argValues[1]).getValue();

    return new EvaluationResult(new IntegerAttribute(arg0 % arg1));
}
 
Example #27
Source File: FloorFunction.java    From balana with Apache License 2.0 5 votes vote down vote up
/**
 * Evaluate the function, using the specified parameters.
 * 
 * @param inputs a <code>List</code> of <code>Evaluatable</code> objects representing the
 *            arguments passed to the function
 * @param context an <code>EvaluationCtx</code> so that the <code>Evaluatable</code> objects can
 *            be evaluated
 * @return an <code>EvaluationResult</code> representing the function's result
 */
public EvaluationResult evaluate(List inputs, EvaluationCtx context) {

    // Evaluate the arguments
    AttributeValue[] argValues = new AttributeValue[inputs.size()];
    EvaluationResult result = evalArgs(inputs, context, argValues);
    if (result != null)
        return result;

    // Now that we have real values, perform the floor operation
    double arg = ((DoubleAttribute) argValues[0]).getValue();

    return new EvaluationResult(new DoubleAttribute(Math.floor(arg)));
}
 
Example #28
Source File: AnyOfSelection.java    From balana with Apache License 2.0 5 votes vote down vote up
/**
     * Determines whether this <code>AnyOfSelection</code> matches the input request (whether it
     * is applicable).
     *
     * @param context the representation of the request
     *
     * @return the result of trying to match the group with the context
     */
    public MatchResult match(EvaluationCtx context) {

        // if we apply to anything, then we always match
//        if (allOfSelections.isEmpty())                   TODO 
//            return new MatchResult(MatchResult.MATCH);

        // there are specific matching elements, so prepare to iterate
        // through the list
        Status firstIndeterminateStatus = null;

        // in order for this section to match, one of the groups must match
        for (AllOfSelection group : allOfSelections) {
            // get the next group and try matching it
            MatchResult result = group.match(context);

            // we only need one match, so if this matched, then we're done
            if (result.getResult() == MatchResult.MATCH){
                return result;
            }
            // if we didn't match then it was either a NO_MATCH or
            // INDETERMINATE...in the second case, we need to remember
            // it happened, 'cause if we don't get a MATCH, then we'll
            // be returning INDETERMINATE
            if (result.getResult() == MatchResult.INDETERMINATE) {
                if (firstIndeterminateStatus == null)
                    firstIndeterminateStatus = result.getStatus();
            }
        }

        // if we got here, then none of the sub-matches passed, so
        // we have to see if we got any INDETERMINATE cases
        if (firstIndeterminateStatus == null){
            return new MatchResult(MatchResult.NO_MATCH);
        } else {
            return new MatchResult(MatchResult.INDETERMINATE,
                                   firstIndeterminateStatus);
        }
    }
 
Example #29
Source File: VariableReference.java    From balana with Apache License 2.0 5 votes vote down vote up
/**
 * Evaluates the referenced expression using the given context, and either returns an error or a
 * resulting value. If this doesn't reference an evaluatable expression (eg, a single Function)
 * then this will throw an exception.
 *
 * @param context the representation of the request
 * @return the result of evaluation
 */
public EvaluationResult evaluate(EvaluationCtx context) {
    Expression xpr = getReferencedDefinition().getExpression();

    // Note that it's technically possible for this expression to
    // be something like a Function, which isn't Evaluatable. It
    // wouldn't make sense to have this, but it is possible. Because
    // it makes no sense, however, it's unlcear exactly what the
    // error should be, so raising the ClassCastException here seems
    // as good an approach as any for now...
    return ((Evaluatable) xpr).evaluate(context);
}
 
Example #30
Source File: AllOfSelection.java    From balana with Apache License 2.0 5 votes vote down vote up
/**
 *
 * Determines whether this <code>AllOfSelection</code> matches the input request (whether it
 * is applicable).
 *
 * @param context the representation of the request
 *
 * @return the result of trying to match the group with the context
 */
public MatchResult match(EvaluationCtx context){

    // there are specific matching elements, so prepare to iterate
    // through the list
    Status firstIndeterminateStatus = null;
    MatchResult result;

    for (TargetMatch targetMatch : matches ) {
        result = targetMatch.match(context);
        if (result.getResult() == MatchResult.NO_MATCH){
            return result;
        }

        if (result.getResult() == MatchResult.INDETERMINATE){
            if(firstIndeterminateStatus == null){
                firstIndeterminateStatus = result.getStatus();
            }
        }
    }

    // if we got here, then none of the sub-matches passed, so
    // we have to see if we got any INDETERMINATE cases
    if (firstIndeterminateStatus == null)
        return new MatchResult(MatchResult.MATCH);
    else
        return new MatchResult(MatchResult.INDETERMINATE,
                               firstIndeterminateStatus);

}